Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: split data model object for api.Repository (#813)
Yilong Lifd470cb140dd
diff --git a/api/project.go b/api/project.goindex 3d4f4bc9b6..fbff701adb 100644--- a/api/project.go+++ b/api/project.go@@ -87,7 +87,7 @@ type ProjectRaw struct {}// ToProject creates an instance of Project based on the ProjectRaw.-// This is intended to be used when we need to compose a Project relationship.+// This is intended to be called when we need to compose a Project relationship.func (raw *ProjectRaw) ToProject() *Project {return &Project{ID: raw.ID,diff --git a/api/repository.go b/api/repository.goindex e0c99d7ee7..ebeb17e8ed 100644--- a/api/repository.go+++ b/api/repository.go@@ -5,6 +5,71 @@ import ("encoding/json")+// RepositoryRaw is the store model for a Repository.+// Fields have exactly the same meanings as Repository.+type RepositoryRaw struct {+ ID int++ // Standard fields+ CreatorID int+ CreatedTs int64+ UpdaterID int+ UpdatedTs int64++ // Related fields+ VCSID int+ ProjectID int++ // Domain specific fields+ Name string+ FullPath string+ WebURL string+ BranchFilter string+ BaseDirectory string+ FilePathTemplate string+ SchemaPathTemplate string+ ExternalID string+ ExternalWebhookID string+ WebhookURLHost string+ WebhookEndpointID string+ WebhookSecretToken string+ AccessToken string+ ExpiresTs int64+ RefreshToken string+}++// ToRepository creates an instance of Repository based on the RepositoryRaw.+// This is intended to be called when we need to compose a Repository relationship.+func (raw *RepositoryRaw) ToRepository() *Repository {+ return &Repository{+ ID: raw.ID,++ CreatorID: raw.CreatorID,+ CreatedTs: raw.CreatedTs,+ UpdaterID: raw.UpdaterID,+ UpdatedTs: raw.UpdatedTs,++ VCSID: raw.VCSID,+ ProjectID: raw.ProjectID,++ Name: raw.Name,+ FullPath: raw.FullPath,+ WebURL: raw.WebURL,+ BranchFilter: raw.BranchFilter,+ BaseDirectory: raw.BaseDirectory,+ FilePathTemplate: raw.FilePathTemplate,+ SchemaPathTemplate: raw.SchemaPathTemplate,+ ExternalID: raw.ExternalID,+ ExternalWebhookID: raw.ExternalWebhookID,+ WebhookURLHost: raw.WebhookURLHost,+ WebhookEndpointID: raw.WebhookEndpointID,+ WebhookSecretToken: raw.WebhookSecretToken,+ AccessToken: raw.AccessToken,+ ExpiresTs: raw.ExpiresTs,+ RefreshToken: raw.RefreshToken,+ }+}+// Repository is the API message for a repository.type Repository struct {ID int `jsonapi:"primary,repository"`@@ -128,9 +193,9 @@ type RepositoryDelete struct {// RepositoryService is the service for repositories.type RepositoryService interface {- CreateRepository(ctx context.Context, create *RepositoryCreate) (*Repository, error)- FindRepositoryList(ctx context.Context, find *RepositoryFind) ([]*Repository, error)- FindRepository(ctx context.Context, find *RepositoryFind) (*Repository, error)- PatchRepository(ctx context.Context, patch *RepositoryPatch) (*Repository, error)+ CreateRepository(ctx context.Context, create *RepositoryCreate) (*RepositoryRaw, error)+ FindRepositoryList(ctx context.Context, find *RepositoryFind) ([]*RepositoryRaw, error)+ FindRepository(ctx context.Context, find *RepositoryFind) (*RepositoryRaw, error)+ PatchRepository(ctx context.Context, patch *RepositoryPatch) (*RepositoryRaw, error)DeleteRepository(ctx context.Context, delete *RepositoryDelete) error}diff --git a/api/vcs.go b/api/vcs.goindex 6ab9d29733..01c29dd5d1 100644--- a/api/vcs.go+++ b/api/vcs.go@@ -28,7 +28,7 @@ type VCSRaw struct {}// ToVCS creates an instance of VCS based on the VCSRaw.-// This is intended to be used when we need to compose a VCS relationship.+// This is intended to be called when we need to compose a VCS relationship.func (raw *VCSRaw) ToVCS() *VCS {return &VCS{ID: raw.ID,diff --git a/server/project.go b/server/project.goindex 4d595d391c..45d4a4d930 100644--- a/server/project.go+++ b/server/project.go@@ -261,7 +261,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// Remove enclosing /repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")- repository, err := s.RepositoryService.CreateRepository(ctx, repositoryCreate)+ repoRaw, err := s.RepositoryService.CreateRepository(ctx, repositoryCreate)if err != nil {if common.ErrorCode(err) == common.Conflict {return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project %d has already linked repository", repositoryCreate.ProjectID))@@ -269,12 +269,13 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)}- if err := s.composeRepositoryRelationship(ctx, repository); err != nil {+ repo, err := s.composeRepositoryRelationship(ctx, repoRaw)+ if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create project").SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, repo); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)}return nil@@ -290,27 +291,30 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)}- repositoryFind := &api.RepositoryFind{+ repoFind := &api.RepositoryFind{ProjectID: &projectID,}- list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)+ repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repoFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectID)).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), projectID)).SetInternal(err)+ if len(repoRawList) > 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoRawList), projectID)).SetInternal(err)}- for _, repository := range list {- if err := s.composeRepositoryRelationship(ctx, repository); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)+ repoList := make([]*api.Repository, 0, len(repoRawList))+ for _, repoRaw := range repoRawList {+ repo, err := s.composeRepositoryRelationship(ctx, repoRaw)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repoRaw.Name)).SetInternal(err)}+ repoList = append(repoList, repo)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, repoList); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectID)).SetInternal(err)}return nil@@ -323,10 +327,10 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)}- repositoryPatch := &api.RepositoryPatch{+ repoPatch := &api.RepositoryPatch{UpdaterID: c.Get(getPrincipalIDContextKey()).(int),}- if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryPatch); err != nil {+ if err := jsonapi.UnmarshalPayload(c.Request().Body, repoPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch linked repository request").SetInternal(err)}project, err := s.composeProjectByID(ctx, projectID)@@ -337,56 +341,56 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)}- if repositoryPatch.FilePathTemplate != nil {- if err := api.ValidateRepositoryFilePathTemplate(*repositoryPatch.FilePathTemplate, project.TenantMode); err != nil {+ if repoPatch.FilePathTemplate != nil {+ if err := api.ValidateRepositoryFilePathTemplate(*repoPatch.FilePathTemplate, project.TenantMode); err != nil {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted patch linked repository request: %s", err.Error()))}}- if repositoryPatch.SchemaPathTemplate != nil {- if err := api.ValidateRepositorySchemaPathTemplate(*repositoryPatch.SchemaPathTemplate, project.TenantMode); err != nil {+ if repoPatch.SchemaPathTemplate != nil {+ if err := api.ValidateRepositorySchemaPathTemplate(*repoPatch.SchemaPathTemplate, project.TenantMode); 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, "/")- repositoryPatch.BaseDirectory = &baseDir+ if repoPatch.BaseDirectory != nil {+ baseDir := strings.Trim(*repoPatch.BaseDirectory, "/")+ repoPatch.BaseDirectory = &baseDir}- repositoryFind := &api.RepositoryFind{+ repoFind := &api.RepositoryFind{ProjectID: &projectID,}- list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)+ repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repoFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectID)).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), projectID)).SetInternal(err)- } else if len(list) == 0 {+ if len(repoRawList) > 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoRawList), projectID)).SetInternal(err)+ } else if len(repoRawList) == 0 {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectID))}- repository := list[0]- repositoryPatch.ID = repository.ID- updatedRepository, err := s.RepositoryService.PatchRepository(ctx, repositoryPatch)+ repo := repoRawList[0]+ repoPatch.ID = repo.ID+ updatedRepoRaw, err := s.RepositoryService.PatchRepository(ctx, repoPatch)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectID)).SetInternal(err)}- if repositoryPatch.BranchFilter != nil {+ if repoPatch.BranchFilter != nil {vcsFind := &api.VCSFind{- ID: &repository.VCSID,+ ID: &repo.VCSID,}vcs, err := s.VCSService.FindVCS(ctx, vcsFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectID)).SetInternal(err)}if vcs == nil {- err := fmt.Errorf("failed to find VCS configuration for ID: %d", repository.VCSID)+ err := fmt.Errorf("failed to find VCS configuration for ID: %d", repo.VCSID)return echo.NewHTTPError(http.StatusInternalServerError, err.Error()).SetInternal(err)}// Update the webhook after we successfully update the repository.@@ -396,12 +400,12 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {switch vcs.Type {case "GITLAB_SELF_HOST":webhookPut := gitlab.WebhookPut{- URL: fmt.Sprintf("%s:%d/%s/%s", s.host, s.port, gitLabWebhookPath, updatedRepository.WebhookEndpointID),- PushEventsBranchFilter: *repositoryPatch.BranchFilter,+ URL: fmt.Sprintf("%s:%d/%s/%s", s.host, s.port, gitLabWebhookPath, updatedRepoRaw.WebhookEndpointID),+ PushEventsBranchFilter: *repoPatch.BranchFilter,}webhookPatchPayload, err = json.Marshal(webhookPut)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal put request for updating webhook %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal put request for updating webhook %s for project ID: %v", repo.ExternalWebhookID, projectID)).SetInternal(err)}}@@ -411,27 +415,28 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// Need to get ApplicationID, Secret from vcs instead of repository.vcs since the latter is not composed.ClientID: vcs.ApplicationID,ClientSecret: vcs.Secret,- AccessToken: repository.AccessToken,- RefreshToken: repository.RefreshToken,- Refresher: s.refreshToken(ctx, repository.ID),+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: s.refreshToken(ctx, repo.ID),},vcs.InstanceURL,- repository.ExternalID,- repository.ExternalWebhookID,+ repo.ExternalID,+ repo.ExternalWebhookID,webhookPatchPayload,)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update webhook ID %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update webhook ID %s for project ID: %v", repo.ExternalWebhookID, projectID)).SetInternal(err)}}- if err := s.composeRepositoryRelationship(ctx, updatedRepository); err != nil {+ updatedRepo, err := s.composeRepositoryRelationship(ctx, updatedRepoRaw)+ if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to updating repository for project").SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, updatedRepository); err != nil {+ 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)}return nildiff --git a/server/repository.go b/server/repository.goindex e834c21655..6785e04360 100644--- a/server/repository.go+++ b/server/repository.go@@ -7,32 +7,36 @@ import ("github.com/bytebase/bytebase/api")-func (s *Server) composeRepositoryRelationship(ctx context.Context, repository *api.Repository) error {- var err error+func (s *Server) composeRepositoryRelationship(ctx context.Context, raw *api.RepositoryRaw) (*api.Repository, error) {+ repository := raw.ToRepository()- repository.Creator, err = s.composePrincipalByID(ctx, repository.CreatorID)+ creator, err := s.composePrincipalByID(ctx, repository.CreatorID)if err != nil {- return err+ return nil, err}+ repository.Creator = creator- repository.Updater, err = s.composePrincipalByID(ctx, repository.UpdaterID)+ updater, err := s.composePrincipalByID(ctx, repository.UpdaterID)if err != nil {- return err+ return nil, err}+ repository.Updater = updater- repository.VCS, err = s.composeVCSByID(ctx, repository.VCSID)+ vcs, err := s.composeVCSByID(ctx, repository.VCSID)if err != nil {- return err+ return nil, err}// We should always expect VCS to exist when ID isn't the default zero.- if repository.VCSID > 0 && repository.VCS == nil {- return fmt.Errorf("VCS not found for ID: %v", repository.VCSID)+ if repository.VCSID > 0 && vcs == nil {+ return nil, fmt.Errorf("VCS not found for ID: %v", repository.VCSID)}+ repository.VCS = vcs- repository.Project, err = s.composeProjectByID(ctx, repository.ProjectID)+ project, err := s.composeProjectByID(ctx, repository.ProjectID)if err != nil {- return err+ return nil, err}+ repository.Project = project- return nil+ return repository, nil}diff --git a/server/task_executor.go b/server/task_executor.goindex 2c1558cfd1..e4868bf8ec 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -12,7 +12,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"- "github.com/bytebase/bytebase/plugin/vcs"+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs""go.uber.org/zap")@@ -34,7 +34,7 @@ func defaultMigrationVersionFromTaskID() string {return time.Now().Format("20060102150405")}-func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcs.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {+func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) ( /*terminated*/ bool /*result*/, *api.TaskRunResultPayload, error) {if task.Database == nil {msg := "missing database when updating schema"if migrationType == db.Data {@@ -44,7 +44,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.}databaseName := task.Database.Name- var repository *api.Repository+ var repoRawOutter *api.RepositoryRawmi := &db.MigrationInfo{ReleaseVersion: server.version,Type: migrationType,@@ -67,20 +67,21 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.mi.Namespace = databaseNamemi.Description = task.Name} else {- repositoryFind := &api.RepositoryFind{+ repoFind := &api.RepositoryFind{ProjectID: &task.Database.ProjectID,}- repository, err = server.RepositoryService.FindRepository(ctx, repositoryFind)+ repoRawInner, err := server.RepositoryService.FindRepository(ctx, repoFind)if err != nil {return true, nil, fmt.Errorf("failed to find linked repository for database %q", databaseName)}- if repository == nil {+ if repoRawInner == nil {return true, nil, fmt.Errorf("repository not found with project ID %v", task.Database.ProjectID)}+ repoRawOutter = repoRawInnermi, err = db.ParseMigrationInfo(vcsPushEvent.FileCommit.Added,- filepath.Join(vcsPushEvent.BaseDirectory, repository.FilePathTemplate),+ filepath.Join(vcsPushEvent.BaseDirectory, repoRawOutter.FilePathTemplate),)// This should not happen normally as we already check this when creating the issue. Just in case.if err != nil {@@ -162,7 +163,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.}// If VCS based and schema path template is specified, then we will write back the latest schema file after migration.- writeBack := (vcsPushEvent != nil) && (repository.SchemaPathTemplate != "")+ writeBack := (vcsPushEvent != nil) && (repoRawOutter.SchemaPathTemplate != "")// For tenant mode project, we will only write back latest schema file on the last task.if writeBack && issue != nil {project, err := server.composeProjectByID(ctx, task.Database.ProjectID)@@ -186,20 +187,23 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.}if writeBack {- latestSchemaFile := filepath.Join(repository.BaseDirectory, repository.SchemaPathTemplate)+ latestSchemaFile := filepath.Join(repoRawOutter.BaseDirectory, repoRawOutter.SchemaPathTemplate)latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", mi.Database)- repository.VCS, err = server.composeVCSByID(ctx, repository.VCSID)+ // TODO(dragonly): revisit the usage of a not-fully-composed Repository here+ repo := repoRawOutter.ToRepository()+ vcs, err := server.composeVCSByID(ctx, repoRawOutter.VCSID)if err != nil {return true, nil, fmt.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, databaseName)}- if repository.VCS == nil {- return true, nil, fmt.Errorf("VCS ID not found: %d", repository.VCSID)+ if vcs == nil {+ return true, nil, fmt.Errorf("VCS ID not found: %d", repoRawOutter.VCSID)}+ repo.VCS = vcs// Writes back the latest schema file to the same branch as the push event.- branch, err := vcs.Branch(vcsPushEvent.Ref)+ branch, err := vcsPlugin.Branch(vcsPushEvent.Ref)if err != nil {return true, nil, err}@@ -209,7 +213,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.bytebaseURL = fmt.Sprintf("%s:%d/issue/%s?stage=%d", server.frontendHost, server.frontendPort, api.IssueSlug(issue), task.StageID)}- commitID, err := writeBackLatestSchema(ctx, server, repository, vcsPushEvent, mi, branch, latestSchemaFile, schema, bytebaseURL)+ commitID, err := writeBackLatestSchema(ctx, server, repo, vcsPushEvent, mi, branch, latestSchemaFile, schema, bytebaseURL)if err != nil {return true, nil, err}@@ -218,7 +222,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.{payload, err := json.Marshal(api.ActivityPipelineTaskFileCommitPayload{TaskID: task.ID,- VCSInstanceURL: repository.VCS.InstanceURL,+ VCSInstanceURL: repo.VCS.InstanceURL,RepositoryFullPath: vcsPushEvent.RepositoryFullPath,Branch: branch,FilePath: latestSchemaFile,@@ -227,7 +231,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.if err != nil {l.Error("Failed to marshal file commit activity after writing back the latest schema",zap.Int("task_id", task.ID),- zap.String("repository", repository.WebURL),+ zap.String("repository", repoRawOutter.WebURL),zap.String("file_path", latestSchemaFile),zap.Error(err),)@@ -253,7 +257,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.if err != nil {l.Error("Failed to create file commit activity after writing back the latest schema",zap.Int("task_id", task.ID),- zap.String("repository", repository.WebURL),+ zap.String("repository", repoRawOutter.WebURL),zap.String("file_path", latestSchemaFile),zap.Error(err),)@@ -275,8 +279,8 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.// 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 *vcs.PushEvent, mi *db.MigrationInfo, branch string, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {- schemaFileMeta, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).ReadFileMeta(+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) {+ schemaFileMeta, err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{Logger: server.l}).ReadFileMeta(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -303,7 +307,7 @@ 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 BTYEBASE"+ commitBody := "THIS COMMIT IS AUTO-GENERATED BY BYTEBASE"if bytebaseURL != "" {commitBody += "\n\n" + bytebaseURL}@@ -313,13 +317,13 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.pushEvent.FileCommit.Message,)- schemaFileCommit := vcs.FileCommitCreate{+ schemaFileCommit := vcsPlugin.FileCommitCreate{Branch: branch,CommitMessage: fmt.Sprintf("%s\n\n%s", commitTitle, commitBody),Content: schema,}if createSchemaFile {- err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).CreateFile(+ err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{Logger: server.l}).CreateFile(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -339,7 +343,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.}} else {schemaFileCommit.LastCommitID = schemaFileMeta.LastCommitID- err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).OverwriteFile(+ err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{Logger: server.l}).OverwriteFile(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -359,7 +363,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.}// VCS such as GitLab API doesn't return the commit on write, so we have to call ReadFileMeta again- schemaFileMeta, err = vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).ReadFileMeta(+ schemaFileMeta, err = vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{Logger: server.l}).ReadFileMeta(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex fdde80129c..850fcb7bf6 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -29,7 +29,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serveif !ok {panicErr = fmt.Errorf("%v", r)}- exec.l.Error("SchemaUpdateTaskExecutor PANIC RECOVER", zap.Error(panicErr))+ exec.l.Error("SchemaUpdateTaskExecutor PANIC RECOVER", zap.Error(panicErr), zap.Stack("stack"))terminated = trueerr = fmt.Errorf("encounter internal error when executing sql")}diff --git a/server/vcs.go b/server/vcs.goindex 0f4f05da98..2cbf5921f7 100644--- a/server/vcs.go+++ b/server/vcs.go@@ -155,19 +155,22 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {repositoryFind := &api.RepositoryFind{VCSID: &id,}- list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)+ repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for vcs ID: %v", id)).SetInternal(err)}- for _, repository := range list {- if err := s.composeRepositoryRelationship(ctx, repository); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.ID)).SetInternal(err)+ repoList := make([]*api.Repository, 0, len(repoRawList))+ for _, repoRaw := range repoRawList {+ repo, err := s.composeRepositoryRelationship(ctx, repoRaw)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repoRaw.ID)).SetInternal(err)}+ repoList = append(repoList, repo)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, repoList); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal repository list response for vcs ID: %v", id)).SetInternal(err)}return nildiff --git a/server/webhook.go b/server/webhook.goindex deedf4b0cd..44095439f3 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -48,35 +48,36 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {repositoryFind := &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID,}- repository, err := s.RepositoryService.FindRepository(ctx, repositoryFind)+ repoRaw, err := s.RepositoryService.FindRepository(ctx, repositoryFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)}- if repository == nil {+ if repoRaw == nil {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Endpoint not found: %v", webhookEndpointID))}- if err := s.composeRepositoryRelationship(ctx, repository); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)+ repo, err := s.composeRepositoryRelationship(ctx, repoRaw)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repoRaw.Name)).SetInternal(err)}- if repository.VCS == nil {- err := fmt.Errorf("VCS not found for ID: %v", repository.VCSID)+ if repo.VCS == nil {+ err := fmt.Errorf("VCS not found for ID: %v", repo.VCSID)return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)}- if c.Request().Header.Get("X-Gitlab-Token") != repository.WebhookSecretToken {+ if c.Request().Header.Get("X-Gitlab-Token") != repo.WebhookSecretToken {return echo.NewHTTPError(http.StatusBadRequest, "Secret token mismatch")}- if strconv.Itoa(pushEvent.Project.ID) != repository.ExternalID {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %d, want %s", pushEvent.Project.ID, repository.ExternalID))+ if strconv.Itoa(pushEvent.Project.ID) != repo.ExternalID {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %d, want %s", pushEvent.Project.ID, repo.ExternalID))}createdMessageList := []string{}for _, commit := range pushEvent.CommitList {for _, added := range commit.AddedList {- if !strings.HasPrefix(added, repository.BaseDirectory) {- s.l.Debug("Ignored committed file, not under base directory.", zap.String("file", added), zap.String("base_directory", repository.BaseDirectory))+ if !strings.HasPrefix(added, repo.BaseDirectory) {+ s.l.Debug("Ignored committed file, not under base directory.", zap.String("file", added), zap.String("base_directory", repo.BaseDirectory))continue}@@ -86,13 +87,13 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}// Ignored the schema file we auto generated to the repository.- if isSkipGeneratedSchemaFile(repository, added, s.l) {+ if isSkipGeneratedSchemaFile(repo, added, s.l) {continue}vcsPushEvent := vcs.PushEvent{- VCSType: repository.VCS.Type,- BaseDirectory: repository.BaseDirectory,+ VCSType: repo.VCS.Type,+ BaseDirectory: repo.BaseDirectory,Ref: pushEvent.Ref,RepositoryID: strconv.Itoa(pushEvent.Project.ID),RepositoryURL: pushEvent.Project.WebURL,@@ -122,7 +123,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {activityCreate := &api.ActivityCreate{CreatorID: api.SystemBotID,- ContainerID: repository.ProjectID,+ ContainerID: repo.ProjectID,Type: api.ActivityProjectRepositoryPush,Level: api.ActivityWarn,Comment: fmt.Sprintf("Ignored committed file %q, %s.", added, err.Error()),@@ -134,7 +135,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}}- mi, err := db.ParseMigrationInfo(added, filepath.Join(repository.BaseDirectory, repository.FilePathTemplate))+ mi, err := db.ParseMigrationInfo(added, filepath.Join(repo.BaseDirectory, repo.FilePathTemplate))if err != nil {createIgnoredFileActivity(err)continue@@ -144,14 +145,14 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {content, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).ReadFile(ctx,common.OauthContext{- ClientID: repository.VCS.ApplicationID,- ClientSecret: repository.VCS.Secret,- AccessToken: repository.AccessToken,- RefreshToken: repository.RefreshToken,- Refresher: s.refreshToken(ctx, repository.ID),+ ClientID: repo.VCS.ApplicationID,+ ClientSecret: repo.VCS.Secret,+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: s.refreshToken(ctx, repo.ID),},- repository.VCS.InstanceURL,- repository.ExternalID,+ repo.VCS.InstanceURL,+ repo.ExternalID,added,commit.ID,)@@ -162,13 +163,13 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {// Create schema update issue.var createContext string- if repository.Project.TenantMode == api.TenantModeTenant {+ if repo.Project.TenantMode == api.TenantModeTenant {if !s.feature(api.FeatureMultiTenancy) {return echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())}- createContext, err = s.createTenantSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, content)+ createContext, err = s.createTenantSchemaUpdateIssue(ctx, repo, mi, vcsPushEvent, commit, added, content)} else {- createContext, err = s.createSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, content)+ createContext, err = s.createSchemaUpdateIssue(ctx, repo, mi, vcsPushEvent, commit, added, content)}if err != nil {createIgnoredFileActivity(err)@@ -180,7 +181,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {issueType = api.IssueDatabaseDataUpdate}issueCreate := &api.IssueCreate{- ProjectID: repository.ProjectID,+ ProjectID: repo.ProjectID,Name: commit.Title,Type: issueType,Description: commit.Message,@@ -210,7 +211,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {activityCreate := &api.ActivityCreate{CreatorID: api.SystemBotID,- ContainerID: repository.ProjectID,+ ContainerID: repo.ProjectID,Type: api.ActivityProjectRepositoryPush,Level: api.ActivityInfo,Comment: fmt.Sprintf("Created issue %q.", issue.Name),diff --git a/store/repository.go b/store/repository.goindex 2dc090d6bb..c4f752e8b7 100644--- a/store/repository.go+++ b/store/repository.go@@ -29,7 +29,7 @@ func NewRepositoryService(logger *zap.Logger, db *DB, projectService api.Project}// CreateRepository creates a new repository.-func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.RepositoryCreate) (*api.Repository, error) {+func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.RepositoryCreate) (*api.RepositoryRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -49,7 +49,7 @@ func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.Re}// FindRepositoryList retrieves a list of repositories based on find.-func (s *RepositoryService) FindRepositoryList(ctx context.Context, find *api.RepositoryFind) ([]*api.Repository, error) {+func (s *RepositoryService) FindRepositoryList(ctx context.Context, find *api.RepositoryFind) ([]*api.RepositoryRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -66,7 +66,7 @@ func (s *RepositoryService) FindRepositoryList(ctx context.Context, find *api.Re// FindRepository retrieves a single repository based on find.// Returns ECONFLICT if finding more than 1 matching records.-func (s *RepositoryService) FindRepository(ctx context.Context, find *api.RepositoryFind) (*api.Repository, error) {+func (s *RepositoryService) FindRepository(ctx context.Context, find *api.RepositoryFind) (*api.RepositoryRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -88,7 +88,7 @@ func (s *RepositoryService) FindRepository(ctx context.Context, find *api.Reposi// PatchRepository updates an existing repository by ID.// Returns ENOTFOUND if repository does not exist.-func (s *RepositoryService) PatchRepository(ctx context.Context, patch *api.RepositoryPatch) (*api.Repository, error) {+func (s *RepositoryService) PatchRepository(ctx context.Context, patch *api.RepositoryPatch) (*api.RepositoryRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -127,7 +127,7 @@ func (s *RepositoryService) DeleteRepository(ctx context.Context, delete *api.Re}// createRepository creates a new repository.-func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, create *api.RepositoryCreate) (*api.Repository, error) {+func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, create *api.RepositoryCreate) (*api.RepositoryRaw, error) {// Updates the project workflow_type to "VCS"workflowType := api.VCSWorkflowprojectPatch := api.ProjectPatch{@@ -192,7 +192,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, crdefer row.Close()row.Next()- var repository api.Repository+ var repository api.RepositoryRawif err := row.Scan(&repository.ID,&repository.CreatorID,@@ -223,7 +223,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, crreturn &repository, nil}-func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFind) ([]*api.Repository, error) {+func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFind) ([]*api.RepositoryRaw, error) {// Build WHERE clause.where, args := []string{"1 = 1"}, []interface{}{}if v := find.ID; v != nil {@@ -273,9 +273,9 @@ func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFindefer rows.Close()// Iterate over result set and deserialize rows into list.- list := make([]*api.Repository, 0)+ list := make([]*api.RepositoryRaw, 0)for rows.Next() {- var repository api.Repository+ var repository api.RepositoryRawif err := rows.Scan(&repository.ID,&repository.CreatorID,@@ -313,7 +313,7 @@ func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFin}// patchRepository updates a repository by ID. Returns the new state of the repository after update.-func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch) (*api.Repository, error) {+func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch) (*api.RepositoryRaw, error) {// Build UPDATE clause.set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}if v := patch.BranchFilter; v != nil {@@ -355,7 +355,7 @@ func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatchdefer row.Close()if row.Next() {- var repository api.Repository+ var repository api.RepositoryRawif err := row.Scan(&repository.ID,&repository.CreatorID,