Skip to content

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

feat: detect duplicate version in revisions (#14079)

p0nyf785e3df9358
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index a81c19d9c5..3336f392b1 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -429,7 +429,7 @@ func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s
sheetID = &mc.sheet.UID
}
- insertedID, err := beginMigration(ctx, s, mi, prevSchemaBuf.String(), statement, sheetID)
+ insertedID, err := beginMigration(ctx, s, mi, mc, prevSchemaBuf.String(), statement, sheetID)
if err != nil {
return "", "", errors.Wrapf(err, "failed to begin migration")
}
@@ -495,27 +495,48 @@ func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s
}
// beginMigration checks before executing migration and inserts a migration history record with pending status.
-func beginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
+func beginMigration(ctx context.Context, stores *store.Store, mi *db.MigrationInfo, mc *migrateContext, prevSchema, statement string, sheetID *int) (string, error) {
+ // list revisions and see if it has been applied
+ // we can do this because
+ // versioned migrations are executed one by one
+ // so no other migrations can insert revisions
+ //
+ // users can create revisions though via API
+ // however we can warn users not to unless they know
+ // what they are doing
+ if common.IsDev() {
+ list, err := stores.ListRevisions(ctx, &store.FindRevisionMessage{
+ DatabaseUID: mc.database.UID,
+ Version: &mc.version,
+ })
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to list revisions")
+ }
+ if len(list) > 0 {
+ return "", errors.Errorf("database %q has already applied version %s, hint: please check the database revisions and the version", mc.database.DatabaseName, mc.version)
+ }
+ }
+
// Phase 1 - Pre-check before executing migration
// Check if the same migration version has already been applied.
if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
- InstanceID: m.InstanceID,
- DatabaseID: m.DatabaseID,
- Version: &m.Version,
+ InstanceID: mi.InstanceID,
+ DatabaseID: mi.DatabaseID,
+ Version: &mi.Version,
}); err != nil {
return "", errors.Wrap(err, "failed to check duplicate version")
} else if len(list) > 0 {
migrationHistory := list[0]
switch migrationHistory.Status {
case db.Done:
- return "", common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, m.Version.Version)
+ return "", common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", mi.Database, mi.Version.Version)
case db.Pending:
- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)
+ err := errors.Errorf("database %q version %s migration is already in progress", mi.Database, mi.Version.Version)
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
return migrationHistory.UID, nil
case db.Failed:
- err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", m.Database, m.Version.Version)
+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", mi.Database, mi.Version.Version)
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
return migrationHistory.UID, nil
@@ -524,7 +545,7 @@ func beginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInf
// Phase 2 - Record migration history as PENDING.
statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
- insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)
+ insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, mi, statementRecord, sheetID)
if err != nil {
return "", err
}
@@ -547,7 +568,7 @@ func endMigration(ctx context.Context, storeInstance *store.Store, startedNs int
// TODO(p0ny): maybe remove this field.
Type: storepb.ReleaseFileType_TYPE_UNSPECIFIED,
},
- }, api.SystemBotID)
+ }, mc.task.CreatorID)
if err != nil {
return errors.Wrapf(err, "failed to create revision")
}
diff --git a/backend/store/revision.go b/backend/store/revision.go
index 2f94d06396..c64df76f9f 100644
--- a/backend/store/revision.go
+++ b/backend/store/revision.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
+ "strings"
"time"
"github.com/pkg/errors"
@@ -27,12 +28,32 @@ type RevisionMessage struct {
type FindRevisionMessage struct {
DatabaseUID int
+ Version *string
+
Limit *int
Offset *int
}
func (s *Store) ListRevisions(ctx context.Context, find *FindRevisionMessage) ([]*RevisionMessage, error) {
- query := `
+ where, args := []string{"TRUE"}, []any{}
+
+ where = append(where, fmt.Sprintf("database_id = $%d", len(args)+1))
+ args = append(args, find.DatabaseUID)
+
+ if v := find.Version; v != nil {
+ where = append(where, fmt.Sprintf("payload->>'version' = $%d", len(args)+1))
+ args = append(args, *v)
+ }
+
+ limitOffsetClause := ""
+ if v := find.Limit; v != nil {
+ limitOffsetClause += fmt.Sprintf(" LIMIT %d", *v)
+ }
+ if v := find.Offset; v != nil {
+ limitOffsetClause += fmt.Sprintf(" OFFSET %d", *v)
+ }
+
+ query := fmt.Sprintf(`
SELECT
id,
database_id,
@@ -40,15 +61,10 @@ func (s *Store) ListRevisions(ctx context.Context, find *FindRevisionMessage) ([
created_ts,
payload
FROM revision
- WHERE database_id = $1
- `
-
- if v := find.Limit; v != nil {
- query += fmt.Sprintf(" LIMIT %d", *v)
- }
- if v := find.Offset; v != nil {
- query += fmt.Sprintf(" OFFSET %d", *v)
- }
+ WHERE %s
+ %s
+ ORDER BY payload->>'version' DESC
+ `, strings.Join(where, " AND "), limitOffsetClause)
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
@@ -56,7 +72,7 @@ func (s *Store) ListRevisions(ctx context.Context, find *FindRevisionMessage) ([
}
defer tx.Rollback()
- rows, err := tx.QueryContext(ctx, query, find.DatabaseUID)
+ rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, errors.Wrapf(err, "failed to query context")
}