AutoMigrate auto migrate values
(values ...interface{})
| 120 | |
| 121 | // AutoMigrate auto migrate values |
| 122 | func (m Migrator) AutoMigrate(values ...interface{}) error { |
| 123 | for _, value := range m.ReorderModels(values, true) { |
| 124 | queryTx, execTx := m.GetQueryAndExecTx() |
| 125 | if !queryTx.Migrator().HasTable(value) { |
| 126 | if err := execTx.Migrator().CreateTable(value); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } else { |
| 130 | if err := m.RunWithValue(value, func(stmt *gorm.Statement) error { |
| 131 | |
| 132 | if stmt.Schema == nil { |
| 133 | return errors.New("failed to get schema") |
| 134 | } |
| 135 | |
| 136 | columnTypes, err := queryTx.Migrator().ColumnTypes(value) |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | var ( |
| 141 | parseIndexes = stmt.Schema.ParseIndexes() |
| 142 | parseCheckConstraints = stmt.Schema.ParseCheckConstraints() |
| 143 | ) |
| 144 | for _, dbName := range stmt.Schema.DBNames { |
| 145 | var foundColumn gorm.ColumnType |
| 146 | |
| 147 | for _, columnType := range columnTypes { |
| 148 | if columnType.Name() == dbName { |
| 149 | foundColumn = columnType |
| 150 | break |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | if foundColumn == nil { |
| 155 | // not found, add column |
| 156 | if err = execTx.Migrator().AddColumn(value, dbName); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | } else { |
| 160 | // found, smartly migrate |
| 161 | field := stmt.Schema.FieldsByDBName[dbName] |
| 162 | if err = execTx.Migrator().MigrateColumn(value, field, foundColumn); err != nil { |
| 163 | return err |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | if !m.DB.DisableForeignKeyConstraintWhenMigrating && !m.DB.IgnoreRelationshipsWhenMigrating { |
| 169 | for _, rel := range stmt.Schema.Relationships.Relations { |
| 170 | if rel.Field.IgnoreMigration { |
| 171 | continue |
| 172 | } |
| 173 | if constraint := rel.ParseConstraint(); constraint != nil && |
| 174 | constraint.Schema == stmt.Schema && !queryTx.Migrator().HasConstraint(value, constraint.Name) { |
| 175 | if err := execTx.Migrator().CreateConstraint(value, constraint.Name); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | } |
| 179 | } |
nothing calls this directly
no test coverage detected