Skip to content

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

chore: add transaction isolation level to MySQL (#17428)

Vincent Huang10b39e528e69
diff --git a/backend/common/engine.go b/backend/common/engine.go
index abe1775795..d0caefe36e 100644
--- a/backend/common/engine.go
+++ b/backend/common/engine.go
@@ -487,6 +487,28 @@ const (
TransactionModeUnspecified TransactionMode = ""
)
+// IsolationLevel represents the transaction isolation level.
+type IsolationLevel string
+
+const (
+ // IsolationLevelDefault uses the database's default isolation level.
+ IsolationLevelDefault IsolationLevel = ""
+ // IsolationLevelReadUncommitted allows dirty reads.
+ IsolationLevelReadUncommitted IsolationLevel = "READ UNCOMMITTED"
+ // IsolationLevelReadCommitted prevents dirty reads.
+ IsolationLevelReadCommitted IsolationLevel = "READ COMMITTED"
+ // IsolationLevelRepeatableRead prevents dirty reads and non-repeatable reads.
+ IsolationLevelRepeatableRead IsolationLevel = "REPEATABLE READ"
+ // IsolationLevelSerializable provides the highest isolation level.
+ IsolationLevelSerializable IsolationLevel = "SERIALIZABLE"
+)
+
+// TransactionConfig represents the complete transaction configuration.
+type TransactionConfig struct {
+ Mode TransactionMode
+ Isolation IsolationLevel
+}
+
// GetDefaultTransactionMode returns the default transaction mode.
// All engines default to "on" (transactional) for safety and backward compatibility.
// Users can explicitly set "-- txn-mode = off" when needed for engines with limited transactional DDL support.
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index bb397385cd..f9c6327912 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -288,13 +288,13 @@ func parseVersion(version string) (string, string, error) {
// Execute executes a SQL statement.
func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
- // Parse transaction mode from the script
- transactionMode, cleanedStatement := base.ParseTransactionMode(statement)
+ // Parse transaction configuration from the script
+ transactionConfig, cleanedStatement := base.ParseTransactionConfig(statement)
statement = cleanedStatement
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionConfig.Mode == common.TransactionModeUnspecified {
+ transactionConfig.Mode = common.GetDefaultTransactionMode()
}
statement, err := mysqlparser.DealWithDelimiter(statement)
@@ -342,15 +342,28 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
originalIndex = []int32{0}
}
+ // Validate isolation level for MySQL if specified
+ if transactionConfig.Isolation != common.IsolationLevelDefault {
+ validLevels := map[common.IsolationLevel]bool{
+ common.IsolationLevelReadUncommitted: true,
+ common.IsolationLevelReadCommitted: true,
+ common.IsolationLevelRepeatableRead: true,
+ common.IsolationLevelSerializable: true,
+ }
+ if !validLevels[transactionConfig.Isolation] {
+ return 0, errors.Errorf("invalid isolation level for MySQL: %s. Supported levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE", transactionConfig.Isolation)
+ }
+ }
+
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionConfig.Mode == common.TransactionModeOff {
return d.executeInAutoCommitMode(ctx, conn, commands, originalIndex, opts, connectionID)
}
- return d.executeInTransactionMode(ctx, conn, commands, originalIndex, opts, connectionID)
+ return d.executeInTransactionMode(ctx, conn, commands, originalIndex, opts, connectionID, transactionConfig.Isolation)
}
// executeInTransactionMode executes statements within a single transaction
-func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions, connectionID string) (int64, error) {
+func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions, connectionID string, isolationLevel common.IsolationLevel) (int64, error) {
var totalRowsAffected int64
if err := conn.Raw(func(driverConn any) error {
@@ -358,7 +371,14 @@ func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, c
exer := driverConn.(driver.ExecerContext)
//nolint
txer := driverConn.(driver.ConnBeginTx)
- tx, err := txer.BeginTx(ctx, driver.TxOptions{})
+
+ // Set isolation level if specified
+ txOptions := driver.TxOptions{}
+ if isolationLevel != common.IsolationLevelDefault {
+ txOptions.Isolation = driver.IsolationLevel(base.ConvertToSQLIsolation(isolationLevel))
+ }
+
+ tx, err := txer.BeginTx(ctx, txOptions)
if err != nil {
opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())
return err
diff --git a/backend/plugin/parser/base/transaction_mode.go b/backend/plugin/parser/base/transaction_mode.go
index 3beefcc419..5373d51910 100644
--- a/backend/plugin/parser/base/transaction_mode.go
+++ b/backend/plugin/parser/base/transaction_mode.go
@@ -1,33 +1,115 @@
package base
import (
+ "database/sql"
"regexp"
"strings"
"github.com/bytebase/bytebase/backend/common"
)
-// txnModeDirectiveRegex matches the transaction mode directive at the beginning of a SQL script.
-// Format: -- txn-mode = on|off
-var txnModeDirectiveRegex = regexp.MustCompile(`(?i)^\s*--\s*txn-mode\s*=\s*(on|off)\s*$`)
+// Directive regex patterns
+var (
+ // txnModeDirectiveRegex matches the transaction mode directive.
+ // Format: -- txn-mode = on|off
+ txnModeDirectiveRegex = regexp.MustCompile(`(?i)^\s*--\s*txn-mode\s*=\s*(on|off)\s*$`)
+
+ // txnIsolationDirectiveRegex matches the isolation level directive.
+ // Format: -- txn-isolation = READ UNCOMMITTED|READ COMMITTED|REPEATABLE READ|SERIALIZABLE
+ txnIsolationDirectiveRegex = regexp.MustCompile(`(?i)^\s*--\s*txn-isolation\s*=\s*(READ\s+UNCOMMITTED|READ\s+COMMITTED|REPEATABLE\s+READ|SERIALIZABLE)\s*$`)
+)
// ParseTransactionMode extracts the transaction mode directive from the SQL script.
// It checks the first line of the script for the -- txn-mode = on|off directive.
// Returns the transaction mode and the SQL script without the directive.
+// Deprecated: Use ParseTransactionConfig instead for full transaction configuration support.
func ParseTransactionMode(script string) (common.TransactionMode, string) {
+ config, cleanScript := ParseTransactionConfig(script)
+ return config.Mode, cleanScript
+}
+
+// ParseTransactionConfig extracts both transaction mode and isolation level directives from the SQL script.
+// It scans comment lines at the top of the file for directives:
+// - -- txn-mode = on|off
+// - -- txn-isolation = READ UNCOMMITTED|READ COMMITTED|REPEATABLE READ|SERIALIZABLE
+// Directives can appear in any order within the top comment lines.
+// Scanning stops at the first non-comment, non-empty line.
+// Returns the transaction configuration and the SQL script without the directives.
+func ParseTransactionConfig(script string) (common.TransactionConfig, string) {
+ config := common.TransactionConfig{
+ Mode: common.TransactionModeUnspecified,
+ Isolation: common.IsolationLevelDefault,
+ }
+
lines := strings.Split(script, "\n")
if len(lines) == 0 {
- return common.TransactionModeUnspecified, script
+ return config, script
+ }
+
+ directiveLines := make(map[int]bool)
+
+ // Scan lines from the top, stopping at first non-comment/non-empty line
+ for i, line := range lines {
+ trimmed := strings.TrimSpace(line)
+
+ // Skip empty lines
+ if trimmed == "" {
+ continue
+ }
+
+ // If it's not a comment, stop scanning for directives
+ if !strings.HasPrefix(trimmed, "--") {
+ break
+ }
+
+ // Check for transaction mode directive
+ if matches := txnModeDirectiveRegex.FindStringSubmatch(line); len(matches) == 2 {
+ mode := strings.ToLower(matches[1])
+ config.Mode = common.TransactionMode(mode)
+ directiveLines[i] = true
+ continue
+ }
+
+ // Check for isolation level directive
+ if matches := txnIsolationDirectiveRegex.FindStringSubmatch(line); len(matches) == 2 {
+ isolation := strings.ToUpper(matches[1])
+ // Normalize the spacing
+ isolation = strings.ReplaceAll(isolation, " ", " ")
+ // Note: We set the value as-is here. Invalid values will be caught
+ // by the specific database driver during execution, allowing each
+ // database to validate according to its supported levels.
+ config.Isolation = common.IsolationLevel(isolation)
+ directiveLines[i] = true
+ continue
+ }
}
- // Check the first line for the transaction mode directive
- matches := txnModeDirectiveRegex.FindStringSubmatch(lines[0])
- if len(matches) == 2 {
- mode := strings.ToLower(matches[1])
- // Remove the directive line from the script
- remainingScript := strings.Join(lines[1:], "\n")
- return common.TransactionMode(mode), strings.TrimSpace(remainingScript)
+ // Remove directive lines from the script
+ if len(directiveLines) > 0 {
+ var remainingLines []string
+ for i, line := range lines {
+ if !directiveLines[i] {
+ remainingLines = append(remainingLines, line)
+ }
+ }
+ return config, strings.TrimSpace(strings.Join(remainingLines, "\n"))
}
- return common.TransactionModeUnspecified, script
+ return config, script
+}
+
+// ConvertToSQLIsolation converts our IsolationLevel to database/sql.IsolationLevel
+func ConvertToSQLIsolation(level common.IsolationLevel) sql.IsolationLevel {
+ switch level {
+ case common.IsolationLevelReadUncommitted:
+ return sql.LevelReadUncommitted
+ case common.IsolationLevelReadCommitted:
+ return sql.LevelReadCommitted
+ case common.IsolationLevelRepeatableRead:
+ return sql.LevelRepeatableRead
+ case common.IsolationLevelSerializable:
+ return sql.LevelSerializable
+ default:
+ return sql.LevelDefault
+ }
}
diff --git a/frontend/src/components/Plan/components/Configuration/Configuration.vue b/frontend/src/components/Plan/components/Configuration/Configuration.vue
index 8207e7543d..07cc0e0ae0 100644
--- a/frontend/src/components/Plan/components/Configuration/Configuration.vue
+++ b/frontend/src/components/Plan/components/Configuration/Configuration.vue
@@ -4,10 +4,11 @@
{{ $t("plan.options.self") }}
</p>
<div class="w-auto flex flex-col gap-2">
- <InstanceRoleSection v-if="shouldShowInstanceRoleSection" />
<TransactionModeSection v-if="shouldShowTransactionModeSection" />
+ <IsolationLevelSection v-if="shouldShowIsolationLevelSection" />
<GhostSection v-if="shouldShowGhostSection" />
<PreBackupSection v-if="shouldShowPreBackupSection" />
+ <InstanceRoleSection v-if="shouldShowInstanceRoleSection" />
</div>
</div>
</template>
@@ -21,6 +22,8 @@ import GhostSection from "./GhostSection";
import { provideGhostSettingContext } from "./GhostSection/context";
import InstanceRoleSection from "./InstanceRoleSection";
import { provideInstanceRoleSettingContext } from "./InstanceRoleSection/context";
+import IsolationLevelSection from "./IsolationLevelSection";
+import { provideIsolationLevelSettingContext } from "./IsolationLevelSection/context";
import PreBackupSection from "./PreBackupSection";
import { providePreBackupSettingContext } from "./PreBackupSection/context";
import TransactionModeSection from "./TransactionModeSection";
@@ -56,6 +59,19 @@ const {
readonly,
});
+const {
+ shouldShow: shouldShowIsolationLevelSection,
+ events: isolationLevelEvents,
+} = provideIsolationLevelSettingContext({
+ project,
+ plan,
+ selectedSpec,
+ isCreating,
+ issue,
+ rollout,
+ readonly,
+});
+
const { shouldShow: shouldShowGhostSection, events: ghostEvents } =
provideGhostSettingContext({
project,
@@ -81,6 +97,7 @@ const { shouldShow: shouldShowPreBackupSection, events: preBackupEvents } =
const shouldShow = computed(() => {
return (
shouldShowTransactionModeSection.value ||
+ shouldShowIsolationLevelSection.value ||
shouldShowInstanceRoleSection.value ||
shouldShowGhostSection.value ||
shouldShowPreBackupSection.value
@@ -99,6 +116,12 @@ instanceRoleEvents.on("update", () => {
});
});
+isolationLevelEvents.on("update", () => {
+ events.emit("status-changed", {
+ eager: true,
+ });
+});
+
preBackupEvents.on("update", () => {
events.emit("status-changed", {
eager: true,
diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vue b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vue
new file mode 100644
index 0000000000..f71334b900
--- /dev/null
+++ b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vue
@@ -0,0 +1,24 @@
+<template>
+ <div
+ v-if="shouldShow"
+ class="w-full flex flex-row justify-start items-center gap-4"
+ >
+ <label class="w-28 shrink-0 text-sm text-control-light">
+ {{ $t("plan.isolation-level.self") }}
+ </label>
+ <IsolationLevelSelect />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useTransactionModeSettingContext } from "../TransactionModeSection/context";
+import IsolationLevelSelect from "./IsolationLevelSelect.vue";
+
+// Only show isolation level when transaction mode is ON
+const { transactionMode } = useTransactionModeSettingContext();
+
+const shouldShow = computed(() => {
+ return transactionMode.value === "on";
+});
+</script>
diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vue b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vue
new file mode 100644
index 0000000000..39274ab060
--- /dev/null
+++ b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vue
@@ -0,0 +1,150 @@
+<template>
+ <NSelect
+ v-model:value="selectedIsolation"
+ class="!w-60"
+ consistent-menu-width
+ size="small"
+ :options="options"
+ :placeholder="$t('plan.select-isolation-level')"
+ :clearable="true"
+ :disabled="!allowChange"
+ />
+</template>
+
+<script setup lang="tsx">
+import { NSelect, type SelectOption } from "naive-ui";
+import { computed, nextTick, ref, watch } from "vue";
+import {
+ usePlanContext,
+ updateSpecSheetWithStatement,
+} from "@/components/Plan/logic";
+import { setSheetStatement } from "@/utils";
+import { useSelectedSpec } from "../../SpecDetailView/context";
+import {
+ parseStatement,
+ updateIsolationLevel,
+ type IsolationLevel,
+} from "../../StatementSection/directiveUtils";
+import { useSpecSheet } from "../../StatementSection/useSpecSheet";
+import { useTransactionModeSettingContext } from "../TransactionModeSection/context";
+import { useIsolationLevelSettingContext } from "./context";
+
+const {
+ allowChange,
+ isolationLevel: contextIsolationLevel,
+ events,
+} = useIsolationLevelSettingContext();
+
+// Also need transaction mode to know if we should show this
+const { transactionMode } = useTransactionModeSettingContext();
+
+const selectedSpec = useSelectedSpec();
+const { sheetStatement, sheet, sheetReady } = useSpecSheet(selectedSpec);
+const { plan, isCreating } = usePlanContext();
+
+// Flag to prevent circular updates
+const isUpdatingFromUI = ref(false);
+
+const selectedIsolation = computed({
+ get: () => contextIsolationLevel.value,
+ set: (value: IsolationLevel | null) => {
+ isUpdatingFromUI.value = true;
+ contextIsolationLevel.value = value || undefined;
+ setIsolationInStatement(value || undefined);
+ // Reset the flag after Vue's next tick to allow statement updates to propagate
+ nextTick(() => {
+ isUpdatingFromUI.value = false;
+ });
+ },
+});
+
+const options = computed(() => {
+ const opts: SelectOption[] = [
+ {
+ value: "READ_UNCOMMITTED",
+ label: "Read Uncommitted",
+ },
+ {
+ value: "READ_COMMITTED",
+ label: "Read Committed",
+ },
+ {
+ value: "REPEATABLE_READ",
+ label: "Repeatable Read",
+ },
+ {
+ value: "SERIALIZABLE",
+ label: "Serializable",
+ },
+ ];
+ return opts;
+});
+
+// Initialize isolation level from statement
+const initializeFromStatement = () => {
+ if (!sheetReady.value || !sheetStatement.value) {
+ // If sheet is not ready or statement is empty, reset to undefined
+ contextIsolationLevel.value = undefined;
+ return;
+ }
+
+ const parsed = parseStatement(sheetStatement.value);
+ contextIsolationLevel.value = parsed.isolationLevel;
+};
+
+watch(
+ () => selectedSpec.value?.id,
+ () => {
+ initializeFromStatement();
+ },
+ {
+ immediate: true,
+ }
+);
+
+// Watch for sheet statement changes to update isolation level
+// Only update when statement changes externally, not when we change it ourselves
+watch(
+ [sheetStatement, sheetReady],
+ () => {
+ if (!isUpdatingFromUI.value) {
+ initializeFromStatement();
+ }
+ },
+ { immediate: true }
+);
+
+// Clear isolation level if transaction mode is turned off
+watch(
+ () => transactionMode.value,
+ (mode) => {
+ if (mode === "off" && contextIsolationLevel.value) {
+ contextIsolationLevel.value = undefined;
+ setIsolationInStatement(undefined);
+ }
+ }
+);
+
+const setIsolationInStatement = async (
+ isolationLevel: IsolationLevel | undefined
+) => {
+ const updatedStatement = updateIsolationLevel(
+ sheetStatement.value,
+ isolationLevel
+ );
+
+ if (isCreating.value) {
+ // When creating a plan, update the local sheet directly.
+ if (!sheet.value) return;
+ setSheetStatement(sheet.value, updatedStatement);
+ } else {
+ // For created plans, create new sheet and update plan/spec
+ await updateSpecSheetWithStatement(
+ plan.value,
+ selectedSpec.value,
+ updatedStatement
+ );
+ }
+ events.emit("update");
+};
+</script>
diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.ts b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.ts
new file mode 100644
index 0000000000..4d1495410b
--- /dev/null
+++ b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.ts
@@ -0,0 +1,147 @@
+import Emittery from "emittery";
+import type { InjectionKey, Ref } from "vue";
+import { computed, inject, provide, ref } from "vue";
+import { targetsForSpec } from "@/components/Plan/logic";
+import { useDatabaseV1Store } from "@/store";
+import { isValidDatabaseName } from "@/types";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
+import type {
+ Plan,
+ Plan_Spec,
+ Plan_ChangeDatabaseConfig,
+} from "@/types/proto-es/v1/plan_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import type { Task, Rollout } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status, Task_Type } from "@/types/proto-es/v1/rollout_service_pb";
+import { flattenTaskV1List } from "@/utils";
+import type { IsolationLevel } from "../../StatementSection/directiveUtils";
+
+export const KEY = Symbol(
+ "bb.plan.setting.isolation-level"
+) as InjectionKey<IsolationLevelSettingContext>;
+
+export type IsolationLevelSettingContext = {
+ allowChange: Ref<boolean>;
+ isolationLevel: Ref<IsolationLevel | undefined>;
+ databases: Ref<any[]>;
+ shouldShow: Ref<boolean>;
+ events: Emittery<{
+ update: never;
+ }>;
+};
+
+export const useIsolationLevelSettingContext = () => {
+ return inject(KEY)!;
+};
+
+export const provideIsolationLevelSettingContext = (refs: {
+ isCreating: Ref<boolean>;
+ project: Ref<Project>;
+ plan: Ref<Plan>;
+ selectedSpec: Ref<Plan_Spec | undefined>;
+ selectedTask?: Ref<Task | undefined>;
+ issue?: Ref<Issue | undefined>;
+ rollout?: Ref<Rollout | undefined>;
+ readonly?: Ref<boolean>;
+}) => {
+ const databaseStore = useDatabaseV1Store();
+
+ const { isCreating, selectedSpec, selectedTask, issue, rollout, readonly } =
+ refs;
+
+ const events = new Emittery<{
+ update: never;
+ }>();
+
+ const isolationLevel = ref<IsolationLevel | undefined>(undefined);
+
+ const databases = computed(() => {
+ const targets = selectedSpec.value
+ ? targetsForSpec(selectedSpec.value)
+ : [];
+ return targets
+ .map((target) => databaseStore.getDatabaseByName(target))
+ .filter((db) => isValidDatabaseName(db.name));
+ });
+
+ const shouldShow = computed(() => {
+ if (!selectedSpec.value) return false;
+
+ // Only show for MySQL/MariaDB/TiDB for now
+ const supportedEngines = [Engine.MYSQL, Engine.MARIADB, Engine.TIDB];
+ const allDatabasesSupported = databases.value.every((db) =>
+ supportedEngines.includes(db.instanceResource.engine)
+ );
+ if (!allDatabasesSupported) return false;
+
+ // Check if this is a DDL or DML change
+ if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {
+ return false;
+ }
+
+ // Get the task type from spec or selected task
+ let taskType: Task_Type | undefined;
+ if (selectedTask?.value) {
+ taskType = selectedTask.value.type;
+ } else if (rollout?.value) {
+ const tasks = flattenTaskV1List(rollout.value);
+ const task = tasks.find((t) => t.specId === selectedSpec.value?.id);
+ taskType = task?.type;
+ } else {
+ // For creating mode, we can infer from the change type
+ const config = selectedSpec.value.config
+ .value as Plan_ChangeDatabaseConfig;
+ // Check if it's a schema or data update based on the config
+ taskType = config.sheet
+ ? Task_Type.DATABASE_SCHEMA_UPDATE
+ : Task_Type.DATABASE_DATA_UPDATE;
+ }
+
+ return (
+ !!taskType &&
+ [
+ Task_Type.DATABASE_SCHEMA_UPDATE,
+ Task_Type.DATABASE_DATA_UPDATE,
+ ].includes(taskType)
+ );
+ });
+
+ const allowChange = computed(() => {
+ if (readonly?.value) return false;
+
+ if (isCreating.value) return true;
+
+ if (issue?.value?.status !== IssueStatus.OPEN) return false;
+
+ if (selectedTask?.value) {
+ return [Task_Status.NOT_STARTED, Task_Status.PENDING].includes(
+ selectedTask.value.status
+ );
+ }
+
+ if (rollout?.value) {
+ const tasks = flattenTaskV1List(rollout.value);
+ const task = tasks.find((t) => t.specId === selectedSpec.value?.id);
+ if (!task) return false;
+ return [Task_Status.NOT_STARTED, Task_Status.PENDING].includes(
+ task.status
+ );
+ }
+
+ return false;
+ });
+
+ const context: IsolationLevelSettingContext = {
+ allowChange,
+ isolationLevel,
+ databases,
+ shouldShow,
+ events,
+ };
+
+ provide(KEY, context);
+
+ return context;
+};
diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.ts b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.ts
new file mode 100644
index 0000000000..54ba6e7612
--- /dev/null
+++ b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./IsolationLevelSection.vue";
+export * from "./context";
diff --git a/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts b/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts
index d7245a0b7a..6f7eb4ea07 100644
--- a/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts
+++ b/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts
@@ -3,6 +3,7 @@
*
* Directives are special comments that must appear at specific positions:
* - Transaction mode directive: Must be on line 1
+ * - Isolation level directive: Must be on line 2 (if txn-mode is on line 1)
*
* Special statements are SQL statements that get special handling:
* - SET ROLE statement: Can appear anywhere but is handled specially by backend
@@ -11,14 +12,26 @@
// Transaction mode directive pattern
const TXN_MODE_REGEX = /^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/i;
+// Isolation level directive pattern
+const TXN_ISOLATION_REGEX =
+ /^\s*--\s*txn-isolation\s*=\s*(READ\s+UNCOMMITTED|READ\s+COMMITTED|REPEATABLE\s+READ|SERIALIZABLE)\s*$/i;
+
// PostgreSQL role setter pattern
// Matches PostgreSQL identifier rules: starts with letter/underscore, up to 63 chars
const ROLE_SETTER_REGEX =
/\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/;
+export type IsolationLevel =
+ | "READ_UNCOMMITTED"
+ | "READ_COMMITTED"
+ | "REPEATABLE_READ"
+ | "SERIALIZABLE";
+
export interface ParsedStatement {
// Line 1 directive (currently only transaction mode)
transactionMode?: "on" | "off";
+ // Line 2 directive (isolation level, only valid when txn-mode is on)
+ isolationLevel?: IsolationLevel;
// Role setter block if present
roleSetterBlock?: string;
// The main SQL content (everything except directives and role setter)
@@ -34,19 +47,47 @@ export function parseStatement(statement: string): ParsedStatement {
mainContent: "",
};
- let currentIndex = 0;
+ const directiveLines = new Set<number>();
+
+ // Scan lines from the top, stopping at first non-comment/non-empty line
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const trimmed = line.trim();
+
+ // Skip empty lines
+ if (trimmed === "") {
+ continue;
+ }
+
+ // If it's not a comment, stop scanning for directives
+ if (!trimmed.startsWith("--")) {
+ break;
+ }
- // 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 transaction mode directive
+ const txnModeMatch = line.match(TXN_MODE_REGEX);
+ if (txnModeMatch) {
+ result.transactionMode = txnModeMatch[1].toLowerCase() as "on" | "off";
+ directiveLines.add(i);
+ continue;
+ }
+
+ // Check for isolation level directive
+ const isolationMatch = line.match(TXN_ISOLATION_REGEX);
+ if (isolationMatch) {
+ // Normalize the isolation level string
+ const isolation = isolationMatch[1].toUpperCase().replace(/\s+/g, "_");
+ result.isolationLevel = isolation as IsolationLevel;
+ directiveLines.add(i);
+ continue;
}
}
+ // Build remaining content without directive lines
+ const remainingLines = lines.filter((_, i) => !directiveLines.has(i));
+ const remainingContent = remainingLines.join("\n");
+
// 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) {
@@ -62,15 +103,27 @@ export function parseStatement(statement: string): ParsedStatement {
/**
* Rebuilds a SQL statement from its components, ensuring proper ordering.
+ * Directives are placed at the top, followed by role setter, then main content.
*/
export function buildStatement(components: ParsedStatement): string {
const parts: string[] = [];
- // Line 1: Transaction mode directive (if present)
+ // Add directives at the top (they can be in any order)
+ // Transaction mode directive (if present)
if (components.transactionMode !== undefined) {
parts.push(`-- txn-mode = ${components.transactionMode}`);
}
+ // Isolation level directive (if present and txn-mode is not explicitly off)
+ if (
+ components.isolationLevel !== undefined &&
+ components.transactionMode !== "off"
+ ) {
+ // Convert back from underscore to space format
+ const isolation = components.isolationLevel.replace(/_/g, " ");
+ parts.push(`-- txn-isolation = ${isolation}`);
+ }
+
// Role setter block (if present) - place it before main content
if (components.roleSetterBlock) {
parts.push(components.roleSetterBlock);
@@ -96,6 +149,18 @@ export function updateTransactionMode(
return buildStatement(parsed);
}
+/**
+ * Updates the isolation level in a statement while preserving other components.
+ */
+export function updateIsolationLevel(
+ statement: string,
+ isolationLevel: IsolationLevel | undefined
+): string {
+ const parsed = parseStatement(statement);
+ parsed.isolationLevel = isolationLevel;
+ return buildStatement(parsed);
+}
+
/**
* Updates the role setter in a statement while preserving other components.
*/
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 71898664e1..34e06fa541 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1144,6 +1144,10 @@
},
"view-all": "View all ({count})"
},
+ "select-isolation-level": "Select isolation level",
+ "isolation-level": {
+ "self": "Isolation Level"
+ },
"options": {
"self": "Options",
"applies-to-all-tasks": "Applies to all tasks",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index de6e8e1689..8b24fa003f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1144,6 +1144,10 @@
},
"view-all": "Ver todo ({count})"
},
+ "select-isolation-level": "Seleccionar nivel de aislamiento",
+ "isolation-level": {
+ "self": "Nivel de Aislamiento"
+ },
"options": {
"self": "Opciones",
"applies-to-all-tasks": "Se aplica a todas las tareas.",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index be5e3375e3..c287e2f47a 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1144,6 +1144,10 @@
},
"view-all": "すべて表示 ({count})"
},
+ "select-isolation-level": "分離レベルを選択",
+ "isolation-level": {
+ "self": "分離レベル"
+ },
"options": {
"self": "オプション",
"applies-to-all-tasks": "すべてのタスクに適用",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 92f3286373..58d5bafac5 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1144,6 +1144,10 @@
},
"view-all": "Xem tất cả ({count})"
},
+ "select-isolation-level": "Chọn mức độ cô lập",
+ "isolation-level": {
+ "self": "Mức Độ Cô Lập"
+ },
"options": {
"self": "Tùy chọn",
"applies-to-all-tasks": "Áp dụng cho tất cả các nhiệm vụ",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 589c9c9433..31af68c507 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1144,6 +1144,10 @@
},
"view-all": "查看全部 ({count})"
},
+ "select-isolation-level": "选择隔离级别",
+ "isolation-level": {
+ "self": "隔离级别"
+ },
"options": {
"self": "配置项",
"applies-to-all-tasks": "适用于所有任务",