MCPcopy
hub / github.com/go-gorm/gorm / CreateTable

Method CreateTable

migrator/migrator.go:216–317  ·  view source on GitHub ↗

CreateTable create table in database for values

(values ...interface{})

Source from the content-addressed store, hash-verified

214
215// CreateTable create table in database for values
216func (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))

Callers

nothing calls this directly

Implementers 1

Migratormigrator/migrator.go

Calls 15

ReorderModelsMethod · 0.95
RunWithValueMethod · 0.95
CurrentTableMethod · 0.95
DataTypeOfMethod · 0.95
SessionMethod · 0.80
ContainsMethod · 0.80
ParseIndexesMethod · 0.80
ParseConstraintMethod · 0.80
QuoteMethod · 0.80
ParseCheckConstraintsMethod · 0.80
NewMethod · 0.65

Tested by

no test coverage detected