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: support schema baseline for SDL (#3068)
Danny Xu82a5b1d059b9
diff --git a/frontend/src/components/DatabaseMigrationHistoryPanel.vue b/frontend/src/components/DatabaseMigrationHistoryPanel.vueindex c9f33b9784..b5e6b14971 100644--- a/frontend/src/components/DatabaseMigrationHistoryPanel.vue+++ b/frontend/src/components/DatabaseMigrationHistoryPanel.vue@@ -85,7 +85,7 @@ import {import { useRouter } from "vue-router";import { BBTableSectionDataSource } from "../bbkit/types";import { instanceSlug, isDBAOrOwner } from "../utils";-import { pushNotification, useCurrentUser, useInstanceStore } from "@/store";+import { useCurrentUser, useInstanceStore } from "@/store";interface LocalState {migrationSetupStatus: MigrationSchemaStatus;@@ -217,25 +217,6 @@ export default defineComponent({const doCreateBaseline = () => {state.showBaselineModal = false;- // If the database is within VCS project, try to find its latest and done migration history from VCS.- // If not found, show error notification.- if (props.database.project.workflowType === "VCS") {- const latestDoneVCSMigrationHistory =- instanceStore.getLatestDoneVCSMigrationHistory(- props.database.instance.id,- props.database.name- );-- if (!latestDoneVCSMigrationHistory) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("migration-history.no-succeed-vcs-migration-record"),- });- return;- }- }-router.push({name: "workspace.issue.detail",params: {diff --git a/frontend/src/components/Issue/logic/common.ts b/frontend/src/components/Issue/logic/common.tsindex cca48c40e9..355d792e9d 100644--- a/frontend/src/components/Issue/logic/common.ts+++ b/frontend/src/components/Issue/logic/common.ts@@ -4,7 +4,6 @@ import formatSQL from "@/components/MonacoEditor/sqlFormatter";import {useCurrentUser,useDatabaseStore,- useInstanceStore,useIssueStore,useTaskStore,useUIStateStore,@@ -26,7 +25,6 @@ import {TaskId,TaskPatch,TaskType,- MigrationContext,MigrationDetail,MigrationType,TaskDatabaseSchemaBaselinePayload,@@ -200,24 +198,6 @@ export const useCommonLogic = () => {detailList: detailList,};- // If the database is within VCS project, try to find its latest and done migration history from VCS.- // If not found, keep the vcsPushEvent field empty and check in backend.- if (detailList.length === 1 && detailList[0].migrationType === "BASELINE") {- const databaseId = detailList[0].databaseId;- const database = databaseStore.getDatabaseById(databaseId);- if (database.project.workflowType === "VCS") {- const migrationHistory =- useInstanceStore().getLatestDoneVCSMigrationHistory(- database.instance.id,- database.name- );- if (migrationHistory) {- (issueCreate.createContext as MigrationContext).vcsPushEvent =- migrationHistory.payload?.pushEvent;- }- }- }-createIssue(issueCreate);};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 982d57d30c..b5b9f27dbb 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -791,8 +791,7 @@"establish-database-baseline": "Establish \"{name}\" baseline","instance-missing-migration-schema": "Missing migration history schema on instance \"{name}\".","instance-bad-connection": "Unable to connect instance \"{name}\" to retrieve migration history.",- "contact-dba": "Please contact your DBA to config it",- "no-succeed-vcs-migration-record": "No succeed migration record from VCS"+ "contact-dba": "Please contact your DBA to config it"},"database": {"select": "Select database",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b1da5f1845..146ab43ed6 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -791,8 +791,7 @@"establish-database-baseline": "建立「{name}」基线","instance-missing-migration-schema": "实例「{name}」缺失用于记录变更历史的 schema。","instance-bad-connection": "无法连接实例「{name}」以获取变更历史。",- "contact-dba": "请联系您的 DBA 进行配置。",- "no-succeed-vcs-migration-record": "没有来自 VCS 的变更历史。"+ "contact-dba": "请联系您的 DBA 进行配置。"},"database": {"select": "选择数据库",diff --git a/frontend/src/plugins/issue/logic/initialize/standard.ts b/frontend/src/plugins/issue/logic/initialize/standard.tsindex cbd0c5ef57..fa79576cf1 100644--- a/frontend/src/plugins/issue/logic/initialize/standard.ts+++ b/frontend/src/plugins/issue/logic/initialize/standard.ts@@ -1,11 +1,5 @@import { TemplateType } from "@/plugins";-import { useInstanceStore } from "@/store";-import {- IssueCreate,- IssueCreateContext,- MigrationType,- MigrationContext,-} from "@/types";+import { IssueCreate, IssueCreateContext, MigrationType } from "@/types";import {findDatabaseListByQuery,BuildNewIssueContext,@@ -46,24 +40,6 @@ export const buildNewStandardIssue = async (}),};- // If the database is within VCS project, try to find its latest and done migration history from VCS.- // If not found, keep the vcsPushEvent field empty and check in backend.- // (Validate only)- if (migrationType === "BASELINE" && databaseList.length === 1) {- const database = databaseList[0];- if (database.project.workflowType === "VCS") {- const migrationHistory =- useInstanceStore().getLatestDoneVCSMigrationHistory(- database.instance.id,- database.name- );- if (migrationHistory) {- (createContext as MigrationContext).vcsPushEvent =- migrationHistory.payload?.pushEvent;- }- }- }-helper.issueCreate!.createContext = createContext;await helper.validate();diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.tsindex 6f377d86f2..6029abca85 100644--- a/frontend/src/store/modules/instance.ts+++ b/frontend/src/store/modules/instance.ts@@ -196,26 +196,6 @@ export const useInstanceStore = defineStore("instance", {) || []);},- getLatestDoneVCSMigrationHistory(- instanceId: InstanceId,- databaseName: string- ): MigrationHistory | undefined {- const migrationHistoryList =- this.getMigrationHistoryListByInstanceIdAndDatabaseName(- instanceId,- databaseName- );- for (const migrationHistory of migrationHistoryList) {- if (- migrationHistory.status === "DONE" &&- migrationHistory.source === "VCS" &&- migrationHistory.payload?.pushEvent !== undefined- ) {- return migrationHistory;- }- }- return undefined;- },setInstanceList(instanceList: Instance[]) {instanceList.forEach((instance) => {this.instanceById.set(instance.id, instance);diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.tsindex 9c56bd6d32..d879b26981 100644--- a/frontend/src/types/issue.ts+++ b/frontend/src/types/issue.ts@@ -10,7 +10,6 @@ import { Pipeline, PipelineCreate } from "./pipeline";import { Principal } from "./principal";import { Project } from "./project";import { MigrationType } from "./instance";-import { VCSPushEvent } from "./vcs";type IssueTypeGeneral = "bb.issue.general";@@ -59,7 +58,6 @@ export type UpdateSchemaGhostDetail = MigrationDetail & {export type MigrationContext = {detailList: MigrationDetail[];- vcsPushEvent?: VCSPushEvent;};export type UpdateSchemaGhostContext = {diff --git a/server/issue.go b/server/issue.goindex befcb4cfa3..fd82063e73 100644--- a/server/issue.go+++ b/server/issue.go@@ -626,17 +626,6 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Conreturn nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project with ID %d", issueCreate.ProjectID)).SetInternal(err)}- // If migration type is establishing baseline and project's workflow is VCS,- // then the context must contain a VCS push event field. We need this VCS- // context to identify the write-back destination after migration.- for _, detail := range c.DetailList {- if detail.MigrationType == db.Baseline && project.WorkflowType == api.VCSWorkflow {- if c.VCSPushEvent == nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Failed to create establishing baseline issue for GitOps workflow project, vcs context missing")- }- }- }-schemaVersion := common.DefaultMigrationVersion()// Tenant mode project pipeline has its own generation.if project.TenantMode == api.TenantModeTenant {diff --git a/server/task_executor.go b/server/task_executor.goindex 7a2277b49d..acecaba715 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -162,21 +162,28 @@ func postMigration(ctx context.Context, server *Server, task *api.Task, vcsPushE// If somehow we cannot find the issue, emit the error since it's not fatal.log.Error("failed to find containing issue", zap.Error(err))}- var repo *api.Repository- if vcsPushEvent != nil {- repo, err = findRepositoryByTask(ctx, server, task)- if err != nil {- return true, nil, err- }- }-- // We write back the latest schema after migration for VCS-based projects if the- // schema path template is specified and the schema migration type is not SDL.- writeBack := (vcsPushEvent != nil) && (repo.Project.SchemaChangeType != api.ProjectSchemaChangeTypeSDL) && (repo.SchemaPathTemplate != "")project, err := server.store.GetProjectByID(ctx, task.Database.ProjectID)if err != nil {return true, nil, err}+ repo, err := server.store.GetRepository(ctx, &api.RepositoryFind{+ ProjectID: &task.Database.ProjectID,+ })+ if err != nil {+ return true, nil, errors.Errorf("failed to find linked repository for database %q", task.Database.Name)+ }++ // We write back the latest schema after migration for VCS-based projects when schema path template is specified and+ // 1) baseline migration for SDL,+ // 2) all DDL/Ghost migrations.+ writeBack := false+ if repo != nil && repo.SchemaPathTemplate != "" {+ if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL {+ writeBack = (task.Type == api.TaskDatabaseSchemaBaseline)+ } else {+ writeBack = (vcsPushEvent != nil) && (task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateGhostCutover)+ }+ }if writeBack && issue != nil {if project.TenantMode == api.TenantModeTenant {// For tenant mode project, we will only write back once and we happen to write back on lastTask done.@@ -219,18 +226,12 @@ func postMigration(ctx context.Context, server *Server, task *api.Task, vcsPushE}repo.VCS = vcs- // Writes back the latest schema file to the same branch as the push event.- branch, err := vcsPlugin.Branch(vcsPushEvent.Ref)- if err != nil {- return true, nil, err- }-bytebaseURL := ""if issue != nil {bytebaseURL = fmt.Sprintf("%s/issue/%s?stage=%d", server.profile.ExternalURL, api.IssueSlug(issue), task.StageID)}- commitID, err := writeBackLatestSchema(ctx, server, repo, vcsPushEvent, mi, branch, latestSchemaFile, schema, bytebaseURL)+ commitID, err := writeBackLatestSchema(ctx, server, repo, vcsPushEvent, mi, repo.BranchFilter, latestSchemaFile, schema, bytebaseURL)if err != nil {return true, nil, err}@@ -240,8 +241,8 @@ func postMigration(ctx context.Context, server *Server, task *api.Task, vcsPushEpayload, err := json.Marshal(api.ActivityPipelineTaskFileCommitPayload{TaskID: task.ID,VCSInstanceURL: repo.VCS.InstanceURL,- RepositoryFullPath: vcsPushEvent.RepositoryFullPath,- Branch: branch,+ RepositoryFullPath: repo.FullPath,+ Branch: repo.BranchFilter,FilePath: latestSchemaFile,CommitID: commitID,})@@ -325,20 +326,6 @@ func findIssueByTask(ctx context.Context, server *Server, task *api.Task) (*api.return issue, nil}-func findRepositoryByTask(ctx context.Context, server *Server, task *api.Task) (*api.Repository, error) {- repoFind := &api.RepositoryFind{- ProjectID: &task.Database.ProjectID,- }- repo, err := server.store.GetRepository(ctx, repoFind)- if err != nil {- return nil, errors.Errorf("failed to find linked repository for database %q", task.Database.Name)- }- if repo == nil {- return nil, errors.Errorf("repository not found with project ID %v", task.Database.ProjectID)- }- return repo, nil-}-// Writes back the latest schema to the repository after migration// Returns the commit id on success.func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.Repository, pushEvent *vcsPlugin.PushEvent, mi *db.MigrationInfo, branch string, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {@@ -368,24 +355,30 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.}}- commitTitle := fmt.Sprintf("[Bytebase] %s latest schema for %q after migration %s", verb, mi.Database, mi.Version)- commitBody := "THIS COMMIT IS AUTO-GENERATED BY BYTEBASE"- if bytebaseURL != "" {- commitBody += "\n\n" + bytebaseURL- }- commitBody += "\n\n--------Original migration change--------\n\n"- if len(pushEvent.CommitList) == 0 {- // For legacy data in task payload stored in the database.- // TODO(dragonly): Remove the field FileCommit.- commitBody += fmt.Sprintf("%s\n\n%s",- pushEvent.FileCommit.URL,- pushEvent.FileCommit.Message,- )+ var commitMessage string+ if mi.Type == db.Baseline {+ commitMessage = fmt.Sprintf("[Bytebase] establish baseline for %q", mi.Database)} else {- commitBody += fmt.Sprintf("%s\n\n%s",- pushEvent.CommitList[0].URL,- pushEvent.CommitList[0].Message,- )+ commitTitle := fmt.Sprintf("[Bytebase] %s latest schema for %q after migration %s", verb, mi.Database, mi.Version)+ commitBody := "THIS COMMIT IS AUTO-GENERATED BY BYTEBASE"+ if bytebaseURL != "" {+ commitBody += "\n\n" + bytebaseURL+ }+ commitBody += "\n\n--------Original migration change--------\n\n"+ if len(pushEvent.CommitList) == 0 {+ // For legacy data in task payload stored in the database.+ // TODO(dragonly): Remove the field FileCommit.+ commitBody += fmt.Sprintf("%s\n\n%s",+ pushEvent.FileCommit.URL,+ pushEvent.FileCommit.Message,+ )+ } else {+ commitBody += fmt.Sprintf("%s\n\n%s",+ pushEvent.CommitList[0].URL,+ pushEvent.CommitList[0].Message,+ )+ }+ commitMessage = fmt.Sprintf("%s\n\n%s", commitTitle, commitBody)}// Retrieve the latest AccessToken and RefreshToken as the previous VCS call may have@@ -401,7 +394,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.schemaFileCommit := vcsPlugin.FileCommitCreate{Branch: branch,- CommitMessage: fmt.Sprintf("%s\n\n%s", commitTitle, commitBody),+ CommitMessage: commitMessage,Content: schema,}if createSchemaFile {diff --git a/server/task_executor_schema_baseline.go b/server/task_executor_schema_baseline.goindex e55a48b763..ddb88ecfbc 100644--- a/server/task_executor_schema_baseline.go+++ b/server/task_executor_schema_baseline.go@@ -29,7 +29,7 @@ func (exec *SchemaBaselineTaskExecutor) RunOnce(ctx context.Context, server *Serreturn true, nil, errors.Wrap(err, "invalid database schema baseline payload")}- return runMigration(ctx, server, task, db.Baseline, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)+ return runMigration(ctx, server, task, db.Baseline, payload.Statement, payload.SchemaVersion, nil /* vcsPushEvent */)}// IsCompleted tells the scheduler if the task execution has completed.