From 44972d0cd579e633ea6bcb0f496c53ecb4f86239 Mon Sep 17 00:00:00 2001 From: Matthew Jacobson Date: Thu, 22 Jun 2023 15:09:36 -0400 Subject: [PATCH] SQLStore: Fix Postgres dialect treating "false" migrator default as true (#69353) * SQLStore: Fix Postgres dialect treating "false" migrator default as true Previously, when creating a migration you could choose a default value for a new boolean column that looked correct but would be interpreted incorrectly by the Postgres dialect. For example, values such as "false" or "FALSE" would be treated as true by the Postgres dialect. This refactors how migration dialects determine the Default column value for boolean type columns. Each dialect now uses the same base code to parse the Default literal and panics if an unknown value is encountered. So, now AddColumnMigration and AddTableMigration will ensure that across dialects: - The exact same Default literals will be allowed. - The literals are converted to equivalent defaults in their DDL. - An error will be thrown if an invalid literal is provided. --- pkg/services/sqlstore/migrator/dialect.go | 9 +++++++++ pkg/services/sqlstore/migrator/postgres_dialect.go | 10 ---------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/pkg/services/sqlstore/migrator/dialect.go b/pkg/services/sqlstore/migrator/dialect.go index 27038cd9c24..9ba7b040450 100644 --- a/pkg/services/sqlstore/migrator/dialect.go +++ b/pkg/services/sqlstore/migrator/dialect.go @@ -2,6 +2,7 @@ package migrator import ( "fmt" + "strconv" "strings" "xorm.io/xorm" @@ -129,6 +130,14 @@ func (b *BaseDialect) EqStr() string { } func (b *BaseDialect) Default(col *Column) string { + if col.Type == DB_Bool { + // Ensure that all dialects support the same literals in the same way. + bl, err := strconv.ParseBool(col.Default) + if err != nil { + panic(fmt.Errorf("failed to create default value for column '%s': invalid boolean default value '%s'", col.Name, col.Default)) + } + return b.dialect.BooleanStr(bl) + } return col.Default } diff --git a/pkg/services/sqlstore/migrator/postgres_dialect.go b/pkg/services/sqlstore/migrator/postgres_dialect.go index e3075d27bf9..6fd443e3876 100644 --- a/pkg/services/sqlstore/migrator/postgres_dialect.go +++ b/pkg/services/sqlstore/migrator/postgres_dialect.go @@ -46,16 +46,6 @@ func (db *PostgresDialect) BatchSize() int { return 1000 } -func (db *PostgresDialect) Default(col *Column) string { - if col.Type == DB_Bool { - if col.Default == "0" { - return "FALSE" - } - return "TRUE" - } - return col.Default -} - func (db *PostgresDialect) SQLType(c *Column) string { var res string switch t := c.Type; t {