CreateTable create table in database for values
(values ...interface{})
| 214 | |
| 215 | // CreateTable create table in database for values |
| 216 | func (m Migrator) CreateTable(values ...interface{}) error { |
| 217 | for _, value := range m.ReorderModels(values, false) { |
| 218 | tx := m.DB.Session(&gorm.Session{}) |
| 219 | if err := m.RunWithValue(value, func(stmt *gorm.Statement) (err error) { |
| 220 | |
| 221 | if stmt.Schema == nil { |
| 222 | return errors.New("failed to get schema") |
| 223 | } |
| 224 | |
| 225 | var ( |
| 226 | createTableSQL = "CREATE TABLE ? (" |
| 227 | values = []interface{}{m.CurrentTable(stmt)} |
| 228 | hasPrimaryKeyInDataType bool |
| 229 | ) |
| 230 | |
| 231 | for _, dbName := range stmt.Schema.DBNames { |
| 232 | field := stmt.Schema.FieldsByDBName[dbName] |
| 233 | if !field.IgnoreMigration { |
| 234 | createTableSQL += "? ?" |
| 235 | hasPrimaryKeyInDataType = hasPrimaryKeyInDataType || strings.Contains(strings.ToUpper(m.DataTypeOf(field)), "PRIMARY KEY") |
| 236 | values = append(values, clause.Column{Name: dbName}, m.DB.Migrator().FullDataTypeOf(field)) |
| 237 | createTableSQL += "," |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | if !hasPrimaryKeyInDataType && len(stmt.Schema.PrimaryFields) > 0 { |
| 242 | createTableSQL += "PRIMARY KEY ?," |
| 243 | primaryKeys := make([]interface{}, 0, len(stmt.Schema.PrimaryFields)) |
| 244 | for _, field := range stmt.Schema.PrimaryFields { |
| 245 | primaryKeys = append(primaryKeys, clause.Column{Name: field.DBName}) |
| 246 | } |
| 247 | |
| 248 | values = append(values, primaryKeys) |
| 249 | } |
| 250 | |
| 251 | for _, idx := range stmt.Schema.ParseIndexes() { |
| 252 | if m.CreateIndexAfterCreateTable { |
| 253 | defer func(value interface{}, name string) { |
| 254 | if err == nil { |
| 255 | err = tx.Migrator().CreateIndex(value, name) |
| 256 | } |
| 257 | }(value, idx.Name) |
| 258 | } else { |
| 259 | if idx.Class != "" { |
| 260 | createTableSQL += idx.Class + " " |
| 261 | } |
| 262 | createTableSQL += "INDEX ? ?" |
| 263 | |
| 264 | if idx.Comment != "" { |
| 265 | createTableSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment) |
| 266 | } |
| 267 | |
| 268 | if idx.Option != "" { |
| 269 | createTableSQL += " " + idx.Option |
| 270 | } |
| 271 | |
| 272 | createTableSQL += "," |
| 273 | values = append(values, clause.Column{Name: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt)) |
nothing calls this directly
no test coverage detected