Skip to content

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

refactor: decouple api/service/store packages for Repository (#1189)

Yilong Lid7200c927ed7
diff --git a/api/repository.go b/api/repository.go
index e88161c53c..95f431dbf2 100644
--- a/api/repository.go
+++ b/api/repository.go
@@ -1,77 +1,9 @@
package api
import (
- "context"
"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
- SheetPathTemplate 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,
- SheetPathTemplate: raw.SheetPathTemplate,
- 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"`
@@ -196,12 +128,3 @@ type RepositoryDelete struct {
// Value is assigned from the jwt subject field passed by the client.
DeleterID int
}
-
-// RepositoryService is the service for repositories.
-type RepositoryService interface {
- 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/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 88828187f3..137c575959 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -461,7 +461,6 @@ func (m *Main) Run(ctx context.Context) error {
s.ColumnService = store.NewColumnService(m.l, db)
s.ViewService = store.NewViewService(m.l, db)
s.IndexService = store.NewIndexService(m.l, db)
- s.RepositoryService = store.NewRepositoryService(m.l, db, storeInstance)
s.DeploymentConfigService = store.NewDeploymentConfigService(m.l, db)
s.SheetService = store.NewSheetService(m.l, db)
diff --git a/server/project.go b/server/project.go
index bb6c4f5d9c..7f05e8a741 100644
--- a/server/project.go
+++ b/server/project.go
@@ -252,7 +252,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// Remove enclosing /
repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")
- repoRaw, err := s.RepositoryService.CreateRepository(ctx, repositoryCreate)
+ repository, err := s.store.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))
@@ -260,13 +260,8 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)
}
- 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, repo); err != nil {
+ 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
@@ -285,23 +280,14 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repoFind := &api.RepositoryFind{
ProjectID: &projectID,
}
- repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repoFind)
+ repoList, err := s.store.FindRepository(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(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)
- }
-
- var repoList []*api.Repository
- 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)
+ if len(repoList) > 1 {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -353,21 +339,21 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repoFind := &api.RepositoryFind{
ProjectID: &projectID,
}
- repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repoFind)
+ repoList, err := s.store.FindRepository(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(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 {
+ if len(repoList) > 1 {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)
+ } else if len(repoList) == 0 {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectID))
}
- repo := repoRawList[0]
+ repo := repoList[0]
repoPatch.ID = repo.ID
- updatedRepoRaw, err := s.RepositoryService.PatchRepository(ctx, repoPatch)
+ 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)
}
@@ -387,7 +373,7 @@ 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, updatedRepoRaw.WebhookEndpointID),
+ URL: fmt.Sprintf("%s:%d/%s/%s", s.host, s.port, gitLabWebhookPath, updatedRepo.WebhookEndpointID),
PushEventsBranchFilter: *repoPatch.BranchFilter,
}
webhookPatchPayload, err = json.Marshal(webhookPut)
@@ -417,11 +403,6 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
}
- 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, updatedRepo); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectID)).SetInternal(err)
@@ -440,19 +421,19 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
ProjectID: &projectID,
}
- repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
+ repoList, err := s.store.FindRepository(ctx, repositoryFind)
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(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 {
+ if len(repoList) > 1 {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)
+ } else if len(repoList) == 0 {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectID))
}
- repo := repoRawList[0]
+ repo := repoList[0]
vcs, err := s.store.GetVCSByID(ctx, repo.VCSID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectID)).SetInternal(err)
@@ -465,7 +446,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
ProjectID: projectID,
DeleterID: c.Get(getPrincipalIDContextKey()).(int),
}
- if err := s.RepositoryService.DeleteRepository(ctx, repositoryDelete); err != nil {
+ if err := s.store.DeleteRepository(ctx, repositoryDelete); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectID)).SetInternal(err)
}
@@ -593,7 +574,7 @@ func (s *Server) composeDeploymentConfigRelationship(ctx context.Context, deploy
// refreshToken is a token refresher that stores the latest access token configuration to repository.
func (s *Server) refreshToken(ctx context.Context, repositoryID int) common.TokenRefresher {
return func(token, refreshToken string, expiresTs int64) error {
- if _, err := s.RepositoryService.PatchRepository(ctx, &api.RepositoryPatch{
+ if _, err := s.store.PatchRepository(ctx, &api.RepositoryPatch{
ID: repositoryID,
UpdaterID: api.SystemBotID,
AccessToken: &token,
diff --git a/server/project_member.go b/server/project_member.go
index 8246053378..4979d5fe18 100644
--- a/server/project_member.go
+++ b/server/project_member.go
@@ -36,8 +36,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
}
// fetch project member from VCS
- repoFind := &api.RepositoryFind{ProjectID: &projectID}
- repo, err := s.RepositoryService.FindRepository(ctx, repoFind)
+ repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{ProjectID: &projectID})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch relevant VCS repo, Project ID: %s", c.Param("projectID"))).SetInternal(err)
}
diff --git a/server/repository.go b/server/repository.go
deleted file mode 100644
index 2f01aef6de..0000000000
--- a/server/repository.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package server
-
-import (
- "context"
- "fmt"
-
- "github.com/bytebase/bytebase/api"
-)
-
-func (s *Server) composeRepositoryRelationship(ctx context.Context, raw *api.RepositoryRaw) (*api.Repository, error) {
- repository := raw.ToRepository()
-
- creator, err := s.store.GetPrincipalByID(ctx, repository.CreatorID)
- if err != nil {
- return nil, err
- }
- repository.Creator = creator
-
- updater, err := s.store.GetPrincipalByID(ctx, repository.UpdaterID)
- if err != nil {
- return nil, err
- }
- repository.Updater = updater
-
- vcs, err := s.store.GetVCSByID(ctx, repository.VCSID)
- if err != nil {
- return nil, err
- }
- // We should always expect VCS to exist when ID isn't the default zero.
- if repository.VCSID > 0 && vcs == nil {
- return nil, fmt.Errorf("VCS not found for ID: %v", repository.VCSID)
- }
- repository.VCS = vcs
-
- project, err := s.store.GetProjectByID(ctx, repository.ProjectID)
- if err != nil {
- return nil, err
- }
- repository.Project = project
-
- return repository, nil
-}
diff --git a/server/server.go b/server/server.go
index 09715ed5c1..b58af3dbbb 100644
--- a/server/server.go
+++ b/server/server.go
@@ -43,7 +43,6 @@ type Server struct {
ColumnService api.ColumnService
ViewService api.ViewService
IndexService api.IndexService
- RepositoryService api.RepositoryService
DeploymentConfigService api.DeploymentConfigService
LicenseService enterprise.LicenseService
SheetService api.SheetService
diff --git a/server/sheet.go b/server/sheet.go
index adcb157a33..417006563c 100644
--- a/server/sheet.go
+++ b/server/sheet.go
@@ -91,7 +91,7 @@ func (s *Server) registerSheetRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid workflow type: %s, need %s to enable this function", project.WorkflowType, api.VCSWorkflow))
}
- repo, err := s.RepositoryService.FindRepository(ctx, &api.RepositoryFind{ProjectID: &projectID})
+ repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{ProjectID: &projectID})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find relevant VCS repo, Project ID: %d", projectID)).SetInternal(err)
}
diff --git a/server/task_executor.go b/server/task_executor.go
index cd00da4512..3348f9edc4 100644
--- a/server/task_executor.go
+++ b/server/task_executor.go
@@ -37,7 +37,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
}
databaseName := task.Database.Name
- var repoRawOutter *api.RepositoryRaw
+ var repoOutter *api.Repository
mi := &db.MigrationInfo{
ReleaseVersion: server.version,
Type: migrationType,
@@ -62,18 +62,18 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
repoFind := &api.RepositoryFind{
ProjectID: &task.Database.ProjectID,
}
- repoRawInner, err := server.RepositoryService.FindRepository(ctx, repoFind)
+ repoInner, err := server.store.GetRepository(ctx, repoFind)
if err != nil {
return true, nil, fmt.Errorf("failed to find linked repository for database %q", databaseName)
}
- if repoRawInner == nil {
+ if repoInner == nil {
return true, nil, fmt.Errorf("repository not found with project ID %v", task.Database.ProjectID)
}
- repoRawOutter = repoRawInner
+ repoOutter = repoInner
mi, err = db.ParseMigrationInfo(
vcsPushEvent.FileCommit.Added,
- filepath.Join(vcsPushEvent.BaseDirectory, repoRawOutter.FilePathTemplate),
+ filepath.Join(vcsPushEvent.BaseDirectory, repoOutter.FilePathTemplate),
)
// This should not happen normally as we already check this when creating the issue. Just in case.
if err != nil {
@@ -149,7 +149,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) && (repoRawOutter.SchemaPathTemplate != "")
+ writeBack := (vcsPushEvent != nil) && (repoOutter.SchemaPathTemplate != "")
// For tenant mode project, we will only write back latest schema file on the last task.
project, err := server.store.GetProjectByID(ctx, task.Database.ProjectID)
if err != nil {
@@ -177,18 +177,17 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
if err != nil {
return true, nil, fmt.Errorf("failed to get BaseDatabaseName for instance %q, database %q: %w", task.Instance.Name, task.Database.Name, err)
}
- latestSchemaFile := filepath.Join(repoRawOutter.BaseDirectory, repoRawOutter.SchemaPathTemplate)
+ latestSchemaFile := filepath.Join(repoOutter.BaseDirectory, repoOutter.SchemaPathTemplate)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", dbName)
- // TODO(dragonly): revisit the usage of a not-fully-composed Repository here
- repo := repoRawOutter.ToRepository()
- vcs, err := server.store.GetVCSByID(ctx, repoRawOutter.VCSID)
+ repo := repoOutter
+ vcs, err := server.store.GetVCSByID(ctx, repoOutter.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 vcs == nil {
- return true, nil, fmt.Errorf("VCS ID not found: %d", repoRawOutter.VCSID)
+ return true, nil, fmt.Errorf("VCS ID not found: %d", repoOutter.VCSID)
}
repo.VCS = vcs
@@ -221,7 +220,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", repoRawOutter.WebURL),
+ zap.String("repository", repoOutter.WebURL),
zap.String("file_path", latestSchemaFile),
zap.Error(err),
)
@@ -247,7 +246,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", repoRawOutter.WebURL),
+ zap.String("repository", repoOutter.WebURL),
zap.String("file_path", latestSchemaFile),
zap.Error(err),
)
diff --git a/server/vcs.go b/server/vcs.go
index 6df436ed44..55f5615bf0 100644
--- a/server/vcs.go
+++ b/server/vcs.go
@@ -132,20 +132,11 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
VCSID: &id,
}
- repoRawList, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
+ repoList, err := s.store.FindRepository(ctx, repositoryFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for vcs ID: %v", id)).SetInternal(err)
}
- var repoList []*api.Repository
- 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, repoList); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal repository list response for vcs ID: %v", id)).SetInternal(err)
diff --git a/server/webhook.go b/server/webhook.go
index e40d99b0f2..014d496579 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -45,21 +45,14 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
webhookEndpointID := c.Param("id")
- repositoryFind := &api.RepositoryFind{
- WebhookEndpointID: &webhookEndpointID,
- }
- repoRaw, err := s.RepositoryService.FindRepository(ctx, repositoryFind)
+ repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)
}
- if repoRaw == nil {
+ if repo == nil {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Endpoint not found: %v", webhookEndpointID))
}
- 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 repo.VCS == nil {
err := fmt.Errorf("VCS not found for ID: %v", repo.VCSID)
return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)
diff --git a/store/project.go b/store/project.go
index 299db7bfed..353ce95550 100644
--- a/store/project.go
+++ b/store/project.go
@@ -32,9 +32,9 @@ type projectRaw struct {
RoleProvider api.ProjectRoleProvider
}
-// ToProject creates an instance of Project based on the projectRaw.
+// toProject creates an instance of Project based on the projectRaw.
// This is intended to be called when we need to compose a Project relationship.
-func (raw *projectRaw) ToProject() *api.Project {
+func (raw *projectRaw) toProject() *api.Project {
return &api.Project{
ID: raw.ID,
@@ -119,7 +119,7 @@ func (s *Store) PatchProject(ctx context.Context, patch *api.ProjectPatch) (*api
//
func (s *Store) composeProject(ctx context.Context, raw *projectRaw) (*api.Project, error) {
- project := raw.ToProject()
+ project := raw.toProject()
creator, err := s.GetPrincipalByID(ctx, project.CreatorID)
if err != nil {
diff --git a/store/repository.go b/store/repository.go
index f4844251a7..30e8247dbb 100644
--- a/store/repository.go
+++ b/store/repository.go
@@ -8,35 +8,200 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
- "go.uber.org/zap"
)
-var (
- _ api.RepositoryService = (*RepositoryService)(nil)
-)
+// 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
+ SheetPathTemplate 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() *api.Repository {
+ return &api.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,
+ SheetPathTemplate: raw.SheetPathTemplate,
+ ExternalID: raw.ExternalID,
+ ExternalWebhookID: raw.ExternalWebhookID,
+ WebhookURLHost: raw.WebhookURLHost,
+ WebhookEndpointID: raw.WebhookEndpointID,
+ WebhookSecretToken: raw.WebhookSecretToken,
+ AccessToken: raw.AccessToken,
+ ExpiresTs: raw.ExpiresTs,
+ RefreshToken: raw.RefreshToken,
+ }
+}
+
+// CreateRepository creates an instance of Repository
+func (s *Store) CreateRepository(ctx context.Context, create *api.RepositoryCreate) (*api.Repository, error) {
+ repositoryRaw, err := s.createRepositoryRaw(ctx, create)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create Repository with RepositoryCreate[%+v], error[%w]", create, err)
+ }
+ repository, err := s.composeRepository(ctx, repositoryRaw)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compose Repository with repositoryRaw[%+v], error[%w]", repositoryRaw, err)
+ }
+ return repository, nil
+}
+
+// GetRepository gets an instance of Repository
+func (s *Store) GetRepository(ctx context.Context, find *api.RepositoryFind) (*api.Repository, error) {
+ repositoryRaw, err := s.getRepositoryRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get Repository with RepositoryFind[%+v], error[%w]", find, err)
+ }
+ if repositoryRaw == nil {
+ return nil, nil
+ }
+ repository, err := s.composeRepository(ctx, repositoryRaw)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compose Repository with repositoryRaw[%+v], error[%w]", repositoryRaw, err)
+ }
+ return repository, nil
+}
+
+// FindRepository finds a list of Repository instances
+func (s *Store) FindRepository(ctx context.Context, find *api.RepositoryFind) ([]*api.Repository, error) {
+ repositoryRawList, err := s.findRepositoryRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find Repository list, error[%w]", err)
+ }
+ var repositoryList []*api.Repository
+ for _, raw := range repositoryRawList {
+ repository, err := s.composeRepository(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compose Repository with repositoryRaw[%+v], error[%w]", raw, err)
+ }
+ repositoryList = append(repositoryList, repository)
+ }
+ return repositoryList, nil
+}
+
+// PatchRepository patches an instance of Repository
+func (s *Store) PatchRepository(ctx context.Context, patch *api.RepositoryPatch) (*api.Repository, error) {
+ repositoryRaw, err := s.patchRepositoryRaw(ctx, patch)
+ if err != nil {
+ return nil, fmt.Errorf("failed to patch Repository with RepositoryPatch[%+v], error[%w]", patch, err)
+ }
+ repository, err := s.composeRepository(ctx, repositoryRaw)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compose Repository with repositoryRaw[%+v], error[%w]", repositoryRaw, err)
+ }
+ return repository, nil
+}
+
+// DeleteRepository deletes an existing repository by ID.
+func (s *Store) DeleteRepository(ctx context.Context, delete *api.RepositoryDelete) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return FormatError(err)
+ }
+ defer tx.PTx.Rollback()
+
+ if err := s.deleteRepository(ctx, tx.PTx, delete); err != nil {
+ return FormatError(err)
+ }
-// RepositoryService represents a service for managing repository.
-type RepositoryService struct {
- l *zap.Logger
- db *DB
+ if err := tx.PTx.Commit(); err != nil {
+ return FormatError(err)
+ }
- store *Store
+ return nil
}
-// NewRepositoryService returns a new instance of RepositoryService.
-func NewRepositoryService(logger *zap.Logger, db *DB, store *Store) *RepositoryService {
- return &RepositoryService{l: logger, db: db, store: store}
+//
+// private functions
+//
+
+func (s *Store) composeRepository(ctx context.Context, raw *repositoryRaw) (*api.Repository, error) {
+ repository := raw.toRepository()
+
+ creator, err := s.GetPrincipalByID(ctx, repository.CreatorID)
+ if err != nil {
+ return nil, err
+ }
+ repository.Creator = creator
+
+ updater, err := s.GetPrincipalByID(ctx, repository.UpdaterID)
+ if err != nil {
+ return nil, err
+ }
+ repository.Updater = updater
+
+ vcs, err := s.GetVCSByID(ctx, repository.VCSID)
+ if err != nil {
+ return nil, err
+ }
+ // We should always expect VCS to exist when ID isn't the default zero.
+ if repository.VCSID > 0 && vcs == nil {
+ return nil, fmt.Errorf("VCS not found for ID: %v", repository.VCSID)
+ }
+ repository.VCS = vcs
+
+ project, err := s.GetProjectByID(ctx, repository.ProjectID)
+ if err != nil {
+ return nil, err
+ }
+ repository.Project = project
+
+ return repository, nil
}
-// CreateRepository creates a new repository.
-func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.RepositoryCreate) (*api.RepositoryRaw, error) {
+// createRepositoryRaw creates a new repository.
+func (s *Store) createRepositoryRaw(ctx context.Context, create *api.RepositoryCreate) (*repositoryRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- repository, err := s.createRepository(ctx, tx.PTx, create)
+ repository, err := s.createRepositoryImpl(ctx, tx.PTx, create)
if err != nil {
return nil, err
}
@@ -48,15 +213,15 @@ func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.Re
return repository, nil
}
-// FindRepositoryList retrieves a list of repositories based on find.
-func (s *RepositoryService) FindRepositoryList(ctx context.Context, find *api.RepositoryFind) ([]*api.RepositoryRaw, error) {
+// findRepositoryRaw retrieves a list of repositories based on find.
+func (s *Store) findRepositoryRaw(ctx context.Context, find *api.RepositoryFind) ([]*repositoryRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- list, err := findRepositoryList(ctx, tx.PTx, find, s.db.mode)
+ list, err := findRepositoryImpl(ctx, tx.PTx, find, s.db.mode)
if err != nil {
return nil, err
}
@@ -64,16 +229,16 @@ func (s *RepositoryService) FindRepositoryList(ctx context.Context, find *api.Re
return list, nil
}
-// FindRepository retrieves a single repository based on find.
+// getRepositoryRaw 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.RepositoryRaw, error) {
+func (s *Store) getRepositoryRaw(ctx context.Context, find *api.RepositoryFind) (*repositoryRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- list, err := findRepositoryList(ctx, tx.PTx, find, s.db.mode)
+ list, err := findRepositoryImpl(ctx, tx.PTx, find, s.db.mode)
if err != nil {
return nil, err
}
@@ -86,16 +251,16 @@ func (s *RepositoryService) FindRepository(ctx context.Context, find *api.Reposi
return list[0], nil
}
-// PatchRepository updates an existing repository by ID.
+// patchRepositoryRaw updates an existing repository by ID.
// Returns ENOTFOUND if repository does not exist.
-func (s *RepositoryService) PatchRepository(ctx context.Context, patch *api.RepositoryPatch) (*api.RepositoryRaw, error) {
+func (s *Store) patchRepositoryRaw(ctx context.Context, patch *api.RepositoryPatch) (*repositoryRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- repository, err := patchRepository(ctx, tx.PTx, patch, s.db.mode)
+ repository, err := patchRepositoryImpl(ctx, tx.PTx, patch, s.db.mode)
if err != nil {
return nil, FormatError(err)
}
@@ -107,27 +272,8 @@ func (s *RepositoryService) PatchRepository(ctx context.Context, patch *api.Repo
return repository, nil
}
-// DeleteRepository deletes an existing repository by ID.
-func (s *RepositoryService) DeleteRepository(ctx context.Context, delete *api.RepositoryDelete) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return FormatError(err)
- }
- defer tx.PTx.Rollback()
-
- if err := s.deleteRepository(ctx, tx.PTx, delete); err != nil {
- return FormatError(err)
- }
-
- if err := tx.PTx.Commit(); err != nil {
- return FormatError(err)
- }
-
- return nil
-}
-
-// createRepository creates a new repository.
-func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, create *api.RepositoryCreate) (*api.RepositoryRaw, error) {
+// createRepositoryImpl creates a new repository.
+func (s *Store) createRepositoryImpl(ctx context.Context, tx *sql.Tx, create *api.RepositoryCreate) (*repositoryRaw, error) {
// Updates the project workflow_type to "VCS"
workflowType := api.VCSWorkflow
projectPatch := api.ProjectPatch{
@@ -135,7 +281,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, cr
UpdaterID: create.CreatorID,
WorkflowType: &workflowType,
}
- if _, err := s.store.patchProjectRawTx(ctx, tx, &projectPatch); err != nil {
+ if _, err := s.patchProjectRawTx(ctx, tx, &projectPatch); err != nil {
return nil, err
}
@@ -195,7 +341,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, cr
defer row.Close()
row.Next()
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := row.Scan(
&repository.ID,
&repository.CreatorID,
@@ -278,7 +424,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, cr
defer row.Close()
row.Next()
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := row.Scan(
&repository.ID,
&repository.CreatorID,
@@ -309,7 +455,7 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *sql.Tx, cr
return &repository, nil
}
-func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFind, mode common.ReleaseMode) ([]*api.RepositoryRaw, error) {
+func findRepositoryImpl(ctx context.Context, tx *sql.Tx, find *api.RepositoryFind, mode common.ReleaseMode) ([]*repositoryRaw, error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
@@ -361,9 +507,9 @@ func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFin
defer rows.Close()
// Iterate over result set and deserialize rows into repoRawList.
- var repoRawList []*api.RepositoryRaw
+ var repoRawList []*repositoryRaw
for rows.Next() {
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := rows.Scan(
&repository.ID,
&repository.CreatorID,
@@ -434,9 +580,9 @@ func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFin
defer rows.Close()
// Iterate over result set and deserialize rows into repoRawList.
- var repoRawList []*api.RepositoryRaw
+ var repoRawList []*repositoryRaw
for rows.Next() {
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := rows.Scan(
&repository.ID,
&repository.CreatorID,
@@ -473,8 +619,8 @@ func findRepositoryList(ctx context.Context, tx *sql.Tx, find *api.RepositoryFin
return repoRawList, nil
}
-// 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, mode common.ReleaseMode) (*api.RepositoryRaw, error) {
+// patchRepositoryImpl updates a repository by ID. Returns the new state of the repository after update.
+func patchRepositoryImpl(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch, mode common.ReleaseMode) (*repositoryRaw, error) {
// Build UPDATE clause.
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
if v := patch.BranchFilter; v != nil {
@@ -522,7 +668,7 @@ func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch
defer row.Close()
if row.Next() {
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := row.Scan(
&repository.ID,
&repository.CreatorID,
@@ -571,7 +717,7 @@ func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch
defer row.Close()
if row.Next() {
- var repository api.RepositoryRaw
+ var repository repositoryRaw
if err := row.Scan(
&repository.ID,
&repository.CreatorID,
@@ -606,7 +752,7 @@ func patchRepository(ctx context.Context, tx *sql.Tx, patch *api.RepositoryPatch
}
// deleteRepository permanently deletes a repository by ID.
-func (s *RepositoryService) deleteRepository(ctx context.Context, tx *sql.Tx, delete *api.RepositoryDelete) error {
+func (s *Store) deleteRepository(ctx context.Context, tx *sql.Tx, delete *api.RepositoryDelete) error {
// Updates the project workflow_type to "UI"
workflowType := api.UIWorkflow
projectPatch := api.ProjectPatch{
@@ -614,7 +760,7 @@ func (s *RepositoryService) deleteRepository(ctx context.Context, tx *sql.Tx, de
UpdaterID: delete.DeleterID,
WorkflowType: &workflowType,
}
- if _, err := s.store.patchProjectRawTx(ctx, tx, &projectPatch); err != nil {
+ if _, err := s.patchProjectRawTx(ctx, tx, &projectPatch); err != nil {
return err
}