gogo-gorm

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.)


Solution

  • 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.