Skip to content

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

feat: update policy table schema to support flexible resources (#3438)

Danny Xu4adda3b21e52
diff --git a/api/policy.go b/api/policy.go
index f3f28a9038..57ff3711a1 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -23,6 +23,9 @@ type BackupPlanPolicySchedule string
// EnvironmentTierValue is the value for environment tier policy.
type EnvironmentTierValue string
+// PolicyResourceType is the resource type for a policy.
+type PolicyResourceType string
+
const (
// DefaultPolicyID is the ID of the default policy.
DefaultPolicyID int = 0
@@ -57,6 +60,17 @@ const (
EnvironmentTierValueProtected EnvironmentTierValue = "PROTECTED"
// EnvironmentTierValueUnprotected is UNPROTECTED environment tier value.
EnvironmentTierValueUnprotected EnvironmentTierValue = "UNPROTECTED"
+
+ // PolicyResourceTypeWorkspace is the resource type for workspaces.
+ PolicyResourceTypeWorkspace PolicyResourceType = "WORKSPACE"
+ // PolicyResourceTypeEnvironment is the resource type for environments.
+ PolicyResourceTypeEnvironment PolicyResourceType = "ENVIRONMENT"
+ // PolicyResourceTypeProject is the resource type for projects.
+ PolicyResourceTypeProject PolicyResourceType = "PROJECT"
+ // PolicyResourceTypeInstance is the resource type for instances.
+ PolicyResourceTypeInstance PolicyResourceType = "INSTANCE"
+ // PolicyResourceTypeDatabase is the resource type for databases.
+ PolicyResourceTypeDatabase PolicyResourceType = "DATABASE"
)
var (
@@ -83,8 +97,9 @@ type Policy struct {
UpdatedTs int64 `jsonapi:"attr,updatedTs"`
// Related fields
- EnvironmentID int
- Environment *Environment `jsonapi:"relation,environment"`
+ ResourceType PolicyResourceType
+ ResourceID int
+ Environment *Environment `jsonapi:"relation,environment"`
// Domain specific fields
Type PolicyType `jsonapi:"attr,type"`
@@ -96,7 +111,8 @@ type PolicyFind struct {
ID *int
// Related fields
- EnvironmentID *int
+ ResourceType *PolicyResourceType
+ ResourceID *int
// Domain specific fields
Type *PolicyType `jsonapi:"attr,type"`
@@ -112,7 +128,8 @@ type PolicyUpsert struct {
RowStatus *string `jsonapi:"attr,rowStatus"`
// Related fields
- EnvironmentID int
+ ResourceType PolicyResourceType
+ ResourceID int
// Domain specific fields
Type PolicyType
@@ -126,7 +143,8 @@ type PolicyDelete struct {
DeleterID int
// Related fields
- EnvironmentID int
+ ResourceType PolicyResourceType
+ ResourceID int
// Domain specific fields
// Type is the policy type.
diff --git a/server/policy.go b/server/policy.go
index f917170963..bf72ca88af 100644
--- a/server/policy.go
+++ b/server/policy.go
@@ -65,7 +65,7 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid policy type: %q", pType)).SetInternal(err)
}
- policyUpsert.EnvironmentID = environmentID
+ policyUpsert.ResourceID = environmentID
policyUpsert.Type = pType
policyUpsert.UpdaterID = c.Get(getPrincipalIDContextKey()).(int)
@@ -95,9 +95,9 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
}
policyDelete := &api.PolicyDelete{
- EnvironmentID: environmentID,
- DeleterID: c.Get(getPrincipalIDContextKey()).(int),
- Type: api.PolicyType(c.QueryParam("type")),
+ ResourceID: environmentID,
+ DeleterID: c.Get(getPrincipalIDContextKey()).(int),
+ Type: api.PolicyType(c.QueryParam("type")),
}
ctx := c.Request().Context()
@@ -125,7 +125,7 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid policy type: %q", pType)).SetInternal(err)
}
policyFind.Type = &pType
- policyFind.EnvironmentID = &environmentID
+ policyFind.ResourceID = &environmentID
policy, err := s.store.GetPolicy(ctx, policyFind)
if err != nil {
diff --git a/server/sql.go b/server/sql.go
index a034f32842..e9f8eea96b 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -809,7 +809,7 @@ func (s *Server) sqlCheck(
driver *sql.DB,
) (advisor.Status, []advisor.Advice, error) {
var adviceList []advisor.Advice
- policy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &environmentID})
+ policy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{ResourceID: &environmentID})
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
adviceList = []advisor.Advice{
diff --git a/server/webhook.go b/server/webhook.go
index 90449a325c..336481c5d1 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -338,7 +338,7 @@ func (s *Server) sqlAdviceForFile(
// There may exist many databases that match the file name.
// We just need to use the first one, which has the SQL review policy and can let us take the check.
for _, database := range databases {
- policy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &database.Instance.EnvironmentID})
+ policy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{ResourceID: &database.Instance.EnvironmentID})
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
log.Debug("Cannot found SQL review policy in environment", zap.Int("Environment", database.Instance.EnvironmentID), zap.Error(err))
diff --git a/store/demo/dev/10051##policy.sql b/store/demo/dev/10051##policy.sql
index 69ddc01aed..f8b8eabb65 100644
--- a/store/demo/dev/10051##policy.sql
+++ b/store/demo/dev/10051##policy.sql
@@ -3,7 +3,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -12,6 +13,7 @@ VALUES
5101,
101,
101,
+ 'ENVIRONMENT',
5001,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_NEVER"}'
@@ -22,7 +24,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -31,6 +34,7 @@ VALUES
5102,
101,
101,
+ 'ENVIRONMENT',
5002,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_NEVER"}'
@@ -41,7 +45,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -50,6 +55,7 @@ VALUES
5103,
101,
101,
+ 'ENVIRONMENT',
5003,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_ALWAYS"}'
@@ -60,7 +66,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -69,6 +76,7 @@ VALUES
5104,
101,
101,
+ 'ENVIRONMENT',
5004,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_NEVER"}'
@@ -79,7 +87,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -88,6 +97,7 @@ VALUES
5105,
101,
101,
+ 'ENVIRONMENT',
5005,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_NEVER"}'
@@ -98,7 +108,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -107,6 +118,7 @@ VALUES
5106,
101,
101,
+ 'ENVIRONMENT',
5003,
'bb.policy.backup-plan',
'{"schedule":"WEEKLY"}'
@@ -117,7 +129,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -126,6 +139,7 @@ VALUES
5107,
101,
101,
+ 'ENVIRONMENT',
5004,
'bb.policy.backup-plan',
'{"schedule":"DAILY"}'
@@ -137,7 +151,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -146,11 +161,12 @@ VALUES
5108,
101,
101,
+ 'ENVIRONMENT',
5004,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_ALWAYS"}'
)
- ON CONFLICT(environment_id, type) DO UPDATE SET
+ ON CONFLICT(resource_type, resource_id, type) DO UPDATE SET
payload = excluded.payload;
ALTER SEQUENCE policy_id_seq RESTART WITH 5109;
diff --git a/store/migration/dev/20221118000000##flexible_policy.sql b/store/migration/dev/20221118000000##flexible_policy.sql
new file mode 100644
index 0000000000..d945d81fd6
--- /dev/null
+++ b/store/migration/dev/20221118000000##flexible_policy.sql
@@ -0,0 +1,16 @@
+CREATE TYPE resource_type AS ENUM ('WORKSPACE', 'ENVIRONMENT', 'PROJECT', 'INSTANCE', 'DATABASE');
+
+DROP INDEX idx_policy_environment_id;
+DROP INDEX idx_policy_unique_environment_id_type;
+
+ALTER TABLE policy ADD COLUMN resource_type resource_type;
+ALTER TABLE policy ADD COLUMN resource_id INTEGER;
+ALTER TABLE policy DROP CONSTRAINT policy_environment_id_fkey;
+
+UPDATE policy SET resource_type='ENVIRONMENT', resource_id=environment_id;
+
+ALTER TABLE policy ALTER COLUMN resource_type SET NOT NULL;
+ALTER TABLE policy ALTER COLUMN resource_id SET NOT NULL;
+ALTER TABLE policy DROP COLUMN environment_id;
+
+CREATE UNIQUE INDEX idx_policy_unique_resource_type_resource_id_type ON policy(resource_type, resource_id, type);
diff --git a/store/migration/dev/LATEST.sql b/store/migration/dev/LATEST.sql
index 1cc699d078..a4669a0bd1 100644
--- a/store/migration/dev/LATEST.sql
+++ b/store/migration/dev/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,13 @@ 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
);
-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/dev/LATEST_DATA.sql b/store/migration/dev/LATEST_DATA.sql
index 2f809b8d18..e51e0065bd 100644
--- a/store/migration/dev/LATEST_DATA.sql
+++ b/store/migration/dev/LATEST_DATA.sql
@@ -40,7 +40,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -49,6 +50,7 @@ VALUES
101,
1,
1,
+ 'ENVIRONMENT',
101,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_NEVER"}'
@@ -59,7 +61,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -68,6 +71,7 @@ VALUES
102,
1,
1,
+ 'ENVIRONMENT',
102,
'bb.policy.pipeline-approval',
'{"value":"MANUAL_APPROVAL_ALWAYS"}'
@@ -78,7 +82,8 @@ INSERT INTO
id,
creator_id,
updater_id,
- environment_id,
+ resource_type,
+ resource_id,
type,
payload
)
@@ -87,6 +92,7 @@ VALUES
103,
1,
1,
+ 'ENVIRONMENT',
102,
'bb.policy.backup-plan',
'{"schedule":"WEEKLY"}'
diff --git a/store/migration/prod/LATEST_DATA.sql b/store/migration/prod/LATEST_DATA.sql
index 2f809b8d18..1f72a3eb4c 100644
--- a/store/migration/prod/LATEST_DATA.sql
+++ b/store/migration/prod/LATEST_DATA.sql
@@ -35,6 +35,7 @@ VALUES
ALTER SEQUENCE environment_id_seq RESTART WITH 103;
+-- TODO(d): update policy data.
INSERT INTO
policy (
id,
diff --git a/store/policy.go b/store/policy.go
index 29976c800d..677b3c0e92 100644
--- a/store/policy.go
+++ b/store/policy.go
@@ -47,7 +47,7 @@ func (raw *policyRaw) toPolicy() *api.Policy {
UpdatedTs: raw.UpdatedTs,
// Related fields
- EnvironmentID: raw.EnvironmentID,
+ ResourceID: raw.EnvironmentID,
// Domain specific fields
Type: raw.Type,
@@ -63,7 +63,7 @@ func (s *Store) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpsert) (*ap
}
// Cache environment tier policy as it is used widely.
if upsert.Type == api.PolicyTypeEnvironmentTier {
- if err := s.cache.UpsertCache(api.TierPolicyCache, upsert.EnvironmentID, policyRaw); err != nil {
+ if err := s.cache.UpsertCache(api.TierPolicyCache, upsert.ResourceID, policyRaw); err != nil {
return nil, err
}
}
@@ -102,10 +102,10 @@ func (s *Store) DeletePolicy(ctx context.Context, policyDelete *api.PolicyDelete
defer tx.Rollback()
find := &api.PolicyFind{
- EnvironmentID: &policyDelete.EnvironmentID,
- Type: &policyDelete.Type,
+ ResourceID: &policyDelete.ResourceID,
+ Type: &policyDelete.Type,
}
- policyRawList, err := findPolicyImpl(ctx, tx, find)
+ policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)
if err != nil {
return errors.Wrapf(err, "failed to list policy with PolicyFind[%+v]", find)
}
@@ -126,7 +126,7 @@ func (s *Store) DeletePolicy(ctx context.Context, policyDelete *api.PolicyDelete
}
if policyDelete.Type == api.PolicyTypeEnvironmentTier {
- s.cache.DeleteCache(api.TierPolicyCache, policyDelete.EnvironmentID)
+ s.cache.DeleteCache(api.TierPolicyCache, policyDelete.ResourceID)
}
return nil
}
@@ -145,7 +145,7 @@ func (s *Store) ListPolicy(ctx context.Context, find *api.PolicyFind) ([]*api.Po
}
defer tx.Rollback()
- policyRawList, err := findPolicyImpl(ctx, tx, find)
+ policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)
if err != nil {
return nil, errors.Wrapf(err, "failed to list policy with PolicyFind[%+v]", find)
}
@@ -166,8 +166,8 @@ func (s *Store) ListPolicy(ctx context.Context, find *api.PolicyFind) ([]*api.Po
func (s *Store) GetBackupPlanPolicyByEnvID(ctx context.Context, environmentID int) (*api.BackupPlanPolicy, error) {
pType := api.PolicyTypeBackupPlan
policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
+ ResourceID: &environmentID,
+ Type: &pType,
})
if err != nil {
return nil, err
@@ -179,8 +179,8 @@ func (s *Store) GetBackupPlanPolicyByEnvID(ctx context.Context, environmentID in
func (s *Store) GetPipelineApprovalPolicy(ctx context.Context, environmentID int) (*api.PipelineApprovalPolicy, error) {
pType := api.PolicyTypePipelineApproval
policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
+ ResourceID: &environmentID,
+ Type: &pType,
})
if err != nil {
return nil, err
@@ -213,8 +213,8 @@ func (s *Store) GetNormalSQLReviewPolicy(ctx context.Context, find *api.PolicyFi
func (s *Store) GetSQLReviewPolicyIDByEnvID(ctx context.Context, environmentID int) (int, error) {
pType := api.PolicyTypeSQLReview
policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
+ ResourceID: &environmentID,
+ Type: &pType,
})
if err != nil {
return 0, err
@@ -232,8 +232,8 @@ func (s *Store) GetEnvironmentTierPolicyByEnvID(ctx context.Context, environment
if !ok {
pType := api.PolicyTypeEnvironmentTier
p, err := s.getPolicyRaw(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
+ ResourceID: &environmentID,
+ Type: &pType,
})
if err != nil {
return nil, err
@@ -266,7 +266,7 @@ func (s *Store) composePolicy(ctx context.Context, raw *policyRaw) (*api.Policy,
}
policy.Updater = updater
- env, err := s.GetEnvironmentByID(ctx, policy.EnvironmentID)
+ env, err := s.GetEnvironmentByID(ctx, policy.ResourceID)
if err != nil {
return nil, err
}
@@ -290,7 +290,7 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy
}
defer tx.Rollback()
- policyRawList, err := findPolicyImpl(ctx, tx, find)
+ policyRawList, err := findPolicyImpl(ctx, tx, find, s.db.mode)
var ret *policyRaw
if err != nil {
return nil, err
@@ -302,8 +302,8 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy
UpdaterID: api.SystemBotID,
Type: *find.Type,
}
- if find.EnvironmentID != nil {
- ret.EnvironmentID = *find.EnvironmentID
+ if find.ResourceID != nil {
+ ret.EnvironmentID = *find.ResourceID
}
} else if len(policyRawList) > 1 {
return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d policy with filter %+v, expect 1. ", len(policyRawList), find)}
@@ -323,13 +323,77 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy
return ret, nil
}
-func findPolicyImpl(ctx context.Context, tx *Tx, find *api.PolicyFind) ([]*policyRaw, error) {
+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)
+ }
+
+ where, args = append(where, fmt.Sprintf("resource_type = $%d", len(args)+1)), append(args, api.PolicyResourceTypeEnvironment)
+
+ if v := find.ResourceID; v != nil {
+ where, args = append(where, fmt.Sprintf("resource_id = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := find.Type; v != nil {
+ where, args = append(where, fmt.Sprintf("type = $%d", len(args)+1)), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ row_status,
+ resource_id,
+ 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.EnvironmentID,
+ &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.
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.EnvironmentID; v != nil {
+ if v := find.ResourceID; v != nil {
where, args = append(where, fmt.Sprintf("environment_id = $%d", len(args)+1)), append(args, *v)
}
if v := find.Type; v != nil {
@@ -397,7 +461,7 @@ func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (
}
defer tx.Rollback()
- policy, err := upsertPolicyImpl(ctx, tx, upsert)
+ policy, err := upsertPolicyImpl(ctx, tx, upsert, s.db.mode)
if err != nil {
return nil, err
}
@@ -410,8 +474,73 @@ 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) (*policyRaw, error) {
- // Upsert row into policy.
+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
+ }
+
+ // TODO(d): handle resource type.
+ query := fmt.Sprintf(`
+ INSERT INTO policy (
+ creator_id,
+ updater_id,
+ resource_type,
+ resource_id,
+ type,
+ payload,
+ row_status
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ 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, type, payload
+ `, strings.Join(set, ","))
+ var policyRaw policyRaw
+ if err := tx.QueryRowContext(ctx, query,
+ upsert.UpdaterID,
+ upsert.UpdaterID,
+ api.PolicyResourceTypeEnvironment,
+ upsert.ResourceID,
+ upsert.Type,
+ upsert.Payload,
+ upsert.RowStatus,
+ ).Scan(
+ &policyRaw.ID,
+ &policyRaw.CreatorID,
+ &policyRaw.CreatedTs,
+ &policyRaw.UpdaterID,
+ &policyRaw.UpdatedTs,
+ &policyRaw.RowStatus,
+ &policyRaw.EnvironmentID,
+ &policyRaw.Type,
+ &policyRaw.Payload,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return nil, FormatError(err)
+ }
+ return &policyRaw, nil
+ }
+
var set []string
if v := upsert.Payload; v != nil {
set = append(set, "payload = EXCLUDED.payload")
@@ -451,7 +580,7 @@ func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert) (*p
if err := tx.QueryRowContext(ctx, query,
upsert.UpdaterID,
upsert.UpdaterID,
- upsert.EnvironmentID,
+ upsert.ResourceID,
upsert.Type,
upsert.Payload,
upsert.RowStatus,
@@ -476,12 +605,12 @@ func upsertPolicyImpl(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert) (*p
// deletePolicyImpl deletes an existing ARCHIVED policy by id and type.
func (*Store) deletePolicyImpl(ctx context.Context, tx *Tx, delete *api.PolicyDelete) error {
- // Remove row from policy.
+ // TODO(d): handle resource type.
if _, err := tx.ExecContext(ctx, `
DELETE FROM policy
- WHERE environment_id = $1 AND type = $2 AND row_status = $3
+ WHERE resource_id = $1 AND type = $2 AND row_status = $3
`,
- delete.EnvironmentID,
+ delete.ResourceID,
delete.Type,
api.Archived,
); err != nil {
diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.go
index 0d6b311565..335ef93866 100644
--- a/tests/backup_restore_test.go
+++ b/tests/backup_restore_test.go
@@ -430,9 +430,9 @@ func setUpForPITRTest(ctx context.Context, t *testing.T, ctl *controller, port i
a.NoError(err)
str := string(buf)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeBackupPlan,
- Payload: &str,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeBackupPlan,
+ Payload: &str,
})
a.NoError(err)
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 59351f6414..75e34006e7 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -1631,9 +1631,9 @@ func TestVCS_SQL_Review(t *testing.T) {
a.NoError(err)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
})
a.NoError(err)
diff --git a/tests/sql_review_test.go b/tests/sql_review_test.go
index 6084e524ab..0470d86568 100644
--- a/tests/sql_review_test.go
+++ b/tests/sql_review_test.go
@@ -299,9 +299,9 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
a.NoError(err)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
})
a.NoError(err)
@@ -309,9 +309,9 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
a.NoError(err)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
})
a.NoError(err)
@@ -352,10 +352,10 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
// disable the SQL review policy
disable := string(api.Archived)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
- RowStatus: &disable,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
+ RowStatus: &disable,
})
a.NoError(err)
@@ -364,8 +364,8 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
// delete the SQL review policy
err = ctl.deletePolicy(api.PolicyDelete{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
})
a.NoError(err)
@@ -1025,9 +1025,9 @@ func TestSQLReviewForMySQL(t *testing.T) {
a.NoError(err)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
})
a.NoError(err)
@@ -1035,9 +1035,9 @@ func TestSQLReviewForMySQL(t *testing.T) {
a.NoError(err)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
})
a.NoError(err)
@@ -1111,10 +1111,10 @@ func TestSQLReviewForMySQL(t *testing.T) {
// disable the SQL review policy
disable := string(api.Archived)
err = ctl.upsertPolicy(api.PolicyUpsert{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
- Payload: &policyPayload,
- RowStatus: &disable,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
+ Payload: &policyPayload,
+ RowStatus: &disable,
})
a.NoError(err)
@@ -1123,8 +1123,8 @@ func TestSQLReviewForMySQL(t *testing.T) {
// delete the SQL review policy
err = ctl.deletePolicy(api.PolicyDelete{
- EnvironmentID: prodEnvironment.ID,
- Type: api.PolicyTypeSQLReview,
+ ResourceID: prodEnvironment.ID,
+ Type: api.PolicyTypeSQLReview,
})
a.NoError(err)
diff --git a/tests/tests.go b/tests/tests.go
index 9b1692c6f5..f1abeb365e 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -1554,7 +1554,7 @@ func (ctl *controller) upsertPolicy(policyUpsert api.PolicyUpsert) error {
return errors.Wrap(err, "failed to marshal policyUpsert")
}
- body, err := ctl.patch(fmt.Sprintf("/policy/environment/%d?type=%s", policyUpsert.EnvironmentID, policyUpsert.Type), buf)
+ body, err := ctl.patch(fmt.Sprintf("/policy/environment/%d?type=%s", policyUpsert.ResourceID, policyUpsert.Type), buf)
if err != nil {
return err
}
@@ -1568,7 +1568,7 @@ func (ctl *controller) upsertPolicy(policyUpsert api.PolicyUpsert) error {
// deletePolicy deletes the archived policy.
func (ctl *controller) deletePolicy(policyDelete api.PolicyDelete) error {
- _, err := ctl.delete(fmt.Sprintf("/policy/environment/%d?type=%s", policyDelete.EnvironmentID, policyDelete.Type), new(bytes.Buffer))
+ _, err := ctl.delete(fmt.Sprintf("/policy/environment/%d?type=%s", policyDelete.ResourceID, policyDelete.Type), new(bytes.Buffer))
if err != nil {
return err
}