Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: implement PostgreSQL column default migration (#16705)

h3n4l41298e1d81a9
diff --git a/backend/common/engine.go b/backend/common/engine.go
index aaae0b7ae9..08392a4ee0 100644
--- a/backend/common/engine.go
+++ b/backend/common/engine.go
@@ -458,3 +458,55 @@ func BackupDatabaseNameOfEngine(e storepb.Engine) string {
return "bbdataarchive"
}
}
+
+// EngineNeedsColumnDefaultMigration returns true if the engine needs column default migration.
+// This is used by both the migrator and the sync process to determine if a database
+// needs the column default migration.
+// When an engine's sync.go is updated to write to the Default field with proper
+// normalization (like schema qualification), we move it to the false case.
+func EngineNeedsColumnDefaultMigration(e storepb.Engine) bool {
+ //exhaustive:enforce
+ switch e {
+ case
+ storepb.Engine_POSTGRES:
+ // PostgreSQL sync.go has been updated to write to Default field with
+ // proper schema qualification, so it doesn't need migration anymore.
+ return false
+ case
+ storepb.Engine_MYSQL,
+ storepb.Engine_TIDB,
+ storepb.Engine_MARIADB,
+ storepb.Engine_ORACLE,
+ storepb.Engine_OCEANBASE_ORACLE,
+ storepb.Engine_OCEANBASE,
+ storepb.Engine_SNOWFLAKE,
+ storepb.Engine_DM,
+ storepb.Engine_MSSQL,
+ storepb.Engine_CLICKHOUSE,
+ storepb.Engine_COCKROACHDB,
+ storepb.Engine_SPANNER,
+ storepb.Engine_BIGQUERY,
+ storepb.Engine_REDSHIFT,
+ storepb.Engine_RISINGWAVE,
+ storepb.Engine_STARROCKS,
+ storepb.Engine_DORIS:
+ // These engines still need migration as their sync.go hasn't been updated yet.
+ return true
+ case
+ storepb.Engine_ENGINE_UNSPECIFIED,
+ storepb.Engine_CASSANDRA,
+ storepb.Engine_SQLITE,
+ storepb.Engine_MONGODB,
+ storepb.Engine_REDIS,
+ storepb.Engine_HIVE,
+ storepb.Engine_DYNAMODB,
+ storepb.Engine_ELASTICSEARCH,
+ storepb.Engine_DATABRICKS,
+ storepb.Engine_COSMOSDB,
+ storepb.Engine_TRINO:
+ // These engines don't have traditional column defaults or are NoSQL databases.
+ return false
+ default:
+ return false
+ }
+}
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 794115707f..ab034153b2 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -135,6 +135,7 @@ CREATE TABLE db_schema (
metadata json NOT NULL DEFAULT '{}',
raw_dump text NOT NULL DEFAULT '',
config jsonb NOT NULL DEFAULT '{}',
+ todo boolean NOT NULL DEFAULT TRUE,
CONSTRAINT db_schema_instance_db_name_fkey FOREIGN KEY(instance, db_name) REFERENCES db(instance, name)
);
diff --git a/backend/plugin/db/pg/sync.go b/backend/plugin/db/pg/sync.go
index f695fe7387..45bb1ccb61 100644
--- a/backend/plugin/db/pg/sync.go
+++ b/backend/plugin/db/pg/sync.go
@@ -727,8 +727,11 @@ func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, er
if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &characterMaxLength, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName, &identityGeneration, &comment); err != nil {
return nil, err
}
+ // Store schema-qualified default in the Default field for Step 4 of column default migration
if defaultStr.Valid {
- column.DefaultExpression = defaultStr.String
+ column.Default = defaultStr.String
+ } else {
+ column.Default = "" // Handle NULL case (no default or DEFAULT NULL)
}
isNullBool, err := util.ConvertYesNo(nullable)
if err != nil {
diff --git a/backend/plugin/db/pg/sync_column_default_test.go b/backend/plugin/db/pg/sync_column_default_test.go
new file mode 100644
index 0000000000..d407010b83
--- /dev/null
+++ b/backend/plugin/db/pg/sync_column_default_test.go
@@ -0,0 +1,349 @@
+package pg
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func TestSync_ColumnDefaultSchemaQualification(t *testing.T) {
+ ctx := context.Background()
+
+ // Use the centralized testcontainer helper
+ pgContainer := testcontainer.GetTestPgContainer(ctx, t)
+ defer pgContainer.Close(ctx)
+
+ // Get database connection
+ pgDB := pgContainer.GetDB()
+ require.NoError(t, pgDB.Ping())
+
+ // Set up test schema with various default value scenarios
+ setupSQL := `
+-- Create enum type for testing schema qualification
+CREATE TYPE test_size AS ENUM ('small', 'medium', 'large');
+
+-- Create sequence for testing schema qualification
+CREATE SEQUENCE test_sequence START 1;
+
+-- Create test table with various default scenarios
+CREATE TABLE test_defaults (
+ -- No default
+ id INTEGER,
+
+ -- NULL default
+ col_null_default TEXT DEFAULT NULL,
+
+ -- String literal with schema-qualified type
+ col_string_literal VARCHAR(50) DEFAULT 'hello',
+
+ -- Numeric literal
+ col_numeric INTEGER DEFAULT 42,
+
+ -- Boolean literal
+ col_boolean BOOLEAN DEFAULT true,
+
+ -- Function expression
+ col_function TIMESTAMP DEFAULT now(),
+
+ -- Expression
+ col_expression INTEGER DEFAULT (10 + 20),
+
+ -- SERIAL (creates sequence automatically)
+ col_serial SERIAL,
+
+ -- Enum default (should be schema-qualified)
+ col_enum test_size DEFAULT 'medium',
+
+ -- Custom sequence (should be schema-qualified)
+ col_sequence INTEGER DEFAULT nextval('test_sequence'),
+
+ -- Array default
+ col_array INTEGER[] DEFAULT '{1,2,3}',
+
+ -- JSON default
+ col_json JSONB DEFAULT '{"key": "value"}',
+
+ -- Binary default
+ col_binary BYTEA DEFAULT '\xDEADBEEF'
+);
+
+-- Add comment to help identify the table
+COMMENT ON TABLE test_defaults IS 'Test table for column default schema qualification';
+`
+
+ // Execute the DDL
+ _, err := pgDB.Exec(setupSQL)
+ require.NoError(t, err)
+
+ // Create driver and get metadata using SyncDBSchema
+ driver := &Driver{}
+ config := db.ConnectionConfig{
+ DataSource: &storepb.DataSource{
+ Type: storepb.DataSourceType_ADMIN,
+ Username: "postgres",
+ Host: pgContainer.GetHost(),
+ Port: pgContainer.GetPort(),
+ Database: "postgres",
+ },
+ Password: "root-password",
+ ConnectionContext: db.ConnectionContext{
+ EngineVersion: "16.0",
+ DatabaseName: "postgres",
+ },
+ }
+
+ openedDriver, err := driver.Open(ctx, storepb.Engine_POSTGRES, config)
+ require.NoError(t, err)
+ defer openedDriver.Close(ctx)
+
+ pgDriver, ok := openedDriver.(*Driver)
+ require.True(t, ok)
+
+ // Run sync operation to get metadata
+ metadata, err := pgDriver.SyncDBSchema(ctx)
+ require.NoError(t, err)
+ require.NotNil(t, metadata)
+
+ // Find our test table
+ var testTable *storepb.TableMetadata
+ for _, schema := range metadata.Schemas {
+ if schema.Name == "public" {
+ for _, table := range schema.Tables {
+ if table.Name == "test_defaults" {
+ testTable = table
+ break
+ }
+ }
+ }
+ }
+ require.NotNil(t, testTable, "test_defaults table should be found")
+
+ // Create a map for easier column lookup
+ columnMap := make(map[string]*storepb.ColumnMetadata)
+ for _, col := range testTable.Columns {
+ columnMap[col.Name] = col
+ }
+
+ // Test cases to verify schema qualification
+ testCases := []struct {
+ columnName string
+ expectedDefault string
+ description string
+ }{
+ {
+ columnName: "id",
+ expectedDefault: "",
+ description: "No default should be empty string",
+ },
+ {
+ columnName: "col_null_default",
+ expectedDefault: "",
+ description: "DEFAULT NULL should be empty string (PostgreSQL limitation)",
+ },
+ {
+ columnName: "col_string_literal",
+ expectedDefault: "'hello'::character varying",
+ description: "String literal should have type cast",
+ },
+ {
+ columnName: "col_numeric",
+ expectedDefault: "42",
+ description: "Numeric literal should be unquoted",
+ },
+ {
+ columnName: "col_boolean",
+ expectedDefault: "true",
+ description: "Boolean literal should be unquoted",
+ },
+ {
+ columnName: "col_function",
+ expectedDefault: "now()",
+ description: "Function should be preserved",
+ },
+ {
+ columnName: "col_expression",
+ expectedDefault: "(10 + 20)",
+ description: "Expression should preserve parentheses",
+ },
+ {
+ columnName: "col_enum",
+ expectedDefault: "'medium'::public.test_size",
+ description: "Enum default should be SCHEMA-QUALIFIED with public.test_size",
+ },
+ {
+ columnName: "col_sequence",
+ expectedDefault: "nextval('public.test_sequence'::regclass)",
+ description: "Custom sequence should be SCHEMA-QUALIFIED with public.test_sequence",
+ },
+ {
+ columnName: "col_array",
+ expectedDefault: "'{1,2,3}'::integer[]",
+ description: "Array should have type cast",
+ },
+ {
+ columnName: "col_json",
+ expectedDefault: "'{\"key\": \"value\"}'::jsonb",
+ description: "JSONB should have type cast",
+ },
+ {
+ columnName: "col_binary",
+ expectedDefault: "'\\xdeadbeef'::bytea",
+ description: "Binary should have type cast and lowercase hex",
+ },
+ }
+
+ // Verify each test case
+ for _, tc := range testCases {
+ t.Run(tc.columnName, func(t *testing.T) {
+ column, exists := columnMap[tc.columnName]
+ require.True(t, exists, "Column %s should exist", tc.columnName)
+
+ require.Equal(t, tc.expectedDefault, column.Default,
+ "Column %s: %s. Expected: %q, Got: %q",
+ tc.columnName, tc.description, tc.expectedDefault, column.Default)
+ })
+ }
+
+ // Special test: Verify SERIAL column has schema-qualified sequence
+ serialColumn, exists := columnMap["col_serial"]
+ require.True(t, exists, "col_serial should exist")
+ require.Contains(t, serialColumn.Default, "public.test_defaults_col_serial_seq",
+ "SERIAL column should have schema-qualified sequence name. Got: %s", serialColumn.Default)
+ require.Contains(t, serialColumn.Default, "nextval(",
+ "SERIAL column should use nextval function. Got: %s", serialColumn.Default)
+
+ // Verify that DefaultExpression is NOT being used (should be empty since we're using Default)
+ for columnName, column := range columnMap {
+ require.Empty(t, column.DefaultExpression,
+ "Column %s should not use DefaultExpression field (Step 4 migration)", columnName)
+ }
+}
+
+func TestSync_ColumnDefaultCrossSchemaQualification(t *testing.T) {
+ ctx := context.Background()
+
+ // Use the centralized testcontainer helper
+ pgContainer := testcontainer.GetTestPgContainer(ctx, t)
+ defer pgContainer.Close(ctx)
+
+ // Get database connection
+ pgDB := pgContainer.GetDB()
+ require.NoError(t, pgDB.Ping())
+
+ // Create schema with cross-schema references
+ setupSQL := `
+-- Create custom schema to test cross-schema qualification
+CREATE SCHEMA custom_schema;
+
+-- Create enum in custom schema
+CREATE TYPE custom_schema.status_type AS ENUM ('active', 'inactive', 'pending');
+
+-- Create sequence in custom schema
+CREATE SEQUENCE custom_schema.my_sequence START 100;
+
+-- Create function in custom schema for testing
+CREATE OR REPLACE FUNCTION custom_schema.get_prefix() RETURNS TEXT AS $$
+BEGIN
+ RETURN 'prefix_value';
+END;
+$$ LANGUAGE plpgsql IMMUTABLE;
+
+-- Test table in public schema with references to custom schema objects
+CREATE TABLE critical_test (
+ -- Cross-schema enum reference
+ status custom_schema.status_type DEFAULT 'active',
+
+ -- Cross-schema sequence reference
+ counter INTEGER DEFAULT nextval('custom_schema.my_sequence'),
+
+ -- Complex expression with cross-schema function
+ computed TEXT DEFAULT custom_schema.get_prefix()
+);
+`
+
+ // Execute the DDL
+ _, err := pgDB.Exec(setupSQL)
+ require.NoError(t, err)
+
+ // Create driver and get metadata
+ driver := &Driver{}
+ config := db.ConnectionConfig{
+ DataSource: &storepb.DataSource{
+ Type: storepb.DataSourceType_ADMIN,
+ Username: "postgres",
+ Host: pgContainer.GetHost(),
+ Port: pgContainer.GetPort(),
+ Database: "postgres",
+ },
+ Password: "root-password",
+ ConnectionContext: db.ConnectionContext{
+ EngineVersion: "16.0",
+ DatabaseName: "postgres",
+ },
+ }
+
+ openedDriver, err := driver.Open(ctx, storepb.Engine_POSTGRES, config)
+ require.NoError(t, err)
+ defer openedDriver.Close(ctx)
+
+ pgDriver, ok := openedDriver.(*Driver)
+ require.True(t, ok)
+
+ // Run sync operation
+ metadata, err := pgDriver.SyncDBSchema(ctx)
+ require.NoError(t, err)
+
+ // Find the test table
+ var testTable *storepb.TableMetadata
+ for _, schema := range metadata.Schemas {
+ if schema.Name == "public" {
+ for _, table := range schema.Tables {
+ if table.Name == "critical_test" {
+ testTable = table
+ break
+ }
+ }
+ }
+ }
+ require.NotNil(t, testTable)
+
+ // Verify cross-schema qualification
+ columnMap := make(map[string]*storepb.ColumnMetadata)
+ for _, col := range testTable.Columns {
+ columnMap[col.Name] = col
+ }
+
+ // Critical test: Cross-schema enum should be fully qualified
+ statusCol := columnMap["status"]
+ require.NotNil(t, statusCol)
+ require.Equal(t, "'active'::custom_schema.status_type", statusCol.Default,
+ "Cross-schema enum should be fully qualified")
+
+ // Critical test: Cross-schema sequence should be fully qualified
+ counterCol := columnMap["counter"]
+ require.NotNil(t, counterCol)
+ require.Equal(t, "nextval('custom_schema.my_sequence'::regclass)", counterCol.Default,
+ "Cross-schema sequence should be fully qualified")
+
+ // Critical test: Complex expression with cross-schema function
+ computedCol := columnMap["computed"]
+ require.NotNil(t, computedCol)
+ require.Equal(t, "custom_schema.get_prefix()", computedCol.Default,
+ "Cross-schema function should be fully qualified")
+
+ // Cleanup: Drop test objects to avoid interference with other tests
+ cleanupSQL := `
+ DROP TABLE IF EXISTS critical_test CASCADE;
+ DROP TABLE IF EXISTS test_defaults CASCADE;
+ DROP SCHEMA IF EXISTS custom_schema CASCADE;
+ DROP TYPE IF EXISTS test_size CASCADE;
+ DROP SEQUENCE IF EXISTS test_sequence CASCADE;
+ `
+ _, err = pgDB.Exec(cleanupSQL)
+ require.NoError(t, err)
+}
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index c6f600a687..e95e220cb6 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -1024,8 +1024,7 @@ func getDefaultExpression(column *storepb.ColumnMetadata) string {
}
if column.Default != "" {
- // Quote string literals
- return fmt.Sprintf("'%s'", column.Default)
+ return column.Default
}
if column.DefaultNull {
diff --git a/backend/plugin/schema/pg/get_database_definition.go b/backend/plugin/schema/pg/get_database_definition.go
index ce67e10d03..aaf2bf06b8 100644
--- a/backend/plugin/schema/pg/get_database_definition.go
+++ b/backend/plugin/schema/pg/get_database_definition.go
@@ -1081,27 +1081,13 @@ func writeCreateTable(out io.Writer, schema string, tableName string, columns []
}
// Handle default values
- if column.DefaultExpression != "" {
+ if column.Default != "" {
if _, err := io.WriteString(out, ` DEFAULT `); err != nil {
return err
}
- if _, err := io.WriteString(out, column.DefaultExpression); err != nil {
- return err
- }
- } else if column.Default != "" {
- if _, err := io.WriteString(out, ` DEFAULT '`); err != nil {
- return err
- }
if _, err := io.WriteString(out, column.Default); err != nil {
return err
}
- if _, err := io.WriteString(out, `'`); err != nil {
- return err
- }
- } else if column.DefaultNull {
- if _, err := io.WriteString(out, ` DEFAULT NULL`); err != nil {
- return err
- }
}
if !column.Nullable {
diff --git a/backend/runner/migrator/column_default_migrator.go b/backend/runner/migrator/column_default_migrator.go
index 8b422ba528..6db6c06eb9 100644
--- a/backend/runner/migrator/column_default_migrator.go
+++ b/backend/runner/migrator/column_default_migrator.go
@@ -36,6 +36,19 @@ func NewColumnDefaultMigrator(store *store.Store, supportedEngines []storepb.Eng
}
}
+// EnginesNeedingMigration returns the list of engines that currently need column default migration.
+// This function dynamically builds the list based on common.EngineNeedsColumnDefaultMigration.
+func EnginesNeedingMigration() []storepb.Engine {
+ var engines []storepb.Engine
+ // Check all known engines
+ for _, engine := range storepb.Engine_value {
+ if common.EngineNeedsColumnDefaultMigration(storepb.Engine(engine)) {
+ engines = append(engines, storepb.Engine(engine))
+ }
+ }
+ return engines
+}
+
// Run starts the ColumnDefaultMigrator.
func (m *ColumnDefaultMigrator) Run(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
@@ -106,8 +119,9 @@ func (m *ColumnDefaultMigrator) migrate(ctx context.Context) error {
continue
}
- // Update metadata and todo in a single transaction.
- if err := m.store.UpdateDBSchemaMetadataAndTodo(ctx, dbSchema.ID, string(marshaled), false); err != nil {
+ // Update metadata and todo in a single transaction, only if todo is still true.
+ // This prevents race conditions with the sync process.
+ if err := m.store.UpdateDBSchemaMetadataIfTodo(ctx, dbSchema.ID, string(marshaled)); err != nil {
slog.Error("Failed to update db schema metadata and todo", slog.Int("db_schema_id", dbSchema.ID), slog.String("db_name", dbSchema.DBName), log.BBError(err))
continue
}
diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.go
index 4da612d313..b0e72f25c2 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -434,9 +434,10 @@ func (s *Syncer) SyncDatabaseSchemaToHistory(ctx context.Context, database *stor
}
rawDump := schemaBuf.Bytes()
+ todo := common.EngineNeedsColumnDefaultMigration(instance.Metadata.GetEngine())
if err := s.store.UpsertDBSchema(ctx,
database.InstanceID, database.DatabaseName,
- databaseMetadata, dbModelConfig.BuildDatabaseConfig(), rawDump,
+ databaseMetadata, dbModelConfig.BuildDatabaseConfig(), rawDump, todo,
); err != nil {
if strings.Contains(err.Error(), "escape sequence") {
if metadataBytes, err := protojson.Marshal(databaseMetadata); err == nil {
@@ -543,9 +544,10 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas
return errors.Wrapf(err, "failed to update database %q for instance %q", database.DatabaseName, database.InstanceID)
}
+ todo := common.EngineNeedsColumnDefaultMigration(instance.Metadata.GetEngine())
if err := s.store.UpsertDBSchema(ctx,
database.InstanceID, database.DatabaseName,
- databaseMetadata, dbModelConfig.BuildDatabaseConfig(), rawDump,
+ databaseMetadata, dbModelConfig.BuildDatabaseConfig(), rawDump, todo,
); err != nil {
if strings.Contains(err.Error(), "escape sequence") {
if metadataBytes, err := protojson.Marshal(databaseMetadata); err == nil {
diff --git a/backend/runner/schemasync/syncer_test.go b/backend/runner/schemasync/syncer_test.go
new file mode 100644
index 0000000000..740d6c0402
--- /dev/null
+++ b/backend/runner/schemasync/syncer_test.go
@@ -0,0 +1,73 @@
+package schemasync
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func TestTodoLogicForColumnDefaultMigration(t *testing.T) {
+ testCases := []struct {
+ name string
+ engine storepb.Engine
+ expectedTodo bool
+ description string
+ }{
+ {
+ name: "PostgreSQL",
+ engine: storepb.Engine_POSTGRES,
+ expectedTodo: false,
+ description: "PostgreSQL sync now writes to Default field with schema qualification",
+ },
+ {
+ name: "MySQL",
+ engine: storepb.Engine_MYSQL,
+ expectedTodo: true,
+ description: "MySQL sync hasn't been updated yet, needs migration",
+ },
+ {
+ name: "SQL Server",
+ engine: storepb.Engine_MSSQL,
+ expectedTodo: true,
+ description: "SQL Server sync hasn't been updated yet, needs migration",
+ },
+ {
+ name: "Oracle",
+ engine: storepb.Engine_ORACLE,
+ expectedTodo: true,
+ description: "Oracle sync hasn't been updated yet, needs migration",
+ },
+ {
+ name: "TiDB",
+ engine: storepb.Engine_TIDB,
+ expectedTodo: true,
+ description: "TiDB sync hasn't been updated yet, needs migration",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Use the centralized logic
+ todo := common.EngineNeedsColumnDefaultMigration(tc.engine)
+
+ require.Equal(t, tc.expectedTodo, todo,
+ "Engine %s: %s. Expected todo=%t, got todo=%t",
+ tc.name, tc.description, tc.expectedTodo, todo)
+ })
+ }
+}
+
+func TestEnginesNeedingMigrationConsistency(t *testing.T) {
+ // Verify that PostgreSQL doesn't need migration using the centralized logic
+ require.False(t, common.EngineNeedsColumnDefaultMigration(storepb.Engine_POSTGRES),
+ "PostgreSQL should not need migration")
+
+ // Verify that other common engines do need migration
+ require.True(t, common.EngineNeedsColumnDefaultMigration(storepb.Engine_MYSQL),
+ "MySQL should need migration")
+ require.True(t, common.EngineNeedsColumnDefaultMigration(storepb.Engine_MSSQL),
+ "SQL Server should need migration")
+}
diff --git a/backend/server/server.go b/backend/server/server.go
index b7e54c76fa..1726a0459c 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -205,7 +205,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
s.planCheckScheduler.Register(store.PlanCheckDatabaseStatementSummaryReport, statementReportExecutor)
// Column default value migrator
- s.columnDefaultMigrator = runnermigrator.NewColumnDefaultMigrator(stores, []storepb.Engine{})
+ s.columnDefaultMigrator = runnermigrator.NewColumnDefaultMigrator(stores, runnermigrator.EnginesNeedingMigration())
// Metric reporter
s.initMetricReporter()
diff --git a/backend/store/db_schema.go b/backend/store/db_schema.go
index 6e898167bc..5b3ea48fa7 100644
--- a/backend/store/db_schema.go
+++ b/backend/store/db_schema.go
@@ -74,6 +74,7 @@ func (s *Store) UpsertDBSchema(
dbMetadata *storepb.DatabaseSchemaMetadata,
dbConfig *storepb.DatabaseConfig,
dbSchema []byte,
+ todo bool,
) error {
metadataBytes, err := protojson.Marshal(dbMetadata)
if err != nil {
@@ -90,13 +91,15 @@ func (s *Store) UpsertDBSchema(
db_name,
metadata,
raw_dump,
- config
+ config,
+ todo
)
- VALUES ($1, $2, $3, $4, $5)
+ VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT(instance, db_name) DO UPDATE SET
metadata = EXCLUDED.metadata,
raw_dump = EXCLUDED.raw_dump,
- config = EXCLUDED.config
+ config = EXCLUDED.config,
+ todo = EXCLUDED.todo
RETURNING metadata, raw_dump, config
`
tx, err := s.db.BeginTx(ctx, nil)
@@ -113,6 +116,7 @@ func (s *Store) UpsertDBSchema(
// Convert to string because []byte{} is null which violates db schema constraints.
string(dbSchema),
configBytes,
+ todo,
).Scan(
&metadata,
&schema,
@@ -252,22 +256,35 @@ func (s *Store) UpdateDBSchemaMetadata(ctx context.Context, id int, metadata str
return tx.Commit()
}
-// UpdateDBSchemaMetadataAndTodo updates the metadata and todo columns of a db_schema.
-func (s *Store) UpdateDBSchemaMetadataAndTodo(ctx context.Context, id int, metadata string, todo bool) error {
+// UpdateDBSchemaMetadataIfTodo updates the metadata and sets todo to false only if todo is currently true.
+// This is used by the migrator to avoid race conditions with the sync process.
+// The WHERE condition ensures atomic check-and-update, preventing any race conditions.
+func (s *Store) UpdateDBSchemaMetadataIfTodo(ctx context.Context, id int, metadata string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
- if _, err := tx.ExecContext(ctx, `
+ result, err := tx.ExecContext(ctx, `
UPDATE db_schema
- SET metadata = $1, todo = $2
- WHERE id = $3
- `, metadata, todo, id); err != nil {
+ SET metadata = $1, todo = false
+ WHERE id = $2 AND todo = true
+ `, metadata, id)
+ if err != nil {
return err
}
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+
+ if rowsAffected == 0 {
+ // Schema was already processed by sync, skip update
+ return tx.Rollback()
+ }
+
return tx.Commit()
}