@@ -12,6 +12,22 @@ import (
1212 "gorm.io/gorm/schema"
1313)
1414
15+ const indexSQL = `
16+ SELECT
17+ i.name AS index_name,
18+ i.is_unique,
19+ i.is_primary_key,
20+ col.name AS column_name
21+ FROM
22+ sys.indexes i
23+ LEFT JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
24+ LEFT JOIN sys.all_columns col ON col.column_id = ic.column_id AND col.object_id = ic.object_id
25+ WHERE
26+ i.name IS NOT NULL
27+ AND i.is_unique_constraint = 0
28+ AND i.object_id = OBJECT_ID(?)
29+ `
30+
1531type Migrator struct {
1632 migrator.Migrator
1733}
@@ -348,14 +364,50 @@ func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error
348364 })
349365}
350366
367+ type Index struct {
368+ TableName string
369+ ColumnName string
370+ IndexName string
371+ IsUnique sql.NullBool
372+ IsPrimaryKey sql.NullBool
373+ }
374+
375+ func (m Migrator ) GetIndexes (value interface {}) ([]gorm.Index , error ) {
376+ indexes := make ([]gorm.Index , 0 )
377+ err := m .RunWithValue (value , func (stmt * gorm.Statement ) error {
378+ result := make ([]* Index , 0 )
379+ if err := m .DB .Raw (indexSQL , stmt .Table ).Scan (& result ).Error ; err != nil {
380+ return err
381+ }
382+ indexMap := make (map [string ]* migrator.Index )
383+ for _ , r := range result {
384+ idx , ok := indexMap [r .IndexName ]
385+ if ! ok {
386+ idx = & migrator.Index {
387+ TableName : stmt .Table ,
388+ NameValue : r .IndexName ,
389+ ColumnList : nil ,
390+ PrimaryKeyValue : r .IsPrimaryKey ,
391+ UniqueValue : r .IsUnique ,
392+ }
393+ }
394+ idx .ColumnList = append (idx .ColumnList , r .ColumnName )
395+ indexMap [r .IndexName ] = idx
396+ }
397+ for _ , idx := range indexMap {
398+ indexes = append (indexes , idx )
399+ }
400+ return nil
401+ })
402+ return indexes , err
403+ }
404+
351405func (m Migrator ) HasConstraint (value interface {}, name string ) bool {
352406 var count int64
353407 m .RunWithValue (value , func (stmt * gorm.Statement ) error {
354- constraint , chk , table := m .GuessConstraintAndTable (stmt , name )
408+ constraint , table := m .GuessConstraintInterfaceAndTable (stmt , name )
355409 if constraint != nil {
356- name = constraint .Name
357- } else if chk != nil {
358- name = chk .Name
410+ name = constraint .GetName ()
359411 }
360412
361413 tableCatalog , schema , tableName := splitFullQualifiedName (table )
0 commit comments