Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: release policy store change (#3549)
Danny Xud3090b8c7beb
diff --git a/store/migration/dev/LATEST.sql b/store/migration/dev/LATEST.sqlindex bb7a785d33..ef359e0f64 100644--- a/store/migration/dev/LATEST.sql+++ b/store/migration/dev/LATEST.sql@@ -926,13 +926,13 @@ CREATE TABLE repository (base_directory TEXT NOT NULL DEFAULT '',-- The file path template for matching the committed migration script.file_path_template TEXT NOT NULL DEFAULT '',+ -- If enable the SQL review CI in VCS repository.+ enable_sql_review_ci BOOLEAN NOT NULL DEFAULT false,-- The file path template for storing the latest schema auto-generated by Bytebase after migration.-- If empty, then Bytebase won't auto generate it.schema_path_template TEXT NOT NULL DEFAULT '',-- The file path template to match the script file for sheet.sheet_path_template TEXT NOT NULL DEFAULT '',- -- If enable the SQL review CI in VCS repository.- enable_sql_review_ci BOOLEAN NOT NULL DEFAULT false,-- Repository id from the corresponding VCS provider.-- For GitLab, this is the project id. e.g. 123external_id TEXT NOT NULL,diff --git a/store/migration/dev/LATEST_DATA.sql b/store/migration/dev/LATEST_DATA.sqlindex e51e0065bd..93ec5f965d 100644--- a/store/migration/dev/LATEST_DATA.sql+++ b/store/migration/dev/LATEST_DATA.sql@@ -42,6 +42,7 @@ INSERT INTOupdater_id,resource_type,resource_id,+ inherit_from_parent,type,payload)@@ -52,6 +53,7 @@ VALUES1,'ENVIRONMENT',101,+ TRUE,'bb.policy.pipeline-approval','{"value":"MANUAL_APPROVAL_NEVER"}');@@ -63,6 +65,7 @@ INSERT INTOupdater_id,resource_type,resource_id,+ inherit_from_parent,type,payload)@@ -73,6 +76,7 @@ VALUES1,'ENVIRONMENT',102,+ TRUE,'bb.policy.pipeline-approval','{"value":"MANUAL_APPROVAL_ALWAYS"}');@@ -84,6 +88,7 @@ INSERT INTOupdater_id,resource_type,resource_id,+ inherit_from_parent,type,payload)@@ -94,6 +99,7 @@ VALUES1,'ENVIRONMENT',102,+ TRUE,'bb.policy.backup-plan','{"schedule":"WEEKLY"}');diff --git a/store/migration/dev/20221118000000##flexible_policy.sql b/store/migration/prod/1.9/0000##flexible_policy.sqlsimilarity index 100%rename from store/migration/dev/20221118000000##flexible_policy.sqlrename to store/migration/prod/1.9/0000##flexible_policy.sqldiff --git a/store/migration/prod/LATEST.sql b/store/migration/prod/LATEST.sqlindex 3507279c78..1518b2c1b1 100644--- a/store/migration/prod/LATEST.sql+++ b/store/migration/prod/LATEST.sql@@ -128,6 +128,8 @@ EXECUTE FUNCTION trigger_update_updated_ts();-- Policy-- policy stores the policies for each environment.-- Policies are associated with environments. Since we may have policies not associated with environment later, we name the table policy.+CREATE TYPE resource_type AS ENUM ('WORKSPACE', 'ENVIRONMENT', 'PROJECT', 'INSTANCE', 'DATABASE');+CREATE TABLE policy (id SERIAL PRIMARY KEY,row_status row_status NOT NULL DEFAULT 'NORMAL',@@ -135,14 +137,14 @@ CREATE TABLE policy (created_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),updater_id INTEGER NOT NULL REFERENCES principal (id),updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),- environment_id INTEGER NOT NULL REFERENCES environment (id),type TEXT NOT NULL CHECK (type LIKE 'bb.policy.%'),- payload JSONB NOT NULL DEFAULT '{}'+ payload JSONB NOT NULL DEFAULT '{}',+ resource_type resource_type NOT NULL,+ resource_id INTEGER NOT NULL,+ inherit_from_parent BOOLEAN DEFAULT TRUE);-CREATE INDEX idx_policy_environment_id ON policy(environment_id);--CREATE UNIQUE INDEX idx_policy_unique_environment_id_type ON policy(environment_id, type);+CREATE UNIQUE INDEX idx_policy_unique_resource_type_resource_id_type ON policy(resource_type, resource_id, type);ALTER SEQUENCE policy_id_seq RESTART WITH 101;diff --git a/store/migration/prod/LATEST_DATA.sql b/store/migration/prod/LATEST_DATA.sqlindex 1f72a3eb4c..93ec5f965d 100644--- a/store/migration/prod/LATEST_DATA.sql+++ b/store/migration/prod/LATEST_DATA.sql@@ -35,13 +35,14 @@ VALUESALTER SEQUENCE environment_id_seq RESTART WITH 103;--- TODO(d): update policy data.INSERT INTOpolicy (id,creator_id,updater_id,- environment_id,+ resource_type,+ resource_id,+ inherit_from_parent,type,payload)@@ -50,7 +51,9 @@ VALUES101,1,1,+ 'ENVIRONMENT',101,+ TRUE,'bb.policy.pipeline-approval','{"value":"MANUAL_APPROVAL_NEVER"}');@@ -60,7 +63,9 @@ INSERT INTOid,creator_id,updater_id,- environment_id,+ resource_type,+ resource_id,+ inherit_from_parent,type,payload)@@ -69,7 +74,9 @@ VALUES102,1,1,+ 'ENVIRONMENT',102,+ TRUE,'bb.policy.pipeline-approval','{"value":"MANUAL_APPROVAL_ALWAYS"}');@@ -79,7 +86,9 @@ INSERT INTOid,creator_id,updater_id,- environment_id,+ resource_type,+ resource_id,+ inherit_from_parent,type,payload)@@ -88,7 +97,9 @@ VALUES103,1,1,+ 'ENVIRONMENT',102,+ TRUE,'bb.policy.backup-plan','{"schedule":"WEEKLY"}');diff --git a/store/pg_engine_test.go b/store/pg_engine_test.goindex 57670f6128..739be033ec 100644--- a/store/pg_engine_test.go+++ b/store/pg_engine_test.go@@ -221,5 +221,5 @@ func TestMigrationCompatibility(t *testing.T) {func TestGetCutoffVersion(t *testing.T) {releaseVersion, err := getProdCutoffVersion()require.NoError(t, err)- require.Equal(t, semver.MustParse("1.8.1"), releaseVersion)+ require.Equal(t, semver.MustParse("1.9.0"), releaseVersion)}diff --git a/store/policy.go b/store/policy.goindex 4c533de0f5..3d021b1745 100644--- a/store/policy.go+++ b/store/policy.go@@ -110,7 +110,7 @@ func (s *Store) DeletePolicy(ctx context.Context, policyDelete *api.PolicyDeleteResourceID: &policyDelete.ResourceID,Type: policyDelete.Type,}- policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)+ policyRawList, err := findPolicyImpl(ctx, tx, find)if err != nil {return errors.Wrapf(err, "failed to list policy with PolicyFind[%+v]", find)}@@ -122,7 +122,7 @@ func (s *Store) DeletePolicy(ctx context.Context, policyDelete *api.PolicyDeletereturn &common.Error{Code: common.Invalid, Err: errors.Errorf("failed to delete policy with PolicyDelete[%+v], expect 'ARCHIVED' row_status", policyDelete)}}- if err := s.deletePolicyImpl(ctx, tx, policyDelete, s.db.mode); err != nil {+ if err := s.deletePolicyImpl(ctx, tx, policyDelete); err != nil {return FormatError(err)}@@ -144,7 +144,7 @@ func (s *Store) ListPolicy(ctx context.Context, find *api.PolicyFind) ([]*api.Po}defer tx.Rollback()- policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)+ policyRawList, err := findPolicyImpl(ctx, tx, find)if err != nil {return nil, errors.Wrapf(err, "failed to list policy with PolicyFind[%+v]", find)}@@ -302,7 +302,7 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy}defer tx.Rollback()- policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)+ policyRawList, err := findPolicyImpl(ctx, tx, find)var ret *policyRawif err != nil {return nil, err@@ -338,78 +338,16 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policyreturn ret, nil}-func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind, mode common.ReleaseMode) ([]*policyRaw, error) {- if mode == common.ReleaseModeDev {- // TODO(d): handle resource type.- // 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.ResourceType; v != nil {- where, args = append(where, fmt.Sprintf("resource_type = $%d", len(args)+1)), append(args, *v)- }- if v := find.ResourceID; v != nil {- where, args = append(where, fmt.Sprintf("resource_id = $%d", len(args)+1)), append(args, *v)- }- where, args = append(where, fmt.Sprintf("type = $%d", len(args)+1)), append(args, find.Type)-- rows, err := tx.QueryContext(ctx, `- SELECT- id,- creator_id,- created_ts,- updater_id,- updated_ts,- row_status,- resource_id,- inherit_from_parent,- type,- payload- FROM policy- WHERE `+strings.Join(where, " AND "),- args...,- )- if err != nil {- return nil, FormatError(err)- }- defer rows.Close()-- // Iterate over result set and deserialize rows into policyRawList.- var policyRawList []*policyRaw- for rows.Next() {- var policyRaw policyRaw- if err := rows.Scan(- &policyRaw.ID,- &policyRaw.CreatorID,- &policyRaw.CreatedTs,- &policyRaw.UpdaterID,- &policyRaw.UpdatedTs,- &policyRaw.RowStatus,- &policyRaw.ResourceID,- &policyRaw.InheritFromParent,- &policyRaw.Type,- &policyRaw.Payload,- ); err != nil {- return nil, FormatError(err)- }-- policyRawList = append(policyRawList, &policyRaw)- }- if err := rows.Err(); err != nil {- return nil, FormatError(err)- }-- return policyRawList, nil- }-- // Build WHERE clause.+func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind) ([]*policyRaw, error) {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.ResourceType; v != nil {+ where, args = append(where, fmt.Sprintf("resource_type = $%d", len(args)+1)), append(args, *v)+ }if v := find.ResourceID; v != nil {- where, args = append(where, fmt.Sprintf("environment_id = $%d", len(args)+1)), append(args, *v)+ where, args = append(where, fmt.Sprintf("resource_id = $%d", len(args)+1)), append(args, *v)}where, args = append(where, fmt.Sprintf("type = $%d", len(args)+1)), append(args, find.Type)@@ -421,7 +359,8 @@ func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind, mode commupdater_id,updated_ts,row_status,- environment_id,+ resource_id,+ inherit_from_parent,type,payloadFROM policy@@ -445,6 +384,7 @@ func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind, mode comm&policyRaw.UpdatedTs,&policyRaw.RowStatus,&policyRaw.ResourceID,+ &policyRaw.InheritFromParent,&policyRaw.Type,&policyRaw.Payload,); err != nil {@@ -456,7 +396,6 @@ func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind, mode commif err := rows.Err(); err != nil {return nil, FormatError(err)}-return policyRawList, nil}@@ -468,7 +407,7 @@ func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (}defer tx.Rollback()- policy, err := upsertPolicyImpl(ctx, tx, upsert, s.db.mode)+ policy, err := upsertPolicyImpl(ctx, tx, upsert)if err != nil {return nil, err}@@ -481,79 +420,7 @@ func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (}// upsertPolicyImpl updates an existing policy by environment id and type.-func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert, mode common.ReleaseMode) (*policyRaw, error) {- if mode == common.ReleaseModeDev {- var set []string- if v := upsert.Payload; v != nil {- set = append(set, "payload = EXCLUDED.payload")- }- if v := upsert.RowStatus; v != nil {- set = append(set, "row_status = EXCLUDED.row_status")- }-- if len(set) == 0 {- return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("invalid policy upsert %+v", upsert)}- }-- if upsert.Payload == nil || *upsert.Payload == "" {- emptyPayload := "{}"- upsert.Payload = &emptyPayload- }- if upsert.RowStatus == nil {- rowStatus := string(api.Normal)- upsert.RowStatus = &rowStatus- }- inheritFromParent := true- if upsert.InheritFromParent != nil {- inheritFromParent = *upsert.InheritFromParent- }-- query := fmt.Sprintf(`- INSERT INTO policy (- creator_id,- updater_id,- resource_type,- resource_id,- inherit_from_parent,- type,- payload,- row_status- )- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)- ON CONFLICT(resource_type, resource_id, type) DO UPDATE SET- %s- RETURNING id, creator_id, created_ts, updater_id, updated_ts, row_status, resource_id, inherit_from_parent, type, payload- `, strings.Join(set, ","))- var policyRaw policyRaw- if err := tx.QueryRowContext(ctx, query,- upsert.UpdaterID,- upsert.UpdaterID,- upsert.ResourceType,- upsert.ResourceID,- inheritFromParent,- upsert.Type,- upsert.Payload,- upsert.RowStatus,- ).Scan(- &policyRaw.ID,- &policyRaw.CreatorID,- &policyRaw.CreatedTs,- &policyRaw.UpdaterID,- &policyRaw.UpdatedTs,- &policyRaw.RowStatus,- &policyRaw.ResourceID,- &policyRaw.InheritFromParent,- &policyRaw.Type,- &policyRaw.Payload,- ); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(query)- }- return nil, FormatError(err)- }- return &policyRaw, nil- }-+func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert) (*policyRaw, error) {var set []stringif v := upsert.Payload; v != nil {set = append(set, "payload = EXCLUDED.payload")@@ -574,26 +441,34 @@ func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert, modrowStatus := string(api.Normal)upsert.RowStatus = &rowStatus}+ inheritFromParent := true+ if upsert.InheritFromParent != nil {+ inheritFromParent = *upsert.InheritFromParent+ }query := fmt.Sprintf(`INSERT INTO policy (creator_id,updater_id,- environment_id,+ resource_type,+ resource_id,+ inherit_from_parent,type,payload,row_status)- VALUES ($1, $2, $3, $4, $5, $6)- ON CONFLICT(environment_id, type) DO UPDATE SET+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ ON CONFLICT(resource_type, resource_id, type) DO UPDATE SET%s- RETURNING id, creator_id, created_ts, updater_id, updated_ts, row_status, environment_id, type, payload+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, row_status, resource_id, inherit_from_parent, type, payload`, strings.Join(set, ","))var policyRaw policyRawif err := tx.QueryRowContext(ctx, query,upsert.UpdaterID,upsert.UpdaterID,+ upsert.ResourceType,upsert.ResourceID,+ inheritFromParent,upsert.Type,upsert.Payload,upsert.RowStatus,@@ -605,6 +480,7 @@ func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert, mod&policyRaw.UpdatedTs,&policyRaw.RowStatus,&policyRaw.ResourceID,+ &policyRaw.InheritFromParent,&policyRaw.Type,&policyRaw.Payload,); err != nil {@@ -617,25 +493,12 @@ func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert, mod}// deletePolicyImpl deletes an existing ARCHIVED policy by id and type.-func (*Store) deletePolicyImpl(ctx context.Context, tx *Tx, delete *api.PolicyDelete, mode common.ReleaseMode) error {- if mode == common.ReleaseModeDev {- if _, err := tx.ExecContext(ctx, `- DELETE FROM policy- WHERE resource_type = $1 AND resource_id = $2 AND type = $3 AND row_status = $4- `,- delete.ResourceType,- delete.ResourceID,- delete.Type,- api.Archived,- ); err != nil {- return FormatError(err)- }- return nil- }+func (*Store) deletePolicyImpl(ctx context.Context, tx *Tx, delete *api.PolicyDelete) error {if _, err := tx.ExecContext(ctx, `DELETE FROM policy- WHERE resource_id = $1 AND type = $2 AND row_status = $3+ WHERE resource_type = $1 AND resource_id = $2 AND type = $3 AND row_status = $4`,+ delete.ResourceType,delete.ResourceID,delete.Type,api.Archived,