diff --git a/go.sum b/go.sum index f26389a..5db00fb 100644 --- a/go.sum +++ b/go.sum @@ -7,4 +7,4 @@ github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/ gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64= gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55 h1:sC1Xj4TYrLqg1n3AN10w871An7wJM0gzgcm8jkIkECQ= -gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= +gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= \ No newline at end of file diff --git a/migrator.go b/migrator.go index d35a86e..61caf04 100644 --- a/migrator.go +++ b/migrator.go @@ -47,6 +47,31 @@ func (m Migrator) FullDataTypeOf(field *schema.Field) clause.Expr { return expr } +func (m Migrator) AddColumn(value interface{}, name string) error { + return m.RunWithValue(value, func(stmt *gorm.Statement) error { + // avoid using the same name field + f := stmt.Schema.LookUpField(name) + if f == nil { + return fmt.Errorf("failed to look up field with name: %s", name) + } + + if !f.IgnoreMigration { + fieldType := m.FullDataTypeOf(f) + columnName := clause.Column{Name: f.DBName} + values := []interface{}{m.CurrentTable(stmt), columnName, fieldType} + var alterSql strings.Builder + alterSql.WriteString("ALTER TABLE ? ADD ? ?") + if f.PrimaryKey || strings.Contains(strings.ToLower(fieldType.SQL), "auto_increment") { + alterSql.WriteString(", ADD PRIMARY KEY (?)") + values = append(values, columnName) + } + return m.DB.Exec(alterSql.String(), values...).Error + } + + return nil + }) +} + func (m Migrator) AlterColumn(value interface{}, field string) error { return m.RunWithValue(value, func(stmt *gorm.Statement) error { if stmt.Schema != nil {