Skip to content

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

feat: implement the CRUD in the backend for the schema review policy (#1144)

ecmadaofb536739323a
diff --git a/api/plan.go b/api/plan.go
index 017dbdbeec..c03ca8c99a 100644
--- a/api/plan.go
+++ b/api/plan.go
@@ -81,6 +81,10 @@ const (
// e.g. One can configure to NOT require backup for dev environment while require
// weekly backup for staging and daily backup for production.
FeatureBackupPolicy FeatureType = "bb.feature.backup-policy"
+ // FeatureSchemaReviewPolicy allows user to specify schema policy for the environment
+ //
+ // e.g. One can configure rules for database schema or SQL query.
+ FeatureSchemaReviewPolicy FeatureType = "bb.feature.schema-review-policy"
// Admin & Security
@@ -121,6 +125,8 @@ func (e FeatureType) String() string {
return "bb.feature.approval-policy"
case FeatureBackupPolicy:
return "bb.feature.backup-policy"
+ case FeatureSchemaReviewPolicy:
+ return "bb.feature.schema-review-policy"
case FeatureRBAC:
return "bb.feature.rbac"
case Feature3rdPartyAuth:
@@ -150,6 +156,8 @@ func (e FeatureType) Name() string {
return "Approval policy"
case FeatureBackupPolicy:
return "Backup policy"
+ case FeatureSchemaReviewPolicy:
+ return "Schema review policy"
case FeatureRBAC:
return "RBAC"
case Feature3rdPartyAuth:
@@ -187,6 +195,7 @@ var FeatureMatrix = map[FeatureType][3]bool{
"bb.feature.data-source": {false, false, false},
"bb.feature.approval-policy": {false, true, true},
"bb.feature.backup-policy": {false, true, true},
+ "bb.feature.schema-review-policy": {false, true, true},
"bb.feature.rbac": {false, true, true},
"bb.feature.3rd-party-auth": {false, true, true},
"bb.feature.branding": {false, true, true},
diff --git a/api/policy.go b/api/policy.go
index 7452db5bbb..88492aaffd 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -19,6 +19,8 @@ const (
PolicyTypePipelineApproval PolicyType = "bb.policy.pipeline-approval"
// PolicyTypeBackupPlan is the backup plan policy type.
PolicyTypeBackupPlan PolicyType = "bb.policy.backup-plan"
+ // PolicyTypeSchemaReview is the schema review policy type.
+ PolicyTypeSchemaReview PolicyType = "bb.policy.schema-review"
// PipelineApprovalValueManualNever is MANUAL_APPROVAL_NEVER approval policy value.
PipelineApprovalValueManualNever PipelineApprovalValue = "MANUAL_APPROVAL_NEVER"
@@ -38,6 +40,7 @@ var (
PolicyTypes = map[PolicyType]bool{
PolicyTypePipelineApproval: true,
PolicyTypeBackupPlan: true,
+ PolicyTypeSchemaReview: true,
}
)
@@ -81,13 +84,29 @@ type PolicyUpsert struct {
// Value is assigned from the jwt subject field passed by the client.
// CreatorID is the ID of the creator.
UpdaterID int
+ RowStatus *string `jsonapi:"attr,rowStatus"`
// Related fields
EnvironmentID int
// Domain specific fields
Type PolicyType
- Payload string `jsonapi:"attr,payload"`
+ Payload *string `jsonapi:"attr,payload"`
+}
+
+// PolicyDelete is the message to delete a policy.
+type PolicyDelete struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ DeleterID int
+
+ // Related fields
+ EnvironmentID int
+
+ // Domain specific fields
+ // Type is the policy type.
+ // Currently we only support delete operation for "bb.policy.schema-review", need it here for validation and update query.
+ Type PolicyType
}
// PipelineApprovalPolicy is the policy configuration for pipeline approval
@@ -134,6 +153,15 @@ func UnmarshalBackupPlanPolicy(payload string) (*BackupPlanPolicy, error) {
return &bp, nil
}
+// UnmarshalSchemaReviewPolicy will unmarshal payload to schema review policy.
+func UnmarshalSchemaReviewPolicy(payload string) (*SchemaReviewPolicy, error) {
+ var sr SchemaReviewPolicy
+ if err := json.Unmarshal([]byte(payload), &sr); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal schema review policy %q: %q", payload, err)
+ }
+ return &sr, nil
+}
+
// ValidatePolicy will validate the policy type and payload values.
func ValidatePolicy(pType PolicyType, payload string) error {
if !PolicyTypes[pType] {
@@ -160,6 +188,14 @@ func ValidatePolicy(pType PolicyType, payload string) error {
if bp.Schedule != BackupPlanPolicyScheduleUnset && bp.Schedule != BackupPlanPolicyScheduleDaily && bp.Schedule != BackupPlanPolicyScheduleWeekly {
return fmt.Errorf("invalid backup plan policy schedule: %q", bp.Schedule)
}
+ case PolicyTypeSchemaReview:
+ sr, err := UnmarshalSchemaReviewPolicy(payload)
+ if err != nil {
+ return err
+ }
+ if sr.Name == "" || len(sr.RuleList) == 0 {
+ return fmt.Errorf("invalid payload for schema review policy, name or rule list cannot be empty")
+ }
}
return nil
}
@@ -176,6 +212,9 @@ func GetDefaultPolicy(pType PolicyType) (string, error) {
return BackupPlanPolicy{
Schedule: BackupPlanPolicyScheduleUnset,
}.String()
+ case PolicyTypeSchemaReview:
+ // TODO(ed): we may need to define the default schema review policy payload in the PR of policy data migration.
+ return "{}", nil
}
return "", nil
}
diff --git a/api/schema_system.go b/api/schema_system.go
new file mode 100644
index 0000000000..25e836da06
--- /dev/null
+++ b/api/schema_system.go
@@ -0,0 +1,70 @@
+package api
+
+// SchemaReviewRuleLevel is the error level for schema review rule.
+type SchemaReviewRuleLevel string
+
+// SchemaReviewRuleType is the type of schema rule.
+type SchemaReviewRuleType string
+
+const (
+ // SchemaRuleLevelError is the error level of SchemaReviewRuleLevel.
+ SchemaRuleLevelError SchemaReviewRuleLevel = "ERROR"
+ // SchemaRuleLevelWarning is the warning level of SchemaReviewRuleLevel.
+ SchemaRuleLevelWarning SchemaReviewRuleLevel = "WARNING"
+ // SchemaRuleLevelDisabled is the disabled level of SchemaReviewRuleLevel.
+ SchemaRuleLevelDisabled SchemaReviewRuleLevel = "DISABLED"
+
+ // SchemaRuleMySQLEngine require InnoDB as the storage engine.
+ SchemaRuleMySQLEngine SchemaReviewRuleType = "engine.mysql.use-innodb"
+
+ // SchemaRuleTableNaming enforce the table name format.
+ SchemaRuleTableNaming SchemaReviewRuleType = "naming.table"
+ // SchemaRuleColumnNaming enforce the column name format
+ SchemaRuleColumnNaming SchemaReviewRuleType = "naming.column"
+ // SchemaRulePKNaming enforce the primary key name formaty.
+ SchemaRulePKNaming SchemaReviewRuleType = "naming.index.pk"
+ // SchemaRuleUKNaming enforce the unique key name format.
+ SchemaRuleUKNaming SchemaReviewRuleType = "naming.index.uk"
+ // SchemaRuleIDXNaming enforce the index name format.
+ SchemaRuleIDXNaming SchemaReviewRuleType = "naming.index.idx"
+
+ // SchemaRuleQueryNoSelectAll disallow 'SELECT *'.
+ SchemaRuleQueryNoSelectAll SchemaReviewRuleType = "query.select.no-select-all"
+ // SchemaRuleQueryRequireWhere require 'WHERE' clause.
+ SchemaRuleQueryRequireWhere SchemaReviewRuleType = "query.where.require"
+ // SchemaRuleQueryNoLeadingWildcardLike disallow leading '%' in LIKE, e.g. LIKE foo = '%x' is not allowed.
+ SchemaRuleQueryNoLeadingWildcardLike SchemaReviewRuleType = "query.where.no-leading-wildcard-like"
+
+ // SchemaRuleTableRequirePK require the table to have a primary key.
+ SchemaRuleTableRequirePK SchemaReviewRuleType = "table.require-pk"
+
+ // SchemaRuleRequiredColumn enforce the required columns in each table.
+ SchemaRuleRequiredColumn SchemaReviewRuleType = "column.required"
+ // SchemaRuleColumnNotNull enforce the columns cannot have NULL value.
+ SchemaRuleColumnNotNull SchemaReviewRuleType = "column.no-null"
+)
+
+// SchemaReviewPolicy is the policy configuration for schema review.
+type SchemaReviewPolicy struct {
+ Name string `json:"name"`
+ RuleList []*SchemaReviewRule `json:"ruleList"`
+}
+
+// SchemaReviewRule is the rule for schema review policy.
+type SchemaReviewRule struct {
+ Type SchemaReviewRuleType `json:"type"`
+ Level SchemaReviewRuleLevel `json:"level"`
+ // Payload is the stringify value for XXXRulePayload (e.g. NamingRulePayload, RequiredColumnRulePayload)
+ // If the rule doesn't have any payload configuration, the payload would be "{}"
+ Payload string `json:"payload"`
+}
+
+// NamingRulePayload is the payload for naming rule.
+type NamingRulePayload struct {
+ Format string `json:"format"`
+}
+
+// RequiredColumnRulePayload is the payload for required column rule.
+type RequiredColumnRulePayload struct {
+ ColumnList []string `json:"columnList"`
+}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 0745b4a722..3967c225f7 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -25,8 +25,10 @@ p, DBA, /project/{projectID}/webhook/{webhookID}/test, GET
p, DBA, /environment, POST
p, DBA, /environment, GET
p, DBA, /environment/{id}, PATCH
+p, DBA, /policy, GET
p, DBA, /policy/environment/{environmentID}, GET
p, DBA, /policy/environment/{environmentID}, PATCH
+p, DBA, /policy/environment/{environmentID}, DELETE
p, DBA, /instance, POST
p, DBA, /instance, GET
p, DBA, /instance/{id}, GET
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 3b07defb41..332bd449a2 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -23,6 +23,7 @@ p, DEVELOPER, /project/{projectID}/webhook/{webhookID}, PATCH
p, DEVELOPER, /project/{projectID}/webhook/{webhookID}, DELETE
p, DEVELOPER, /project/{projectID}/webhook/{webhookID}/test, GET
p, DEVELOPER, /environment, GET
+p, DEVELOPER, /policy, GET
p, DEVELOPER, /policy/environment/{environmentID}, GET
p, DEVELOPER, /instance, GET
p, DEVELOPER, /instance/{id}, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 66af363c4b..2152e74970 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -29,8 +29,10 @@ p, OWNER, /project/{projectID}/webhook/{webhookID}/test, GET
p, OWNER, /environment, POST
p, OWNER, /environment, GET
p, OWNER, /environment/{id}, PATCH
+p, OWNER, /policy, GET
p, OWNER, /policy/environment/{environmentID}, GET
p, OWNER, /policy/environment/{environmentID}, PATCH
+p, OWNER, /policy/environment/{environmentID}, DELETE
p, OWNER, /instance, POST
p, OWNER, /instance, GET
p, OWNER, /instance/{id}, GET
diff --git a/server/policy.go b/server/policy.go
index a79d787711..8d2f0d5d9e 100644
--- a/server/policy.go
+++ b/server/policy.go
@@ -6,6 +6,7 @@ import (
"strconv"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -13,19 +14,32 @@ import (
// hasAccessToUpdatePolicy checks if user can access to policy control feature.
// return nil if user has access.
func (s *Server) hasAccessToUpsertPolicy(policyUpsert *api.PolicyUpsert) error {
+ // nil payload means user doesn't update the payload field
+ if policyUpsert.Payload == nil {
+ return nil
+ }
+
defaultPolicy, err := api.GetDefaultPolicy(policyUpsert.Type)
if err != nil {
return err
}
+
+ if defaultPolicy == *policyUpsert.Payload {
+ return nil
+ }
switch policyUpsert.Type {
case api.PolicyTypePipelineApproval:
- if policyUpsert.Payload != defaultPolicy && !s.feature(api.FeatureApprovalPolicy) {
+ if !s.feature(api.FeatureApprovalPolicy) {
return fmt.Errorf(api.FeatureApprovalPolicy.AccessErrorMessage())
}
case api.PolicyTypeBackupPlan:
- if policyUpsert.Payload != defaultPolicy && !s.feature(api.FeatureBackupPolicy) {
+ if !s.feature(api.FeatureBackupPolicy) {
return fmt.Errorf(api.FeatureBackupPolicy.AccessErrorMessage())
}
+ case api.PolicyTypeSchemaReview:
+ if !s.feature(api.FeatureSchemaReviewPolicy) {
+ return fmt.Errorf(api.FeatureSchemaReviewPolicy.AccessErrorMessage())
+ }
}
return nil
}
@@ -57,6 +71,9 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
policy, err := s.store.UpsertPolicy(ctx, policyUpsert)
if err != nil {
+ if common.ErrorCode(err) == common.Invalid {
+ return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
+ }
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to set policy for type %q", pType)).SetInternal(err)
}
@@ -67,6 +84,31 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
return nil
})
+ g.DELETE("/policy/environment/:environmentID", func(c echo.Context) error {
+ environmentID, err := strconv.Atoi(c.Param("environmentID"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("environmentID"))).SetInternal(err)
+ }
+
+ policyDelete := &api.PolicyDelete{
+ EnvironmentID: environmentID,
+ DeleterID: c.Get(getPrincipalIDContextKey()).(int),
+ Type: api.PolicyType(c.QueryParam("type")),
+ }
+
+ ctx := c.Request().Context()
+ if err := s.store.DeletePolicy(ctx, policyDelete); err != nil {
+ if common.ErrorCode(err) == common.Invalid {
+ return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete policy by environment ID %d", environmentID)).SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ c.Response().WriteHeader(http.StatusOK)
+ return nil
+ })
+
g.GET("/policy/environment/:environmentID", func(c echo.Context) error {
ctx := c.Request().Context()
environmentID, err := strconv.Atoi(c.Param("environmentID"))
@@ -92,4 +134,27 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
}
return nil
})
+
+ g.GET("/policy", func(c echo.Context) error {
+ pType := api.PolicyType(c.QueryParam("type"))
+ if err := api.ValidatePolicy(pType, ""); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid policy type: %q", pType)).SetInternal(err)
+ }
+
+ policyFind := &api.PolicyFind{
+ Type: &pType,
+ }
+
+ ctx := c.Request().Context()
+ policyList, err := s.store.ListPolicy(ctx, policyFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to list policy for type %q", pType)).SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, policyList); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal list policy response: %v", pType)).SetInternal(err)
+ }
+ return nil
+ })
}
diff --git a/store/policy.go b/store/policy.go
index bbd540461f..c43fbb2209 100644
--- a/store/policy.go
+++ b/store/policy.go
@@ -78,6 +78,78 @@ func (s *Store) GetPolicy(ctx context.Context, find *api.PolicyFind) (*api.Polic
return policy, nil
}
+// DeletePolicy deletes an existing ARCHIVED policy by PolicyDelete.
+func (s *Store) DeletePolicy(ctx context.Context, delete *api.PolicyDelete) error {
+ // Validate policy.
+ // Currently we only support PolicyTypeSchemaReview type policy to delete by id
+ if delete.Type != api.PolicyTypeSchemaReview {
+ return &common.Error{Code: common.Invalid, Err: fmt.Errorf("Invalid policy type")}
+ }
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return FormatError(err)
+ }
+ defer tx.PTx.Rollback()
+
+ find := &api.PolicyFind{
+ EnvironmentID: &delete.EnvironmentID,
+ Type: &delete.Type,
+ }
+ policyRawList, err := findPolicyImpl(ctx, tx.PTx, find)
+ if err != nil {
+ return fmt.Errorf("Failed to list policy with PolicyFind[%+v], error[%w]", find, err)
+ }
+ if len(policyRawList) != 1 {
+ return &common.Error{Code: common.NotFound, Err: fmt.Errorf("Failed to found policy with filter %+v, expect 1. ", find)}
+ }
+ policyRaw := policyRawList[0]
+ if policyRaw.RowStatus != api.Archived {
+ return &common.Error{Code: common.Invalid, Err: fmt.Errorf("Failed to delete policy with PolicyDelete[%+v], expect 'ARCHIVED' row_status", delete)}
+ }
+
+ if err := deletePolicyImpl(ctx, tx.PTx, delete); err != nil {
+ return FormatError(err)
+ }
+
+ if err := tx.PTx.Commit(); err != nil {
+ return FormatError(err)
+ }
+
+ return nil
+}
+
+// ListPolicy gets a list of policy by PolicyFind.
+func (s *Store) ListPolicy(ctx context.Context, find *api.PolicyFind) ([]*api.Policy, error) {
+ // Validate policy type existence.
+ if find.Type != nil && *find.Type != "" {
+ if err := api.ValidatePolicy(*find.Type, ""); err != nil {
+ return nil, &common.Error{Code: common.Invalid, Err: err}
+ }
+ }
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.PTx.Rollback()
+
+ policyRawList, err := findPolicyImpl(ctx, tx.PTx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to list policy with PolicyFind[%+v], error[%w]", find, err)
+ }
+
+ policyList := []*api.Policy{}
+ for _, raw := range policyRawList {
+ policy, err := s.composePolicy(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose policy with policyRaw[%+v], error[%w]", raw, err)
+ }
+ policyList = append(policyList, policy)
+ }
+
+ return policyList, nil
+}
+
// GetBackupPlanPolicyByEnvID will get the backup plan policy for an environment.
func (s *Store) GetBackupPlanPolicyByEnvID(ctx context.Context, environmentID int) (*api.BackupPlanPolicy, error) {
pType := api.PolicyTypeBackupPlan
@@ -147,7 +219,7 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy
}
defer tx.PTx.Rollback()
- policyRawList, err := s.findPolicyImpl(ctx, tx.PTx, find)
+ policyRawList, err := findPolicyImpl(ctx, tx.PTx, find)
var ret *policyRaw
if err != nil {
return nil, err
@@ -177,7 +249,7 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policy
return ret, nil
}
-func (s *Store) findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.PolicyFind) ([]*policyRaw, error) {
+func findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.PolicyFind) ([]*policyRaw, error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
@@ -197,6 +269,7 @@ func (s *Store) findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.Policy
created_ts,
updater_id,
updated_ts,
+ row_status,
environment_id,
type,
payload
@@ -219,6 +292,7 @@ func (s *Store) findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.Policy
&policyRaw.CreatedTs,
&policyRaw.UpdaterID,
&policyRaw.UpdatedTs,
+ &policyRaw.RowStatus,
&policyRaw.EnvironmentID,
&policyRaw.Type,
&policyRaw.Payload,
@@ -238,8 +312,8 @@ func (s *Store) findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.Policy
// upsertPolicyRaw sets a policy for an environment.
func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (*policyRaw, error) {
// Validate policy.
- if upsert.Type != "" {
- if err := api.ValidatePolicy(upsert.Type, upsert.Payload); err != nil {
+ if upsert.Type != "" && upsert.Payload != nil {
+ if err := api.ValidatePolicy(upsert.Type, *upsert.Payload); err != nil {
return nil, &common.Error{Code: common.Invalid, Err: err}
}
}
@@ -249,7 +323,7 @@ func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (
}
defer tx.PTx.Rollback()
- policy, err := s.upsertPolicyImpl(ctx, tx.PTx, upsert)
+ policy, err := upsertPolicyImpl(ctx, tx.PTx, upsert)
if err != nil {
return nil, err
}
@@ -261,30 +335,50 @@ func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (
return policy, nil
}
-// upsertPolicyImpl updates an existing policy.
-func (s *Store) upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.PolicyUpsert) (*policyRaw, error) {
+// upsertPolicyImpl updates an existing policy by environment id and type.
+func upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.PolicyUpsert) (*policyRaw, error) {
// Upsert row into policy.
- if upsert.Payload == "" {
- upsert.Payload = "{}"
+ var set []string
+ if v := upsert.Payload; v != nil {
+ set = append(set, "payload = EXCLUDED.payload")
}
- row, err := tx.QueryContext(ctx, `
+ 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: fmt.Errorf("invalid policy upsert %+v", upsert)}
+ }
+
+ if upsert.Payload == nil || *upsert.Payload == "" {
+ emptyPayload := "{}"
+ upsert.Payload = &emptyPayload
+ }
+ if upsert.RowStatus == nil {
+ rowStatus := api.Normal.String()
+ upsert.RowStatus = &rowStatus
+ }
+
+ row, err := tx.QueryContext(ctx, fmt.Sprintf(`
INSERT INTO policy (
creator_id,
updater_id,
environment_id,
type,
- payload
+ payload,
+ row_status
)
- VALUES ($1, $2, $3, $4, $5)
+ VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT(environment_id, type) DO UPDATE SET
- payload = excluded.payload
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, environment_id, type, payload
- `,
+ %s
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, row_status, environment_id, type, payload
+ `, strings.Join(set, ",")),
upsert.UpdaterID,
upsert.UpdaterID,
upsert.EnvironmentID,
upsert.Type,
upsert.Payload,
+ upsert.RowStatus,
)
if err != nil {
@@ -300,6 +394,7 @@ func (s *Store) upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.Po
&policyRaw.CreatedTs,
&policyRaw.UpdaterID,
&policyRaw.UpdatedTs,
+ &policyRaw.RowStatus,
&policyRaw.EnvironmentID,
&policyRaw.Type,
&policyRaw.Payload,
@@ -309,3 +404,19 @@ func (s *Store) upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.Po
return &policyRaw, nil
}
+
+// deletePolicyImpl deletes an existing ARCHIVED policy by id and type.
+func deletePolicyImpl(ctx context.Context, tx *sql.Tx, delete *api.PolicyDelete) error {
+ // Remove row from policy.
+ if _, err := tx.ExecContext(ctx, `
+ DELETE FROM policy
+ WHERE environment_id = $1 AND type = $2 AND row_status = $3
+ `,
+ delete.EnvironmentID,
+ delete.Type,
+ api.Archived,
+ ); err != nil {
+ return FormatError(err)
+ }
+ return nil
+}