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.Project (#754)
Yilong Lie0afbf6495e2
diff --git a/api/project.go b/api/project.goindex cfca826794..55ca3f71ed 100644--- a/api/project.go+++ b/api/project.go@@ -64,6 +64,50 @@ const (TenantModeTenant ProjectTenantMode = "TENANT")+// ProjectRaw is the store model for a project.+type ProjectRaw struct {+ ID int++ // Standard fields+ RowStatus RowStatus+ CreatorID int+ CreatedTs int64+ UpdaterID int+ UpdatedTs int64++ // Domain specific fields+ Name string+ Key string+ WorkflowType ProjectWorkflowType+ Visibility ProjectVisibility+ TenantMode ProjectTenantMode+ // DBNameTemplate is only used when a project is in tenant mode.+ // Empty value means {{DB_NAME}}.+ DBNameTemplate string+ RoleProvider ProjectRoleProvider+}++// CopyToProject copies fields of ProjectRaw to an instance of Project.+// This is intented to be used when we need to compose a Project relationship.+func (raw *ProjectRaw) CopyToProject(p *Project) {+ p.ID = raw.ID++ p.RowStatus = raw.RowStatus+ p.CreatorID = raw.CreatorID+ p.CreatedTs = raw.CreatedTs+ p.UpdaterID = raw.UpdaterID+ p.UpdatedTs = raw.UpdatedTs++ p.Name = raw.Name+ p.Key = raw.Key+ p.WorkflowType = raw.WorkflowType+ p.Visibility = raw.Visibility+ p.TenantMode = raw.TenantMode++ p.DBNameTemplate = raw.DBNameTemplate+ p.RoleProvider = raw.RoleProvider+}+// Project is the API message for a project.type Project struct {ID int `jsonapi:"primary,project"`@@ -306,12 +350,12 @@ func getTemplateTokens(template string) []string {return r.FindAllString(template, -1)}-// ProjectService is the service for projects.+// ProjectService is the storage access service for projects.type ProjectService interface {- CreateProject(ctx context.Context, create *ProjectCreate) (*Project, error)- FindProjectList(ctx context.Context, find *ProjectFind) ([]*Project, error)- FindProject(ctx context.Context, find *ProjectFind) (*Project, error)- PatchProject(ctx context.Context, patch *ProjectPatch) (*Project, error)+ CreateProject(ctx context.Context, create *ProjectCreate) (*ProjectRaw, error)+ FindProjectList(ctx context.Context, find *ProjectFind) ([]*ProjectRaw, error)+ FindProject(ctx context.Context, find *ProjectFind) (*ProjectRaw, error)+ PatchProject(ctx context.Context, patch *ProjectPatch) (*ProjectRaw, error)// This is specifically used to update the ProjectWorkflowType when linking/unlinking the repository.- PatchProjectTx(ctx context.Context, tx *sql.Tx, patch *ProjectPatch) (*Project, error)+ PatchProjectTx(ctx context.Context, tx *sql.Tx, patch *ProjectPatch) (*ProjectRaw, error)}diff --git a/api/slug.go b/api/slug.goindex 87ae462e24..773e26042d 100644--- a/api/slug.go+++ b/api/slug.go@@ -11,16 +11,26 @@ func IssueSlug(issue *Issue) string {return fmt.Sprintf("%s-%d", slug.Make(issue.Name), issue.ID)}-// ProjectSlug is the slug formatter for projects.+// ProjectSlug is the slug formatter for Project.func ProjectSlug(project *Project) string {return fmt.Sprintf("%s-%d", slug.Make(project.Name), project.ID)}-// ProjectShortSlug is the slug short formatter for projects.+// ProjectRawSlug is the slug formatter for ProjectRaw.+func ProjectRawSlug(project *ProjectRaw) string {+ return fmt.Sprintf("%s-%d", slug.Make(project.Name), project.ID)+}++// ProjectShortSlug is the slug short formatter for Project.func ProjectShortSlug(project *Project) string {return slug.Make(project.Name)}+// ProjectRawShortSlug is the slug short formatter for ProjectRaw.+func ProjectRawShortSlug(project *ProjectRaw) string {+ return slug.Make(project.Name)+}+// EnvSlug is the slug formatter for environments.func EnvSlug(env *Environment) string {return slug.Make(env.Name)diff --git a/server/activity_manager.go b/server/activity_manager.goindex 64e47c858c..b14862622b 100644--- a/server/activity_manager.go+++ b/server/activity_manager.go@@ -7,10 +7,10 @@ import ("strconv""time"- "github.com/pkg/errors"-"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/plugin/webhook"++ "github.com/pkg/errors""go.uber.org/zap")@@ -71,13 +71,15 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.ActiviprojectFind := &api.ProjectFind{ID: &meta.issue.ProjectID,}- meta.issue.Project, err = m.s.ProjectService.FindProject(ctx, projectFind)+ projectRaw, err := m.s.ProjectService.FindProject(ctx, projectFind)if err != nil {return nil, fmt.Errorf("failed to find project for posting webhook event after changing the issue status: %v, error: %w", meta.issue.Name, err)}- if meta.issue.Project == nil {+ if projectRaw == nil {return nil, fmt.Errorf("failed to find project ID %v for posting webhook event after changing the issue status %q", meta.issue.ProjectID, meta.issue.Name)}+ // TODO(dragonly): revisit the necessity of this function to depend on ActivityMeta.+ projectRaw.CopyToProject(meta.issue.Project)}principalFind := &api.PrincipalFind{diff --git a/server/project.go b/server/project.goindex 2155dc4b5e..1b1e518304 100644--- a/server/project.go+++ b/server/project.go@@ -38,7 +38,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {if projectCreate.TenantMode != api.TenantModeTenant && projectCreate.DBNameTemplate != "" {return echo.NewHTTPError(http.StatusBadRequest, "database name template can only be set for tenant mode project")}- project, err := s.ProjectService.CreateProject(ctx, projectCreate)+ projectRaw, err := s.ProjectService.CreateProject(ctx, projectCreate)if err != nil {if common.ErrorCode(err) == common.Conflict {return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project name already exists: %s", projectCreate.Name))@@ -48,17 +48,17 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {projectMember := &api.ProjectMemberCreate{CreatorID: projectCreate.CreatorID,- ProjectID: project.ID,+ ProjectID: projectRaw.ID,Role: common.ProjectOwner,PrincipalID: projectCreate.CreatorID,}- _, err = s.ProjectMemberService.CreateProjectMember(ctx, projectMember)- if err != nil {+ if _, err = s.ProjectMemberService.CreateProjectMember(ctx, projectMember); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to add owner after creating project").SetInternal(err)}- if err := s.composeProjectRelationship(ctx, project); err != nil {+ project, err := s.composeProjectRelationship(ctx, projectRaw)+ if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch relationship after creating project").SetInternal(err)}@@ -83,21 +83,26 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {rowStatus := api.RowStatus(rowStatusStr)projectFind.RowStatus = &rowStatus}- list, err := s.ProjectService.FindProjectList(ctx, projectFind)+ projectRawList, err := s.ProjectService.FindProjectList(ctx, projectFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch project list").SetInternal(err)}var activeProjectList []*api.Project- for _, project := range list {- if err := s.composeProjectRelationship(ctx, project); err != nil {+ projectList := make([]*api.Project, 0, len(projectRawList))+ for _, projectRaw := range projectRawList {+ project, err := s.composeProjectRelationship(ctx, projectRaw)+ if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project relationship: %v", project.Name)).SetInternal(err)}+ projectList = append(projectList, project)// We will filter those project with the current principle as an inactive member (the role provider differs from that of the project)+ // TODO(dragonly): move this if-branch out of the for loop to optimize access patternif projectFind.PrincipalID != nil {+ principalID := *projectFind.PrincipalID+ roleProvider := project.RoleProviderfor _, projectMember := range project.ProjectMemberList {- if projectMember.PrincipalID == *projectFind.PrincipalID &&- projectMember.RoleProvider == project.RoleProvider {+ if projectMember.PrincipalID == principalID && projectMember.RoleProvider == roleProvider {activeProjectList = append(activeProjectList, project)break}@@ -107,7 +112,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// if principalID is not passed, we will disable the filter logicif projectFind.PrincipalID == nil {- activeProjectList = list+ activeProjectList = projectList}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -154,7 +159,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch project request").SetInternal(err)}- project, err := s.ProjectService.PatchProject(ctx, projectPatch)+ projectRaw, err := s.ProjectService.PatchProject(ctx, projectPatch)if err != nil {if common.ErrorCode(err) == common.NotFound {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", id))@@ -162,7 +167,8 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch project ID: %v", id)).SetInternal(err)}- if err := s.composeProjectRelationship(ctx, project); err != nil {+ project, err := s.composeProjectRelationship(ctx, projectRaw)+ if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated project relationship: %v", project.Name)).SetInternal(err)}@@ -581,40 +587,44 @@ func (s *Server) composeProjectByID(ctx context.Context, id int) (*api.Project,projectFind := &api.ProjectFind{ID: &id,}- project, err := s.ProjectService.FindProject(ctx, projectFind)+ projectRaw, err := s.ProjectService.FindProject(ctx, projectFind)if err != nil {return nil, err}- if project == nil {+ if projectRaw == nil {return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("project ID not found: %d", id)}}- if err := s.composeProjectRelationship(ctx, project); err != nil {+ project, err := s.composeProjectRelationship(ctx, projectRaw)+ if err != nil {return nil, err}return project, nil}-func (s *Server) composeProjectRelationship(ctx context.Context, project *api.Project) error {+func (s *Server) composeProjectRelationship(ctx context.Context, projectRaw *api.ProjectRaw) (*api.Project, error) {var err error+ project := &api.Project{}+ projectRaw.CopyToProject(project)+project.Creator, err = s.composePrincipalByID(ctx, project.CreatorID)if err != nil {- return err+ return nil, err}project.Updater, err = s.composePrincipalByID(ctx, project.UpdaterID)if err != nil {- return err+ return nil, err}project.ProjectMemberList, err = s.composeProjectMemberListByProjectID(ctx, project.ID)if err != nil {- return err+ return nil, err}- return nil+ return project, nil}func (s *Server) composeDeploymentConfigRelationship(ctx context.Context, deploymentConfig *api.DeploymentConfig) error {diff --git a/server/project_webhook.go b/server/project_webhook.goindex 48e44d7212..ded3312a27 100644--- a/server/project_webhook.go+++ b/server/project_webhook.go@@ -188,11 +188,11 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {projectFind := &api.ProjectFind{ID: &projectID,}- project, err := s.ProjectService.FindProject(ctx, projectFind)+ projectRaw, err := s.ProjectService.FindProject(ctx, projectFind)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)}- if project == nil {+ if projectRaw == nil {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", projectID))}@@ -220,14 +220,14 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {Level: webhook.WebhookInfo,Title: fmt.Sprintf("Test webhook %q", hook.Name),Description: "This is a test",- Link: fmt.Sprintf("%s:%d/project/%s/webhook/%s", s.frontendHost, s.frontendPort, api.ProjectSlug(project), api.ProjectWebhookSlug(hook)),+ Link: fmt.Sprintf("%s:%d/project/%s/webhook/%s", s.frontendHost, s.frontendPort, api.ProjectRawSlug(projectRaw), api.ProjectWebhookSlug(hook)),CreatorName: "Bytebase",CreatorEmail: "[email protected]",CreatedTs: time.Now().Unix(),MetaList: []webhook.Meta{{Name: "Project",- Value: project.Name,+ Value: projectRaw.Name,},},},diff --git a/store/project.go b/store/project.goindex b89321f79b..6d3f54270e 100644--- a/store/project.go+++ b/store/project.go@@ -29,14 +29,14 @@ func NewProjectService(logger *zap.Logger, db *DB, cache api.CacheService) *Proj}// CreateProject creates a new project.-func (s *ProjectService) CreateProject(ctx context.Context, create *api.ProjectCreate) (*api.Project, error) {+func (s *ProjectService) CreateProject(ctx context.Context, create *api.ProjectCreate) (*api.ProjectRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- project, err := createProject(ctx, tx.PTx, create)+ projectRaw, err := createProject(ctx, tx.PTx, create)if err != nil {return nil, err}@@ -45,15 +45,15 @@ func (s *ProjectService) CreateProject(ctx context.Context, create *api.ProjectCreturn nil, FormatError(err)}- if err := s.cache.UpsertCache(api.ProjectCache, project.ID, project); err != nil {+ if err := s.cache.UpsertCache(api.ProjectCache, projectRaw.ID, projectRaw); err != nil {return nil, err}- return project, nil+ return projectRaw, nil}// FindProjectList retrieves a list of projects based on find.-func (s *ProjectService) FindProjectList(ctx context.Context, find *api.ProjectFind) ([]*api.Project, error) {+func (s *ProjectService) FindProjectList(ctx context.Context, find *api.ProjectFind) ([]*api.ProjectRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -62,7 +62,7 @@ func (s *ProjectService) FindProjectList(ctx context.Context, find *api.ProjectFlist, err := findProjectList(ctx, tx.PTx, find)if err != nil {- return []*api.Project{}, err+ return []*api.ProjectRaw{}, err}if err == nil {@@ -78,9 +78,9 @@ func (s *ProjectService) FindProjectList(ctx context.Context, find *api.ProjectF// FindProject retrieves a single project based on find.// Returns ECONFLICT if finding more than 1 matching records.-func (s *ProjectService) FindProject(ctx context.Context, find *api.ProjectFind) (*api.Project, error) {+func (s *ProjectService) FindProject(ctx context.Context, find *api.ProjectFind) (*api.ProjectRaw, error) {if find.ID != nil {- project := &api.Project{}+ project := &api.ProjectRaw{}has, err := s.cache.FindCache(api.ProjectCache, *find.ID, project)if err != nil {return nil, err@@ -114,7 +114,7 @@ func (s *ProjectService) FindProject(ctx context.Context, find *api.ProjectFind)// PatchProject updates an existing project by ID.// Returns ENOTFOUND if project does not exist.-func (s *ProjectService) PatchProject(ctx context.Context, patch *api.ProjectPatch) (*api.Project, error) {+func (s *ProjectService) PatchProject(ctx context.Context, patch *api.ProjectPatch) (*api.ProjectRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -139,7 +139,7 @@ func (s *ProjectService) PatchProject(ctx context.Context, patch *api.ProjectPat// PatchProjectTx updates an existing project by ID.// Returns ENOTFOUND if project does not exist.-func (s *ProjectService) PatchProjectTx(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.Project, error) {+func (s *ProjectService) PatchProjectTx(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.ProjectRaw, error) {project, err := patchProject(ctx, tx, patch)if err != nil {@@ -154,7 +154,7 @@ func (s *ProjectService) PatchProjectTx(ctx context.Context, tx *sql.Tx, patch *}// createProject creates a new project.-func createProject(ctx context.Context, tx *sql.Tx, create *api.ProjectCreate) (*api.Project, error) {+func createProject(ctx context.Context, tx *sql.Tx, create *api.ProjectCreate) (*api.ProjectRaw, error) {// Insert row into database.if create.RoleProvider == "" {create.RoleProvider = api.ProjectRoleProviderBytebase@@ -189,7 +189,7 @@ func createProject(ctx context.Context, tx *sql.Tx, create *api.ProjectCreate) (defer row.Close()row.Next()- var project api.Project+ var project api.ProjectRawif err := row.Scan(&project.ID,&project.RowStatus,@@ -211,7 +211,7 @@ func createProject(ctx context.Context, tx *sql.Tx, create *api.ProjectCreate) (return &project, nil}-func findProjectList(ctx context.Context, tx *sql.Tx, find *api.ProjectFind) (_ []*api.Project, err error) {+func findProjectList(ctx context.Context, tx *sql.Tx, find *api.ProjectFind) (_ []*api.ProjectRaw, err error) {// Build WHERE clause.where, args := []string{"1 = 1"}, []interface{}{}if v := find.ID; v != nil {@@ -249,9 +249,9 @@ func findProjectList(ctx context.Context, tx *sql.Tx, find *api.ProjectFind) (_defer rows.Close()// Iterate over result set and deserialize rows into list.- list := make([]*api.Project, 0)+ list := make([]*api.ProjectRaw, 0)for rows.Next() {- var project api.Project+ var project api.ProjectRawif err := rows.Scan(&project.ID,&project.RowStatus,@@ -280,7 +280,7 @@ func findProjectList(ctx context.Context, tx *sql.Tx, find *api.ProjectFind) (_}// patchProject updates a project by ID. Returns the new state of the project after update.-func patchProject(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.Project, error) {+func patchProject(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.ProjectRaw, error) {// Build UPDATE clause.set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}if v := patch.RowStatus; v != nil {@@ -316,7 +316,7 @@ func patchProject(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*apdefer row.Close()if row.Next() {- var project api.Project+ var project api.ProjectRawif err := row.Scan(&project.ID,&project.RowStatus,