Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Implement restore project from version control workflow to UI workflow

天舟39229e546a7c
diff --git a/backend/api/repository.go b/backend/api/repository.go
index 906a927d0a..a7a99c9cad 100644
--- a/backend/api/repository.go
+++ b/backend/api/repository.go
@@ -82,7 +82,8 @@ type RepositoryPatch struct {
}
type RepositoryDelete struct {
- ID int
+ // Related fields
+ ProjectId int
// Standard fields
// Value is assigned from the jwt subject field passed by the client.
diff --git a/backend/external/gitlab/gitlab.go b/backend/external/gitlab/gitlab.go
new file mode 100644
index 0000000000..b943af1a23
--- /dev/null
+++ b/backend/external/gitlab/gitlab.go
@@ -0,0 +1,31 @@
+package gitlab
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+)
+
+const (
+ ApiPath = "/api/v4"
+)
+
+func Delete(instanceURL string, resourcePath string, token string) (*http.Response, error) {
+ url := fmt.Sprintf("%s%s%s", instanceURL, ApiPath, resourcePath)
+ log.Printf("url: %s token: %s\n", url, token)
+ req, err := http.NewRequest("DELETE",
+ url, nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to construct DELETE %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Add("Authorization", "Bearer "+token)
+ client := &http.Client{}
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed DELETE %v (%w)", url, err)
+ }
+
+ return resp, nil
+}
diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csv
index 8713de584c..9ba6e41c1e 100644
--- a/backend/server/acl_casbin_policy_dba.csv
+++ b/backend/server/acl_casbin_policy_dba.csv
@@ -8,6 +8,7 @@ p, DBA, /project/{id}, GET
p, DBA, /project/{id}, PATCH
p, DBA, /project/{id}/repository, GET
p, DBA, /project/{id}/repository, POST
+p, DBA, /project/{id}/repository, DELETE
p, DBA, /project/{projectId}/member, POST
p, DBA, /project/{projectId}/member/{memberId}, PATCH
p, DBA, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csv
index 0c85731be6..b3d2ac576e 100644
--- a/backend/server/acl_casbin_policy_developer.csv
+++ b/backend/server/acl_casbin_policy_developer.csv
@@ -8,6 +8,7 @@ p, DEVELOPER, /project/{id}, GET
p, DEVELOPER, /project/{id}, PATCH
p, DEVELOPER, /project/{id}/repository, GET
p, DEVELOPER, /project/{id}/repository, POST
+p, DEVELOPER, /project/{id}/repository, DELETE
p, DEVELOPER, /project/{projectId}/member, POST
p, DEVELOPER, /project/{projectId}/member/{memberId}, PATCH
p, DEVELOPER, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csv
index 054c518e05..b663aedc94 100644
--- a/backend/server/acl_casbin_policy_owner.csv
+++ b/backend/server/acl_casbin_policy_owner.csv
@@ -13,6 +13,7 @@ p, OWNER, /project/{id}, GET
p, OWNER, /project/{id}, PATCH
p, OWNER, /project/{id}/repository, GET
p, OWNER, /project/{id}/repository, POST
+p, OWNER, /project/{id}/repository, DELETE
p, OWNER, /project/{projectId}/member, POST
p, OWNER, /project/{projectId}/member/{memberId}, PATCH
p, OWNER, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/project.go b/backend/server/project.go
index f9c4e29e68..28956fd152 100644
--- a/backend/server/project.go
+++ b/backend/server/project.go
@@ -8,8 +8,10 @@ import (
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/external/gitlab"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
+ "go.uber.org/zap"
)
func (s *Server) registerProjectRoutes(g *echo.Group) {
@@ -183,6 +185,71 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
return nil
})
+
+ // When we unlink the repository with the project, we will also change the project workflow type to UI
+ g.DELETE("/project/:projectId/repository", func(c echo.Context) error {
+ id, err := strconv.Atoi(c.Param("projectId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
+ }
+
+ repositoryFind := &api.RepositoryFind{
+ ProjectId: &id,
+ }
+ list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", id)).SetInternal(err)
+ }
+
+ // Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_id
+ if len(list) > 1 {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), id)).SetInternal(err)
+ } else if len(list) == 0 {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", id))
+ }
+
+ repository := list[0]
+ vcsFind := &api.VCSFind{
+ ID: &repository.VCSId,
+ }
+ vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", id)).SetInternal(err)
+ }
+
+ repositoryDelete := &api.RepositoryDelete{
+ ProjectId: id,
+ DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
+ }
+ if err := s.RepositoryService.DeleteRepository(context.Background(), repositoryDelete); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", id)).SetInternal(err)
+ }
+
+ // Deletes the webhook after we successfully delete the repository.
+ // This is because in case the webhook deletion fails, we can still have a cleanup processor to cleanup the orphaned webhook.
+ // If we delete it before we delete the repository, then if the repository deletion fails, we will have a broken repository with no webhook.
+ switch vcs.Type {
+ case "GITLAB_SELF_HOST":
+ resp, err := gitlab.Delete(vcs.InstanceURL, fmt.Sprintf("/projects/%s/hooks/%s", repository.ExternalId, repository.WebhookId), vcs.AccessToken)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete webhook ID %s for project ID: %v", repository.WebhookId, id)).SetInternal(err)
+ }
+
+ // Just emits a warning since we have already removed the repository entry. We will have a separate processor to cleanup the orphaned webhook.
+ if resp.StatusCode >= 300 {
+ s.l.Error(("failed to delete gitlab webhook when unlinking repository from project"),
+ zap.Int("status_code", resp.StatusCode),
+ zap.Int("project_id", id),
+ zap.Int("repository_id", repository.ID),
+ zap.String("gitlab_project_id", repository.ExternalId),
+ zap.String("gitlab_webhook_id", repository.WebhookId))
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ c.Response().WriteHeader(http.StatusOK)
+ return nil
+ })
}
func (s *Server) ComposeProjectlById(ctx context.Context, id int, includeList []string) (*api.Project, error) {
diff --git a/backend/server/vcs.go b/backend/server/vcs.go
index 61b9b0fce0..bc82696a0b 100644
--- a/backend/server/vcs.go
+++ b/backend/server/vcs.go
@@ -5,17 +5,15 @@ import (
"fmt"
"net/http"
"strconv"
+ "strings"
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/external/gitlab"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
-const (
- apiPath = "api/v4"
-)
-
func (s *Server) registerVCSRoutes(g *echo.Group) {
g.POST("/vcs", func(c echo.Context) error {
vcsCreate := &api.VCSCreate{
@@ -24,7 +22,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, vcsCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create VCS request").SetInternal(err)
}
- vcsCreate.ApiURL = fmt.Sprintf("%s/%s", vcsCreate.InstanceURL, apiPath)
+ vcsCreate.ApiURL = fmt.Sprintf("%s/%s", vcsCreate.InstanceURL, gitlab.ApiPath)
vcs, err := s.VCSService.CreateVCS(context.Background(), vcsCreate)
if err != nil {
diff --git a/backend/store/repository.go b/backend/store/repository.go
index d1c39fee0e..d607fe2e62 100644
--- a/backend/store/repository.go
+++ b/backend/store/repository.go
@@ -114,7 +114,7 @@ func (s *RepositoryService) DeleteRepository(ctx context.Context, delete *api.Re
}
defer tx.Rollback()
- err = deleteRepository(ctx, tx, delete)
+ err = s.deleteRepository(ctx, tx, delete)
if err != nil {
return FormatError(err)
}
@@ -330,16 +330,27 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*
}
// deleteRepository permanently deletes a repository by ID.
-func deleteRepository(ctx context.Context, tx *Tx, delete *api.RepositoryDelete) error {
+func (s *RepositoryService) deleteRepository(ctx context.Context, tx *Tx, delete *api.RepositoryDelete) error {
+ // Updates the project workflow_type to "UI"
+ workflowType := api.UI_WORKFLOW
+ projectPatch := api.ProjectPatch{
+ ID: delete.ProjectId,
+ UpdaterId: delete.DeleterId,
+ WorkflowType: &workflowType,
+ }
+ if _, err := s.ProjectService.PatchProjectWithTx(ctx, tx.Tx, &projectPatch); err != nil {
+ return err
+ }
+
// Remove row from database.
- result, err := tx.ExecContext(ctx, `DELETE FROM repo WHERE id = ?`, delete.ID)
+ result, err := tx.ExecContext(ctx, `DELETE FROM repo WHERE project_id = ?`, delete.ProjectId)
if err != nil {
return FormatError(err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
- return &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("repository ID not found: %d", delete.ID)}
+ return &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("repository not found for project ID: %d", delete.ProjectId)}
}
return nil
diff --git a/frontend/src/components/ProjectVersionControlPanel.vue b/frontend/src/components/ProjectVersionControlPanel.vue
index 45bffd6a4a..0fc5dead74 100644
--- a/frontend/src/components/ProjectVersionControlPanel.vue
+++ b/frontend/src/components/ProjectVersionControlPanel.vue
@@ -81,7 +81,7 @@
</template>
</template>
<template v-else-if="project.workflowType == 'VCS'">
- <RepositoryDetail :repository="repository" />
+ <RepositoryDetail :project="project" :repository="repository" />
</template>
</template>
</template>
diff --git a/frontend/src/components/RepositoryDetail.vue b/frontend/src/components/RepositoryDetail.vue
index bf9269e0c4..9e7d99df9b 100644
--- a/frontend/src/components/RepositoryDetail.vue
+++ b/frontend/src/components/RepositoryDetail.vue
@@ -1,28 +1,83 @@
<template>
+ <div class="text-lg leading-6 font-medium text-main">
+ Version control is enabled
+ </div>
+ <div class="mt-1 textinfolabel">
+ Database migration scripts are stored in
+ <a class="normal-link" :href="repository.webURL" target="_blank">{{
+ repository.fullPath
+ }}</a
+ >. To make schema changes, a developer would create a migration script and
+ submit for review there. After the script is approved and merged into the
+ branch matching pattern
+ <span class="text-main">{{ repository.branchFilter }}</span
+ >, Bytebase will automatically kicks off the task to apply the new schema
+ change.
+ </div>
<RepositoryForm
+ class="mt-4"
:vcsType="repository.vcs.type"
:vcsName="repository.vcs.name"
:repositoryInfo="repositoryInfo"
:repositoryConfig="repositoryConfig"
/>
+ <div class="mt-4 pt-4 flex border-t justify-between">
+ <BBButtonConfirm
+ :style="'RESTORE'"
+ :buttonText="'Restore to UI workflow'"
+ :requireConfirm="true"
+ :okText="'Restore'"
+ :confirmTitle="'Restore to UI workflow?'"
+ :confirmDescription="'When using the UI workflow, the developer submits a SQL review ticket directly from Bytebase and waits for the assigned DBA or peer developer to review. Bytebase applies the SQL change after review approved.'"
+ @confirm="restoreToUIWorkflowType"
+ />
+ <div>
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ @click.prevent="cancel"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
+ :disabled="!allowUpdate"
+ @click.prevent="doUpdate"
+ >
+ Update
+ </button>
+ </div>
+ </div>
</template>
<script lang="ts">
import { computed, PropType } from "vue";
import { useRouter } from "vue-router";
import RepositoryForm from "./RepositoryForm.vue";
-import { Repository, ExternalRepositoryInfo, RepositoryConfig } from "../types";
+import {
+ Repository,
+ ExternalRepositoryInfo,
+ RepositoryConfig,
+ Project,
+} from "../types";
+import { useStore } from "vuex";
export default {
name: "RepositoryDetail",
components: { RepositoryForm },
props: {
+ project: {
+ required: true,
+ type: Object as PropType<Project>,
+ },
repository: {
required: true,
type: Object as PropType<Repository>,
},
},
setup(props, ctx) {
+ const store = useStore();
const router = useRouter();
const repositoryInfo = computed((): ExternalRepositoryInfo => {
@@ -42,7 +97,29 @@ export default {
};
});
- return { repositoryInfo, repositoryConfig };
+ const allowUpdate = computed(() => {
+ return true;
+ });
+
+ const restoreToUIWorkflowType = () => {
+ store.dispatch(
+ "repository/deleteRepositoryByProjectId",
+ props.project.id
+ );
+ };
+
+ const doUpdate = () => {};
+
+ const cancel = () => {};
+
+ return {
+ repositoryInfo,
+ repositoryConfig,
+ allowUpdate,
+ restoreToUIWorkflowType,
+ doUpdate,
+ cancel,
+ };
},
};
</script>
diff --git a/frontend/src/store/modules/repository.ts b/frontend/src/store/modules/repository.ts
index 58e972e6df..dd1d253b24 100644
--- a/frontend/src/store/modules/repository.ts
+++ b/frontend/src/store/modules/repository.ts
@@ -140,6 +140,19 @@ const actions = {
return unknown("REPOSITORY") as Repository;
},
+
+ async deleteRepositoryByProjectId(
+ { dispatch, commit }: any,
+ projectId: ProjectId
+ ) {
+ await axios.delete(`/api/project/${projectId}/repository`);
+ commit("deleteRepositoryByProjectId", projectId);
+
+ // Refetch the project as the project workflow type has been updated to "UI"
+ dispatch("project/fetchProjectById", projectId, {
+ root: true,
+ });
+ },
};
const mutations = {
@@ -168,6 +181,10 @@ const mutations = {
) {
state.repositoryByProjectId.set(projectId, repository);
},
+
+ deleteRepositoryByProjectId(state: RepositoryState, projectId: ProjectId) {
+ state.repositoryByProjectId.delete(projectId);
+ },
};
export default {