migrator.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package gorm
  2. import (
  3. "gorm.io/gorm/clause"
  4. "gorm.io/gorm/schema"
  5. )
  6. // Migrator returns migrator
  7. func (db *DB) Migrator() Migrator {
  8. tx := db.getInstance()
  9. // apply scopes to migrator
  10. for len(tx.Statement.scopes) > 0 {
  11. scopes := tx.Statement.scopes
  12. tx.Statement.scopes = nil
  13. for _, scope := range scopes {
  14. tx = scope(tx)
  15. }
  16. }
  17. return tx.Dialector.Migrator(tx.Session(&Session{}))
  18. }
  19. // AutoMigrate run auto migration for given models
  20. func (db *DB) AutoMigrate(dst ...interface{}) error {
  21. return db.Migrator().AutoMigrate(dst...)
  22. }
  23. // ViewOption view option
  24. type ViewOption struct {
  25. Replace bool
  26. CheckOption string
  27. Query *DB
  28. }
  29. type ColumnType interface {
  30. Name() string
  31. DatabaseTypeName() string
  32. Length() (length int64, ok bool)
  33. DecimalSize() (precision int64, scale int64, ok bool)
  34. Nullable() (nullable bool, ok bool)
  35. }
  36. type Migrator interface {
  37. // AutoMigrate
  38. AutoMigrate(dst ...interface{}) error
  39. // Database
  40. CurrentDatabase() string
  41. FullDataTypeOf(*schema.Field) clause.Expr
  42. // Tables
  43. CreateTable(dst ...interface{}) error
  44. DropTable(dst ...interface{}) error
  45. HasTable(dst interface{}) bool
  46. RenameTable(oldName, newName interface{}) error
  47. // Columns
  48. AddColumn(dst interface{}, field string) error
  49. DropColumn(dst interface{}, field string) error
  50. AlterColumn(dst interface{}, field string) error
  51. MigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) error
  52. HasColumn(dst interface{}, field string) bool
  53. RenameColumn(dst interface{}, oldName, field string) error
  54. ColumnTypes(dst interface{}) ([]ColumnType, error)
  55. // Views
  56. CreateView(name string, option ViewOption) error
  57. DropView(name string) error
  58. // Constraints
  59. CreateConstraint(dst interface{}, name string) error
  60. DropConstraint(dst interface{}, name string) error
  61. HasConstraint(dst interface{}, name string) bool
  62. // Indexes
  63. CreateIndex(dst interface{}, name string) error
  64. DropIndex(dst interface{}, name string) error
  65. HasIndex(dst interface{}, name string) bool
  66. RenameIndex(dst interface{}, oldName, newName string) error
  67. }