Skip to content

Commit

Permalink
When adding a new column to a table, include a primary key if the fie…
Browse files Browse the repository at this point in the history
…ld is either a primary key itself or has an auto-increment attribute (#129)

* When adding a new column to a table, include a primary key if the field is either a primary key itself or has an auto-increment attribute.

* When adding a new column to a table, include a primary key if the field is either a primary key itself or has an auto-increment attribute.

---------

Co-authored-by: Ganesan Karuppasamy <[email protected]>
  • Loading branch information
ckganesan and Ganesan Karuppasamy authored Oct 10, 2023
1 parent 386f545 commit 2a61ba0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
25 changes: 25 additions & 0 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 2a61ba0

Please sign in to comment.