Skip to content

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

chore: migrate rollbackStatement to sheet (#5870)

Danny Xuf0077a461e33
diff --git a/backend/legacyapi/issue.go b/backend/legacyapi/issue.go
index b16153b586..eff1b13a08 100644
--- a/backend/legacyapi/issue.go
+++ b/backend/legacyapi/issue.go
@@ -163,7 +163,7 @@ type MigrationDetail struct {
// SchemaVersion is parsed from VCS file name.
// It is automatically generated in the UI workflow.
SchemaVersion string `json:"schemaVersion"`
- // If RollbackEnabled, build the rollbackStatement of the task.
+ // If RollbackEnabled, build the RollbackSheetID of the task.
RollbackEnabled bool `json:"rollbackEnabled"`
// if RollbackDetail is not nil, then this task is for rolling back another task.
RollbackDetail *RollbackDetail `json:"rollbackDetail"`
diff --git a/backend/legacyapi/task.go b/backend/legacyapi/task.go
index 5e2dd576cd..bc9a4d27cf 100644
--- a/backend/legacyapi/task.go
+++ b/backend/legacyapi/task.go
@@ -185,7 +185,7 @@ type TaskDatabaseDataUpdatePayload struct {
// MySQL rollback SQL related.
- // Build the RollbackStatement if RollbackEnabled.
+ // Build the RollbackSheetID if RollbackEnabled.
RollbackEnabled bool `json:"rollbackEnabled,omitempty"`
// RollbackSQLStatus is the status of the rollback generation.
RollbackSQLStatus RollbackSQLStatus `json:"rollbackSqlStatus,omitempty"`
@@ -205,8 +205,8 @@ type TaskDatabaseDataUpdatePayload struct {
BinlogPosStart int64 `json:"binlogPosStart,omitempty"`
BinlogPosEnd int64 `json:"binlogPosEnd,omitempty"`
RollbackError string `json:"rollbackError,omitempty"`
- // RollbackStatement is the generated rollback SQL statement for the DML task.
- RollbackStatement string `json:"rollbackStatement,omitempty"`
+ // RollbackSheetID is the generated rollback SQL statement for the DML task.
+ RollbackSheetID int `json:"rollbackSheetId,omitempty"`
// RollbackFromIssueID is the issue ID containing the original task from which the rollback SQL statement is generated for this task.
RollbackFromIssueID int `json:"rollbackFromIssueId,omitempty"`
// RollbackFromTaskID is the task ID from which the rollback SQL statement is generated for this task.
@@ -350,8 +350,10 @@ type TaskPatch struct {
SchemaVersion *string
RollbackEnabled *bool `jsonapi:"attr,rollbackEnabled"`
RollbackSQLStatus *RollbackSQLStatus
- RollbackStatement *string
- RollbackError *string
+ // RollbackSheetID sets the rollback sheet ID.
+ // When RollbackEnabled is enabled, RollbackSheetID is kept till it's set to the new sheet ID by the runner.
+ RollbackSheetID *int
+ RollbackError *string
}
// TaskStatusPatch is the API message for patching a task status.
diff --git a/backend/migrator/migration/prod/1.18/0001##migrate_task_payload_statement_to_sheet.sql b/backend/migrator/migration/prod/1.18/0001##migrate_task_payload_statement_to_sheet.sql
index 2af132f1c7..a71610a982 100644
--- a/backend/migrator/migration/prod/1.18/0001##migrate_task_payload_statement_to_sheet.sql
+++ b/backend/migrator/migration/prod/1.18/0001##migrate_task_payload_statement_to_sheet.sql
@@ -24,3 +24,30 @@ WHERE task.id = task_row.id;
END LOOP;
END $$;
+
+DO $$
+DECLARE
+ task_row RECORD;
+ sheet_id INT;
+BEGIN
+FOR task_row IN (
+ SELECT task.id, task.payload->>'rollbackStatement' AS statement FROM task WHERE task.payload ? 'rollbackStatement' ORDER BY task.id
+)
+LOOP
+
+INSERT INTO
+ sheet (creator_id, updater_id, project_id, database_id, name, statement, visibility, source, type, payload)
+SELECT
+ task.creator_id, task.creator_id, issue.project_id, task.database_id, CONCAT('A rollback sheet for issue #', issue.id), task_row.statement, 'PROJECT', 'BYTEBASE_ARTIFACT', 'SQL', '{}'
+FROM task
+LEFT JOIN issue ON task.pipeline_id = issue.pipeline_id
+WHERE task.id = task_row.id
+RETURNING sheet.id
+INTO sheet_id;
+
+UPDATE task
+SET payload = task.payload - 'rollbackStatement' || jsonb_build_object('rollbackSheetId', sheet_id)
+WHERE task.id = task_row.id;
+
+END LOOP;
+END $$;
diff --git a/backend/runner/rollbackrun/runner.go b/backend/runner/rollbackrun/runner.go
index 0cd268b2e4..cc4ca52333 100644
--- a/backend/runner/rollbackrun/runner.go
+++ b/backend/runner/rollbackrun/runner.go
@@ -105,16 +105,27 @@ func (r *Runner) generateRollbackSQL(ctx context.Context, task *store.TaskMessag
log.Error("Failed to find instance", zap.Error(err))
return
}
+ database, err := r.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})
+ if err != nil {
+ log.Error("Failed to find database", zap.Error(err))
+ return
+ }
+ project, err := r.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &database.ProjectID})
+ if err != nil {
+ log.Error("Failed to find project", zap.Error(err))
+ return
+ }
+
switch instance.Engine {
case db.MySQL:
// TODO(d): support MariaDB.
- r.generateMySQLRollbackSQL(ctx, task, payload, instance)
+ r.generateMySQLRollbackSQL(ctx, task, payload, instance, project)
case db.Oracle:
- r.generateOracleRollbackSQL(ctx, task, payload, instance)
+ r.generateOracleRollbackSQL(ctx, task, payload, instance, project)
}
}
-func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.TaskMessage, payload *api.TaskDatabaseDataUpdatePayload, instance *store.InstanceMessage) {
+func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.TaskMessage, payload *api.TaskDatabaseDataUpdatePayload, instance *store.InstanceMessage, project *store.ProjectMessage) {
var rollbackSQLStatus api.RollbackSQLStatus
var rollbackStatement, rollbackError string
@@ -128,11 +139,26 @@ func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.Task
rollbackStatement = statementsBuffer.String()
}
+ sheet, err := r.store.CreateSheet(ctx, &api.SheetCreate{
+ CreatorID: api.SystemBotID,
+ ProjectID: project.UID,
+ Name: fmt.Sprintf("Sheet for rolling back task %v", task.ID),
+ Statement: rollbackStatement,
+ Visibility: api.ProjectSheet,
+ Source: api.SheetFromBytebaseArtifact,
+ Type: api.SheetForSQL,
+ Payload: "{}",
+ })
+ if err != nil {
+ log.Error("failed to create database creation sheet", zap.Error(err))
+ return
+ }
+
patch := &api.TaskPatch{
ID: task.ID,
UpdaterID: api.SystemBotID,
RollbackSQLStatus: &rollbackSQLStatus,
- RollbackStatement: &rollbackStatement,
+ RollbackSheetID: &sheet.ID,
RollbackError: &rollbackError,
}
if _, err := r.store.UpdateTaskV2(ctx, patch); err != nil {
@@ -180,7 +206,7 @@ func (r *Runner) generateOracleRollbackSQLImpl(ctx context.Context, payload *api
return &statements, nil
}
-func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskMessage, payload *api.TaskDatabaseDataUpdatePayload, instance *store.InstanceMessage) {
+func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskMessage, payload *api.TaskDatabaseDataUpdatePayload, instance *store.InstanceMessage, project *store.ProjectMessage) {
var rollbackSQLStatus api.RollbackSQLStatus
var rollbackStatement, rollbackError string
@@ -201,11 +227,25 @@ func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskM
rollbackStatement = rollbackSQL
}
+ sheet, err := r.store.CreateSheet(ctx, &api.SheetCreate{
+ CreatorID: api.SystemBotID,
+ ProjectID: project.UID,
+ Name: fmt.Sprintf("Sheet for rolling back task %d", task.ID),
+ Statement: rollbackStatement,
+ Visibility: api.ProjectSheet,
+ Source: api.SheetFromBytebaseArtifact,
+ Type: api.SheetForSQL,
+ Payload: "{}",
+ })
+ if err != nil {
+ log.Error("failed to create database creation sheet", zap.Error(err))
+ return
+ }
patch := &api.TaskPatch{
ID: task.ID,
UpdaterID: api.SystemBotID,
RollbackSQLStatus: &rollbackSQLStatus,
- RollbackStatement: &rollbackStatement,
+ RollbackSheetID: &sheet.ID,
RollbackError: &rollbackError,
}
if _, err := r.store.UpdateTaskV2(ctx, patch); err != nil {
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index ae8901dfcb..1b090b1a21 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -375,12 +375,12 @@ func (s *Scheduler) PatchTask(ctx context.Context, task *store.TaskMessage, task
}
// Reset because we are trying to build
- // the rollbackStatement again and there could be previous runs.
+ // the RollbackSheetID again and there could be previous runs.
if taskPatch.RollbackEnabled != nil && *taskPatch.RollbackEnabled {
empty := ""
pending := api.RollbackSQLStatusPending
taskPatch.RollbackSQLStatus = &pending
- taskPatch.RollbackStatement = &empty
+ taskPatch.RollbackSheetID = nil
taskPatch.RollbackError = &empty
}
// if *taskPatch.RollbackEnabled == false, we don't reset
diff --git a/backend/store/task.go b/backend/store/task.go
index d5f30ef375..a5572734d4 100644
--- a/backend/store/task.go
+++ b/backend/store/task.go
@@ -438,8 +438,8 @@ func (s *Store) UpdateTaskV2(ctx context.Context, patch *api.TaskPatch) (*TaskMe
if (patch.SchemaVersion != nil || patch.SheetID != nil) && patch.Payload != nil {
return nil, errors.Errorf("cannot set both sheetID/schemaVersion and payload for TaskPatch")
}
- if (patch.RollbackEnabled != nil || patch.RollbackSQLStatus != nil || patch.RollbackStatement != nil || patch.RollbackError != nil) && patch.Payload != nil {
- return nil, errors.Errorf("cannot set both rollbackEnabled/rollbackSQLStatus/rollbackStatement/rollbackError payload for TaskPatch")
+ if (patch.RollbackEnabled != nil || patch.RollbackSQLStatus != nil || patch.RollbackSheetID != nil || patch.RollbackError != nil) && patch.Payload != nil {
+ return nil, errors.Errorf("cannot set both rollbackEnabled/rollbackSQLStatus/rollbackSheetID/rollbackError payload for TaskPatch")
}
var payloadSet []string
if v := patch.SheetID; v != nil {
@@ -454,8 +454,8 @@ func (s *Store) UpdateTaskV2(ctx context.Context, patch *api.TaskPatch) (*TaskMe
if v := patch.RollbackSQLStatus; v != nil {
payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('rollbackSqlStatus', to_jsonb($%d::TEXT))`, len(args)+1)), append(args, *v)
}
- if v := patch.RollbackStatement; v != nil {
- payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('rollbackStatement', to_jsonb($%d::TEXT))`, len(args)+1)), append(args, *v)
+ if v := patch.RollbackSheetID; v != nil {
+ payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('rollbackSheetId', to_jsonb($%d::INT))`, len(args)+1)), append(args, *v)
}
if v := patch.RollbackError; v != nil {
payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('rollbackError', to_jsonb($%d::TEXT))`, len(args)+1)), append(args, *v)
diff --git a/backend/tests/rollback_test.go b/backend/tests/rollback_test.go
index 1798482fca..808ba6f88d 100644
--- a/backend/tests/rollback_test.go
+++ b/backend/tests/rollback_test.go
@@ -251,16 +251,6 @@ func TestCreateRollbackIssueMySQL(t *testing.T) {
a.NoError(err)
a.Equal(api.RollbackSQLStatusDone, payload.RollbackSQLStatus)
- rollbackSheet, err := ctl.createSheet(api.SheetCreate{
- ProjectID: project.ID,
- Name: "rollback statement sheet",
- Statement: payload.RollbackStatement,
- Visibility: api.ProjectSheet,
- Source: api.SheetFromBytebaseArtifact,
- Type: api.SheetForSQL,
- })
- a.NoError(err)
-
// Run a rollback issue.
var rollbackIssue *api.Issue
rollbackCreateContext, err := json.Marshal(&api.MigrationContext{
@@ -268,7 +258,7 @@ func TestCreateRollbackIssueMySQL(t *testing.T) {
{
MigrationType: db.Data,
DatabaseID: database.ID,
- SheetID: rollbackSheet.ID,
+ SheetID: payload.RollbackSheetID,
RollbackDetail: &api.RollbackDetail{
IssueID: issue.ID,
TaskID: task.ID,
@@ -484,16 +474,6 @@ func TestCreateRollbackIssueMySQLByPatch(t *testing.T) {
a.NoError(err)
a.Equal(api.RollbackSQLStatusDone, payload.RollbackSQLStatus)
- rollbackSheet, err := ctl.createSheet(api.SheetCreate{
- ProjectID: project.ID,
- Name: "rollback statement sheet",
- Statement: payload.RollbackStatement,
- Visibility: api.ProjectSheet,
- Source: api.SheetFromBytebaseArtifact,
- Type: api.SheetForSQL,
- })
- a.NoError(err)
-
// Run a rollback issue.
var rollbackIssue *api.Issue
rollbackCreateContext, err := json.Marshal(&api.MigrationContext{
@@ -501,7 +481,7 @@ func TestCreateRollbackIssueMySQLByPatch(t *testing.T) {
{
MigrationType: db.Data,
DatabaseID: database.ID,
- SheetID: rollbackSheet.ID,
+ SheetID: payload.RollbackSheetID,
RollbackDetail: &api.RollbackDetail{
IssueID: issue.ID,
TaskID: task.ID,
diff --git a/frontend/src/components/Issue/rollback/RollbackStatus.vue b/frontend/src/components/Issue/rollback/RollbackStatus.vue
index 6c784cc32f..d76e38cfc3 100644
--- a/frontend/src/components/Issue/rollback/RollbackStatus.vue
+++ b/frontend/src/components/Issue/rollback/RollbackStatus.vue
@@ -37,7 +37,7 @@
>
{{ $t("task.rollback.preview-rollback-issue") }}
</button>
- <NTooltip v-else :disabled="!!payload?.rollbackStatement">
+ <NTooltip v-else :disabled="!!payload?.rollbackSheetId">
<template #trigger>
<div
class="select-none inline-flex border border-control-border rounded-md bg-control-bg opacity-50 cursor-not-allowed px-3 py-1 text-sm leading-5 font-medium"
@@ -46,10 +46,10 @@
</div>
</template>
- <div v-if="!payload?.rollbackStatement" class="whitespace-pre-line">
+ <div v-if="!payload?.rollbackSheetId" class="whitespace-pre-line">
{{ $t("task.rollback.empty-rollback-statement") }}
<LearnMoreLink
- url="https://www.bytebase.com/docs/change-database/rollback-data-changes?source=console#why-i-get-the-rollback-statement-is-empty"
+ url="https://www.bytebase.com/docs/change-database/rollback-data-changes?source=console#why-i-get-the-rollback-sheet-is-empty"
color="light"
class="ml-1"
/>
@@ -109,7 +109,7 @@ const allowPreviewRollback = computed(() => {
if (!allowRollback.value) {
return false;
}
- if (!payload.value?.rollbackStatement) {
+ if (!payload.value?.rollbackSheetId) {
return false;
}
return true;
@@ -157,6 +157,7 @@ const tryRollbackTask = async () => {
`${issue.value.name}`,
].join(" ");
+ // TODO(boojack): use sheetID. Or can we display partial sheet or link the sheet here.
const description = [
"The original SQL statement:",
`${payload.value!.statement}`,
@@ -174,7 +175,8 @@ const tryRollbackTask = async () => {
databaseList: [task.value.database!.id].join(","),
rollbackIssueId: issue.value.id,
rollbackTaskIdList: [task.value.id].join(","),
- sql: payload.value!.rollbackStatement!,
+ // TODO(boojack): use the rollbackSheetId.
+ sql: "",
description,
},
});
diff --git a/frontend/src/types/pipeline/task.ts b/frontend/src/types/pipeline/task.ts
index a90db083a9..8bafbc5645 100644
--- a/frontend/src/types/pipeline/task.ts
+++ b/frontend/src/types/pipeline/task.ts
@@ -124,7 +124,7 @@ export type TaskDatabaseDataUpdatePayload = {
pushEvent?: VCSPushEvent;
rollbackEnabled: boolean;
rollbackSqlStatus?: RollbackSQLStatus;
- rollbackStatement?: string;
+ rollbackSheetId?: SheetId;
rollbackError?: string;
rollbackFromIssueId?: IssueId;
rollbackFromTaskId?: TaskId;