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: ghost for tenant mode (#3886)
p0ny69cac5328f0a
diff --git a/api/issue.go b/api/issue.goindex be06ded6de..bd37c34f82 100644--- a/api/issue.go+++ b/api/issue.go@@ -186,28 +186,6 @@ type MigrationFileYAML struct {Statement string `yaml:"statement"` // The SQL statement to be executed to specified list of databases}-// UpdateSchemaGhostDetail is the detail of updating database schema using gh-ost.-type UpdateSchemaGhostDetail struct {- // DatabaseID is the ID of a database.- DatabaseID int `json:"databaseId"`- // DatabaseName is the name of databases, mutually exclusive to DatabaseID.- // This should be set when a project is in tenant mode, and ProjectID is derived from IssueCreate.- DatabaseName string `json:"databaseName"`- // Statement is the statement to update database schema.- Statement string `json:"statement"`- // EarliestAllowedTs the earliest execution time of the change at system local Unix timestamp in seconds.- EarliestAllowedTs int64 `jsonapi:"attr,earliestAllowedTs"`-}--// UpdateSchemaGhostContext is the issue create context for updating database schema using gh-ost.-type UpdateSchemaGhostContext struct {- // DetailList is the details of schema update.- // When a project is in tenant mode, there should be one item in the list.- DetailList []*UpdateSchemaGhostDetail `json:"detailList"`- // VCSPushEvent is the event information for VCS push.- VCSPushEvent *vcs.PushEvent-}-// PITRContext is the issue create context for performing a PITR in a database.type PITRContext struct {DatabaseID int `json:"databaseId"`diff --git a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vueindex bf11c06508..b356ea2ac1 100644--- a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue+++ b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue@@ -147,6 +147,7 @@<SchemaEditorModalv-if="state.showSchemaEditorModal":database-id-list="schemaEditorContext.databaseIdList"+ :alter-type="state.alterType"@close="state.showSchemaEditorModal = false"/></template>diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 51231fd631..ee0454c9df 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -167,6 +167,10 @@ const props = defineProps({type: Array as PropType<DatabaseId[]>,required: true,},+ alterType: {+ type: String as PropType<"TENANT" | "MULTI_DB" | "SINGLE_DB">,+ required: true,+ },});const emit = defineEmits<{@@ -252,11 +256,6 @@ const dismissModal = () => {// 'online' -> online migration// false -> user clicked cancel buttonconst isUsingGhostMigration = async (databaseList: Database[]) => {- // Gh-ost is not available for tenant mode yet.- if (databaseList.some((db) => db.project.tenantMode === "TENANT")) {- return "normal";- }-// check if all selected databases supports gh-ostif (allowGhostMigration(databaseList)) {// open the dialog to ask the user@@ -384,26 +383,33 @@ const handlePreviewIssue = async () => {const query: Record<string, any> = {template: "bb.issue.database.schema.update",project: project.id,- mode: isTenantProject ? "tenant" : "normal",- databaseList: props.databaseIdList.join(","),+ mode: "normal",+ ghost: undefined,};-+ if (isTenantProject && props.databaseIdList.length > 1) {+ query.mode = "tenant";+ }+ if (props.alterType !== "TENANT") {+ // If we are not using tenant deployment config pipeline+ // we need to pass the databaseIdList explicitly.+ query.databaseList = props.databaseIdList.join(",");+ }if (state.selectedTab === "raw-sql") {query.sql = state.editStatement;- if (!isTenantProject) {- // We should show select ghost mode dialog only for altering table statment not create/drop table.- // TODO(steven): parse the sql check if there only alter table statement.- const actionResult = await isUsingGhostMigration(databaseList);- if (actionResult === false) {- return;- }- query.mode = actionResult;- query.name = generateIssueName(- databaseList.map((db) => db.name),- query.mode === "online"- );+ // We should show select ghost mode dialog only for altering table statement not create/drop table.+ // TODO(steven): parse the sql check if there only alter table statement.+ const actionResult = await isUsingGhostMigration(databaseList);+ if (actionResult === false) {+ return;}+ if (actionResult === "online") {+ query.ghost = 1;+ }+ query.name = generateIssueName(+ databaseList.map((db) => db.name),+ !!query.ghost+ );} else {const databaseEditList = getDatabaseEditListWithSchemaEditor();const validateResultList = [];@@ -429,12 +435,14 @@ const handlePreviewIssue = async () => {return;}- if (!isTenantProject && hasOnlyAlterTableChanges) {+ if (hasOnlyAlterTableChanges) {const actionResult = await isUsingGhostMigration(databaseList);if (actionResult === false) {return;}- query.mode = actionResult;+ if (actionResult === "online") {+ query.ghost = 1;+ }}const statementMap = await fetchDatabaseEditStatementMapWithSchemaEditor();@@ -442,26 +450,23 @@ const handlePreviewIssue = async () => {return;}const databaseIdList = Array.from(statementMap.keys());- const statmentList = Array.from(statementMap.values());+ const statementList = Array.from(statementMap.values());if (isTenantProject) {- query.sql = statmentList.join("\n");+ query.sql = statementList.join("\n");query.name = generateIssueName(databaseList.map((db) => db.name),- query.mode === "online"+ !!query.ghost);} else {query.databaseList = databaseIdList.join(",");- query.sqlList = JSON.stringify(statmentList);+ query.sqlList = JSON.stringify(statementList);const databaseNameList = databaseList.filter((database) => databaseIdList.includes(database.id)).map((db) => db.name);- query.name = generateIssueName(databaseNameList, query.mode === "online");+ query.name = generateIssueName(databaseNameList, !!query.ghost);}}- if (query.mode === "online") {- query.ghost = 1;- }router.push({name: "workspace.issue.detail",params: {diff --git a/frontend/src/components/Issue/IssueDetailLayout.vue b/frontend/src/components/Issue/IssueDetailLayout.vueindex 42d67fd542..71420cfd48 100644--- a/frontend/src/components/Issue/IssueDetailLayout.vue+++ b/frontend/src/components/Issue/IssueDetailLayout.vue@@ -24,12 +24,12 @@<!-- Stage Flow Bar --><template v-if="showPipelineFlowBar">- <template v-if="isTenantMode">- <PipelineTenantFlow v-if="project" class="border-t border-b" />- </template>- <template v-else-if="isGhostMode">+ <template v-if="isGhostMode"><PipelineGhostFlow v-if="project" class="border-t border-b" /></template>+ <template v-else-if="isTenantMode">+ <PipelineTenantFlow v-if="project" class="border-t border-b" />+ </template><template v-else-if="isPITRMode"><PipelinePITRFlow v-if="project" class="border-t border-b" /></template>@@ -190,14 +190,17 @@ const {isValidStage,allowApplyIssueStatusTransition,allowApplyTaskStatusTransition,+ selectedStatement,+ allowApplyStatementToOtherTasks,+ applyStatementToOtherTasks,} = useBaseIssueLogic({ issue, create });const issueLogic = ref<IssueLogic>();// Determine which type of IssueLogicProvider should be usedconst logicProviderType = computed(() => {- if (isTenantMode.value) return TenantModeProvider;if (isGhostMode.value) return GhostModeProvider;+ if (isTenantMode.value) return TenantModeProvider;return StandardModeProvider;});@@ -384,6 +387,9 @@ provideIssueLogic(createIssue,allowApplyIssueStatusTransition,allowApplyTaskStatusTransition,+ selectedStatement,+ allowApplyStatementToOtherTasks,+ applyStatementToOtherTasks,},true// This is the root logic, could be overwritten by other (standard, gh-ost, tenant...) logic providers.diff --git a/frontend/src/components/Issue/PipelineGhostFlow.vue b/frontend/src/components/Issue/PipelineGhostFlow.vueindex c9a1d6ac2d..6168b469ae 100644--- a/frontend/src/components/Issue/PipelineGhostFlow.vue+++ b/frontend/src/components/Issue/PipelineGhostFlow.vue@@ -6,67 +6,74 @@</template></PipelineStageList>- <div- class="task-list p-2 lg:flex lg:items-center relative space-y-2 lg:space-y-0"- >- <template v-for="(task, i) in taskList" :key="i">- <div- class="task px-2 py-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-center"- :class="taskClass(task)"- @click="onClickTask(task, i)"- >- <div class="flex-1">- <div class="flex items-center pb-1">- <div class="flex flex-1 items-center">- <TaskStatusIcon- :create="create"- :active="isActiveTask(task)"- :status="task.status"- class="transform scale-75"- />- <heroicons-solid:arrow-narrow-right- v-if="isActiveTask(task)"- class="name w-5 h-5"- />- <div class="name">{{ databaseOfTask(task).name }}</div>+ <div class="relative">+ <div+ ref="taskBar"+ class="task-list gap-2 p-2 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 4xl:grid-cols-6 max-h-48 overflow-y-auto"+ :class="{+ 'more-bottom': taskBarScrollState.bottom,+ 'more-top': taskBarScrollState.top,+ }"+ >+ <template v-for="(task, i) in taskList" :key="i">+ <div+ class="task relative px-2 py-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-center"+ :class="taskClass(task)"+ @click="onClickTask(task, i)"+ >+ <div class="flex-1">+ <div class="flex items-center pb-1">+ <div class="flex flex-1 items-center">+ <TaskStatusIcon+ :create="create"+ :active="isActiveTask(task)"+ :status="task.status"+ class="transform scale-75"+ />+ <heroicons-solid:arrow-narrow-right+ v-if="isActiveTask(task)"+ class="name w-5 h-5"+ />+ <div class="name">{{ databaseOfTask(task).name }}</div>+ </div>++ <TaskExtraActionsButton :task="(task as Task)" /></div>- <TaskExtraActionsButton :task="(task as Task)" />+ <div class="flex items-center justify-between px-1 py-1">+ <div+ class="flex flex-1 items-center whitespace-pre-wrap break-all"+ >+ {{ taskNameOfTask(task) }}+ </div>+ </div></div>- <div class="flex items-center justify-between px-1 py-1">- <div- class="flex flex-1 items-center whitespace-pre-wrap break-all"- >- {{ taskNameOfTask(task) }}- </div>+ <TaskProgressPie+ v-if="+ !create &&+ task.type === 'bb.task.database.schema.update.ghost.sync'+ "+ :task="(task as Task)"+ unit-key="row"+ />++ <div+ v-if="task.type === 'bb.task.database.schema.update.ghost.sync'"+ class="hidden md:flex items-center justify-center w-4 h-2 overflow-visible absolute -right-[13px]"+ >+ <!-- show an arrow indicator between tasks -->+ <heroicons-outline:chevron-right class="w-4 h-4" /></div></div>-- <TaskProgressPie- v-if="- !create &&- task.type === 'bb.task.database.schema.update.ghost.sync'- "- :task="(task as Task)"- unit-key="row"- />- </div>-- <div- v-if="i < taskList.length - 1"- class="hidden lg:flex items-center justify-center w-4 h-2 overflow-visible relative"- >- <!-- show an arrow indicator between tasks -->- <heroicons-outline:chevron-right class="w-4 h-4" />- </div>- </template>+ </template>+ </div></div></div></template><script lang="ts" setup>-import { computed } from "vue";+import { computed, ref } from "vue";import { useI18n } from "vue-i18n";import type {Pipeline,@@ -83,12 +90,15 @@ import PipelineStageList from "./PipelineStageList.vue";import TaskProgressPie from "./TaskProgressPie.vue";import TaskExtraActionsButton from "./TaskExtraActionsButton.vue";import { useIssueLogic } from "./logic";+import { useVerticalScrollState } from "@/composables/useScrollState";const { t } = useI18n();const databaseStore = useDatabaseStore();const { create, issue, selectedStage, selectedTask, selectStageOrTask } =useIssueLogic();+const taskBar = ref<HTMLDivElement>();+const taskBarScrollState = useVerticalScrollState(taskBar, 192);const pipeline = computed(() => issue.value.pipeline!);@@ -188,4 +198,21 @@ const onClickTask = (task: Task | TaskCreate, index: number) => {.task.status_failed .name {@apply text-red-500;}++.task-list::before {+ @apply absolute top-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;+ content: "";+ box-shadow: none;+}+.task-list::after {+ @apply absolute bottom-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;+ content: "";+ box-shadow: none;+}+.task-list.more-top::before {+ box-shadow: inset 0 0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);+}+.task-list.more-bottom::after {+ box-shadow: inset 0 -0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);+}</style>diff --git a/frontend/src/components/Issue/logic/GhostModeProvider.ts b/frontend/src/components/Issue/logic/GhostModeProvider.tsindex 447b1047f3..97e968a124 100644--- a/frontend/src/components/Issue/logic/GhostModeProvider.ts+++ b/frontend/src/components/Issue/logic/GhostModeProvider.ts@@ -1,16 +1,24 @@import { computed, defineComponent } from "vue";import { cloneDeep } from "lodash-es";import { provideIssueLogic, useIssueLogic } from "./index";-import { maybeFormatStatementOnSave, useCommonLogic } from "./common";import {+ flattenTaskList,+ maybeFormatStatementOnSave,+ TaskTypeWithStatement,+ useCommonLogic,+} from "./common";+import {+ Issue,IssueCreate,Task,TaskCreate,TaskDatabaseSchemaUpdateGhostSyncPayload,TaskStatus,- UpdateSchemaGhostContext,+ MigrationContext,+ TaskId,+ TaskPatch,} from "@/types";-import { useDatabaseStore } from "@/store";+import { useDatabaseStore, useTaskStore } from "@/store";export default defineComponent({name: "GhostModeProvider",@@ -20,47 +28,163 @@ export default defineComponent({issue,selectedTask,createIssue,+ isTenantMode,allowApplyTaskStatusTransition: baseAllowApplyTaskStatusTransition,+ allowApplyStatementToOtherTasks: baseAllowApplyStatementToOtherTasks,+ applyStatementToOtherTasks: baseApplyStatementToOtherTasks,+ onStatusChanged,} = useIssueLogic();const databaseStore = useDatabaseStore();+ const taskStore = useTaskStore();++ const patchTask = (+ taskId: TaskId,+ taskPatch: TaskPatch,+ postUpdated?: (updatedTask: Task) => void+ ) => {+ taskStore+ .patchTask({+ issueId: (issue.value as Issue).id,+ pipelineId: (issue.value as Issue).pipeline.id,+ taskId,+ taskPatch,+ })+ .then((updatedTask) => {+ // For now, the only task/patchTask is to change statement, which will trigger async task check.+ // Thus we use the short poll interval+ onStatusChanged(true);+ if (postUpdated) {+ postUpdated(updatedTask);+ }+ });+ };- // In gh-ost mode, each stage can own its SQL statement- // But only for task.type === "bb.task.database.schema.update.ghost.sync"const selectedStatement = computed(() => {- const task = selectedTask.value;- if (task.type === "bb.task.database.schema.update.ghost.sync") {+ if (isTenantMode.value) {+ // In tenant mode, the entire issue shares only one SQL statementif (create.value) {- return (task as TaskCreate).statement;+ const issueCreate = issue.value as IssueCreate;+ const context = issueCreate.createContext as MigrationContext;+ return context.detailList[0].statement;} else {- const payload = (task as Task)- .payload as TaskDatabaseSchemaUpdateGhostSyncPayload;+ const issueEntity = issue.value as Issue;+ const task = issueEntity.pipeline.stageList[0].taskList[0];+ const payload =+ task.payload as TaskDatabaseSchemaUpdateGhostSyncPayload;return payload.statement;}} else {- return "";+ // In standard pipeline, each ghost-sync task can hold its own+ // statement+ const task = selectedTask.value;+ if (task.type === "bb.task.database.schema.update.ghost.sync") {+ if (create.value) {+ return (task as TaskCreate).statement;+ } else {+ const payload = (task as Task)+ .payload as TaskDatabaseSchemaUpdateGhostSyncPayload;+ return payload.statement;+ }+ } else {+ return "";+ }}});+ const updateStatement = (+ newStatement: string,+ postUpdated?: (updatedTask: Task) => void+ ) => {+ if (isTenantMode.value) {+ if (create.value) {+ // For tenant deploy mode, we apply the statement to all stages and all tasks+ const allTaskList = flattenTaskList<TaskCreate>(issue.value);+ allTaskList.forEach((task) => {+ if (TaskTypeWithStatement.includes(task.type)) {+ task.statement = newStatement;+ }+ });++ const issueCreate = issue.value as IssueCreate;+ const context = issueCreate.createContext as MigrationContext;+ // We also apply it back to the CreateContext+ context.detailList.forEach(+ (detail) => (detail.statement = newStatement)+ );+ } else {+ const issueEntity = issue.value as Issue;+ taskStore+ .patchAllTasksInIssue({+ issueId: issueEntity.id,+ pipelineId: issueEntity.pipeline.id,+ taskPatch: {+ statement: newStatement,+ },+ })+ .then(() => {+ onStatusChanged(true);+ if (postUpdated) {+ postUpdated(issueEntity.pipeline.stageList[0].taskList[0]);+ }+ });+ }+ } else {+ if (create.value) {+ const task = selectedTask.value as TaskCreate;+ task.statement = newStatement;+ } else {+ // otherwise, patch the task+ const task = selectedTask.value as Task;+ patchTask(+ task.id,+ {+ statement: maybeFormatStatementOnSave(+ newStatement,+ task.database+ ),+ updatedTs: task.updatedTs,+ },+ postUpdated+ );+ }+ }+ };+const doCreate = () => {const issueCreate = cloneDeep(issue.value as IssueCreate);- // for gh-ost mode, copy user edited tasks back to issue.createContext- // only the first subtask (bb.task.database.schema.update.ghost.sync) has statement- const stageList = issueCreate.pipeline!.stageList;- const createContext =- issueCreate.createContext as UpdateSchemaGhostContext;- const detailList = createContext.detailList;- stageList.forEach((stage, i) => {- const detail = detailList[i];- const syncTask = stage.taskList.find(+ if (isTenantMode.value) {+ // for tenant pipeline+ // createContext is up-to-date already+ // so we just format the statement if needed+ const context = issueCreate.createContext as MigrationContext;+ context.detailList.forEach((detail) => {+ const db = databaseStore.getDatabaseById(detail.databaseId!);+ detail.statement = maybeFormatStatementOnSave(detail.statement, db);+ });+ } else {+ // for standard pipeline, we copy user edited tasks back to+ // issue.createContext+ // For each ghost-sync task, we copy its edited statement back to the+ // createContext.detailList by its databaseId accordingly.+ const createContext = issueCreate.createContext as MigrationContext;+ const syncTaskList = flattenTaskList<TaskCreate>(issueCreate).filter((task) => task.type === "bb.task.database.schema.update.ghost.sync"- )!;- const db = databaseStore.getDatabaseById(syncTask.databaseId!);-- detail.databaseId = syncTask.databaseId!;- detail.statement = maybeFormatStatementOnSave(syncTask.statement, db);- detail.earliestAllowedTs = syncTask.earliestAllowedTs;- });+ );+ const detailList = createContext.detailList;+ syncTaskList.forEach((task) => {+ const { databaseId } = task;+ if (!databaseId) return;+ const detail = detailList.find(+ (detail) => detail.databaseId === databaseId+ );+ if (detail) {+ const db = databaseStore.getDatabaseById(databaseId);+ detail.statement = maybeFormatStatementOnSave(task.statement, db);+ detail.earliestAllowedTs = task.earliestAllowedTs;+ }+ });+ }createIssue(issueCreate);};@@ -88,11 +212,24 @@ export default defineComponent({return baseAllowApplyTaskStatusTransition(task, to);};+ const allowApplyStatementToOtherTasks = computed(() => {+ // We are never allowed to "apply statement to other stages" in tenant mode.+ if (isTenantMode.value) return false;+ return baseAllowApplyStatementToOtherTasks.value;+ });+ const applyStatementToOtherTasks = (statement: string) => {+ if (!allowApplyStatementToOtherTasks.value) return;+ return baseApplyStatementToOtherTasks(statement);+ };+const logic = {...useCommonLogic(),selectedStatement,doCreate,allowApplyTaskStatusTransition,+ allowApplyStatementToOtherTasks,+ applyStatementToOtherTasks,+ updateStatement,};provideIssueLogic(logic);return logic;diff --git a/frontend/src/components/Issue/logic/base.ts b/frontend/src/components/Issue/logic/base.tsindex d7bedec7f6..92604d4aa8 100644--- a/frontend/src/components/Issue/logic/base.ts+++ b/frontend/src/components/Issue/logic/base.ts@@ -22,7 +22,11 @@ import {taskSlug,} from "@/utils";import { useDatabaseStore, useIssueStore, useProjectStore } from "@/store";-import { flattenTaskList, TaskTypeWithStatement } from "./common";+import {+ flattenTaskList,+ statementOfTask,+ TaskTypeWithStatement,+} from "./common";export const useBaseIssueLogic = (params: {create: Ref<boolean>;@@ -158,17 +162,21 @@ export const useBaseIssueLogic = (params: {return (selectedTask.value as Task).database;});+ const isGhostMode = computed((): boolean => {+ return issue.value.type === "bb.issue.database.schema.update.ghost";+ });+const isTenantMode = computed((): boolean => {if (project.value.tenantMode !== "TENANT") return false;// We support single database migration in tenant mode projects.// So a pipeline should be tenant mode when it contains more// than one tasks.- return flattenTaskList(issue.value).length > 1;- });-- const isGhostMode = computed((): boolean => {- return issue.value.type === "bb.issue.database.schema.update.ghost";+ return (+ flattenTaskList(issue.value).filter((task) =>+ TaskTypeWithStatement.includes(task.type)+ ).length > 1+ );});const isPITRMode = computed((): boolean => {@@ -202,6 +210,29 @@ export const useBaseIssueLogic = (params: {return true;};+ const selectedStatement = computed((): string => {+ const task = selectedTask.value;+ if (create.value) {+ return (task as TaskCreate).statement;+ }++ // Extract statement from different types of payloads+ return statementOfTask(task as Task) || "";+ });++ const allowApplyStatementToOtherTasks = computed(() => {+ if (!create.value) {+ return false;+ }+ const taskList = flattenTaskList<TaskCreate>(issue.value);+ // Allowed when more than one tasks need SQL statement.+ const count = taskList.filter((task) =>+ TaskTypeWithStatement.includes(task.type)+ ).length;++ return count > 1;+ });+const allowApplyIssueStatusTransition = () => {// no extra logic by defaultreturn true;@@ -218,6 +249,16 @@ export const useBaseIssueLogic = (params: {return true;};+ const applyStatementToOtherTasks = (statement: string) => {+ const taskList = flattenTaskList<TaskCreate>(issue.value);++ for (const task of taskList) {+ if (TaskTypeWithStatement.includes(task.type)) {+ task.statement = statement;+ }+ }+ };+return {project,isTenantMode,@@ -231,6 +272,9 @@ export const useBaseIssueLogic = (params: {selectTask,taskStatusOfStage,isValidStage,+ selectedStatement,+ allowApplyStatementToOtherTasks,+ applyStatementToOtherTasks,allowApplyIssueStatusTransition,allowApplyTaskStatusTransition,};diff --git a/frontend/src/components/Issue/logic/common.ts b/frontend/src/components/Issue/logic/common.tsindex c5453cb65b..4e8b30e9d3 100644--- a/frontend/src/components/Issue/logic/common.ts+++ b/frontend/src/components/Issue/logic/common.ts@@ -86,7 +86,9 @@ export const useCommonLogic = () => {const initialTaskListStatement = () => {if (create.value) {- const taskList = flattenTaskList<TaskCreate>(issue.value);+ const taskList = flattenTaskList<TaskCreate>(issue.value).filter((task) =>+ TaskTypeWithStatement.includes(task.type)+ );const databaseStatementMap = new Map<DatabaseId, string>();// route.query.databaseList is comma-splitted databaseId list// e.g. databaseList=7002,7006,7014@@ -156,16 +158,6 @@ export const useCommonLogic = () => {return isTaskEditable(selectedTask.value as Task);});- const selectedStatement = computed((): string => {- const task = selectedTask.value;- if (create.value) {- return (task as TaskCreate).statement;- }-- // Extract statement from different types of payloads- return statementOfTask(task as Task) || "";- });-const updateStatement = (newStatement: string,postUpdated?: (updatedTask: Task) => void@@ -187,29 +179,6 @@ export const useCommonLogic = () => {}};- const applyStatementToOtherTasks = (statement: string) => {- const taskList = flattenTaskList<TaskCreate>(issue.value);-- for (const task of taskList) {- if (TaskTypeWithStatement.includes(task.type)) {- task.statement = statement;- }- }- };-- const allowApplyStatementToOtherTasks = computed(() => {- if (!create.value) {- return false;- }- const taskList = flattenTaskList<TaskCreate>(issue.value);- // Allowed when more than one tasks need SQL statement.- const count = taskList.filter((task) =>- TaskTypeWithStatement.includes(task.type)- ).length;-- return count > 1;- });-const doCreate = () => {const issueCreate = cloneDeep(issue.value as IssueCreate);// for standard issue pipeline (1 * 1 or M * 1)@@ -236,11 +205,8 @@ export const useCommonLogic = () => {patchIssue,patchTask,allowEditStatement,- selectedStatement,initialTaskListStatement,updateStatement,- allowApplyStatementToOtherTasks,- applyStatementToOtherTasks,doCreate,};};@@ -315,7 +281,7 @@ export const errorAssertion = () => {}};-const statementOfTask = (task: Task) => {+export const statementOfTask = (task: Task) => {switch (task.type) {case "bb.task.general":return ((task as Task).payload as TaskGeneralPayload).statement || "";diff --git a/frontend/src/plugins/issue/logic/initialize/ghost.ts b/frontend/src/plugins/issue/logic/initialize/ghost.tsindex 007f1d0489..d8c3046380 100644--- a/frontend/src/plugins/issue/logic/initialize/ghost.ts+++ b/frontend/src/plugins/issue/logic/initialize/ghost.ts@@ -1,4 +1,4 @@-import { IssueCreate, IssueType, UpdateSchemaGhostContext } from "@/types";+import { IssueCreate, IssueType, MigrationContext } from "@/types";import {findDatabaseListByQuery,BuildNewIssueContext,@@ -31,17 +31,29 @@ const buildNewGhostIssue = async (helper.issueCreate!.type = "bb.issue.database.schema.update.ghost";const databaseList = findDatabaseListByQuery(context);- const createContext: UpdateSchemaGhostContext = {- detailList: databaseList.map((db) => {+ const createContext: MigrationContext = {+ detailList: [],+ };+ if (databaseList.length > 0) {+ // For multi-selection pipeline, pass databaseId accordingly.+ createContext.detailList = databaseList.map((db) => {return {migrationType: "MIGRATE",databaseId: db.id,statement: VALIDATE_ONLY_SQL,earliestAllowedTs: 0,};- }),- };-+ });+ } else {+ // For tenant deployment config pipeline, omit databaseId+ createContext.detailList = [+ {+ migrationType: "MIGRATE",+ statement: VALIDATE_ONLY_SQL,+ earliestAllowedTs: 0,+ },+ ];+ }helper.issueCreate!.createContext = createContext;await helper.validate();diff --git a/frontend/src/plugins/issue/logic/initialize/index.ts b/frontend/src/plugins/issue/logic/initialize/index.tsindex 2b6b056eae..bd0d7789c9 100644--- a/frontend/src/plugins/issue/logic/initialize/index.ts+++ b/frontend/src/plugins/issue/logic/initialize/index.ts@@ -68,15 +68,15 @@ export function useInitializeIssue(issueSlug: Ref<string>) {const buildNewIssue = async (context: BuildNewIssueContext): Promise<IssueCreate> => {- const tenant = await maybeBuildTenantDeployIssue(context);- if (tenant) {- return tenant;- }-const ghost = await maybeBuildGhostIssue(context);if (ghost) {return ghost;}+ const tenant = await maybeBuildTenantDeployIssue(context);+ if (tenant) {+ return tenant;+ }+return buildNewStandardIssue(context);};diff --git a/frontend/src/plugins/issue/logic/initialize/tenant.ts b/frontend/src/plugins/issue/logic/initialize/tenant.tsindex d1d98eb719..02eef5d92e 100644--- a/frontend/src/plugins/issue/logic/initialize/tenant.ts+++ b/frontend/src/plugins/issue/logic/initialize/tenant.ts@@ -50,22 +50,26 @@ const buildNewTenantSchemaUpdateIssue = async (}const databaseList = findDatabaseListByQuery(context);- if (databaseList.length !== 0) {+ if (databaseList.length > 0) {+ // For multi-selection pipeline, pass databaseId accordingly.helper.issueCreate!.createContext = {detailList: databaseList.map((db) => {return {migrationType: migrationType,databaseId: db.id,statement: VALIDATE_ONLY_SQL,+ earliestAllowedTs: 0,};}),};} else {+ // For tenant deployment config pipeline, omit databaseIdhelper.issueCreate!.createContext = {detailList: [{migrationType: migrationType,statement: VALIDATE_ONLY_SQL,+ earliestAllowedTs: 0,},],};diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.tsindex b352c47715..33cf99979e 100644--- a/frontend/src/types/issue.ts+++ b/frontend/src/types/issue.ts@@ -47,7 +47,7 @@ export type CreateDatabaseContext = {export type MigrationDetail = {migrationType: MigrationType;- databaseId: DatabaseId;+ databaseId?: DatabaseId;statement: string;earliestAllowedTs: number;};@@ -61,10 +61,6 @@ export type MigrationContext = {detailList: MigrationDetail[];};-export type UpdateSchemaGhostContext = {- detailList: UpdateSchemaGhostDetail[];-};-export type PITRContext = {databaseId: DatabaseId;pointInTimeTs?: number; // UNIX timestamp@@ -85,7 +81,6 @@ export type EmptyContext = {};export type IssueCreateContext =| CreateDatabaseContext| MigrationContext- | UpdateSchemaGhostContext| PITRContext| RollbackContext| EmptyContext;diff --git a/frontend/src/utils/database.ts b/frontend/src/utils/database.tsindex 9eeb300a9d..2129ebdbb0 100644--- a/frontend/src/utils/database.ts+++ b/frontend/src/utils/database.ts@@ -1,4 +1,3 @@-import { groupBy } from "lodash-es";import { Database, DataSourceType, Environment, Principal } from "../types";import { hasWorkspacePermission } from "./role";import { isDev, semverCompare } from "./util";@@ -62,18 +61,6 @@ export function sortDatabaseList(const MIN_GHOST_SUPPORT_MYSQL_VERSION = "5.7.0";export function allowGhostMigration(databaseList: Database[]): boolean {- const groupByEnvironment = groupBy(- databaseList,- (db) => db.instance.environment.id- );- // Multiple tasks in one stage is not supported by gh-ost now.- for (const environmentId in groupByEnvironment) {- const databaseListInStage = groupByEnvironment[environmentId];- if (databaseListInStage.length > 1) {- return false;- }- }-return databaseList.every((db) => {return (db.instance.engine === "MYSQL" &&diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex 997992cd22..db137f53cf 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -296,6 +296,7 @@<SchemaEditorModalv-if="state.showSchemaEditorModal":database-id-list="[database.id]"+ alter-type="SINGLE_DB"@close="state.showSchemaEditorModal = false"/></template>diff --git a/server/issue.go b/server/issue.goindex a7be02a62e..faca492a4f 100644--- a/server/issue.go+++ b/server/issue.go@@ -478,10 +478,8 @@ func (s *Server) getPipelineCreate(ctx context.Context, issueCreate *api.IssueCrreturn s.getPipelineCreateForDatabaseCreate(ctx, issueCreate)case api.IssueDatabaseRestorePITR:return s.getPipelineCreateForDatabasePITR(ctx, issueCreate)- case api.IssueDatabaseSchemaUpdate, api.IssueDatabaseDataUpdate:+ case api.IssueDatabaseSchemaUpdate, api.IssueDatabaseDataUpdate, api.IssueDatabaseSchemaUpdateGhost:return s.getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx, issueCreate)- case api.IssueDatabaseSchemaUpdateGhost:- return s.getPipelineCreateForDatabaseSchemaUpdateGhost(ctx, issueCreate)case api.IssueDatabaseRollback:return s.getPipelineCreateForDatabaseRollback(ctx, issueCreate)default:@@ -726,10 +724,6 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Con}}}- create := &api.PipelineCreate{- Name: "Change database pipeline",- CreatorID: issueCreate.CreatorID,- }project, err := s.store.GetProjectByID(ctx, issueCreate.ProjectID)if err != nil {@@ -766,7 +760,7 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Conreturn nil, echo.NewHTTPError(http.StatusBadRequest, "Migration detail should set either database name or database ID.")}if emptyDatabaseIDCount > 1 {- return nil, echo.NewHTTPError(http.StatusBadRequest, "There should be at most one migration detail with database name.")+ return nil, echo.NewHTTPError(http.StatusBadRequest, "There should be at most one migration detail with empty database ID.")}if project.TenantMode == api.TenantModeTenant && !s.licenseService.IsFeatureEnabled(api.FeatureMultiTenancy) {return nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())@@ -822,6 +816,54 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Con}}+ if issueCreate.Type == api.IssueDatabaseSchemaUpdateGhost {+ create := &api.PipelineCreate{+ Name: "Update database schema (gh-ost) pipeline",+ CreatorID: issueCreate.CreatorID,+ }+ for i, databaseList := range aggregatedMatrix {+ // Skip the stage if the stage includes no database.+ if len(databaseList) == 0 {+ continue+ }+ var environmentID int+ var taskCreateLists [][]api.TaskCreate+ var taskIndexDAGLists [][]api.TaskIndexDAG+ for _, database := range databaseList {+ if environmentID > 0 && environmentID != database.Instance.EnvironmentID {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "all databases in a stage should have the same environment")+ }+ environmentID = database.Instance.EnvironmentID++ schemaVersion := common.DefaultMigrationVersion()+ migrationDetailList := databaseToMigrationList[database.ID]+ for _, migrationDetail := range migrationDetailList {+ taskCreateList, taskIndexDAGList, err := createGhostTaskList(database, c.VCSPushEvent, migrationDetail, schemaVersion)+ if err != nil {+ return nil, err+ }+ taskCreateLists = append(taskCreateLists, taskCreateList)+ taskIndexDAGLists = append(taskIndexDAGLists, taskIndexDAGList)+ }+ }++ taskCreateList, taskIndexDAGList, err := utils.MergeTaskCreateLists(taskCreateLists, taskIndexDAGLists)+ if err != nil {+ return nil, err+ }+ create.StageList = append(create.StageList, api.StageCreate{+ Name: deploySchedule.Deployments[i].Name,+ EnvironmentID: environmentID,+ TaskList: taskCreateList,+ TaskIndexDAGList: taskIndexDAGList,+ })+ }+ return create, nil+ }+ create := &api.PipelineCreate{+ Name: "Change database pipeline",+ CreatorID: issueCreate.CreatorID,+ }for i, databaseList := range aggregatedMatrix {// Skip the stage if the stage includes no database.if len(databaseList) == 0 {@@ -862,63 +904,6 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Conreturn create, nil}-func (s *Server) getPipelineCreateForDatabaseSchemaUpdateGhost(ctx context.Context, issueCreate *api.IssueCreate) (*api.PipelineCreate, error) {- if !s.licenseService.IsFeatureEnabled(api.FeatureOnlineMigration) {- return nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureOnlineMigration.AccessErrorMessage())- }- c := api.UpdateSchemaGhostContext{}- if err := json.Unmarshal([]byte(issueCreate.CreateContext), &c); err != nil {- return nil, err- }- if !s.licenseService.IsFeatureEnabled(api.FeatureTaskScheduleTime) {- for _, detail := range c.DetailList {- if detail.EarliestAllowedTs != 0 {- return nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureTaskScheduleTime.AccessErrorMessage())- }- }- }-- project, err := s.store.GetProjectByID(ctx, issueCreate.ProjectID)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch project with ID %d", issueCreate.ProjectID)).SetInternal(err)- }- if project.TenantMode == api.TenantModeTenant {- return nil, echo.NewHTTPError(http.StatusBadRequest, "not implemented yet")- }-- create := &api.PipelineCreate{- Name: "Update database schema (gh-ost) pipeline",- CreatorID: issueCreate.CreatorID,- }- schemaVersion := common.DefaultMigrationVersion()- for _, detail := range c.DetailList {- if detail.Statement == "" {- return nil, echo.NewHTTPError(http.StatusBadRequest, "failed to create issue, sql statement missing")- }-- database, err := s.store.GetDatabase(ctx, &api.DatabaseFind{ID: &detail.DatabaseID})- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch database ID: %v", detail.DatabaseID)).SetInternal(err)- }- if database == nil {- return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("database ID not found: %d", detail.DatabaseID))- }-- taskCreateList, taskIndexDAGList, err := createGhostTaskList(database, c.VCSPushEvent, detail, schemaVersion)- if err != nil {- return nil, err- }-- create.StageList = append(create.StageList, api.StageCreate{- Name: fmt.Sprintf("%s %s", database.Instance.Environment.Name, database.Name),- EnvironmentID: database.Instance.Environment.ID,- TaskList: taskCreateList,- TaskIndexDAGList: taskIndexDAGList,- })- }- return create, nil-}-func getOrDefaultSchemaVersion(detail *api.MigrationDetail) string {if detail.SchemaVersion != "" {return detail.SchemaVersion@@ -1189,7 +1174,7 @@ func getCreateDatabaseStatement(dbType db.Type, createDatabaseContext api.Create}// creates gh-ost TaskCreate list and dependency.-func createGhostTaskList(database *api.Database, vcsPushEvent *vcs.PushEvent, detail *api.UpdateSchemaGhostDetail, schemaVersion string) ([]api.TaskCreate, []api.TaskIndexDAG, error) {+func createGhostTaskList(database *api.Database, vcsPushEvent *vcs.PushEvent, detail *api.MigrationDetail, schemaVersion string) ([]api.TaskCreate, []api.TaskIndexDAG, error) {var taskCreateList []api.TaskCreate// task "sync"payloadSync := api.TaskDatabaseSchemaUpdateGhostSyncPayload{diff --git a/server/task.go b/server/task.goindex 256f34afed..485061531b 100644--- a/server/task.go+++ b/server/task.go@@ -42,6 +42,10 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {var taskPatchedList []*api.Taskfor _, stage := range issue.Pipeline.StageList {for _, task := range stage.TaskList {+ // Skip gh-ost cutover task as this task has no statement.+ if task.Type == api.TaskDatabaseSchemaUpdateGhostCutover {+ continue+ }taskPatch := *taskPatchtaskPatch.ID = task.IDtaskPatched, httpErr := s.TaskScheduler.PatchTaskStatement(ctx, task, &taskPatch, issue)diff --git a/server/utils/utils.go b/server/utils/utils.goindex 239a976d2d..ef6a9217e2 100644--- a/server/utils/utils.go+++ b/server/utils/utils.go@@ -394,3 +394,28 @@ func GetTaskStatement(task *api.Task) (string, error) {}return taskStatement.Statement, nil}++// MergeTaskCreateLists merges a matrix of taskCreate and taskIndexDAG to a list of taskCreate and taskIndexDAG.+// The index of returned taskIndexDAG list is set regarding the merged taskCreate.+func MergeTaskCreateLists(taskCreateLists [][]api.TaskCreate, taskIndexDAGLists [][]api.TaskIndexDAG) ([]api.TaskCreate, []api.TaskIndexDAG, error) {+ if len(taskCreateLists) != len(taskIndexDAGLists) {+ return nil, nil, errors.Errorf("expect taskCreateLists and taskIndexDAGLists to have the same length, get %d, %d respectively", len(taskCreateLists), len(taskIndexDAGLists))+ }+ var resTaskCreateList []api.TaskCreate+ var resTaskIndexDAGList []api.TaskIndexDAG+ offset := 0+ for i := range taskCreateLists {+ taskCreateList := taskCreateLists[i]+ taskIndexDAGList := taskIndexDAGLists[i]++ resTaskCreateList = append(resTaskCreateList, taskCreateList...)+ for _, dag := range taskIndexDAGList {+ resTaskIndexDAGList = append(resTaskIndexDAGList, api.TaskIndexDAG{+ FromIndex: dag.FromIndex + offset,+ ToIndex: dag.ToIndex + offset,+ })+ }+ offset += len(taskCreateList)+ }+ return resTaskCreateList, resTaskIndexDAGList, nil+}diff --git a/server/utils/utils_test.go b/server/utils/utils_test.goindex 6c08131675..e9af2aafed 100644--- a/server/utils/utils_test.go+++ b/server/utils/utils_test.go@@ -4,6 +4,7 @@ import ("testing""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""github.com/bytebase/bytebase/api")@@ -259,7 +260,6 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {"twoDifferentKeys",&api.DeploymentSchedule{Deployments: []*api.Deployment{-{Spec: &api.DeploymentSpec{Selector: &api.LabelSelector{@@ -300,7 +300,6 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {"differentDatabaseNames",&api.DeploymentSchedule{Deployments: []*api.Deployment{-{Spec: &api.DeploymentSpec{Selector: &api.LabelSelector{@@ -327,7 +326,6 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {"useDatabaseNameTemplate",&api.DeploymentSchedule{Deployments: []*api.Deployment{-{Spec: &api.DeploymentSpec{Selector: &api.LabelSelector{@@ -357,3 +355,107 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {assert.Equal(t, matrix, test.want, test.name)}}++func TestMergeTaskCreateLists(t *testing.T) {+ tests := []struct {+ name string+ taskCreateLists [][]api.TaskCreate+ taskIndexDAGLists [][]api.TaskIndexDAG+ wantTaskCreateList []api.TaskCreate+ wantTaskDAGList []api.TaskIndexDAG+ }{+ {+ name: "simple, len=1",+ taskCreateLists: [][]api.TaskCreate{+ {+ {}, {},+ },+ },+ taskIndexDAGLists: [][]api.TaskIndexDAG{+ {+ {FromIndex: 0, ToIndex: 1},+ },+ },+ wantTaskCreateList: []api.TaskCreate{+ {}, {},+ },+ wantTaskDAGList: []api.TaskIndexDAG{+ {FromIndex: 0, ToIndex: 1},+ },+ },+ {+ name: "len=2",+ taskCreateLists: [][]api.TaskCreate{+ {+ {}, {}, {}, {},+ },+ {+ {}, {}, {}, {},+ },+ },+ taskIndexDAGLists: [][]api.TaskIndexDAG{+ {+ {FromIndex: 0, ToIndex: 1},+ {FromIndex: 1, ToIndex: 3},+ },+ {+ {FromIndex: 1, ToIndex: 2},+ },+ },+ wantTaskCreateList: []api.TaskCreate{+ {}, {}, {}, {}, {}, {}, {}, {},+ },+ wantTaskDAGList: []api.TaskIndexDAG{+ {FromIndex: 0, ToIndex: 1},+ {FromIndex: 1, ToIndex: 3},+ {FromIndex: 5, ToIndex: 6},+ },+ },+ {+ name: "len=3",+ taskCreateLists: [][]api.TaskCreate{+ {+ {}, {}, {}, {},+ },+ {+ {}, {}, {}, {},+ },+ {+ {}, {}, {}, {},+ },+ },+ taskIndexDAGLists: [][]api.TaskIndexDAG{+ {+ {FromIndex: 0, ToIndex: 1},+ {FromIndex: 1, ToIndex: 3},+ },+ {+ {FromIndex: 1, ToIndex: 2},+ },+ {+ {FromIndex: 1, ToIndex: 2},+ },+ },+ wantTaskCreateList: []api.TaskCreate{+ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},+ },+ wantTaskDAGList: []api.TaskIndexDAG{+ {FromIndex: 0, ToIndex: 1},+ {FromIndex: 1, ToIndex: 3},+ {FromIndex: 5, ToIndex: 6},+ {FromIndex: 9, ToIndex: 10},+ },+ },+ }++ for i := range tests {+ test := tests[i]+ t.Run(test.name, func(t *testing.T) {+ a := require.New(t)+ taskCreateList, taskIndexDAGList, err := MergeTaskCreateLists(test.taskCreateLists, test.taskIndexDAGLists)+ a.NoError(err)+ a.Equal(test.wantTaskCreateList, taskCreateList)+ a.Equal(test.wantTaskDAGList, taskIndexDAGList)+ })+ }+}diff --git a/tests/ghost_test.go b/tests/ghost_test.goindex 3f0ee9ba93..75b13f0d70 100644--- a/tests/ghost_test.go+++ b/tests/ghost_test.go@@ -175,11 +175,12 @@ func TestGhostSchemaUpdate(t *testing.T) {a.NoError(err)a.Equal(mysqlBookSchema1, result)- createContext, err = json.Marshal(&api.UpdateSchemaGhostContext{- DetailList: []*api.UpdateSchemaGhostDetail{+ createContext, err = json.Marshal(&api.MigrationContext{+ DetailList: []*api.MigrationDetail{{- DatabaseID: database.ID,- Statement: mysqlGhostMigrationStatement,+ MigrationType: db.Migrate,+ DatabaseID: database.ID,+ Statement: mysqlGhostMigrationStatement,},},})@@ -202,3 +203,244 @@ func TestGhostSchemaUpdate(t *testing.T) {a.NoError(err)a.Equal(mysqlBookSchema2, result)}++func TestGhostTenant(t *testing.T) {+ var (+ databaseName = "testGhostSchemaUpdate"+ mysqlMigrationStatement = `+ CREATE TABLE book (+ id INT PRIMARY KEY AUTO_INCREMENT,+ name TEXT+ );+ `+ mysqlGhostMigrationStatement = `+ ALTER TABLE book ADD author VARCHAR(54)+ `+ mysqlQueryBookTable = `+ SELECT * FROM INFORMATION_SCHEMA.COLUMNS+ WHERE table_name = 'book'+ ORDER BY ORDINAL_POSITION+ `+ mysqlBookSchema1 = `[["TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","COLUMN_NAME","ORDINAL_POSITION","COLUMN_DEFAULT","IS_NULLABLE","DATA_TYPE","CHARACTER_MAXIMUM_LENGTH","CHARACTER_OCTET_LENGTH","NUMERIC_PRECISION","NUMERIC_SCALE","DATETIME_PRECISION","CHARACTER_SET_NAME","COLLATION_NAME","COLUMN_TYPE","COLUMN_KEY","EXTRA","PRIVILEGES","COLUMN_COMMENT","GENERATION_EXPRESSION","SRS_ID"],["VARCHAR","VARCHAR","VARCHAR","VARCHAR","INT","TEXT","VARCHAR","TEXT","BIGINT","BIGINT","BIGINT","BIGINT","INT","VARCHAR","VARCHAR","TEXT","CHAR","VARCHAR","VARCHAR","TEXT","TEXT","INT"],[["def","testGhostSchemaUpdate","book","id",1,null,"NO","int",null,null,"10","0",null,null,null,"int","PRI","auto_increment","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","name",2,null,"YES","text","65535","65535",null,null,null,"utf8mb4","utf8mb4_general_ci","text","","","select,insert,update,references","","",null]]]`+ mysqlBookSchema2 = `[["TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","COLUMN_NAME","ORDINAL_POSITION","COLUMN_DEFAULT","IS_NULLABLE","DATA_TYPE","CHARACTER_MAXIMUM_LENGTH","CHARACTER_OCTET_LENGTH","NUMERIC_PRECISION","NUMERIC_SCALE","DATETIME_PRECISION","CHARACTER_SET_NAME","COLLATION_NAME","COLUMN_TYPE","COLUMN_KEY","EXTRA","PRIVILEGES","COLUMN_COMMENT","GENERATION_EXPRESSION","SRS_ID"],["VARCHAR","VARCHAR","VARCHAR","VARCHAR","INT","TEXT","VARCHAR","TEXT","BIGINT","BIGINT","BIGINT","BIGINT","INT","VARCHAR","VARCHAR","TEXT","CHAR","VARCHAR","VARCHAR","TEXT","TEXT","INT"],[["def","testGhostSchemaUpdate","book","id",1,null,"NO","int",null,null,"10","0",null,null,null,"int","PRI","auto_increment","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","name",2,null,"YES","text","65535","65535",null,null,null,"utf8mb4","utf8mb4_general_ci","text","","","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","author",3,null,"YES","varchar","54","216",null,null,null,"utf8mb4","utf8mb4_general_ci","varchar(54)","","","select,insert,update,references","","",null]]]`+ )+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ dataDir := t.TempDir()+ err := ctl.StartServerWithExternalPg(ctx, &config{+ dataDir: dataDir,+ vcsProviderCreator: fake.NewGitLab,+ })+ a.NoError(err)+ defer ctl.Close(ctx)+ err = ctl.Login()+ a.NoError(err)+ err = ctl.setLicense()+ a.NoError(err)++ // Create a project.+ project, err := ctl.createProject(api.ProjectCreate{+ Name: "Test Project",+ Key: "TestTenantGhost",+ TenantMode: api.TenantModeTenant,+ })+ a.NoError(err)++ environments, err := ctl.getEnvironments()+ a.NoError(err)+ stagingEnvironment, err := findEnvironment(environments, "Staging")+ a.NoError(err)+ prodEnvironment, err := findEnvironment(environments, "Prod")+ a.NoError(err)++ // Provision instances.+ var stagingInstances []*api.Instance+ var prodInstances []*api.Instance+ for i := 0; i < stagingTenantNumber; i++ {+ port, err := getMySQLInstanceForGhostTest(t)+ a.NoError(err)+ // Add the provisioned instances.+ instance, err := ctl.addInstance((api.InstanceCreate{+ EnvironmentID: stagingEnvironment.ID,+ Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),+ Engine: db.MySQL,+ Host: "127.0.0.1",+ Port: strconv.Itoa(port),+ Username: "bytebase",+ Password: "bytebase",+ }))+ a.NoError(err)+ stagingInstances = append(stagingInstances, instance)+ }+ for i := 0; i < prodTenantNumber; i++ {+ port, err := getMySQLInstanceForGhostTest(t)+ a.NoError(err)+ // Add the provisioned instances.+ instance, err := ctl.addInstance((api.InstanceCreate{+ EnvironmentID: prodEnvironment.ID,+ Name: fmt.Sprintf("%s-%d", prodInstanceName, i),+ Engine: db.MySQL,+ Host: "127.0.0.1",+ Port: strconv.Itoa(port),+ Username: "bytebase",+ Password: "bytebase",+ }))+ a.NoError(err)+ prodInstances = append(prodInstances, instance)+ }++ // Set up label values for tenants.+ // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.+ var tenants []string+ for i := 0; i < prodTenantNumber; i++ {+ tenants = append(tenants, fmt.Sprintf("tenant%d", i))+ }+ err = ctl.addLabelValues(api.TenantLabelKey, tenants)+ a.NoError(err)++ // Create deployment configuration.+ _, err = ctl.upsertDeploymentConfig(+ api.DeploymentConfigUpsert{+ ProjectID: project.ID,+ },+ deploymentSchedule,+ )+ a.NoError(err)++ // Create issues that create databases.+ for i, stagingInstance := range stagingInstances {+ err := ctl.createDatabase(project, stagingInstance, databaseName, "", map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})+ a.NoError(err)+ }+ for i, prodInstance := range prodInstances {+ err := ctl.createDatabase(project, prodInstance, databaseName, "", map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})+ a.NoError(err)+ }++ // Getting databases for each environment.+ databases, err := ctl.getDatabases(api.DatabaseFind{+ ProjectID: &project.ID,+ })+ a.NoError(err)++ var stagingDatabases []*api.Database+ var prodDatabases []*api.Database+ for _, stagingInstance := range stagingInstances {+ for _, database := range databases {+ if database.Instance.ID == stagingInstance.ID {+ stagingDatabases = append(stagingDatabases, database)+ break+ }+ }+ }+ for _, prodInstance := range prodInstances {+ for _, database := range databases {+ if database.Instance.ID == prodInstance.ID {+ prodDatabases = append(prodDatabases, database)+ break+ }+ }+ }+ a.Equal(stagingTenantNumber, len(stagingDatabases))+ a.Equal(prodTenantNumber, len(prodDatabases))++ // Create an issue that updates database schema.+ createContext, err := json.Marshal(&api.MigrationContext{+ DetailList: []*api.MigrationDetail{+ {+ MigrationType: db.Migrate,+ Statement: mysqlMigrationStatement,+ },+ },+ })+ a.NoError(err)+ issue, err := ctl.createIssue(api.IssueCreate{+ ProjectID: project.ID,+ Name: fmt.Sprintf("update schema for database %q", databaseName),+ Type: api.IssueDatabaseSchemaUpdate,+ Description: fmt.Sprintf("This updates the schema of database %q.", databaseName),+ // Assign to self.+ AssigneeID: project.Creator.ID,+ CreateContext: string(createContext),+ })+ a.NoError(err)+ status, err := ctl.waitIssuePipeline(issue.ID)+ a.NoError(err)+ a.Equal(api.TaskDone, status)++ // Query schema.+ for _, stagingInstance := range stagingInstances {+ result, err := ctl.query(stagingInstance, databaseName, mysqlQueryBookTable)+ a.NoError(err)+ a.Equal(mysqlBookSchema1, result)+ }+ for _, prodInstance := range prodInstances {+ result, err := ctl.query(prodInstance, databaseName, mysqlQueryBookTable)+ a.NoError(err)+ a.Equal(mysqlBookSchema1, result)+ }++ // Create an issue that updates database schema using gh-ost.+ createContext, err = json.Marshal(&api.MigrationContext{+ DetailList: []*api.MigrationDetail{+ {+ MigrationType: db.Migrate,+ DatabaseID: 0,+ Statement: mysqlGhostMigrationStatement,+ },+ },+ })+ a.NoError(err)+ issue, err = ctl.createIssue(api.IssueCreate{+ ProjectID: project.ID,+ Name: fmt.Sprintf("update schema for database %q", databaseName),+ Type: api.IssueDatabaseSchemaUpdateGhost,+ Description: fmt.Sprintf("This updates the schema of database %q.", databaseName),+ // Assign to self.+ AssigneeID: project.Creator.ID,+ CreateContext: string(createContext),+ })+ a.NoError(err)+ status, err = ctl.waitIssuePipeline(issue.ID)+ a.NoError(err)+ a.Equal(api.TaskDone, status)++ // Query schema.+ for _, stagingInstance := range stagingInstances {+ result, err := ctl.query(stagingInstance, databaseName, mysqlQueryBookTable)+ a.NoError(err)+ a.Equal(mysqlBookSchema2, result)+ }+ for _, prodInstance := range prodInstances {+ result, err := ctl.query(prodInstance, databaseName, mysqlQueryBookTable)+ a.NoError(err)+ a.Equal(mysqlBookSchema2, result)+ }+}++func getMySQLInstanceForGhostTest(t *testing.T) (int, error) {+ mysqlPort := getTestPort()+ stopInstance := mysql.SetupTestInstance(t, mysqlPort, mysqlBinDir)+ t.Cleanup(stopInstance)++ mysqlDB, err := connectTestMySQL(mysqlPort, "")+ if err != nil {+ return 0, err+ }+ defer mysqlDB.Close()++ if _, err := mysqlDB.Exec("DROP USER IF EXISTS bytebase"); err != nil {+ return 0, err+ }++ if _, err = mysqlDB.Exec("CREATE USER 'bytebase' IDENTIFIED WITH mysql_native_password BY 'bytebase'"); err != nil {+ return 0, err+ }++ if _, err = mysqlDB.Exec("GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, SELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, REPLICATION CLIENT, REPLICATION SLAVE, LOCK TABLES, RELOAD ON *.* to bytebase"); err != nil {+ return 0, err+ }+ return mysqlPort, nil+}