Debian Codegraph @

migrator/migrator.go

raw
1 package migrator
2
3 import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "reflect"
9 "regexp"
10 "strconv"
11 "strings"
12 "time"
13
14 "gorm.io/gorm"
15 "gorm.io/gorm/clause"
16 "gorm.io/gorm/logger"
17 "gorm.io/gorm/schema"
18 )
19
20 // This regular expression seeks to find a sequence of digits (\d+) among zero or more non-digit characters (\D*),
21 // with a possible trailing non-digit character (\D?).
22
23 // For example, values that can pass this regular expression are:
24 // - "123"
25 // - "abc456"
26 // -"%$#@789"
27 var regFullDataType = regexp.MustCompile(`\D*(\d+)\D?`)
28
29 // TODO:? Create const vars for raw sql queries ?
30
31 var _ gorm.Migrator = (*Migrator)(nil)
32
33 // Migrator m struct
34 type Migrator struct {
35 Config
36 }
37
38 // Config schema config
39 type Config struct {
40 CreateIndexAfterCreateTable bool
41 DB *gorm.DB
42 gorm.Dialector
43 }
44
45 type printSQLLogger struct {
46 logger.Interface
47 }
48
49 func (l *printSQLLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
50 sql, _ := fc()
51 fmt.Println(sql + ";")
52 l.Interface.Trace(ctx, begin, fc, err)
53 }
54
55 // GormDataTypeInterface gorm data type interface
56 type GormDataTypeInterface interface {
57 GormDBDataType(*gorm.DB, *schema.Field) string
58 }
59
60 // RunWithValue run migration with statement value
61 func (m Migrator) RunWithValue(value interface{}, fc func(*gorm.Statement) error) error {
62 stmt := &gorm.Statement{DB: m.DB}
63 if m.DB.Statement != nil {
64 stmt.Table = m.DB.Statement.Table
65 stmt.TableExpr = m.DB.Statement.TableExpr
66 }
67
68 if table, ok := value.(string); ok {
69 stmt.Table = table
70 } else if err := stmt.ParseWithSpecialTableName(value, stmt.Table); err != nil {
71 return err
72 }
73
74 return fc(stmt)
75 }
76
77 // DataTypeOf return field's db data type
78 func (m Migrator) DataTypeOf(field *schema.Field) string {
79 fieldValue := reflect.New(field.IndirectFieldType)
80 if dataTyper, ok := fieldValue.Interface().(GormDataTypeInterface); ok {
81 if dataType := dataTyper.GormDBDataType(m.DB, field); dataType != "" {
82 return dataType
83 }
84 }
85
86 return m.Dialector.DataTypeOf(field)
87 }
88
89 // FullDataTypeOf returns field's db full data type
90 func (m Migrator) FullDataTypeOf(field *schema.Field) (expr clause.Expr) {
91 expr.SQL = m.DataTypeOf(field)
92
93 if field.NotNull {
94 expr.SQL += " NOT NULL"
95 }
96
97 if field.HasDefaultValue && (field.DefaultValueInterface != nil || field.DefaultValue != "") {
98 if field.DefaultValueInterface != nil {
99 defaultStmt := &gorm.Statement{Vars: []interface{}{field.DefaultValueInterface}}
100 m.Dialector.BindVarTo(defaultStmt, defaultStmt, field.DefaultValueInterface)
101 expr.SQL += " DEFAULT " + m.Dialector.Explain(defaultStmt.SQL.String(), field.DefaultValueInterface)
102 } else if field.DefaultValue != "(-)" {
103 expr.SQL += " DEFAULT " + field.DefaultValue
104 }
105 }
106
107 return
108 }
109
110 func (m Migrator) GetQueryAndExecTx() (queryTx, execTx *gorm.DB) {
111 queryTx = m.DB.Session(&gorm.Session{})
112 execTx = queryTx
113 if m.DB.DryRun {
114 queryTx.DryRun = false
115 execTx = m.DB.Session(&gorm.Session{Logger: &printSQLLogger{Interface: m.DB.Logger}})
116 }
117 return queryTx, execTx
118 }
119
120 // AutoMigrate auto migrate values
121 func (m Migrator) AutoMigrate(values ...interface{}) error {
122 for _, value := range m.ReorderModels(values, true) {
123 queryTx, execTx := m.GetQueryAndExecTx()
124 if !queryTx.Migrator().HasTable(value) {
125 if err := execTx.Migrator().CreateTable(value); err != nil {
126 return err
127 }
128 } else {
129 if err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
130
131 if stmt.Schema == nil {
132 return errors.New("failed to get schema")
133 }
134
135 columnTypes, err := queryTx.Migrator().ColumnTypes(value)
136 if err != nil {
137 return err
138 }
139 var (
140 parseIndexes = stmt.Schema.ParseIndexes()
141 parseCheckConstraints = stmt.Schema.ParseCheckConstraints()
142 )
143 for _, dbName := range stmt.Schema.DBNames {
144 var foundColumn gorm.ColumnType
145
146 for _, columnType := range columnTypes {
147 if columnType.Name() == dbName {
148 foundColumn = columnType
149 break
150 }
151 }
152
153 if foundColumn == nil {
154 // not found, add column
155 if err = execTx.Migrator().AddColumn(value, dbName); err != nil {
156 return err
157 }
158 } else {
159 // found, smartly migrate
160 field := stmt.Schema.FieldsByDBName[dbName]
161 if err = execTx.Migrator().MigrateColumn(value, field, foundColumn); err != nil {
162 return err
163 }
164 }
165 }
166
167 if !m.DB.DisableForeignKeyConstraintWhenMigrating && !m.DB.IgnoreRelationshipsWhenMigrating {
168 for _, rel := range stmt.Schema.Relationships.Relations {
169 if rel.Field.IgnoreMigration {
170 continue
171 }
172 if constraint := rel.ParseConstraint(); constraint != nil &&
173 constraint.Schema == stmt.Schema && !queryTx.Migrator().HasConstraint(value, constraint.Name) {
174 if err := execTx.Migrator().CreateConstraint(value, constraint.Name); err != nil {
175 return err
176 }
177 }
178 }
179 }
180
181 for _, chk := range parseCheckConstraints {
182 if !queryTx.Migrator().HasConstraint(value, chk.Name) {
183 if err := execTx.Migrator().CreateConstraint(value, chk.Name); err != nil {
184 return err
185 }
186 }
187 }
188
189 for _, idx := range parseIndexes {
190 if !queryTx.Migrator().HasIndex(value, idx.Name) {
191 if err := execTx.Migrator().CreateIndex(value, idx.Name); err != nil {
192 return err
193 }
194 }
195 }
196
197 return nil
198 }); err != nil {
199 return err
200 }
201 }
202 }
203
204 return nil
205 }
206
207 // GetTables returns tables
208 func (m Migrator) GetTables() (tableList []string, err error) {
209 err = m.DB.Raw("SELECT TABLE_NAME FROM information_schema.tables where TABLE_SCHEMA=?", m.CurrentDatabase()).
210 Scan(&tableList).Error
211 return
212 }
213
214 // CreateTable create table in database for values
215 func (m Migrator) CreateTable(values ...interface{}) error {
216 for _, value := range m.ReorderModels(values, false) {
217 tx := m.DB.Session(&gorm.Session{})
218 if err := m.RunWithValue(value, func(stmt *gorm.Statement) (err error) {
219
220 if stmt.Schema == nil {
221 return errors.New("failed to get schema")
222 }
223
224 var (
225 createTableSQL = "CREATE TABLE ? ("
226 values = []interface{}{m.CurrentTable(stmt)}
227 hasPrimaryKeyInDataType bool
228 )
229
230 for _, dbName := range stmt.Schema.DBNames {
231 field := stmt.Schema.FieldsByDBName[dbName]
232 if !field.IgnoreMigration {
233 createTableSQL += "? ?"
234 hasPrimaryKeyInDataType = hasPrimaryKeyInDataType || strings.Contains(strings.ToUpper(m.DataTypeOf(field)), "PRIMARY KEY")
235 values = append(values, clause.Column{Name: dbName}, m.DB.Migrator().FullDataTypeOf(field))
236 createTableSQL += ","
237 }
238 }
239
240 if !hasPrimaryKeyInDataType && len(stmt.Schema.PrimaryFields) > 0 {
241 createTableSQL += "PRIMARY KEY ?,"
242 primaryKeys := make([]interface{}, 0, len(stmt.Schema.PrimaryFields))
243 for _, field := range stmt.Schema.PrimaryFields {
244 primaryKeys = append(primaryKeys, clause.Column{Name: field.DBName})
245 }
246
247 values = append(values, primaryKeys)
248 }
249
250 for _, idx := range stmt.Schema.ParseIndexes() {
251 if m.CreateIndexAfterCreateTable {
252 defer func(value interface{}, name string) {
253 if err == nil {
254 err = tx.Migrator().CreateIndex(value, name)
255 }
256 }(value, idx.Name)
257 } else {
258 if idx.Class != "" {
259 createTableSQL += idx.Class + " "
260 }
261 createTableSQL += "INDEX ? ?"
262
263 if idx.Comment != "" {
264 createTableSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment)
265 }
266
267 if idx.Option != "" {
268 createTableSQL += " " + idx.Option
269 }
270
271 createTableSQL += ","
272 values = append(values, clause.Column{Name: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt))
273 }
274 }
275
276 if !m.DB.DisableForeignKeyConstraintWhenMigrating && !m.DB.IgnoreRelationshipsWhenMigrating {
277 for _, rel := range stmt.Schema.Relationships.Relations {
278 if rel.Field.IgnoreMigration {
279 continue
280 }
281 if constraint := rel.ParseConstraint(); constraint != nil {
282 if constraint.Schema == stmt.Schema {
283 sql, vars := constraint.Build()
284 createTableSQL += sql + ","
285 values = append(values, vars...)
286 }
287 }
288 }
289 }
290
291 for _, uni := range stmt.Schema.ParseUniqueConstraints() {
292 createTableSQL += "CONSTRAINT ? UNIQUE (?),"
293 values = append(values, clause.Column{Name: uni.Name}, clause.Expr{SQL: stmt.Quote(uni.Field.DBName)})
294 }
295
296 for _, chk := range stmt.Schema.ParseCheckConstraints() {
297 createTableSQL += "CONSTRAINT ? CHECK (?),"
298 values = append(values, clause.Column{Name: chk.Name}, clause.Expr{SQL: chk.Constraint})
299 }
300
301 createTableSQL = strings.TrimSuffix(createTableSQL, ",")
302
303 createTableSQL += ")"
304
305 if tableOption, ok := m.DB.Get("gorm:table_options"); ok {
306 createTableSQL += fmt.Sprint(tableOption)
307 }
308
309 err = tx.Exec(createTableSQL, values...).Error
310 return err
311 }); err != nil {
312 return err
313 }
314 }
315 return nil
316 }
317
318 // DropTable drop table for values
319 func (m Migrator) DropTable(values ...interface{}) error {
320 values = m.ReorderModels(values, false)
321 for i := len(values) - 1; i >= 0; i-- {
322 tx := m.DB.Session(&gorm.Session{})
323 if err := m.RunWithValue(values[i], func(stmt *gorm.Statement) error {
324 return tx.Exec("DROP TABLE IF EXISTS ?", m.CurrentTable(stmt)).Error
325 }); err != nil {
326 return err
327 }
328 }
329 return nil
330 }
331
332 // HasTable returns table exists or not for value, value could be a struct or string
333 func (m Migrator) HasTable(value interface{}) bool {
334 var count int64
335
336 m.RunWithValue(value, func(stmt *gorm.Statement) error {
337 currentDatabase := m.DB.Migrator().CurrentDatabase()
338 return m.DB.Raw("SELECT count(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ? AND table_type = ?", currentDatabase, stmt.Table, "BASE TABLE").Row().Scan(&count)
339 })
340
341 return count > 0
342 }
343
344 // RenameTable rename table from oldName to newName
345 func (m Migrator) RenameTable(oldName, newName interface{}) error {
346 var oldTable, newTable interface{}
347 if v, ok := oldName.(string); ok {
348 oldTable = clause.Table{Name: v}
349 } else {
350 stmt := &gorm.Statement{DB: m.DB}
351 if err := stmt.Parse(oldName); err == nil {
352 oldTable = m.CurrentTable(stmt)
353 } else {
354 return err
355 }
356 }
357
358 if v, ok := newName.(string); ok {
359 newTable = clause.Table{Name: v}
360 } else {
361 stmt := &gorm.Statement{DB: m.DB}
362 if err := stmt.Parse(newName); err == nil {
363 newTable = m.CurrentTable(stmt)
364 } else {
365 return err
366 }
367 }
368
369 return m.DB.Exec("ALTER TABLE ? RENAME TO ?", oldTable, newTable).Error
370 }
371
372 // AddColumn create `name` column for value
373 func (m Migrator) AddColumn(value interface{}, name string) error {
374 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
375 // avoid using the same name field
376 if stmt.Schema == nil {
377 return errors.New("failed to get schema")
378 }
379 f := stmt.Schema.LookUpField(name)
380 if f == nil {
381 return fmt.Errorf("failed to look up field with name: %s", name)
382 }
383
384 if !f.IgnoreMigration {
385 return m.DB.Exec(
386 "ALTER TABLE ? ADD ? ?",
387 m.CurrentTable(stmt), clause.Column{Name: f.DBName}, m.DB.Migrator().FullDataTypeOf(f),
388 ).Error
389 }
390
391 return nil
392 })
393 }
394
395 // DropColumn drop value's `name` column
396 func (m Migrator) DropColumn(value interface{}, name string) error {
397 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
398 if stmt.Schema != nil {
399 if field := stmt.Schema.LookUpField(name); field != nil {
400 name = field.DBName
401 }
402 }
403
404 return m.DB.Exec(
405 "ALTER TABLE ? DROP COLUMN ?", m.CurrentTable(stmt), clause.Column{Name: name},
406 ).Error
407 })
408 }
409
410 // AlterColumn alter value's `field` column' type based on schema definition
411 func (m Migrator) AlterColumn(value interface{}, field string) error {
412 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
413 if stmt.Schema != nil {
414 if field := stmt.Schema.LookUpField(field); field != nil {
415 fileType := m.FullDataTypeOf(field)
416 return m.DB.Exec(
417 "ALTER TABLE ? ALTER COLUMN ? TYPE ?",
418 m.CurrentTable(stmt), clause.Column{Name: field.DBName}, fileType,
419 ).Error
420
421 }
422 }
423 return fmt.Errorf("failed to look up field with name: %s", field)
424 })
425 }
426
427 // HasColumn check has column `field` for value or not
428 func (m Migrator) HasColumn(value interface{}, field string) bool {
429 var count int64
430 m.RunWithValue(value, func(stmt *gorm.Statement) error {
431 currentDatabase := m.DB.Migrator().CurrentDatabase()
432 name := field
433 if stmt.Schema != nil {
434 if field := stmt.Schema.LookUpField(field); field != nil {
435 name = field.DBName
436 }
437 }
438
439 return m.DB.Raw(
440 "SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?",
441 currentDatabase, stmt.Table, name,
442 ).Row().Scan(&count)
443 })
444
445 return count > 0
446 }
447
448 // RenameColumn rename value's field name from oldName to newName
449 func (m Migrator) RenameColumn(value interface{}, oldName, newName string) error {
450 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
451 if stmt.Schema != nil {
452 if field := stmt.Schema.LookUpField(oldName); field != nil {
453 oldName = field.DBName
454 }
455
456 if field := stmt.Schema.LookUpField(newName); field != nil {
457 newName = field.DBName
458 }
459 }
460
461 return m.DB.Exec(
462 "ALTER TABLE ? RENAME COLUMN ? TO ?",
463 m.CurrentTable(stmt), clause.Column{Name: oldName}, clause.Column{Name: newName},
464 ).Error
465 })
466 }
467
468 // MigrateColumn migrate column
469 func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnType gorm.ColumnType) error {
470 if field.IgnoreMigration {
471 return nil
472 }
473
474 // found, smart migrate
475 fullDataType := strings.TrimSpace(strings.ToLower(m.DB.Migrator().FullDataTypeOf(field).SQL))
476 realDataType := strings.ToLower(columnType.DatabaseTypeName())
477 var (
478 alterColumn bool
479 isSameType = fullDataType == realDataType
480 )
481
482 if !field.PrimaryKey {
483 // check type
484 if !strings.HasPrefix(fullDataType, realDataType) {
485 // check type aliases
486 aliases := m.DB.Migrator().GetTypeAliases(realDataType)
487 for _, alias := range aliases {
488 if strings.HasPrefix(fullDataType, alias) {
489 isSameType = true
490 break
491 }
492 }
493
494 if !isSameType {
495 alterColumn = true
496 }
497 }
498 }
499
500 if !isSameType {
501 // check size
502 if length, ok := columnType.Length(); length != int64(field.Size) {
503 if length > 0 && field.Size > 0 {
504 alterColumn = true
505 } else {
506 // has size in data type and not equal
507 // Since the following code is frequently called in the for loop, reg optimization is needed here
508 matches2 := regFullDataType.FindAllStringSubmatch(fullDataType, -1)
509 if !field.PrimaryKey &&
510 (len(matches2) == 1 && matches2[0][1] != fmt.Sprint(length) && ok) {
511 alterColumn = true
512 }
513 }
514 }
515 }
516
517 // check precision
518 if realDataType == "decimal" || realDataType == "numeric" &&
519 regexp.MustCompile(realDataType+`\(.*\)`).FindString(fullDataType) != "" { // if realDataType has no precision,ignore
520 precision, scale, ok := columnType.DecimalSize()
521 if ok {
522 if !strings.HasPrefix(fullDataType, fmt.Sprintf("%s(%d,%d)", realDataType, precision, scale)) &&
523 !strings.HasPrefix(fullDataType, fmt.Sprintf("%s(%d)", realDataType, precision)) {
524 alterColumn = true
525 }
526 }
527 } else {
528 if precision, _, ok := columnType.DecimalSize(); ok && int64(field.Precision) != precision {
529 if regexp.MustCompile(fmt.Sprintf("[^0-9]%d[^0-9]", field.Precision)).MatchString(m.DataTypeOf(field)) {
530 alterColumn = true
531 }
532 }
533 }
534
535 // check nullable
536 if nullable, ok := columnType.Nullable(); ok && nullable == field.NotNull {
537 // not primary key & current database is non-nullable(to be nullable)
538 if !field.PrimaryKey && !nullable {
539 alterColumn = true
540 }
541 }
542
543 // check default value
544 if !field.PrimaryKey {
545 currentDefaultNotNull := field.HasDefaultValue && (field.DefaultValueInterface != nil || !strings.EqualFold(field.DefaultValue, "NULL"))
546 dv, dvNotNull := columnType.DefaultValue()
547 if dvNotNull && !currentDefaultNotNull {
548 // default value -> null
549 alterColumn = true
550 } else if !dvNotNull && currentDefaultNotNull {
551 // null -> default value
552 alterColumn = true
553 } else if currentDefaultNotNull || dvNotNull {
554 switch field.GORMDataType {
555 case schema.Time:
556 if !strings.EqualFold(strings.TrimSuffix(dv, "()"), strings.TrimSuffix(field.DefaultValue, "()")) {
557 alterColumn = true
558 }
559 case schema.Bool:
560 v1, _ := strconv.ParseBool(dv)
561 v2, _ := strconv.ParseBool(field.DefaultValue)
562 alterColumn = v1 != v2
563 case schema.String:
564 if dv != field.DefaultValue && dv != strings.Trim(field.DefaultValue, "'\"") {
565 alterColumn = true
566 }
567 default:
568 alterColumn = dv != field.DefaultValue
569 }
570 }
571 }
572
573 // check comment
574 if comment, ok := columnType.Comment(); ok && comment != field.Comment {
575 // not primary key
576 if !field.PrimaryKey {
577 alterColumn = true
578 }
579 }
580
581 if alterColumn {
582 if err := m.DB.Migrator().AlterColumn(value, field.DBName); err != nil {
583 return err
584 }
585 }
586
587 if err := m.DB.Migrator().MigrateColumnUnique(value, field, columnType); err != nil {
588 return err
589 }
590
591 return nil
592 }
593
594 func (m Migrator) MigrateColumnUnique(value interface{}, field *schema.Field, columnType gorm.ColumnType) error {
595 unique, ok := columnType.Unique()
596 if !ok || field.PrimaryKey {
597 return nil // skip primary key
598 }
599 // By default, ColumnType's Unique is not affected by UniqueIndex, so we don't care about UniqueIndex.
600 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
601 // We're currently only receiving boolean values on `Unique` tag,
602 // so the UniqueConstraint name is fixed
603 constraint := m.DB.NamingStrategy.UniqueName(stmt.Table, field.DBName)
604 if unique && !field.Unique {
605 return m.DB.Migrator().DropConstraint(value, constraint)
606 }
607 if !unique && field.Unique {
608 return m.DB.Migrator().CreateConstraint(value, constraint)
609 }
610 return nil
611 })
612 }
613
614 // ColumnTypes return columnTypes []gorm.ColumnType and execErr error
615 func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
616 columnTypes := make([]gorm.ColumnType, 0)
617 execErr := m.RunWithValue(value, func(stmt *gorm.Statement) (err error) {
618 rows, err := m.DB.Session(&gorm.Session{}).Table(stmt.Table).Limit(1).Rows()
619 if err != nil {
620 return err
621 }
622
623 defer func() {
624 err = rows.Close()
625 }()
626
627 var rawColumnTypes []*sql.ColumnType
628 rawColumnTypes, err = rows.ColumnTypes()
629 if err != nil {
630 return err
631 }
632
633 for _, c := range rawColumnTypes {
634 columnTypes = append(columnTypes, ColumnType{SQLColumnType: c})
635 }
636
637 return
638 })
639
640 return columnTypes, execErr
641 }
642
643 // CreateView create view from Query in gorm.ViewOption.
644 // Query in gorm.ViewOption is a [subquery]
645 //
646 // // CREATE VIEW `user_view` AS SELECT * FROM `users` WHERE age > 20
647 // q := DB.Model(&User{}).Where("age > ?", 20)
648 // DB.Debug().Migrator().CreateView("user_view", gorm.ViewOption{Query: q})
649 //
650 // // CREATE OR REPLACE VIEW `users_view` AS SELECT * FROM `users` WITH CHECK OPTION
651 // q := DB.Model(&User{})
652 // DB.Debug().Migrator().CreateView("user_view", gorm.ViewOption{Query: q, Replace: true, CheckOption: "WITH CHECK OPTION"})
653 //
654 // [subquery]: https://gorm.io/docs/advanced_query.html#SubQuery
655 func (m Migrator) CreateView(name string, option gorm.ViewOption) error {
656 if option.Query == nil {
657 return gorm.ErrSubQueryRequired
658 }
659
660 sql := new(strings.Builder)
661 sql.WriteString("CREATE ")
662 if option.Replace {
663 sql.WriteString("OR REPLACE ")
664 }
665 sql.WriteString("VIEW ")
666 m.QuoteTo(sql, name)
667 sql.WriteString(" AS ")
668
669 m.DB.Statement.AddVar(sql, option.Query)
670
671 if option.CheckOption != "" {
672 sql.WriteString(" ")
673 sql.WriteString(option.CheckOption)
674 }
675 return m.DB.Exec(m.Explain(sql.String(), m.DB.Statement.Vars...)).Error
676 }
677
678 // DropView drop view
679 func (m Migrator) DropView(name string) error {
680 return m.DB.Exec("DROP VIEW IF EXISTS ?", clause.Table{Name: name}).Error
681 }
682
683 // GuessConstraintAndTable guess statement's constraint and it's table based on name
684 //
685 // Deprecated: use GuessConstraintInterfaceAndTable instead.
686 func (m Migrator) GuessConstraintAndTable(stmt *gorm.Statement, name string) (*schema.Constraint, *schema.CheckConstraint, string) {
687 constraint, table := m.GuessConstraintInterfaceAndTable(stmt, name)
688 switch c := constraint.(type) {
689 case *schema.Constraint:
690 return c, nil, table
691 case *schema.CheckConstraint:
692 return nil, c, table
693 default:
694 return nil, nil, table
695 }
696 }
697
698 // GuessConstraintInterfaceAndTable guess statement's constraint and it's table based on name
699 // nolint:cyclop
700 func (m Migrator) GuessConstraintInterfaceAndTable(stmt *gorm.Statement, name string) (_ schema.ConstraintInterface, table string) {
701 if stmt.Schema == nil {
702 return nil, stmt.Table
703 }
704
705 checkConstraints := stmt.Schema.ParseCheckConstraints()
706 if chk, ok := checkConstraints[name]; ok {
707 return &chk, stmt.Table
708 }
709
710 uniqueConstraints := stmt.Schema.ParseUniqueConstraints()
711 if uni, ok := uniqueConstraints[name]; ok {
712 return &uni, stmt.Table
713 }
714
715 getTable := func(rel *schema.Relationship) string {
716 switch rel.Type {
717 case schema.HasOne, schema.HasMany:
718 return rel.FieldSchema.Table
719 case schema.Many2Many:
720 return rel.JoinTable.Table
721 }
722 return stmt.Table
723 }
724
725 for _, rel := range stmt.Schema.Relationships.Relations {
726 if constraint := rel.ParseConstraint(); constraint != nil && constraint.Name == name {
727 return constraint, getTable(rel)
728 }
729 }
730
731 if field := stmt.Schema.LookUpField(name); field != nil {
732 for k := range checkConstraints {
733 if checkConstraints[k].Field == field {
734 v := checkConstraints[k]
735 return &v, stmt.Table
736 }
737 }
738
739 for k := range uniqueConstraints {
740 if uniqueConstraints[k].Field == field {
741 v := uniqueConstraints[k]
742 return &v, stmt.Table
743 }
744 }
745
746 for _, rel := range stmt.Schema.Relationships.Relations {
747 if constraint := rel.ParseConstraint(); constraint != nil && rel.Field == field {
748 return constraint, getTable(rel)
749 }
750 }
751 }
752
753 return nil, stmt.Schema.Table
754 }
755
756 // CreateConstraint create constraint
757 func (m Migrator) CreateConstraint(value interface{}, name string) error {
758 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
759 constraint, table := m.GuessConstraintInterfaceAndTable(stmt, name)
760 if constraint != nil {
761 vars := []interface{}{clause.Table{Name: table}}
762 if stmt.TableExpr != nil {
763 vars[0] = stmt.TableExpr
764 }
765 sql, values := constraint.Build()
766 return m.DB.Exec("ALTER TABLE ? ADD "+sql, append(vars, values...)...).Error
767 }
768 return nil
769 })
770 }
771
772 // DropConstraint drop constraint
773 func (m Migrator) DropConstraint(value interface{}, name string) error {
774 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
775 constraint, table := m.GuessConstraintInterfaceAndTable(stmt, name)
776 if constraint != nil {
777 name = constraint.GetName()
778 }
779 return m.DB.Exec("ALTER TABLE ? DROP CONSTRAINT ?", clause.Table{Name: table}, clause.Column{Name: name}).Error
780 })
781 }
782
783 // HasConstraint check has constraint or not
784 func (m Migrator) HasConstraint(value interface{}, name string) bool {
785 var count int64
786 m.RunWithValue(value, func(stmt *gorm.Statement) error {
787 currentDatabase := m.DB.Migrator().CurrentDatabase()
788 constraint, table := m.GuessConstraintInterfaceAndTable(stmt, name)
789 if constraint != nil {
790 name = constraint.GetName()
791 }
792
793 return m.DB.Raw(
794 "SELECT count(*) FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ?",
795 currentDatabase, table, name,
796 ).Row().Scan(&count)
797 })
798
799 return count > 0
800 }
801
802 // BuildIndexOptions build index options
803 func (m Migrator) BuildIndexOptions(opts []schema.IndexOption, stmt *gorm.Statement) (results []interface{}) {
804 for _, opt := range opts {
805 str := stmt.Quote(opt.DBName)
806 if opt.Expression != "" {
807 str = opt.Expression
808 } else if opt.Length > 0 {
809 str += fmt.Sprintf("(%d)", opt.Length)
810 }
811
812 if opt.Collate != "" {
813 str += " COLLATE " + opt.Collate
814 }
815
816 if opt.Sort != "" {
817 str += " " + opt.Sort
818 }
819 results = append(results, clause.Expr{SQL: str})
820 }
821 return
822 }
823
824 // BuildIndexOptionsInterface build index options interface
825 type BuildIndexOptionsInterface interface {
826 BuildIndexOptions([]schema.IndexOption, *gorm.Statement) []interface{}
827 }
828
829 // CreateIndex create index `name`
830 func (m Migrator) CreateIndex(value interface{}, name string) error {
831 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
832 if stmt.Schema == nil {
833 return errors.New("failed to get schema")
834 }
835 if idx := stmt.Schema.LookIndex(name); idx != nil {
836 opts := m.DB.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt)
837 values := []interface{}{clause.Column{Name: idx.Name}, m.CurrentTable(stmt), opts}
838
839 createIndexSQL := "CREATE "
840 if idx.Class != "" {
841 createIndexSQL += idx.Class + " "
842 }
843 createIndexSQL += "INDEX ? ON ??"
844
845 if idx.Type != "" {
846 createIndexSQL += " USING " + idx.Type
847 }
848
849 if idx.Comment != "" {
850 createIndexSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment)
851 }
852
853 if idx.Option != "" {
854 createIndexSQL += " " + idx.Option
855 }
856
857 return m.DB.Exec(createIndexSQL, values...).Error
858 }
859
860 return fmt.Errorf("failed to create index with name %s", name)
861 })
862 }
863
864 // DropIndex drop index `name`
865 func (m Migrator) DropIndex(value interface{}, name string) error {
866 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
867 if stmt.Schema != nil {
868 if idx := stmt.Schema.LookIndex(name); idx != nil {
869 name = idx.Name
870 }
871 }
872
873 return m.DB.Exec("DROP INDEX ? ON ?", clause.Column{Name: name}, m.CurrentTable(stmt)).Error
874 })
875 }
876
877 // HasIndex check has index `name` or not
878 func (m Migrator) HasIndex(value interface{}, name string) bool {
879 var count int64
880 m.RunWithValue(value, func(stmt *gorm.Statement) error {
881 currentDatabase := m.DB.Migrator().CurrentDatabase()
882 if stmt.Schema != nil {
883 if idx := stmt.Schema.LookIndex(name); idx != nil {
884 name = idx.Name
885 }
886 }
887
888 return m.DB.Raw(
889 "SELECT count(*) FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND index_name = ?",
890 currentDatabase, stmt.Table, name,
891 ).Row().Scan(&count)
892 })
893
894 return count > 0
895 }
896
897 // RenameIndex rename index from oldName to newName
898 func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error {
899 return m.RunWithValue(value, func(stmt *gorm.Statement) error {
900 return m.DB.Exec(
901 "ALTER TABLE ? RENAME INDEX ? TO ?",
902 m.CurrentTable(stmt), clause.Column{Name: oldName}, clause.Column{Name: newName},
903 ).Error
904 })
905 }
906
907 // CurrentDatabase returns current database name
908 func (m Migrator) CurrentDatabase() (name string) {
909 m.DB.Raw("SELECT DATABASE()").Row().Scan(&name)
910 return
911 }
912
913 // ReorderModels reorder models according to constraint dependencies
914 func (m Migrator) ReorderModels(values []interface{}, autoAdd bool) (results []interface{}) {
915 type Dependency struct {
916 *gorm.Statement
917 Depends []*schema.Schema
918 }
919
920 var (
921 modelNames, orderedModelNames []string
922 orderedModelNamesMap = map[string]bool{}
923 parsedSchemas = map[*schema.Schema]bool{}
924 valuesMap = map[string]Dependency{}
925 insertIntoOrderedList func(name string)
926 parseDependence func(value interface{}, addToList bool)
927 )
928
929 parseDependence = func(value interface{}, addToList bool) {
930 dep := Dependency{
931 Statement: &gorm.Statement{DB: m.DB, Dest: value},
932 }
933 beDependedOn := map[*schema.Schema]bool{}
934 // support for special table name
935 if err := dep.ParseWithSpecialTableName(value, m.DB.Statement.Table); err != nil {
936 m.DB.Logger.Error(context.Background(), "failed to parse value %#v, got error %v", value, err)
937 }
938 if _, ok := parsedSchemas[dep.Statement.Schema]; ok {
939 return
940 }
941 parsedSchemas[dep.Statement.Schema] = true
942
943 if !m.DB.IgnoreRelationshipsWhenMigrating {
944 for _, rel := range dep.Schema.Relationships.Relations {
945 if rel.Field.IgnoreMigration {
946 continue
947 }
948 if c := rel.ParseConstraint(); c != nil && c.Schema == dep.Statement.Schema && c.Schema != c.ReferenceSchema {
949 dep.Depends = append(dep.Depends, c.ReferenceSchema)
950 }
951
952 if rel.Type == schema.HasOne || rel.Type == schema.HasMany {
953 beDependedOn[rel.FieldSchema] = true
954 }
955
956 if rel.JoinTable != nil {
957 // append join value
958 defer func(rel *schema.Relationship, joinValue interface{}) {
959 if !beDependedOn[rel.FieldSchema] {
960 dep.Depends = append(dep.Depends, rel.FieldSchema)
961 } else {
962 fieldValue := reflect.New(rel.FieldSchema.ModelType).Interface()
963 parseDependence(fieldValue, autoAdd)
964 }
965 parseDependence(joinValue, autoAdd)
966 }(rel, reflect.New(rel.JoinTable.ModelType).Interface())
967 }
968 }
969 }
970
971 valuesMap[dep.Schema.Table] = dep
972
973 if addToList {
974 modelNames = append(modelNames, dep.Schema.Table)
975 }
976 }
977
978 insertIntoOrderedList = func(name string) {
979 if _, ok := orderedModelNamesMap[name]; ok {
980 return // avoid loop
981 }
982 orderedModelNamesMap[name] = true
983
984 if autoAdd {
985 dep := valuesMap[name]
986 for _, d := range dep.Depends {
987 if _, ok := valuesMap[d.Table]; ok {
988 insertIntoOrderedList(d.Table)
989 } else {
990 parseDependence(reflect.New(d.ModelType).Interface(), autoAdd)
991 insertIntoOrderedList(d.Table)
992 }
993 }
994 }
995
996 orderedModelNames = append(orderedModelNames, name)
997 }
998
999 for _, value := range values {
1000 if v, ok := value.(string); ok {
1001 results = append(results, v)
1002 } else {
1003 parseDependence(value, true)
1004 }
1005 }
1006
1007 for _, name := range modelNames {
1008 insertIntoOrderedList(name)
1009 }
1010
1011 for _, name := range orderedModelNames {
1012 results = append(results, valuesMap[name].Statement.Dest)
1013 }
1014 return
1015 }
1016
1017 // CurrentTable returns current statement's table expression
1018 func (m Migrator) CurrentTable(stmt *gorm.Statement) interface{} {
1019 if stmt.TableExpr != nil {
1020 return *stmt.TableExpr
1021 }
1022 return clause.Table{Name: stmt.Table}
1023 }
1024
1025 // GetIndexes return Indexes []gorm.Index and execErr error
1026 func (m Migrator) GetIndexes(dst interface{}) ([]gorm.Index, error) {
1027 return nil, errors.New("not support")
1028 }
1029
1030 // GetTypeAliases return database type aliases
1031 func (m Migrator) GetTypeAliases(databaseTypeName string) []string {
1032 return nil
1033 }
1034
1035 // TableType return tableType gorm.TableType and execErr error
1036 func (m Migrator) TableType(dst interface{}) (gorm.TableType, error) {
1037 return nil, errors.New("not support")
1038 }