Skip to content

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

feat(frontend): pick tables to rollout branch (#9922)

Liu Jib99afc01dffc
diff --git a/frontend/src/components/Branch/BranchDetailView.vue b/frontend/src/components/Branch/BranchDetailView.vue
index ca7ad70127..c0bce88ee5 100644
--- a/frontend/src/components/Branch/BranchDetailView.vue
+++ b/frontend/src/components/Branch/BranchDetailView.vue
@@ -1,8 +1,5 @@
<template>
- <div
- class="flex flex-col gap-y-3 w-full overflow-x-auto relative"
- v-bind="$attrs"
- >
+ <div class="flex flex-col gap-y-3 w-full h-full relative" v-bind="$attrs">
<MaskSpinner
v-if="state.isReverting || state.savingStatus"
class="!bg-white/75"
@@ -17,15 +14,19 @@
<div class="w-full flex flex-row justify-between items-center">
<div class="w-full flex flex-row justify-start items-center gap-x-2">
<NInput
+ v-if="!readonly"
v-model:value="state.branchId"
class="!w-auto"
:passively-activated="true"
:style="branchIdInputStyle"
- :readonly="!state.isEditingBranchId"
+ :readonly="readonly || !state.isEditingBranchId"
:placeholder="'feature/add-billing'"
@focus="state.isEditingBranchId = true"
@blur="handleBranchIdInputBlur"
/>
+ <span v-else class="text-xl leading-[34px]">{{
+ cleanBranch.branchId
+ }}</span>
<NTag v-if="parentBranch" round>
{{ $t("schema-designer.parent-branch") }}:
{{ parentBranch.branchId }}
@@ -40,16 +41,13 @@
<template v-if="!state.isEditing">
<NButton @click="handleEdit">{{ $t("common.edit") }}</NButton>
<NButton
- :disabled="!ready"
- :loading="!ready"
+ :disabled="!branchListReady"
@click="handleMergeBranch"
>{{ $t("schema-designer.merge-branch") }}</NButton
>
- <NButton
- type="primary"
- @click="selectTargetDatabasesContext.show = true"
- >{{ $t("schema-designer.apply-to-database") }}</NButton
- >
+ <NButton type="primary" @click="handleApplyBranchToDatabase">{{
+ $t("schema-designer.apply-to-database")
+ }}</NButton>
</template>
<template v-else>
<NButton :loading="state.isReverting" @click="handleCancelEdit">{{
@@ -67,7 +65,7 @@
</div>
</div>
- <NDivider />
+ <NDivider class="!my-0" />
<div
class="w-full flex flex-row justify-between items-center text-sm mt-1 gap-4"
@@ -80,7 +78,7 @@
</div>
</div>
- <div class="w-full h-[32rem]">
+ <div class="w-full flex-1 flex flex-col">
<SchemaDesignEditorLite
ref="schemaDesignerRef"
:project="project"
@@ -171,7 +169,7 @@ const { t } = useI18n();
const router = useRouter();
const databaseStore = useDatabaseV1Store();
const branchStore = useBranchStore();
-const { branchList, ready } = useBranchListByProject(
+const { branchList, ready: branchListReady } = useBranchListByProject(
computed(() => props.project.name)
);
const { runSQLCheck } = provideSQLCheckContext();
@@ -421,6 +419,16 @@ const handleMergeAfterConflictResolved = (branchName: string) => {
});
};
+const handleApplyBranchToDatabase = () => {
+ router.push({
+ name: "workspace.project.branch.rollout",
+ params: {
+ projectSlug: projectV1Slug(props.project),
+ branchName: props.cleanBranch.branchId,
+ },
+ });
+};
+
const handleApplyToDatabase = async (databaseIdList: string[]) => {
const cleanup = () => {
state.applyingToDatabaseStatus = false;
diff --git a/frontend/src/components/Branch/BranchRolloutView/BranchRolloutView.vue b/frontend/src/components/Branch/BranchRolloutView/BranchRolloutView.vue
new file mode 100644
index 0000000000..6f91bba7a5
--- /dev/null
+++ b/frontend/src/components/Branch/BranchRolloutView/BranchRolloutView.vue
@@ -0,0 +1,275 @@
+<template>
+ <div
+ class="flex flex-col gap-y-2 w-full h-full overflow-x-auto relative p-1"
+ v-bind="$attrs"
+ >
+ <div class="flex flex-row justify-between">
+ <div class="flex flex-col flex-1 gap-y-2">
+ <div class="textlabel">
+ {{ $t("branch.rollout.select-target-database") }}
+ </div>
+ <div class="flex flex-row items-center gap-x-4">
+ <div class="flex flex-row items-center gap-x-2">
+ <div class="textlabel">{{ $t("common.environment") }}</div>
+ <EnvironmentSelect
+ :environment="environment?.uid"
+ style="width: 8rem"
+ @update:environment="handleSelectEnvironment"
+ />
+ </div>
+ <div class="flex flex-row items-center gap-x-2">
+ <div class="textlabel">{{ $t("common.database") }}</div>
+ <DatabaseSelect
+ :database="database?.uid"
+ :project="project.uid"
+ :environment="environment?.uid"
+ :filter="filterDatabase"
+ style="width: 16rem"
+ @update:database="handleSelectDatabase"
+ />
+ </div>
+ </div>
+ </div>
+
+ <div class="flex flex-row items-end justify-end">
+ <NButton
+ type="primary"
+ :disabled="!allowPreviewIssue"
+ @click="handlePreviewIssue"
+ >
+ {{ $t("issue.preview") }}
+ </NButton>
+ </div>
+ </div>
+ <div class="flex-1 overflow-hidden relative">
+ <SchemaEditorLite
+ v-if="database"
+ :key="virtualBranch.name"
+ ref="schemaEditorRef"
+ v-model:selected-rollout-objects="selectedRolloutObjects"
+ :project="project"
+ :readonly="true"
+ :resource-type="'branch'"
+ :branch="virtualBranch"
+ :loading="isLoadingVirtualBranch"
+ :diff-when-ready="true"
+ />
+
+ <!-- used as a placeholder -->
+ <template v-else>
+ <SchemaEditorLite
+ :project="project"
+ :readonly="true"
+ :resource-type="'branch'"
+ :branch="emptyBranch"
+ />
+ <div
+ class="absolute inset-0 bg-white/75 text-sm flex flex-col items-center justify-center"
+ >
+ {{ $t("branch.rollout.select-target-database") }}
+ </div>
+ </template>
+ </div>
+
+ <MaskSpinner
+ v-if="virtualBranchReady && isGeneratingDDL"
+ class="!bg-white/75"
+ >
+ <div class="text-sm">Generating DDL</div>
+ </MaskSpinner>
+ </div>
+
+ <div
+ class="text-xs font-mono fixed bottom-0 left-0 bg-white/50 border p-1 max-w-[40rem]"
+ >
+ <div>ready: {{ virtualBranchReady }}</div>
+ <div>
+ selectedRolloutObjects.length: {{ selectedRolloutObjects.length }}
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import dayjs from "dayjs";
+import { cloneDeep } from "lodash-es";
+import { NButton } from "naive-ui";
+import { computed, ref, toRef, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import SchemaEditorLite, {
+ RolloutObject,
+ generateDiffDDL,
+} from "@/components/SchemaEditorLite";
+import MaskSpinner from "@/components/misc/MaskSpinner.vue";
+import { DatabaseSelect, EnvironmentSelect } from "@/components/v2";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useEnvironmentV1Store,
+ useSheetV1Store,
+} from "@/store";
+import { ComposedDatabase, ComposedProject, UNKNOWN_ID } from "@/types";
+import { Branch } from "@/types/proto/v1/branch_service";
+import { Environment } from "@/types/proto/v1/environment_service";
+import {
+ Sheet,
+ SheetPayload_Type,
+ Sheet_Source,
+ Sheet_Type,
+ Sheet_Visibility,
+} from "@/types/proto/v1/sheet_service";
+import { extractSheetUID, setSheetStatement } from "@/utils";
+import { useVirtualBranch } from "./useVirtualBranch";
+
+const props = defineProps<{
+ project: ComposedProject;
+ branch: Branch;
+}>();
+
+const { t } = useI18n();
+const router = useRouter();
+const schemaEditorRef = ref<InstanceType<typeof SchemaEditorLite>>();
+const environment = ref<Environment>();
+const database = ref<ComposedDatabase>();
+const {
+ isLoading: isLoadingVirtualBranch,
+ ready: virtualBranchReady,
+ branch: virtualBranch,
+} = useVirtualBranch(toRef(props, "project"), toRef(props, "branch"), database);
+const selectedRolloutObjects = ref<RolloutObject[]>([]);
+const emptyBranch = Branch.fromJSON({});
+const isGeneratingDDL = ref(false);
+
+const handleSelectEnvironment = (uid: string | undefined) => {
+ if (!uid || uid === String(UNKNOWN_ID)) {
+ environment.value = undefined;
+ return;
+ }
+ environment.value = useEnvironmentV1Store().getEnvironmentByUID(uid);
+ if (database.value) {
+ if (database.value.effectiveEnvironment !== environment.value.name) {
+ // de-select database since environment changed
+ handleSelectDatabase(undefined);
+ }
+ }
+};
+const handleSelectDatabase = (uid: string | undefined) => {
+ if (!uid || uid === String(UNKNOWN_ID)) {
+ database.value = undefined;
+ return;
+ }
+ database.value = useDatabaseV1Store().getDatabaseByUID(uid);
+ if (!environment.value) {
+ // Auto select environment if it's not selected
+ environment.value = database.value.effectiveEnvironmentEntity;
+ }
+};
+const filterDatabase = (db: ComposedDatabase) => {
+ return db.instanceEntity.engine === props.branch.engine;
+};
+
+const allowPreviewIssue = computed(() => {
+ if (!database.value) return false;
+ if (!virtualBranchReady.value) return false;
+ return selectedRolloutObjects.value.length > 0;
+});
+
+const handlePreviewIssue = async () => {
+ const cleanup = (errors: string[], fatal: boolean) => {
+ if (errors.length > 0) {
+ pushNotification({
+ module: "bytebase",
+ style: fatal ? "CRITICAL" : "WARN",
+ title: t("common.error"),
+ description: errors.join("\n"),
+ });
+ }
+ isGeneratingDDL.value = false;
+ };
+
+ const source = cloneDeep(virtualBranch.value.baselineSchemaMetadata);
+ const target = cloneDeep(virtualBranch.value.schemaMetadata);
+ const db = database.value;
+ const editor = schemaEditorRef.value;
+ if (!source) return;
+ if (!target) return;
+ if (!db) return;
+ if (!editor) return;
+ editor.applySelectedMetadataEdit(
+ db,
+ source,
+ target,
+ selectedRolloutObjects.value
+ );
+
+ isGeneratingDDL.value = true;
+ const { statement, errors, fatal } = await generateDiffDDL(
+ db,
+ source,
+ target,
+ /* !allowEmptyDiffDDLWithConfigChange */ false
+ );
+ if (errors.length > 0) {
+ return cleanup(errors, fatal);
+ }
+ const sheet = Sheet.fromPartial({
+ database: db.name,
+ visibility: Sheet_Visibility.VISIBILITY_PROJECT,
+ type: Sheet_Type.TYPE_SQL,
+ source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,
+ payload: {
+ type: SheetPayload_Type.SCHEMA_DESIGN,
+ baselineDatabaseConfig: {
+ schemaConfigs: source.schemaConfigs,
+ },
+ databaseConfig: {
+ schemaConfigs: target.schemaConfigs,
+ },
+ },
+ });
+ setSheetStatement(sheet, statement);
+ const createdSheet = await useSheetV1Store().createSheet(
+ props.project.name,
+ sheet
+ );
+ const query: Record<string, any> = {
+ template: "bb.issue.database.schema.update",
+ project: props.project.uid,
+ databaseList: db.uid,
+ sheetId: extractSheetUID(createdSheet.name),
+ name: generateIssueName(db.databaseName),
+ };
+ const routeInfo = {
+ name: "workspace.issue.detail",
+ params: {
+ issueSlug: "new",
+ },
+ query,
+ };
+ router.push(routeInfo);
+};
+
+const generateIssueName = (databaseName: string) => {
+ const issueNameParts: string[] = [];
+ issueNameParts.push(`Apply branch`);
+ issueNameParts.push(`"${props.branch.branchId}"`);
+ issueNameParts.push("to database");
+ issueNameParts.push(`[${databaseName}]`);
+ const datetime = dayjs().format("@MM-DD HH:mm");
+ const tz = "UTC" + dayjs().format("ZZ");
+ issueNameParts.push(`${datetime} ${tz}`);
+ return issueNameParts.join(" ");
+};
+
+watch(
+ () => props.branch,
+ () => {
+ // Auto select the branch's baseline database as the target database by default
+ const db = useDatabaseV1Store().getDatabaseByName(
+ props.branch.baselineDatabase
+ );
+ handleSelectDatabase(db.uid);
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/Branch/BranchRolloutView/index.ts b/frontend/src/components/Branch/BranchRolloutView/index.ts
new file mode 100644
index 0000000000..ef3c4466d4
--- /dev/null
+++ b/frontend/src/components/Branch/BranchRolloutView/index.ts
@@ -0,0 +1,3 @@
+import BranchRolloutView from "./BranchRolloutView.vue";
+
+export default BranchRolloutView;
diff --git a/frontend/src/components/Branch/BranchRolloutView/useVirtualBranch.ts b/frontend/src/components/Branch/BranchRolloutView/useVirtualBranch.ts
new file mode 100644
index 0000000000..357c8930a9
--- /dev/null
+++ b/frontend/src/components/Branch/BranchRolloutView/useVirtualBranch.ts
@@ -0,0 +1,82 @@
+import { uniqueId } from "lodash-es";
+import { computed, reactive, ref, unref, watchEffect } from "vue";
+import { useDBSchemaV1Store } from "@/store";
+import {
+ ComposedDatabase,
+ ComposedProject,
+ MaybeRef,
+ unknownDatabase,
+} from "@/types";
+import { Branch } from "@/types/proto/v1/branch_service";
+import {
+ DatabaseMetadata,
+ DatabaseMetadataView,
+} from "@/types/proto/v1/database_service";
+
+/**
+ * Create a "virtual" branch to show the diff between a branch's head and a database's head
+ * @param database
+ * @param branch
+ */
+export const useVirtualBranch = (
+ project: MaybeRef<ComposedProject>,
+ branch: MaybeRef<Branch>,
+ database: MaybeRef<ComposedDatabase | undefined>
+) => {
+ const state = reactive({
+ isLoadingDatabaseMetadata: false,
+ });
+ const databaseHeadMetadata = ref<DatabaseMetadata>();
+
+ const fetchDatabaseHeadMetadata = async (
+ db: ComposedDatabase | undefined,
+ signal: AbortController["signal"]
+ ) => {
+ if (!db) {
+ databaseHeadMetadata.value = undefined;
+ state.isLoadingDatabaseMetadata = false;
+ return;
+ }
+
+ state.isLoadingDatabaseMetadata = true;
+ const metadata = await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
+ database: db.name,
+ skipCache: false /* ensure using the latest */,
+ view: DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL,
+ });
+ if (signal.aborted) return;
+ databaseHeadMetadata.value = metadata;
+ state.isLoadingDatabaseMetadata = false;
+ };
+
+ watchEffect((onCancel) => {
+ const controller = new AbortController();
+ fetchDatabaseHeadMetadata(unref(database), controller.signal);
+ onCancel(() => controller.abort());
+ });
+
+ const virtualBranch = computed(() => {
+ const db = unref(database) ?? unknownDatabase();
+ return Branch.fromPartial({
+ name: `${unref(project).name}/branches/-${uniqueId()}`,
+ engine: db.instanceEntity.engine,
+ baselineDatabase: db.name,
+ schemaMetadata: unref(branch).schemaMetadata,
+ baselineSchemaMetadata: databaseHeadMetadata.value,
+ });
+ });
+
+ const isLoading = computed(() => {
+ return state.isLoadingDatabaseMetadata;
+ });
+
+ const ready = computed(() => {
+ return !state.isLoadingDatabaseMetadata;
+ });
+
+ return {
+ isLoading,
+ ready,
+ branch: virtualBranch,
+ };
+};
diff --git a/frontend/src/components/Icon/DatabaseIcon.vue b/frontend/src/components/Icon/DatabaseIcon.vue
new file mode 100644
index 0000000000..a120c91cd1
--- /dev/null
+++ b/frontend/src/components/Icon/DatabaseIcon.vue
@@ -0,0 +1,8 @@
+<template>
+ <div class="relative">
+ <DatabaseIcon v-bind="$attrs" />
+ </div>
+</template>
+<script setup lang="ts">
+import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
+</script>
diff --git a/frontend/src/components/Icon/SchemaIcon.vue b/frontend/src/components/Icon/SchemaIcon.vue
new file mode 100644
index 0000000000..f3c172eca9
--- /dev/null
+++ b/frontend/src/components/Icon/SchemaIcon.vue
@@ -0,0 +1,8 @@
+<template>
+ <div class="relative">
+ <SchemaIcon v-bind="$attrs" />
+ </div>
+</template>
+<script setup lang="ts">
+import SchemaIcon from "~icons/heroicons-outline/view-columns";
+</script>
diff --git a/frontend/src/components/Icon/index.ts b/frontend/src/components/Icon/index.ts
index 85e301e576..789ebd1af5 100644
--- a/frontend/src/components/Icon/index.ts
+++ b/frontend/src/components/Icon/index.ts
@@ -1,6 +1,8 @@
+import DatabaseIcon from "./DatabaseIcon.vue";
import EngineIcon from "./EngineIcon.vue";
+import SchemaIcon from "./SchemaIcon.vue";
import SkipIcon from "./SkipIcon.vue";
import TableIcon from "./TableIcon.vue";
import ViewIcon from "./ViewIcon.vue";
-export { SkipIcon, EngineIcon, TableIcon, ViewIcon };
+export { SkipIcon, EngineIcon, DatabaseIcon, SchemaIcon, TableIcon, ViewIcon };
diff --git a/frontend/src/components/IssueV1/logic/initialize/create.ts b/frontend/src/components/IssueV1/logic/initialize/create.ts
index 519f5d5915..3e4a482d08 100644
--- a/frontend/src/components/IssueV1/logic/initialize/create.ts
+++ b/frontend/src/components/IssueV1/logic/initialize/create.ts
@@ -1,4 +1,4 @@
-import { groupBy, orderBy } from "lodash-es";
+import { cloneDeep, groupBy, orderBy } from "lodash-es";
import { v4 as uuidv4 } from "uuid";
import { reactive } from "vue";
import { rolloutServiceClient } from "@/grpcweb";
@@ -327,6 +327,23 @@ export const buildSpecForTarget = async (
type,
sheet,
});
+
+ if (query.sheetId) {
+ const remoteSheet = await useSheetV1Store().getOrFetchSheetByUID(
+ query.sheetId
+ );
+ if (remoteSheet) {
+ // make a local copy for remote sheet for further editing
+ console.debug(
+ "copy remote sheet to local for further editing",
+ remoteSheet
+ );
+ const localSheet = getLocalSheetByName(sheet);
+ localSheet.payload = cloneDeep(remoteSheet.payload);
+ const statement = getSheetStatement(remoteSheet);
+ setSheetStatement(localSheet, statement);
+ }
+ }
}
if (template === "bb.issue.database.schema.baseline") {
spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
diff --git a/frontend/src/components/SchemaEditorLite/Aside/BranchTree.vue b/frontend/src/components/SchemaEditorLite/Aside/BranchTree.vue
index 338f9803b4..85cecd67fa 100644
--- a/frontend/src/components/SchemaEditorLite/Aside/BranchTree.vue
+++ b/frontend/src/components/SchemaEditorLite/Aside/BranchTree.vue
@@ -83,9 +83,8 @@ import { TreeOption, NEllipsis, NInput, NDropdown, NTree } from "naive-ui";
import { computed, watch, ref, h, reactive, nextTick, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import DuplicateIcon from "~icons/heroicons-outline/document-duplicate";
-import TableIcon from "~icons/heroicons-outline/table-cells";
-import SchemaIcon from "~icons/heroicons-outline/view-columns";
import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";
+import { SchemaIcon, TableIcon } from "@/components/Icon";
import { ComposedDatabase } from "@/types";
import { Engine } from "@/types/proto/v1/common";
import {
@@ -156,6 +155,7 @@ const {
getSchemaStatus,
getTableStatus,
upsertTableConfig,
+ queuePendingScrollToTable,
} = useSchemaEditorContext();
const treeContainerElRef = ref<HTMLElement>();
const { height: treeContainerHeight } = useElementSize(
@@ -423,6 +423,68 @@ const renderLabel = ({ option }: { option: TreeOption }) => {
);
};
+const handleDuplicateTable = (schema: SchemaMetadata, table: TableMetadata) => {
+ const db = database.value;
+ const matchPattern = new RegExp(
+ `^${getOriginalName(table.name)}` + "(_copy[0-9]{0,}){0,1}$"
+ );
+ const copiedTableNames = flattenTableList.value
+ .filter((table) => {
+ return matchPattern.test(table.name);
+ })
+ .sort((t1, t2) => {
+ return extractDuplicateNumber(t1.name) - extractDuplicateNumber(t2.name);
+ });
+ const targetName = copiedTableNames.slice(-1)[0]?.name ?? table.name;
+
+ const newTable = cloneDeep(table);
+ newTable.name = getDuplicateName(targetName);
+ schema.tables.push(newTable);
+ markEditStatus(db, metadataForTable(schema, newTable), "created");
+ newTable.columns.forEach((newColumn) => {
+ markEditStatus(
+ db,
+ { ...metadataForTable(schema, newTable), column: newColumn },
+ "created"
+ );
+ });
+ const tableConfig = metadata.value.schemaConfigs
+ .find((sc) => sc.name === schema.name)
+ ?.tableConfigs.find((tc) => tc.name === table.name);
+ if (tableConfig) {
+ const tableConfigCopy = cloneDeep(tableConfig);
+ tableConfigCopy.name = newTable.name;
+ upsertTableConfig(
+ db,
+ {
+ database: metadata.value,
+ schema,
+ table: newTable,
+ },
+ (config) => {
+ Object.assign(config, tableConfigCopy);
+ }
+ );
+ }
+ addTab({
+ type: "table",
+ database: database.value,
+ metadata: {
+ database: metadata.value,
+ schema: schema,
+ table: newTable,
+ },
+ });
+ queuePendingScrollToTable({
+ db: database.value,
+ metadata: {
+ database: metadata.value,
+ schema: schema,
+ table: newTable,
+ },
+ });
+};
+
// Render a 'menu' icon in the right of the node
const renderSuffix = ({ option }: { option: TreeOption }) => {
if (readonly.value) {
@@ -443,64 +505,11 @@ const renderSuffix = ({ option }: { option: TreeOption }) => {
e.stopPropagation();
e.stopImmediatePropagation();
- const db = database.value;
const { schema, table } = treeNode as TreeNodeForTable;
if (!schema || !table) {
return;
}
-
- const matchPattern = new RegExp(
- `^${getOriginalName(table.name)}` + "(_copy[0-9]{0,}){0,1}$"
- );
- const copiedTableNames = flattenTableList.value
- .filter((table) => {
- return matchPattern.test(table.name);
- })
- .sort((t1, t2) => {
- return (
- extractDuplicateNumber(t1.name) - extractDuplicateNumber(t2.name)
- );
- });
- const targetName = copiedTableNames.slice(-1)[0]?.name ?? table.name;
-
- const newTable = cloneDeep(table);
- newTable.name = getDuplicateName(targetName);
- schema.tables.push(newTable);
- markEditStatus(db, metadataForTable(schema, newTable), "created");
- newTable.columns.forEach((newColumn) => {
- markEditStatus(
- db,
- { ...metadataForTable(schema, newTable), column: newColumn },
- "created"
- );
- });
- const tableConfig = metadata.value.schemaConfigs
- .find((sc) => sc.name === schema.name)
- ?.tableConfigs.find((tc) => tc.name === table.name);
- if (tableConfig) {
- const tableConfigCopy = cloneDeep(tableConfig);
- tableConfigCopy.name = newTable.name;
- upsertTableConfig(
- db,
- {
- database: metadata.value,
- schema,
- table: newTable,
- },
- (config) => {
- Object.assign(config, tableConfigCopy);
- }
- );
- }
- addTab({
- type: "table",
- database: database.value,
- metadata: {
- database: metadata.value,
- schema: schema,
- table: newTable,
- },
- });
+ handleDuplicateTable(schema, table);
},
});
if (treeNode.type === "schema") {
diff --git a/frontend/src/components/SchemaEditorLite/Aside/DatabaseTree.vue b/frontend/src/components/SchemaEditorLite/Aside/DatabaseTree.vue
index b59647fbf7..a5761605ae 100644
--- a/frontend/src/components/SchemaEditorLite/Aside/DatabaseTree.vue
+++ b/frontend/src/components/SchemaEditorLite/Aside/DatabaseTree.vue
@@ -33,8 +33,9 @@
:node-props="nodeProps"
:expanded-keys="expandedKeysRef"
:selected-keys="selectedKeysRef"
- :on-update:expanded-keys="handleExpandedKeysChange"
+ :show-irrelevant-nodes="false"
:theme-overrides="{ nodeHeight: '28px' }"
+ @update:expanded-keys="handleExpandedKeysChange"
/>
<NDropdown
trigger="manual"
@@ -80,10 +81,8 @@ import {
} from "naive-ui";
import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";
import { useI18n } from "vue-i18n";
-import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
-import TableIcon from "~icons/heroicons-outline/table-cells";
-import SchemaIcon from "~icons/heroicons-outline/view-columns";
import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";
+import { DatabaseIcon, SchemaIcon, TableIcon } from "@/components/Icon";
import { InstanceV1EngineIcon } from "@/components/v2";
import { ComposedDatabase, ComposedInstance } from "@/types";
import { Engine } from "@/types/proto/v1/common";
diff --git a/frontend/src/components/SchemaEditorLite/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaEditorLite/Modals/EditColumnForeignKeyModal.vue
index 05d8817135..8f792cf30d 100644
--- a/frontend/src/components/SchemaEditorLite/Modals/EditColumnForeignKeyModal.vue
+++ b/frontend/src/components/SchemaEditorLite/Modals/EditColumnForeignKeyModal.vue
@@ -10,6 +10,7 @@
v-model:value="state.referencedSchemaName"
:options="referenceSelectOptions"
:placeholder="$t('schema-editor.schema.select')"
+ :filterable="true"
@update:value="
() => {
state.referencedTableName = null;
@@ -24,6 +25,7 @@
v-model:value="state.referencedTableName"
:options="referencedTableOptions"
:placeholder="$t('schema-editor.table.select')"
+ :filterable="true"
@update:value="state.referencedColumnName = null"
/>
</div>
@@ -33,6 +35,7 @@
v-model:value="state.referencedColumnName"
:options="referencedColumnOptions"
:placeholder="$t('schema-editor.column.select')"
+ :filterable="true"
/>
</div>
diff --git a/frontend/src/components/SchemaEditorLite/Modals/TableNameModal.vue b/frontend/src/components/SchemaEditorLite/Modals/TableNameModal.vue
index c5cc2f153c..9737733ad9 100644
--- a/frontend/src/components/SchemaEditorLite/Modals/TableNameModal.vue
+++ b/frontend/src/components/SchemaEditorLite/Modals/TableNameModal.vue
@@ -63,8 +63,8 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
-const context = useSchemaEditorContext();
-const { addTab, markEditStatus } = context;
+const { addTab, markEditStatus, queuePendingScrollToTable } =
+ useSchemaEditorContext();
const inputRef = ref<InputInst>();
const notificationStore = useNotificationStore();
const mode = computed(() => {
@@ -139,6 +139,15 @@ const handleConfirmButtonClick = async () => {
table,
},
});
+
+ queuePendingScrollToTable({
+ db: props.database,
+ metadata: {
+ database: props.metadata,
+ schema: props.schema,
+ table,
+ },
+ });
} else {
const { table } = props;
table.name = state.tableName;
diff --git a/frontend/src/components/SchemaEditorLite/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditorLite/Panels/DatabaseEditor.vue
index 2d50dbd1ff..83cc8f5569 100644
--- a/frontend/src/components/SchemaEditorLite/Panels/DatabaseEditor.vue
+++ b/frontend/src/components/SchemaEditorLite/Panels/DatabaseEditor.vue
@@ -40,6 +40,14 @@
</template>
{{ $t("schema-editor.actions.add-from-template") }}
</NButton>
+ <div
+ v-if="selectedRolloutObjects"
+ class="text-sm flex flex-row items-center gap-x-2"
+ >
+ <span class="text-main">
+ {{ $t("branch.select-tables-to-rollout") }}
+ </span>
+ </div>
</div>
</div>
</div>
@@ -79,7 +87,7 @@
<div class="flex-1 overflow-y-hidden">
<!-- List view -->
<template v-if="state.selectedSubTab === 'table-list'">
- <tables
+ <TableList
v-if="selectedSchema"
:db="db"
:database="database"
@@ -151,7 +159,7 @@ import { SchemaTemplateSetting_TableTemplate } from "@/types/proto/v1/setting_se
import TableTemplates from "@/views/SchemaTemplate/TableTemplates.vue";
import TableNameModal from "../Modals/TableNameModal.vue";
import { useSchemaEditorContext } from "../context";
-import tables from "./TableList";
+import TableList from "./TableList";
const props = withDefaults(
defineProps<{
@@ -181,8 +189,15 @@ interface LocalState {
}
const context = useSchemaEditorContext();
-const { readonly, addTab, getSchemaStatus, markEditStatus, upsertTableConfig } =
- context;
+const {
+ readonly,
+ selectedRolloutObjects,
+ addTab,
+ getSchemaStatus,
+ markEditStatus,
+ upsertTableConfig,
+ queuePendingScrollToTable,
+} = context;
const state = reactive<LocalState>({
selectedSubTab: "table-list",
showFeatureModal: false,
@@ -341,5 +356,10 @@ const handleApplyTemplate = (template: SchemaTemplateSetting_TableTemplate) => {
database: db,
metadata: metadataForTable(),
});
+
+ queuePendingScrollToTable({
+ db,
+ metadata: metadataForTable(),
+ });
};
</script>
diff --git a/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/TableColumnEditor.vue b/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/TableColumnEditor.vue
index 2716b8f656..bf6b635fa7 100644
--- a/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/TableColumnEditor.vue
+++ b/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/TableColumnEditor.vue
@@ -1,13 +1,14 @@
<template>
<div
ref="containerElRef"
- class="w-full h-full"
+ class="w-full h-full overflow-x-auto"
:data-height="containerHeight"
:data-table-header-height="tableHeaderHeight"
:data-table-body-height="tableBodyHeight"
>
<NDataTable
v-bind="$attrs"
+ ref="dataTableRef"
size="small"
:row-key="getColumnKey"
:columns="columns"
@@ -62,7 +63,12 @@
<script lang="ts" setup>
import { useElementSize } from "@vueuse/core";
-import { DataTableColumn, NCheckbox, NDataTable } from "naive-ui";
+import {
+ DataTableColumn,
+ DataTableInst,
+ NCheckbox,
+ NDataTable,
+} from "naive-ui";
import { computed, h, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import SelectClassificationDrawer from "@/components/SchemaTemplate/SelectClassificationDrawer.vue";
@@ -164,14 +170,15 @@ const state = reactive<LocalState>({
showLabelsDrawer: false,
});
-const context = useSchemaEditorContext();
const {
resourceType,
markEditStatus,
getColumnStatus,
getColumnConfig,
upsertColumnConfig,
-} = context;
+ useConsumePendingScrollToColumn,
+} = useSchemaEditorContext();
+const dataTableRef = ref<DataTableInst>();
const containerElRef = ref<HTMLElement>();
const tableHeaderElRef = computed(
() =>
@@ -267,7 +274,7 @@ const columns = computed(() => {
key: "name",
title: t("schema-editor.column.name"),
resizable: true,
- width: 140,
+ minWidth: 140,
className: "input-cell",
render: (column) => {
return h(InlineInput, {
@@ -290,7 +297,8 @@ const columns = computed(() => {
key: "semantic-types",
title: t("settings.sensitive-data.semantic-types.self"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
hide: !showSemanticTypeColumn.value,
render: (column) => {
return h(SemanticTypeCell, {
@@ -313,7 +321,8 @@ const columns = computed(() => {
title: t("schema-editor.column.classification"),
hide: !classificationConfig.value,
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
render: (column) => {
return h(ClassificationCell, {
classification: column.classification,
@@ -334,7 +343,8 @@ const columns = computed(() => {
key: "type",
title: t("schema-editor.column.type"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
className: "input-cell",
render: (column) => {
return h(DataTypeCell, {
@@ -353,7 +363,8 @@ const columns = computed(() => {
key: "default-value",
title: t("schema-editor.column.default"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
className: "input-cell",
render: (column) => {
return h(DefaultValueCell, {
@@ -370,7 +381,8 @@ const columns = computed(() => {
key: "comment",
title: t("schema-editor.column.comment"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
className: "input-cell",
render: (column) => {
return h(InlineInput, {
@@ -393,7 +405,8 @@ const columns = computed(() => {
key: "not-null",
title: t("schema-editor.column.not-null"),
resizable: true,
- width: 80,
+ minWidth: 80,
+ maxWidth: 160,
className: "checkbox-cell",
render: (column) => {
return h(NCheckbox, {
@@ -413,7 +426,8 @@ const columns = computed(() => {
key: "primary",
title: t("schema-editor.column.primary"),
resizable: true,
- width: 80,
+ minWidth: 80,
+ maxWidth: 160,
className: "checkbox-cell",
render: (column) => {
return h(NCheckbox, {
@@ -429,7 +443,8 @@ const columns = computed(() => {
title: t("schema-editor.column.foreign-key"),
hide: !props.showForeignKey,
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
className: "text-cell",
render: (column) => {
return h(ForeignKeyCell, {
@@ -449,7 +464,8 @@ const columns = computed(() => {
key: "labels",
title: t("common.labels"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
hide: !showDatabaseConfigColumn.value,
render: (column) => {
return h(LabelsCell, {
@@ -631,6 +647,35 @@ const isDroppedColumn = (column: ColumnMetadata): boolean => {
const getColumnKey = (column: ColumnMetadata) => {
return markUUID(column);
};
+
+const vlRef = computed(() => {
+ return (dataTableRef.value as any)?.$refs?.mainTableInstRef?.bodyInstRef
+ ?.virtualListRef;
+});
+useConsumePendingScrollToColumn(
+ computed(() => ({
+ db: props.db,
+ metadata: {
+ database: props.database,
+ schema: props.schema,
+ table: props.table,
+ },
+ })),
+ vlRef,
+ (params, vl) => {
+ const key = getColumnKey(params.metadata.column);
+ if (!key) return;
+ requestAnimationFrame(() => {
+ try {
+ console.debug("scroll-to-column", vl, params, key);
+ vl.scrollTo({ key });
+ // TODO: focus name or type input element
+ } catch {
+ // Do nothing
+ }
+ });
+ }
+);
</script>
<style lang="postcss" scoped>
diff --git a/frontend/src/components/SchemaEditorLite/Panels/TableEditor.vue b/frontend/src/components/SchemaEditorLite/Panels/TableEditor.vue
index eab43f9ede..ca29d4183e 100644
--- a/frontend/src/components/SchemaEditorLite/Panels/TableEditor.vue
+++ b/frontend/src/components/SchemaEditorLite/Panels/TableEditor.vue
@@ -141,6 +141,7 @@ const {
getTableStatus,
getColumnStatus,
upsertColumnConfig,
+ queuePendingScrollToColumn,
} = useSchemaEditorContext();
const engine = computed(() => {
return props.db.instanceEntity.engine;
@@ -236,16 +237,15 @@ const handleAddColumn = () => {
props.table.columns.push(column);
markColumnStatus(column, "created");
- // TODO: scroll to the new column and focus its name textbox
- // table.value.columnList.push(column);
- // nextTick(() => {
- // const container = document.querySelector("#table-editor-container");
- // (
- // container?.querySelector(
- // `.column-${column.id} .column-name-input`
- // ) as HTMLInputElement
- // )?.focus();
- // });
+ queuePendingScrollToColumn({
+ db: props.db,
+ metadata: {
+ database: props.database,
+ schema: props.schema,
+ table: props.table,
+ column,
+ },
+ });
};
const handleApplyColumnTemplate = (
@@ -271,6 +271,15 @@ const handleApplyColumnTemplate = (
});
}
markColumnStatus(column, "created");
+ queuePendingScrollToColumn({
+ db: props.db,
+ metadata: {
+ database: props.database,
+ schema: props.schema,
+ table: props.table,
+ column,
+ },
+ });
};
const gotoForeignKeyReferencedTable = (
@@ -314,17 +323,15 @@ const gotoForeignKeyReferencedTable = (
},
});
- // TODO: scroll column into view
- // nextTick(() => {
- // const container = document.querySelector("#table-editor-container");
- // const input = container?.querySelector(
- // `.column-${referColumn.id} .column-name-input`
- // ) as HTMLInputElement | undefined;
- // if (input) {
- // input.focus();
- // scrollIntoView(input);
- // }
- // });
+ queuePendingScrollToColumn({
+ db: props.db,
+ metadata: {
+ database: props.database,
+ schema: referencedSchema,
+ table: referencedTable,
+ column: referencedColumn,
+ },
+ });
};
const handleEditColumnForeignKey = (
diff --git a/frontend/src/components/SchemaEditorLite/Panels/TableList/TableList.vue b/frontend/src/components/SchemaEditorLite/Panels/TableList/TableList.vue
index ccd6e79cca..1502924ceb 100644
--- a/frontend/src/components/SchemaEditorLite/Panels/TableList/TableList.vue
+++ b/frontend/src/components/SchemaEditorLite/Panels/TableList/TableList.vue
@@ -1,13 +1,14 @@
<template>
<div
ref="containerElRef"
- class="w-full h-full"
+ class="w-full h-full overflow-x-auto"
:data-height="containerHeight"
:data-table-header-height="tableHeaderHeight"
:data-table-body-height="tableBodyHeight"
>
<NDataTable
v-bind="$attrs"
+ ref="dataTableRef"
size="small"
:row-key="getTableKey"
:columns="columns"
@@ -18,7 +19,9 @@
:striped="true"
:bordered="true"
:bottom-bordered="true"
+ :checked-row-keys="checkedRowKeys"
class="schema-editor-table-list"
+ @update:checked-row-keys="handleUpdateCheckedRowKeys"
/>
</div>
@@ -55,12 +58,12 @@
<script lang="ts" setup>
import { useElementSize } from "@vueuse/core";
import { cloneDeep } from "lodash-es";
-import { DataTableColumn, NDataTable } from "naive-ui";
+import { DataTableColumn, DataTableInst, NDataTable } from "naive-ui";
import { computed, h, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import FeatureModal from "@/components/FeatureGuard/FeatureModal.vue";
import SelectClassificationDrawer from "@/components/SchemaTemplate/SelectClassificationDrawer.vue";
-import { Drawer, DrawerContent } from "@/components/v2";
+import { Drawer, DrawerContent, InlineInput } from "@/components/v2";
import { hasFeature, useSettingV1Store } from "@/store";
import { ComposedDatabase } from "@/types";
import {
@@ -74,6 +77,7 @@ import {
} from "@/types/proto/v1/setting_service";
import TableTemplates from "@/views/SchemaTemplate/TableTemplates.vue";
import { useSchemaEditorContext } from "../../context";
+import { RolloutObject } from "../../types";
import ClassificationCell from "../TableColumnEditor/components/ClassificationCell.vue";
import { markUUID } from "../common";
import { NameCell, OperationCell } from "./components";
@@ -94,17 +98,20 @@ interface LocalState {
}
const { t } = useI18n();
-const context = useSchemaEditorContext();
const {
+ events,
project,
readonly,
+ selectedRolloutObjects,
addTab,
markEditStatus,
removeEditStatus,
getSchemaStatus,
getTableStatus,
upsertTableConfig,
-} = context;
+ useConsumePendingScrollToTable,
+} = useSchemaEditorContext();
+const dataTableRef = ref<DataTableInst>();
const containerElRef = ref<HTMLElement>();
const tableHeaderElRef = computed(
() =>
@@ -135,6 +142,10 @@ const engine = computed(() => {
return props.db.instanceEntity.engine;
});
+const shouldShowSelectionColumn = computed(() => {
+ return !!selectedRolloutObjects.value;
+});
+
const classificationConfig = computed(() => {
if (!project.value.dataClassificationConfigId) {
return;
@@ -183,11 +194,16 @@ const isDroppedSchema = computed(() => {
const columns = computed(() => {
const columns: (DataTableColumn<TableMetadata> & { hide?: boolean })[] = [
+ {
+ type: "selection",
+ width: 32,
+ hide: !shouldShowSelectionColumn.value,
+ },
{
key: "name",
title: t("schema-editor.database.name"),
resizable: true,
- width: 140,
+ minWidth: 140,
className: "truncate",
render: (table) => {
return h(NameCell, {
@@ -200,7 +216,8 @@ const columns = computed(() => {
key: "classification",
title: t("schema-editor.column.classification"),
resizable: true,
- width: 140,
+ minWidth: 140,
+ maxWidth: 320,
hide: !classificationConfig.value,
render: (table) => {
return h(ClassificationCell, {
@@ -222,7 +239,8 @@ const columns = computed(() => {
key: "engine",
title: t("schema-editor.database.engine"),
resizable: true,
- width: 120,
+ minWidth: 120,
+ maxWidth: 180,
render: (table) => {
return table.engine;
},
@@ -231,7 +249,8 @@ const columns = computed(() => {
key: "collation",
title: t("schema-editor.database.collation"),
resizable: true,
- width: 120,
+ minWidth: 120,
+ maxWidth: 180,
ellipsis: true,
ellipsisComponent: "performant-ellipsis",
},
@@ -239,9 +258,26 @@ const columns = computed(() => {
key: "comment",
title: t("schema-editor.database.comment"),
resizable: true,
- width: 140,
- ellipsis: true,
- ellipsisComponent: "performant-ellipsis",
+ minWidth: 140,
+ maxWidth: 320,
+ className: "input-cell",
+ render: (table) => {
+ return h(InlineInput, {
+ value: table.userComment,
+ disabled:
+ readonly.value || isDroppedSchema.value || isDroppedTable(table),
+ placeholder: "comment",
+ style: {
+ "--n-padding-left": "6px",
+ "--n-padding-right": "4px",
+ "--n-text-color-disabled": "rgb(var(--color-main))",
+ },
+ "onUpdate:value": (value) => {
+ table.userComment = value;
+ markEditStatus(props.db, metadataForTable(table), "updated");
+ },
+ });
+ },
},
{
key: "operations",
@@ -318,6 +354,66 @@ const isDroppedTable = (table: TableMetadata) => {
const getTableKey = (table: TableMetadata) => {
return markUUID(table);
};
+
+const checkedRowKeys = computed(() => {
+ return selectedRolloutObjects.value
+ ?.filter((ro) => {
+ return (
+ ro.db.name === props.db.name &&
+ ro.metadata.schema.name === props.schema.name
+ );
+ })
+ .map((ro) => {
+ return getTableKey(ro.metadata.table);
+ });
+});
+const handleUpdateCheckedRowKeys = (keys: string[], rows: TableMetadata[]) => {
+ const selected = selectedRolloutObjects.value;
+ if (!selected) {
+ return;
+ }
+
+ const objectsInCurrentSchema = rows.map<RolloutObject>((table) => ({
+ db: props.db,
+ metadata: metadataForTable(table),
+ }));
+ const objectsOutCurrentSchema = selected.filter((ro) => {
+ return (
+ ro.db.name !== props.db.name ||
+ ro.metadata.schema.name !== props.schema.name
+ );
+ });
+ const mergedObjects = [...objectsOutCurrentSchema, ...objectsInCurrentSchema];
+
+ events.emit("update:selected-rollout-objects", mergedObjects);
+};
+
+const vlRef = computed(() => {
+ return (dataTableRef.value as any)?.$refs?.mainTableInstRef?.bodyInstRef
+ ?.virtualListRef;
+});
+useConsumePendingScrollToTable(
+ computed(() => ({
+ db: props.db,
+ metadata: {
+ database: props.database,
+ schema: props.schema,
+ },
+ })),
+ vlRef,
+ (params, vl) => {
+ const key = getTableKey(params.metadata.table);
+ if (!key) return;
+ requestAnimationFrame(() => {
+ try {
+ console.debug("scroll-to-table", vl, params, key);
+ vl.scrollTo({ key });
+ } catch {
+ // Do nothing
+ }
+ });
+ }
+);
</script>
<style lang="postcss" scoped>
@@ -325,6 +421,9 @@ const getTableKey = (table: TableMetadata) => {
:deep(.n-data-table-th .n-data-table-resize-button::after) {
@apply bg-control-bg h-2/3;
}
+.schema-editor-table-list :deep(.n-data-table-td.input-cell) {
+ @apply pl-0.5 pr-1 py-0;
+}
.schema-editor-table-list :deep(.n-data-table-tr.created .n-data-table-td) {
@apply text-green-700 !bg-green-50;
}
diff --git a/frontend/src/components/SchemaEditorLite/SchemaEditorLite.vue b/frontend/src/components/SchemaEditorLite/SchemaEditorLite.vue
index 5020de8bc8..583b53ca87 100644
--- a/frontend/src/components/SchemaEditorLite/SchemaEditorLite.vue
+++ b/frontend/src/components/SchemaEditorLite/SchemaEditorLite.vue
@@ -1,6 +1,6 @@
<template>
<div
- class="w-full h-full flex flex-col border rounded-lg overflow-hidden relative"
+ class="bb-schema-editor w-full h-full flex flex-col border rounded-lg overflow-hidden relative"
v-bind="$attrs"
>
<MaskSpinner v-if="combinedLoading" />
@@ -19,8 +19,10 @@
<script lang="ts" setup>
import { Splitpanes, Pane } from "splitpanes";
+import "splitpanes/dist/splitpanes.css";
import { reactive, computed, onMounted, toRef, watch } from "vue";
import MaskSpinner from "@/components/misc/MaskSpinner.vue";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import { useDatabaseV1Store, useSettingV1Store } from "@/store";
import { ComposedProject } from "@/types";
import { Branch } from "@/types/proto/v1/branch_service";
@@ -29,18 +31,22 @@ import Aside from "./Aside";
import Editor from "./Editor.vue";
import { useAlgorithm } from "./algorithm";
import { provideSchemaEditorContext } from "./context";
-import { EditTarget } from "./types";
+import { EditTarget, RolloutObject } from "./types";
const props = defineProps<{
project: ComposedProject;
resourceType: "database" | "branch";
readonly?: boolean;
+ selectedRolloutObjects?: RolloutObject[];
targets?: EditTarget[];
// NOTE: we only support editing one branch for now.
branch?: Branch;
loading?: boolean;
diffWhenReady?: boolean;
}>();
+const emit = defineEmits<{
+ (event: "update:selected-rollout-objects", objects: RolloutObject[]): void;
+}>();
interface LocalState {
diffing: boolean;
@@ -90,8 +96,10 @@ const context = provideSchemaEditorContext({
project: toRef(props, "project"),
resourceType: toRef(props, "resourceType"),
readonly: toRef(props, "readonly"),
+ selectedRolloutObjects: toRef(props, "selectedRolloutObjects"),
});
-const { rebuildMetadataEdit, applyMetadataEdit } = useAlgorithm(context);
+const { rebuildMetadataEdit, applyMetadataEdit, applySelectedMetadataEdit } =
+ useAlgorithm(context);
watch(
[ready, () => props.diffWhenReady],
@@ -109,35 +117,46 @@ watch(
{ immediate: true }
);
+useEmitteryEventListener(
+ context.events,
+ "update:selected-rollout-objects",
+ (objects) => {
+ emit("update:selected-rollout-objects", objects);
+ }
+);
+
defineExpose({
rebuildMetadataEdit,
applyMetadataEdit,
+ applySelectedMetadataEdit,
});
</script>
-<style>
-@import "splitpanes/dist/splitpanes.css";
-
+<style lang="postcss" scoped>
/* splitpanes pane style */
-.splitpanes.default-theme .splitpanes__pane {
+.bb-schema-editor :deep(.splitpanes.default-theme .splitpanes__pane) {
@apply bg-transparent !transition-none;
}
-.splitpanes.default-theme .splitpanes__splitter {
+.bb-schema-editor :deep(.splitpanes.default-theme .splitpanes__splitter) {
@apply bg-gray-100 border-none;
}
-.splitpanes.default-theme .splitpanes__splitter:hover {
+.bb-schema-editor :deep(.splitpanes.default-theme .splitpanes__splitter:hover) {
@apply bg-indigo-300;
}
-.splitpanes.default-theme .splitpanes__splitter::before,
-.splitpanes.default-theme .splitpanes__splitter::after {
+.bb-schema-editor
+ :deep(.splitpanes.default-theme .splitpanes__splitter::before),
+.bb-schema-editor
+ :deep(.splitpanes.default-theme .splitpanes__splitter::after) {
@apply bg-gray-700 opacity-50 text-white;
}
-.splitpanes.default-theme .splitpanes__splitter:hover::before,
-.splitpanes.default-theme .splitpanes__splitter:hover::after {
+.bb-schema-editor
+ :deep(.splitpanes.default-theme .splitpanes__splitter:hover::before),
+.bb-schema-editor
+ :deep(.splitpanes.default-theme .splitpanes__splitter:hover::after) {
@apply bg-white opacity-100;
}
</style>
diff --git a/frontend/src/components/SchemaEditorLite/TabsContainer.vue b/frontend/src/components/SchemaEditorLite/TabsContainer.vue
index d545163ceb..983f221919 100644
--- a/frontend/src/components/SchemaEditorLite/TabsContainer.vue
+++ b/frontend/src/components/SchemaEditorLite/TabsContainer.vue
@@ -20,13 +20,13 @@
>
<div class="flex flex-row justify-start items-center mr-1">
<span class="mr-1">
- <heroicons-outline:circle-stack
+ <DatabaseIcon
v-if="tab.type === 'database'"
- class="rounded w-4 h-auto text-gray-400"
+ class="w-4 h-4 text-gray-400"
/>
- <heroicons-outline:table-cells
+ <TableIcon
v-if="tab.type === 'table'"
- class="rounded w-4 h-auto text-gray-400"
+ class="w-4 h-4 text-gray-400"
/>
</span>
<NEllipsis
@@ -64,6 +64,7 @@ import { NEllipsis, NInput } from "naive-ui";
import scrollIntoView from "scroll-into-view-if-needed";
import { computed, nextTick, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
+import { DatabaseIcon, TableIcon } from "../Icon";
import { useSchemaEditorContext } from "./context";
import { TabContext } from "./types";
@@ -149,9 +150,13 @@ const getTabName = (tab: TabContext) => {
return database.databaseName;
} else if (tab.type === "table") {
const {
- metadata: { table },
+ metadata: { schema, table },
} = tab;
- return table.name;
+ const parts = [table.name];
+ if (schema.name) {
+ parts.unshift(schema.name);
+ }
+ return parts.join(".");
} else {
// Should never reach here.
return "unknown tab";
diff --git a/frontend/src/components/SchemaEditorLite/algorithm/diff-merge.ts b/frontend/src/components/SchemaEditorLite/algorithm/diff-merge.ts
index f8c5a7af21..47abcdb047 100644
--- a/frontend/src/components/SchemaEditorLite/algorithm/diff-merge.ts
+++ b/frontend/src/components/SchemaEditorLite/algorithm/diff-merge.ts
@@ -1,9 +1,12 @@
import { cloneDeep, isEqual } from "lodash-es";
import { ComposedDatabase } from "@/types";
import {
+ ColumnConfig,
ColumnMetadata,
DatabaseMetadata,
+ SchemaConfig,
SchemaMetadata,
+ TableConfig,
TableMetadata,
} from "@/types/proto/v1/database_service";
import { TinyTimer } from "@/utils";
@@ -20,6 +23,15 @@ type RichTableMetadata = RichSchemaMetadata & {
type RichColumnMetadata = RichTableMetadata & {
column: ColumnMetadata;
};
+type RichSchemaConfig = {
+ schemaConfig: SchemaConfig;
+};
+type RichTableConfig = RichSchemaConfig & {
+ tableConfig: TableConfig;
+};
+type RichColumnConfig = RichTableConfig & {
+ columnConfig: ColumnConfig;
+};
export class DiffMerge {
context: SchemaEditorContext;
@@ -32,8 +44,22 @@ export class DiffMerge {
targetTableMap = new Map<string, TableMetadata>();
sourceColumnMap = new Map<string, ColumnMetadata>();
targetColumnMap = new Map<string, ColumnMetadata>();
+ sourceSchemaConfigMap = new Map<string, SchemaConfig>();
+ targetSchemaConfigMap = new Map<string, SchemaConfig>();
+ sourceTableConfigMap = new Map<string, TableConfig>();
+ targetTableConfigMap = new Map<string, TableConfig>();
+ sourceColumnConfigMap = new Map<string, ColumnConfig>();
+ targetColumnConfigMap = new Map<string, ColumnConfig>();
timer = new TinyTimer<
- "merge" | "mergeSchemas" | "mergeTables" | "mergeColumns" | "diffColumn"
+ | "merge"
+ | "mergeSchemas"
+ | "mergeTables"
+ | "mergeColumns"
+ | "diffColumn"
+ | "mergeSchemaConfigs"
+ | "mergeTableConfigs"
+ | "mergeColumnConfigs"
+ | "diffColumnConfig"
>("DiffMerge");
constructor(
context: SchemaEditorContext,
@@ -49,6 +75,7 @@ export class DiffMerge {
merge() {
this.timer.begin("merge");
this.mergeSchemas();
+ this.mergeSchemaConfigs();
this.timer.end("merge");
}
mergeSchemas() {
@@ -59,12 +86,24 @@ export class DiffMerge {
targetMetadata,
sourceSchemaMap,
targetSchemaMap,
+ sourceSchemaConfigMap,
+ targetSchemaConfigMap,
} = this;
const sourceSchemas = sourceMetadata.schemas;
const targetSchemas = targetMetadata.schemas;
this.timer.begin("mergeSchemas");
mapSchemas(database, sourceSchemas, sourceSchemaMap);
mapSchemas(database, targetSchemas, targetSchemaMap);
+ mapSchemaConfigs(
+ database,
+ sourceMetadata.schemaConfigs,
+ sourceSchemaConfigMap
+ );
+ mapSchemaConfigs(
+ database,
+ targetMetadata.schemaConfigs,
+ targetSchemaConfigMap
+ );
const mergedSchemas: SchemaMetadata[] = [];
for (let i = 0; i < sourceSchemas.length; i++) {
@@ -134,6 +173,17 @@ export class DiffMerge {
{ ...source, table: sourceTable },
{ ...target, table: targetTable }
);
+ if (
+ !isEqual(sourceTable.classification, targetTable.classification) ||
+ !isEqual(sourceTable.userComment, targetTable.userComment) ||
+ !isEqual(sourceTable.foreignKeys, targetTable.foreignKeys) ||
+ !isEqual(sourceTable.indexes, targetTable.indexes)
+ ) {
+ // Index and foreignKey changes are considered as table updating by now
+ // for simplification
+ context.markEditStatusByKey(key, "updated");
+ }
+
continue;
}
// dropped table
@@ -246,6 +296,234 @@ export class DiffMerge {
}
this.timer.end("diffColumn", 1);
}
+ mergeSchemaConfigs() {
+ const {
+ context,
+ database,
+ sourceMetadata,
+ targetMetadata,
+ sourceSchemaConfigMap,
+ targetSchemaConfigMap,
+ } = this;
+ this.timer.begin("mergeSchemaConfigs");
+ const sourceSchemaConfigs = sourceMetadata.schemaConfigs;
+ const targetSchemaConfigs = targetMetadata.schemaConfigs;
+ mapSchemaConfigs(database, sourceSchemaConfigs, sourceSchemaConfigMap);
+ mapSchemaConfigs(database, targetSchemaConfigs, targetSchemaConfigMap);
+ const mergedSchemaConfigs: SchemaConfig[] = [];
+ for (let i = 0; i < targetMetadata.schemas.length; i++) {
+ const schema = targetMetadata.schemas[i];
+ const key = keyForResourceName(database.name, schema.name);
+ const sourceSchemaConfig = sourceSchemaConfigMap.get(key);
+ const targetSchemaConfig = targetSchemaConfigMap.get(key);
+ const schemaStatus = context.getEditStatusByKey(key);
+ if (schemaStatus === "dropped") {
+ // copy source schemaConfig for further restoring
+ if (sourceSchemaConfig) {
+ mergedSchemaConfigs.push(cloneDeep(sourceSchemaConfig));
+ }
+ } else if (schemaStatus === "created") {
+ // use newly created schemaConfig
+ if (targetSchemaConfig) {
+ mergedSchemaConfigs.push(targetSchemaConfig);
+ }
+ } else {
+ // use the updated schemaConfig and diff recursively
+ if (targetSchemaConfig) {
+ mergedSchemaConfigs.push(targetSchemaConfig);
+ }
+ this.mergeTableConfigs(
+ schema,
+ {
+ schemaConfig:
+ sourceSchemaConfig ??
+ SchemaConfig.fromPartial({ name: schema.name }),
+ },
+ {
+ schemaConfig:
+ targetSchemaConfig ??
+ SchemaConfig.fromPartial({ name: schema.name }),
+ }
+ );
+ }
+ }
+ targetMetadata.schemaConfigs = mergedSchemaConfigs;
+ this.timer.end("mergeSchemaConfigs", targetMetadata.schemas.length);
+ }
+ mergeTableConfigs(
+ schema: SchemaMetadata,
+ source: RichSchemaConfig,
+ target: RichSchemaConfig
+ ) {
+ const { context, database, sourceTableConfigMap, targetTableConfigMap } =
+ this;
+ const { schemaConfig: sourceSchemaConfig } = source;
+ const { schemaConfig: targetSchemaConfig } = target;
+ const sourceTableConfigs = sourceSchemaConfig.tableConfigs;
+ const targetTableConfigs = targetSchemaConfig.tableConfigs;
+ this.timer.begin("mergeTableConfigs");
+ mapTableConfigs(
+ database,
+ sourceSchemaConfig,
+ sourceTableConfigs,
+ sourceTableConfigMap
+ );
+ mapTableConfigs(
+ database,
+ targetSchemaConfig,
+ targetTableConfigs,
+ targetTableConfigMap
+ );
+ const mergedTableConfigs: TableConfig[] = [];
+ for (let i = 0; i < schema.tables.length; i++) {
+ const table = schema.tables[i];
+ const key = keyForResourceName(database.name, schema.name, table.name);
+ const sourceTableConfig = sourceTableConfigMap.get(key);
+ const targetTableConfig = targetTableConfigMap.get(key);
+ const tableStatus = context.getEditStatusByKey(key);
+ if (tableStatus === "dropped") {
+ // copy source tableConfig for further restoring
+ if (sourceTableConfig) {
+ mergedTableConfigs.push(cloneDeep(sourceTableConfig));
+ }
+ } else if (tableStatus === "created") {
+ // use newly created tableConfig
+ if (targetTableConfig) {
+ mergedTableConfigs.push(targetTableConfig);
+ }
+ } else {
+ // use the updated tableConfig and diff recursively
+ if (targetTableConfig) {
+ mergedTableConfigs.push(targetTableConfig);
+ }
+ this.mergeColumnConfigs(
+ schema,
+ table,
+ {
+ ...source,
+ tableConfig:
+ sourceTableConfig ??
+ TableConfig.fromPartial({ name: table.name }),
+ },
+ {
+ ...target,
+ tableConfig:
+ targetTableConfig ??
+ TableConfig.fromPartial({ name: table.name }),
+ }
+ );
+ }
+ }
+ targetSchemaConfig.tableConfigs = mergedTableConfigs;
+ this.timer.end("mergeTableConfigs", schema.tables.length);
+ }
+ mergeColumnConfigs(
+ schema: SchemaMetadata,
+ table: TableMetadata,
+ source: RichTableConfig,
+ target: RichTableConfig
+ ) {
+ const { context, database, sourceColumnConfigMap, targetColumnConfigMap } =
+ this;
+ const { schemaConfig: sourceSchemaConfig, tableConfig: sourceTableConfig } =
+ source;
+ const { schemaConfig: targetSchemaConfig, tableConfig: targetTableConfig } =
+ target;
+ const sourceColumnConfigs = sourceTableConfig.columnConfigs;
+ const targetColumnConfigs = targetTableConfig.columnConfigs;
+ this.timer.begin("mergeColumnConfigs");
+ mapColumnConfigs(
+ database,
+ sourceSchemaConfig,
+ sourceTableConfig,
+ sourceColumnConfigs,
+ sourceColumnConfigMap
+ );
+ mapColumnConfigs(
+ database,
+ targetSchemaConfig,
+ targetTableConfig,
+ targetColumnConfigs,
+ targetColumnConfigMap
+ );
+ const mergedColumnConfigs: ColumnConfig[] = [];
+ for (let i = 0; i < table.columns.length; i++) {
+ const column = table.columns[i];
+ const key = keyForResourceName(
+ database.name,
+ schema.name,
+ table.name,
+ column.name
+ );
+ const sourceColumnConfig = sourceColumnConfigMap.get(key);
+ const targetColumnConfig = targetColumnConfigMap.get(key);
+ const columnStatus = context.getEditStatusByKey(key);
+ if (columnStatus === "dropped") {
+ // copy source columnConfig for further restoring
+ if (sourceColumnConfig) {
+ mergedColumnConfigs.push(cloneDeep(sourceColumnConfig));
+ }
+ } else if (columnStatus === "created") {
+ // use newly created columnConfig
+ if (targetColumnConfig) {
+ mergedColumnConfigs.push(targetColumnConfig);
+ }
+ } else {
+ // use the updated columnConfig and diff recursively
+ if (targetColumnConfig) {
+ mergedColumnConfigs.push(targetColumnConfig);
+ }
+ this.diffColumnConfig(
+ schema,
+ table,
+ column,
+ {
+ ...source,
+ columnConfig:
+ sourceColumnConfig ??
+ ColumnConfig.fromPartial({ name: column.name }),
+ },
+ {
+ ...target,
+ columnConfig:
+ targetColumnConfig ??
+ ColumnConfig.fromPartial({ name: column.name }),
+ }
+ );
+ }
+ }
+ targetTableConfig.columnConfigs = mergedColumnConfigs;
+ this.timer.end("mergeColumnConfigs", table.columns.length);
+ }
+ diffColumnConfig(
+ schema: SchemaMetadata,
+ table: TableMetadata,
+ column: ColumnMetadata,
+ source: RichColumnConfig,
+ target: RichColumnConfig
+ ) {
+ const { columnConfig: sourceColumnConfig } = source;
+ const {
+ schemaConfig: targetSchemaConfig,
+ tableConfig: targetTableConfig,
+ columnConfig: targetColumnConfig,
+ } = target;
+ this.timer.begin("diffColumnConfig");
+
+ if (!isEqual(sourceColumnConfig, targetColumnConfig)) {
+ const key = keyForResourceName(
+ this.database.name,
+ targetSchemaConfig.name,
+ targetTableConfig.name,
+ targetColumnConfig.name
+ );
+ const status = this.context.getEditStatusByKey(key);
+ if (status !== "created" && status !== "dropped") {
+ this.context.markEditStatusByKey(key, "updated");
+ }
+ }
+ this.timer.end("diffColumnConfig", 1);
+ }
}
const mapSchemas = (
@@ -286,3 +564,46 @@ const mapColumns = (
map.set(key, column);
});
};
+const mapSchemaConfigs = (
+ db: ComposedDatabase,
+ schemaConfigs: SchemaConfig[],
+ map: Map<string, SchemaConfig>
+) => {
+ schemaConfigs.forEach((schemaConfig) => {
+ const key = keyForResourceName(db.name, schemaConfig.name);
+ map.set(key, schemaConfig);
+ });
+};
+const mapTableConfigs = (
+ db: ComposedDatabase,
+ schemaConfig: SchemaConfig,
+ tableConfigs: TableConfig[],
+ map: Map<string, TableConfig>
+) => {
+ tableConfigs.forEach((tableConfig) => {
+ const key = keyForResourceName(
+ db.name,
+ schemaConfig.name,
+ tableConfig.name
+ );
+ map.set(key, tableConfig);
+ });
+};
+
+const mapColumnConfigs = (
+ db: ComposedDatabase,
+ schemaConfig: SchemaConfig,
+ tableConfig: TableConfig,
+ columnConfigs: ColumnConfig[],
+ map: Map<string, ColumnConfig>
+) => {
+ columnConfigs.forEach((columnConfig) => {
+ const key = keyForResourceName(
+ db.name,
+ schemaConfig.name,
+ tableConfig.name,
+ columnConfig.name
+ );
+ map.set(key, columnConfig);
+ });
+};
diff --git a/frontend/src/components/SchemaEditorLite/algorithm/index.ts b/frontend/src/components/SchemaEditorLite/algorithm/index.ts
index 896668b97b..5e521f5f14 100644
--- a/frontend/src/components/SchemaEditorLite/algorithm/index.ts
+++ b/frontend/src/components/SchemaEditorLite/algorithm/index.ts
@@ -1,3 +1,4 @@
+import { cloneDeep } from "lodash-es";
import { ComposedDatabase } from "@/types";
import {
DatabaseMetadata,
@@ -8,6 +9,8 @@ import {
} from "@/types/proto/v1/database_service";
import { keyBy } from "@/utils";
import { SchemaEditorContext } from "../context";
+import { keyForResource, keyForResourceName } from "../context/common";
+import { RolloutObject } from "../types";
import { DiffMerge } from "./diff-merge";
export const useAlgorithm = (context: SchemaEditorContext) => {
@@ -66,7 +69,116 @@ export const useAlgorithm = (context: SchemaEditorContext) => {
cleanupUnusedConfigs(metadata);
};
- return { rebuildMetadataEdit, applyMetadataEdit };
+ const applySelectedMetadataEdit = (
+ db: ComposedDatabase,
+ source: DatabaseMetadata,
+ target: DatabaseMetadata,
+ selectedRolloutObjects: RolloutObject[]
+ ) => {
+ const selectedObjectKeys = new Set(
+ selectedRolloutObjects.map((ro) => keyForResource(ro.db, ro.metadata))
+ );
+ const sourceTableMap = new Map(
+ source.schemas.flatMap((schema) => {
+ return schema.tables.map((table) => {
+ const key = keyForResource(db, {
+ schema,
+ table,
+ });
+ return [key, { schema, table }];
+ });
+ })
+ );
+ const sourceTableConfigMap = new Map(
+ source.schemaConfigs.flatMap((schemaConfig) => {
+ return schemaConfig.tableConfigs.map((tableConfig) => {
+ const key = keyForResourceName(
+ db.name,
+ schemaConfig.name,
+ tableConfig.name
+ );
+ return [key, { schemaConfig, tableConfig }];
+ });
+ })
+ );
+
+ const applyTableEdits = (schema: SchemaMetadata, table: TableMetadata) => {
+ // Drop columns
+ target.schemas.forEach((schema) => {
+ schema.tables.forEach((table) => {
+ table.columns = table.columns.filter((column) => {
+ const status = getColumnStatus(db, {
+ database: target,
+ schema,
+ table,
+ column,
+ });
+ return status !== "dropped";
+ });
+ });
+ });
+ };
+
+ const schemaConfigs: SchemaConfig[] = [];
+ for (let i = 0; i < target.schemas.length; i++) {
+ const schema = target.schemas[i];
+ const schemaConfig = SchemaConfig.fromPartial({ name: schema.name });
+ const targetSchemaConfig = target.schemaConfigs.find(
+ (sc) => sc.name === schema.name
+ );
+ const tables: TableMetadata[] = [];
+ for (let j = 0; j < schema.tables.length; j++) {
+ const table = schema.tables[j];
+ const key = keyForResource(db, { schema, table });
+ const picked = selectedObjectKeys.has(key);
+ if (picked) {
+ const status = getTableStatus(db, {
+ database: target,
+ schema,
+ table,
+ });
+ if (status === "dropped") {
+ // Drop table
+ // Don't collect the dropped table
+ continue;
+ } else {
+ // Collect the edited table
+ tables.push(table);
+ // Together with its tableConfig
+ const tableConfig = targetSchemaConfig?.tableConfigs.find(
+ (tc) => tc.name === table.name
+ );
+ if (tableConfig) {
+ schemaConfig.tableConfigs.push(tableConfig);
+ }
+ // apply column edits for non-pending-creating (existed and updated) tables
+ if (status !== "created") {
+ applyTableEdits(schema, table);
+ }
+ }
+ } else {
+ const sourceTable = sourceTableMap.get(key);
+ if (sourceTable) {
+ // Collect the original table
+ tables.push(cloneDeep(sourceTable.table));
+ // Together with its tableConfig
+ const sourceTableConfig =
+ sourceTableConfigMap.get(key)?.tableConfig;
+ if (sourceTableConfig) {
+ schemaConfig.tableConfigs.push(cloneDeep(sourceTableConfig));
+ }
+ }
+ }
+ }
+ schema.tables = tables;
+ if (schemaConfig.tableConfigs.length > 0) {
+ schemaConfigs.push(schemaConfig);
+ }
+ }
+ target.schemaConfigs = schemaConfigs;
+ };
+
+ return { rebuildMetadataEdit, applyMetadataEdit, applySelectedMetadataEdit };
};
const cleanupUnusedConfigs = (metadata: DatabaseMetadata) => {
diff --git a/frontend/src/components/SchemaEditorLite/context/edit.ts b/frontend/src/components/SchemaEditorLite/context/edit.ts
index ab6cbbbacb..55d0962c27 100644
--- a/frontend/src/components/SchemaEditorLite/context/edit.ts
+++ b/frontend/src/components/SchemaEditorLite/context/edit.ts
@@ -33,6 +33,10 @@ export const useEditStatus = () => {
dirtyPaths.value.set(key, status);
};
+ const getEditStatusByKey = (key: string) => {
+ return dirtyPaths.value.get(key);
+ };
+
const removeEditStatus = (
database: ComposedDatabase,
metadata: {
@@ -112,8 +116,10 @@ export const useEditStatus = () => {
};
return {
+ dirtyPaths,
markEditStatus,
markEditStatusByKey,
+ getEditStatusByKey,
removeEditStatus,
clearEditStatus,
getSchemaStatus,
diff --git a/frontend/src/components/SchemaEditorLite/context/index.ts b/frontend/src/components/SchemaEditorLite/context/index.ts
index 52d67fd308..ebea6e5039 100644
--- a/frontend/src/components/SchemaEditorLite/context/index.ts
+++ b/frontend/src/components/SchemaEditorLite/context/index.ts
@@ -1,23 +1,32 @@
+import Emittery from "emittery";
import { Ref, inject, provide } from "vue";
import { ComposedProject } from "@/types";
-import { EditTarget, ResourceType } from "../types";
+import { EditTarget, ResourceType, RolloutObject } from "../types";
import { useEditConfigs } from "./config";
import { useEditStatus } from "./edit";
+import { useScrollStatus } from "./scroll";
import { useTabs } from "./tabs";
export const KEY = Symbol("bb.schema-editor");
+export type SchemaEditorEvents = Emittery<{
+ ["update:selected-rollout-objects"]: RolloutObject[];
+}>;
+
export const provideSchemaEditorContext = (params: {
resourceType: Ref<ResourceType>;
readonly: Ref<boolean>;
project: Ref<ComposedProject>;
targets: Ref<EditTarget[]>;
+ selectedRolloutObjects: Ref<RolloutObject[] | undefined>;
}) => {
const context = {
+ events: new Emittery() as SchemaEditorEvents,
...params,
...useTabs(),
...useEditStatus(),
...useEditConfigs(params.targets),
+ ...useScrollStatus(),
};
provide(KEY, context);
diff --git a/frontend/src/components/SchemaEditorLite/context/scroll.ts b/frontend/src/components/SchemaEditorLite/context/scroll.ts
new file mode 100644
index 0000000000..d4d59fc20c
--- /dev/null
+++ b/frontend/src/components/SchemaEditorLite/context/scroll.ts
@@ -0,0 +1,112 @@
+import { useMounted } from "@vueuse/core";
+import { Ref, computed, ref, watch } from "vue";
+import { ComposedDatabase } from "@/types";
+import {
+ ColumnMetadata,
+ DatabaseMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto/v1/database_service";
+
+type RichSchemaMetadata = {
+ database: DatabaseMetadata;
+ schema: SchemaMetadata;
+};
+type RichTableMetadata = RichSchemaMetadata & {
+ table: TableMetadata;
+};
+type RichColumnMetadata = RichTableMetadata & {
+ column: ColumnMetadata;
+ // field?: "name" | "type"; // TODO
+};
+type RichMetadataWithDB<T> = {
+ db: ComposedDatabase;
+ metadata: T;
+};
+
+export const useScrollStatus = () => {
+ const pendingScrollToTable = ref<RichMetadataWithDB<RichTableMetadata>>();
+ const pendingScrollToColumn = ref<RichMetadataWithDB<RichColumnMetadata>>();
+ const useConsumePendingScrollToTable = <TContext>(
+ condition: Ref<RichMetadataWithDB<RichSchemaMetadata>>,
+ context: Ref<TContext>,
+ fn: (
+ params: RichMetadataWithDB<RichTableMetadata>,
+ context: TContext
+ ) => void
+ ) => {
+ const mounted = useMounted();
+ const matched = computed(() => {
+ const pending = pendingScrollToTable.value;
+ if (!pending) return false;
+ return (
+ pending.db.name === condition.value.db.name &&
+ pending.metadata.schema.name === condition.value.metadata.schema.name
+ );
+ });
+ watch(
+ [mounted, matched, context, pendingScrollToTable],
+ ([mounted, matched, context, pending]) => {
+ if (!mounted) return;
+ if (!matched) return;
+ if (!context) return;
+ if (!pending) return;
+ fn(pending, context);
+ pendingScrollToTable.value = undefined;
+ },
+ { immediate: true }
+ );
+ };
+ const useConsumePendingScrollToColumn = <TContext>(
+ condition: Ref<RichMetadataWithDB<RichTableMetadata>>,
+ context: Ref<TContext>,
+ fn: (
+ params: RichMetadataWithDB<RichColumnMetadata>,
+ context: TContext
+ ) => void
+ ) => {
+ const mounted = useMounted();
+ const matched = computed(() => {
+ const pending = pendingScrollToColumn.value;
+ if (!pending) return false;
+ return (
+ pending.db.name === condition.value.db.name &&
+ pending.metadata.schema.name === condition.value.metadata.schema.name &&
+ pending.metadata.table.name === condition.value.metadata.table.name
+ );
+ });
+ watch(
+ [mounted, matched, context, pendingScrollToColumn],
+ ([mounted, matched, context, pending]) => {
+ if (!mounted) return;
+ if (!matched) return;
+ if (!context) return;
+ if (!pending) return;
+ fn(pending, context);
+ pendingScrollToColumn.value = undefined;
+ },
+ { immediate: true }
+ );
+ };
+ const queuePendingScrollToTable = (
+ params: RichMetadataWithDB<RichTableMetadata>
+ ) => {
+ requestAnimationFrame(() => {
+ pendingScrollToTable.value = params;
+ });
+ };
+ const queuePendingScrollToColumn = (
+ params: RichMetadataWithDB<RichColumnMetadata>
+ ) => {
+ requestAnimationFrame(() => {
+ pendingScrollToColumn.value = params;
+ });
+ };
+
+ return {
+ queuePendingScrollToTable,
+ queuePendingScrollToColumn,
+ useConsumePendingScrollToTable,
+ useConsumePendingScrollToColumn,
+ };
+};
diff --git a/frontend/src/components/SchemaEditorLite/types.ts b/frontend/src/components/SchemaEditorLite/types.ts
index 0975243e1c..cb3c9bec46 100644
--- a/frontend/src/components/SchemaEditorLite/types.ts
+++ b/frontend/src/components/SchemaEditorLite/types.ts
@@ -48,3 +48,16 @@ export type CoreTabContext =
| Omit<TableTabContext, "id">;
export type EditStatus = "normal" | "created" | "dropped" | "updated";
+
+/**
+ * Only tables are selectable rollout objects by now
+ */
+export type RolloutObject = {
+ db: ComposedDatabase;
+ metadata: {
+ database: DatabaseMetadata;
+ schema: SchemaMetadata;
+ table: TableMetadata;
+ // column?: ColumnMetadata; // Columns are not selectable by now
+ };
+};
diff --git a/frontend/src/components/v2/Select/DatabaseSelect.vue b/frontend/src/components/v2/Select/DatabaseSelect.vue
index d31c5e1624..271ae74815 100644
--- a/frontend/src/components/v2/Select/DatabaseSelect.vue
+++ b/frontend/src/components/v2/Select/DatabaseSelect.vue
@@ -1,6 +1,6 @@
<template>
<NSelect
- :value="database"
+ :value="database ?? null"
:options="options"
:placeholder="placeholder ?? $t('database.select')"
:virtual-scroll="true"
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 4633e33754..4f8cc8f110 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1168,7 +1168,8 @@
"approvers-of-current-step": "Approvers of current step"
},
"unfinished-resolved-issue-tips": "This issue is marked as \"Done\" but some of its tasks are not executed successfully.",
- "some-tasks-are-not-executed-successfully": "(Some tasks are not executed successfully)"
+ "some-tasks-are-not-executed-successfully": "(Some tasks are not executed successfully)",
+ "preview": "Preview issue"
},
"alter-schema": {
"vcs-enabled": "This project has enabled VCS based version control and selecting database below will navigate you to the corresponding Git repository to initiate the change process.",
@@ -3349,5 +3350,11 @@
"export-rows-must-gt-zero": "Export rows must greater than 0"
},
"export-format": "Export format"
+ },
+ "branch": {
+ "rollout": {
+ "select-target-database": "Select target database"
+ },
+ "select-tables-to-rollout": "Select tables to rollout"
}
}
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 6416cc130f..acd206aa48 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1167,7 +1167,8 @@
"approvers-of-current-step": "Aprobadores del paso actual"
},
"unfinished-resolved-issue-tips": "Este problema está marcado como \"Listo\", pero algunas de sus tareas no se ejecutan correctamente.",
- "some-tasks-are-not-executed-successfully": "(Algunas tareas no se ejecutan correctamente)"
+ "some-tasks-are-not-executed-successfully": "(Algunas tareas no se ejecutan correctamente)",
+ "preview": "Problema de vista previa"
},
"alter-schema": {
"vcs-enabled": "Este proyecto ha habilitado el control de versiones basado en VCS y seleccionar la base de datos a continuación lo llevará al repositorio Git correspondiente para iniciar el proceso de cambio.",
@@ -3347,5 +3348,11 @@
"export-rows-must-gt-zero": "Las filas de exportación deben ser mayores que 0"
},
"export-format": "Formato de exportación"
+ },
+ "branch": {
+ "rollout": {
+ "select-target-database": "Seleccionar base de datos de destino"
+ },
+ "select-tables-to-rollout": "Seleccionar tablas para implementar"
}
}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index faa4686f7a..19503c2501 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1165,7 +1165,8 @@
"approvers-of-current-step": "当前步骤的审批人"
},
"unfinished-resolved-issue-tips": "该工单被标记为「已完成」,但其中某些任务并未成功执行。",
- "some-tasks-are-not-executed-successfully": "(部分任务并未成功执行)"
+ "some-tasks-are-not-executed-successfully": "(部分任务并未成功执行)",
+ "preview": "预览工单"
},
"alter-schema": {
"vcs-enabled": "该项目开启了基于 VCS 的版本管理,选择下面的数据库会将您导航到相应的 Git 仓库以发起变更流程。",
@@ -3342,5 +3343,11 @@
"export-rows-must-gt-zero": "导出行数必须大于 0"
},
"export-format": "导出格式"
+ },
+ "branch": {
+ "rollout": {
+ "select-target-database": "选择目标数据库"
+ },
+ "select-tables-to-rollout": "选择要发布的表"
}
}
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 45b4fbe9c8..e6b10a5b6a 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -696,6 +696,15 @@ const routes: Array<RouteRecordRaw> = [
component: () => import("../views/branch/BranchDetail.vue"),
props: true,
},
+ {
+ path: "branches/:branchName/rollout",
+ name: "workspace.project.branch.rollout",
+ meta: {
+ overrideTitle: true,
+ },
+ component: () => import("../views/branch/BranchRollout.vue"),
+ props: true,
+ },
{
path: "changelists/:changelistName",
name: "workspace.project.changelist.detail",
diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.ts
index 5fb4ee9720..bd111b330b 100644
--- a/frontend/src/store/modules/user.ts
+++ b/frontend/src/store/modules/user.ts
@@ -140,7 +140,7 @@ export const useUserStore = defineStore("user", {
});
export const extractUserEmail = (emailResource: string) => {
- const matches = emailResource.match(/^user:(.+)$/);
+ const matches = emailResource.match(/^(?:user:|users\/)(.+)$/);
return matches?.[1] ?? emailResource;
};
diff --git a/frontend/src/views/branch/BranchDetail.vue b/frontend/src/views/branch/BranchDetail.vue
index dcef4b26bd..889c83b071 100644
--- a/frontend/src/views/branch/BranchDetail.vue
+++ b/frontend/src/views/branch/BranchDetail.vue
@@ -10,6 +10,7 @@
:project="project"
:clean-branch="branch.clean"
:dirty-branch="branch.dirty"
+ :readonly="!allowEdit"
v-bind="$attrs"
@update:branch-id="handleUpdateBranchId"
/>
@@ -28,10 +29,10 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import BranchCreateView from "@/components/Branch/BranchCreateView.vue";
import BranchDetailView from "@/components/Branch/BranchDetailView.vue";
-import { useProjectV1Store } from "@/store";
+import { extractUserEmail, useCurrentUserV1, useProjectV1Store } from "@/store";
import { useBranchStore } from "@/store/modules/branch";
import { Branch } from "@/types/proto/v1/branch_service";
-import { idFromSlug } from "@/utils";
+import { idFromSlug, isOwnerOfProjectV1 } from "@/utils";
const props = defineProps<{
projectSlug: string;
@@ -40,6 +41,7 @@ const props = defineProps<{
const { t } = useI18n();
const router = useRouter();
+const me = useCurrentUserV1();
const projectStore = useProjectV1Store();
const branchStore = useBranchStore();
const branchFullName = ref<string>("");
@@ -56,6 +58,14 @@ const project = computed(() => {
String(idFromSlug(props.projectSlug as string))
);
});
+const allowEdit = computed(() => {
+ if (!project.value) return false;
+ if (!branch.value) return false;
+ if (isOwnerOfProjectV1(project.value.iamPolicy, me.value)) {
+ return true;
+ }
+ return extractUserEmail(branch.value.clean.creator) === me.value.email;
+});
const handleUpdateBranchId = (id: string) => {
if (!branch.value) return;
diff --git a/frontend/src/views/branch/BranchRollout.vue b/frontend/src/views/branch/BranchRollout.vue
new file mode 100644
index 0000000000..9cd0a23139
--- /dev/null
+++ b/frontend/src/views/branch/BranchRollout.vue
@@ -0,0 +1,87 @@
+<template>
+ <div class="w-full h-full relative">
+ <BranchRolloutView
+ v-if="project && ready && branch"
+ :project="project"
+ :branch="branch"
+ v-bind="$attrs"
+ />
+ <MaskSpinner v-else />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { useTitle } from "@vueuse/core";
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import BranchRolloutView from "@/components/Branch/BranchRolloutView";
+import { useProjectV1Store } from "@/store";
+import { useBranchStore } from "@/store/modules/branch";
+import { Branch } from "@/types/proto/v1/branch_service";
+import { idFromSlug } from "@/utils";
+
+const props = defineProps<{
+ projectSlug: string;
+ branchName: string;
+}>();
+
+const { t } = useI18n();
+const router = useRouter();
+const projectStore = useProjectV1Store();
+const branchStore = useBranchStore();
+const branchFullName = ref<string>("");
+const ready = ref<boolean>(false);
+
+const project = computed(() => {
+ if (props.projectSlug === "-") {
+ return;
+ }
+ return projectStore.getProjectByUID(
+ String(idFromSlug(props.projectSlug as string))
+ );
+});
+const branch = ref<Branch>();
+
+watch(
+ [() => props.projectSlug, () => props.branchName],
+ async () => {
+ // Prepare branch name from route params.
+ const branchId = props.branchName;
+ if (!branchId || !project.value) {
+ return;
+ }
+ branchFullName.value = `${project.value.name}/branches/${branchId}`;
+ },
+ {
+ immediate: true,
+ }
+);
+
+watch(
+ () => branchFullName.value,
+ async () => {
+ ready.value = false;
+ const br = await branchStore.fetchBranchByName(
+ branchFullName.value,
+ false /* useCache */
+ );
+ branch.value = br;
+ if (!br) {
+ router.replace("error.404");
+ }
+ ready.value = true;
+ },
+ {
+ immediate: true,
+ }
+);
+
+const documentTitle = computed(() => {
+ if (branch.value) {
+ return branch.value.branchId;
+ }
+ return t("common.loading");
+});
+useTitle(documentTitle);
+</script>