Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Add schema_path_template to allow cutomize the path for where Bytebase writes the latest schema after each migration
天舟f13bc9cb1b28
diff --git a/api/repository.go b/api/repository.goindex f6a265da61..fda3cae1f6 100644--- a/api/repository.go+++ b/api/repository.go@@ -23,12 +23,16 @@ type Repository struct {Project *Project `jsonapi:"relation,project"`// Domain specific fields- Name string `jsonapi:"attr,name"`- FullPath string `jsonapi:"attr,fullPath"`- WebURL string `jsonapi:"attr,webURL"`- BranchFilter string `jsonapi:"attr,branchFilter"`- BaseDirectory string `jsonapi:"attr,baseDirectory"`- FilePathTemplate string `jsonapi:"attr,filePathTemplate"`+ Name string `jsonapi:"attr,name"`+ FullPath string `jsonapi:"attr,fullPath"`+ WebURL string `jsonapi:"attr,webURL"`+ BranchFilter string `jsonapi:"attr,branchFilter"`+ BaseDirectory string `jsonapi:"attr,baseDirectory"`+ // The file path template for matching the commited migration script.+ FilePathTemplate string `jsonapi:"attr,filePathTemplate"`+ // The file path template for storing the latest schema auto-generated by Bytebase after migration.+ // If empty, then Bytebase won't auto generate it.+ SchemaPathTemplate string `jsonapi:"attr,schemaPathTemplate"`ExternalId string `jsonapi:"attr,externalId"`ExternalWebhookId stringWebhookURLHost string@@ -50,13 +54,14 @@ type RepositoryCreate struct {ProjectId int `jsonapi:"attr,projectId"`// Domain specific fields- Name string `jsonapi:"attr,name"`- FullPath string `jsonapi:"attr,fullPath"`- WebURL string `jsonapi:"attr,webURL"`- BranchFilter string `jsonapi:"attr,branchFilter"`- BaseDirectory string `jsonapi:"attr,baseDirectory"`- FilePathTemplate string `jsonapi:"attr,filePathTemplate"`- ExternalId string `jsonapi:"attr,externalId"`+ Name string `jsonapi:"attr,name"`+ FullPath string `jsonapi:"attr,fullPath"`+ WebURL string `jsonapi:"attr,webURL"`+ BranchFilter string `jsonapi:"attr,branchFilter"`+ BaseDirectory string `jsonapi:"attr,baseDirectory"`+ FilePathTemplate string `jsonapi:"attr,filePathTemplate"`+ SchemaPathTemplate string `jsonapi:"attr,schemaPathTemplate"`+ ExternalId string `jsonapi:"attr,externalId"`// Token belonged by the user linking the project to the VCS repository. We store this token together// with the refresh token in the new repository record so we can use it to call VCS API on// behalf of that user to perform tasks like webhook CRUD later.@@ -96,9 +101,10 @@ type RepositoryPatch struct {UpdaterId int// Domain specific fields- BranchFilter *string `jsonapi:"attr,branchFilter"`- BaseDirectory *string `jsonapi:"attr,baseDirectory"`- FilePathTemplate *string `jsonapi:"attr,filePathTemplate"`+ BranchFilter *string `jsonapi:"attr,branchFilter"`+ BaseDirectory *string `jsonapi:"attr,baseDirectory"`+ FilePathTemplate *string `jsonapi:"attr,filePathTemplate"`+ SchemaPathTemplate *string `jsonapi:"attr,schemaPathTemplate"`}type RepositoryDelete struct {diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vueindex 511af6f86c..f9a05379b6 100644--- a/frontend/src/components/RepositoryForm.vue+++ b/frontend/src/components/RepositoryForm.vue@@ -73,7 +73,7 @@<div class="textlabel">File path template <span class="text-red-600">*</span><a- href="https://docs.bytebase.com/use-bytebase/vcs-integration/organize-repository-files"+ href="https://docs.bytebase.com/use-bytebase/vcs-integration/organize-repository-files#file-path-template"target="__blank"class="font-normal normal-link">@@ -94,8 +94,8 @@/><div class="mt-2 textinfolabel"><span class="text-red-600">*</span> Required placeholders:- {{ REQUIRED_PLACEHOLDER }}. Optional placeholders:- {{ OPTIONAL_PLACEHOLDER }}+ {{ FILE_REQUIRED_PLACEHOLDER }}; optional placeholders:+ {{ FILE_OPTIONAL_PLACEHOLDER }}</div><div class="mt-2 textinfolabel">• File path example for normal migration type:@@ -118,6 +118,53 @@}}</div></div>+ <div>+ <div class="textlabel">+ Schema path template+ <a+ href="https://docs.bytebase.com/use-bytebase/vcs-integration/organize-repository-files#schema-path-template"+ target="__blank"+ class="font-normal normal-link"+ >+ config guide</a+ >+ </div>+ <div class="mt-1 textinfolabel">+ When specified, after each migration, Bytebase will write the latest+ schema to the schema path relative to the base directory in the same+ branch as the original commit triggering the migration. Leave empty if+ you don't want Bytebase to do this.+ <span class="font-medium text-main"+ >Make sure the changed branch is not protected or allow repository+ maintainer to push to that protected branch</span+ >.+ </div>+ <input+ id="schemapathtemplate"+ name="schemapathtemplate"+ type="text"+ class="textfield mt-2 w-full"+ :disabled="!allowEdit"+ v-model="repositoryConfig.schemaPathTemplate"+ />+ <div class="mt-2 textinfolabel">+ <span class="text-red-600">*</span> If specified, required placeholder:+ {{ SCHEMA_REQUIRED_PLACEHOLDER }}; optional placeholder:+ {{ SCHEMA_OPTIONAL_PLACEHOLDER }}+ </div>+ <div+ v-if="repositoryConfig.schemaPathTemplate"+ class="mt-2 textinfolabel"+ >+ • Schema path example:+ {{+ sampleSchemaPath(+ repositoryConfig.baseDirectory,+ repositoryConfig.schemaPathTemplate+ )+ }}+ </div>+ </div></div></template>@@ -126,8 +173,10 @@ import { reactive } from "@vue/reactivity";import { PropType } from "@vue/runtime-core";import { ExternalRepositoryInfo, RepositoryConfig, VCSType } from "../types";-const REQUIRED_PLACEHOLDER = "{{DB_NAME}}, {{VERSION}}, {{TYPE}}";-const OPTIONAL_PLACEHOLDER = "{{ENV_NAME}}, {{DESCRIPTION}}";+const FILE_REQUIRED_PLACEHOLDER = "{{DB_NAME}}, {{VERSION}}, {{TYPE}}";+const FILE_OPTIONAL_PLACEHOLDER = "{{ENV_NAME}}, {{DESCRIPTION}}";+const SCHEMA_REQUIRED_PLACEHOLDER = "{{DB_NAME}}";+const SCHEMA_OPTIONAL_PLACEHOLDER = "{{ENV_NAME}}";interface LocalState {}@@ -205,11 +254,38 @@ export default {return result;};+ const sampleSchemaPath = (+ baseDirectory: string,+ schemaPathTemplate: string+ ): string => {+ type Item = {+ placeholder: string;+ sampleText: string;+ };++ const placeholderList: Item[] = [+ {+ placeholder: "{{DB_NAME}}",+ sampleText: "db1",+ },+ ];++ let result: string = `${baseDirectory}/${schemaPathTemplate}`;+ for (const item of placeholderList) {+ const re = new RegExp(item.placeholder, "g");+ result = result.replace(re, item.sampleText);+ }+ return result;+ };+return {- REQUIRED_PLACEHOLDER,- OPTIONAL_PLACEHOLDER,+ FILE_REQUIRED_PLACEHOLDER,+ FILE_OPTIONAL_PLACEHOLDER,+ SCHEMA_REQUIRED_PLACEHOLDER,+ SCHEMA_OPTIONAL_PLACEHOLDER,state,sampleFilePath,+ sampleSchemaPath,};},};diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vueindex 1650ca1444..33bf5cb970 100644--- a/frontend/src/components/RepositoryPanel.vue+++ b/frontend/src/components/RepositoryPanel.vue@@ -23,6 +23,15 @@><span v-else class="font-medium text-main">default branch</span>, Bytebasewill automatically kicks off the task to apply the new schema change.+ <template v-if="state.repositoryConfig.schemaPathTemplate"+ >After applying the schema change, if schema path template is specified,+ Bytebase will also write the latest schema to the specified schema path+ location+ <span class="font-medium text-main">{{+ state.repositoryConfig.schemaPathTemplate+ }}</span+ >.</template+ ></div><RepositoryFormclass="mt-4"@@ -98,6 +107,7 @@ export default {baseDirectory: props.repository.baseDirectory,branchFilter: props.repository.branchFilter,filePathTemplate: props.repository.filePathTemplate,+ schemaPathTemplate: props.repository.schemaPathTemplate,},});@@ -108,6 +118,7 @@ export default {baseDirectory: cur.baseDirectory,branchFilter: cur.branchFilter,filePathTemplate: cur.filePathTemplate,+ schemaPathTemplate: cur.schemaPathTemplate,};});@@ -129,7 +140,9 @@ export default {props.repository.baseDirectory !=state.repositoryConfig.baseDirectory ||props.repository.filePathTemplate !=- state.repositoryConfig.filePathTemplate)+ state.repositoryConfig.filePathTemplate ||+ props.repository.schemaPathTemplate !=+ state.repositoryConfig.schemaPathTemplate));});@@ -164,6 +177,13 @@ export default {repositoryPatch.filePathTemplate =state.repositoryConfig.filePathTemplate;}+ if (+ props.repository.schemaPathTemplate !=+ state.repositoryConfig.schemaPathTemplate+ ) {+ repositoryPatch.schemaPathTemplate =+ state.repositoryConfig.schemaPathTemplate;+ }store.dispatch("repository/updateRepositoryByProjectId", {projectId: props.project.id,diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vueindex bf5cf30e3c..05b4e6f694 100644--- a/frontend/src/components/RepositorySetupWizard.vue+++ b/frontend/src/components/RepositorySetupWizard.vue@@ -52,6 +52,8 @@ import { projectSlug } from "../utils";// Default file path template is to organize migration files from different environments under separate directories.const DEFAULT_FILE_PATH_TEMPLATE ="{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql";+// Default schema path template is co-locate with the corresponding db's migration files and use .(dot) to appear the first.+const DEFAULT_SCHEMA_PATH_TEMPLATE = "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql";const CHOOSE_PROVIDER_STEP = 0;const CHOOSE_REPOSITORY_STEP = 1;@@ -109,6 +111,7 @@ export default {baseDirectory: "",branchFilter: "",filePathTemplate: DEFAULT_FILE_PATH_TEMPLATE,+ schemaPathTemplate: DEFAULT_SCHEMA_PATH_TEMPLATE,},},currentStep: CHOOSE_PROVIDER_STEP,@@ -144,6 +147,7 @@ export default {branchFilter: state.config.repositoryConfig.branchFilter,baseDirectory: state.config.repositoryConfig.baseDirectory,filePathTemplate: state.config.repositoryConfig.filePathTemplate,+ schemaPathTemplate: state.config.repositoryConfig.schemaPathTemplate,externalId: state.config.repositoryInfo.externalId,accessToken: state.config.token.accessToken,expiresTs: state.config.token.expiresTs,diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex bdf4d117e3..84de19d563 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -376,6 +376,7 @@ export const unknown = (baseDirectory: "",branchFilter: "",filePathTemplate: "",+ schemaPathTemplate: "",externalId: UNKNOWN_ID.toString(),};@@ -684,6 +685,7 @@ export const empty = (baseDirectory: "",branchFilter: "",filePathTemplate: "",+ schemaPathTemplate: "",externalId: EMPTY_ID.toString(),};diff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.tsindex 60d8cb817b..2678774f23 100644--- a/frontend/src/types/repository.ts+++ b/frontend/src/types/repository.ts@@ -27,6 +27,7 @@ export type Repository = {baseDirectory: string;branchFilter: string;filePathTemplate: string;+ schemaPathTemplate: string;// e.g. In GitLab, this is the corresponding project id.externalId: string;};@@ -43,6 +44,7 @@ export type RepositoryCreate = {branchFilter: string;baseDirectory: string;filePathTemplate: string;+ schemaPathTemplate: string;externalId: string;accessToken: string;expiresTs: number;@@ -53,12 +55,14 @@ export type RepositoryPatch = {baseDirectory?: string;branchFilter?: string;filePathTemplate?: string;+ schemaPathTemplate?: string;};export type RepositoryConfig = {baseDirectory: string;branchFilter: string;filePathTemplate: string;+ schemaPathTemplate: string;};export type ExternalRepositoryInfo = {diff --git a/server/project.go b/server/project.goindex a5bae91a2a..1d50c969fb 100644--- a/server/project.go+++ b/server/project.go@@ -152,6 +152,10 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted create linked repository request: %s", err.Error()))}+ if err := validateRepositorySchemaPathTemplate(repositoryCreate.SchemaPathTemplate); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted create linked repository request: %s", err.Error()))+ }+vcsFind := &api.VCSFind{ID: &repositoryCreate.VCSId,}@@ -278,6 +282,12 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {}}+ if repositoryPatch.SchemaPathTemplate != nil {+ if err := validateRepositorySchemaPathTemplate(*repositoryPatch.SchemaPathTemplate); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted create linked repository request: %s", err.Error()))+ }+ }+// Remove enclosing /if repositoryPatch.BaseDirectory != nil {baseDir := strings.Trim(*repositoryPatch.BaseDirectory, "/")@@ -475,3 +485,13 @@ func validateRepositoryFilePathTemplate(filePathTemplate string) error {}return nil}++func validateRepositorySchemaPathTemplate(schemaPathTemplate string) error {+ if schemaPathTemplate == "" {+ return nil+ }+ if !strings.Contains(schemaPathTemplate, "{{DB_NAME}}") {+ return fmt.Errorf("missing {{DB_NAME}} in schema path template")+ }+ return nil+}diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex 9f8b9a9669..5c3064ae03 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -152,9 +152,12 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Servereturn true, "", err}- // If VCS based, then we will write back the latest schema file after migration.- if payload.VCSPushEvent != nil {- latestSchemaFile := fmt.Sprintf("%s__#LATEST.sql", databaseName)+ // If VCS based and schema path template is specified, then we will write back the latest schema file after migration.+ if payload.VCSPushEvent != nil && repository.SchemaPathTemplate != "" {+ latestSchemaFile := filepath.Join(repository.BaseDirectory, repository.SchemaPathTemplate)+ latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)+ latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", mi.Database)+repository.VCS, err = server.ComposeVCSById(context.Background(), repository.VCSId)if err != nil {return true, "", fmt.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, databaseName)diff --git a/server/webhook.go b/server/webhook.goindex 08e3f539ea..46850028f6 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -8,6 +8,7 @@ import ("net/http""net/url""path/filepath"+ "regexp""strconv""strings""time"@@ -78,6 +79,29 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {if err != nil {s.l.Warn("Ignored committed file, failed to parse commit timestamp.", zap.String("file", added), zap.String("timestamp", commit.Timestamp), zap.Error(err))}++ // Ignored the schema file we auto generated to the repository.+ if repository.SchemaPathTemplate != "" {+ placeholderList := []string{+ "ENV_NAME",+ "DB_NAME",+ }+ schemafilePathRegex := repository.SchemaPathTemplate+ for _, placeholder := range placeholderList {+ schemafilePathRegex = strings.ReplaceAll(schemafilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))+ }+ myRegex, err := regexp.Compile(schemafilePathRegex)+ if err != nil {+ s.l.Warn("Invalid schema path template.", zap.String("schema_path_template",+ repository.SchemaPathTemplate),+ zap.Error(err),+ )+ }+ if myRegex.MatchString(added) {+ continue+ }+ }+vcsPushEvent := common.VCSPushEvent{VCSType: repository.VCS.Type,BaseDirectory: repository.BaseDirectory,diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sqlindex 89cd1c4f03..c98f30d628 100644--- a/store/migration/10001__init_schema.sql+++ b/store/migration/10001__init_schema.sql@@ -1066,6 +1066,9 @@ CREATE TABLE repository (base_directory TEXT NOT NULL DEFAULT '',-- The file path template for matching the commited migration script.file_path_template TEXT NOT NULL,+ -- The file path template for storing the latest schema auto-generated by Bytebase after migration.+ -- If empty, then Bytebase won't auto generate it.+ schema_path_template TEXT NOT NULL DEFAULT '',-- Repository id from the corresponding VCS provider.-- For GitLab, this is the project id. e.g. 123external_id TEXT NOT NULL,diff --git a/store/repository.go b/store/repository.goindex c1e79ecf85..41f7be63b8 100644--- a/store/repository.go+++ b/store/repository.go@@ -152,6 +152,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, createbranch_filter,base_directory,file_path_template,+ schema_path_template,external_id,external_webhook_id,webhook_url_host,@@ -161,8 +162,8 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, createexpires_ts,refresh_token)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, branch_filter, base_directory, file_path_template, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token, access_token, expires_ts, refresh_token+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, branch_filter, base_directory, file_path_template, schema_path_template, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token, access_token, expires_ts, refresh_token`,create.CreatorId,create.CreatorId,@@ -174,6 +175,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, createcreate.BranchFilter,create.BaseDirectory,create.FilePathTemplate,+ create.SchemaPathTemplate,create.ExternalId,create.ExternalWebhookId,create.WebhookURLHost,@@ -205,6 +207,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, create&repository.BranchFilter,&repository.BaseDirectory,&repository.FilePathTemplate,+ &repository.SchemaPathTemplate,&repository.ExternalId,&repository.ExternalWebhookId,&repository.WebhookURLHost,@@ -251,6 +254,7 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (branch_filter,base_directory,file_path_template,+ schema_path_template,external_id,external_webhook_id,webhook_url_host,@@ -286,6 +290,7 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (&repository.BranchFilter,&repository.BaseDirectory,&repository.FilePathTemplate,+ &repository.SchemaPathTemplate,&repository.ExternalId,&repository.ExternalWebhookId,&repository.WebhookURLHost,@@ -320,6 +325,9 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*if v := patch.FilePathTemplate; v != nil {set, args = append(set, "file_path_template = ?"), append(args, *v)}+ if v := patch.SchemaPathTemplate; v != nil {+ set, args = append(set, "schema_path_template = ?"), append(args, *v)+ }args = append(args, patch.ID)@@ -328,7 +336,7 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*UPDATE repositorySET `+strings.Join(set, ", ")+`WHERE id = ?- RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, branch_filter, base_directory, file_path_template, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token, access_token, expires_ts, refresh_token+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, branch_filter, base_directory, file_path_template, schema_path_template, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token, access_token, expires_ts, refresh_token`,args...,)@@ -353,6 +361,7 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*&repository.BranchFilter,&repository.BaseDirectory,&repository.FilePathTemplate,+ &repository.SchemaPathTemplate,&repository.ExternalId,&repository.ExternalWebhookId,&repository.WebhookURLHost,diff --git a/store/seed/test/10180__repository.sql b/store/seed/test/10180__repository.sqlindex 53a9c12285..74fcfdfc4a 100644--- a/store/seed/test/10180__repository.sql+++ b/store/seed/test/10180__repository.sql@@ -12,6 +12,7 @@ INSERT INTObranch_filter,base_directory,file_path_template,+ schema_path_template,external_id,external_webhook_id,webhook_url_host,@@ -34,6 +35,7 @@ VALUES"master","bytebase","{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",-- Refers to the bytebase-demo/blog"13",-- Refers to the webhook in bytebase-demo/blog@@ -59,6 +61,7 @@ INSERT INTObranch_filter,base_directory,file_path_template,+ schema_path_template,external_id,external_webhook_id,webhook_url_host,@@ -81,6 +84,7 @@ VALUES"master","bytebase","{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",-- Refers to the bytebase-demo/shop"14",-- Refers to the webhook in bytebase-demo/shop