Reputation: 550
Refering this help doc, there is a drop table if exists syntax db.DropTableIfExists(&User{}, "products")
but for db.Model(&User{}).DropColumn("description")
DropColumnIfExists doesn't exists. What should I use to implement DropColumn (if the column exists, otherwise not.)
Upvotes: 0
Views: 3717
Reputation: 11
This should work:
func getTableName(db *gorm.DB, dst interface{}) string {
stmt := &gorm.Statement{DB: db}
if err := stmt.Parse(dst); err != nil {
return fmt.Sprintf("\"unknown; error parsing schema: %+v\"", err)
}
return stmt.Schema.Table
}
func dropColumnIfExists(db *gorm.DB, dst interface{}, field string) error {
if db.Migrator().HasColumn(dst, field) {
if err := db.Migrator().DropColumn(dst, field); err != nil {
return fmt.Errorf("unable to drop the %s column from table %s due to error: %+v", field, getTableName(db, dst), err)
}
} else {
log.Printf("Table %s no longer has a column named %s; skipping.", getTableName(db, dst), field)
}
return nil
}
Upvotes: 0
Reputation: 2627
What should I use to implement DropColumn (if the column exists, otherwise not.)
To answer your question...
Go ahead with that. You can use db.Model(&User{}).DropColumn("description")
.
Just handle the errors gracefully. Remember, in Golang, Errors are values.
func main() {
db.AutoMigrate(&User{})
err := db.Model(&User{}).DropColumn("description").Error
if err != nil {
// Do whatever you want to do!
log.Print("ERROR: We expect the description column to be
drop-able")
}
}
Under the Hood, gorm will execute raw postgresql query if it has no error. Otherwise, it will return the error.
Upvotes: 6
Reputation: 800
Update to Mohsin's answer as of 2021:
What should I use to implement DropColumn (if the column exists, otherwise not.)
the current version (3.5.5) does no more support the syntax/api of 2017
err = db.Migrator().DropColumn(&AuthUser{}, "name")
if err != nil {
// Do whatever you want to do!
log.Print("ERROR: We expect the description column to be drop-able")
}
Upvotes: 1