Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: move Transaction Mode toggle and Instance Role dropdown into plans (#17415)
Vincent Huangd3c64b8b99cc
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vueindex e9db883c08..0dfc4ff851 100644--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/InstanceRoleSelect.vue@@ -77,7 +77,9 @@ watch(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+);/);+ const match = parsed.roleSetterBlock.match(+ /SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/+ );if (match) {state.selectedRole = match[1];} else {diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.tsindex 0f848f4ce2..e7d521d8ba 100644--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/directiveUtils.ts@@ -12,8 +12,9 @@const TXN_MODE_REGEX = /^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/i;// PostgreSQL role setter pattern+// Matches PostgreSQL identifier rules: starts with letter/underscore, up to 63 charsconst ROLE_SETTER_REGEX =- /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE (\w+);/;+ /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/;export interface ParsedStatement {// Line 1 directive (currently only transaction mode)diff --git a/frontend/src/components/Plan/components/Configuration/Configuration.vue b/frontend/src/components/Plan/components/Configuration/Configuration.vueindex 4cf5cb34a7..94f031d66e 100644--- a/frontend/src/components/Plan/components/Configuration/Configuration.vue+++ b/frontend/src/components/Plan/components/Configuration/Configuration.vue@@ -3,9 +3,11 @@<p class="text-base">{{ $t("plan.options.self") }}</p>- <div class="w-auto">+ <div class="w-auto flex flex-col gap-2">+ <TransactionModeSection v-if="shouldShowTransactionModeSection" /><GhostSection v-if="shouldShowGhostSection" /><PreBackupSection v-if="shouldShowPreBackupSection" />+ <InstanceRoleSection v-if="shouldShowInstanceRoleSection" /></div></div></template>@@ -17,13 +19,43 @@ import { usePlanContext } from "../../logic";import { useSelectedSpec } from "../SpecDetailView/context";import GhostSection from "./GhostSection";import { provideGhostSettingContext } from "./GhostSection/context";+import InstanceRoleSection from "./InstanceRoleSection";+import { provideInstanceRoleSettingContext } from "./InstanceRoleSection/context";import PreBackupSection from "./PreBackupSection";import { providePreBackupSettingContext } from "./PreBackupSection/context";+import TransactionModeSection from "./TransactionModeSection";+import { provideTransactionModeSettingContext } from "./TransactionModeSection/context";const { project } = useCurrentProjectV1();const { isCreating, plan, events, issue, rollout, readonly } = usePlanContext();const selectedSpec = useSelectedSpec();+const {+ shouldShow: shouldShowTransactionModeSection,+ events: transactionModeEvents,+} = provideTransactionModeSettingContext({+ project,+ plan,+ selectedSpec,+ isCreating,+ issue,+ rollout,+ readonly,+});++const {+ shouldShow: shouldShowInstanceRoleSection,+ events: instanceRoleEvents,+} = provideInstanceRoleSettingContext({+ project,+ plan,+ selectedSpec,+ isCreating,+ issue,+ rollout,+ readonly,+});+const { shouldShow: shouldShowGhostSection, events: ghostEvents } =provideGhostSettingContext({project,@@ -47,7 +79,24 @@ const { shouldShow: shouldShowPreBackupSection, events: preBackupEvents } =});const shouldShow = computed(() => {- return shouldShowGhostSection.value || shouldShowPreBackupSection.value;+ return (+ shouldShowTransactionModeSection.value ||+ shouldShowInstanceRoleSection.value ||+ shouldShowGhostSection.value ||+ shouldShowPreBackupSection.value+ );+});++transactionModeEvents.on("update", () => {+ events.emit("status-changed", {+ eager: true,+ });+});++instanceRoleEvents.on("update", () => {+ events.emit("status-changed", {+ eager: true,+ });});preBackupEvents.on("update", () => {diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vue b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vuenew file mode 100644index 0000000000..db3181c8f9--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vue@@ -0,0 +1,24 @@+<template>+ <div+ class="w-full flex items-center justify-start gap-x-2 flex-wrap whitespace-nowrap"+ >+ <InstanceRoleSelect />+ <NTooltip>+ <template #trigger>+ <div class="textlabel flex items-center">+ <span>{{ $t("common.role.self") }}</span>+ </div>+ </template>+ <template #default>+ <div class="max-w-[20rem]">+ {{ $t("instance.select-database-user") }}+ </div>+ </template>+ </NTooltip>+ </div>+</template>++<script lang="ts" setup>+import { NTooltip } from "naive-ui";+import InstanceRoleSelect from "./InstanceRoleSelect.vue";+</script>diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vue b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vuenew file mode 100644index 0000000000..df9775936f--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vue@@ -0,0 +1,126 @@+<template>+ <NSelect+ v-model:value="selectedRole"+ class="!w-40"+ consistent-menu-width+ size="small"+ :options="options"+ :placeholder="$t('instance.select-database-user')"+ :filterable="true"+ :virtual-scroll="true"+ :fallback-option="false"+ :disabled="!allowChange"+ :loading="loading"+ />+</template>++<script setup lang="tsx">+import { create } from "@bufbuild/protobuf";+import { NSelect, type SelectOption } from "naive-ui";+import { computed, ref, watch } from "vue";+import { instanceRoleServiceClientConnect } from "@/grpcweb";+import { DEFAULT_PAGE_SIZE } from "@/store/modules/common";+import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";+import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";+import { useSelectedSpec } from "../../SpecDetailView/context";+import {+ parseStatement,+ updateRoleSetter,+} from "../../StatementSection/directiveUtils";+import { useSpecSheet } from "../../StatementSection/useSpecSheet";+import { useInstanceRoleSettingContext } from "./context";++const {+ allowChange,+ selectedRole: contextSelectedRole,+ databases,+ events,+} = useInstanceRoleSettingContext();+const selectedSpec = useSelectedSpec();+const { sheetStatement, updateSheetStatement } = useSpecSheet(selectedSpec);++const instanceRoles = ref<InstanceRole[]>([]);+const loading = ref(false);++const selectedRole = computed({+ get: () => contextSelectedRole.value,+ set: (value: string | undefined) => {+ contextSelectedRole.value = value;+ if (value) {+ setRoleInStatement(value);+ }+ },+});++const database = computed(() => {+ // For instance roles, we just need to get from the first database+ // since all databases in a spec share the same instance+ return databases.value[0];+});++watch(+ () => database.value?.instance,+ async () => {+ if (!database.value) return;++ loading.value = true;+ try {+ const request = create(ListInstanceRolesRequestSchema, {+ parent: database.value.instance,+ pageSize: DEFAULT_PAGE_SIZE,+ });+ const response =+ await instanceRoleServiceClientConnect.listInstanceRoles(request);+ instanceRoles.value = response.roles;+ } finally {+ loading.value = false;+ }+ },+ {+ immediate: true,+ }+);++const options = computed(() => {+ return instanceRoles.value.map<SelectOption>((instanceRole) => {+ return {+ value: instanceRole.roleName,+ label: instanceRole.roleName,+ };+ });+});++// Initialize selected role from statement+const initializeFromStatement = () => {+ const parsed = parseStatement(sheetStatement.value);+ if (parsed.roleSetterBlock) {+ // Extract role name from the role setter block+ const match = parsed.roleSetterBlock.match(+ /SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/+ );+ if (match) {+ contextSelectedRole.value = match[1];+ } else {+ contextSelectedRole.value = undefined;+ }+ } else {+ contextSelectedRole.value = undefined;+ }+};++watch(+ () => selectedSpec.value?.id,+ () => {+ initializeFromStatement();+ },+ {+ immediate: true,+ }+);++const setRoleInStatement = (roleName: string) => {+ const updatedStatement = updateRoleSetter(sheetStatement.value, roleName);+ updateSheetStatement(updatedStatement);+ events.emit("update");+};+</script>diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.ts b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.tsnew file mode 100644index 0000000000..bce9228ce0--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.ts@@ -0,0 +1,165 @@+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";++export const KEY = Symbol(+ "bb.plan.setting.instance-role"+) as InjectionKey<InstanceRoleSettingContext>;++export const useInstanceRoleSettingContext = () => {+ return inject(KEY)!;+};++export const provideInstanceRoleSettingContext = (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,+ plan,+ selectedSpec,+ selectedTask,+ issue,+ rollout,+ readonly,+ } = refs;++ const events = new Emittery<{+ update: never;+ }>();++ const selectedRole = ref<string | 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 PostgreSQL databases+ const allDatabasesArePostgres = databases.value.every(+ (db) => db.instanceResource.engine === Engine.POSTGRES+ );+ if (!allDatabasesArePostgres) return false;++ // Check if this is a DDL or DML change+ if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {+ return false;+ }++ // Get the task type+ 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 mode, disallow changes+ if (readonly?.value) {+ return false;+ }++ // Allow changes when creating+ if (isCreating.value) {+ return true;+ }++ // If issue is not open, disallow+ if (issue?.value && issue.value.status !== IssueStatus.OPEN) {+ return false;+ }++ let task: Task | undefined;+ if (selectedTask?.value) {+ task = selectedTask.value;+ } else if (rollout?.value) {+ const tasks = flattenTaskV1List(rollout.value);+ task = tasks.find((t) => t.specId === selectedSpec.value?.id);+ }++ // If task is running/done/etc, disallow+ if (+ task &&+ [+ Task_Status.PENDING,+ Task_Status.RUNNING,+ Task_Status.DONE,+ Task_Status.SKIPPED,+ ].includes(task.status)+ ) {+ return false;+ }++ return true;+ });++ const context = {+ isCreating,+ selectedSpec,+ selectedTask,+ plan,+ shouldShow,+ allowChange,+ selectedRole,+ databases,+ events,+ };++ provide(KEY, context);++ return context;+};++type InstanceRoleSettingContext = ReturnType<+ typeof provideInstanceRoleSettingContext+>;diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.ts b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.tsnew file mode 100644index 0000000000..dd0186438f--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.ts@@ -0,0 +1,3 @@+import InstanceRoleSection from "./InstanceRoleSection.vue";++export default InstanceRoleSection;diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vue b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vuenew file mode 100644index 0000000000..cbb15941cf--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vue@@ -0,0 +1,32 @@+<template>+ <div+ class="w-full flex items-center justify-start gap-x-2 flex-wrap whitespace-nowrap"+ >+ <TransactionModeSwitch />+ <NTooltip>+ <template #trigger>+ <div class="textlabel flex items-center">+ <span>{{ $t("issue.transaction-mode.label") }}</span>+ </div>+ </template>+ <template #default>+ <div class="max-w-[20rem]">+ <div v-if="transactionMode === 'on'">+ {{ $t("issue.transaction-mode.on-tooltip") }}+ </div>+ <div v-else>+ {{ $t("issue.transaction-mode.off-tooltip") }}+ </div>+ </div>+ </template>+ </NTooltip>+ </div>+</template>++<script lang="ts" setup>+import { NTooltip } from "naive-ui";+import TransactionModeSwitch from "./TransactionModeSwitch.vue";+import { useTransactionModeSettingContext } from "./context";++const { transactionMode } = useTransactionModeSettingContext();+</script>diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vue b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vuenew file mode 100644index 0000000000..695f7d4faf--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vue@@ -0,0 +1,65 @@+<template>+ <NSwitch+ v-model:value="isTransactionOn"+ size="small"+ :disabled="!allowChange"+ />+</template>++<script setup lang="tsx">+import { NSwitch } from "naive-ui";+import { computed, watch } from "vue";+import { getDefaultTransactionMode } from "@/utils";+import { useSelectedSpec } from "../../SpecDetailView/context";+import {+ parseStatement,+ updateTransactionMode,+} from "../../StatementSection/directiveUtils";+import { useSpecSheet } from "../../StatementSection/useSpecSheet";+import { useTransactionModeSettingContext } from "./context";++const { allowChange, transactionMode, events } =+ useTransactionModeSettingContext();+const selectedSpec = useSelectedSpec();+const { sheetStatement, updateSheetStatement } = useSpecSheet(selectedSpec);++// Default transaction mode+const getDefaultForCurrentTask = () => {+ return getDefaultTransactionMode();+};++const isTransactionOn = computed({+ get: () => transactionMode.value === "on",+ set: (value: boolean) => {+ transactionMode.value = value ? "on" : "off";+ updateStatementWithTransactionMode();+ },+});++// Initialize transaction mode from statement+const initializeFromStatement = () => {+ const parsed = parseStatement(sheetStatement.value);+ if (parsed.transactionMode !== undefined) {+ transactionMode.value = parsed.transactionMode;+ } else {+ transactionMode.value = getDefaultForCurrentTask() ? "on" : "off";+ }+};++// Watch for spec changes to reset defaults+watch(+ () => selectedSpec.value?.id,+ () => {+ initializeFromStatement();+ },+ { immediate: true }+);++// Update statement when transaction mode changes+const updateStatementWithTransactionMode = () => {+ const mode = transactionMode.value;+ const updatedStatement = updateTransactionMode(sheetStatement.value, mode);+ updateSheetStatement(updatedStatement);+ events.emit("update");+};+</script>diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.ts b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.tsnew file mode 100644index 0000000000..7443eaa9ce--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.ts@@ -0,0 +1,164 @@+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 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, instanceV1SupportsTransactionMode } from "@/utils";++export const KEY = Symbol(+ "bb.plan.setting.transaction-mode"+) as InjectionKey<TransactionModeSettingContext>;++export const useTransactionModeSettingContext = () => {+ return inject(KEY)!;+};++export const provideTransactionModeSettingContext = (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,+ plan,+ selectedSpec,+ selectedTask,+ issue,+ rollout,+ readonly,+ } = refs;++ const events = new Emittery<{+ update: never;+ }>();++ const transactionMode = ref<"on" | "off">("on");++ 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;++ // Check if all databases support transaction mode+ const allDatabasesSupportTransactionMode = databases.value.every((db) =>+ instanceV1SupportsTransactionMode(db.instanceResource.engine)+ );+ if (!allDatabasesSupportTransactionMode) 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 mode, disallow changes+ if (readonly?.value) {+ return false;+ }++ // Allow changes when creating+ if (isCreating.value) {+ return true;+ }++ // If issue is not open, disallow+ if (issue?.value && issue.value.status !== IssueStatus.OPEN) {+ return false;+ }++ let task: Task | undefined;+ if (selectedTask?.value) {+ task = selectedTask.value;+ } else if (rollout?.value) {+ const tasks = flattenTaskV1List(rollout.value);+ task = tasks.find((t) => t.specId === selectedSpec.value?.id);+ }++ // If task is running/done/etc, disallow+ if (+ task &&+ [+ Task_Status.PENDING,+ Task_Status.RUNNING,+ Task_Status.DONE,+ Task_Status.SKIPPED,+ ].includes(task.status)+ ) {+ return false;+ }++ return true;+ });++ const context = {+ isCreating,+ selectedSpec,+ selectedTask,+ plan,+ shouldShow,+ allowChange,+ transactionMode,+ databases,+ events,+ };++ provide(KEY, context);++ return context;+};++type TransactionModeSettingContext = ReturnType<+ typeof provideTransactionModeSettingContext+>;diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.ts b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.tsnew file mode 100644index 0000000000..f87274efbe--- /dev/null+++ b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.ts@@ -0,0 +1,3 @@+import TransactionModeSection from "./TransactionModeSection.vue";++export default TransactionModeSection;diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vueindex a04f1237f0..5a2eb73f40 100644--- a/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue@@ -14,6 +14,7 @@</div><div class="flex items-center justify-end gap-x-2"><template v-if="isCreating">+ <FormatOnSaveCheckbox /><SQLUploadButtonsize="small":loading="state.isUploadingFile"@@ -55,6 +56,7 @@</template></template><template v-else>+ <FormatOnSaveCheckbox /><SQLUploadButtonsize="small":loading="state.isUploadingFile"@@ -207,6 +209,7 @@ import {import { useSelectedSpec } from "../../SpecDetailView/context";import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";import { useSpecSheet } from "../useSpecSheet";+import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";type LocalState = {statement: string;diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue b/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vuenew file mode 100644index 0000000000..d7dd7ca391--- /dev/null+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue@@ -0,0 +1,40 @@+<template>+ <NCheckbox+ v-if="allowFormatOnSave"+ :checked="formatOnSave"+ size="small"+ @update:checked="updateFormatOnSave"+ >+ {{ $t("issue.format-on-save") }}+ </NCheckbox>+</template>++<script setup lang="ts">+import { NCheckbox } from "naive-ui";+import { computed } from "vue";+import { databaseForSpec } from "@/components/Plan/logic";+import { useUIStateStore } from "@/store";+import { useCurrentProjectV1 } from "@/store";+import { useInstanceV1EditorLanguage } from "@/utils";+import { useSelectedSpec } from "../../SpecDetailView/context";++const { project } = useCurrentProjectV1();+const selectedSpec = useSelectedSpec();+const uiStateStore = useUIStateStore();++const database = computed(() => {+ return databaseForSpec(project.value, selectedSpec.value);+});++const language = useInstanceV1EditorLanguage(+ computed(() => database.value.instanceResource)+);++const allowFormatOnSave = computed(() => language.value === "sql");++const formatOnSave = computed(() => uiStateStore.editorFormatStatementOnSave);++const updateFormatOnSave = (value: boolean) => {+ uiStateStore.setEditorFormatStatementOnSave(value);+};+</script>diff --git a/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts b/frontend/src/components/Plan/components/StatementSection/directiveUtils.tsnew file mode 100644index 0000000000..e7d521d8ba--- /dev/null+++ b/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts@@ -0,0 +1,115 @@+/**+ * 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+// 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 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/components/Plan/components/StatementSection/useSpecSheet.ts b/frontend/src/components/Plan/components/StatementSection/useSpecSheet.tsindex 56cfbbe281..0d9872c58c 100644--- a/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts+++ b/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts@@ -43,10 +43,15 @@ export const useSpecSheet = (spec: ComputedRef<Plan_Spec>) => {},});+ const updateSheetStatement = (statement: string) => {+ sheetStatement.value = statement;+ };+return {sheet,sheetName,sheetReady,sheetStatement,+ updateSheetStatement,};};