Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): Changelist UI (#8481)
Liu Jib62c7462fad7
diff --git a/frontend/src/components/Breadcrumb.vue b/frontend/src/components/Breadcrumb.vueindex ec22e32854..c4c1604860 100644--- a/frontend/src/components/Breadcrumb.vue+++ b/frontend/src/components/Breadcrumb.vue@@ -77,8 +77,8 @@ import {getProjectAndSheetId,projectNamePrefix,} from "@/store/modules/v1/common";+import { RouteMapList } from "@/types";import { Bookmark } from "@/types/proto/v1/bookmark_service";-import { RouteMapList } from "../types";import { databaseV1Slug, idFromSlug, projectV1Slug } from "../utils";interface BreadcrumbItem {@@ -243,6 +243,12 @@ export default defineComponent({path: `/db/${databaseV1Slug(database)}#change-history`,});}+ if (route.name === "workspace.changelist.detail") {+ list.push({+ name: t("changelist.self"),+ path: `/changelists`,+ });+ }const {title: routeTitle,diff --git a/frontend/src/components/DatabaseChangeHistoryPanel.vue b/frontend/src/components/DatabaseChangeHistoryPanel.vueindex c0c6801c48..198f89f6fe 100644--- a/frontend/src/components/DatabaseChangeHistoryPanel.vue+++ b/frontend/src/components/DatabaseChangeHistoryPanel.vue@@ -120,7 +120,7 @@ import { BBTableSectionDataSource } from "@/bbkit/types";import { ChangeHistoryTable } from "@/components/ChangeHistory";import { useChangeHistoryStore, useDBSchemaV1Store } from "@/store";import { ComposedDatabase, DEFAULT_PROJECT_V1_NAME } from "@/types";-import { AffectedTable } from "@/types/changeHistory";+import { AffectedTable, EmptyAffectedTable } from "@/types/changeHistory";import {ChangeHistory,ChangeHistory_Status,@@ -134,12 +134,6 @@ import {getHistoryChangeType,} from "@/utils";-const EmptyAffectedTable: AffectedTable = {- schema: "",- table: "",- dropped: false,-};-interface LocalState {showBaselineModal: boolean;loading: boolean;diff --git a/frontend/src/components/DatabaseInfo.vue b/frontend/src/components/DatabaseInfo.vueindex 06e8e8911c..df8714f648 100644--- a/frontend/src/components/DatabaseInfo.vue+++ b/frontend/src/components/DatabaseInfo.vue@@ -3,7 +3,8 @@<InstanceV1Name:instance="database.instanceEntity":plain="true"- text-class="hover:underline"+ :link="link"+ :text-class="link ? 'hover:underline' : ''"><templatev-if="@@ -15,7 +16,8 @@:environment="database.instanceEntity.environmentEntity":plain="true":show-icon="false"- text-class="hover:underline text-control-light"+ :link="link"+ :text-class="`text-control-light ${link ? 'hover:underline' : ''}`"/></template></InstanceV1Name>@@ -30,13 +32,15 @@:environment="database.effectiveEnvironmentEntity":plain="true":show-icon="false"- text-class="hover:underline text-control-light"+ :link="link"+ :text-class="`text-control-light ${link ? 'hover:underline' : ''}`"/><DatabaseV1Name:database="database":plain="true"- class="hover:underline"+ :link="link"+ :text-class="link ? 'hover:underline' : ''"/></template>@@ -50,8 +54,14 @@ import { SQLEditorButtonV1 } from "@/components/DatabaseDetail";import { DatabaseV1Name, InstanceV1Name } from "@/components/v2";import { ComposedDatabase } from "@/types";-defineProps<{- database: ComposedDatabase;- showSQLEditorButton?: boolean;-}>();+withDefaults(+ defineProps<{+ database: ComposedDatabase;+ showSQLEditorButton?: boolean;+ link?: boolean;+ }>(),+ {+ link: true,+ }+);</script>diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vueindex db44f7c004..c6020648ca 100644--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue@@ -200,12 +200,12 @@ import {sheetNameOfTaskV1,useInstanceV1EditorLanguage,} from "@/utils";+import { readFileAsync } from "@/utils";import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";import { useAutoEditorHeight } from "./useAutoEditorHeight";import { useEditorAutoCompletion } from "./useEditorAutoCompletion";import { EditState, useTempEditState } from "./useTempEditState";-import { readFileAsync } from "./utils";type LocalState = EditState & {showFeatureModal: boolean;diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.tsdeleted file mode 100644index 404c00bb55..0000000000--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.ts+++ /dev/null@@ -1,65 +0,0 @@-import { t } from "@/plugins/i18n";-import { pushNotification } from "@/store";--export const readFileAsync = (- event: Event,- maxFileSizeMB: number-): Promise<{- filename: string;- content: string;-}> => {- return new Promise((resolve, reject) => {- const target = event.target as HTMLInputElement;- const file = (target.files || [])[0];- const cleanup = () => {- // Note that once selected a file, selecting the same file again will not- // trigger <input type="file">'s change event.- // So we need to do some cleanup stuff here.- target.files = null;- target.value = "";- };-- if (!file) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "File not found",- });- cleanup();- reject();- return;- }- if (file.size > maxFileSizeMB * 1024 * 1024) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("issue.upload-sql-file-max-size-exceeded", {- size: `${maxFileSizeMB}MB`,- }),- });- cleanup();- reject();- return;- }-- const fr = new FileReader();- fr.onload = async () => {- const content = fr.result as string;- resolve({- filename: file.name,- content: content,- });- };- fr.onerror = () => {- pushNotification({- module: "bytebase",- style: "WARN",- title: "Read file error",- description: String(fr.error),- });- reject();- };- fr.readAsText(file);- cleanup();- });-};diff --git a/frontend/src/components/IssueV1/logic/initialize/create.ts b/frontend/src/components/IssueV1/logic/initialize/create.tsindex 9a1c742027..9f8dda80eb 100644--- a/frontend/src/components/IssueV1/logic/initialize/create.ts+++ b/frontend/src/components/IssueV1/logic/initialize/create.ts@@ -5,6 +5,7 @@ import { type _RouteLocationBase } from "vue-router";import { rolloutServiceClient } from "@/grpcweb";import { TemplateType } from "@/plugins";import {+ useChangelistStore,useDatabaseV1Store,useEnvironmentV1Store,useProjectV1Store,@@ -29,6 +30,7 @@ import {} from "@/types/proto/v1/rollout_service";import {extractSheetUID,+ generateSQLForChangeToDatabase,getSheetStatement,setSheetNameForTask,setSheetStatement,@@ -100,7 +102,14 @@ export const buildPlan = async (params: CreateIssueParams) => {uid: nextUID(),});plan.name = `${project.name}/plans/${plan.uid}`;- if (route.query.mode === "tenant") {+ if (route.query.changelist) {+ // build plan for changelist+ plan.steps = await buildStepsViaChangelist(+ databaseUIDList,+ route.query.changelist as string,+ params+ );+ } else if (route.query.mode === "tenant") {// in tenant mode, all specs share a unique sheetconst sheetUID = nextUID();// build tenant plan@@ -122,11 +131,7 @@ export const buildPlan = async (params: CreateIssueParams) => {}} else {// build standard plan- plan.steps = await buildSteps(- databaseUIDList,- params,- undefined // each spec should has an independent sheet- );+ plan.steps = await buildSteps(databaseUIDList, params, undefined);}return plan;};@@ -218,6 +223,60 @@ export const buildStepsViaDeploymentConfig = async (return [step];};+export const buildStepsViaChangelist = async (+ databaseUIDList: string[],+ changelistResourceName: string,+ params: CreateIssueParams+) => {+ const changelist = await useChangelistStore().getOrFetchChangelistByName(+ changelistResourceName+ );+ const { changes } = changelist;++ const databaseList = databaseUIDList.map((uid) =>+ useDatabaseV1Store().getDatabaseByUID(uid)+ );++ const databaseListGroupByEnvironment = groupBy(+ databaseList,+ (db) => db.effectiveEnvironment+ );+ const stageList = orderBy(+ Object.keys(databaseListGroupByEnvironment).map((env) => {+ const environment = useEnvironmentV1Store().getEnvironmentByName(env);+ const databases = databaseListGroupByEnvironment[env];+ return {+ environment,+ databases,+ };+ }),+ [(stage) => stage.environment?.order],+ ["asc"]+ );++ const steps: Plan_Step[] = [];+ for (let i = 0; i < stageList.length; i++) {+ const step = Plan_Step.fromJSON({});+ const { databases } = stageList[i];+ for (let j = 0; j < databases.length; j++) {+ const db = databases[j];+ for (let k = 0; k < changes.length; k++) {+ const change = changes[k];+ const statement = await generateSQLForChangeToDatabase(change, db);+ const sheetUID = nextUID();+ const sheetName = `${params.project.name}/sheets/${sheetUID}`;+ const sheet = getLocalSheetByName(sheetName);+ setSheetStatement(sheet, statement);+ const spec = await buildSpecForTarget(db.name, params, sheetUID);+ step.specs.push(spec);+ }+ }+ steps.push(step);+ }++ return steps;+};+export const buildSpecForTarget = async (target: string,{ project, route }: CreateIssueParams,diff --git a/frontend/src/components/v2/Button/ErrorTipsButton.vue b/frontend/src/components/v2/Button/ErrorTipsButton.vuenew file mode 100644index 0000000000..01f9cf61be--- /dev/null+++ b/frontend/src/components/v2/Button/ErrorTipsButton.vue@@ -0,0 +1,48 @@+<template>+ <NTooltip+ :disabled="disabled || (errors ?? []).length === 0"+ v-bind="tooltipProps"+ >+ <template #trigger>+ <NButton+ tag="div"+ :disabled="disabled || (errors ?? []).length > 0"+ v-bind="{+ ...$attrs,+ ...buttonProps,+ }"+ @click="$emit('click')"+ >+ <template #icon>+ <slot name="icon" />+ </template>+ <template #default>+ <slot name="default" />+ </template>+ </NButton>+ </template>+ <template #default>+ <slot name="tooltip" :errors="errors">+ <ErrorList :errors="errors ?? []" :class="errorListClass" />+ </slot>+ </template>+ </NTooltip>+</template>++<script setup lang="ts">+import { NTooltip, NButton, TooltipProps, ButtonProps } from "naive-ui";+import ErrorList from "@/components/misc/ErrorList.vue";+import { VueClass } from "@/utils";++defineProps<{+ disabled?: boolean;+ errors?: string[];+ tooltipProps?: TooltipProps;+ buttonProps?: ButtonProps;+ errorListClass?: VueClass;+}>();++defineEmits<{+ (event: "click"): void;+}>();+</script>diff --git a/frontend/src/components/v2/Button/index.ts b/frontend/src/components/v2/Button/index.tsindex de2632a09c..61617576d8 100644--- a/frontend/src/components/v2/Button/index.ts+++ b/frontend/src/components/v2/Button/index.ts@@ -1,5 +1,6 @@import ContextMenuButton from "./ContextMenuButton.vue";+import ErrorTipsButton from "./ErrorTipsButton.vue";import TooltipButton from "./TooltipButton.vue";-export { ContextMenuButton, TooltipButton };+export { ContextMenuButton, TooltipButton, ErrorTipsButton };export * from "./types";diff --git a/frontend/src/components/v2/Container/Drawer.vue b/frontend/src/components/v2/Container/Drawer.vueindex 66ada9b96e..db693dc085 100644--- a/frontend/src/components/v2/Container/Drawer.vue+++ b/frontend/src/components/v2/Container/Drawer.vue@@ -4,7 +4,7 @@:show="show":auto-focus="false":trap-focus="false"- :close-on-esc="true"+ :close-on-esc="closeOnEsc"v-bind="$attrs"@update:show="onUpdateShow">@@ -16,12 +16,14 @@import { useEventListener } from "@vueuse/core";import { NDrawer } from "naive-ui";-withDefaults(+const props = withDefaults(defineProps<{show?: boolean;+ closeOnEsc?: boolean;}>(),{show: true,+ closeOnEsc: true,});const emit = defineEmits<{@@ -39,6 +41,7 @@ const onUpdateShow = (show: boolean) => {useEventListener("keydown", (e) => {if (e.code == "Escape") {+ if (!props.closeOnEsc) return;emit("update:show", false);emit("close");}diff --git a/frontend/src/components/v2/Form/ResourceIdField.vue b/frontend/src/components/v2/Form/ResourceIdField.vueindex 204c52ca36..2ed56f8452 100644--- a/frontend/src/components/v2/Form/ResourceIdField.vue+++ b/frontend/src/components/v2/Form/ResourceIdField.vue@@ -85,7 +85,8 @@ type ResourceType =| "idp"| "role"| "database-group"- | "schema-group";+ | "schema-group"+ | "changelist";const props = withDefaults(defineProps<{diff --git a/frontend/src/components/v2/Model/RichDatabaseName.vue b/frontend/src/components/v2/Model/RichDatabaseName.vuenew file mode 100644index 0000000000..f3ddf759d8--- /dev/null+++ b/frontend/src/components/v2/Model/RichDatabaseName.vue@@ -0,0 +1,78 @@+<template>+ <NPopover :disabled="!tooltip">+ <template #trigger>+ <div class="flex flex-row justify-start items-center gap-x-1">+ <div+ v-if="showInstance || showEngineIcon"+ class="flex flex-row items-center gap-x-1"+ >+ <InstanceV1EngineIcon+ v-if="showEngineIcon"+ :instance="database.instanceEntity"+ />+ <InstanceV1Name+ v-if="showInstance"+ :instance="database.instanceEntity"+ :icon="false"+ :link="false"+ />+ </div>++ <heroicons:chevron-right+ v-if="(showInstance || showEngineIcon) && showArrow"+ class="text-control-light"+ />++ <div class="flex flex-row items-center gap-x-1">+ <EnvironmentV1Name+ v-if="showEnvironment"+ :environment="database.effectiveEnvironmentEntity"+ :link="false"+ :show-icon="showProductionEnvironmentIcon"+ text-class="text-control-light"+ />+ <DatabaseV1Name+ :database="database"+ :link="false"+ :show-icon="false"+ />+ </div>+ </div>+ </template>+ <template #default>+ <InstanceV1Name+ v-if="tooltip === 'instance'"+ :instance="database.instanceEntity"+ :link="false"+ />+ </template>+ </NPopover>+</template>++<script setup lang="ts">+import { NPopover } from "naive-ui";+import { ComposedDatabase } from "@/types";+import DatabaseV1Name from "./DatabaseV1Name.vue";+import EnvironmentV1Name from "./EnvironmentV1Name.vue";+import { InstanceV1EngineIcon, InstanceV1Name } from "./Instance";++withDefaults(+ defineProps<{+ database: ComposedDatabase;+ showEngineIcon?: boolean;+ showInstance?: boolean;+ showArrow?: boolean;+ showEnvironment?: boolean;+ showProductionEnvironmentIcon?: boolean;+ tooltip?: "instance" | undefined;+ }>(),+ {+ showEngineIcon: true,+ showInstance: true,+ showArrow: true,+ showEnvironment: true,+ showProductionEnvironmentIcon: true,+ tooltip: undefined,+ }+);+</script>diff --git a/frontend/src/components/v2/Model/index.ts b/frontend/src/components/v2/Model/index.tsindex 60f3f79e71..029e859ec9 100644--- a/frontend/src/components/v2/Model/index.ts+++ b/frontend/src/components/v2/Model/index.ts@@ -9,12 +9,14 @@ import ProductionEnvironmentV1Icon from "./ProductionEnvironmentV1Icon.vue";import ProjectName from "./ProjectName.vue";import ProjectV1Name from "./ProjectV1Name.vue";import ProjectV1Table from "./ProjectV1Table.vue";+import RichDatabaseName from "./RichDatabaseName.vue";export * from "./Instance";export * from "./User";export {DatabaseName,DatabaseV1Name,+ RichDatabaseName,DatabaseV1Table,EnvironmentName,EnvironmentV1Name,diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vueindex d5f1a1059e..e326535188 100644--- a/frontend/src/components/v2/Select/ProjectSelect.vue+++ b/frontend/src/components/v2/Select/ProjectSelect.vue@@ -182,7 +182,7 @@ watchEffect(prepare);</script><style lang="postcss" scoped>-.bb-project-select ::v-deep .n-base-selection-input:focus {+.bb-project-select :deep(.n-base-selection-input:focus) {@apply !ring-0;}</style>diff --git a/frontend/src/grpcweb/index.ts b/frontend/src/grpcweb/index.tsindex 53b73b6f52..07fc052535 100644--- a/frontend/src/grpcweb/index.ts+++ b/frontend/src/grpcweb/index.ts@@ -10,6 +10,7 @@ import { AnomalyServiceDefinition } from "@/types/proto/v1/anomaly_service";import { AuthServiceDefinition } from "@/types/proto/v1/auth_service";import { BookmarkServiceDefinition } from "@/types/proto/v1/bookmark_service";import { CelServiceDefinition } from "@/types/proto/v1/cel_service";+import { ChangelistServiceDefinition } from "@/types/proto/v1/changelist_service";import { DatabaseServiceDefinition } from "@/types/proto/v1/database_service";import { EnvironmentServiceDefinition } from "@/types/proto/v1/environment_service";import { ExternalVersionControlServiceDefinition } from "@/types/proto/v1/externalvs_service";@@ -190,6 +191,11 @@ export const schemaDesignServiceClient = clientFactory.create(channel);+export const changelistServiceClient = clientFactory.create(+ ChangelistServiceDefinition,+ channel+);+// e.g. How to use `authServiceClient`?//// await authServiceClient.login({diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 4d224eca72..56bf0c5944 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -263,7 +263,10 @@"merge": "Merge","info": "Info","minutes": "Minutes",- "go-to-configure": "Configure"+ "go-to-configure": "Configure",+ "updated-at-by": "Updated {time} by {user}",+ "created-at-by": "Created {time} by {user}",+ "filter-by-name": "Filter by name"},"error-page": {"go-back-home": "Go back home"@@ -2561,7 +2564,8 @@"idp": "Identity Provider","role": "Role","database-group": "Database Group",- "schema-group": "Table Group"+ "schema-group": "Table Group",+ "changelist": "Changelist"},"resource-id": {"self": "{resource} ID",@@ -3044,5 +3048,45 @@"column_name": "Column name","classification_level": "Classification level"}+ },+ "changelist": {+ "self": "Changelist",+ "changelists": "Changelists",+ "change-center": "Change Center",+ "new": "New Changelist",+ "name": "Changelist name",+ "name-placeholder": "My changelist",+ "error": {+ "project-is-required": "Project is required",+ "name-is-required": "Changelist name is required",+ "invalid-resource-id": "Invalid resource Id",+ "nothing-changed": "Nothing changed",+ "sql-cannot-be-empty": "SQL is required",+ "select-at-least-one-change": "Select at least one change",+ "select-at-least-one-change-to-export": "Select at least one change to export",+ "add-at-least-one-change": "Add at least one change",+ "select-at-least-one-database": "Select at least one database",+ "you-are-not-allowed-to-perform-this-action": "You are not allowed to perform this action"+ },+ "apply-to-database": "Apply to database",+ "add-change": {+ "self": "Add Change",+ "change-history": {+ "select-at-least-one-history-below": "Select at least one history below"+ },+ "branch": {+ "select-at-least-one-branch-below": "Select at least one branch below"+ }+ },+ "change-source": {+ "self": "Change source",+ "raw-sql": "Raw SQL",+ "change-history": {+ "tables": "Tables"+ },+ "source": "Source"+ },+ "confirm-remove-change": "Remove this change?",+ "confirm-delete-changelist": "Delete this changelist?"}}diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 80aef645a8..f56af28065 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -263,7 +263,10 @@"merge": "Combinar","info": "Información","minutes": "Minutos",- "go-to-configure": "Configurar"+ "go-to-configure": "Configurar",+ "updated-at-by": "Actualizado {time} por {user}",+ "created-at-by": "Creado {time} por {user}",+ "filter-by-name": "Filtrar por nombre"},"error-page": {"go-back-home": "Volver al inicio"@@ -2557,7 +2560,8 @@"idp": "Proveedor de Identidad","role": "Rol","database-group": "grupo de bases de datos",- "schema-group": "grupo de mesas"+ "schema-group": "grupo de mesas",+ "changelist": "Lista de cambios"},"resource-id": {"self": "ID de {resource}",@@ -3042,5 +3046,45 @@"column_name": "Nombre de columna","classification_level": "Nivel de clasificación"}+ },+ "changelist": {+ "self": "Lista de cambios",+ "changelists": "Listas de cambios",+ "change-center": "Centro de cambios",+ "new": "Nueva lista de cambios",+ "name": "Nombre de la lista de cambios",+ "name-placeholder": "Mi lista de cambios",+ "error": {+ "project-is-required": "Se requiere proyecto",+ "name-is-required": "El nombre de la lista de cambios es obligatorio",+ "invalid-resource-id": "ID de recurso no válido",+ "nothing-changed": "nada ha cambiado",+ "sql-cannot-be-empty": "Se requiere SQL",+ "select-at-least-one-change": "Seleccione al menos un cambio",+ "select-at-least-one-change-to-export": "Seleccione al menos un cambio para exportar",+ "add-at-least-one-change": "Añade al menos un cambio",+ "select-at-least-one-database": "Seleccione al menos una base de datos",+ "you-are-not-allowed-to-perform-this-action": "No tienes permiso para realizar esta acción."+ },+ "apply-to-database": "Aplicar a la base de datos",+ "add-change": {+ "self": "Agregar cambio",+ "change-history": {+ "select-at-least-one-history-below": "Seleccione al menos un historial a continuación"+ },+ "branch": {+ "select-at-least-one-branch-below": "Seleccione al menos una sucursal a continuación"+ }+ },+ "change-source": {+ "self": "Cambiar fuente",+ "raw-sql": "SQL sin formato",+ "change-history": {+ "tables": "Mesas"+ },+ "source": "Fuente"+ },+ "confirm-remove-change": "¿Eliminar este cambio?",+ "confirm-delete-changelist": "¿Eliminar esta lista de cambios?"}}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 4ba59ae478..7e01ba2a4a 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -261,7 +261,10 @@"merge": "合并","info": "信息","minutes": "分钟",- "go-to-configure": "去配置"+ "go-to-configure": "去配置",+ "updated-at-by": "由 {user} 更新于 {time}",+ "created-at-by": "由 {user} 创建于 {time}",+ "filter-by-name": "按名称过滤"},"error-page": {"go-back-home": "回到主页"@@ -2557,7 +2560,8 @@"idp": "身份提供商","role": "角色","database-group": "数据库分组",- "schema-group": "表分组"+ "schema-group": "表分组",+ "changelist": "变更列表"},"resource-id": {"self": "{resource} ID",@@ -3037,5 +3041,45 @@"column_name": "字段名称","classification_level": "数据分级"}+ },+ "changelist": {+ "self": "变更列表",+ "changelists": "变更列表",+ "change-center": "变更中心",+ "new": "新建变更列表",+ "name": "变更列表名称",+ "name-placeholder": "我的变更列表",+ "error": {+ "project-is-required": "项目不能为空",+ "name-is-required": "变更列表名称不能为空",+ "invalid-resource-id": "无效的资源 ID",+ "nothing-changed": "无任何改变",+ "sql-cannot-be-empty": "SQL 不能为空",+ "select-at-least-one-change": "选择至少一条变更",+ "select-at-least-one-change-to-export": "至少选择一项要导出的变更",+ "add-at-least-one-change": "添加至少一项变更",+ "select-at-least-one-database": "至少选择一个数据库",+ "you-are-not-allowed-to-perform-this-action": "你无权执行此操作"+ },+ "apply-to-database": "应用到数据库",+ "add-change": {+ "self": "添加变更",+ "change-history": {+ "select-at-least-one-history-below": "请在下方选择至少一条记录"+ },+ "branch": {+ "select-at-least-one-branch-below": "请在下方选择至少一条记录"+ }+ },+ "change-source": {+ "self": "变更来源",+ "raw-sql": "SQL 语句",+ "change-history": {+ "tables": "表"+ },+ "source": "来源"+ },+ "confirm-remove-change": "移除这项变更?",+ "confirm-delete-changelist": "删除变更列表?"}}diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 2954207dd3..1590cda1c1 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -39,6 +39,7 @@ import {useInstanceV1Store,useDatabaseV1Store,useChangeHistoryStore,+ useChangelistStore,} from "@/store";import {DEFAULT_PROJECT_ID,@@ -241,6 +242,35 @@ const routes: Array<RouteRecordRaw> = [leftSidebar: true,},},+ {+ path: "changelists",+ name: "workspace.changelist.dashboard",+ meta: { title: () => t("changelist.changelists") },+ components: {+ content: () => import("../views/Changelist/ChangelistDashboard/"),+ leftSidebar: DashboardSidebar,+ },+ props: {+ content: true,+ leftSidebar: true,+ },+ },+ {+ path: "/projects/:projectName/changelists/:changelistName",+ name: "workspace.changelist.detail",+ meta: {+ allowBookmark: true,+ overrideTitle: true,+ },+ components: {+ content: () => import("../views/Changelist/ChangelistDetail/"),+ leftSidebar: DashboardSidebar,+ },+ props: {+ content: true,+ leftSidebar: true,+ },+ },{path: "sync-schema",name: "workspace.sync-schema",@@ -1293,6 +1323,7 @@ router.beforeEach((to, from, next) => {to.name === "workspace.home" ||to.name === "workspace.inbox" ||to.name === "workspace.slow-query" ||+ to.name === "workspace.changelist.dashboard" ||to.name === "workspace.sync-schema" ||to.name === "workspace.export-center" ||to.name === "workspace.anomaly-center" ||@@ -1601,6 +1632,31 @@ router.beforeEach((to, from, next) => {return;}+ if (to.name === "workspace.changelist.detail") {+ const name = `projects/${to.params.projectName}/changelists/${to.params.changelistName}`;+ useChangelistStore()+ .fetchChangelistByName(name)+ .then((changelist) => {+ if (changelist) {+ next();+ } else {+ next({+ name: "error.404",+ replace: false,+ });+ return;+ }+ })+ .catch((error) => {+ next({+ name: "error.404",+ replace: false,+ });+ throw error;+ });+ return;+ }+next({name: "error.404",replace: false,diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.tsindex 00a1585864..610ba4f875 100644--- a/frontend/src/store/modules/index.ts+++ b/frontend/src/store/modules/index.ts@@ -30,3 +30,4 @@ export * from "./role";export * from "./dbGroup";export * from "./utils";export * from "./v1";+export * from "./schemaDesign";diff --git a/frontend/src/store/modules/v1/changelist.ts b/frontend/src/store/modules/v1/changelist.tsnew file mode 100644index 0000000000..c1322b3d89--- /dev/null+++ b/frontend/src/store/modules/v1/changelist.ts@@ -0,0 +1,122 @@+import { defineStore } from "pinia";+import { reactive } from "vue";+import { changelistServiceClient } from "@/grpcweb";+import {+ Changelist,+ Changelist_Change as Change,+ CreateChangelistRequest,+ DeepPartial,+ ListChangelistsRequest,+} from "@/types/proto/v1/changelist_service";+import {+ ResourceComposer,+ isBranchChangeSource,+ isChangeHistoryChangeSource,+} from "@/utils";+import { useSchemaDesignStore } from "../schemaDesign";+import { useChangeHistoryStore } from "./changeHistory";+import { useSheetV1Store } from "./sheet";++export const useChangelistStore = defineStore("changelist", () => {+ const changelistMapByName = reactive(new Map<string, Changelist>());++ const upsertChangelistMap = async (changelists: Changelist[]) => {+ for (let i = 0; i < changelists.length; i++) {+ const changelist = changelists[i];+ await composeChangelist(changelist);+ changelistMapByName.set(changelist.name, changelist);+ }+ };++ const getChangelistByName = (name: string) => {+ return changelistMapByName.get(name);+ };++ const fetchChangelistByName = async (name: string, silent = false) => {+ const changelist = await changelistServiceClient.getChangelist(+ { name },+ { silent }+ );+ await upsertChangelistMap([changelist]);+ return changelist;+ };++ const getOrFetchChangelistByName = async (name: string, silent = false) => {+ const cachedData = changelistMapByName.get(name);+ if (cachedData) {+ return cachedData;+ }++ return fetchChangelistByName(name, silent);+ };++ const createChangelist = async (request: CreateChangelistRequest) => {+ const created = await changelistServiceClient.createChangelist(request);+ await upsertChangelistMap([created]);+ return created;+ };++ const fetchChangelists = async (+ request: DeepPartial<ListChangelistsRequest>+ ) => {+ const response = await changelistServiceClient.listChangelists(request);+ await upsertChangelistMap(response.changelists);+ return response;+ };++ const patchChangelist = async (+ changelist: DeepPartial<Changelist>,+ updateMask: string[]+ ) => {+ const updated = await changelistServiceClient.updateChangelist({+ changelist,+ updateMask,+ });+ await upsertChangelistMap([updated]);+ return updated;+ };++ const deleteChangelist = async (name: string) => {+ await changelistServiceClient.deleteChangelist({+ name,+ });+ changelistMapByName.delete(name);+ };++ const composeChangelist = async (changelist: Changelist) => {+ const composer = new ResourceComposer();+ const { changes } = changelist;+ for (let i = 0; i < changes.length; i++) {+ composeChange(changes[i], composer);+ }++ await composer.compose();+ };+ const composeChange = (change: Change, composer: ResourceComposer) => {+ const { sheet, source } = change;+ if (isChangeHistoryChangeSource(change)) {+ composer.collect(source, () =>+ useChangeHistoryStore().getOrFetchChangeHistoryByName(source)+ );+ } else if (isBranchChangeSource(change)) {+ composer.collect(source, () =>+ useSchemaDesignStore().getOrFetchSchemaDesignByName(source)+ );+ } else {+ // Raw SQL, no need to compose+ }+ composer.collect(sheet, () =>+ useSheetV1Store().getOrFetchSheetByName(sheet)+ );+ };++ return {+ getChangelistByName,+ fetchChangelistByName,+ getOrFetchChangelistByName,+ createChangelist,+ fetchChangelists,+ patchChangelist,+ deleteChangelist,+ };+});diff --git a/frontend/src/store/modules/v1/dbSchema.ts b/frontend/src/store/modules/v1/dbSchema.tsindex f44a2f1e70..4081841b60 100644--- a/frontend/src/store/modules/v1/dbSchema.ts+++ b/frontend/src/store/modules/v1/dbSchema.ts@@ -83,8 +83,6 @@ export const useDBSchemaV1Store = defineStore("dbSchema_v1", {}).then((res) => {- console.log("metadata");- console.log(res);this.setCache(res);return res;});diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.tsindex 3d5103725b..da6a24ada0 100644--- a/frontend/src/store/modules/v1/index.ts+++ b/frontend/src/store/modules/v1/index.ts@@ -7,6 +7,7 @@ export * from "./projectWebhook";export * from "./deploymentConfig";export * from "./databaseSecret";export * from "./sheet";+export * from "./localSheet";export * from "./policy";export * from "./setting";export * from "./instance";@@ -25,3 +26,4 @@ export * from "./bookmark";export * from "./inbox";export * from "./anomaly";export * from "./schemaEditor";+export * from "./changelist";diff --git a/frontend/src/store/modules/v1/localSheet.ts b/frontend/src/store/modules/v1/localSheet.tsnew file mode 100644index 0000000000..df14179ae3--- /dev/null+++ b/frontend/src/store/modules/v1/localSheet.ts@@ -0,0 +1,68 @@+import { defineStore } from "pinia";+import { reactive } from "vue";+import {+ Sheet,+ Sheet_Source,+ Sheet_Type,+ Sheet_Visibility,+ DeepPartial,+} from "@/types/proto/v1/sheet_service";+import { extractProjectResourceName } from "@/utils";+import { useSheetV1Store } from "./sheet";++const state = reactive({+ uid: -101,+});++/**+ * The `local_sheet` store is used for creating and editing local sheets pending+ * create. Once used they should be saved and organized by the `sheet` store.+ */+export const useLocalSheetStore = defineStore("local_sheet", () => {+ const sheetsByName = reactive(new Map<string, Sheet>());++ const nextUID = () => {+ return state.uid--;+ };++ const createLocalSheet = (+ name: string,+ defaults: DeepPartial<Sheet> = {}+ ) => {+ return reactive(+ Sheet.fromPartial({+ name,+ source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,+ visibility: Sheet_Visibility.VISIBILITY_PROJECT,+ type: Sheet_Type.TYPE_SQL,+ ...defaults,+ })+ );+ };++ const getOrCreateSheetByName = (name: string) => {+ const existed = sheetsByName.get(name);+ if (existed) {+ return existed;+ }+ const sheet = createLocalSheet(name);+ sheetsByName.set(name, sheet);+ return sheet;+ };++ const saveLocalSheetToRemote = async (localSheet: Sheet) => {+ const project = extractProjectResourceName(localSheet.name);+ const remoteSheet = await useSheetV1Store().createSheet(+ `projects/${project}`,+ localSheet+ );+ return remoteSheet;+ };++ return {+ nextUID,+ createLocalSheet,+ getOrCreateSheetByName,+ saveLocalSheetToRemote,+ };+});diff --git a/frontend/src/store/modules/v1/sheet.ts b/frontend/src/store/modules/v1/sheet.tsindex e5000dec3e..ce7017d6bc 100644--- a/frontend/src/store/modules/v1/sheet.ts+++ b/frontend/src/store/modules/v1/sheet.ts@@ -75,7 +75,7 @@ export const useSheetV1Store = defineStore("sheet_v1", () => {const getSheetByName = (name: string) => {return sheetsByName.value.get(name);};- const fetchSheetByName = async (name: string) => {+ const fetchSheetByName = async (name: string, raw = false) => {const uid = extractSheetUID(name);if (uid.startsWith("-") || !uid) {return undefined;@@ -83,6 +83,7 @@ export const useSheetV1Store = defineStore("sheet_v1", () => {try {const sheet = await sheetServiceClient.getSheet({name,+ raw,});setSheetList([sheet]);diff --git a/frontend/src/types/changeHistory.ts b/frontend/src/types/changeHistory.tsindex 0765e01e01..42e4da5a90 100644--- a/frontend/src/types/changeHistory.ts+++ b/frontend/src/types/changeHistory.ts@@ -3,3 +3,9 @@ export interface AffectedTable {table: string;dropped: boolean;}++export const EmptyAffectedTable: AffectedTable = {+ schema: "",+ table: "",+ dropped: false,+};diff --git a/frontend/src/types/v1/changelist.ts b/frontend/src/types/v1/changelist.tsnew file mode 100644index 0000000000..db658f5780--- /dev/null+++ b/frontend/src/types/v1/changelist.ts@@ -0,0 +1,22 @@+import { SYSTEM_BOT_USER_NAME } from "@/types";+import { Changelist } from "@/types/proto/v1/changelist_service";++export const UNKNOWN_CHANGELIST_NAME = "projects/-1/changelists/-1";++export const unknownChangelist = () => {+ return Changelist.fromPartial({+ name: UNKNOWN_CHANGELIST_NAME,+ description: "<<Unknown Changelist>>",+ creator: SYSTEM_BOT_USER_NAME,+ updater: SYSTEM_BOT_USER_NAME,+ });+};++export const Changelist_Change_Source_List = [+ "CHANGE_HISTORY",+ "BRANCH",+ "RAW_SQL",+] as const;++export type Changelist_Change_Source =+ typeof Changelist_Change_Source_List[number];diff --git a/frontend/src/types/v1/index.ts b/frontend/src/types/v1/index.tsindex b94a79778e..d4d6233846 100644--- a/frontend/src/types/v1/index.ts+++ b/frontend/src/types/v1/index.ts@@ -10,3 +10,4 @@ export * from "./repository";export * from "./sql";export * from "./webTerminal";export * from "./issue";+export * from "./changelist";diff --git a/frontend/src/utils/dom.ts b/frontend/src/utils/dom.tsindex 672a0459a9..c80d138a5a 100644--- a/frontend/src/utils/dom.ts+++ b/frontend/src/utils/dom.ts@@ -1,3 +1,6 @@+import { t } from "@/plugins/i18n";+import { pushNotification } from "@/store";+export const isDescendantOf = (node: Element | null | undefined,selector: string@@ -10,3 +13,66 @@ export const isDescendantOf = (}return false;};++export const readFileAsync = (+ event: Event,+ maxFileSizeMB: number+): Promise<{+ filename: string;+ content: string;+}> => {+ return new Promise((resolve, reject) => {+ const target = event.target as HTMLInputElement;+ const file = (target.files || [])[0];+ const cleanup = () => {+ // Note that once selected a file, selecting the same file again will not+ // trigger <input type="file">'s change event.+ // So we need to do some cleanup stuff here.+ target.files = null;+ target.value = "";+ };++ if (!file) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "File not found",+ });+ cleanup();+ reject();+ return;+ }+ if (file.size > maxFileSizeMB * 1024 * 1024) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("issue.upload-sql-file-max-size-exceeded", {+ size: `${maxFileSizeMB}MB`,+ }),+ });+ cleanup();+ reject();+ return;+ }++ const fr = new FileReader();+ fr.onload = async () => {+ const content = fr.result as string;+ resolve({+ filename: file.name,+ content: content,+ });+ };+ fr.onerror = () => {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: "Read file error",+ description: String(fr.error),+ });+ reject();+ };+ fr.readAsText(file);+ cleanup();+ });+};diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex 9939ea80f5..1ec40e252d 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -29,5 +29,6 @@ export * from "./id";export * from "./workspaceApprovalSetting";export * from "./projectIamPolicy";export * from "./slowQuery";+export * from "./resource-composer";export * from "./v1";diff --git a/frontend/src/utils/resource-composer.ts b/frontend/src/utils/resource-composer.tsnew file mode 100644index 0000000000..fcf8807285--- /dev/null+++ b/frontend/src/utils/resource-composer.ts@@ -0,0 +1,17 @@+type RequestFn = () => Promise<any>;++export class ResourceComposer {+ requests: Record<string, RequestFn> = {};+ collect(resource: string, request: RequestFn) {+ this.requests[resource] = request;+ }+ compose(method: "all" | "allSettled" = "all") {+ const distinctRequests: Promise<void>[] = [];+ for (const resource in this.requests) {+ distinctRequests.push(this.requests[resource]());+ }+ return method === "all"+ ? Promise.all(distinctRequests)+ : Promise.allSettled(distinctRequests);+ }+}diff --git a/frontend/src/utils/string.ts b/frontend/src/utils/string.tsindex ad18a3030d..4310432acf 100644--- a/frontend/src/utils/string.ts+++ b/frontend/src/utils/string.ts@@ -1,3 +1,7 @@export const escapeMarkdown = (md: string): string => {return md.replaceAll(/[*_~\-#`[\]()\\]/g, (ch) => `\\${ch}`);};++export const escapeFilename = (str: string): string => {+ return str.replace(/[/\\?%*:|"<>]/g, "-");+};diff --git a/frontend/src/utils/v1/changelist.ts b/frontend/src/utils/v1/changelist.tsnew file mode 100644index 0000000000..0d14aacb59--- /dev/null+++ b/frontend/src/utils/v1/changelist.ts@@ -0,0 +1,94 @@+import {+ useChangeHistoryStore,+ useSchemaDesignStore,+ useSheetV1Store,+} from "@/store";+import { Changelist_Change_Source, ComposedDatabase } from "@/types";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { getHistoryChangeType } from "./changeHistory";+import { generateDDLByBranchAndDatabase } from "./schemaDesign";+import { getSheetStatement } from "./sheet";++export const extractChangelistResourceName = (name: string) => {+ const pattern = /(?:^|\/)changelists\/([^/]+)(?:$|\/)/;+ const matches = name.match(pattern);+ return matches?.[1] ?? "";+};++export const isChangeHistoryChangeSource = (change: Change) => {+ return change.source.match(/(^|\/)changeHistories\//);+};+export const isBranchChangeSource = (change: Change) => {+ return change.source.match(/(^|\/)schemaDesigns\//);+};++export const getChangelistChangeSourceType = (+ change: Change+): Changelist_Change_Source => {+ if (isChangeHistoryChangeSource(change)) {+ return "CHANGE_HISTORY";+ } else if (isBranchChangeSource(change)) {+ return "BRANCH";+ } else {+ return "RAW_SQL";+ }+};++export const guessChangelistChangeType = (+ change: Change+): "DML" | "DDL" | "-" => {+ const type = getChangelistChangeSourceType(change);+ if (type === "CHANGE_HISTORY") {+ const history = useChangeHistoryStore().getChangeHistoryByName(+ change.source+ );+ if (!history) {+ return "-";+ }+ return getHistoryChangeType(history.type);+ }+ if (type === "BRANCH") {+ return "DDL";+ }+ if (type === "RAW_SQL") {+ return "-";+ }++ console.error("Should never reach this line");+ return "-";+};++export const generateSQLForChangeToDatabase = async (+ change: Change,+ database: ComposedDatabase+) => {+ const type = getChangelistChangeSourceType(change);+ if (type === "CHANGE_HISTORY" || type === "RAW_SQL") {+ const sheet = await useSheetV1Store().fetchSheetByName(+ change.sheet,+ true /* raw */+ );+ if (!sheet) {+ return "";+ }++ return getSheetStatement(sheet);+ }+ if (type === "BRANCH") {+ const branch = await useSchemaDesignStore().getOrFetchSchemaDesignByName(+ change.source+ );+ if (!branch) {+ return "";+ }+ const diffResult = await generateDDLByBranchAndDatabase(+ branch,+ database,+ false /* !silent */+ );+ return diffResult.statement;+ }++ console.error("Should never reach this line");+ return "";+};diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.tsindex 5e043567de..1df75a9bc0 100644--- a/frontend/src/utils/v1/index.ts+++ b/frontend/src/utils/v1/index.ts@@ -18,4 +18,6 @@ export * from "./sheet";export * from "./vcs";export * from "./issue";export * from "./changeHistory";+export * from "./changelist";export * from "./cel";+export * from "./schemaDesign";diff --git a/frontend/src/utils/v1/schemaDesign.ts b/frontend/src/utils/v1/schemaDesign.tsnew file mode 100644index 0000000000..7e9ff2a5ac--- /dev/null+++ b/frontend/src/utils/v1/schemaDesign.ts@@ -0,0 +1,141 @@+import { postDatabaseEdit } from "@/components/AlterSchemaPrepForm/utils";+import { validateDatabaseMetadata } from "@/components/SchemaEditorV1/utils";+import { convertBranchToBranchSchema } from "@/components/SchemaEditorV1/utils/branch";+import { schemaDesignServiceClient } from "@/grpcweb";+import { t } from "@/plugins/i18n";+import { useDBSchemaV1Store } from "@/store";+import { ComposedDatabase, DatabaseEdit } from "@/types";+import { Engine } from "@/types/proto/v1/common";+import { DatabaseMetadata } from "@/types/proto/v1/database_service";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";+import { BranchSchema } from "@/types/v1/schemaEditor";+import {+ checkHasSchemaChanges,+ diffSchema,+ mergeDiffResults,+} from "../schemaEditor/diffSchema";++const diffViaMetadata = async (+ branch: SchemaDesign,+ database: ComposedDatabase,+ silent = false+) => {+ const sourceMetadata = await useDBSchemaV1Store().getOrFetchDatabaseMetadata(+ database.name,+ false /* !skipCache */,+ silent /* silent */+ );+ const targetMetadata =+ branch.schemaMetadata ?? DatabaseMetadata.fromPartial({});+ const validationMessages = validateDatabaseMetadata(targetMetadata);+ if (validationMessages.length > 0) {+ return {+ errors: validationMessages,+ statement: "",+ };+ }+ try {+ const { diff } = await schemaDesignServiceClient.diffMetadata(+ {+ sourceMetadata,+ targetMetadata,+ engine: database.instanceEntity.engine,+ },+ {+ silent,+ }+ );+ if (diff.length === 0) {+ return {+ errors: [t("schema-editor.nothing-changed")],+ statement: "",+ };+ }+ return {+ errors: [],+ statement: diff,+ };+ } catch {+ return {+ errors: [t("schema-editor.message.invalid-schema")],+ statement: "",+ };+ }+};++const diffViaDatabaseEdit = async (+ branch: SchemaDesign,+ database: ComposedDatabase,+ silent = false+) => {+ const branchSchema = convertBranchToBranchSchema(branch);++ const databaseEdit = calcDatabaseEditFromBranchSchema(branchSchema, database);++ const databaseEditResult = await postDatabaseEdit(databaseEdit, silent);+ if (databaseEditResult.validateResultList.length > 0) {+ return {+ errors: databaseEditResult.validateResultList.map((v) => v.message),+ statement: "",+ };+ }+ const { statement } = databaseEditResult;+ if (statement.length === 0) {+ return {+ errors: [t("schema-editor.nothing-changed")],+ statement: "",+ };+ }+ return {+ errors: [],+ statement,+ };+};++const calcDatabaseEditFromBranchSchema = (+ branchSchema: BranchSchema,+ database: ComposedDatabase+) => {+ let databaseEdit: DatabaseEdit = {+ databaseId: Number(database.uid),+ createSchemaList: [],+ renameSchemaList: [],+ dropSchemaList: [],+ createTableList: [],+ alterTableList: [],+ renameTableList: [],+ dropTableList: [],+ };+ for (const schema of branchSchema.schemaList) {+ const originSchema = branchSchema.originSchemaList.find(+ (originSchema) => originSchema.id === schema.id+ );+ if (!originSchema) {+ continue;+ }++ const diffSchemaResult = diffSchema(database.name, originSchema, schema);+ if (checkHasSchemaChanges(diffSchemaResult)) {+ databaseEdit = {+ databaseId: Number(database.uid),+ ...mergeDiffResults([diffSchemaResult, databaseEdit]),+ };+ }+ }++ return databaseEdit;+};++export const generateDDLByBranchAndDatabase = async (+ branch: SchemaDesign,+ database: ComposedDatabase,+ silent = false+) => {+ // Use `SchemaDesignService.DiffMetadata` for MySQL as we only support MySQL for now.+ if (database.instanceEntity.engine === Engine.MYSQL) {+ return await diffViaMetadata(branch, database, silent);+ } else {+ // Use legacy `DatabaseEdit` for non-MySQL databases.+ return await diffViaDatabaseEdit(branch, database, silent);+ }+};diff --git a/frontend/src/utils/v1/sheet.ts b/frontend/src/utils/v1/sheet.tsindex 6b9a917cae..fb81f78454 100644--- a/frontend/src/utils/v1/sheet.ts+++ b/frontend/src/utils/v1/sheet.ts@@ -26,6 +26,10 @@ export const extractSheetUID = (name: string) => {return matches?.[1] ?? "-1";};+export const isLocalSheet = (name: string) => {+ return extractSheetUID(name).startsWith("-");+};+export const isSheetReadableV1 = (sheet: Sheet) => {const currentUserV1 = useCurrentUserV1();diff --git a/frontend/src/views/ChangeHistoryDetail.vue b/frontend/src/views/ChangeHistoryDetail.vueindex 4633849b4a..f3b0224133 100644--- a/frontend/src/views/ChangeHistoryDetail.vue+++ b/frontend/src/views/ChangeHistoryDetail.vue@@ -1,6 +1,6 @@<template>- <div class="flex-1 overflow-auto focus:outline-none" tabindex="0">- <main v-if="changeHistory" class="flex-1 relative pb-8 overflow-y-auto">+ <div class="focus:outline-none" tabindex="0" v-bind="$attrs">+ <main v-if="changeHistory" class="flex flex-col relative pb-8 gap-y-6"><!-- Highlight Panel --><divclass="px-4 pb-4 border-b border-block-border md:flex md:items-center md:justify-between"@@ -97,8 +97,8 @@</div></div>- <div v-if="affectedTables.length > 0" class="mt-6 px-4">- <span class="flex items-center text-lg text-main mt-6 capitalize">+ <div v-if="affectedTables.length > 0" class="px-4">+ <span class="flex items-center text-lg text-main capitalize">{{ $t("change-history.affected-tables") }}</span><div@@ -121,30 +121,32 @@</div></div>- <div class="mt-6 px-4">- <a- id="statement"- href="#statement"- class="w-auto flex items-center text-lg text-main mb-2 hover:underline"- >- {{ $t("common.statement") }}- <button- tabindex="-1"- class="btn-icon ml-1"- @click.prevent="copyStatement"+ <div class="px-4 flex flex-col gap-y-6">+ <div class="flex flex-col gap-y-2">+ <a+ id="statement"+ href="#statement"+ class="w-auto flex items-center text-lg text-main mb-2 hover:underline">- <heroicons-outline:clipboard class="w-6 h-6" />- </button>- </a>- <highlight-code-block- class="border px-2 whitespace-pre-wrap w-full"- :code="changeHistory.statement"- />- <template v-if="showSchemaSnapshot">+ {{ $t("common.statement") }}+ <button+ tabindex="-1"+ class="btn-icon ml-1"+ @click.prevent="copyStatement"+ >+ <heroicons-outline:clipboard class="w-6 h-6" />+ </button>+ </a>+ <highlight-code-block+ class="border px-2 whitespace-pre-wrap w-full"+ :code="changeHistory.statement"+ />+ </div>+ <div v-if="showSchemaSnapshot" class="flex flex-col gap-y-2"><aid="schema"href="#schema"- class="flex items-center text-lg text-main mt-6 hover:underline capitalize"+ class="flex items-center text-lg text-main hover:underline capitalize">Schema {{ $t("common.snapshot") }}<button@@ -156,7 +158,7 @@</button></a>- <div v-if="hasDrift" class="flex items-center space-x-2 mt-2">+ <div v-if="hasDrift" class="flex items-center gap-x-2"><div class="flex items-center text-sm font-normal"><heroicons-outline:exclamation-circleclass="w-5 h-5 mr-0.5 text-error"@@ -172,7 +174,7 @@</div></div>- <div class="flex flex-row items-center space-x-2 mt-2">+ <div class="flex flex-row items-center gap-x-2"><BBSwitchv-if="allowShowDiff":label="$t('change-history.show-diff')"@@ -215,15 +217,15 @@<template v-else><highlight-code-blockv-if="changeHistory.schema"- class="border mt-2 px-2 whitespace-pre-wrap w-full"+ class="border px-2 whitespace-pre-wrap w-full":code="changeHistory.schema"data-label="bb-change-history-code-block"/>- <div v-else class="mt-2">+ <div v-else>{{ $t("change-history.current-schema-empty") }}</div></template>- </template>+ </div></div></main>diff --git a/frontend/src/views/Changelist/ChangelistDashboard/ChangelistDashboard.vue b/frontend/src/views/Changelist/ChangelistDashboard/ChangelistDashboard.vuenew file mode 100644index 0000000000..449ebb5aac--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/ChangelistDashboard.vue@@ -0,0 +1,71 @@+<template>+ <div class="flex flex-col gap-y-2 px-4">+ <NavBar />++ <ChangelistTable+ :changelists="filteredChangelists"+ :is-fetching="isFetching"+ :keyword="filter.keyword"+ />++ <CreateChangelistPanel />+ </div>+</template>++<script lang="ts" setup>+import { computed, onMounted, ref } from "vue";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import {+ useChangelistStore,+ useCurrentUserV1,+ useProjectV1Store,+} from "@/store";+import { Changelist } from "@/types/proto/v1/changelist_service";+import { extractProjectResourceName, isMemberOfProjectV1 } from "@/utils";+import ChangelistTable from "./ChangelistTable.vue";+import CreateChangelistPanel from "./CreateChangelistPanel.vue";+import NavBar from "./NavBar.vue";+import { provideChangelistDashboardContext } from "./context";++const me = useCurrentUserV1();+const { filter, events } = provideChangelistDashboardContext();++const isFetching = ref(false);+const changelists = ref<Changelist[]>([]);++const filteredChangelists = computed(() => {+ let list = changelists.value.filter((changelist) => {+ // The server-side has not implemented ACL by now.+ // So we manually filter the changelists by project here to workaround.+ const project = useProjectV1Store().getProjectByName(+ `projects/${extractProjectResourceName(changelist.name)}`+ );+ return isMemberOfProjectV1(project.iamPolicy, me.value);+ });+ const keyword = filter.value.keyword.trim();+ if (keyword) {+ list = list.filter((changelist) => {+ return changelist.description+ .toLowerCase()+ .includes(keyword.toLowerCase());+ });+ }+ return list;+});++const fetchChangelists = async () => {+ isFetching.value = true;+ try {+ const response = await useChangelistStore().fetchChangelists({+ parent: filter.value.project,+ });++ changelists.value = response.changelists;+ } finally {+ isFetching.value = false;+ }+};++useEmitteryEventListener(events, "refresh", fetchChangelists);+onMounted(fetchChangelists);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDashboard/ChangelistTable.vue b/frontend/src/views/Changelist/ChangelistDashboard/ChangelistTable.vuenew file mode 100644index 0000000000..3e2311c99c--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/ChangelistTable.vue@@ -0,0 +1,109 @@+<template>+ <BBGrid+ :column-list="columns"+ :ready="!isFetching"+ :data-source="changelists"+ :show-placeholder="true"+ class="border"+ @click-row="handleClickRow"+ >+ <template #item="{ item: changelist }: BBGridRow<Changelist>">+ <!-- eslint-disable-next-line vue/no-v-html -->+ <div class="bb-grid-cell" v-html="renderDescription(changelist)"></div>+ <div class="bb-grid-cell">+ {{ projectForChangelist(changelist).title }}+ </div>+ <div class="bb-grid-cell">+ <i18n-t keypath="common.updated-at-by">+ <template #time>+ <HumanizeDate :date="changelist.updateTime" />+ </template>+ <template #user>{{ getUser(changelist.updater)?.title }}</template>+ </i18n-t>+ </div>+ <div class="bb-grid-cell">+ <i18n-t keypath="common.created-at-by">+ <template #time>+ <HumanizeDate :date="changelist.createTime" />+ </template>+ <template #user>{{ getUser(changelist.creator)?.title }}</template>+ </i18n-t>+ </div>+ </template>+ </BBGrid>+</template>++<script setup lang="ts">+import { escape } from "lodash-es";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import { BBGrid, BBGridRow, BBGridColumn } from "@/bbkit";+import { useProjectV1Store, useUserStore } from "@/store";+import { Changelist } from "@/types/proto/v1/changelist_service";+import {+ extractProjectResourceName,+ extractUserResourceName,+ getHighlightHTMLByRegExp,+} from "@/utils";++const props = defineProps<{+ changelists: Changelist[];+ isFetching: boolean;+ keyword?: string;+}>();++const { t } = useI18n();+const router = useRouter();++const columns = computed((): BBGridColumn[] => {+ return [+ { title: t("changelist.self"), width: "3fr" },+ { title: t("common.project"), width: "1fr" },+ { title: t("common.updated-at"), width: "minmax(8rem, auto)" },+ { title: t("common.created-at"), width: "minmax(8rem, auto)" },+ ];+});++const projectForChangelist = (changelist: Changelist) => {+ const proj = extractProjectResourceName(changelist.name);+ return useProjectV1Store().getProjectByName(`projects/${proj}`);+};++const getUser = (name: string) => {+ const email = extractUserResourceName(name);+ return useUserStore().getUserByEmail(email);+};++const handleClickRow = (+ item: Changelist,+ section: number,+ row: number,+ e: MouseEvent+) => {+ const url = router.resolve({+ path: `/${item.name}`,+ }).fullPath;+ if (e.ctrlKey || e.metaKey) {+ window.open(url, "_blank");+ } else {+ router.push(url);+ }+};++const renderDescription = (item: Changelist) => {+ const keyword = (props.keyword ?? "").trim().toLowerCase();++ const { description } = item;++ if (!keyword) {+ return escape(description);+ }++ return getHighlightHTMLByRegExp(+ escape(description),+ escape(keyword),+ false /* !caseSensitive */+ );+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDashboard/CreateChangelistPanel.vue b/frontend/src/views/Changelist/ChangelistDashboard/CreateChangelistPanel.vuenew file mode 100644index 0000000000..68074f8333--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/CreateChangelistPanel.vue@@ -0,0 +1,204 @@+<template>+ <Drawer :show="showCreatePanel" @close="showCreatePanel = false">+ <DrawerContent :title="$t('changelist.new')" class="w-[40rem] relative">+ <template #default>+ <div+ class="grid items-center gap-y-4 gap-x-4"+ style="grid-template-columns: minmax(6rem, auto) 1fr"+ >+ <div class="contents">+ <div class="textlabel">+ {{ $t("common.project") }}+ <span class="ml-0.5 text-error">*</span>+ </div>+ <div>+ <ProjectSelect+ v-model:project="projectUID"+ :include-all="false"+ style="width: 14rem"+ />+ </div>+ </div>+ <div class="contents">+ <div class="textlabel">+ {{ $t("changelist.name") }}+ <span class="ml-0.5 text-error">*</span>+ </div>+ <div>+ <NInput+ v-model:value="title"+ :placeholder="$t('changelist.name-placeholder')"+ style="width: 14rem"+ />+ </div>+ </div>+ <div class="contents">+ <div class="col-span-2">+ <ResourceIdField+ ref="resourceIdField"+ v-model:value="resourceId"+ resource-type="changelist"+ :resource-title="title"+ :validate="validateResourceId"+ />+ </div>+ </div>+ </div>++ <div+ v-if="isLoading"+ v-zindexable="{ enabled: true }"+ class="absolute bg-white/50 inset-0 flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>++ <template #footer>+ <div class="flex items-center justify-end gap-x-3">+ <NButton>{{ $t("common.cancel") }}</NButton>+ <NTooltip :disabled="errors.length === 0">+ <template #trigger>+ <NButton+ type="primary"+ tag="div"+ :disabled="errors.length > 0"+ @click="doCreate"+ >+ {{ $t("common.add") }}+ </NButton>+ </template>+ <template #default>+ <ErrorList :errors="errors" />+ </template>+ </NTooltip>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { asyncComputed } from "@vueuse/core";+import { NInput, NTooltip } from "naive-ui";+import { Status } from "nice-grpc-common";+import { zindexable as vZindexable } from "vdirs";+import { ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import ErrorList from "@/components/misc/ErrorList.vue";+import {+ Drawer,+ DrawerContent,+ ProjectSelect,+ ResourceIdField,+} from "@/components/v2";+import {+ pushNotification,+ useChangelistStore,+ useProjectV1Store,+} from "@/store";+import { ResourceId, UNKNOWN_ID, ValidatedMessage } from "@/types";+import { Changelist } from "@/types/proto/v1/changelist_service";+import { getErrorCode } from "@/utils/grpcweb";+import { useChangelistDashboardContext } from "./context";++const router = useRouter();+const { t } = useI18n();+const { showCreatePanel, events } = useChangelistDashboardContext();++const title = ref("");+const projectUID = ref<string>();+const isLoading = ref(false);+const resourceId = ref("");+const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();++const errors = asyncComputed(() => {+ const errors: string[] = [];+ if (!projectUID.value || projectUID.value === String(UNKNOWN_ID)) {+ errors.push(t("changelist.error.project-is-required"));+ }+ if (!title.value.trim()) {+ errors.push(t("changelist.error.name-is-required"));+ }+ if (resourceIdField.value && !resourceIdField.value.isValidated) {+ errors.push(t("changelist.error.invalid-resource-id"));+ }++ return errors;+}, []);++const validateResourceId = async (+ resourceId: ResourceId+): Promise<ValidatedMessage[]> => {+ if (!resourceId) {+ return [];+ }++ if (!projectUID.value) return [];+ const project = useProjectV1Store().getProjectByUID(projectUID.value);++ try {+ const name = `${project.name}/changelists/${resourceId}`;+ const maybeExistedChangelist =+ await useChangelistStore().getOrFetchChangelistByName(+ name,+ true /* silent */+ );+ if (maybeExistedChangelist) {+ return [+ {+ type: "error",+ message: t("resource-id.validation.duplicated", {+ resource: t("resource.changelist"),+ }),+ },+ ];+ }+ } catch (error) {+ if (getErrorCode(error) !== Status.NOT_FOUND) {+ throw error;+ }+ }+ return [];+};++const doCreate = async () => {+ if (errors.value.length > 0) return;+ if (!resourceIdField.value) return;++ isLoading.value = true;+ try {+ const project = useProjectV1Store().getProjectByUID(projectUID.value!);++ const created = await useChangelistStore().createChangelist({+ parent: project.name,+ changelist: Changelist.fromPartial({+ description: title.value,+ }),+ changelistId: resourceId.value,+ });+ showCreatePanel.value = false;+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });+ router.push(created.name);+ events.emit("refresh");+ } finally {+ isLoading.value = false;+ }+};++const reset = () => {+ title.value = "";+ projectUID.value = undefined;+};++watch(showCreatePanel, (show) => {+ if (show) {+ reset();+ }+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDashboard/NavBar.vue b/frontend/src/views/Changelist/ChangelistDashboard/NavBar.vuenew file mode 100644index 0000000000..3359195e16--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/NavBar.vue@@ -0,0 +1,41 @@+<template>+ <div class="flex flex-row items-center justify-between py-0.5">+ <div class="flex items-center justify-start">+ <ProjectSelect v-model:project="projectUID" :include-all="true" />+ </div>+ <div class="flex items-center justify-end gap-x-2">+ <SearchBox v-model:value="filter.keyword" />+ <NButton type="primary" @click="showCreatePanel = true">+ {{ $t("changelist.new") }}+ </NButton>+ </div>+ </div>+</template>++<script setup lang="ts">+import { NButton } from "naive-ui";+import { computed, watch } from "vue";+import { ProjectSelect } from "@/components/v2";+import { useProjectV1Store } from "@/store";+import { UNKNOWN_ID } from "@/types";+import { useChangelistDashboardContext } from "./context";++const { filter, showCreatePanel, events } = useChangelistDashboardContext();++const projectUID = computed({+ get() {+ const { project } = filter.value;+ if (project === "projects/-") return String(UNKNOWN_ID);+ return useProjectV1Store().getProjectByName(project).uid;+ },+ set(uid) {+ if (!uid || uid === String(UNKNOWN_ID)) {+ filter.value.project = "projects/-";+ } else {+ filter.value.project = useProjectV1Store().getProjectByUID(uid).name;+ }+ },+});++watch(projectUID, () => events.emit("refresh"));+</script>diff --git a/frontend/src/views/Changelist/ChangelistDashboard/context.ts b/frontend/src/views/Changelist/ChangelistDashboard/context.tsnew file mode 100644index 0000000000..5326923c0c--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/context.ts@@ -0,0 +1,40 @@+import Emittery from "emittery";+import { InjectionKey, Ref, inject, provide, ref } from "vue";++export type ChangelistDashboardFilter = {+ project: string;+ keyword: string;+};++export type ChangelistDashboardEvents = Emittery<{+ refresh: undefined;+}>;++export type ChangelistDashboardContext = {+ filter: Ref<ChangelistDashboardFilter>;+ showCreatePanel: Ref<boolean>;+ events: ChangelistDashboardEvents;+};++export const KEY = Symbol(+ "bb.changelist.dashboard"+) as InjectionKey<ChangelistDashboardContext>;++export const useChangelistDashboardContext = () => {+ return inject(KEY)!;+};++export const provideChangelistDashboardContext = () => {+ const context: ChangelistDashboardContext = {+ filter: ref({+ project: "projects/-",+ keyword: "",+ }),+ showCreatePanel: ref(false),+ events: new Emittery(),+ };++ provide(KEY, context);++ return context;+};diff --git a/frontend/src/views/Changelist/ChangelistDashboard/index.ts b/frontend/src/views/Changelist/ChangelistDashboard/index.tsnew file mode 100644index 0000000000..987ba1c614--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDashboard/index.ts@@ -0,0 +1,3 @@+import ChangelistDashboard from "./ChangelistDashboard.vue";++export default ChangelistDashboard;diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/AddChangePanel.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/AddChangePanel.vuenew file mode 100644index 0000000000..c3516906f9--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/AddChangePanel.vue@@ -0,0 +1,206 @@+<template>+ <Drawer+ :show="showAddChangePanel"+ :close-on-esc="false"+ @close="showAddChangePanel = false"+ >+ <DrawerContent+ :title="$t('changelist.add-change.self')"+ class="w-[75vw] relative"+ style="max-width: calc(100vw - 8rem)"+ >+ <template #default>+ <div class="flex flex-col gap-y-4 min-h-full">+ <div class="flex items-center gap-x-8">+ <div class="textlabel">+ {{ $t("changelist.change-source.self") }}+ </div>+ <NRadioGroup v-model:value="changeSource">+ <NRadio value="CHANGE_HISTORY">+ {{ $t("common.change-history") }}+ </NRadio>+ <NRadio value="BRANCH">+ {{ $t("common.branch") }}+ </NRadio>+ <NRadio value="RAW_SQL">+ {{ $t("changelist.change-source.raw-sql") }}+ </NRadio>+ </NRadioGroup>+ </div>++ <ChangeHistoryForm v-if="changeSource === 'CHANGE_HISTORY'" />+ <BranchForm v-if="changeSource === 'BRANCH'" />+ <RawSQLForm v-if="changeSource === 'RAW_SQL'" />+ </div>++ <div+ v-if="isLoading"+ v-zindexable="{ enabled: true }"+ class="absolute bg-white/50 inset-0 flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>++ <template #footer>+ <div class="flex items-center justify-end gap-x-3">+ <NButton @click="showAddChangePanel = false">+ {{ $t("common.cancel") }}+ </NButton>++ <ErrorTipsButton+ :errors="errors"+ :button-props="{+ type: 'primary',+ }"+ @click="doAddChange"+ >+ <span>{{ $t("common.add") }}</span>+ <span+ v-if="changeSource !== 'RAW_SQL' && pendingAddChanges.length > 0"+ class="ml-1"+ >+ ({{ pendingAddChanges.length }})+ </span>+ </ErrorTipsButton>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { asyncComputed } from "@vueuse/core";+import { NRadio, NRadioGroup } from "naive-ui";+import { zindexable as vZindexable } from "vdirs";+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Drawer, DrawerContent, ErrorTipsButton } from "@/components/v2";+import {+ pushNotification,+ useChangeHistoryStore,+ useChangelistStore,+ useLocalSheetStore,+} from "@/store";+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";+import {+ Changelist_Change as Change,+ Changelist,+} from "@/types/proto/v1/changelist_service";+import {+ getChangelistChangeSourceType,+ getSheetStatement,+ isLocalSheet,+ setSheetStatement,+} from "@/utils";+import { useChangelistDetailContext } from "../context";+import { provideAddChangeContext } from "./context";+import { BranchForm, ChangeHistoryForm, RawSQLForm } from "./form";+import { emptyRawSQLChange } from "./utils";++const { t } = useI18n();+const { project, changelist, showAddChangePanel } =+ useChangelistDetailContext();+const {+ changeSource,+ changesFromChangeHistory,+ changesFromBranch,+ changeFromRawSQL,+} = provideAddChangeContext();+const isLoading = ref(false);++const pendingAddChanges = computed(() => {+ switch (changeSource.value) {+ case "CHANGE_HISTORY":+ return changesFromChangeHistory.value;+ case "BRANCH":+ return changesFromBranch.value;+ case "RAW_SQL":+ return [changeFromRawSQL.value];+ }+ console.warn("should never reach this line");+ return [];+});++const errors = asyncComputed(() => {+ const errors: string[] = [];++ if (pendingAddChanges.value.length === 0) {+ errors.push(t("changelist.error.select-at-least-one-change"));+ }+ if (changeSource.value === "RAW_SQL") {+ const name = changeFromRawSQL.value.sheet;+ const sheet = useLocalSheetStore().getOrCreateSheetByName(name);+ const statement = getSheetStatement(sheet);+ if (statement.trim().length === 0) {+ errors.push(t("changelist.error.sql-cannot-be-empty"));+ }+ }++ return errors;+}, []);++const doAddChange = async () => {+ if (errors.value.length > 0) return;++ isLoading.value = true;+ const createSheetForPendingAddChange = async (pendingAddChange: Change) => {+ const change = { ...pendingAddChange };+ if (isLocalSheet(change.sheet)) {+ const localSheetStore = useLocalSheetStore();+ const sheet = localSheetStore.getOrCreateSheetByName(change.sheet);+ const sourceType = getChangelistChangeSourceType(change);+ if (sourceType === "CHANGE_HISTORY") {+ const changeHistory = useChangeHistoryStore().getChangeHistoryByName(+ change.source+ );+ setSheetStatement(sheet, changeHistory?.statement ?? "");+ }+ if (sourceType === "BRANCH") {+ const branch = useSchemaDesignStore().getSchemaDesignByName(+ change.source+ );+ setSheetStatement(sheet, branch.schema);+ }+ const created = await localSheetStore.saveLocalSheetToRemote(sheet);+ change.sheet = created.name;+ }++ return change;+ };+ try {+ const newChanges: Change[] = [];+ for (let i = 0; i < pendingAddChanges.value.length; i++) {+ newChanges.push(+ await createSheetForPendingAddChange(pendingAddChanges.value[i])+ );+ }+ const changelistPatch = {+ ...Changelist.fromPartial(changelist.value),+ changes: [...changelist.value.changes, ...newChanges],+ };+ await useChangelistStore().patchChangelist(changelistPatch, ["changes"]);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.added"),+ });+ showAddChangePanel.value = false;+ } finally {+ isLoading.value = false;+ }+};++const reset = () => {+ changeSource.value = "CHANGE_HISTORY";+ changesFromChangeHistory.value = [];+ changesFromBranch.value = [];+ changeFromRawSQL.value = emptyRawSQLChange(project.value.name);+};++watch(showAddChangePanel, (show) => {+ if (show) {+ reset();+ }+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/context.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/context.tsnew file mode 100644index 0000000000..a7036d4a47--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/context.ts@@ -0,0 +1,44 @@+import Emittery from "emittery";+import { InjectionKey, Ref, inject, provide, ref } from "vue";+import { Changelist_Change_Source as ChangeSource } from "@/types";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { useChangelistDetailContext } from "../context";+import { emptyRawSQLChange } from "./utils";++export type AddChangeEvents = Emittery<{+ // not used yet+}>;++export type AddChangeContext = {+ changeSource: Ref<ChangeSource>;+ changesFromChangeHistory: Ref<Change[]>;+ changesFromBranch: Ref<Change[]>;+ changeFromRawSQL: Ref<Change>;++ events: AddChangeEvents;+};++export const KEY = Symbol(+ "bb.changelist.add-change"+) as InjectionKey<AddChangeContext>;++export const useAddChangeContext = () => {+ return inject(KEY)!;+};++export const provideAddChangeContext = () => {+ const { project } = useChangelistDetailContext();++ const context: AddChangeContext = {+ changeSource: ref("CHANGE_HISTORY"),+ changesFromChangeHistory: ref([]),+ changesFromBranch: ref([]),+ changeFromRawSQL: ref(emptyRawSQLChange(project.value.name)),++ events: new Emittery(),+ };++ provide(KEY, context);++ return context;+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchChangeItem.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchChangeItem.vuenew file mode 100644index 0000000000..9db8dd8fd8--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchChangeItem.vue@@ -0,0 +1,70 @@+<template>+ <div class="flex flex-row items-center justify-between gap-x-2 group">+ <div class="flex flex-row items-center gap-x-2">+ <div+ class="flex flex-row items-center gap-x-1 border-b border-transparent group-hover:border-control-border cursor-pointer"+ @click="$emit('click-item', change)"+ >+ <RichDatabaseName+ :database="database"+ :show-instance="false"+ :show-arrow="false"+ :show-production-environment-icon="false"+ tooltip="instance"+ />+ <span>@</span>+ <div>+ {{ branch.title }}+ </div>+ </div>+ </div>+ <div+ class="flex flex-row items-center justify-end gap-x-1 invisible group-hover:visible"+ >+ <NButton+ size="small"+ quaternary+ style="--n-padding: 0 6px"+ @click.stop="$emit('remove-item', change)"+ >+ <template #icon>+ <heroicons:x-mark />+ </template>+ </NButton>+ </div>+ </div>+</template>++<script setup lang="ts">+import { NButton } from "naive-ui";+import { computed } from "vue";+import { RichDatabaseName } from "@/components/v2";+import { useDatabaseV1Store } from "@/store";+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";++const props = defineProps<{+ change: Change;+}>();++defineEmits<{+ (event: "click-item", change: Change): void;+ (event: "remove-item", change: Change): void;+}>();++const branch = computed(() => {+ const name = props.change.source;+ return (+ useSchemaDesignStore().getSchemaDesignByName(name) ??+ SchemaDesign.fromPartial({+ name,+ title: "<<Unknown Branch>>",+ })+ );+});++const database = computed(() => {+ return useDatabaseV1Store().getDatabaseByName(branch.value.baselineDatabase);+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchForm.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchForm.vuenew file mode 100644index 0000000000..bcb77de6dd--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchForm.vue@@ -0,0 +1,177 @@+<template>+ <div class="flex flex-col gap-y-4">+ <div class="flex flex-col gap-y-2 max-w-max">+ <div+ v-if="changes.length === 0"+ class="text-control-placeholder text-sm leading-[28px]"+ >+ {{+ $t("changelist.add-change.branch.select-at-least-one-branch-below")+ }}+ </div>+ <BranchChangeItem+ v-for="change in changes"+ :key="change.source"+ :change="change"+ @click-item="handleClickChange($event)"+ @remove-item="handleRemoveChange($event)"+ />+ </div>+ <div class="flex flex-row items-center justify-between py-0.5">+ <div class="flex flex-row items-center justify-start gap-x-2">+ <DatabaseSelect+ v-model:database="state.databaseUID"+ :project="project.uid"+ />+ </div>+ <div class="flex flex-row items-center justify-end gap-x-2">+ <SearchBox+ v-model:value="state.keyword"+ :placeholder="$t('common.filter-by-name')"+ />+ </div>+ </div>++ <BranchTable+ v-model:selected="selectedBranchList"+ :branch-list="filteredBranchList"+ :is-fetching="!ready"+ :keyword="state.keyword"+ @click-item="state.detailBranchName = $event.name"+ />+ <BranchDetailPanel+ :branch-name="state.detailBranchName"+ @close="state.detailBranchName = undefined"+ />+ </div>+</template>++<script setup lang="ts">+import { first, orderBy } from "lodash-es";+import { computed, reactive, watch } from "vue";+import { DatabaseSelect } from "@/components/v2";+import { useDatabaseV1Store, useLocalSheetStore } from "@/store";+import {+ useSchemaDesignList,+ useSchemaDesignStore,+} from "@/store/modules/schemaDesign";+import { UNKNOWN_ID } from "@/types";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";+import { keyBy, setSheetStatement } from "@/utils";+import BranchDetailPanel from "../../BranchDetailPanel";+import { useChangelistDetailContext } from "../../context";+import { useAddChangeContext } from "../context";+import BranchChangeItem from "./BranchChangeItem.vue";+import BranchTable from "./BranchTable";++type LocalState = {+ keyword: string;+ databaseUID: string | undefined;+ branchList: SchemaDesign[];+ detailBranchName: string | undefined;+};++const state = reactive<LocalState>({+ keyword: "",+ databaseUID: undefined,+ branchList: [],+ detailBranchName: undefined,+});++const { project } = useChangelistDetailContext();+const { changesFromBranch: changes } = useAddChangeContext();+const { schemaDesignList: branchList, ready } = useSchemaDesignList();+const localSheetStore = useLocalSheetStore();++const database = computed(() => {+ const uid = state.databaseUID;+ if (!uid || uid === String(UNKNOWN_ID)) return undefined;+ return useDatabaseV1Store().getDatabaseByUID(uid);+});++const filteredBranchList = computed(() => {+ const db = database.value;+ if (!db) {+ return [];+ }+ const branchListFilterByDatabase = branchList.value.filter((branch) => {+ return branch.baselineDatabase === db.name;+ });+ let list = orderBy(+ branchListFilterByDatabase,+ (branch) => branch.updateTime,+ "desc"+ );++ const kw = state.keyword.trim().toLowerCase();+ if (kw) {+ list = list.filter((branch) => branch.title.toLowerCase().includes(kw));+ }++ return list;+});++const selectedBranchList = computed<string[]>({+ get() {+ return changes.value.map((change) => {+ return change.source;+ });+ },+ set(selected) {+ const existedChangesByBranchName = keyBy(+ changes.value,+ (change) => change.source+ );+ const updatedChanges: Change[] = [];+ for (let i = 0; i < selected.length; i++) {+ const name = selected[i];+ const branch = useSchemaDesignStore().getSchemaDesignByName(name);+ if (branch) {+ const existedChange = existedChangesByBranchName.get(name);+ if (existedChange) {+ updatedChanges.push(existedChange);+ } else {+ const uid = localSheetStore.nextUID();+ const sheet = localSheetStore.createLocalSheet(+ `${project.value.name}/sheets/${uid}`+ );+ setSheetStatement(sheet, branch.schema);+ updatedChanges.push({+ sheet: sheet.name,+ source: branch.name,+ });+ }+ }+ }+ changes.value = updatedChanges;+ },+});++const handleRemoveChange = (change: Change) => {+ const index = changes.value.findIndex((c) => c.source === change.source);+ if (index >= 0) {+ changes.value.splice(index, 1);+ }+};++const handleClickChange = (change: Change) => {+ const branchName = change.source;+ const branch = useSchemaDesignStore().getSchemaDesignByName(branchName);+ const database = useDatabaseV1Store().getDatabaseByName(+ branch.baselineDatabase+ );+ state.databaseUID = database.uid;+ state.detailBranchName = branchName;+};++// Select the first database automatically+watch(+ () => project.value.name,+ (project) => {+ const databaseList = useDatabaseV1Store().databaseListByProject(project);+ state.databaseUID = first(databaseList)?.uid;+ },+ { immediate: true }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/BranchTable.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/BranchTable.vuenew file mode 100644index 0000000000..d928792f0a--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/BranchTable.vue@@ -0,0 +1,168 @@+<template>+ <BBGrid+ :column-list="columns"+ :ready="!isFetching"+ :data-source="branchList"+ :show-placeholder="true"+ :custom-header="true"+ class="border-y"+ @click-row="handleClickRow"+ >+ <template #header>+ <div role="table-row" class="bb-grid-row bb-grid-header-row group">+ <div+ v-for="(column, index) in columns"+ :key="index"+ role="table-cell"+ class="bb-grid-header-cell capitalize"+ :class="[column.class]"+ >+ <template v-if="index === 0">+ <NCheckbox+ :checked="allSelectionState.checked"+ :indeterminate="allSelectionState.indeterminate"+ @update:checked="toggleSelectAll"+ />+ </template>+ <template v-else>{{ column.title }}</template>+ </div>+ </div>+ </template>+ <template #item="{ item: branch }: BBGridRow<SchemaDesign>">+ <div class="bb-grid-cell">+ <NCheckbox+ :checked="isSelected(branch)"+ @update:checked="toggleSelect(branch, $event)"+ @click.stop+ />+ </div>++ <!-- eslint-disable-next-line vue/no-v-html -->+ <div class="bb-grid-cell" v-html="renderTitle(branch)"></div>+ <div class="bb-grid-cell">+ <DatabaseInfo :database="databaseForBranch(branch)" :link="false" />+ </div>+ <div class="bb-grid-cell">+ <i18n-t keypath="common.updated-at-by">+ <template #time>+ <HumanizeDate :date="branch.updateTime" />+ </template>+ <template #user>{{ getUser(branch.updater)?.title }}</template>+ </i18n-t>+ </div>+ </template>+ </BBGrid>+</template>++<script lang="ts" setup>+import { escape } from "lodash-es";+import { NCheckbox } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { BBGrid, BBGridColumn, BBGridRow } from "@/bbkit";+import DatabaseInfo from "@/components/DatabaseInfo.vue";+import HumanizeDate from "@/components/misc/HumanizeDate.vue";+import { useDatabaseV1Store, useUserStore } from "@/store";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";+import { extractUserResourceName, getHighlightHTMLByRegExp } from "@/utils";++const props = defineProps<{+ selected: string[];+ branchList: SchemaDesign[];+ isFetching: boolean;+ keyword: string;+}>();++const emit = defineEmits<{+ (event: "update:selected", selected: string[]): void;+ (event: "click-item", branch: SchemaDesign): void;+}>();++const { t } = useI18n();++const columns = computed((): BBGridColumn[] => {+ return [+ { title: "", width: "auto" },+ { title: t("common.branch"), width: "1fr" },+ { title: t("schema-designer.baseline-version"), width: "2fr" },+ {+ title: t("common.updated-at"),+ width: "auto",+ },+ ];+});++const allSelectionState = computed(() => {+ const { branchList: list, selected } = props;+ const set = new Set(selected);++ const checked =+ selected.length > 0 && list.every((branch) => set.has(branch.name));+ const indeterminate = !checked && selected.some((name) => set.has(name));++ return {+ checked,+ indeterminate,+ };+});++const toggleSelectAll = (on: boolean) => {+ if (on) {+ emit(+ "update:selected",+ props.branchList.map((branch) => branch.name)+ );+ } else {+ emit("update:selected", []);+ }+};++const isSelected = (branch: SchemaDesign) => {+ return props.selected.includes(branch.name);+};++const toggleSelect = (branch: SchemaDesign, on: boolean) => {+ const set = new Set(props.selected);+ const key = branch.name;+ if (on) {+ if (!set.has(key)) {+ set.add(key);+ emit("update:selected", Array.from(set));+ }+ } else {+ if (set.has(key)) {+ set.delete(key);+ emit("update:selected", Array.from(set));+ }+ }+};++const renderTitle = (item: SchemaDesign) => {+ const keyword = props.keyword.trim().toLowerCase();++ const { title } = item;++ if (!keyword) {+ return escape(title);+ }++ return getHighlightHTMLByRegExp(+ escape(title),+ escape(keyword),+ false /* !caseSensitive */+ );+};++const databaseForBranch = (branch: SchemaDesign) => {+ return useDatabaseV1Store().getDatabaseByName(branch.baselineDatabase);+};++const getUser = (name: string) => {+ const email = extractUserResourceName(name);+ return useUserStore().getUserByEmail(email);+};++const handleClickRow = (item: SchemaDesign) => {+ emit("click-item", item);+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/index.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/index.tsnew file mode 100644index 0000000000..69b431139f--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/BranchTable/index.ts@@ -0,0 +1,3 @@+import BranchTable from "./BranchTable.vue";++export default BranchTable;diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryChangeItem.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryChangeItem.vuenew file mode 100644index 0000000000..5df0e5fce4--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryChangeItem.vue@@ -0,0 +1,77 @@+<template>+ <div class="flex flex-row items-center justify-between gap-x-2 group">+ <div class="flex flex-row items-center gap-x-2">+ <NTag>+ <span class="inline-block w-[30px] text-center">+ {{ displaySemanticType(changeHistory.type) }}+ </span>+ </NTag>+ <div+ class="flex flex-row items-center gap-x-1 border-b border-transparent group-hover:border-control-border cursor-pointer"+ @click="$emit('click-item', change)"+ >+ <RichDatabaseName+ :database="database"+ :show-instance="false"+ :show-arrow="false"+ :show-production-environment-icon="false"+ tooltip="instance"+ />+ <span>@</span>+ <span class="text-sm">{{ changeHistory.version }}</span>+ </div>+ </div>+ <div+ class="flex flex-row items-center justify-end gap-x-1 invisible group-hover:visible"+ >+ <NButton+ size="small"+ quaternary+ style="--n-padding: 0 6px"+ @click.stop="$emit('remove-item', change)"+ >+ <template #icon>+ <heroicons:x-mark />+ </template>+ </NButton>+ </div>+ </div>+</template>++<script setup lang="ts">+import { NButton, NTag } from "naive-ui";+import { computed } from "vue";+import { RichDatabaseName } from "@/components/v2";+import { useChangeHistoryStore, useDatabaseV1Store } from "@/store";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { ChangeHistory } from "@/types/proto/v1/database_service";+import { extractDatabaseResourceName } from "@/utils";+import { displaySemanticType } from "./utils";++const props = defineProps<{+ change: Change;+}>();++defineEmits<{+ (event: "click-item", change: Change): void;+ (event: "remove-item", change: Change): void;+}>();++const changeHistory = computed(() => {+ const name = props.change.source;+ return (+ useChangeHistoryStore().getChangeHistoryByName(name) ??+ ChangeHistory.fromPartial({+ name,+ version: "<<Unknown Change History>>",+ })+ );+});++const database = computed(() => {+ const { full: databaseResourceName } = extractDatabaseResourceName(+ changeHistory.value.name+ );+ return useDatabaseV1Store().getDatabaseByName(databaseResourceName);+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryForm.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryForm.vuenew file mode 100644index 0000000000..7ed8ab50de--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryForm.vue@@ -0,0 +1,280 @@+<template>+ <div class="flex flex-col items-stretch gap-y-4 overflow-x-hidden">+ <div class="flex flex-col gap-y-2 max-w-max">+ <div+ v-if="changes.length === 0"+ class="text-control-placeholder text-sm leading-[28px]"+ >+ {{+ $t(+ "changelist.add-change.change-history.select-at-least-one-history-below"+ )+ }}+ </div>+ <ChangeHistoryChangeItem+ v-for="change in changes"+ :key="change.source"+ :change="change"+ @click-item="handleClickChange($event)"+ @remove-item="handleRemoveChange($event)"+ />+ </div>+ <div class="flex flex-row items-center justify-between py-0.5">+ <div class="flex flex-row items-center justify-start gap-x-2">+ <DatabaseSelect+ v-model:database="state.databaseUID"+ :project="project.uid"+ />+ <NSelect+ v-model:value="state.affectedTableKey"+ :options="affectedTableOptions"+ style="width: 12rem"+ />+ <NCheckboxGroup v-model:value="state.changeHistoryTypes">+ <NCheckbox :value="ChangeHistory_Type.MIGRATE">DDL</NCheckbox>+ <NCheckbox :value="ChangeHistory_Type.DATA">DML</NCheckbox>+ </NCheckboxGroup>+ </div>+ <div class="flex flex-row items-center justify-end gap-x-2">+ <SearchBox+ v-model:value="state.keyword"+ :placeholder="$t('common.filter-by-name')"+ />+ </div>+ </div>+ <ChangeHistoryTable+ v-model:selected="selectedChangeHistoryList"+ :change-history-list="filteredChangeHistoryList"+ :is-fetching="state.isLoading"+ :keyword="state.keyword"+ class="w-full"+ @click-item="state.detailChangeHistoryName = $event.name"+ />++ <ChangeHistoryDetailPanel+ :change-history-name="state.detailChangeHistoryName"+ @close="state.detailChangeHistoryName = undefined"+ />+ </div>+</template>++<script setup lang="ts">+import { first } from "lodash-es";+import { NCheckbox, NCheckboxGroup, NSelect, SelectOption } from "naive-ui";+import { computed, reactive, watch } from "vue";+import { h } from "vue";+import { DatabaseSelect, SearchBox } from "@/components/v2";+import {+ useChangeHistoryStore,+ useDBSchemaV1Store,+ useDatabaseV1Store,+ useLocalSheetStore,+} from "@/store";+import { UNKNOWN_ID } from "@/types";+import { AffectedTable, EmptyAffectedTable } from "@/types/changeHistory";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import {+ ChangeHistory,+ ChangeHistory_Type,+} from "@/types/proto/v1/database_service";+import {+ extractDatabaseResourceName,+ getAffectedTablesOfChangeHistory,+ keyBy,+ setSheetStatement,+} from "@/utils";+import ChangeHistoryDetailPanel from "../../ChangeHistoryDetailPanel";+import { useChangelistDetailContext } from "../../context";+import { useAddChangeContext } from "../context";+import ChangeHistoryChangeItem from "./ChangeHistoryChangeItem.vue";+import ChangeHistoryTable from "./ChangeHistoryTable";+import {+ getAffectedTableDisplayName,+ getAffectedTableKey,+ getAffectedTablesFromChangeHistoryList,+ semanticChangeHistoryType,+} from "./utils";++type LocalState = {+ isLoading: boolean;+ keyword: string;+ databaseUID: string | undefined;+ changeHistoryList: ChangeHistory[];+ affectedTableKey: string | undefined;+ changeHistoryTypes: ChangeHistory_Type[];+ detailChangeHistoryName: string | undefined;+};++type AffectedTableSelectOption = SelectOption & {+ affectedTable: AffectedTable;+ value: string;+};++const ALL_TABLE_KEY = getAffectedTableKey(EmptyAffectedTable);++const { project } = useChangelistDetailContext();+const { changesFromChangeHistory: changes } = useAddChangeContext();+const localSheetStore = useLocalSheetStore();++const state = reactive<LocalState>({+ isLoading: false,+ keyword: "",+ databaseUID: undefined,+ changeHistoryList: [],+ affectedTableKey: undefined,+ changeHistoryTypes: [ChangeHistory_Type.DATA, ChangeHistory_Type.MIGRATE],+ detailChangeHistoryName: undefined,+});++const database = computed(() => {+ const uid = state.databaseUID;+ if (!uid || uid === String(UNKNOWN_ID)) return undefined;+ return useDatabaseV1Store().getDatabaseByUID(uid);+});++const affectedTableOptions = computed(() => {+ const affectedTables = getAffectedTablesFromChangeHistoryList(+ state.changeHistoryList+ );++ return affectedTables.map<AffectedTableSelectOption>((item) => {+ const key = getAffectedTableKey(item);+ const name = getAffectedTableDisplayName(item);+ return {+ label: name,+ value: key,+ affectedTable: item,+ renderLabel() {+ const classes = ["truncate"];+ if (item.dropped) {+ classes.push("text-gray-400");+ }+ return h("span", { class: classes, "data-key": key }, name);+ },+ };+ });+});++const filteredChangeHistoryList = computed(() => {+ let list = [...state.changeHistoryList];+ const types = state.changeHistoryTypes;+ list = list.filter((changeHistory) => {+ const semanticType = semanticChangeHistoryType(changeHistory.type);+ return types.includes(semanticType);+ });++ const kw = state.keyword.trim().toLowerCase();+ if (kw) {+ list = list.filter((changeHistory) =>+ changeHistory.version.toLowerCase().includes(kw)+ );+ }+ const tableKey = state.affectedTableKey;+ if (tableKey && tableKey !== ALL_TABLE_KEY) {+ list = list.filter((changeHistory) => {+ const affectedTables = getAffectedTablesOfChangeHistory(changeHistory);+ return affectedTables.find(+ (item) => getAffectedTableKey(item) === tableKey+ );+ });+ }++ return list;+});++const selectedChangeHistoryList = computed<string[]>({+ get() {+ return changes.value.map((change) => {+ return change.source;+ });+ },+ set(selected) {+ const existedChangesByChangeHistoryName = keyBy(+ changes.value,+ (change) => change.source+ );+ const updatedChanges: Change[] = [];+ for (let i = 0; i < selected.length; i++) {+ const name = selected[i];+ const changeHistory =+ useChangeHistoryStore().getChangeHistoryByName(name);+ if (changeHistory) {+ const existedChange = existedChangesByChangeHistoryName.get(name);+ if (existedChange) {+ updatedChanges.push(existedChange);+ } else {+ const uid = localSheetStore.nextUID();+ const sheet = localSheetStore.createLocalSheet(+ `${project.value.name}/sheets/${uid}`+ );+ setSheetStatement(sheet, changeHistory.statement);+ updatedChanges.push({+ sheet: sheet.name,+ source: changeHistory.name,+ });+ }+ }+ }+ changes.value = updatedChanges;+ },+});++const fetchChangeHistoryList = async () => {+ const db = database.value;+ if (!db) {+ state.changeHistoryList = [];+ return;+ }++ state.isLoading = true;+ const name = db.name;+ await useDBSchemaV1Store().getOrFetchDatabaseMetadata(+ name,+ false /* !skipCache */,+ true /* silent */+ );+ const changeHistoryList =+ await useChangeHistoryStore().getOrFetchChangeHistoryListOfDatabase(name);+ // Check if the state is still valid+ if (name === database.value?.name) {+ state.changeHistoryList = changeHistoryList;+ }+ state.isLoading = false;+};++const handleRemoveChange = (change: Change) => {+ const index = changes.value.findIndex((c) => c.source === change.source);+ if (index >= 0) {+ changes.value.splice(index, 1);+ }+};++const handleClickChange = (change: Change) => {+ const changeHistoryName = change.source;+ const database = useDatabaseV1Store().getDatabaseByName(+ extractDatabaseResourceName(changeHistoryName).full+ );+ state.databaseUID = database.uid;+ state.detailChangeHistoryName = changeHistoryName;+};++// Select the first database automatically+watch(+ () => project.value.name,+ (project) => {+ const databaseList = useDatabaseV1Store().databaseListByProject(project);+ state.databaseUID = first(databaseList)?.uid;+ },+ { immediate: true }+);++watch(() => database.value?.uid, fetchChangeHistoryList, { immediate: true });++watch(+ affectedTableOptions,+ (options) => {+ state.affectedTableKey = first(options)?.value;+ },+ { immediate: true }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/ChangeHistoryTable.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/ChangeHistoryTable.vuenew file mode 100644index 0000000000..f298236f7b--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/ChangeHistoryTable.vue@@ -0,0 +1,169 @@+<template>+ <BBGrid+ :column-list="columns"+ :ready="!isFetching"+ :data-source="changeHistoryList"+ :show-placeholder="true"+ :custom-header="true"+ class="border-y"+ @click-row="handleClickRow"+ >+ <template #header>+ <div role="table-row" class="bb-grid-row bb-grid-header-row group">+ <div+ v-for="(column, index) in columns"+ :key="index"+ role="table-cell"+ class="bb-grid-header-cell capitalize whitespace-nowrap"+ :class="[column.class]"+ >+ <template v-if="index === 0">+ <NCheckbox+ :checked="allSelectionState.checked"+ :indeterminate="allSelectionState.indeterminate"+ @update:checked="toggleSelectAll"+ />+ </template>+ <template v-else>{{ column.title }}</template>+ </div>+ </div>+ </template>+ <template #item="{ item: changeHistory }: BBGridRow<ChangeHistory>">+ <div class="bb-grid-cell">+ <NCheckbox+ :checked="isSelected(changeHistory)"+ @update:checked="toggleSelect(changeHistory, $event)"+ @click.stop+ />+ </div>++ <div class="bb-grid-cell">+ {{ displaySemanticType(changeHistory.type) }}+ </div>+ <div class="bb-grid-cell">+ <!-- eslint-disable-next-line vue/no-v-html -->+ <span class="whitespace-nowrap" v-html="renderVersion(changeHistory)" />+ </div>+ <div class="bb-grid-cell whitespace-nowrap">+ <IssueUID :change-history="changeHistory" />+ </div>+ <div class="bb-grid-cell">+ <Tables :change-history="changeHistory" />+ </div>+ <div class="bb-grid-cell overflow-hidden">+ <SQL :change-history="changeHistory" />+ </div>+ </template>+ </BBGrid>+</template>++<script setup lang="ts">+import { escape } from "lodash-es";+import { NCheckbox } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { BBGrid, BBGridRow, BBGridColumn } from "@/bbkit";+import { ChangeHistory } from "@/types/proto/v1/database_service";+import { getHighlightHTMLByRegExp } from "@/utils";+import { displaySemanticType } from "../utils";+import IssueUID from "./IssueUID.vue";+import SQL from "./SQL.vue";+import Tables from "./Tables.vue";++const props = defineProps<{+ selected: string[];+ changeHistoryList: ChangeHistory[];+ isFetching: boolean;+ keyword: string;+}>();++const emit = defineEmits<{+ (event: "update:selected", selected: string[]): void;+ (event: "click-item", change: ChangeHistory): void;+}>();++const { t } = useI18n();++const columns = computed((): BBGridColumn[] => {+ return [+ { title: "", width: "auto" },+ { title: t("common.type"), width: "auto" },+ { title: t("common.version"), width: "1fr" },+ { title: t("common.issue"), width: "auto" },+ {+ title: t("changelist.change-source.change-history.tables"),+ width: "minmax(auto, 1fr)",+ },+ {+ title: t("common.sql"),+ width: "3fr",+ },+ ];+});++const allSelectionState = computed(() => {+ const { changeHistoryList: list, selected } = props;+ const set = new Set(selected);++ const checked =+ selected.length > 0 &&+ list.every((changeHistory) => set.has(changeHistory.name));+ const indeterminate = !checked && selected.some((name) => set.has(name));++ return {+ checked,+ indeterminate,+ };+});++const toggleSelectAll = (on: boolean) => {+ if (on) {+ emit(+ "update:selected",+ props.changeHistoryList.map((changeHistory) => changeHistory.name)+ );+ } else {+ emit("update:selected", []);+ }+};++const isSelected = (changeHistory: ChangeHistory) => {+ return props.selected.includes(changeHistory.name);+};++const toggleSelect = (changeHistory: ChangeHistory, on: boolean) => {+ const set = new Set(props.selected);+ const key = changeHistory.name;+ if (on) {+ if (!set.has(key)) {+ set.add(key);+ emit("update:selected", Array.from(set));+ }+ } else {+ if (set.has(key)) {+ set.delete(key);+ emit("update:selected", Array.from(set));+ }+ }+};++const renderVersion = (item: ChangeHistory) => {+ const keyword = props.keyword.trim().toLowerCase();++ const { version } = item;++ if (!keyword) {+ return escape(version);+ }++ return getHighlightHTMLByRegExp(+ escape(version),+ escape(keyword),+ false /* !caseSensitive */+ );+};++const handleClickRow = (item: ChangeHistory) => {+ emit("click-item", item);+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/IssueUID.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/IssueUID.vuenew file mode 100644index 0000000000..88c155b47f--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/IssueUID.vue@@ -0,0 +1,25 @@+<template>+ <router-link+ v-if="issueUID"+ :to="`/issue/${issueUID}`"+ class="normal-link"+ target="_blank"+ @click.stop+ >#{{ issueUID }}</router-link+ >+ <span v-else>-</span>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { ChangeHistory } from "@/types/proto/v1/database_service";+import { extractIssueUID } from "@/utils";++const props = defineProps<{+ changeHistory: ChangeHistory;+}>();++const issueUID = computed(() => {+ return extractIssueUID(props.changeHistory.issue);+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/SQL.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/SQL.vuenew file mode 100644index 0000000000..79f792ba4b--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/SQL.vue@@ -0,0 +1,17 @@+<template>+ <TextOverflowPopover+ :content="changeHistory.statement"+ :max-length="100"+ content-class="whitespace-nowrap w-full truncate"+ placement="bottom"+ />+</template>++<script setup lang="ts">+import TextOverflowPopover from "@/components/misc/TextOverflowPopover.vue";+import { ChangeHistory } from "@/types/proto/v1/database_service";++defineProps<{+ changeHistory: ChangeHistory;+}>();+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/Tables.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/Tables.vuenew file mode 100644index 0000000000..b00089a092--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/Tables.vue@@ -0,0 +1,25 @@+<template>+ <TextOverflowPopover+ :content="content"+ :max-length="100"+ placement="bottom"+ />+</template>++<script setup lang="ts">+import { computed } from "vue";+import TextOverflowPopover from "@/components/misc/TextOverflowPopover.vue";+import { ChangeHistory } from "@/types/proto/v1/database_service";+import { getAffectedTablesOfChangeHistory } from "@/utils";+import { getAffectedTableDisplayName } from "../utils";++const props = defineProps<{+ changeHistory: ChangeHistory;+}>();++const content = computed(() => {+ return getAffectedTablesOfChangeHistory(props.changeHistory)+ .map(getAffectedTableDisplayName)+ .join(", ");+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/index.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/index.tsnew file mode 100644index 0000000000..446adf5c9b--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/ChangeHistoryTable/index.ts@@ -0,0 +1,3 @@+import ChangeHistoryTable from "./ChangeHistoryTable.vue";++export default ChangeHistoryTable;diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vuenew file mode 100644index 0000000000..7ba16a5808--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue@@ -0,0 +1,44 @@+<template>+ <div class="flex flex-col gap-y-4 flex-1 overflow-hidden">+ <RawSQLEditor+ v-if="sheet"+ v-model:statement="statement"+ :readonly="false"+ class="flex-1 overflow-hidden relative"+ @upload="handleUploadEvent"+ />+ </div>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { useLocalSheetStore } from "@/store";+import { getSheetStatement, readFileAsync, setSheetStatement } from "@/utils";+import RawSQLEditor from "../../RawSQLEditor";+import { useAddChangeContext } from "../context";++const { changeFromRawSQL: change } = useAddChangeContext();++const sheet = computed(() => {+ return useLocalSheetStore().getOrCreateSheetByName(change.value.sheet);+});++const statement = computed({+ get() {+ return getSheetStatement(sheet.value);+ },+ set(statement) {+ setSheetStatement(sheet.value, statement);+ },+});++const handleUploadEvent = async (e: Event) => {+ try {+ const { filename, content } = await readFileAsync(e, 100);+ statement.value = content;+ sheet.value.title = filename;+ } finally {+ // Nothing+ }+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/index.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/index.tsnew file mode 100644index 0000000000..5e1a0eb400--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/index.ts@@ -0,0 +1,5 @@+import BranchForm from "./BranchForm.vue";+import ChangeHistoryForm from "./ChangeHistoryForm.vue";+import RawSQLForm from "./RawSQLForm.vue";++export { ChangeHistoryForm, BranchForm, RawSQLForm };diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/utils.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/utils.tsnew file mode 100644index 0000000000..afb75072f2--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/form/utils.ts@@ -0,0 +1,69 @@+import { isEqual, orderBy, uniqBy } from "lodash-es";+import { t } from "@/plugins/i18n";+import { AffectedTable, EmptyAffectedTable } from "@/types/changeHistory";+import {+ ChangeHistory,+ ChangeHistory_Type,+} from "@/types/proto/v1/database_service";+import { getAffectedTablesOfChangeHistory } from "@/utils";++export const getAffectedTablesFromChangeHistoryList = (+ changeHistoryList: ChangeHistory[]+) => {+ return [+ EmptyAffectedTable,+ ...orderBy(+ uniqBy(+ changeHistoryList+ .map((changeHistory) =>+ getAffectedTablesOfChangeHistory(changeHistory)+ )+ .flat(),+ (affectedTable) => `${affectedTable.schema}.${affectedTable.table}`+ ),+ ["dropped", "table", "schema"]+ ),+ ];+};++export const getAffectedTableKey = (affectedTable: AffectedTable) => {+ return JSON.stringify(affectedTable);+};++export const getAffectedTableDisplayName = (affectedTable: AffectedTable) => {+ if (isEqual(affectedTable, EmptyAffectedTable)) {+ return t("change-history.all-tables");+ }++ const { schema, table, dropped } = affectedTable;+ let name = table;+ if (schema !== "") {+ name = `${schema}.${table}`;+ }+ if (dropped) {+ name = `${name} (deleted)`;+ }+ return name;+};++export const semanticChangeHistoryType = (type: ChangeHistory_Type) => {+ switch (type) {+ case ChangeHistory_Type.BASELINE:+ case ChangeHistory_Type.MIGRATE:+ case ChangeHistory_Type.MIGRATE_SDL:+ case ChangeHistory_Type.BRANCH:+ case ChangeHistory_Type.MIGRATE_GHOST:+ return ChangeHistory_Type.MIGRATE;+ case ChangeHistory_Type.DATA:+ return ChangeHistory_Type.DATA;+ default:+ return ChangeHistory_Type.UNRECOGNIZED;+ }+};++export const displaySemanticType = (type: ChangeHistory_Type) => {+ const semanticType = semanticChangeHistoryType(type);+ if (semanticType === ChangeHistory_Type.MIGRATE) return "DDL";+ if (semanticType === ChangeHistory_Type.DATA) return "DML";+ return "-";+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/index.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/index.tsnew file mode 100644index 0000000000..00e8d44acc--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/index.ts@@ -0,0 +1,3 @@+import AddChangePanel from "./AddChangePanel.vue";++export default AddChangePanel;diff --git a/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/utils.ts b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/utils.tsnew file mode 100644index 0000000000..158dc60b90--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/AddChangePanel/utils.ts@@ -0,0 +1,12 @@+import { reactive } from "vue";+import { useLocalSheetStore } from "@/store";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";++export const emptyRawSQLChange = (project: string) => {+ return reactive(+ Change.fromPartial({+ sheet: `${project}/sheets/${useLocalSheetStore().nextUID()}`,+ source: "",+ })+ );+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/ApplyToDatabasePanel.vue b/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/ApplyToDatabasePanel.vuenew file mode 100644index 0000000000..e2feff7c81--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/ApplyToDatabasePanel.vue@@ -0,0 +1,250 @@+<template>+ <Drawer :show="show" :close-on-esc="true" @close="show = false">+ <DrawerContent :title="$t('changelist.apply-to-database')">+ <template #default>+ <div+ class="w-[calc(100vw-8rem)] lg:w-[60rem] max-w-[calc(100vw-8rem)] overflow-x-auto"+ >+ <div v-if="ready" class="flex flex-col gap-y-4">+ <ProjectStandardView+ :state="state"+ :project="project"+ :database-list="schemaDatabaseList"+ :environment-list="environmentList"+ @select-database="handleSelectDatabase"+ >+ <template #header>+ <div class="flex items-center justify-end mx-2">+ <SearchBox+ v-model:value="state.keyword"+ class="m-px"+ :placeholder="$t('database.filter-database')"+ />+ </div>+ </template>+ </ProjectStandardView>+ <SchemalessDatabaseTable+ v-if="guessedDatabaseChangeType === 'DDL'"+ mode="PROJECT"+ class="px-2"+ :database-list="schemalessDatabaseList"+ />+ </div>+ <div+ v-if="!ready || state.isGenerating"+ v-zindexable="{ enabled: true }"+ class="absolute inset-0 flex flex-col items-center justify-center bg-white/50"+ >+ <BBSpin />+ </div>+ </div>+ </template>++ <template #footer>+ <div class="flex-1 flex items-center justify-between">+ <div>+ <div+ v-if="flattenSelectedDatabaseUidList.length > 0"+ class="textinfolabel"+ >+ {{+ $t("database.selected-n-databases", {+ n: flattenSelectedDatabaseUidList.length,+ })+ }}+ </div>+ </div>++ <div class="flex items-center justify-end gap-x-3">+ <NButton @click.prevent="show = false">+ {{ $t("common.cancel") }}+ </NButton>++ <ErrorTipsButton+ style="--n-padding: 0 10px"+ :errors="nextButtonErrors"+ :button-props="{+ type: 'primary',+ }"+ @click="handleClickNext"+ >+ {{ $t("common.next") }}+ </ErrorTipsButton>+ </div>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script lang="ts" setup>+import { NButton } from "naive-ui";+import { zindexable as vZindexable } from "vdirs";+import { computed, reactive, watch } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import ProjectStandardView, {+ ProjectStandardViewState,+} from "@/components/AlterSchemaPrepForm/ProjectStandardView.vue";+import { ErrorTipsButton, SearchBox } from "@/components/v2";+import {+ useDatabaseV1Store,+ useEnvironmentV1List,+ useSearchDatabaseV1List,+} from "@/store";+import { ComposedDatabase, DEFAULT_PROJECT_V1_NAME } from "@/types";+import { State } from "@/types/proto/v1/common";+import {+ filterDatabaseV1ByKeyword,+ guessChangelistChangeType,+ instanceV1HasAlterSchema,+ sortDatabaseV1List,+} from "@/utils";+import { generateIssueName } from "../common";+import { useChangelistDetailContext } from "../context";++type LocalState = ProjectStandardViewState & {+ keyword: string;+ isGenerating: boolean;+};++const { t } = useI18n();+const router = useRouter();+const databaseStore = useDatabaseV1Store();+const {+ changelist,+ project,+ showApplyToDatabasePanel: show,+} = useChangelistDetailContext();++const state = reactive<LocalState>({+ selectedDatabaseUidListForEnvironment: new Map(),+ alterType: "MULTI_DB",+ keyword: "",+ isGenerating: false,+});++const { ready } = useSearchDatabaseV1List(+ computed(() => ({+ parent: "instances/-",+ filter: `project == "${project.value.name}"`,+ }))+);++const environmentList = useEnvironmentV1List(false /* !showDeleted */);++const guessedDatabaseChangeType = computed(() => {+ if (+ changelist.value.changes.some(+ (change) => guessChangelistChangeType(change) === "DDL"+ )+ ) {+ return "DDL";+ }+ return "DML";+});++const databaseList = computed(() => {+ let list: ComposedDatabase[] = [];+ list = databaseStore.databaseListByProject(project.value.name);++ list = list.filter(+ (db) =>+ db.syncState == State.ACTIVE && db.project !== DEFAULT_PROJECT_V1_NAME+ );++ list = list.filter((db) => {+ return filterDatabaseV1ByKeyword(db, state.keyword.trim(), [+ "name",+ "environment",+ "instance",+ ]);+ });++ return sortDatabaseV1List(list);+});++const schemaDatabaseList = computed(() => {+ if (guessedDatabaseChangeType.value === "DDL") {+ return databaseList.value.filter((db) =>+ instanceV1HasAlterSchema(db.instanceEntity)+ );+ }++ return databaseList.value;+});++const schemalessDatabaseList = computed(() => {+ return databaseList.value.filter(+ (db) => !instanceV1HasAlterSchema(db.instanceEntity)+ );+});++const flattenSelectedDatabaseUidList = computed(() => {+ const flattenDatabaseIdList: string[] = [];+ for (const databaseIdList of state.selectedDatabaseUidListForEnvironment.values()) {+ flattenDatabaseIdList.push(...databaseIdList);+ }+ return flattenDatabaseIdList;+});++const nextButtonErrors = computed(() => {+ const errors: string[] = [];++ if (flattenSelectedDatabaseUidList.value.length === 0) {+ errors.push(t("changelist.error.select-at-least-one-database"));+ }+ return errors;+});++const handleSelectDatabase = (db: ComposedDatabase) => {+ console.log("handleSelectDatabase", db);+};++const handleClickNext = async () => {+ state.isGenerating = true;+ try {+ const databaseUIDList = [...flattenSelectedDatabaseUidList.value];+ const databaseList = databaseUIDList.map((uid) =>+ databaseStore.getDatabaseByUID(uid)+ );++ const query: Record<string, any> = {+ template:+ guessedDatabaseChangeType.value === "DDL"+ ? "bb.issue.database.schema.update"+ : "bb.issue.database.data.update",+ name: generateIssueName(+ databaseList.map((db) => db.databaseName),+ changelist.value+ ),+ project: project.value.uid,+ changelist: changelist.value.name,+ databaseList: databaseUIDList.join(","),+ };++ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query,+ });+ } catch {+ state.isGenerating = false;+ }+};++const reset = () => {+ state.selectedDatabaseUidListForEnvironment = new Map();+ state.keyword = "";+};++watch(+ show,+ (show) => {+ if (show) reset();+ },+ { immediate: true }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/index.ts b/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/index.tsnew file mode 100644index 0000000000..54841d2b76--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ApplyToDatabasePanel/index.ts@@ -0,0 +1,3 @@+import ApplyToDatabasePanel from "./ApplyToDatabasePanel.vue";++export default ApplyToDatabasePanel;diff --git a/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/BranchDetailPanel.vue b/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/BranchDetailPanel.vuenew file mode 100644index 0000000000..3e89938b06--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/BranchDetailPanel.vue@@ -0,0 +1,74 @@+<template>+ <Drawer :show="show" :close-on-esc="true" @close="$emit('close')">+ <DrawerContent+ :title="title"+ style="width: 60vw; max-width: calc(100vw - 8rem)"+ >+ <SchemaEditorV1+ v-if="editorBindings"+ :readonly="true"+ :project="editorBindings.project"+ :resource-type="'branch'"+ :databases="editorBindings.databases"+ :branches="editorBindings.branches"+ />+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import SchemaEditorV1 from "@/components/SchemaEditorV1/index.vue";+import { Drawer, DrawerContent } from "@/components/v2";+import { useDatabaseV1Store } from "@/store";+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";++const props = defineProps<{+ branchName?: string;+}>();++defineEmits<{+ (event: "close"): void;+}>();++const { t } = useI18n();+const title = ref(t("common.branch"));++const branch = computed(() => {+ const { branchName } = props;+ if (!branchName) {+ return undefined;+ }+ return useSchemaDesignStore().getSchemaDesignByName(branchName);+});++const editorBindings = computed(() => {+ if (!branch.value) {+ return undefined;+ }++ const db = useDatabaseV1Store().getDatabaseByName(+ branch.value.baselineDatabase+ );+ const project = db.projectEntity;++ return {+ readonly: true,+ project,+ resourceType: "branch",+ databases: [db],+ branches: [branch.value],+ };+});++const show = computed(() => {+ return branch.value !== undefined;+});++watch(branch, (branch) => {+ if (branch) {+ title.value = branch.title;+ }+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/index.ts b/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/index.tsnew file mode 100644index 0000000000..f4cd81c3ff--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/BranchDetailPanel/index.ts@@ -0,0 +1,3 @@+import BranchDetailPanel from "./BranchDetailPanel.vue";++export default BranchDetailPanel;diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/ChangeHistoryDetailPanel.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/ChangeHistoryDetailPanel.vuenew file mode 100644index 0000000000..2d35ff9754--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/ChangeHistoryDetailPanel.vue@@ -0,0 +1,54 @@+<template>+ <Drawer :show="show" :close-on-esc="true" @close="$emit('close')">+ <DrawerContent+ style="width: 60vw; max-width: calc(100vw - 8rem)"+ :title="$t('common.change-history')"+ >+ <ChangeHistoryDetail v-if="detailBindings" v-bind="detailBindings" />+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { Drawer, DrawerContent } from "@/components/v2";+import { useChangeHistoryStore } from "@/store";+import { changeHistorySlug, extractDatabaseResourceName } from "@/utils";+import ChangeHistoryDetail from "@/views/ChangeHistoryDetail.vue";++const props = defineProps<{+ changeHistoryName?: string;+}>();++defineEmits<{+ (event: "close"): void;+}>();++const changeHistory = computed(() => {+ const { changeHistoryName } = props;+ if (!changeHistoryName) {+ return undefined;+ }+ return useChangeHistoryStore().getChangeHistoryByName(changeHistoryName);+});++const detailBindings = computed(() => {+ if (!changeHistory.value) {+ return undefined;+ }+ const { instance, database } = extractDatabaseResourceName(+ changeHistory.value.name+ );+ const { uid, version } = changeHistory.value;+ const slug = changeHistorySlug(uid, version);+ return {+ instance,+ database,+ changeHistorySlug: slug,+ };+});++const show = computed(() => {+ return changeHistory.value !== undefined;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/index.ts b/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/index.tsnew file mode 100644index 0000000000..773ae2d5e4--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeHistoryDetailPanel/index.ts@@ -0,0 +1,3 @@+import ChangeHistoryDetailPanel from "./ChangeHistoryDetailPanel.vue";++export default ChangeHistoryDetailPanel;diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ChangeTable.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ChangeTable.vuenew file mode 100644index 0000000000..41d15f7fcc--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ChangeTable.vue@@ -0,0 +1,177 @@+<template>+ <BBGrid+ :data-source="changes"+ :column-list="columns"+ :show-placeholder="true"+ :custom-header="true"+ :row-clickable="true"+ class="border-y"+ @click-row="handleClickRow"+ >+ <template #header>+ <div role="table-row" class="bb-grid-row bb-grid-header-row group">+ <div+ v-for="(column, index) in columns"+ :key="index"+ role="table-cell"+ class="bb-grid-header-cell capitalize"+ :class="[column.class]"+ >+ <template v-if="index === 0">+ <NCheckbox+ :class="[reorderMode && 'invisible']"+ :checked="allSelectionState.checked"+ :indeterminate="allSelectionState.indeterminate"+ @update:checked="toggleSelectAll"+ />+ </template>+ <template v-else>{{ column.title }}</template>+ </div>+ </div>+ </template>++ <template #item="{ item: change, row }: BBGridRow<Change>">+ <div class="bb-grid-cell justify-center gap-x-1">+ <NCheckbox+ v-if="!reorderMode"+ :checked="isSelected(change)"+ @update:checked="toggleSelect(change, $event)"+ @click.stop+ />+ <ReorderButtons+ v-else+ :row="row"+ :changes="changes"+ @move="$emit('reorder-move', row, $event)"+ />+ </div>+ <div class="bb-grid-cell">+ <Source :change="change" />+ </div>++ <div class="bb-grid-cell">+ <RichDatabaseName+ v-if="databaseForChange(change)"+ :database="databaseForChange(change)!"+ :show-instance="false"+ :show-arrow="false"+ :show-production-environment-icon="false"+ tooltip="instance"+ />+ </div>+ <div class="bb-grid-cell">+ <SQL :change="change" />+ </div>+ <div class="bb-grid-cell">+ <RemoveChangeButton @click="$emit('remove-change', change)" />+ </div>+ </template>+ </BBGrid>+</template>++<script setup lang="ts">+import { NCheckbox } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { BBGrid, BBGridColumn, BBGridRow } from "@/bbkit";+import { RichDatabaseName } from "@/components/v2";+import { useDatabaseV1Store } from "@/store";+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import {+ extractDatabaseResourceName,+ isBranchChangeSource,+ isChangeHistoryChangeSource,+} from "@/utils";+import RemoveChangeButton from "./RemoveChangeButton.vue";+import ReorderButtons from "./ReorderButtons.vue";+import SQL from "./SQL.vue";+import Source from "./Source.vue";++const props = defineProps<{+ changes: Change[];+ selected: Change[];+ reorderMode: boolean;+}>();++const emit = defineEmits<{+ (event: "update:selected", selected: Change[]): void;+ (event: "select-change", change: Change): void;+ (event: "remove-change", change: Change): void;+ (event: "reorder-move", row: number, delta: -1 | 1): void;+}>();++const { t } = useI18n();++const columns = computed((): BBGridColumn[] => {+ return [+ { title: "", width: "4rem", class: "justify-center" },+ { title: t("changelist.change-source.source"), width: "auto" },+ { title: t("common.database"), width: "1fr" },+ { title: t("common.sql"), width: "3fr" },+ {+ title: "",+ width: "6rem",+ },+ ];+});++const allSelectionState = computed(() => {+ const { changes, selected } = props;+ const set = new Set(selected);++ const checked =+ selected.length > 0 && changes.every((change) => set.has(change));+ const indeterminate = !checked && selected.some((name) => set.has(name));++ return {+ checked,+ indeterminate,+ };+});++const toggleSelectAll = (on: boolean) => {+ if (on) {+ emit("update:selected", [...props.changes]);+ } else {+ emit("update:selected", []);+ }+};++const isSelected = (change: Change) => {+ return props.selected.includes(change);+};++const toggleSelect = (change: Change, on: boolean) => {+ const set = new Set(props.selected);+ if (on) {+ if (!set.has(change)) {+ set.add(change);+ emit("update:selected", Array.from(set));+ }+ } else {+ if (set.has(change)) {+ set.delete(change);+ emit("update:selected", Array.from(set));+ }+ }+};++const databaseForChange = (change: Change) => {+ const { source } = change;+ if (isChangeHistoryChangeSource(change)) {+ const { full: database } = extractDatabaseResourceName(source);+ return useDatabaseV1Store().getDatabaseByName(database);+ } else if (isBranchChangeSource(change)) {+ const branch = useSchemaDesignStore().getSchemaDesignByName(source);+ return useDatabaseV1Store().getDatabaseByName(branch.baselineDatabase);+ } else {+ // Raw SQL+ return undefined;+ }+};++const handleClickRow = (item: Change) => {+ emit("select-change", item);+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/RemoveChangeButton.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/RemoveChangeButton.vuenew file mode 100644index 0000000000..cb776460b5--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/RemoveChangeButton.vue@@ -0,0 +1,58 @@+<template>+ <NTooltip :disabled="errors.length === 0">+ <template #trigger>+ <NPopconfirm+ :disabled="errors.length > 0"+ @positive-click="$emit('click')"+ >+ <template #trigger>+ <NButton+ quaternary+ size="small"+ style="--n-padding: 0 6px"+ :disabled="errors.length > 0"+ @click.stop+ >+ <template #icon>+ <heroicons:trash />+ </template>+ </NButton>+ </template>++ <template #default>+ <div>{{ $t("changelist.confirm-remove-change") }}</div>+ </template>+ </NPopconfirm>+ </template>++ <template #default>+ <ErrorList :errors="errors" />+ </template>+ </NTooltip>+</template>++<script setup lang="ts">+import { NButton, NPopconfirm } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import ErrorList from "@/components/misc/ErrorList.vue";+import { useChangelistDetailContext } from "../context";++defineEmits<{+ (event: "click"): void;+}>();++const { t } = useI18n();+const { allowEdit } = useChangelistDetailContext();++const errors = computed(() => {+ const errors: string[] = [];+ if (!allowEdit.value) {+ errors.push(+ t("changelist.error.you-are-not-allowed-to-perform-this-action")+ );+ return errors;+ }+ return errors;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ReorderButtons.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ReorderButtons.vuenew file mode 100644index 0000000000..596dbd0af6--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/ReorderButtons.vue@@ -0,0 +1,43 @@+<template>+ <NButton+ size="tiny"+ style="--n-padding: 0 6px"+ :disabled="!allowMoveUp"+ @click.stop="$emit('move', -1)"+ >+ <template #icon>+ <heroicons:arrow-up />+ </template>+ </NButton>+ <NButton+ size="tiny"+ style="--n-padding: 0 6px"+ :disabled="!allowMoveDown"+ @click.stop="$emit('move', 1)"+ >+ <template #icon>+ <heroicons:arrow-down />+ </template>+ </NButton>+</template>++<script lang="ts" setup>+import { NButton } from "naive-ui";+import { computed } from "vue";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";++const props = defineProps<{+ changes: Change[];+ row: number;+}>();+defineEmits<{+ (event: "move", delta: -1 | 1): void;+}>();++const allowMoveUp = computed(() => {+ return props.row > 0;+});+const allowMoveDown = computed(() => {+ return props.row < props.changes.length - 1;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/SQL.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/SQL.vuenew file mode 100644index 0000000000..5cd467f186--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/SQL.vue@@ -0,0 +1,29 @@+<template>+ <TextOverflowPopover+ :content="statement"+ :max-length="100"+ content-class="line-clamp-1"+ placement="bottom"+ />+</template>++<script setup lang="ts">+import { computed } from "vue";+import TextOverflowPopover from "@/components/misc/TextOverflowPopover.vue";+import { useSheetV1Store } from "@/store";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { getSheetStatement } from "@/utils";++const props = defineProps<{+ change: Change;+}>();++const sheet = computed(() => {+ return useSheetV1Store().getSheetByName(props.change.sheet);+});++const statement = computed(() => {+ if (!sheet.value) return "";+ return getSheetStatement(sheet.value);+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/Source.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/Source.vuenew file mode 100644index 0000000000..d640e221f5--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/Source.vue@@ -0,0 +1,27 @@+<template>+ <div>+ <template v-if="type === 'CHANGE_HISTORY'">+ {{ $t("common.change-history") }}+ </template>+ <template v-if="type === 'BRANCH'">+ {{ $t("common.branch") }}+ </template>+ <template v-if="type === 'RAW_SQL'">+ {{ $t("changelist.change-source.raw-sql") }}+ </template>+ </div>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import { getChangelistChangeSourceType } from "@/utils";++const props = defineProps<{+ change: Change;+}>();++const type = computed(() => {+ return getChangelistChangeSourceType(props.change);+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/index.ts b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/index.tsnew file mode 100644index 0000000000..4bbbdaecfb--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangeTable/index.ts@@ -0,0 +1,3 @@+import ChangeTable from "./ChangeTable.vue";++export default ChangeTable;diff --git a/frontend/src/views/Changelist/ChangelistDetail/ChangelistDetail.vue b/frontend/src/views/Changelist/ChangelistDetail/ChangelistDetail.vuenew file mode 100644index 0000000000..9e67a9ea38--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/ChangelistDetail.vue@@ -0,0 +1,160 @@+<template>+ <div class="flex flex-col items-stretch gap-y-4 px-4 relative">+ <NavBar />++ <ChangeTable+ v-model:selected="selectedChanges"+ :changes="state.changes"+ :reorder-mode="reorderMode"+ @remove-change="handleRemoveChange($event)"+ @select-change="handleSelectChange($event)"+ @reorder-move="(row, delta) => handleReorderMove(row, delta)"+ />++ <div class="flex flex-row">+ <DeleteChangelistButton />+ </div>++ <AddChangePanel />++ <div+ v-if="isUpdating"+ class="absolute inset-0 bg-white/50 flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>++ <ChangeHistoryDetailPanel+ :change-history-name="state.detailChangeHistoryName"+ @close="state.detailChangeHistoryName = undefined"+ />+ <BranchDetailPanel+ :branch-name="state.detailBranchName"+ @close="state.detailBranchName = undefined"+ />+ <RawSQLPanel+ :sheet-name="state.detailRawSQLSheetName"+ @close="state.detailRawSQLSheetName = undefined"+ />++ <ApplyToDatabasePanel />+ </div>+</template>++<script lang="ts" setup>+import { computed, reactive, watch } from "vue";+import { useI18n } from "vue-i18n";+import { useRoute } from "vue-router";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import { pushNotification, useChangelistStore } from "@/store";+import {+ Changelist_Change as Change,+ Changelist,+} from "@/types/proto/v1/changelist_service";+import { getChangelistChangeSourceType } from "@/utils";+import AddChangePanel from "./AddChangePanel";+import ApplyToDatabasePanel from "./ApplyToDatabasePanel";+import BranchDetailPanel from "./BranchDetailPanel";+import ChangeHistoryDetailPanel from "./ChangeHistoryDetailPanel";+import ChangeTable from "./ChangeTable";+import DeleteChangelistButton from "./DeleteChangelistButton.vue";+import NavBar from "./NavBar";+import RawSQLPanel from "./RawSQLPanel";+import { provideChangelistDetailContext } from "./context";++const { t } = useI18n();+const route = useRoute();+const { changelist, reorderMode, selectedChanges, isUpdating, events } =+ provideChangelistDetailContext();++const state = reactive({+ changes: [] as Change[],+ detailChangeHistoryName: undefined as string | undefined,+ detailBranchName: undefined as string | undefined,+ detailRawSQLSheetName: undefined as string | undefined,+});++const patchChanges = async (changes: Change[]) => {+ const patch = {+ ...Changelist.fromPartial(changelist.value),+ changes,+ };+ try {+ isUpdating.value = true;+ await useChangelistStore().patchChangelist(patch, ["changes"]);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ } finally {+ isUpdating.value = false;+ }+};++const handleRemoveChange = async (change: Change) => {+ const changes = [...changelist.value.changes];+ const index = changes.indexOf(change);+ if (index < 0) {+ return;+ }+ changes.splice(index, 1);+ await patchChanges(changes);+};+const handleSelectChange = async (change: Change) => {+ const sourceType = getChangelistChangeSourceType(change);+ if (sourceType === "CHANGE_HISTORY") {+ state.detailChangeHistoryName = change.source;+ }+ if (sourceType === "BRANCH") {+ state.detailBranchName = change.source;+ }+ if (sourceType === "RAW_SQL") {+ state.detailRawSQLSheetName = change.sheet;+ }+};+const handleReorderMove = (row: number, delta: -1 | 1) => {+ const target = row + delta;+ const { changes } = state;+ if (target < 0 || target >= changes.length) {+ return;+ }+ const temp = changes[row];+ changes[row] = changes[target];+ changes[target] = temp;+};++const documentTitle = computed(() => {+ if (route.name !== "workspace.changelist.detail") {+ return undefined;+ }+ return changelist.value.description;+});+watch(+ documentTitle,+ (title) => {+ if (title) {+ document.title = title;+ }+ },+ { immediate: true }+);++useEmitteryEventListener(events, "reorder-cancel", () => {+ state.changes = [...changelist.value.changes];+ reorderMode.value = false;+});+useEmitteryEventListener(events, "reorder-confirm", async () => {+ const changes = [...state.changes];+ await patchChanges(changes);+ reorderMode.value = false;+});++watch(+ () => changelist.value.changes,+ (changes) => {+ state.changes = [...changes];+ },+ { immediate: true }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/DeleteChangelistButton.vue b/frontend/src/views/Changelist/ChangelistDetail/DeleteChangelistButton.vuenew file mode 100644index 0000000000..a730a2548e--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/DeleteChangelistButton.vue@@ -0,0 +1,75 @@+<template>+ <NTooltip :disabled="errors.length === 0">+ <template #trigger>+ <NPopconfirm :disabled="errors.length > 0" @positive-click="handleDelete">+ <template #trigger>+ <NButton+ quaternary+ size="small"+ style="--n-padding: 0 6px"+ :disabled="errors.length > 0"+ @click.stop+ >+ <template #icon>+ <heroicons:trash />+ </template>+ <template #default>+ {{ $t("common.delete") }}+ </template>+ </NButton>+ </template>++ <template #default>+ <div>{{ $t("changelist.confirm-delete-changelist") }}</div>+ </template>+ </NPopconfirm>+ </template>++ <template #default>+ <ErrorList :errors="errors" />+ </template>+ </NTooltip>+</template>++<script setup lang="ts">+import { NButton, NPopconfirm } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import ErrorList from "@/components/misc/ErrorList.vue";+import { pushNotification, useChangelistStore } from "@/store";+import { useChangelistDetailContext } from "./context";++const router = useRouter();+const { t } = useI18n();+const { allowEdit, changelist, isUpdating } = useChangelistDetailContext();++const errors = computed(() => {+ const errors: string[] = [];+ if (!allowEdit.value) {+ errors.push(+ t("changelist.error.you-are-not-allowed-to-perform-this-action")+ );+ return errors;+ }+ return errors;+});++const handleDelete = async () => {+ isUpdating.value = true;++ try {+ await useChangelistStore().deleteChangelist(changelist.value.name);+ router.push({+ name: "workspace.changelist.dashboard",+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.deleted"),+ });+ } catch {+ isUpdating.value = false;+ }+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/AddChangeButton.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/AddChangeButton.vuenew file mode 100644index 0000000000..df24d37954--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/AddChangeButton.vue@@ -0,0 +1,33 @@+<template>+ <ErrorTipsButton+ icon+ style="--n-padding: 0 10px"+ :errors="errors"+ @click="showAddChangePanel = true"+ >+ <template #icon>+ <heroicons:plus />+ </template>+ </ErrorTipsButton>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { ErrorTipsButton } from "@/components/v2";+import { useChangelistDetailContext } from "../context";++const { t } = useI18n();+const { allowEdit, showAddChangePanel } = useChangelistDetailContext();++const errors = computed(() => {+ const errors: string[] = [];+ if (!allowEdit.value) {+ errors.push(+ t("changelist.error.you-are-not-allowed-to-perform-this-action")+ );+ return errors;+ }+ return errors;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/ApplyToDatabaseButton.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ApplyToDatabaseButton.vuenew file mode 100644index 0000000000..a4629cfaba--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ApplyToDatabaseButton.vue@@ -0,0 +1,30 @@+<template>+ <ErrorTipsButton+ style="--n-padding: 0 10px"+ :errors="errors"+ :button-props="{+ type: 'primary',+ }"+ @click="showApplyToDatabasePanel = true"+ >+ {{ $t("changelist.apply-to-database") }}+ </ErrorTipsButton>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { ErrorTipsButton } from "@/components/v2";+import { useChangelistDetailContext } from "../context";++const { t } = useI18n();+const { changelist, showApplyToDatabasePanel } = useChangelistDetailContext();++const errors = computed(() => {+ const errors: string[] = [];+ if (changelist.value.changes.length === 0) {+ errors.push(t("changelist.error.add-at-least-one-change"));+ }+ return errors;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/ExportButton.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ExportButton.vuenew file mode 100644index 0000000000..a3fdc57117--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ExportButton.vue@@ -0,0 +1,66 @@+<template>+ <ErrorTipsButton+ icon+ style="--n-padding: 0 10px"+ :errors="errors"+ :button-props="{+ loading: isExporting,+ }"+ :disabled="isExporting"+ @click="handleExport"+ >+ <template #icon>+ <heroicons:arrow-down-tray />+ </template>+ </ErrorTipsButton>+</template>++<script setup lang="ts">+import dayjs from "dayjs";+import saveAs from "file-saver";+import JSZip from "jszip";+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { ErrorTipsButton } from "@/components/v2";+import { escapeFilename } from "@/utils";+import { useChangelistDetailContext } from "../context";+import { zipFileForChange } from "./export";++const { t } = useI18n();+const { changelist, selectedChanges } = useChangelistDetailContext();+const isExporting = ref(false);++const errors = computed(() => {+ const errors: string[] = [];+ if (selectedChanges.value.length === 0) {+ errors.push(t("changelist.error.select-at-least-one-change-to-export"));+ }+ return errors;+});++const handleExport = async () => {+ if (isExporting.value) {+ return;+ }++ isExporting.value = true;+ const zip = new JSZip();+ const changes = selectedChanges.value;+ for (let i = 0; i < changes.length; i++) {+ await zipFileForChange(zip, changes[i], i);+ }++ try {+ const content = await zip.generateAsync({ type: "blob" });+ const basename = `${changelist.value.description}_${dayjs().format(+ "YYYYMMDD"+ )}`;+ const fileName = `${escapeFilename(basename)}.zip`;+ saveAs(content, fileName);+ } catch (error) {+ console.error(error);+ }++ isExporting.value = false;+};+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/NavBar.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/NavBar.vuenew file mode 100644index 0000000000..f058799857--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/NavBar.vue@@ -0,0 +1,48 @@+<template>+ <div class="flex flex-row items-center justify-between gap-x-4">+ <div class="flex-1 flex items-center justify-start overflow-hidden">+ <ProjectV1Name :project="project" />+ <span class="ml-3 mr-0.5">/</span>+ <div class="flex-1 p-0.5 overflow-hidden truncate">+ <TitleEditor />+ </div>+ </div>+ <div class="flex items-center justify-end gap-x-3">+ <template v-if="!reorderMode">+ <ReorderButton @click="beginReorder" />+ <ExportButton />+ <AddChangeButton />+ <ApplyToDatabaseButton />+ </template>++ <template v-if="reorderMode">+ <NButton @click="cancelReorder">+ {{ $t("common.cancel") }}+ </NButton>+ <NButton type="primary" @click="confirmReorder">+ {{ $t("common.confirm") }}+ </NButton>+ </template>+ </div>+ </div>+</template>++<script setup lang="ts">+import { NButton } from "naive-ui";+import { ProjectV1Name } from "@/components/v2";+import { useChangelistDetailContext } from "../context";+import AddChangeButton from "./AddChangeButton.vue";+import ApplyToDatabaseButton from "./ApplyToDatabaseButton.vue";+import ExportButton from "./ExportButton.vue";+import ReorderButton from "./ReorderButton.vue";+import TitleEditor from "./TitleEditor.vue";+import { useReorderChangelist } from "./reorder";++const { project, reorderMode } = useChangelistDetailContext();++const {+ begin: beginReorder,+ cancel: cancelReorder,+ confirm: confirmReorder,+} = useReorderChangelist();+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/ReorderButton.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ReorderButton.vuenew file mode 100644index 0000000000..6591384310--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/ReorderButton.vue@@ -0,0 +1,31 @@+<template>+ <ErrorTipsButton icon style="--n-padding: 0 10px" :errors="errors">+ <template #icon>+ <heroicons:arrows-up-down />+ </template>+ </ErrorTipsButton>+</template>++<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { ErrorTipsButton } from "@/components/v2";+import { useChangelistDetailContext } from "../context";++const { t } = useI18n();+const { allowEdit, changelist } = useChangelistDetailContext();++const errors = computed(() => {+ const errors: string[] = [];+ if (!allowEdit.value) {+ errors.push(+ t("changelist.error.you-are-not-allowed-to-perform-this-action")+ );+ return errors;+ }+ if (changelist.value.changes.length === 0) {+ errors.push(t("changelist.error.add-at-least-one-change"));+ }+ return errors;+});+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/TitleEditor.vue b/frontend/src/views/Changelist/ChangelistDetail/NavBar/TitleEditor.vuenew file mode 100644index 0000000000..d2b24d0a63--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/TitleEditor.vue@@ -0,0 +1,97 @@+<template>+ <span v-if="!allowEdit" class="text-sm ml-2 py-1 leading-[34px]">+ {{ state.title }}+ </span>+ <NInput+ v-else+ :value="state.title"+ :style="style"+ :loading="state.isUpdating"+ :disabled="!allowEdit || state.isUpdating"+ autosize+ size="medium"+ required+ @focus="state.isEditing = true"+ @blur="onBlur"+ @keyup.enter="onEnter"+ @update:value="onUpdateValue"+ />+</template>++<script setup lang="ts">+import { NInput } from "naive-ui";+import { CSSProperties, computed, reactive, watch } from "vue";+import { useI18n } from "vue-i18n";+import { pushNotification, useChangelistStore } from "@/store";+import { Changelist } from "@/types/proto/v1/changelist_service";+import { useChangelistDetailContext } from "../context";++const { t } = useI18n();+const { changelist, allowEdit } = useChangelistDetailContext();++const state = reactive({+ isEditing: false,+ isUpdating: false,+ title: changelist.value.description,+});++const style = computed(() => {+ const style: CSSProperties = {+ cursor: "default",+ minWidth: "10rem",+ "--n-color-disabled": "transparent",+ "--n-padding-left": "0.5rem",+ "--n-padding-right": "0.5rem",+ };+ const border = state.isEditing+ ? "1px solid var(--color-control-border)"+ : "none";+ style["--n-border"] = border;+ style["--n-border-disabled"] = border;++ return style;+});++const onBlur = async () => {+ const cleanup = () => {+ state.isEditing = false;+ state.isUpdating = false;+ };++ if (state.title === changelist.value.description) {+ cleanup();+ return;+ }+ try {+ state.isUpdating = true;+ const patch = Changelist.fromPartial({+ ...changelist.value,+ description: state.title,+ });+ useChangelistStore().patchChangelist(patch, ["description"]);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ } finally {+ cleanup();+ }+};++const onEnter = (e: Event) => {+ const input = e.target as HTMLInputElement;+ input.blur();+};++const onUpdateValue = (title: string) => {+ state.title = title;+};++watch(+ () => changelist.value.description,+ (title) => {+ state.title = title;+ }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts b/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.tsnew file mode 100644index 0000000000..12777ebb8f--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts@@ -0,0 +1,118 @@+import JSZip from "jszip";+import { padStart } from "lodash-es";+import { useChangeHistoryStore, useSheetV1Store } from "@/store";+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";+import { Changelist_Change_Source as ChangeSource } from "@/types";+import { Changelist_Change as Change } from "@/types/proto/v1/changelist_service";+import {+ ChangeHistoryView,+ ChangeHistory_Status,+ ChangeHistory_Type,+} from "@/types/proto/v1/database_service";+import {+ escapeFilename,+ getChangelistChangeSourceType,+ getSheetStatement,+} from "@/utils";++const buildFileName = (type: ChangeSource, name: string, index: number) => {+ const parts = [padStart(String(index + 1), 2, "0")];+ parts.push(type);+ if (name) {+ parts.push(escapeFilename(name));+ }+ const basename = parts.join("-");+ return `${basename}.sql`;+};++const zipFileForChangeHistory = async (+ zip: JSZip,+ change: Change,+ index: number+) => {+ const name = change.source;+ const changeHistory = await useChangeHistoryStore().fetchChangeHistory({+ name,+ view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,+ });++ if (changeHistory) {+ if (changeHistory.status !== ChangeHistory_Status.DONE) {+ return;+ }++ if (+ changeHistory.type === ChangeHistory_Type.MIGRATE ||+ changeHistory.type === ChangeHistory_Type.MIGRATE_SDL ||+ changeHistory.type === ChangeHistory_Type.MIGRATE_GHOST ||+ changeHistory.type === ChangeHistory_Type.BRANCH ||+ changeHistory.type === ChangeHistory_Type.DATA+ ) {+ const filename = buildFileName(+ "CHANGE_HISTORY",+ changeHistory.version,+ index+ );+ zip.file(filename, changeHistory.statement);+ } else if (changeHistory.type === ChangeHistory_Type.BASELINE) {+ const filename = buildFileName(+ "CHANGE_HISTORY",+ `${changeHistory.version}_baseline`,+ index+ );+ zip.file(filename, changeHistory.schema);+ } else {+ // NOT SUPPORTED.+ return;+ }+ }+};++const zipFileForBranch = async (zip: JSZip, change: Change, index: number) => {+ const sheet = await useSheetV1Store().fetchSheetByName(+ change.sheet,+ true /* raw */+ );+ if (!sheet) {+ return;+ }+ const branch = await useSchemaDesignStore().getOrFetchSchemaDesignByName(+ change.source+ );+ if (!branch) {+ return;+ }++ const filename = buildFileName("BRANCH", branch.title, index);+ zip.file(filename, getSheetStatement(sheet));+};++const zipFileForRawSQL = async (zip: JSZip, change: Change, index: number) => {+ const sheet = await useSheetV1Store().fetchSheetByName(+ change.sheet,+ true /* raw */+ );+ if (!sheet) {+ return;+ }++ const filename = buildFileName("RAW_SQL", "", index);+ zip.file(filename, getSheetStatement(sheet));+};++export const zipFileForChange = async (+ zip: JSZip,+ change: Change,+ index: number+) => {+ const type = getChangelistChangeSourceType(change);+ if (type === "CHANGE_HISTORY") {+ await zipFileForChangeHistory(zip, change, index);+ }+ if (type === "BRANCH") {+ await zipFileForBranch(zip, change, index);+ }+ if (type === "RAW_SQL") {+ await zipFileForRawSQL(zip, change, index);+ }+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/index.ts b/frontend/src/views/Changelist/ChangelistDetail/NavBar/index.tsnew file mode 100644index 0000000000..0a296d688c--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/index.ts@@ -0,0 +1,3 @@+import NavBar from "./NavBar.vue";++export default NavBar;diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/reorder.ts b/frontend/src/views/Changelist/ChangelistDetail/NavBar/reorder.tsnew file mode 100644index 0000000000..c61477c529--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/reorder.ts@@ -0,0 +1,20 @@+import { useChangelistDetailContext } from "../context";++export const useReorderChangelist = () => {+ const { reorderMode, events } = useChangelistDetailContext();++ const begin = () => {+ reorderMode.value = true;+ };+ const cancel = () => {+ events.emit("reorder-cancel");+ };+ const confirm = () => {+ events.emit("reorder-confirm");+ };+ return {+ begin,+ cancel,+ confirm,+ };+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue b/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vuenew file mode 100644index 0000000000..57100fcb11--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue@@ -0,0 +1,58 @@+<template>+ <div class="flex flex-col gap-y-2">+ <div v-if="!readonly" class="flex justify-end">+ <UploadProgressButton size="tiny" :upload="handleUploadFile">+ {{ $t("issue.upload-sql") }}+ </UploadProgressButton>+ </div>++ <div+ ref="editorWrapperRef"+ class="flex-1 overflow-hidden"+ :data-height="editorWrapperHeight"+ >+ <MonacoEditor+ ref="editorRef"+ :value="statement"+ :readonly="readonly || isSheetOversize"+ class="border w-full h-full"+ @change="$emit('update:statement', $event)"+ @ready="adjustEditorHeight"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { useElementSize } from "@vueuse/core";+import { ref, watch } from "vue";+import MonacoEditor from "@/components/MonacoEditor";+import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";++defineProps<{+ statement: string;+ readonly: boolean;+ isSheetOversize?: boolean;+}>();++const emit = defineEmits<{+ (event: "update:statement", statement: string): void;+ (event: "upload", e: Event): void;+}>();++const editorWrapperRef = ref<HTMLDivElement>();+const editorRef = ref<InstanceType<typeof MonacoEditor>>();+const { height: editorWrapperHeight } = useElementSize(editorWrapperRef);++const handleUploadFile = async (event: Event) => {+ emit("upload", event);+};++const adjustEditorHeight = () => {+ const editor = editorRef.value;+ if (!editor) return;+ editor.setEditorContentHeight(editorWrapperHeight.value);+};++watch(editorWrapperHeight, adjustEditorHeight);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/index.ts b/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/index.tsnew file mode 100644index 0000000000..426f84c794--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/RawSQLEditor/index.ts@@ -0,0 +1,3 @@+import RawSQLEditor from "./RawSQLEditor.vue";++export default RawSQLEditor;diff --git a/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue b/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vuenew file mode 100644index 0000000000..00d60ca5ff--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue@@ -0,0 +1,177 @@+<template>+ <Drawer :show="show" :close-on-esc="!dirty" @close="$emit('close')">+ <DrawerContent+ :title="title"+ class="relative"+ style="width: 60vw; max-width: calc(100vw - 8rem)"+ >+ <template #default>+ <div class="h-full flex flex-col gap-y-4 flex-1 overflow-hidden">+ <BBAttention+ v-if="isSheetOversize"+ :style="`WARN`"+ :title="$t('issue.statement-from-sheet-warning')"+ >+ <template #action>+ <DownloadSheetButton+ v-if="sheetName"+ :sheet="sheetName"+ size="small"+ />+ </template>+ </BBAttention>+ <RawSQLEditor+ v-if="sheet"+ v-model:statement="statement"+ :readonly="!allowEdit"+ :is-sheet-oversize="isSheetOversize"+ class="flex-1 overflow-hidden relative"+ @upload="handleUploadEvent"+ />+ </div>+ <div+ v-if="isUpdating"+ v-zindexable="{ enabled: true }"+ class="absolute bg-white/50 inset-0 flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>++ <template #footer>+ <div class="flex items-center justify-end gap-x-3">+ <NButton @click="$emit('close')">+ {{ $t("common.cancel") }}+ </NButton>++ <ErrorTipsButton+ v-if="allowEdit"+ :errors="errors"+ :button-props="{+ type: 'primary',+ }"+ @click="doSaveChange"+ >+ {{ $t("common.save") }}+ </ErrorTipsButton>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { zindexable as vZindexable } from "vdirs";+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { BBAttention } from "@/bbkit";+import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";+import { Drawer, DrawerContent } from "@/components/v2";+import { pushNotification, useSheetV1Store } from "@/store";+import { Sheet } from "@/types/proto/v1/sheet_service";+import { getSheetStatement, readFileAsync, setSheetStatement } from "@/utils";+import RawSQLEditor from "../RawSQLEditor";+import { useChangelistDetailContext } from "../context";++const props = defineProps<{+ sheetName?: string;+}>();++const emit = defineEmits<{+ (event: "close"): void;+}>();++const sheetStore = useSheetV1Store();+const { t } = useI18n();+const { allowEdit } = useChangelistDetailContext();+const title = ref(t("changelist.change-source.raw-sql"));+const statement = ref("");+const isUpdating = ref(false);++const sheet = computed(() => {+ const { sheetName } = props;+ if (!sheetName) return undefined;+ return sheetStore.getSheetByName(sheetName);+});++const show = computed(() => {+ return sheet.value !== undefined;+});++const isSheetOversize = computed(() => {+ if (!sheet.value) return false;+ return getSheetStatement(sheet.value).length < sheet.value.contentSize;+});++const dirty = computed(() => {+ if (!sheet.value) return false;+ return statement.value !== getSheetStatement(sheet.value);+});++const errors = computed(() => {+ const errors: string[] = [];+ if (statement.value.trim().length === 0) {+ errors.push(t("changelist.error.sql-cannot-be-empty"));+ }+ if (!dirty.value) {+ errors.push(t("changelist.error.nothing-changed"));+ }+ return errors;+});++const reset = () => {+ if (!sheet.value) {+ statement.value = "";+ } else {+ statement.value = getSheetStatement(sheet.value);+ }+};++const handleUploadEvent = async (e: Event) => {+ try {+ const { content } = await readFileAsync(e, 100);+ statement.value = content;+ } finally {+ // Nothing+ }+};++const doSaveChange = async () => {+ if (!sheet.value) {+ return;+ }+ if (errors.value.length > 0) {+ return;+ }++ try {+ isUpdating.value = true;+ const patch = Sheet.fromPartial({+ name: sheet.value.name,+ });+ setSheetStatement(patch, statement.value);+ await sheetStore.patchSheet(patch, ["content"]);++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ emit("close");+ } finally {+ isUpdating.value = false;+ }+};++watch(sheet, reset, { immediate: true });++watch(+ show,+ (show) => {+ if (show) {+ reset();+ }+ },+ { immediate: true }+);+</script>diff --git a/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/index.ts b/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/index.tsnew file mode 100644index 0000000000..f79ca16ca0--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/RawSQLPanel/index.ts@@ -0,0 +1,3 @@+import RawSQLPanel from "./RawSQLPanel.vue";++export default RawSQLPanel;diff --git a/frontend/src/views/Changelist/ChangelistDetail/common.ts b/frontend/src/views/Changelist/ChangelistDetail/common.tsnew file mode 100644index 0000000000..ead72c09b2--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/common.ts@@ -0,0 +1,21 @@+import dayjs from "@/plugins/dayjs";+import { Changelist } from "@/types/proto/v1/changelist_service";++export const generateIssueName = (+ databaseNameList: string[],+ changelist: Changelist+) => {+ // Create a user friendly default issue name+ const issueNameParts: string[] = [];+ if (databaseNameList.length === 1) {+ issueNameParts.push(`[${databaseNameList[0]}]`);+ } else {+ issueNameParts.push(`[${databaseNameList.length} databases]`);+ }+ issueNameParts.push(`Apply changelist [${changelist.description}]`);+ const datetime = dayjs().format("@MM-DD HH:mm");+ const tz = "UTC" + dayjs().format("ZZ");+ issueNameParts.push(`${datetime} ${tz}`);++ return issueNameParts.join(" ");+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/context.ts b/frontend/src/views/Changelist/ChangelistDetail/context.tsnew file mode 100644index 0000000000..1ca2e92acd--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/context.ts@@ -0,0 +1,101 @@+import Emittery from "emittery";+import { InjectionKey, Ref, computed, inject, provide, ref } from "vue";+import { useRoute } from "vue-router";+import {+ useChangelistStore,+ useCurrentUserV1,+ useProjectV1Store,+} from "@/store";+import { ComposedProject, unknownChangelist } from "@/types";+import {+ Changelist,+ Changelist_Change as Change,+} from "@/types/proto/v1/changelist_service";+import {+ extractUserResourceName,+ hasWorkspacePermissionV1,+ isOwnerOfProjectV1,+} from "@/utils";++export type ChangelistDetailEvents = Emittery<{+ "reorder-cancel": undefined;+ "reorder-confirm": undefined;+}>;++export type ChangelistDetailContext = {+ changelist: Ref<Changelist>;+ project: Ref<ComposedProject>;+ allowEdit: Ref<boolean>;+ reorderMode: Ref<boolean>;+ selectedChanges: Ref<Change[]>;+ showAddChangePanel: Ref<boolean>;+ showApplyToDatabasePanel: Ref<boolean>;+ isUpdating: Ref<boolean>;++ events: ChangelistDetailEvents;+};++export const KEY = Symbol(+ "bb.changelist.detail"+) as InjectionKey<ChangelistDetailContext>;++export const useChangelistDetailContext = () => {+ return inject(KEY)!;+};++export const provideChangelistDetailContext = () => {+ const me = useCurrentUserV1();+ const route = useRoute();+ const name = computed(() => {+ return `projects/${route.params.projectName}/changelists/${route.params.changelistName}`;+ });+ const changelist = computed(() => {+ return (+ useChangelistStore().getChangelistByName(name.value) ??+ unknownChangelist()+ );+ });+ const project = computed(() => {+ return useProjectV1Store().getProjectByName(+ `projects/${route.params.projectName}`+ );+ });+ const allowEdit = computed(() => {+ if (+ hasWorkspacePermissionV1(+ "bb.permission.workspace.manage-issue",+ me.value.userRole+ )+ ) {+ // Allow workspace high-privileged user to edit all changelists.+ return true;+ }+ if (isOwnerOfProjectV1(project.value.iamPolicy, me.value)) {+ // Allow project owners to edit all changelists in the project.+ return true;+ }+ if (extractUserResourceName(changelist.value.creator) === me.value.email) {+ // Allow the initial creator of the changelist to edit it.+ return true;+ }+ // Disallowed to edit otherwise.+ return false;+ });++ const context: ChangelistDetailContext = {+ changelist,+ project,+ allowEdit,+ reorderMode: ref(false),+ selectedChanges: ref([]),+ showAddChangePanel: ref(false),+ showApplyToDatabasePanel: ref(false),+ isUpdating: ref(false),++ events: new Emittery(),+ };++ provide(KEY, context);++ return context;+};diff --git a/frontend/src/views/Changelist/ChangelistDetail/index.ts b/frontend/src/views/Changelist/ChangelistDetail/index.tsnew file mode 100644index 0000000000..55ba44e63d--- /dev/null+++ b/frontend/src/views/Changelist/ChangelistDetail/index.ts@@ -0,0 +1,3 @@+import ChangelistDetail from "./ChangelistDetail.vue";++export default ChangelistDetail;diff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vueindex 7021d606e7..4b66c9b3fb 100644--- a/frontend/src/views/DashboardSidebar.vue+++ b/frontend/src/views/DashboardSidebar.vue@@ -46,6 +46,16 @@<img src="../assets/slow-query.svg" class="w-5 h-auto mr-2" />{{ $t("slow-query.slow-queries") }}</router-link>+ <router-link+ v-if="isDev"+ to="/changelists"+ class="outline-item group flex items-center px-2 py-1.5 capitalize"+ >+ <div class="flex items-center justify-center w-5 h-5 mr-2">+ <PencilRuler :size="16" />+ </div>+ {{ $t("changelist.change-center") }}+ </router-link><router-linkto="/export-center"class="outline-item group flex items-center px-2 py-1.5 capitalize"@@ -75,6 +85,7 @@<script lang="ts" setup>import { useKBarHandler } from "@bytebase/vue-kbar";+import { PencilRuler } from "lucide-vue-next";import { computed } from "vue";import BookmarkListSidePanel from "@/components/BookmarkListSidePanel.vue";import BytebaseLogo from "@/components/BytebaseLogo.vue";