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: migrate legacy store to use v1 store for environment (#4164)
Danny Xu24453d6b155b
diff --git a/api/environment.go b/api/environment.goindex 579ce25014..471c8f2aa7 100644--- a/api/environment.go+++ b/api/environment.go@@ -1,7 +1,6 @@package apiimport (- "encoding/json""regexp""github.com/pkg/errors"@@ -40,21 +39,7 @@ type EnvironmentCreate struct {// EnvironmentFind is the API message for finding environments.type EnvironmentFind struct {- ID *int-- // Standard fieldsRowStatus *RowStatus-- // Domain specific fields- Name *string-}--func (find *EnvironmentFind) String() string {- str, err := json.Marshal(*find)- if err != nil {- return err.Error()- }- return string(str)}// placeholderRegexp is the regexp for placeholder.@@ -87,12 +72,3 @@ type EnvironmentPatch struct {Name *string `jsonapi:"attr,name"`Order *int `jsonapi:"attr,order"`}--// EnvironmentDelete is the API message for deleting an environment.-type EnvironmentDelete struct {- ID int-- // Standard fields- // Value is assigned from the jwt subject field passed by the client.- DeleterID int-}diff --git a/resources/postgres/postgres.go b/resources/postgres/postgres.goindex adc68a2744..9e0d3af1a7 100644--- a/resources/postgres/postgres.go+++ b/resources/postgres/postgres.go@@ -96,7 +96,7 @@ func Install(resourceDir string) (string, error) {// Start starts a postgres database instance.// If port is 0, then it will choose a random unused port.-func Start(port int, binDir string, dataDir string) (err error) {+func Start(port int, binDir, dataDir string, serverLog bool) (err error) {pgbin := filepath.Join(binDir, "pg_ctl")// See -p -k -h option definitions in the link below.@@ -116,8 +116,10 @@ func Start(port int, binDir string, dataDir string) (err error) {}}- // Suppress log spam- p.Stdout = nil+ // It's useful to log the SQL statement errors from Postgres in developer environment.+ if serverLog {+ p.Stdout = os.Stdout+ }p.Stderr = os.Stderrif err := p.Run(); err != nil {return errors.Wrapf(err, "failed to start postgres %q", p.String())diff --git a/server/environment.go b/server/environment.goindex 4efca94516..4f94e888ef 100644--- a/server/environment.go+++ b/server/environment.go@@ -155,22 +155,27 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {}func (s *Server) createEnvironment(ctx context.Context, create *store.EnvironmentCreate) (*api.Environment, error) {- normalRowStatus := api.Normal- envFind := &api.EnvironmentFind{- RowStatus: &normalRowStatus,+ if err := api.IsValidEnvironmentName(create.Name); err != nil {+ return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)}- envList, err := s.store.FindEnvironment(ctx, envFind)++ environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{ShowDeleted: true})if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to find environment list").SetInternal(err)}-maximumEnvironmentLimit := s.licenseService.GetPlanLimitValue(api.PlanLimitMaximumEnvironment)- if int64(len(envList)) >= maximumEnvironmentLimit {+ if int64(len(environments)) >= maximumEnvironmentLimit {return nil, echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("Current plan can create up to %d environments.", maximumEnvironmentLimit))}-- if err := api.IsValidEnvironmentName(create.Name); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)+ order := 0+ for _, envenvironment := range environments {+ if int(envenvironment.Order) > order {+ order = int(envenvironment.Order)+ }+ }+ if create.Order == nil {+ order+++ create.Order = &order}env, err := s.store.CreateEnvironment(ctx, create)diff --git a/server/instance.go b/server/instance.goindex 9d92a762be..383e1ef5bb 100644--- a/server/instance.go+++ b/server/instance.go@@ -422,7 +422,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to init embedded postgres database").SetInternal(err)}- if err := postgres.Start(port, s.pgBinDir, dataDir); err != nil {+ if err := postgres.Start(port, s.pgBinDir, dataDir, false /* serverLog */); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to start embedded postgres instance").SetInternal(err)}}diff --git a/server/openapi_environment.go b/server/openapi_environment.goindex 360cb3e1a4..012f2507e4 100644--- a/server/openapi_environment.go+++ b/server/openapi_environment.go@@ -23,9 +23,6 @@ func (s *Server) listEnvironment(c echo.Context) error {find := &api.EnvironmentFind{RowStatus: &rowStatus,}- if name := c.QueryParam("name"); name != "" {- find.Name = &name- }envList, err := s.store.FindEnvironment(ctx, find)if err != nil {@@ -75,13 +72,9 @@ func (s *Server) createEnvironmentByOpenAPI(c echo.Context) error {creatorID := c.Get(getPrincipalIDContextKey()).(int)env, err := s.createEnvironment(ctx, &store.EnvironmentCreate{- CreatorID: creatorID,- EnvironmentTierPolicy: upsert.EnvironmentTierPolicy,- PipelineApprovalPolicy: upsert.PipelineApprovalPolicy,- BackupPlanPolicy: upsert.BackupPlanPolicy,- SQLReviewPolicy: upsert.SQLReviewPolicy,- Name: *upsert.Name,- Order: upsert.Order,+ CreatorID: creatorID,+ Name: *upsert.Name,+ Order: upsert.Order,})if err != nil {return err@@ -134,29 +127,11 @@ func (s *Server) updateEnvironmentByOpenAPI(c echo.Context) error {if err := json.Unmarshal(body, upsert); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)}-- if err := s.validateEnvironmentPolicy(api.PolicyTypePipelineApproval, upsert.PipelineApprovalPolicy); err != nil {- return err- }- if err := s.validateEnvironmentPolicy(api.PolicyTypeBackupPlan, upsert.BackupPlanPolicy); err != nil {- return err- }- if err := s.validateEnvironmentPolicy(api.PolicyTypeEnvironmentTier, upsert.EnvironmentTierPolicy); err != nil {- return err- }- if err := s.validateEnvironmentPolicy(api.PolicyTypeSQLReview, upsert.SQLReviewPolicy); err != nil {- return err- }-env, err := s.updateEnvironment(ctx, &store.EnvironmentPatch{- ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- EnvironmentTierPolicy: upsert.EnvironmentTierPolicy,- PipelineApprovalPolicy: upsert.PipelineApprovalPolicy,- BackupPlanPolicy: upsert.BackupPlanPolicy,- SQLReviewPolicy: upsert.SQLReviewPolicy,- Name: upsert.Name,- Order: upsert.Order,+ ID: id,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ Name: upsert.Name,+ Order: upsert.Order,})if err != nil {return errdiff --git a/server/openapi_sql.go b/server/openapi_sql.goindex f913cb93f6..3f69226bab 100644--- a/server/openapi_sql.go+++ b/server/openapi_sql.go@@ -18,6 +18,7 @@ import ("github.com/bytebase/bytebase/plugin/metric""github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/differ"+ "github.com/bytebase/bytebase/store")var (@@ -75,6 +76,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {return echo.NewHTTPError(http.StatusBadRequest, "Cannot format request body").SetInternal(err)}+ // EnvironmentName is the environment resource ID.if request.EnvironmentName == "" {return echo.NewHTTPError(http.StatusBadRequest, "Missing required environment name")}@@ -124,13 +126,11 @@ func (s *Server) sqlCheckController(c echo.Context) error {catalog = newCatalogService(advisorDBType)}- envList, err := s.store.FindEnvironment(ctx, &api.EnvironmentFind{- Name: &request.EnvironmentName,- })+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &request.EnvironmentName})if err != nil {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to find environment %s", request.EnvironmentName)).SetInternal(err)}- if len(envList) != 1 {+ if environment == nil {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid environment %s", request.EnvironmentName))}@@ -139,7 +139,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {advisorDBType,"utf8mb4","utf8mb4_general_ci",- envList[0].ID,+ environment.UID,request.Statement,catalog,connection,diff --git a/server/runner/anomaly/scanner.go b/server/runner/anomaly/scanner.goindex 4b7676ab4f..a9c266b557 100644--- a/server/runner/anomaly/scanner.go+++ b/server/runner/anomaly/scanner.go@@ -67,22 +67,22 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {ctx := context.Background()- envList, err := s.store.FindEnvironment(ctx, &api.EnvironmentFind{})+ environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{})if err != nil {log.Error("Failed to retrieve instance list", zap.Error(err))return}backupPlanPolicyMap := make(map[int]*api.BackupPlanPolicy)- for _, env := range envList {- policy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, env.ID)+ for _, environment := range environments {+ policy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, environment.UID)if err != nil {log.Error("Failed to retrieve backup policy",- zap.String("environment", env.Name),+ zap.String("environment", environment.Title),zap.Error(err))return}- backupPlanPolicyMap[env.ID] = policy+ backupPlanPolicyMap[environment.UID] = policy}rowStatus := api.Normal@@ -97,16 +97,12 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {for _, instance := range instanceList {foundEnv := false- for _, env := range envList {- if env.ID == instance.EnvironmentID {- if env.RowStatus == api.Normal {- instance.Environment = env- }+ for _, environment := range environments {+ if environment.UID == instance.EnvironmentID {foundEnv = truebreak}}-if !foundEnv {continue}diff --git a/store/cache.go b/store/cache.goindex d1e170237c..9ee243c9ed 100644--- a/store/cache.go+++ b/store/cache.go@@ -15,8 +15,6 @@ type cacheNamespace stringconst (// principalCacheNamespace is the cache type of principals.principalCacheNamespace cacheNamespace = "p"- // environmentCacheNamespace is the cache type of environments.- environmentCacheNamespace cacheNamespace = "e"// projectCacheNamespace is the cache type of projects.projectCacheNamespace cacheNamespace = "r"// projectMemberCacheNamespace is the cache type of project members.diff --git a/store/deploy.go b/store/deploy.goindex a3f911b659..efeb674bf1 100644--- a/store/deploy.go+++ b/store/deploy.go@@ -74,19 +74,19 @@ func (s *Store) GetDeploymentConfigByProjectID(ctx context.Context, projectID in}func (s *Store) getDefaultDeploymentConfig(ctx context.Context, projectID int) (*deploymentConfigRaw, error) {- normalRowStatus := api.Normal- environmentList, err := s.FindEnvironment(ctx, &api.EnvironmentFind{RowStatus: &normalRowStatus})+ environmentList, err := s.ListEnvironmentV2(ctx, &FindEnvironmentMessage{})if err != nil {return nil, err}scheduleList := api.DeploymentSchedule{}for _, environment := range environmentList {scheduleList.Deployments = append(scheduleList.Deployments, &api.Deployment{- Name: fmt.Sprintf("%s Stage", environment.Name),+ Name: fmt.Sprintf("%s Stage", environment.Title),Spec: &api.DeploymentSpec{Selector: &api.LabelSelector{MatchExpressions: []*api.LabelSelectorRequirement{- {Key: "bb.environment", Operator: api.InOperatorType, Values: []string{environment.Name}},+ // TODO(d): use environment ID for the label.+ {Key: "bb.environment", Operator: api.InOperatorType, Values: []string{environment.Title}},},},},diff --git a/store/environment.go b/store/environment.goindex 4c3414c52b..9b41deabaf 100644--- a/store/environment.go+++ b/store/environment.go@@ -3,7 +3,6 @@ package storeimport ("context""database/sql"- "encoding/json""fmt""sort""strings"@@ -12,7 +11,6 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"- "github.com/bytebase/bytebase/plugin/advisor")// EnvironmentCreate is the API message for creating an environment.@@ -21,12 +19,6 @@ type EnvironmentCreate struct {// Standard fieldsCreatorID int- // Related fields- EnvironmentTierPolicy *api.EnvironmentTierPolicy- PipelineApprovalPolicy *api.PipelineApprovalPolicy- BackupPlanPolicy *api.BackupPlanPolicy- SQLReviewPolicy *advisor.SQLReviewPolicy-// Domain specific fieldsName stringOrder *int@@ -41,112 +33,101 @@ type EnvironmentPatch struct {RowStatus *stringUpdaterID int- // Related fields- EnvironmentTierPolicy *api.EnvironmentTierPolicy- PipelineApprovalPolicy *api.PipelineApprovalPolicy- BackupPlanPolicy *api.BackupPlanPolicy- SQLReviewPolicy *advisor.SQLReviewPolicy-// Domain specific fieldsName *stringOrder *int}-// environmentRaw is the store model for an Environment.-// Fields have exactly the same meanings as Environment.-type environmentRaw struct {- ID int- ResourceID string-- // Standard fields- RowStatus api.RowStatus- CreatorID int- CreatedTs int64- UpdaterID int- UpdatedTs int64-- // Domain specific fields- Name string- Order int-}--// toEnvironment creates an instance of Environment based on the environmentRaw.-// This is intended to be called when we need to compose an Environment relationship.-func (raw *environmentRaw) toEnvironment() *api.Environment {- return &api.Environment{- ID: raw.ID,- ResourceID: raw.ResourceID,-- RowStatus: raw.RowStatus,- CreatorID: raw.CreatorID,- CreatedTs: raw.CreatedTs,- UpdaterID: raw.UpdaterID,- UpdatedTs: raw.UpdatedTs,-- Name: raw.Name,- Order: raw.Order,- }-}-// CreateEnvironment creates an instance of Environment.func (s *Store) CreateEnvironment(ctx context.Context, create *EnvironmentCreate) (*api.Environment, error) {- environmentRaw, err := s.createEnvironmentRaw(ctx, create)+ if create.Order == nil {+ return nil, errors.Errorf("order must be set in legacy CreateEnvironment")+ }+ environment, err := s.CreateEnvironmentV2(ctx, &EnvironmentMessage{+ ResourceID: strings.ToLower(create.Name),+ Title: create.Name,+ Order: int32(*create.Order),+ Protected: false,+ }, create.CreatorID)if err != nil {return nil, errors.Wrapf(err, "failed to create Environment with EnvironmentCreate[%+v]", create)}- environment, err := s.composeEnvironment(ctx, environmentRaw)++ composedEnvironment, err := s.composeEnvironment(ctx, environment)if err != nil {- return nil, errors.Wrapf(err, "failed to compose Environment with environmentRaw[%+v]", environmentRaw)+ return nil, errors.Wrapf(err, "failed to compose Environment with environmentRaw[%+v]", environment)}- return environment, nil+ return composedEnvironment, nil}// FindEnvironment finds a list of Environment instances.func (s *Store) FindEnvironment(ctx context.Context, find *api.EnvironmentFind) ([]*api.Environment, error) {- environmentRawList, err := s.findEnvironmentRaw(ctx, find)+ v2Find := &FindEnvironmentMessage{ShowDeleted: true}+ environments, err := s.ListEnvironmentV2(ctx, v2Find)if err != nil {- return nil, errors.Wrapf(err, "failed to find Environment list with EnvironmentFind[%+v]", find)+ return nil, errors.Wrapf(err, "failed to find Environment list with ListEnvironmentV2[%+v]", find)}- sort.Slice(environmentRawList, func(i, j int) bool {- return environmentRawList[i].Order < environmentRawList[j].Order+ sort.Slice(environments, func(i, j int) bool {+ return environments[i].Order < environments[j].Order})- var environmentList []*api.Environment- for _, raw := range environmentRawList {- environment, err := s.composeEnvironment(ctx, raw)+ var composedEnvironmentList []*api.Environment+ for _, environment := range environments {+ composedEnvironment, err := s.composeEnvironment(ctx, environment)if err != nil {- return nil, errors.Wrapf(err, "failed to compose Environment role with environmentRaw[%+v]", raw)+ return nil, errors.Wrapf(err, "failed to compose Environment role with environmentRaw[%+v]", environment)+ }+ if find.RowStatus != nil && composedEnvironment.RowStatus != *find.RowStatus {+ continue}- environmentList = append(environmentList, environment)+ composedEnvironmentList = append(composedEnvironmentList, composedEnvironment)}- return environmentList, nil+ return composedEnvironmentList, nil}// PatchEnvironment patches an instance of Environment.func (s *Store) PatchEnvironment(ctx context.Context, patch *EnvironmentPatch) (*api.Environment, error) {- environmentRaw, err := s.patchEnvironmentRaw(ctx, patch)+ environment, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{UID: &patch.ID})+ if err != nil {+ return nil, err+ }+ v2Update := &UpdateEnvironmentMessage{+ Name: patch.Name,+ }+ if patch.Order != nil {+ order := int32(*patch.Order)+ v2Update.Order = &order+ }+ if patch.RowStatus != nil {+ deleted := false+ if *patch.RowStatus == string(api.Archived) {+ deleted = true+ }+ v2Update.Delete = &deleted+ }+ environment, err = s.UpdateEnvironmentV2(ctx, environment.ResourceID, v2Update, patch.UpdaterID)if err != nil {return nil, errors.Wrapf(err, "failed to patch Environment with EnvironmentPatch[%+v]", patch)}- environment, err := s.composeEnvironment(ctx, environmentRaw)+ composedEnvironment, err := s.composeEnvironment(ctx, environment)if err != nil {- return nil, errors.Wrapf(err, "failed to compose Environment role with environmentRaw[%+v]", environmentRaw)+ return nil, errors.Wrapf(err, "failed to compose Environment with environmentRaw[%+v]", environment)}- return environment, nil+ return composedEnvironment, nil}// GetEnvironmentByID gets an instance of Environment by ID.func (s *Store) GetEnvironmentByID(ctx context.Context, id int) (*api.Environment, error) {- envRaw, err := s.getEnvironmentByIDRaw(ctx, id)+ environment, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{UID: &id})if err != nil {return nil, errors.Wrapf(err, "failed to get environment with ID %d", id)}- if envRaw == nil {+ if environment == nil {return nil, common.Errorf(common.NotFound, "environment %d not found", id)}- env, err := s.composeEnvironment(ctx, envRaw)+ env, err := s.composeEnvironment(ctx, environment)if err != nil {- return nil, errors.Wrapf(err, "failed to compose environment with environmentRaw[%+v]", envRaw)+ return nil, errors.Wrapf(err, "failed to compose environment with environmentRaw[%+v]", environment)}return env, nil@@ -156,392 +137,57 @@ func (s *Store) GetEnvironmentByID(ctx context.Context, id int) (*api.Environmen// private functions//-func (s *Store) composeEnvironment(ctx context.Context, raw *environmentRaw) (*api.Environment, error) {- env := raw.toEnvironment()-- creator, err := s.GetPrincipalByID(ctx, env.CreatorID)- if err != nil {- return nil, err- }- env.Creator = creator-- updater, err := s.GetPrincipalByID(ctx, env.UpdaterID)- if err != nil {- return nil, err- }- env.Updater = updater-- tier, err := s.GetEnvironmentTierPolicyByEnvID(ctx, env.ID)- if err != nil {- return nil, err- }- env.Tier = tier.EnvironmentTier-- return env, nil-}--// createEnvironmentRaw creates a new environment.-func (s *Store) createEnvironmentRaw(ctx context.Context, create *EnvironmentCreate) (*environmentRaw, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, FormatError(err)- }- defer tx.Rollback()-- environment, err := s.createEnvironmentImpl(ctx, tx, create)- if err != nil {- return nil, err- }-- if p := create.PipelineApprovalPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypePipelineApproval, p); err != nil {- return nil, err- }- }- if p := create.BackupPlanPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeBackupPlan, p); err != nil {- return nil, err- }- }- if p := create.EnvironmentTierPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeEnvironmentTier, p); err != nil {- return nil, err- }- }- if p := create.SQLReviewPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeSQLReview, p); err != nil {- return nil, err- }- }-- if err := tx.Commit(); err != nil {- return nil, FormatError(err)+func (s *Store) composeEnvironment(ctx context.Context, raw *EnvironmentMessage) (*api.Environment, error) {+ rowStatus := api.Normal+ if raw.Deleted {+ rowStatus = api.Archived}+ ret := &api.Environment{+ ID: raw.UID,+ ResourceID: raw.ResourceID,- if err := s.cache.UpsertCache(environmentCacheNamespace, environment.ID, environment); err != nil {- return nil, err- }-- return environment, nil-}--func (s *Store) upsertEnvironmentPolicy(- ctx context.Context,- tx *Tx,- env *environmentRaw,- policyType api.PolicyType,- policy interface{},-) (*policyRaw, error) {- bytes, err := json.Marshal(policy)- payload := string(bytes)- if err != nil {- return nil, FormatError(err)- }+ RowStatus: rowStatus,+ CreatorID: api.SystemBotID,+ CreatedTs: 0,+ UpdaterID: api.SystemBotID,+ UpdatedTs: 0,- policyUpsert := &api.PolicyUpsert{- ResourceType: api.PolicyResourceTypeEnvironment,- ResourceID: env.ID,- Type: policyType,- UpdaterID: env.CreatorID,- Payload: &payload,+ Name: raw.Title,+ Order: int(raw.Order),}-- policyRaw, err := upsertPolicyImpl(ctx, tx, policyUpsert)+ bot, err := s.GetPrincipalByID(ctx, api.SystemBotID)if err != nil {return nil, err}+ ret.Creator = bot+ ret.Updater = bot- if err := s.upsertPolicyCache(policyUpsert.Type, policyUpsert.ResourceID, policyRaw.Payload); err != nil {- return nil, err- }-- return policyRaw, nil-}--// findEnvironmentRaw retrieves a list of environments based on find.-func (s *Store) findEnvironmentRaw(ctx context.Context, find *api.EnvironmentFind) ([]*environmentRaw, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, FormatError(err)- }- defer tx.Rollback()-- list, err := s.findEnvironmentImpl(ctx, tx, find)+ tier, err := s.GetEnvironmentTierPolicyByEnvID(ctx, raw.UID)if err != nil {return nil, err}+ ret.Tier = tier.EnvironmentTier- if err == nil {- for _, environment := range list {- if err := s.cache.UpsertCache(environmentCacheNamespace, environment.ID, environment); err != nil {- return nil, err- }- }- }-- return list, nil-}--// getEnvironmentByIDRaw retrieves a single environment based on find.-// Returns ECONFLICT if finding more than 1 matching records.-func (s *Store) getEnvironmentByIDRaw(ctx context.Context, id int) (*environmentRaw, error) {- envRaw := &environmentRaw{}- has, err := s.cache.FindCache(environmentCacheNamespace, id, envRaw)- if err != nil {- return nil, err- }- if has {- return envRaw, nil- }-- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, FormatError(err)- }- defer tx.Rollback()-- find := &api.EnvironmentFind{ID: &id}- envRawList, err := s.findEnvironmentImpl(ctx, tx, find)- if err != nil {- return nil, err- }-- if len(envRawList) == 0 {- return nil, nil- } else if len(envRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d environments with filter %+v, expect 1", len(envRawList), find)}- }- if err := s.cache.UpsertCache(environmentCacheNamespace, envRawList[0].ID, envRawList[0]); err != nil {- return nil, err- }- return envRawList[0], nil-}--// patchEnvironmentRaw updates an existing environment by ID.-// Returns ENOTFOUND if environment does not exist.-func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *EnvironmentPatch) (*environmentRaw, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, FormatError(err)- }- defer tx.Rollback()-- envRaw, err := s.patchEnvironmentImpl(ctx, tx, patch)- if err != nil {- return nil, FormatError(err)- }-- if p := patch.PipelineApprovalPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypePipelineApproval, p); err != nil {- return nil, err- }- }- if p := patch.BackupPlanPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeBackupPlan, p); err != nil {- return nil, err- }- }- if p := patch.EnvironmentTierPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeEnvironmentTier, p); err != nil {- return nil, err- }- }- if p := patch.SQLReviewPolicy; p != nil {- if _, err := s.upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeSQLReview, p); err != nil {- return nil, err- }- }-- if err := tx.Commit(); err != nil {- return nil, FormatError(err)- }-- if err := s.cache.UpsertCache(environmentCacheNamespace, envRaw.ID, envRaw); err != nil {- return nil, err- }- delete(s.environmentCache, envRaw.ResourceID)-- return envRaw, nil-}--// createEnvironmentImpl creates a new environment.-func (Store) createEnvironmentImpl(ctx context.Context, tx *Tx, create *EnvironmentCreate) (*environmentRaw, error) {- var order int-- if create.Order != nil {- order = *create.Order- } else {- // The order is the MAX(order) + 1- if err := tx.QueryRowContext(ctx, `- SELECT "order"- FROM environment- ORDER BY "order" DESC- LIMIT 1- `).Scan(&order); err != nil {- if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("no environment record found")}- }- return nil, FormatError(err)- }- order++- }-- // TODO(d): allow users to set resource_id.- resourceID := strings.ToLower(create.Name)- // Insert row into database.- query := `- INSERT INTO environment (- creator_id,- updater_id,- name,- "order",- resource_id- )- VALUES ($1, $2, $3, $4, $5)- RETURNING id, resource_id, row_status, creator_id, created_ts, updater_id, updated_ts, name, "order"- `- var envRaw environmentRaw- if err := tx.QueryRowContext(ctx, query,- create.CreatorID,- create.CreatorID,- create.Name,- order,- resourceID,- ).Scan(- &envRaw.ID,- &envRaw.ResourceID,- &envRaw.RowStatus,- &envRaw.CreatorID,- &envRaw.CreatedTs,- &envRaw.UpdaterID,- &envRaw.UpdatedTs,- &envRaw.Name,- &envRaw.Order,- ); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(query)- }- return nil, FormatError(err)- }- return &envRaw, nil-}--func (*Store) findEnvironmentImpl(ctx context.Context, tx *Tx, find *api.EnvironmentFind) ([]*environmentRaw, error) {- // Build WHERE clause.- where, args := []string{"1 = 1"}, []interface{}{}- if v := find.ID; v != nil {- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)- }- if v := find.Name; v != nil {- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)- }- if v := find.RowStatus; v != nil {- where, args = append(where, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)- }-- rows, err := tx.QueryContext(ctx, `- SELECT- id,- resource_id,- row_status,- creator_id,- created_ts,- updater_id,- updated_ts,- name,- "order"- FROM environment- WHERE `+strings.Join(where, " AND "),- args...,- )- if err != nil {- return nil, FormatError(err)- }- defer rows.Close()-- // Iterate over result set and deserialize rows into list.- var envRawList []*environmentRaw- for rows.Next() {- var environment environmentRaw- if err := rows.Scan(- &environment.ID,- &environment.ResourceID,- &environment.RowStatus,- &environment.CreatorID,- &environment.CreatedTs,- &environment.UpdaterID,- &environment.UpdatedTs,- &environment.Name,- &environment.Order,- ); err != nil {- return nil, FormatError(err)- }-- envRawList = append(envRawList, &environment)- }- if err := rows.Err(); err != nil {- return nil, FormatError(err)- }-- return envRawList, nil-}--// patchEnvironmentImpl updates a environment by ID. Returns the new state of the environment after update.-func (*Store) patchEnvironmentImpl(ctx context.Context, tx *Tx, patch *EnvironmentPatch) (*environmentRaw, error) {- // Build UPDATE clause.- set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}- if v := patch.RowStatus; v != nil {- set, args = append(set, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, api.RowStatus(*v))- }- if v := patch.Name; v != nil {- set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)- }- if v := patch.Order; v != nil {- set, args = append(set, fmt.Sprintf(`"order" = $%d`, len(args)+1)), append(args, *v)- }-- args = append(args, patch.ID)-- var environment environmentRaw- // Execute update query with RETURNING.- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`- UPDATE environment- SET `+strings.Join(set, ", ")+`- WHERE id = $%d- RETURNING id, resource_id, row_status, creator_id, created_ts, updater_id, updated_ts, name, "order"- `, len(args)),- args...,- ).Scan(- &environment.ID,- &environment.ResourceID,- &environment.RowStatus,- &environment.CreatorID,- &environment.CreatedTs,- &environment.UpdaterID,- &environment.UpdatedTs,- &environment.Name,- &environment.Order,- ); err != nil {- if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("environment ID not found: %d", patch.ID)}- }- return nil, FormatError(err)- }- return &environment, nil+ return ret, nil}// EnvironmentMessage is the mssage for environment.type EnvironmentMessage struct {- UID intResourceID stringTitle stringOrder int32Protected bool- Deleted bool++ // The following fields are output only and not used for create().+ UID int+ Deleted bool}// FindEnvironmentMessage is the message to find environments.type FindEnvironmentMessage struct {+ // We should only set either UID or ResourceID.+ // Deprecate UID later once we fully migrate to ResourceID.+ UID *intResourceID *stringShowDeleted bool}@@ -556,6 +202,17 @@ type UpdateEnvironmentMessage struct {// GetEnvironmentV2 gets environment by resource ID.func (s *Store) GetEnvironmentV2(ctx context.Context, find *FindEnvironmentMessage) (*EnvironmentMessage, error) {+ if find.ResourceID != nil {+ if environment, ok := s.environmentCache[*find.ResourceID]; ok {+ return environment, nil+ }+ }+ if find.UID != nil {+ if environment, ok := s.environmentIDCache[*find.UID]; ok {+ return environment, nil+ }+ }+// We will always return the resource regardless of its deleted state.find.ShowDeleted = true@@ -575,6 +232,7 @@ func (s *Store) GetEnvironmentV2(ctx context.Context, find *FindEnvironmentMessa}s.environmentCache[environment.ResourceID] = environment+ s.environmentIDCache[environment.UID] = environmentreturn environment, nil}@@ -597,6 +255,7 @@ func (s *Store) ListEnvironmentV2(ctx context.Context, find *FindEnvironmentMessfor _, environment := range environments {s.environmentCache[environment.ResourceID] = environment+ s.environmentIDCache[environment.UID] = environment}return environments, nil}@@ -616,7 +275,7 @@ func (s *Store) CreateEnvironmentV2(ctx context.Context, create *EnvironmentMessname,"order",creator_id,- updater_id,+ updater_id)VALUES ($1, $2, $3, $4, $5)RETURNING id@@ -643,6 +302,7 @@ func (s *Store) CreateEnvironmentV2(ctx context.Context, create *EnvironmentMessif _, err := upsertPolicyImpl(ctx, tx, &api.PolicyUpsert{ResourceType: api.PolicyResourceTypeEnvironment,ResourceID: uid,+ Type: api.PolicyTypeEnvironmentTier,Payload: &payload,UpdaterID: creatorID,}); err != nil {@@ -657,9 +317,12 @@ func (s *Store) CreateEnvironmentV2(ctx context.Context, create *EnvironmentMessResourceID: create.ResourceID,Title: create.Title,Order: create.Order,+ Protected: create.Protected,+ UID: uid,Deleted: false,}- s.environmentCache[create.ResourceID] = environment+ s.environmentCache[environment.ResourceID] = environment+ s.environmentIDCache[environment.UID] = environmentreturn environment, nil}@@ -687,7 +350,7 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, environmentID string, p}defer tx.Rollback()- var uid int+ var environmentUID intif err := tx.QueryRowContext(ctx, fmt.Sprintf(`UPDATE environmentSET `+strings.Join(set, ", ")+`@@ -696,7 +359,7 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, environmentID string, p`, len(args)),args...,).Scan(- &uid,+ &environmentUID,); err != nil {if err == sql.ErrNoRows {return nil, nil@@ -717,7 +380,8 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, environmentID string, p}if _, err := upsertPolicyImpl(ctx, tx, &api.PolicyUpsert{ResourceType: api.PolicyResourceTypeEnvironment,- ResourceID: uid,+ ResourceID: environmentUID,+ Type: api.PolicyTypeEnvironmentTier,Payload: &payload,UpdaterID: updaterID,}); err != nil {@@ -730,17 +394,14 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, environmentID string, p}// Invalid the cache and read the value again.delete(s.environmentCache, environmentID)+ delete(s.environmentIDCache, environmentUID)return s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{ResourceID: &environmentID,})}-func (s *Store) getEnvironmentImplV2(ctx context.Context, tx *Tx, find *FindEnvironmentMessage) (*EnvironmentMessage, error) {- if environment, ok := s.environmentCache[*find.ResourceID]; ok {- return environment, nil- }-+func (*Store) getEnvironmentImplV2(ctx context.Context, tx *Tx, find *FindEnvironmentMessage) (*EnvironmentMessage, error) {environments, err := listEnvironmentImplV2(ctx, tx, find)if err != nil {return nil, err@@ -759,6 +420,9 @@ func listEnvironmentImplV2(ctx context.Context, tx *Tx, find *FindEnvironmentMesif v := find.ResourceID; v != nil {where, args = append(where, fmt.Sprintf("environment.resource_id = $%d", len(args)+1)), append(args, *v)}+ if v := find.UID; v != nil {+ where, args = append(where, fmt.Sprintf("environment.id = $%d", len(args)+1)), append(args, *v)+ }if !find.ShowDeleted {where, args = append(where, fmt.Sprintf("environment.row_status = $%d", len(args)+1)), append(args, api.Normal)}diff --git a/store/instance.go b/store/instance.goindex e5075f5ccf..24217257bf 100644--- a/store/instance.go+++ b/store/instance.go@@ -850,6 +850,7 @@ func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, inst}defer tx.Rollback()+ // TODO(d): use the same query for environment.environment, err := s.getEnvironmentImplV2(ctx, tx, &FindEnvironmentMessage{ResourceID: &environmentID,})@@ -956,6 +957,7 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa}defer tx.Rollback()+ // TODO(d): use the same query for environment.environment, err := s.getEnvironmentImplV2(ctx, tx, &FindEnvironmentMessage{ResourceID: &patch.EnvironmentID,})diff --git a/store/metadb.go b/store/metadb.goindex 365853f3c9..acfde27f1f 100644--- a/store/metadb.go+++ b/store/metadb.go@@ -64,7 +64,8 @@ func (m *MetadataDB) Connect(datastorePort int, readonly bool, version string) (// connectEmbed starts the embed postgres server and returns an instance of store.DB.func (m *MetadataDB) connectEmbed(datastorePort int, pgUser string, readonly bool, demoDataDir, version string, mode common.ReleaseMode) (*DB, error) {- if err := postgres.Start(datastorePort, m.binDir, m.pgDataDir); err != nil {+ serverLog := mode == common.ReleaseModeDev+ if err := postgres.Start(datastorePort, m.binDir, m.pgDataDir, serverLog); err != nil {return nil, err}// mark pgStarted if start successfully, used in Close()diff --git a/store/pg_engine_test.go b/store/pg_engine_test.goindex 4e2e6698ee..b641233748 100644--- a/store/pg_engine_test.go+++ b/store/pg_engine_test.go@@ -150,7 +150,7 @@ func TestMigrationCompatibility(t *testing.T) {require.NoError(t, err)err = postgres.InitDB(pgBinDir, pgDataDir, pgUser)require.NoError(t, err)- err = postgres.Start(pgPort, pgBinDir, pgDataDir)+ err = postgres.Start(pgPort, pgBinDir, pgDataDir, false /* serverLog */)require.NoError(t, err)ctx := context.Background()diff --git a/store/store.go b/store/store.goindex 70f87506c7..f40d43d0ae 100644--- a/store/store.go+++ b/store/store.go@@ -8,19 +8,21 @@ type Store struct {db *DBcache *CacheService- environmentCache map[string]*EnvironmentMessage- instanceCache map[string]*InstanceMessage- dbSchemaCache map[int]*DBSchema+ environmentCache map[string]*EnvironmentMessage+ environmentIDCache map[int]*EnvironmentMessage+ instanceCache map[string]*InstanceMessage+ dbSchemaCache map[int]*DBSchema}// New creates a new instance of Store.func New(db *DB) *Store {return &Store{- db: db,- cache: newCacheService(),- environmentCache: make(map[string]*EnvironmentMessage),- instanceCache: make(map[string]*InstanceMessage),- dbSchemaCache: make(map[int]*DBSchema),+ db: db,+ cache: newCacheService(),+ environmentCache: make(map[string]*EnvironmentMessage),+ environmentIDCache: make(map[int]*EnvironmentMessage),+ instanceCache: make(map[string]*InstanceMessage),+ dbSchemaCache: make(map[int]*DBSchema),}}diff --git a/tests/start_test.go b/tests/start_test.goindex 39b946bf28..3e64305ac0 100644--- a/tests/start_test.go+++ b/tests/start_test.go@@ -82,7 +82,7 @@ func TestMain(m *testing.M) {if err := postgres.InitDB(externalPgBinDir, externalPgDataDir, externalPgUser); err != nil {log.Fatal(err)}- if err = postgres.Start(externalPgPort, externalPgBinDir, externalPgDataDir); err != nil {+ if err = postgres.Start(externalPgPort, externalPgBinDir, externalPgDataDir, false /* serverLog */); err != nil {log.Fatal(err)}