Skip to content

Commit 2a61ba0

Browse files
ckganesanGanesan Karuppasamy
andauthored
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 (#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 <ganesan.karuppasamy@sap.com>
1 parent 386f545 commit 2a61ba0

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

go.sum

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/
77
gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64=
88
gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
99
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55 h1:sC1Xj4TYrLqg1n3AN10w871An7wJM0gzgcm8jkIkECQ=
10-
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
10+
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=

migrator.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,31 @@ func (m Migrator) FullDataTypeOf(field *schema.Field) clause.Expr {
4747
return expr
4848
}
4949

50+
func (m Migrator) AddColumn(value interface{}, name string) error {
51+
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
52+
// avoid using the same name field
53+
f := stmt.Schema.LookUpField(name)
54+
if f == nil {
55+
return fmt.Errorf("failed to look up field with name: %s", name)
56+
}
57+
58+
if !f.IgnoreMigration {
59+
fieldType := m.FullDataTypeOf(f)
60+
columnName := clause.Column{Name: f.DBName}
61+
values := []interface{}{m.CurrentTable(stmt), columnName, fieldType}
62+
var alterSql strings.Builder
63+
alterSql.WriteString("ALTER TABLE ? ADD ? ?")
64+
if f.PrimaryKey || strings.Contains(strings.ToLower(fieldType.SQL), "auto_increment") {
65+
alterSql.WriteString(", ADD PRIMARY KEY (?)")
66+
values = append(values, columnName)
67+
}
68+
return m.DB.Exec(alterSql.String(), values...).Error
69+
}
70+
71+
return nil
72+
})
73+
}
74+
5075
func (m Migrator) AlterColumn(value interface{}, field string) error {
5176
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
5277
if stmt.Schema != nil {

0 commit comments

Comments
 (0)