Skip to content

Commit 91f1756

Browse files
committed
sanitize schema and split create migration table from checking its existence when running migrations
1 parent ec76d83 commit 91f1756

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

dbos/system_database.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,8 @@ func runMigrations(pool *pgxpool.Pool, schema string) error {
173173

174174
// Check if the schema exists
175175
var schemaExists bool
176-
checkSchemaQuery := fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE schema_name = '%s')", schema)
177-
err = tx.QueryRow(ctx, checkSchemaQuery).Scan(&schemaExists)
176+
checkSchemaQuery := `SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE schema_name = $1)`
177+
err = tx.QueryRow(ctx, checkSchemaQuery, schema).Scan(&schemaExists)
178178
if err != nil {
179179
return fmt.Errorf("failed to check if schema %s exists: %v", schema, err)
180180
}
@@ -189,13 +189,19 @@ func runMigrations(pool *pgxpool.Pool, schema string) error {
189189
}
190190

191191
// Create the migrations table if it doesn't exist
192-
createTableQuery := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s.%s (
193-
version BIGINT NOT NULL PRIMARY KEY
194-
)`, pgx.Identifier{schema}.Sanitize(), _DBOS_MIGRATION_TABLE)
192+
checkMigrationTableExistsQuery := `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2)`
195193

196-
_, err = tx.Exec(ctx, createTableQuery)
194+
var migrationTableExists bool
195+
err = tx.QueryRow(ctx, checkMigrationTableExistsQuery, schema, _DBOS_MIGRATION_TABLE).Scan(&migrationTableExists)
197196
if err != nil {
198-
return fmt.Errorf("failed to create migrations table: %v", err)
197+
return fmt.Errorf("failed to check if migration table exists: %v", err)
198+
}
199+
if !migrationTableExists {
200+
createTableQuery := fmt.Sprintf(`CREATE TABLE %s.%s (version BIGINT NOT NULL PRIMARY KEY)`, pgx.Identifier{schema}.Sanitize(), _DBOS_MIGRATION_TABLE)
201+
_, err = tx.Exec(ctx, createTableQuery)
202+
if err != nil {
203+
return fmt.Errorf("failed to create migrations table: %v", err)
204+
}
199205
}
200206

201207
// Get current migration version

0 commit comments

Comments
 (0)