@@ -12,6 +12,22 @@ import (
12
12
"gorm.io/gorm/schema"
13
13
)
14
14
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
+
15
31
type Migrator struct {
16
32
migrator.Migrator
17
33
}
@@ -348,14 +364,50 @@ func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error
348
364
})
349
365
}
350
366
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
+
351
405
func (m Migrator ) HasConstraint (value interface {}, name string ) bool {
352
406
var count int64
353
407
m .RunWithValue (value , func (stmt * gorm.Statement ) error {
354
- constraint , chk , table := m .GuessConstraintAndTable (stmt , name )
408
+ constraint , table := m .GuessConstraintInterfaceAndTable (stmt , name )
355
409
if constraint != nil {
356
- name = constraint .Name
357
- } else if chk != nil {
358
- name = chk .Name
410
+ name = constraint .GetName ()
359
411
}
360
412
361
413
tableCatalog , schema , tableName := splitFullQualifiedName (table )
0 commit comments