Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: refactor sql review ci setup (#3085)
ecmadao61ce67c07bd5
diff --git a/api/repository.go b/api/repository.goindex 13be989d53..c80977c774 100644--- a/api/repository.go+++ b/api/repository.go@@ -36,23 +36,27 @@ type Repository struct {// The file path template for matching the sql files for sheet.SheetPathTemplate string `jsonapi:"attr,sheetPathTemplate"`// Setup CI to do SQL review for all PRs.- EnableSQLReviewCI bool `jsonapi:"attr,enableSQLReviewCI"`- // SQLReviewCIPullRequestURL is the pull request URL to setup the SQL review CI.- // This field is used by the frontend to redirect users to the pull request.- // We don't need to persist it in the storage,- // only return this value if we need to auto-create the pull request for users.- SQLReviewCIPullRequestURL string `jsonapi:"attr,sqlReviewCIPullRequestURL"`- ExternalID string `jsonapi:"attr,externalId"`- ExternalWebhookID string- WebhookURLHost string- WebhookEndpointID string `jsonapi:"attr,webhookEndpointID"`- WebhookSecretToken string+ EnableSQLReviewCI bool `jsonapi:"attr,enableSQLReviewCI"`+ ExternalID string `jsonapi:"attr,externalId"`+ ExternalWebhookID string+ WebhookURLHost string+ WebhookEndpointID string `jsonapi:"attr,webhookEndpointID"`+ WebhookSecretToken string// These will be exclusively used on the server side and we don't return it to the client.AccessToken stringExpiresTs int64RefreshToken string}+// SQLReviewCISetup is the API message for set up repository SQL review CI.+type SQLReviewCISetup struct {+ // PullRequestURL is the pull request URL to setup the SQL review CI.+ // This field is used by the frontend to redirect users to the pull request.+ // We don't need to persist it in the storage,+ // only return this value if we need to auto-create the pull request for users.+ PullRequestURL string `jsonapi:"attr,pullRequestURL"`+}+// RepositoryCreate is the API message for creating a repository.type RepositoryCreate struct {// Standard fields@@ -72,7 +76,6 @@ type RepositoryCreate struct {FilePathTemplate string `jsonapi:"attr,filePathTemplate"`SchemaPathTemplate string `jsonapi:"attr,schemaPathTemplate"`SheetPathTemplate string `jsonapi:"attr,sheetPathTemplate"`- EnableSQLReviewCI bool `jsonapi:"attr,enableSQLReviewCI"`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 ondiff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vueindex 6e81474c6c..fbd1f22c02 100644--- a/frontend/src/components/RepositoryForm.vue+++ b/frontend/src/components/RepositoryForm.vue@@ -251,10 +251,17 @@:title="enableSQLReviewTitle":value="repositoryConfig.enableSQLReviewCI"@toggle="(on: boolean) => {- repositoryConfig.enableSQLReviewCI = on; }"+ repositoryConfig.enableSQLReviewCI = on;+ onSQLReviewCIToggle(on);+ }"/></div></div>+ <FeatureModal+ v-if="state.showFeatureModal"+ feature="bb.feature.vcs-sql-review"+ @cancel="state.showFeatureModal = false"+ /></div></template>@@ -269,6 +276,7 @@ import {VCSType,} from "@/types";import BBBetaBadge from "@/bbkit/BBBetaBadge.vue";+import { hasFeature } from "@/store";const FILE_REQUIRED_PLACEHOLDER = "{{DB_NAME}}, {{VERSION}}, {{TYPE}}";const SCHEMA_REQUIRED_PLACEHOLDER = "{{DB_NAME}}";@@ -277,7 +285,9 @@ const SINGLE_ASTERISK_REGEX = /\/\*\//g;const DOUBLE_ASTERISKS_REGEX = /\/\*\*\//g;// eslint-disable-next-line @typescript-eslint/no-empty-interface-interface LocalState {}+interface LocalState {+ showFeatureModal: boolean;+}export default defineComponent({name: "RepositoryForm",@@ -320,7 +330,9 @@ export default defineComponent({setup(props) {const { t } = useI18n();- const state = reactive<LocalState>({});+ const state = reactive<LocalState>({+ showFeatureModal: false,+ });const isTenantProject = computed(() => {return props.project.tenantMode === "TENANT";@@ -413,6 +425,12 @@ export default defineComponent({return tags;});+ const onSQLReviewCIToggle = (on: boolean) => {+ if (on && !hasFeature("bb.feature.vcs-sql-review")) {+ state.showFeatureModal = true;+ }+ };+return {FILE_REQUIRED_PLACEHOLDER,SCHEMA_REQUIRED_PLACEHOLDER,@@ -424,6 +442,7 @@ export default defineComponent({enableSQLReviewTitle,sampleFilePath,sampleSchemaPath,+ onSQLReviewCIToggle,};},});diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vueindex a865028a36..338f6ce189 100644--- a/frontend/src/components/RepositoryPanel.vue+++ b/frontend/src/components/RepositoryPanel.vue@@ -114,6 +114,24 @@</div></div></BBModal>+ <BBAlert+ v-if="state.showSetupSQLReviewCIFailureModal"+ :style="'CRITICAL'"+ :ok-text="$t('common.retry')"+ :title="$t('repository.sql-review-ci-setup-failed')"+ @ok="+ () => {+ state.showSetupSQLReviewCIFailureModal = false;+ createSQLReviewCI();+ }+ "+ @cancel="+ () => {+ state.showSetupSQLReviewCIFailureModal = false;+ }+ "+ >+ </BBAlert><BBModalv-if="state.showLoadingSQLReviewPRModal"class="relative overflow-hidden"@@ -238,6 +256,7 @@ interface LocalState {schemaChangeType: SchemaChangeType;showFeatureModal: boolean;showSetupSQLReviewCIModal: boolean;+ showSetupSQLReviewCIFailureModal: boolean;showLoadingSQLReviewPRModal: boolean;showDisableSQLReviewCIModal: boolean;showRestoreSQLReviewCIModal: boolean;@@ -277,6 +296,7 @@ export default defineComponent({schemaChangeType: props.project.schemaChangeType,showFeatureModal: false,showSetupSQLReviewCIModal: false,+ showSetupSQLReviewCIFailureModal: false,showLoadingSQLReviewPRModal: false,showDisableSQLReviewCIModal: false,showRestoreSQLReviewCIModal: false,@@ -352,6 +372,32 @@ export default defineComponent({});};+ const createSQLReviewCI = async () => {+ const repository = repositoryStore.getRepositoryByProjectId(+ props.project.id+ );++ state.showLoadingSQLReviewPRModal = true;++ try {+ const sqlReviewCISetup = await repositoryStore.createSQLReviewCI({+ projectId: props.project.id,+ repositoryId: repository.id,+ });+ state.sqlReviewCIPullRequestURL = sqlReviewCISetup.pullRequestURL;+ state.showSetupSQLReviewCIModal = true;+ window.open(sqlReviewCISetup.pullRequestURL, "_blank");+ repositoryStore.setRepositorySQLReviewCIEnabled({+ projectId: props.project.id,+ sqlReviewCIEnabled: true,+ });+ } catch {+ state.showSetupSQLReviewCIFailureModal = true;+ } finally {+ state.showLoadingSQLReviewPRModal = false;+ }+ };+const doUpdate = async () => {if (state.repositoryConfig.enableSQLReviewCI &&@@ -362,12 +408,9 @@ export default defineComponent({return;}- if (+ const needSetupCI =!props.repository.enableSQLReviewCI &&- state.repositoryConfig.enableSQLReviewCI- ) {- state.showLoadingSQLReviewPRModal = true;- }+ state.repositoryConfig.enableSQLReviewCI;const repositoryPatch: RepositoryPatch = {};if (@@ -425,20 +468,17 @@ export default defineComponent({const disableSQLReview = disableSQLReviewCI.value;- const updatedRepository =- await repositoryStore.updateRepositoryByProjectId({- projectId: props.project.id,- repositoryPatch,- });- if (updatedRepository.sqlReviewCIPullRequestURL) {- state.sqlReviewCIPullRequestURL =- updatedRepository.sqlReviewCIPullRequestURL;- state.showLoadingSQLReviewPRModal = false;- state.showSetupSQLReviewCIModal = true;- window.open(updatedRepository.sqlReviewCIPullRequestURL, "_blank");+ await repositoryStore.updateRepositoryByProjectId({+ projectId: props.project.id,+ repositoryPatch,+ });++ if (needSetupCI) {+ createSQLReviewCI();} else if (disableSQLReview) {state.showDisableSQLReviewCIModal = true;}+pushNotification({module: "bytebase",style: "SUCCESS",@@ -453,6 +493,7 @@ export default defineComponent({restoreToUIWorkflowType,onSQLReviewCIModalClose,doUpdate,+ createSQLReviewCI,};},});diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vueindex c1bbe66d0f..7bc6d39d9f 100644--- a/frontend/src/components/RepositorySetupWizard.vue+++ b/frontend/src/components/RepositorySetupWizard.vue@@ -80,6 +80,25 @@</div></div></BBModal>+ <BBAlert+ v-if="state.showSetupSQLReviewCIFailureModal"+ :style="'CRITICAL'"+ :ok-text="$t('common.retry')"+ :title="$t('repository.sql-review-ci-setup-failed')"+ @ok="+ () => {+ state.showSetupSQLReviewCIFailureModal = false;+ createSQLReviewCI();+ }+ "+ @cancel="+ () => {+ state.showSetupSQLReviewCIFailureModal = false;+ $emit('finish');+ }+ "+ >+ </BBAlert><BBModalv-if="state.showLoadingSQLReviewPRModal"class="relative overflow-hidden"@@ -154,6 +173,7 @@ interface LocalState {currentStep: number;showFeatureModal: boolean;showSetupSQLReviewCIModal: boolean;+ showSetupSQLReviewCIFailureModal: boolean;showLoadingSQLReviewPRModal: boolean;sqlReviewCIPullRequestURL: string;}@@ -227,6 +247,7 @@ export default defineComponent({currentStep: CHOOSE_PROVIDER_STEP,showFeatureModal: false,showSetupSQLReviewCIModal: false,+ showSetupSQLReviewCIFailureModal: false,showLoadingSQLReviewPRModal: false,sqlReviewCIPullRequestURL: "",});@@ -250,6 +271,31 @@ export default defineComponent({allowChangeCallback();};+ const createSQLReviewCI = async () => {+ const repository = repositoryStore.getRepositoryByProjectId(+ props.project.id+ );+ state.showLoadingSQLReviewPRModal = true;++ try {+ const sqlReviewCISetup = await repositoryStore.createSQLReviewCI({+ projectId: props.project.id,+ repositoryId: repository.id,+ });+ state.sqlReviewCIPullRequestURL = sqlReviewCISetup.pullRequestURL;+ state.showSetupSQLReviewCIModal = true;+ window.open(sqlReviewCISetup.pullRequestURL, "_blank");+ repositoryStore.setRepositorySQLReviewCIEnabled({+ projectId: props.project.id,+ sqlReviewCIEnabled: true,+ });+ } catch {+ state.showSetupSQLReviewCIFailureModal = true;+ } finally {+ state.showLoadingSQLReviewPRModal = false;+ }+ };+const tryFinishSetup = (allowFinishCallback: () => void) => {if (state.config.repositoryConfig.enableSQLReviewCI &&@@ -260,10 +306,6 @@ export default defineComponent({}const createFunc = async () => {- if (state.config.repositoryConfig.enableSQLReviewCI) {- state.showLoadingSQLReviewPRModal = true;- }-let externalId = state.config.repositoryInfo.externalId;if (state.config.vcs.type == "GITHUB_COM") {externalId = state.config.repositoryInfo.fullPath;@@ -290,25 +332,22 @@ export default defineComponent({filePathTemplate: state.config.repositoryConfig.filePathTemplate,schemaPathTemplate: state.config.repositoryConfig.schemaPathTemplate,sheetPathTemplate: state.config.repositoryConfig.sheetPathTemplate,- enableSQLReviewCI: state.config.repositoryConfig.enableSQLReviewCI,externalId: externalId,accessToken: state.config.token.accessToken,expiresTs: state.config.token.expiresTs,refreshToken: state.config.token.refreshToken,};- const createdRepository = await repositoryStore.createRepository({+ await repositoryStore.createRepository({projectId: props.project.id,repositoryCreate,});- if (createdRepository.sqlReviewCIPullRequestURL) {- state.showLoadingSQLReviewPRModal = false;- state.sqlReviewCIPullRequestURL =- createdRepository.sqlReviewCIPullRequestURL;- state.showSetupSQLReviewCIModal = true;- window.open(createdRepository.sqlReviewCIPullRequestURL, "_blank");++ if (state.config.repositoryConfig.enableSQLReviewCI) {+ createSQLReviewCI();} else {emit("finish");}+allowFinishCallback();};@@ -369,6 +408,7 @@ export default defineComponent({setVCS,setToken,setRepository,+ createSQLReviewCI,closeSetupSQLReviewModal,};},diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex b5b9f27dbb..e7f3d715ed 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -933,6 +933,7 @@"sql-review-ci-enable-github": "Enable SQL Review CI via GitHub Action","sql-review-ci-description": "Bytebase will create a {pr} to set up the SQL review CI in your repository. After the setup, in every {pr}, the SQL review policy will check against changed files matching the \"{pathTemplate}\".","sql-review-ci-setup": "Setup SQL Review CI",+ "sql-review-ci-setup-failed": "Failed to setup SQL Review CI","sql-review-ci-setup-pr": "Review the {pr}","merge-request": "merge request","pull-request": "pull request",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 146ab43ed6..6b12a038cf 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -934,6 +934,7 @@"sql-review-ci-enable-github": "基于 GitHub Action 开启 SQL 审核","sql-review-ci-description": "Bytebase 会发起{pr}为您的代码仓库配置 SQL 审核 CI。配置完成后,在每一个{pr}中,SQL 审核策略将应用于任何匹配上「{pathTemplate}」的文件修改。","sql-review-ci-setup": "配置 SQL 审核 CI",+ "sql-review-ci-setup-failed": "SQL 审核 CI 创建失败","sql-review-ci-setup-pr": "查看{pr}","merge-request": "合并请求","pull-request": "拉取请求",diff --git a/frontend/src/store/modules/repository.ts b/frontend/src/store/modules/repository.tsindex 496a23e47c..6b895d4c9d 100644--- a/frontend/src/store/modules/repository.ts+++ b/frontend/src/store/modules/repository.ts@@ -3,10 +3,12 @@ import axios from "axios";import {Project,ProjectId,+ RepositoryId,Repository,RepositoryCreate,RepositoryPatch,RepositoryState,+ SQLReviewCISetup,ResourceIdentifier,ResourceObject,unknown,@@ -97,6 +99,23 @@ export const useRepositoryStore = defineStore("repository", {removeRepositoryByProjectId(projectId: ProjectId) {this.repositoryByProjectId.delete(projectId);},+ setRepositorySQLReviewCIEnabled({+ projectId,+ sqlReviewCIEnabled,+ }: {+ projectId: ProjectId;+ sqlReviewCIEnabled: boolean;+ }) {+ const repository = this.repositoryByProjectId.get(projectId);+ if (!repository) {+ return;+ }++ this.repositoryByProjectId.set(projectId, {+ ...repository,+ enableSQLReviewCI: sqlReviewCIEnabled,+ });+ },async createRepository({projectId,repositoryCreate,@@ -191,5 +210,24 @@ export const useRepositoryStore = defineStore("repository", {// Refetch the project as the project workflow type has been updated to "UI"useProjectStore().fetchProjectById(projectId);},+ async createSQLReviewCI({+ projectId,+ repositoryId,+ }: {+ projectId: ProjectId;+ repositoryId: RepositoryId;+ }): Promise<SQLReviewCISetup> {+ const data = (+ await axios.post(+ `/api/project/${projectId}/repository/${repositoryId}/sql-review-ci`+ )+ ).data;++ const sqlReviewCISetup: SQLReviewCISetup = {+ ...(data.data.attributes as Omit<SQLReviewCISetup, "">),+ };++ return sqlReviewCISetup;+ },},});diff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.tsindex de3ab278bf..5d0aa75891 100644--- a/frontend/src/types/repository.ts+++ b/frontend/src/types/repository.ts@@ -35,6 +35,10 @@ export type Repository = {externalId: string;};+export type SQLReviewCISetup = {+ pullRequestURL: string;+};+export type RepositoryCreate = {// Related fieldsvcsId: VCSId;@@ -48,7 +52,6 @@ export type RepositoryCreate = {filePathTemplate: string;schemaPathTemplate: string;sheetPathTemplate: string;- enableSQLReviewCI: boolean;externalId: string;accessToken: string;expiresTs: number;diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex 8c0e4a9985..4572f9ac0f 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -10,6 +10,7 @@ p, DBA, /project/{id}/repository, GETp, DBA, /project/{id}/repository, POSTp, DBA, /project/{id}/repository, PATCHp, DBA, /project/{id}/repository, DELETE+p, DBA, /project/{projectID}/repository/{repositoryID}/sql-review-ci, POSTp, DBA, /project/{id}/deployment, GETp, DBA, /project/{id}/deployment, PATCHp, DBA, /project/{projectID}/sync-member, POSTdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex cd1ddd2c5c..dc3801f7f2 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -10,6 +10,7 @@ p, DEVELOPER, /project/{id}/repository, GETp, DEVELOPER, /project/{id}/repository, POSTp, DEVELOPER, /project/{id}/repository, PATCHp, DEVELOPER, /project/{id}/repository, DELETE+p, DEVELOPER, /project/{projectID}/repository/{repositoryID}/sql-review-ci, POSTp, DEVELOPER, /project/{id}/deployment, GETp, DEVELOPER, /project/{id}/deployment, PATCHp, DEVELOPER, /project/{projectID}/sync-member, POSTdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 9eeacb494f..08947186f3 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -14,6 +14,7 @@ p, OWNER, /project/{id}/repository, GETp, OWNER, /project/{id}/repository, POSTp, OWNER, /project/{id}/repository, PATCHp, OWNER, /project/{id}/repository, DELETE+p, OWNER, /project/{projectID}/repository/{repositoryID}/sql-review-ci, POSTp, OWNER, /project/{id}/deployment, GETp, OWNER, /project/{id}/deployment, PATCHp, OWNER, /project/{projectID}/sync-member, POSTdiff --git a/server/project.go b/server/project.goindex c16c368bc1..fe8b8bfc87 100644--- a/server/project.go+++ b/server/project.go@@ -317,18 +317,73 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)}- // Setup SQL review CI for VCS- if repository.EnableSQLReviewCI && s.flight(api.FeatureVCSSQLReviewWorkflow) && s.feature(api.FeatureVCSSQLReviewWorkflow) {- pullRequest, err := s.setupVCSSQLReviewCI(ctx, repository)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create SQL review CI").SetInternal(err)+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)+ }+ return nil+ })++ g.POST("/project/:projectID/repository/:repositoryID/sql-review-ci", func(c echo.Context) error {+ if !s.flight(api.FeatureVCSSQLReviewWorkflow) {+ return echo.NewHTTPError(http.StatusBadRequest, "SQL review CI feature is not enabled")+ }++ ctx := c.Request().Context()+ projectID, err := strconv.Atoi(c.Param("projectID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)+ }+ repositoryID, err := strconv.Atoi(c.Param("repositoryID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Repository ID is not a number: %s", c.Param("repositoryID"))).SetInternal(err)+ }++ repository, err := s.store.GetRepository(ctx, &api.RepositoryFind{+ ID: &repositoryID,+ ProjectID: &projectID,+ })+ if err != nil {+ if common.ErrorCode(err) == common.NotFound {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot found repository %d in project %d", repositoryID, projectID)).SetInternal(err)}- repository.SQLReviewCIPullRequestURL = pullRequest.URL+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find repository %d in project %d", repositoryID, projectID)).SetInternal(err)+ }++ if repository.Project.RowStatus == api.Archived {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project %d is archived", projectID))+ }++ if !s.feature(api.FeatureVCSSQLReviewWorkflow) {+ return echo.NewHTTPError(http.StatusForbidden, api.FeatureVCSSQLReviewWorkflow.AccessErrorMessage())+ }++ if repository.EnableSQLReviewCI {+ return echo.NewHTTPError(http.StatusBadRequest, "SQL review CI is already enabled")+ }++ pullRequest, err := s.setupVCSSQLReviewCI(ctx, repository)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create SQL review CI").SetInternal(err)+ }++ response := &api.SQLReviewCISetup{+ PullRequestURL: pullRequest.URL,+ }++ enabledCI := true+ repoPatch := &api.RepositoryPatch{+ ID: &repository.ID,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ EnableSQLReviewCI: &enabledCI,+ }+ if _, err := s.store.PatchRepository(ctx, repoPatch); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository: %d", repository.ID)).SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)+ if err := jsonapi.MarshalPayload(c.Response().Writer, response); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response").SetInternal(err)}return nil})@@ -438,20 +493,17 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, errors.Wrap(err, "Invalid base directory and filepath template combination").Error())}+ // DO NOT enable the EnableSQLReviewCI field.+ // We will update it through POST /project/:projectID/repository/:repositoryID/sql-review-ci endpoint+ if repoPatch.EnableSQLReviewCI != nil && *repoPatch.EnableSQLReviewCI && !repo.EnableSQLReviewCI {+ repoPatch.EnableSQLReviewCI = &repo.EnableSQLReviewCI+ }+updatedRepo, err := s.store.PatchRepository(ctx, repoPatch)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectID)).SetInternal(err)}- // Setup SQL review CI for VCS- if !repo.EnableSQLReviewCI && updatedRepo.EnableSQLReviewCI && s.flight(api.FeatureVCSSQLReviewWorkflow) && s.feature(api.FeatureVCSSQLReviewWorkflow) {- pullRequest, err := s.setupVCSSQLReviewCI(ctx, updatedRepo)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create SQL review CI").SetInternal(err)- }- updatedRepo.SQLReviewCIPullRequestURL = pullRequest.URL- }-c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, updatedRepo); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectID)).SetInternal(err)diff --git a/store/repository.go b/store/repository.goindex e293b0060e..363522cd7f 100644--- a/store/repository.go+++ b/store/repository.go@@ -306,7 +306,6 @@ func (s *Store) createRepositoryImpl(ctx context.Context, tx *Tx, create *api.Refile_path_template,schema_path_template,sheet_path_template,- enable_sql_review_ci,external_id,external_webhook_id,webhook_url_host,@@ -316,7 +315,7 @@ func (s *Store) createRepositoryImpl(ctx context.Context, tx *Tx, create *api.Reexpires_ts,refresh_token)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)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, sheet_path_template, enable_sql_review_ci, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token, access_token, expires_ts, refresh_token`if err := tx.QueryRowContext(ctx, query,@@ -332,7 +331,6 @@ func (s *Store) createRepositoryImpl(ctx context.Context, tx *Tx, create *api.Recreate.FilePathTemplate,create.SchemaPathTemplate,create.SheetPathTemplate,- create.EnableSQLReviewCI,create.ExternalID,create.ExternalWebhookID,create.WebhookURLHost,diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 507b9259ae..23f8fadb4b 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -400,7 +400,6 @@ func TestVCS(t *testing.T) {ExternalID: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",- EnableSQLReviewCI: true,},)a.NoError(err)@@ -755,7 +754,6 @@ func TestVCS_SDL(t *testing.T) {ExternalID: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",- EnableSQLReviewCI: true,},)a.NoError(err)@@ -1274,7 +1272,6 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {ExternalID: externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",- EnableSQLReviewCI: true,},)a.NoError(err)@@ -1527,14 +1524,23 @@ func TestVCS_SQL_Review(t *testing.T) {ExternalID: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",- EnableSQLReviewCI: true,},)a.NoError(err)a.NotNil(repository)+ a.Equal(false, repository.EnableSQLReviewCI)- // Simulate Git commits and pull request for SQL review.+ sqlReviewCI, err := ctl.createSQLReviewCI(project.ID, repository.ID)+ a.NoError(err)+ a.NotNil(sqlReviewCI)+ repositoryList, err := ctl.listRepository(project.ID)+ a.NoError(err)+ a.NotNil(repositoryList)+ a.Equal(1, len(repositoryList))+ a.Equal(true, repositoryList[0].EnableSQLReviewCI)++ // Simulate Git commits and pull request for SQL review.prID := rand.Int()gitFile := "bbtest/Prod/testVCSSchemaUpdate##ver3##migrate##create_table_book.sql"fileContent := "CREATE TABLE book (id serial PRIMARY KEY, name TEXT);"diff --git a/tests/tests.go b/tests/tests.goindex 2a0583d7b4..40ab1d57e1 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -1082,6 +1082,42 @@ func (ctl *controller) createRepository(repositoryCreate api.RepositoryCreate) (return repository, nil}+// listRepository gets the repository list.+func (ctl *controller) listRepository(projectID int) ([]*api.Repository, error) {+ body, err := ctl.get(fmt.Sprintf("/project/%d/repository", projectID), nil)+ if err != nil {+ return nil, err+ }++ var repositories []*api.Repository+ ps, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.Repository)))+ if err != nil {+ return nil, errors.Wrap(err, "fail to unmarshal get repository response")+ }+ for _, p := range ps {+ repository, ok := p.(*api.Repository)+ if !ok {+ return nil, errors.Errorf("fail to convert repository")+ }+ repositories = append(repositories, repository)+ }+ return repositories, nil+}++// createSQLReviewCI set up the SQL review CI.+func (ctl *controller) createSQLReviewCI(projectID, repositoryID int) (*api.SQLReviewCISetup, error) {+ body, err := ctl.post(fmt.Sprintf("/project/%d/repository/%d/sql-review-ci", projectID, repositoryID), new(bytes.Buffer))+ if err != nil {+ return nil, err+ }++ sqlReviewCISetup := new(api.SQLReviewCISetup)+ if err = jsonapi.UnmarshalPayload(body, sqlReviewCISetup); err != nil {+ return nil, errors.Wrap(err, "fail to unmarshal SQL reivew CI response")+ }+ return sqlReviewCISetup, nil+}+func (ctl *controller) createDatabase(project *api.Project, instance *api.Instance, databaseName string, owner string, labelMap map[string]string) error {labels, err := marshalLabels(labelMap, instance.Environment.Name)if err != nil {