Yash Goel
Yash Goel

Reputation: 550

DropColumn if exists in GORM

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

Answers (3)

Michael Pigott
Michael Pigott

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

Mohsin Aljiwala
Mohsin Aljiwala

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

lumo
lumo

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

From GORM Migration Reference

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

Related Questions