Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug when changing an existing column property from a state with a default value to a state without a default value #289

Open
wookie0 opened this issue Nov 12, 2024 · 0 comments
Assignees

Comments

@wookie0
Copy link
Contributor

wookie0 commented Nov 12, 2024

GORM Playground Link

Sorry, It's such an obvious bug that I don't think there's any need for example code.

Description

The code below does not take some cases into account. I think this is a bug. There is a default value in the existing column property, but if the column property to be changed does not have a default value, no processing is performed. I think if field.HasDefaultValue is false, you need to perform a DROP DEFAULT query.

postgres/migrator.go

Lines 383 to 401 in 0d37bf2

if v, ok := fieldColumnType.DefaultValue(); (field.DefaultValueInterface == nil && ok) || v != field.DefaultValue {
if field.HasDefaultValue && (field.DefaultValueInterface != nil || field.DefaultValue != "") {
if field.DefaultValueInterface != nil {
defaultStmt := &gorm.Statement{Vars: []interface{}{field.DefaultValueInterface}}
m.Dialector.BindVarTo(defaultStmt, defaultStmt, field.DefaultValueInterface)
if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? SET DEFAULT ?", m.CurrentTable(stmt), clause.Column{Name: field.DBName}, clause.Expr{SQL: m.Dialector.Explain(defaultStmt.SQL.String(), field.DefaultValueInterface)}).Error; err != nil {
return err
}
} else if field.DefaultValue != "(-)" {
if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? SET DEFAULT ?", m.CurrentTable(stmt), clause.Column{Name: field.DBName}, clause.Expr{SQL: field.DefaultValue}).Error; err != nil {
return err
}
} else {
if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? DROP DEFAULT", m.CurrentTable(stmt), clause.Column{Name: field.DBName}, clause.Expr{SQL: field.DefaultValue}).Error; err != nil {
return err
}
}
}
}

wookie0 added a commit to wookie0/postgres that referenced this issue Nov 12, 2024
wookie0 added a commit to wookie0/postgres that referenced this issue Nov 18, 2024
jinzhu pushed a commit that referenced this issue Nov 21, 2024
* [#289] Add coverage for eliminating default value tag

* [#289] wip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants