Skip to content

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

feat(editor): add transaction mode toggle for Redshift DDL/DML tasks (#16886)

h3n4l89ff072ea2e5
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
index a5e7eb956d..572a1b58b8 100644
--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
@@ -13,6 +13,10 @@
<InstanceRoleSelect />
<NDivider class="!my-2" />
</template>
+ <template v-if="shouldShowTransactionModeToggle">
+ <TransactionModeToggle />
+ <NDivider class="!my-2" />
+ </template>
<FormatOnSaveCheckbox v-model:value="formatOnSave" :language="language" />
</div>
</NPopover>
@@ -27,9 +31,13 @@ import { useCurrentProjectV1 } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { Task_Type } from "@/types/proto-es/v1/rollout_service_pb";
import { databaseForTask } from "@/utils";
-import { useInstanceV1EditorLanguage } from "@/utils";
+import {
+ useInstanceV1EditorLanguage,
+ instanceV1SupportsTransactionMode,
+} from "@/utils";
import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";
import InstanceRoleSelect from "./InstanceRoleSelect.vue";
+import TransactionModeToggle from "./TransactionModeToggle.vue";
const { formatOnSave, selectedTask } = useIssueContext();
const { project } = useCurrentProjectV1();
@@ -59,4 +67,23 @@ const shouldShowInstanceRoleSelect = computed(() => {
}
return true;
});
+
+const shouldShowTransactionModeToggle = computed(() => {
+ // Check if the engine supports transaction mode
+ if (
+ !instanceV1SupportsTransactionMode(database.value.instanceResource.engine)
+ ) {
+ return false;
+ }
+ // Only show for DDL/DML tasks
+ if (
+ ![
+ Task_Type.DATABASE_SCHEMA_UPDATE,
+ Task_Type.DATABASE_DATA_UPDATE,
+ ].includes(selectedTask.value.type)
+ ) {
+ return false;
+ }
+ return true;
+});
</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue
index 6e5062e176..e9db883c08 100644
--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue
@@ -27,17 +27,7 @@ import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb"
import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";
import { databaseForTask } from "@/utils";
import { useEditorContext } from "./context";
-
-/**
- * Regular expression to match and capture the role name in a specific comment format.
- * The expected format is:
- * /* === Bytebase Role Setter. DO NOT EDIT. === *\/
- * SET ROLE <role_name>;
- *
- * The regex captures the role name (\w+) following the "SET ROLE" statement.
- */
-const ROLE_SETTER_REGEX =
- /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE (\w+);/;
+import { parseStatement, updateRoleSetter } from "./directiveUtils";
interface LocalState {
selectedRole?: string;
@@ -83,10 +73,16 @@ const options = computed(() => {
watch(
() => selectedTask.value.name,
async () => {
- // Initialize selected role from statement using regex.
- const match = editorContext.statement.value.match(ROLE_SETTER_REGEX);
- if (match) {
- state.selectedRole = match[1];
+ // Initialize selected role from statement
+ const parsed = parseStatement(editorContext.statement.value);
+ if (parsed.roleSetterBlock) {
+ // Extract role name from the role setter block
+ const match = parsed.roleSetterBlock.match(/SET ROLE (\w+);/);
+ if (match) {
+ state.selectedRole = match[1];
+ } else {
+ state.selectedRole = undefined;
+ }
} else {
state.selectedRole = undefined;
}
@@ -106,16 +102,10 @@ watch(
);
const setRoleInTaskStatement = (roleName: string) => {
- const roleSetterTemplate = `/* === Bytebase Role Setter. DO NOT EDIT. === */\nSET ROLE ${roleName};`;
- let statement = "";
- if (ROLE_SETTER_REGEX.test(editorContext.statement.value)) {
- statement = editorContext.statement.value.replace(
- ROLE_SETTER_REGEX,
- roleSetterTemplate
- );
- } else {
- statement = roleSetterTemplate + "\n" + editorContext.statement.value;
- }
- editorContext.setStatement(statement);
+ const updatedStatement = updateRoleSetter(
+ editorContext.statement.value,
+ roleName
+ );
+ editorContext.setStatement(updatedStatement);
};
</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/TransactionModeToggle.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/TransactionModeToggle.vue
new file mode 100644
index 0000000000..dd59481154
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/TransactionModeToggle.vue
@@ -0,0 +1,112 @@
+<template>
+ <div class="flex flex-row justify-start items-center gap-2">
+ <span class="shrink-0 text-sm">{{
+ $t("issue.transaction-mode.label")
+ }}</span>
+ <NTooltip>
+ <template #trigger>
+ <NSwitch
+ v-model:value="isTransactionOn"
+ size="small"
+ :disabled="shouldDisableTransactionMode"
+ >
+ <template #checked>
+ {{ $t("issue.transaction-mode.on") }}
+ </template>
+ <template #unchecked>
+ {{ $t("issue.transaction-mode.off") }}
+ </template>
+ </NSwitch>
+ </template>
+ <template #default>
+ <div class="max-w-xs">
+ <div v-if="isTransactionOn">
+ {{ $t("issue.transaction-mode.on-tooltip") }}
+ </div>
+ <div v-else>
+ {{ $t("issue.transaction-mode.off-tooltip") }}
+ </div>
+ </div>
+ </template>
+ </NTooltip>
+ </div>
+</template>
+
+<script setup lang="tsx">
+import { NSwitch, NTooltip } from "naive-ui";
+import { computed, ref, watch } from "vue";
+import { useIssueContext } from "@/components/IssueV1/logic";
+import { useCurrentProjectV1 } from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { Task_Type } from "@/types/proto-es/v1/rollout_service_pb";
+import { databaseForTask } from "@/utils";
+import { useEditorContext } from "./context";
+import { parseStatement, updateTransactionMode } from "./directiveUtils";
+
+const editorContext = useEditorContext();
+const { selectedTask } = useIssueContext();
+const { project } = useCurrentProjectV1();
+
+const database = computed(() => {
+ return databaseForTask(project.value, selectedTask.value);
+});
+
+const engine = computed(() => database.value.instanceResource.engine);
+
+// Some engines or task types might not support disabling transactions
+const shouldDisableTransactionMode = computed(() => {
+ // For DML, always use transactions
+ if (selectedTask.value.type === Task_Type.DATABASE_DATA_UPDATE) {
+ return true;
+ }
+ return false;
+});
+
+// Default transaction mode based on engine and task type
+const getDefaultTransactionMode = () => {
+ // For Redshift DDL, default to off
+ if (
+ engine.value === Engine.REDSHIFT &&
+ selectedTask.value.type === Task_Type.DATABASE_SCHEMA_UPDATE
+ ) {
+ return false;
+ }
+ // For all other cases, default to on
+ return true;
+};
+
+const isTransactionOn = ref(getDefaultTransactionMode());
+
+// Watch for task changes to reset defaults
+watch(
+ () => selectedTask.value.name,
+ () => {
+ // Parse existing statement for transaction mode
+ const parsed = parseStatement(editorContext.statement.value);
+ if (parsed.transactionMode !== undefined) {
+ isTransactionOn.value = parsed.transactionMode === "on";
+ } else {
+ // Use default if no directive found
+ isTransactionOn.value = getDefaultTransactionMode();
+ }
+ },
+ { immediate: true }
+);
+
+// Update statement when transaction mode changes
+watch(
+ () => isTransactionOn.value,
+ () => {
+ updateStatementWithTransactionMode();
+ }
+);
+
+const updateStatementWithTransactionMode = () => {
+ const mode = isTransactionOn.value ? "on" : "off";
+ const updatedStatement = updateTransactionMode(
+ editorContext.statement.value,
+ mode
+ );
+ editorContext.setStatement(updatedStatement);
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts
new file mode 100644
index 0000000000..0f848f4ce2
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts
@@ -0,0 +1,114 @@
+/**
+ * Utilities for managing SQL directives and special statements in the editor.
+ *
+ * Directives are special comments that must appear at specific positions:
+ * - Transaction mode directive: Must be on line 1
+ *
+ * Special statements are SQL statements that get special handling:
+ * - SET ROLE statement: Can appear anywhere but is handled specially by backend
+ */
+
+// Transaction mode directive pattern
+const TXN_MODE_REGEX = /^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/i;
+
+// PostgreSQL role setter pattern
+const ROLE_SETTER_REGEX =
+ /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE (\w+);/;
+
+export interface ParsedStatement {
+ // Line 1 directive (currently only transaction mode)
+ transactionMode?: "on" | "off";
+ // Role setter block if present
+ roleSetterBlock?: string;
+ // The main SQL content (everything except directives and role setter)
+ mainContent: string;
+}
+
+/**
+ * Parses a SQL statement into its components.
+ */
+export function parseStatement(statement: string): ParsedStatement {
+ const lines = statement.split("\n");
+ const result: ParsedStatement = {
+ mainContent: "",
+ };
+
+ let currentIndex = 0;
+
+ // Check line 1 for transaction mode directive
+ if (lines.length > 0 && TXN_MODE_REGEX.test(lines[0])) {
+ const match = lines[0].match(TXN_MODE_REGEX);
+ if (match) {
+ result.transactionMode = match[1].toLowerCase() as "on" | "off";
+ currentIndex = 1;
+ }
+ }
+
+ // Check for role setter block (can be anywhere in the remaining content)
+ const remainingContent = lines.slice(currentIndex).join("\n");
+ const roleSetterMatch = remainingContent.match(ROLE_SETTER_REGEX);
+
+ if (roleSetterMatch) {
+ result.roleSetterBlock = roleSetterMatch[0];
+ // Remove the role setter block from the content
+ result.mainContent = remainingContent.replace(ROLE_SETTER_REGEX, "").trim();
+ } else {
+ result.mainContent = remainingContent.trim();
+ }
+
+ return result;
+}
+
+/**
+ * Rebuilds a SQL statement from its components, ensuring proper ordering.
+ */
+export function buildStatement(components: ParsedStatement): string {
+ const parts: string[] = [];
+
+ // Line 1: Transaction mode directive (if present)
+ if (components.transactionMode !== undefined) {
+ parts.push(`-- txn-mode = ${components.transactionMode}`);
+ }
+
+ // Role setter block (if present) - place it before main content
+ if (components.roleSetterBlock) {
+ parts.push(components.roleSetterBlock);
+ }
+
+ // Main SQL content
+ if (components.mainContent) {
+ parts.push(components.mainContent);
+ }
+
+ return parts.filter((part) => part.length > 0).join("\n");
+}
+
+/**
+ * Updates the transaction mode in a statement while preserving other components.
+ */
+export function updateTransactionMode(
+ statement: string,
+ mode: "on" | "off"
+): string {
+ const parsed = parseStatement(statement);
+ parsed.transactionMode = mode;
+ return buildStatement(parsed);
+}
+
+/**
+ * Updates the role setter in a statement while preserving other components.
+ */
+export function updateRoleSetter(
+ statement: string,
+ roleName: string | null
+): string {
+ const parsed = parseStatement(statement);
+
+ if (roleName) {
+ parsed.roleSetterBlock = `/* === Bytebase Role Setter. DO NOT EDIT. === */\nSET ROLE ${roleName};`;
+ } else {
+ parsed.roleSetterBlock = undefined;
+ }
+
+ return buildStatement(parsed);
+}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index bbc9b7b254..36f44d17bf 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -927,6 +927,13 @@
"statement-from-sheet-warning": "Due to the SQL being oversized, it has been truncated to display, and editing is disabled. You can upload a new SQL file to overwrite it.",
"overwrite-current-statement": "Overwrite current SQL statement",
"upload-sql-file-max-size-exceeded": "Max file size ({size}) exceeded.",
+ "transaction-mode": {
+ "label": "Transaction Mode",
+ "on": "ON",
+ "off": "OFF",
+ "on-tooltip": "Wraps all statements in a single transaction (BEGIN/COMMIT).",
+ "off-tooltip": "Executes statements individually in auto-commit mode. Statements are committed immediately and cannot be rolled back if a later statement fails."
+ },
"waiting-earliest-allowed-time": "Will run after {time}",
"batch-transition": {
"not-allowed-tips": "Some of selected issues cannot be {operation}",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index fc8dab7d6f..3b34399584 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -927,6 +927,13 @@
"statement-from-sheet-warning": "Debido a que el SQL es demasiado grande, se ha truncado para mostrarlo y la edición está deshabilitada. Puede cargar un nuevo archivo SQL para sobrescribirlo.",
"overwrite-current-statement": "Sobrescribir la declaración SQL actual",
"upload-sql-file-max-size-exceeded": "Se ha excedido el tamaño máximo del archivo ({size}).",
+ "transaction-mode": {
+ "label": "Modo de transacción",
+ "on": "Activado",
+ "off": "Desactivado",
+ "on-tooltip": "Envuelve todas las declaraciones en una sola transacción (BEGIN/COMMIT).",
+ "off-tooltip": "Ejecuta declaraciones individualmente en modo de confirmación automática. Las declaraciones se confirman inmediatamente y no se pueden revertir si una declaración posterior falla."
+ },
"waiting-earliest-allowed-time": "Se ejecutará después de {time}",
"batch-transition": {
"not-allowed-tips": "Algunos de las incidencias seleccionadas no se pueden {operation}",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 939266ec29..04de4983b3 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -927,6 +927,13 @@
"statement-from-sheet-warning": "SQL が大きすぎるため、表示時に切り捨てられ、編集が無効になっています。新しい SQL ファイルをアップロードして上書きすることができます。",
"overwrite-current-statement": "現在の SQL ステートメントを上書きする",
"upload-sql-file-max-size-exceeded": "アップロード ファイルのサイズは {size} を超えることはできません。",
+ "transaction-mode": {
+ "label": "トランザクションモード",
+ "on": "オン",
+ "off": "オフ",
+ "on-tooltip": "すべてのステートメントを単一のトランザクション(BEGIN/COMMIT)でラップします。",
+ "off-tooltip": "自動コミットモードで個別にステートメントを実行します。ステートメントは即座にコミットされ、後続のステートメントが失敗してもロールバックできません。"
+ },
"waiting-earliest-allowed-time": "{time}の後に実行されます",
"batch-transition": {
"not-allowed-tips": "選択したイシューの一部を {operation} にすることはできません",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 2d8f9f14fa..9e4227601b 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -927,6 +927,13 @@
"statement-from-sheet-warning": "Do kích thước SQL vượt quá, nó đã bị cắt bớt để hiển thị và chỉnh sửa bị vô hiệu hóa. Bạn có thể tải lên một tệp SQL mới để ghi đè nó.",
"overwrite-current-statement": "Ghi đè câu lệnh SQL hiện tại",
"upload-sql-file-max-size-exceeded": "Vượt quá kích thước tệp tối đa ({size}).",
+ "transaction-mode": {
+ "label": "Chế độ giao dịch",
+ "on": "Bật",
+ "off": "Tắt",
+ "on-tooltip": "Gói tất cả các câu lệnh trong một giao dịch duy nhất (BEGIN/COMMIT).",
+ "off-tooltip": "Thực thi các câu lệnh riêng lẻ trong chế độ tự động commit. Các câu lệnh được commit ngay lập tức và không thể khôi phục nếu câu lệnh sau đó thất bại."
+ },
"waiting-earliest-allowed-time": "Sẽ chạy sau {time}",
"batch-transition": {
"not-allowed-tips": "Một số vấn đề đã chọn không thể {operation}",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 6e1d9282ae..76e7c863d4 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -927,6 +927,13 @@
"statement-from-sheet-warning": "由于 SQL 文件过大,因此被截断以便显示,并且编辑功能已禁用。你可以上传新的 SQL 文件以将其覆盖。",
"overwrite-current-statement": "覆盖当前的 SQL 语句",
"upload-sql-file-max-size-exceeded": "上传文件大小不能超过 {size}。",
+ "transaction-mode": {
+ "label": "事务模式",
+ "on": "开启",
+ "off": "关闭",
+ "on-tooltip": "将所有语句包装在单个事务中(BEGIN/COMMIT)。",
+ "off-tooltip": "以自动提交模式单独执行语句。语句立即提交,如果后续语句失败则无法回滚。"
+ },
"waiting-earliest-allowed-time": "将于 {time} 之后执行",
"batch-transition": {
"not-allowed-tips": "部分选中的工单无法被{operation}",
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 074b284a39..3dfc9ce81b 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -473,3 +473,10 @@ export const supportGetStringSchema = (engine: Engine) => {
Engine.MSSQL,
].includes(engine);
};
+
+// instanceV1SupportsTransactionMode returns true if the engine supports configurable transaction mode.
+export const instanceV1SupportsTransactionMode = (engine: Engine): boolean => {
+ // For MVP, only enable for Redshift
+ // TODO: Enable for other engines after testing
+ return [Engine.REDSHIFT].includes(engine);
+};