Skip to content

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

feat: implement the frontend part of restore sql (#12191)

rebelice1b10eaa889ba
diff --git a/backend/api/v1/acl_iam.go b/backend/api/v1/acl_iam.go
index e3442b0e7b..478b641d6e 100644
--- a/backend/api/v1/acl_iam.go
+++ b/backend/api/v1/acl_iam.go
@@ -75,6 +75,7 @@ func isSkippedMethod(fullMethod string) bool {
v1pb.SQLService_ParseMyBatisMapper_FullMethodName,
v1pb.SQLService_Pretty_FullMethodName,
v1pb.SQLService_StringifyMetadata_FullMethodName,
+ v1pb.SQLService_GenerateRestoreSQL_FullMethodName,
v1pb.SubscriptionService_GetSubscription_FullMethodName,
v1pb.SubscriptionService_GetFeatureMatrix_FullMethodName,
v1pb.SubscriptionService_UpdateSubscription_FullMethodName:
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index dc8e85a154..edfd578542 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1457,12 +1457,12 @@ func getOffsetAndOriginTable(backupTable string) (int, string, error) {
return 0, "", nil
}
parts := strings.Split(backupTable, "_")
- if len(parts) != 3 {
+ if len(parts) != 4 {
return 0, "", status.Errorf(codes.InvalidArgument, "invalid backup table format: %s", backupTable)
}
- offset, err := strconv.Atoi(parts[1])
+ offset, err := strconv.Atoi(parts[2])
if err != nil {
return 0, "", status.Errorf(codes.InvalidArgument, "invalid offset: %s", parts[0])
}
- return offset, parts[2], nil
+ return offset, parts[3], nil
}
diff --git a/backend/plugin/parser/mysql/restore.go b/backend/plugin/parser/mysql/restore.go
index c3c513a198..9f00c7065c 100644
--- a/backend/plugin/parser/mysql/restore.go
+++ b/backend/plugin/parser/mysql/restore.go
@@ -32,8 +32,16 @@ func GenerateRestoreSQL(statement string, backupDatabase string, backupTable str
originalDatabase: originalDatabase,
originalTable: originalTable,
}
+ var buf strings.Builder
antlr.ParseTreeWalkerDefault.Walk(g, parseResult[0].Tree)
- return g.result, g.err
+ if g.err != nil {
+ return "", g.err
+ }
+
+ if _, err := fmt.Fprintf(&buf, "/*\nOriginal SQL:\n%s\n*/\n%s", statement, g.result); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
}
type generator struct {
diff --git a/backend/plugin/parser/mysql/test-data/test_restore.yaml b/backend/plugin/parser/mysql/test-data/test_restore.yaml
index 8ef84550a5..88aeae278e 100644
--- a/backend/plugin/parser/mysql/test-data/test_restore.yaml
+++ b/backend/plugin/parser/mysql/test-data/test_restore.yaml
@@ -3,16 +3,31 @@
backuptable: prefix_1_test
originaldatabase: db
originaltable: test
- result: INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test`;
+ result: |-
+ /*
+ Original SQL:
+ DELETE test FROM test, test2 as t2 where test.id = t2.id;
+ */
+ INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test`;
- input: UPDATE test x SET x.c1 = 1 WHERE x.c1 = 1;
backupdatabase: bbarchive
backuptable: prefix_1_test
originaldatabase: db
originaltable: test
- result: INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test` ON DUPLICATE KEY UPDATE `c1` = VALUES(`c1`);
+ result: |-
+ /*
+ Original SQL:
+ UPDATE test x SET x.c1 = 1 WHERE x.c1 = 1;
+ */
+ INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test` ON DUPLICATE KEY UPDATE `c1` = VALUES(`c1`);
- input: UPDATE test SET c1 = 1 WHERE c1 = 1;
backupdatabase: bbarchive
backuptable: prefix_1_test
originaldatabase: db
originaltable: test
- result: INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test` ON DUPLICATE KEY UPDATE `c1` = VALUES(`c1`);
+ result: |-
+ /*
+ Original SQL:
+ UPDATE test SET c1 = 1 WHERE c1 = 1;
+ */
+ INSERT INTO `db`.`test` SELECT * FROM `bbarchive`.`prefix_1_test` ON DUPLICATE KEY UPDATE `c1` = VALUES(`c1`);
diff --git a/backend/runner/taskrun/data_update_executor.go b/backend/runner/taskrun/data_update_executor.go
index 3a61a89ee0..a03c8ef45f 100644
--- a/backend/runner/taskrun/data_update_executor.go
+++ b/backend/runner/taskrun/data_update_executor.go
@@ -136,10 +136,16 @@ func (exec *DataUpdateExecutor) backupData(
}
var originalLine *int32
switch instance.Engine {
- case storepb.Engine_MYSQL, storepb.Engine_TIDB:
+ case storepb.Engine_TIDB:
if _, err := driver.Execute(driverCtx, fmt.Sprintf("ALTER TABLE `%s`.`%s` COMMENT = 'issue %d'", backupDatabaseName, statement.TableName, issue.UID), db.ExecuteOptions{}); err != nil {
return err
}
+ case storepb.Engine_MYSQL:
+ if _, err := driver.Execute(driverCtx, fmt.Sprintf("ALTER TABLE `%s`.`%s` COMMENT = 'issue %d'", backupDatabaseName, statement.TableName, issue.UID), db.ExecuteOptions{}); err != nil {
+ return err
+ }
+ num := int32(statement.OriginalLine)
+ originalLine = &num
case storepb.Engine_MSSQL:
if _, err := backupDriver.Execute(driverCtx, fmt.Sprintf("EXEC sp_addextendedproperty 'MS_Description', 'issue %d', 'SCHEMA', 'dbo', 'TABLE', '%s'", issue.UID, statement.TableName), db.ExecuteOptions{}); err != nil {
return err
diff --git a/frontend/src/components/IssueV1/components/IssueCommentSection/IssueCommentView/IssueCommentAction.vue b/frontend/src/components/IssueV1/components/IssueCommentSection/IssueCommentView/IssueCommentAction.vue
index 70b3927bb9..3c93f128ba 100644
--- a/frontend/src/components/IssueV1/components/IssueCommentSection/IssueCommentView/IssueCommentAction.vue
+++ b/frontend/src/components/IssueV1/components/IssueCommentSection/IssueCommentView/IssueCommentAction.vue
@@ -13,6 +13,13 @@
<ActionSentence :issue="issue" :issue-comment="issueComment" />
+ <NButton
+ v-if="showRestoreButton(issueComment)"
+ @click.prevent="createRestoreIssue(issueComment)"
+ >
+ <span>{{ $t("activity.restore") }}</span>
+ </NButton>
+
<HumanizeTs
:ts="(issueComment.createTime?.getTime() ?? 0) / 1000"
class="ml-1"
@@ -53,17 +60,104 @@
</template>
<script lang="ts" setup>
+import dayjs from "dayjs";
+import { computed } from "vue";
+import { useRouter } from "vue-router";
+import { useIssueContext, databaseForTask } from "@/components/IssueV1/logic";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { IssueCommentType, type ComposedIssueComment } from "@/store";
+import { useSheetV1Store } from "@/store";
+import { useGenerateRestoreSQL } from "@/store/modules/restore";
import type { ComposedIssue } from "@/types";
import { SYSTEM_BOT_EMAIL } from "@/types";
-import { extractUserResourceName } from "@/utils";
+import { Engine } from "@/types/proto/v1/common";
+import { IssueComment_TaskPriorBackup } from "@/types/proto/v1/issue_service";
+import type { IssueComment } from "@/types/proto/v1/issue_service";
+import {
+ extractUserResourceName,
+ extractProjectResourceName,
+ getSheetStatement,
+ sheetNameOfTaskV1,
+ extractDatabaseResourceName,
+} from "@/utils";
import ActionCreator from "./ActionCreator.vue";
import ActionSentence from "./ActionSentence.vue";
-defineProps<{
+const props = defineProps<{
issue: ComposedIssue;
index: number;
issueComment: ComposedIssueComment;
similar: ComposedIssueComment[];
}>();
+
+const { selectedTask } = useIssueContext();
+const router = useRouter();
+
+const coreDatabaseInfo = computed(() => {
+ return databaseForTask(props.issue, selectedTask.value);
+});
+
+const showRestoreButton = (comment: ComposedIssueComment) => {
+ if (comment.type !== IssueCommentType.TASK_PRIOR_BACKUP) {
+ return false;
+ }
+ if (!selectedTask.value) {
+ return false;
+ }
+ if (coreDatabaseInfo.value.instanceEntity.engine !== Engine.MYSQL) {
+ return false;
+ }
+ return true;
+};
+
+const createRestoreIssue = async (comment: IssueComment) => {
+ const {
+ tables,
+ originalLine,
+ database: backupDatabase,
+ } = IssueComment_TaskPriorBackup.fromPartial(comment.taskPriorBackup || {});
+
+ const issueNameParts: string[] = [];
+ issueNameParts.push(
+ `Restore the sql at line ${originalLine} of (${props.issue.title})`
+ );
+ const datetime = dayjs().format("%MM-DD HH:mm");
+ const tz = "UTC" + dayjs().format("ZZ");
+ issueNameParts.push(`${datetime} ${tz}`);
+ const sheetName = sheetNameOfTaskV1(selectedTask.value);
+ const sheet = useSheetV1Store().getSheetByName(sheetName);
+ if (!sheet) {
+ console.error(`Sheet ${sheetName} not found`);
+ return;
+ }
+ const statement = getSheetStatement(sheet);
+ const { instance } = extractDatabaseResourceName(selectedTask.value.target);
+ const restoreSQL = await useGenerateRestoreSQL().generateRestoreSQL({
+ name: selectedTask.value.target,
+ statement: statement,
+ backupDataSource: `${instance}/databases/${backupDatabase.length > 0 ? backupDatabase : "bbdataarchive"}`,
+ backupTable: tables[0].table,
+ });
+ if (!restoreSQL) {
+ console.error("Failed to generate restore SQL");
+ return;
+ }
+
+ const query: Record<string, any> = {
+ template: "bb.issue.database.data.update",
+ name: issueNameParts.join(" "),
+ databaseList: selectedTask.value.target,
+ sql: restoreSQL,
+ };
+
+ router.push({
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(selectedTask.value.name),
+ issueSlug: "create",
+ },
+ query,
+ });
+};
+
</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 64d7d275ab..1c34637789 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -960,7 +960,8 @@
"task": "Task",
"stage": "Stage"
},
- "n-similar-activities": "({count} similar activity) | ({count} similar activities)"
+ "n-similar-activities": "({count} similar activity) | ({count} similar activities)",
+ "restore": "Restore"
},
"issue": {
"my-issues": "My Issues",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 19fd5eac3c..c34d947b1f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -960,7 +960,8 @@
"task": "Tarea",
"stage": "Etapa"
},
- "n-similar-activities": "({count} actividad similar) | ({count} actividades similares)"
+ "n-similar-activities": "({count} actividad similar) | ({count} actividades similares)",
+ "restore": "Restaurar"
},
"issue": {
"my-issues": "Mis Incidencias",
@@ -3539,4 +3540,4 @@
"self": "Última actualización"
}
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 40ec436d7c..de00045443 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -960,7 +960,8 @@
"task": "タスク",
"stage": "ステージ"
},
- "n-similar-activities": "({count} 件の同様のイベント)"
+ "n-similar-activities": "({count} 件の同様のイベント)",
+ "restore": "復元する"
},
"issue": {
"my-issues": "私の仕事の命令",
@@ -3539,4 +3540,4 @@
"self": "最後の更新"
}
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index ae9dd3873b..e1989e1056 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -960,7 +960,8 @@
"task": "任务",
"stage": "阶段"
},
- "n-similar-activities": "({count} 个相似的活动)"
+ "n-similar-activities": "({count} 个相似的活动)",
+ "restore": "恢复"
},
"issue": {
"my-issues": "我的工单",
diff --git a/frontend/src/store/modules/restore.ts b/frontend/src/store/modules/restore.ts
new file mode 100644
index 0000000000..b4b18d7b51
--- /dev/null
+++ b/frontend/src/store/modules/restore.ts
@@ -0,0 +1,22 @@
+import { useSQLStore } from "@/store";
+
+export type GenerateRestoreSQLParams = {
+ name: string; // instances/{instance}/databases/{database}
+ statement: string;
+ backupDataSource: string; // instances/{instance}/databases/{database} or instances/{instance}/databases/{database}/schemas/{schema} for pg
+ backupTable: string;
+}
+
+export const useGenerateRestoreSQL = () => {
+ const sqlStore = useSQLStore();
+
+ const generateRestoreSQL = async (params: GenerateRestoreSQLParams) => {
+ const { statement } = await sqlStore.generateRestoreSQL(params);
+
+ return statement;
+ };
+
+ return {
+ generateRestoreSQL,
+ };
+}
\ No newline at end of file
diff --git a/frontend/src/store/modules/v1/sql.ts b/frontend/src/store/modules/v1/sql.ts
index 3f36489aea..310eb33fe8 100644
--- a/frontend/src/store/modules/v1/sql.ts
+++ b/frontend/src/store/modules/v1/sql.ts
@@ -8,6 +8,7 @@ import type {
ExportRequest,
QueryRequest,
Advice,
+ GenerateRestoreSQLRequest,
} from "@/types/proto/v1/sql_service";
import { Advice_Status } from "@/types/proto/v1/sql_service";
import { extractGrpcErrorMessage } from "@/utils/grpcweb";
@@ -74,9 +75,17 @@ export const useSQLStore = defineStore("sql", () => {
ignoredCodes: [Status.PERMISSION_DENIED],
});
};
+
+ const generateRestoreSQL = async (params: GenerateRestoreSQLRequest) => {
+ return await sqlServiceClient.generateRestoreSQL(params, {
+ // Won't jump to 403 page when permission denied.
+ ignoredCodes: [Status.PERMISSION_DENIED],
+ });
+ }
return {
queryReadonly,
exportData,
+ generateRestoreSQL,
};
});