Skip to content

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

feat: review config backend (#12418)

ecmadaobef735dc17fa
diff --git a/backend/api/v1/acl_iam.go b/backend/api/v1/acl_iam.go
index 478b641d6e..3a32cec90a 100644
--- a/backend/api/v1/acl_iam.go
+++ b/backend/api/v1/acl_iam.go
@@ -78,7 +78,13 @@ func isSkippedMethod(fullMethod string) bool {
v1pb.SQLService_GenerateRestoreSQL_FullMethodName,
v1pb.SubscriptionService_GetSubscription_FullMethodName,
v1pb.SubscriptionService_GetFeatureMatrix_FullMethodName,
- v1pb.SubscriptionService_UpdateSubscription_FullMethodName:
+ v1pb.SubscriptionService_UpdateSubscription_FullMethodName,
+ // TODO(p0ny): permission for review config service.
+ v1pb.ReviewConfigService_CreateReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_ListReviewConfigs_FullMethodName,
+ v1pb.ReviewConfigService_GetReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_UpdateReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_DeleteReviewConfig_FullMethodName:
return true
// skip checking for sheet service because we want to
// discriminate bytebase artifact sheets and user sheets first.
diff --git a/backend/api/v1/ctx.go b/backend/api/v1/ctx.go
index 0d6b5443d6..7176216d0e 100644
--- a/backend/api/v1/ctx.go
+++ b/backend/api/v1/ctx.go
@@ -93,6 +93,11 @@ func (p *ContextProvider) do(ctx context.Context, fullMethod string, req any) ([
v1pb.OrgPolicyService_CreatePolicy_FullMethodName,
v1pb.OrgPolicyService_UpdatePolicy_FullMethodName,
v1pb.OrgPolicyService_DeletePolicy_FullMethodName,
+ v1pb.ReviewConfigService_CreateReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_ListReviewConfigs_FullMethodName,
+ v1pb.ReviewConfigService_GetReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_UpdateReviewConfig_FullMethodName,
+ v1pb.ReviewConfigService_DeleteReviewConfig_FullMethodName,
v1pb.IdentityProviderService_GetIdentityProvider_FullMethodName,
v1pb.IdentityProviderService_CreateIdentityProvider_FullMethodName,
v1pb.IdentityProviderService_UpdateIdentityProvider_FullMethodName,
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 623d54777b..39846c5eff 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -1835,10 +1835,10 @@ func (s *DatabaseService) convertToDatabase(ctx context.Context, database *store
}
environment, effectiveEnvironment := "", ""
if database.EnvironmentID != "" {
- environment = fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, database.EnvironmentID)
+ environment = common.FormatEnvironment(database.EnvironmentID)
}
if database.EffectiveEnvironmentID != "" {
- effectiveEnvironment = fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, database.EffectiveEnvironmentID)
+ effectiveEnvironment = common.FormatEnvironment(database.EffectiveEnvironmentID)
}
instanceResource, err := convertToInstanceResource(instance)
if err != nil {
diff --git a/backend/api/v1/environment_service.go b/backend/api/v1/environment_service.go
index 9da5e2d79b..999d00f10c 100644
--- a/backend/api/v1/environment_service.go
+++ b/backend/api/v1/environment_service.go
@@ -225,7 +225,7 @@ func convertToEnvironment(environment *store.EnvironmentMessage) *v1pb.Environme
tier = v1pb.EnvironmentTier_PROTECTED
}
return &v1pb.Environment{
- Name: fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, environment.ResourceID),
+ Name: common.FormatEnvironment(environment.ResourceID),
Uid: fmt.Sprintf("%d", environment.UID),
State: convertDeletedToState(environment.Deleted),
Title: environment.Title,
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index 35067958fa..33c16fbf67 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -17,7 +17,6 @@ import (
"github.com/bytebase/bytebase/backend/common/log"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
- "github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -437,7 +436,7 @@ func (s *OrgPolicyService) getPolicyParentPath(ctx context.Context, policyMessag
if err != nil {
return "", err
}
- return fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, env.ResourceID), nil
+ return common.FormatEnvironment(env.ResourceID), nil
case api.PolicyResourceTypeProject:
proj, err := s.findActiveProject(ctx, &store.FindProjectMessage{
UID: &policyMessage.ResourceUID,
@@ -445,7 +444,7 @@ func (s *OrgPolicyService) getPolicyParentPath(ctx context.Context, policyMessag
if err != nil {
return "", err
}
- return fmt.Sprintf("%s%s", common.ProjectNamePrefix, proj.ResourceID), nil
+ return common.FormatProject(proj.ResourceID), nil
case api.PolicyResourceTypeInstance:
ins, err := s.findActiveInstance(ctx, &store.FindInstanceMessage{
UID: &policyMessage.ResourceUID,
@@ -453,7 +452,7 @@ func (s *OrgPolicyService) getPolicyParentPath(ctx context.Context, policyMessag
if err != nil {
return "", err
}
- return fmt.Sprintf("%s%s", common.InstanceNamePrefix, ins.ResourceID), nil
+ return common.FormatInstance(ins.ResourceID), nil
case api.PolicyResourceTypeDatabase:
db, err := s.findActiveDatabase(ctx, &store.FindDatabaseMessage{
UID: &policyMessage.ResourceUID,
@@ -461,7 +460,7 @@ func (s *OrgPolicyService) getPolicyParentPath(ctx context.Context, policyMessag
if err != nil {
return "", err
}
- return fmt.Sprintf("%s%s/%s%s", common.InstanceNamePrefix, db.InstanceID, common.DatabaseIDPrefix, db.DatabaseName), nil
+ return common.FormatDatabase(db.InstanceID, db.DatabaseName), nil
default:
return "", nil
}
@@ -547,11 +546,15 @@ func (s *OrgPolicyService) convertPolicyPayloadToString(ctx context.Context, pol
}
return string(payloadBytes), nil
case v1pb.PolicyType_SQL_REVIEW:
+ // TODO(ed): remove PolicyType_SQL_REVIEW
if err := s.licenseService.IsFeatureEnabled(api.FeatureSQLReview); err != nil {
return "", status.Errorf(codes.PermissionDenied, err.Error())
}
v1SqlReviewPolicy := policy.GetSqlReviewPolicy()
- if err := validateSQLReviewPolicy(v1SqlReviewPolicy); err != nil {
+ if v1SqlReviewPolicy.Name == "" {
+ return "", status.Errorf(codes.InvalidArgument, "invalid payload, name cannot be empty")
+ }
+ if err := validateSQLReviewRules(v1SqlReviewPolicy.Rules); err != nil {
return "", status.Errorf(codes.InvalidArgument, err.Error())
}
payload, err := convertToSQLReviewPolicyPayload(v1SqlReviewPolicy)
@@ -560,7 +563,16 @@ func (s *OrgPolicyService) convertPolicyPayloadToString(ctx context.Context, pol
}
payloadBytes, err := protojson.Marshal(payload)
if err != nil {
- return "", status.Errorf(codes.Internal, "failed to marshal sql review policy with error: %v", err)
+ return "", errors.Wrap(err, "failed to marshal sql review policy")
+ }
+ return string(payloadBytes), nil
+ case v1pb.PolicyType_TAG:
+ tagPolicy := &storepb.TagPolicy{
+ Tags: policy.GetTagPolicy().Tags,
+ }
+ payloadBytes, err := protojson.Marshal(tagPolicy)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal tag policy")
}
return string(payloadBytes), nil
case v1pb.PolicyType_MASKING:
@@ -669,6 +681,15 @@ func (s *OrgPolicyService) convertToPolicy(ctx context.Context, parentPath strin
return nil, err
}
policy.Policy = payload
+ case api.PolicyTypeTag:
+ pType = v1pb.PolicyType_TAG
+ p := &v1pb.TagPolicy{}
+ if err := protojson.Unmarshal([]byte(policyMessage.Payload), p); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal rollout policy payload")
+ }
+ policy.Policy = &v1pb.Policy_TagPolicy{
+ TagPolicy: p,
+ }
case api.PolicyTypeMasking:
pType = v1pb.PolicyType_MASKING
payload, err := convertToV1PBMaskingPolicy(policyMessage.Payload)
@@ -740,8 +761,17 @@ func convertToV1PBSQLReviewPolicy(payloadStr string) (*v1pb.Policy_SqlReviewPoli
return nil, err
}
+ return &v1pb.Policy_SqlReviewPolicy{
+ SqlReviewPolicy: &v1pb.SQLReviewPolicy{
+ Name: p.Name,
+ Rules: convertToV1PBSQLReviewRules(p.RuleList),
+ },
+ }, nil
+}
+
+func convertToV1PBSQLReviewRules(ruleList []*storepb.SQLReviewRule) []*v1pb.SQLReviewRule {
var rules []*v1pb.SQLReviewRule
- for _, rule := range p.RuleList {
+ for _, rule := range ruleList {
level := v1pb.SQLReviewRuleLevel_LEVEL_UNSPECIFIED
switch rule.Level {
case storepb.SQLReviewRuleLevel_ERROR:
@@ -760,17 +790,12 @@ func convertToV1PBSQLReviewPolicy(payloadStr string) (*v1pb.Policy_SqlReviewPoli
})
}
- return &v1pb.Policy_SqlReviewPolicy{
- SqlReviewPolicy: &v1pb.SQLReviewPolicy{
- Name: p.Name,
- Rules: rules,
- },
- }, nil
+ return rules
}
-func convertToSQLReviewPolicyPayload(policy *v1pb.SQLReviewPolicy) (*storepb.SQLReviewPolicy, error) {
+func convertToSQLReviewRules(rules []*v1pb.SQLReviewRule) ([]*storepb.SQLReviewRule, error) {
var ruleList []*storepb.SQLReviewRule
- for _, rule := range policy.Rules {
+ for _, rule := range rules {
var level storepb.SQLReviewRuleLevel
switch rule.Level {
case v1pb.SQLReviewRuleLevel_ERROR:
@@ -791,6 +816,14 @@ func convertToSQLReviewPolicyPayload(policy *v1pb.SQLReviewPolicy) (*storepb.SQL
})
}
+ return ruleList, nil
+}
+
+func convertToSQLReviewPolicyPayload(policy *v1pb.SQLReviewPolicy) (*storepb.SQLReviewPolicy, error) {
+ ruleList, err := convertToSQLReviewRules(policy.Rules)
+ if err != nil {
+ return nil, err
+ }
return &storepb.SQLReviewPolicy{
Name: policy.Name,
RuleList: ruleList,
@@ -1091,7 +1124,10 @@ func convertPolicyType(pType string) (api.PolicyType, error) {
case v1pb.PolicyType_ROLLOUT_POLICY.String():
return api.PolicyTypeRollout, nil
case v1pb.PolicyType_SQL_REVIEW.String():
+ // TODO(ed): remove this.
return api.PolicyTypeSQLReview, nil
+ case v1pb.PolicyType_TAG.String():
+ return api.PolicyTypeTag, nil
case v1pb.PolicyType_MASKING.String():
return api.PolicyTypeMasking, nil
case v1pb.PolicyType_MASKING_RULE.String():
@@ -1107,46 +1143,3 @@ func convertPolicyType(pType string) (api.PolicyType, error) {
}
return policyType, errors.Errorf("invalid policy type %v", pType)
}
-
-// validateSQLReviewPolicy validates the SQL review rule.
-func validateSQLReviewPolicy(policy *v1pb.SQLReviewPolicy) error {
- if policy.Name == "" || len(policy.Rules) == 0 {
- return errors.Errorf("invalid payload, name or rule list cannot be empty")
- }
- for _, rule := range policy.Rules {
- ruleType := advisor.SQLReviewRuleType(rule.Type)
- // TODO(rebelice): add other SQL review rule validation.
- switch ruleType {
- case advisor.SchemaRuleTableNaming, advisor.SchemaRuleColumnNaming, advisor.SchemaRuleAutoIncrementColumnNaming:
- if _, _, err := advisor.UnmarshalNamingRulePayloadAsRegexp(rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleFKNaming, advisor.SchemaRuleIDXNaming, advisor.SchemaRuleUKNaming:
- if _, _, _, err := advisor.UnmarshalNamingRulePayloadAsTemplate(ruleType, rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleRequiredColumn:
- if _, err := advisor.UnmarshalRequiredColumnList(rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleColumnCommentConvention, advisor.SchemaRuleTableCommentConvention:
- if _, err := advisor.UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleIndexKeyNumberLimit, advisor.SchemaRuleStatementInsertRowLimit, advisor.SchemaRuleIndexTotalNumberLimit,
- advisor.SchemaRuleColumnMaximumCharacterLength, advisor.SchemaRuleColumnMaximumVarcharLength, advisor.SchemaRuleColumnAutoIncrementInitialValue, advisor.SchemaRuleStatementAffectedRowLimit:
- if _, err := advisor.UnmarshalNumberTypeRulePayload(rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleColumnTypeDisallowList, advisor.SchemaRuleCharsetAllowlist, advisor.SchemaRuleCollationAllowlist, advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist:
- if _, err := advisor.UnmarshalStringArrayTypeRulePayload(rule.Payload); err != nil {
- return err
- }
- case advisor.SchemaRuleIdentifierCase:
- if _, err := advisor.UnmarshalNamingCaseRulePayload(rule.Payload); err != nil {
- return err
- }
- }
- }
- return nil
-}
diff --git a/backend/api/v1/review_config_service.go b/backend/api/v1/review_config_service.go
new file mode 100644
index 0000000000..bd9ef7257b
--- /dev/null
+++ b/backend/api/v1/review_config_service.go
@@ -0,0 +1,273 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/types/known/emptypb"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
+ api "github.com/bytebase/bytebase/backend/legacyapi"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/store"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+// ReviewConfigService implements the review config service.
+type ReviewConfigService struct {
+ v1pb.UnimplementedReviewConfigServiceServer
+ store *store.Store
+ licenseService enterprise.LicenseService
+}
+
+// NewReviewConfigService creates a new ReviewConfigService.
+func NewReviewConfigService(store *store.Store, licenseService enterprise.LicenseService) *ReviewConfigService {
+ return &ReviewConfigService{
+ store: store,
+ licenseService: licenseService,
+ }
+}
+
+// CreateReviewConfig creates a new review config.
+func (s *ReviewConfigService) CreateReviewConfig(ctx context.Context, request *v1pb.CreateReviewConfigRequest) (*v1pb.ReviewConfig, error) {
+ if err := s.licenseService.IsFeatureEnabled(api.FeatureSQLReview); err != nil {
+ return nil, status.Errorf(codes.PermissionDenied, err.Error())
+ }
+ if err := validateSQLReviewRules(request.ReviewConfig.Rules); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ reviewConfigMessage, err := convertToReviewConfigMessage(request.ReviewConfig)
+ if err != nil {
+ return nil, err
+ }
+
+ principalID, ok := ctx.Value(common.PrincipalIDContextKey).(int)
+ if !ok {
+ return nil, status.Errorf(codes.Internal, "principal ID not found")
+ }
+
+ reviewConfigMessage.CreatorUID = principalID
+ created, err := s.store.CreateReviewConfig(ctx, reviewConfigMessage)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return s.convertToV1ReviewConfig(ctx, created)
+}
+
+// ListReviewConfigs lists the review configs.
+func (s *ReviewConfigService) ListReviewConfigs(ctx context.Context, _ *v1pb.ListReviewConfigsRequest) (*v1pb.ListReviewConfigsResponse, error) {
+ messages, err := s.store.ListReviewConfigs(ctx, &store.FindReviewConfigMessage{})
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ response := &v1pb.ListReviewConfigsResponse{}
+ for _, message := range messages {
+ sqlReview, err := s.convertToV1ReviewConfig(ctx, message)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ response.ReviewConfigs = append(response.ReviewConfigs, sqlReview)
+ }
+ return response, nil
+}
+
+// GetReviewConfig gets the review config.
+func (s *ReviewConfigService) GetReviewConfig(ctx context.Context, request *v1pb.GetReviewConfigRequest) (*v1pb.ReviewConfig, error) {
+ id, err := common.GetReviewConfigID(request.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ message, err := s.store.GetReviewConfig(ctx, id)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return s.convertToV1ReviewConfig(ctx, message)
+}
+
+// UpdateReviewConfig updates the review config.
+func (s *ReviewConfigService) UpdateReviewConfig(ctx context.Context, request *v1pb.UpdateReviewConfigRequest) (*v1pb.ReviewConfig, error) {
+ id, err := common.GetReviewConfigID(request.ReviewConfig.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ principalID, ok := ctx.Value(common.PrincipalIDContextKey).(int)
+ if !ok {
+ return nil, status.Errorf(codes.Internal, "principal ID not found")
+ }
+
+ patch := &store.PatchReviewConfigMessage{
+ ID: id,
+ UpdaterID: principalID,
+ }
+
+ for _, path := range request.UpdateMask.Paths {
+ switch path {
+ case "title":
+ patch.Name = &request.ReviewConfig.Title
+ case "payload":
+ ruleList, err := convertToSQLReviewRules(request.ReviewConfig.Rules)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to convert rules, error %v", err)
+ }
+ patch.Payload = &storepb.ReviewConfigPayload{
+ SqlReviewRules: ruleList,
+ }
+ case "enabled":
+ patch.Enforce = &request.ReviewConfig.Enabled
+ default:
+ return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid update mask path %q", path))
+ }
+ }
+
+ message, err := s.store.UpdateReviewConfig(ctx, patch)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return s.convertToV1ReviewConfig(ctx, message)
+}
+
+// DeleteReviewConfig deletes the review config.
+func (s *ReviewConfigService) DeleteReviewConfig(ctx context.Context, request *v1pb.DeleteReviewConfigRequest) (*emptypb.Empty, error) {
+ id, err := common.GetReviewConfigID(request.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ if err := s.store.DeleteReviewConfig(ctx, id); err != nil {
+ return nil, status.Errorf(codes.Internal, fmt.Sprintf("failed to delete review config: %v", err))
+ }
+
+ return &emptypb.Empty{}, nil
+}
+
+func convertToReviewConfigMessage(reviewConfig *v1pb.ReviewConfig) (*store.ReviewConfigMessage, error) {
+ ruleList, err := convertToSQLReviewRules(reviewConfig.Rules)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to convert rules, error %v", err)
+ }
+
+ id, err := common.GetReviewConfigID(reviewConfig.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid config name %s, error %v", reviewConfig.Name, err)
+ }
+
+ if !isValidResourceID(id) {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid config id %v", reviewConfig.Name)
+ }
+
+ return &store.ReviewConfigMessage{
+ ID: id,
+ Name: reviewConfig.Title,
+ Enforce: reviewConfig.Enabled,
+ Payload: &storepb.ReviewConfigPayload{
+ SqlReviewRules: ruleList,
+ },
+ }, nil
+}
+
+func (s *ReviewConfigService) convertToV1ReviewConfig(ctx context.Context, reviewConfigMessage *store.ReviewConfigMessage) (*v1pb.ReviewConfig, error) {
+ creator, err := s.store.GetUserByID(ctx, reviewConfigMessage.CreatorUID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get creator, error %v", err)
+ }
+ if creator == nil {
+ return nil, status.Errorf(codes.NotFound, "creator %d not found", reviewConfigMessage.CreatorUID)
+ }
+
+ resourceType := api.PolicyResourceTypeEnvironment
+ policyType := api.PolicyTypeTag
+ tagPolicies, err := s.store.ListPoliciesV2(ctx, &store.FindPolicyMessage{
+ ResourceType: &resourceType,
+ Type: &policyType,
+ ShowDeleted: false,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to list tag policy, error %v", err)
+ }
+
+ config := &v1pb.ReviewConfig{
+ Name: common.FormatReviewConfig(reviewConfigMessage.ID),
+ Creator: common.FormatUserEmail(creator.Email),
+ CreateTime: timestamppb.New(reviewConfigMessage.CreatedTime),
+ UpdateTime: timestamppb.New(reviewConfigMessage.CreatedTime),
+ Title: reviewConfigMessage.Name,
+ Enabled: reviewConfigMessage.Enforce,
+ Rules: convertToV1PBSQLReviewRules(reviewConfigMessage.Payload.SqlReviewRules),
+ }
+
+ for _, policy := range tagPolicies {
+ p := &v1pb.TagPolicy{}
+ if err := protojson.Unmarshal([]byte(policy.Payload), p); err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to unmarshal tag policy, error %v", err)
+ }
+ if p.Tags[string(api.ReservedTagReviewConfig)] != config.Name {
+ continue
+ }
+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{
+ UID: &policy.ResourceUID,
+ ShowDeleted: false,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get environment %d with error: %v", policy.ResourceUID, err)
+ }
+ if environment == nil {
+ continue
+ }
+ config.Resources = append(config.Resources, common.FormatEnvironment(environment.ResourceID))
+ }
+
+ return config, nil
+}
+
+// validateSQLReviewRules validates the SQL review rule.
+func validateSQLReviewRules(rules []*v1pb.SQLReviewRule) error {
+ if len(rules) == 0 {
+ return errors.Errorf("invalid payload, rule list cannot be empty")
+ }
+ for _, rule := range rules {
+ ruleType := advisor.SQLReviewRuleType(rule.Type)
+ // TODO(rebelice): add other SQL review rule validation.
+ switch ruleType {
+ case advisor.SchemaRuleTableNaming, advisor.SchemaRuleColumnNaming, advisor.SchemaRuleAutoIncrementColumnNaming:
+ if _, _, err := advisor.UnmarshalNamingRulePayloadAsRegexp(rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleFKNaming, advisor.SchemaRuleIDXNaming, advisor.SchemaRuleUKNaming:
+ if _, _, _, err := advisor.UnmarshalNamingRulePayloadAsTemplate(ruleType, rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleRequiredColumn:
+ if _, err := advisor.UnmarshalRequiredColumnList(rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleColumnCommentConvention, advisor.SchemaRuleTableCommentConvention:
+ if _, err := advisor.UnmarshalCommentConventionRulePayload(rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleIndexKeyNumberLimit, advisor.SchemaRuleStatementInsertRowLimit, advisor.SchemaRuleIndexTotalNumberLimit,
+ advisor.SchemaRuleColumnMaximumCharacterLength, advisor.SchemaRuleColumnMaximumVarcharLength, advisor.SchemaRuleColumnAutoIncrementInitialValue, advisor.SchemaRuleStatementAffectedRowLimit:
+ if _, err := advisor.UnmarshalNumberTypeRulePayload(rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleColumnTypeDisallowList, advisor.SchemaRuleCharsetAllowlist, advisor.SchemaRuleCollationAllowlist, advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist:
+ if _, err := advisor.UnmarshalStringArrayTypeRulePayload(rule.Payload); err != nil {
+ return err
+ }
+ case advisor.SchemaRuleIdentifierCase:
+ if _, err := advisor.UnmarshalNamingCaseRulePayload(rule.Payload); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/backend/api/v1/rollout_service_converter.go b/backend/api/v1/rollout_service_converter.go
index 7a1ebfd37c..3c85fdeeeb 100644
--- a/backend/api/v1/rollout_service_converter.go
+++ b/backend/api/v1/rollout_service_converter.go
@@ -619,7 +619,7 @@ func convertToTaskFromDatabaseCreate(ctx context.Context, s *store.Store, projec
Status: convertToTaskStatus(task.LatestTaskRunStatus, payload.Skipped),
SkippedReason: payload.SkippedReason,
DependsOnTasks: nil,
- Target: fmt.Sprintf("%s%s", common.InstanceNamePrefix, instance.ResourceID),
+ Target: common.FormatInstance(instance.ResourceID),
Payload: &v1pb.Task_DatabaseCreate_{
DatabaseCreate: &v1pb.Task_DatabaseCreate{
Project: "",
@@ -628,7 +628,7 @@ func convertToTaskFromDatabaseCreate(ctx context.Context, s *store.Store, projec
Sheet: getResourceNameForSheet(project, payload.SheetID),
CharacterSet: payload.CharacterSet,
Collation: payload.Collation,
- Environment: fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, payload.EnvironmentID),
+ Environment: common.FormatEnvironment(payload.EnvironmentID),
Labels: labels,
},
},
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 541642e6d0..d4fc47a4c0 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1322,7 +1322,7 @@ func (s *SQLService) sqlCheck(
currentDatabase string,
) (storepb.Advice_Status, []*storepb.Advice, error) {
var adviceList []*storepb.Advice
- policy, err := s.store.GetSQLReviewPolicy(ctx, environmentID)
+ reviewConfig, err := s.store.GetReviewConfigByEnvironment(ctx, environmentID)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
return storepb.Advice_SUCCESS, nil, nil
@@ -1330,7 +1330,7 @@ func (s *SQLService) sqlCheck(
return storepb.Advice_ERROR, nil, err
}
- res, err := advisor.SQLReviewCheck(s.sheetManager, statement, policy.RuleList, advisor.SQLReviewCheckContext{
+ res, err := advisor.SQLReviewCheck(s.sheetManager, statement, reviewConfig.SqlReviewRules, advisor.SQLReviewCheckContext{
Charset: dbSchema.CharacterSet,
Collation: dbSchema.Collation,
ChangeType: convertChangeType(changeType),
diff --git a/backend/common/resource_name.go b/backend/common/resource_name.go
index 15126db376..7ccb434135 100644
--- a/backend/common/resource_name.go
+++ b/backend/common/resource_name.go
@@ -48,6 +48,7 @@ const (
VCSConnectorPrefix = "vcsConnectors/"
AuditLogPrefix = "auditLogs/"
UserGroupPrefix = "groups/"
+ ReviewConfigPrefix = "reviewConfigs/"
SchemaSuffix = "/schema"
MetadataSuffix = "/metadata"
@@ -484,11 +485,20 @@ func GetWorksheetUID(name string) (int, error) {
}
sheetUID, err := strconv.Atoi(tokens[0])
if err != nil {
- return 0, errors.Wrapf(err, "failed to convert sheet uid %q to int", tokens[1])
+ return 0, errors.Wrapf(err, "failed to convert worksheet uid %q to int", tokens[1])
}
return sheetUID, nil
}
+// GetReviewConfigID returns the review config id from a resource name.
+func GetReviewConfigID(name string) (string, error) {
+ tokens, err := GetNameParentTokens(name, ReviewConfigPrefix)
+ if err != nil {
+ return "", err
+ }
+ return tokens[0], nil
+}
+
var branchRegexp = regexp.MustCompile("^projects/([^/]+)/branches/(.+)$")
// GetProjectAndBranchID returns the project and branch ID from a resource name.
@@ -576,8 +586,20 @@ func FormatGroupEmail(email string) string {
return fmt.Sprintf("%s%s", UserGroupPrefix, email)
}
+func FormatReviewConfig(id string) string {
+ return fmt.Sprintf("%s%s", ReviewConfigPrefix, id)
+}
+
+func FormatEnvironment(resourceID string) string {
+ return fmt.Sprintf("%s%s", EnvironmentNamePrefix, resourceID)
+}
+
+func FormatInstance(resourceID string) string {
+ return fmt.Sprintf("%s%s", InstanceNamePrefix, resourceID)
+}
+
func FormatDatabase(instance string, database string) string {
- return fmt.Sprintf("%s%s/%s%s", InstanceNamePrefix, instance, DatabaseIDPrefix, database)
+ return fmt.Sprintf("%s/%s%s", FormatInstance(instance), DatabaseIDPrefix, database)
}
func FormatRole(role string) string {
diff --git a/backend/legacyapi/policy.go b/backend/legacyapi/policy.go
index 2e016c8cb8..9fd91f2bb2 100644
--- a/backend/legacyapi/policy.go
+++ b/backend/legacyapi/policy.go
@@ -21,6 +21,9 @@ type EnvironmentTierValue string
// PolicyResourceType is the resource type for a policy.
type PolicyResourceType string
+// ReservedTag is the reserved tags for bb.policy.tag.
+type ReservedTag string
+
const (
// DefaultPolicyID is the ID of the default policy.
DefaultPolicyID int = 0
@@ -28,6 +31,7 @@ const (
// PolicyTypeRollout is the rollout policy type.
PolicyTypeRollout PolicyType = "bb.policy.rollout"
// PolicyTypeSQLReview is the sql review policy type.
+ // TODO(ed): remove this.
PolicyTypeSQLReview PolicyType = "bb.policy.sql-review"
// PolicyTypeEnvironmentTier is the tier of an environment.
PolicyTypeEnvironmentTier PolicyType = "bb.policy.environment-tier"
@@ -45,6 +49,8 @@ const (
PolicyTypeRestrictIssueCreationForSQLReview PolicyType = "bb.policy.restrict-issue-creation-for-sql-review"
// PolicyTypeProjectIAM is the policy for IAM in the project.
PolicyTypeProjectIAM PolicyType = "bb.policy.project-iam"
+ // PolicyTypeTag is the policy type for resource tags.
+ PolicyTypeTag PolicyType = "bb.policy.tag"
// PipelineApprovalValueManualNever means the pipeline will automatically be approved without user intervention.
PipelineApprovalValueManualNever PipelineApprovalValue = "MANUAL_APPROVAL_NEVER"
@@ -73,14 +79,19 @@ const (
PolicyResourceTypeInstance PolicyResourceType = "INSTANCE"
// PolicyResourceTypeDatabase is the resource type for databases.
PolicyResourceTypeDatabase PolicyResourceType = "DATABASE"
+
+ // ReservedTagReviewConfig is the tag for review config.
+ ReservedTagReviewConfig ReservedTag = "bb.tag.review_config"
)
var (
// AllowedResourceTypes includes allowed resource types for each policy type.
AllowedResourceTypes = map[PolicyType][]PolicyResourceType{
- PolicyTypeRollout: {PolicyResourceTypeEnvironment},
+ PolicyTypeRollout: {PolicyResourceTypeEnvironment},
+ // TODO(ed): remove this.
PolicyTypeSQLReview: {PolicyResourceTypeEnvironment},
PolicyTypeEnvironmentTier: {PolicyResourceTypeEnvironment},
+ PolicyTypeTag: {PolicyResourceTypeEnvironment},
PolicyTypeMasking: {PolicyResourceTypeDatabase},
PolicyTypeSlowQuery: {PolicyResourceTypeInstance},
PolicyTypeDisableCopyData: {PolicyResourceTypeEnvironment},
diff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.go
index 7bc20ff9b7..f047d1907e 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -140,14 +140,12 @@ func (e *StatementAdviseExecutor) runForDatabaseTarget(ctx context.Context, conf
return nil, errors.Wrapf(err, "failed to get sheet statement %d", sheetUID)
}
- policy, err := e.store.GetSQLReviewPolicy(ctx, environment.UID)
+ reviewConfig, err := e.store.GetReviewConfigByEnvironment(ctx, environment.UID)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
- policy = &storepb.SQLReviewPolicy{
- Name: "Default",
- }
+ reviewConfig = &storepb.ReviewConfigPayload{}
} else {
- return nil, common.Wrapf(err, common.Internal, "failed to get SQL review policy")
+ return nil, common.Wrapf(err, common.Internal, "failed to get SQL review config")
}
}
@@ -166,7 +164,7 @@ func (e *StatementAdviseExecutor) runForDatabaseTarget(ctx context.Context, conf
materials := utils.GetSecretMapFromDatabaseMessage(database)
// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
renderedStatement := utils.RenderStatement(statement, materials)
- adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, policy.RuleList, advisor.SQLReviewCheckContext{
+ adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, reviewConfig.SqlReviewRules, advisor.SQLReviewCheckContext{
Charset: dbSchema.GetMetadata().CharacterSet,
Collation: dbSchema.GetMetadata().Collation,
DBSchema: dbSchema.GetMetadata(),
@@ -330,14 +328,12 @@ func (e *StatementAdviseExecutor) runForDatabaseGroupTarget(ctx context.Context,
return nil, errors.Wrapf(err, "failed to get db schema %q", database.UID)
}
- policy, err := e.store.GetSQLReviewPolicy(ctx, environment.UID)
+ reviewConfig, err := e.store.GetReviewConfigByEnvironment(ctx, environment.UID)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
- policy = &storepb.SQLReviewPolicy{
- Name: "Default",
- }
+ reviewConfig = &storepb.ReviewConfigPayload{}
} else {
- return nil, common.Wrapf(err, common.Internal, "failed to get SQL review policy")
+ return nil, common.Wrapf(err, common.Internal, "failed to get SQL review config")
}
}
@@ -357,7 +353,7 @@ func (e *StatementAdviseExecutor) runForDatabaseGroupTarget(ctx context.Context,
materials := utils.GetSecretMapFromDatabaseMessage(database)
// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
renderedStatement := utils.RenderStatement(sheetStatement, materials)
- adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, policy.RuleList, advisor.SQLReviewCheckContext{
+ adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, reviewConfig.SqlReviewRules, advisor.SQLReviewCheckContext{
Charset: dbSchema.GetMetadata().CharacterSet,
Collation: dbSchema.GetMetadata().Collation,
DBSchema: dbSchema.GetMetadata(),
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index b4ecc9f318..f03dc9fa3e 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -94,6 +94,7 @@ func configureGrpcRouters(
v1pb.RegisterChangelistServiceServer(grpcServer, apiv1.NewChangelistService(stores, profile, iamManager))
v1pb.RegisterVCSConnectorServiceServer(grpcServer, apiv1.NewVCSConnectorService(stores))
v1pb.RegisterUserGroupServiceServer(grpcServer, apiv1.NewUserGroupService(stores, iamManager))
+ v1pb.RegisterReviewConfigServiceServer(grpcServer, apiv1.NewReviewConfigService(stores, licenseService))
// REST gateway proxy.
grpcEndpoint := fmt.Sprintf(":%d", profile.Port)
@@ -177,5 +178,8 @@ func configureGrpcRouters(
if err := v1pb.RegisterUserGroupServiceHandler(ctx, mux, grpcConn); err != nil {
return nil, nil, nil, err
}
+ if err := v1pb.RegisterReviewConfigServiceHandler(ctx, mux, grpcConn); err != nil {
+ return nil, nil, nil, err
+ }
return planService, rolloutService, issueService, nil
}
diff --git a/backend/server/onboard.go b/backend/server/onboard.go
index 34932f1e6e..1fefd4e998 100644
--- a/backend/server/onboard.go
+++ b/backend/server/onboard.go
@@ -152,21 +152,38 @@ func (s *Server) generateOnboardingData(ctx context.Context, user *store.UserMes
// Add a sample SQL Review policy to the prod environment. This pairs with the following schema
// change issue to demonstrate the SQL Review feature.
- policyPayload, err := protojson.Marshal(getSampleSQLReviewPolicy())
+ sqlReviewConfig := &store.ReviewConfigMessage{
+ Name: "SQL Review Sample Policy",
+ CreatorUID: userID,
+ Enforce: true,
+ Payload: getSampleSQLReviewPayload(),
+ }
+
+ config, err := s.store.CreateReviewConfig(ctx, sqlReviewConfig)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create onboarding SQL Review policy")
+ }
+
+ policyPayload, err := protojson.Marshal(&storepb.TagPolicy{
+ Tags: map[string]string{
+ string(api.ReservedTagReviewConfig): common.FormatReviewConfig(config.ID),
+ },
+ })
if err != nil {
- return errors.Wrapf(err, "failed to marshal onboarding SQL Review policy")
+ return errors.Wrapf(err, "failed to marshal environment tag")
}
+
_, err = s.store.CreatePolicyV2(ctx, &store.PolicyMessage{
ResourceUID: api.DefaultProdEnvironmentUID,
ResourceType: api.PolicyResourceTypeEnvironment,
Payload: string(policyPayload),
- Type: api.PolicyTypeSQLReview,
+ Type: api.PolicyTypeTag,
InheritFromParent: true,
// Enforce cannot be false while creating a policy.
Enforce: true,
}, userID)
if err != nil {
- return errors.Wrapf(err, "failed to create onboarding SQL Review policy")
+ return errors.Wrapf(err, "failed to create onboarding environment tag policy")
}
// Create a standalone sample SQL sheet.
@@ -320,20 +337,16 @@ func (s *Server) generateOnboardingData(ctx context.Context, user *store.UserMes
return nil
}
-// getSampleSQLReviewPolicy returns a sample SQL review policy for preparing onboardign data.
-func getSampleSQLReviewPolicy() *storepb.SQLReviewPolicy {
- policy := &storepb.SQLReviewPolicy{
- Name: "SQL Review Sample Policy",
- }
-
- ruleList := []*storepb.SQLReviewRule{}
+// getSampleSQLReviewPayload returns a sample SQL review policy for preparing onboardign data.
+func getSampleSQLReviewPayload() *storepb.ReviewConfigPayload {
+ payload := &storepb.ReviewConfigPayload{}
// Add DropEmptyDatabase rule.
for _, e := range []storepb.Engine{
storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_OCEANBASE,
storepb.Engine_MARIADB,
} {
- ruleList = append(ruleList, &storepb.SQLReviewRule{
+ payload.SqlReviewRules = append(payload.SqlReviewRules, &storepb.SQLReviewRule{
Type: string(advisor.SchemaRuleDropEmptyDatabase),
Level: storepb.SQLReviewRuleLevel_ERROR,
Engine: e,
@@ -347,7 +360,7 @@ func getSampleSQLReviewPolicy() *storepb.SQLReviewPolicy {
storepb.Engine_ORACLE, storepb.Engine_OCEANBASE_ORACLE, storepb.Engine_OCEANBASE,
storepb.Engine_SNOWFLAKE, storepb.Engine_MSSQL, storepb.Engine_MARIADB,
} {
- ruleList = append(ruleList, &storepb.SQLReviewRule{
+ payload.SqlReviewRules = append(payload.SqlReviewRules, &storepb.SQLReviewRule{
Type: string(advisor.SchemaRuleColumnNotNull),
Level: storepb.SQLReviewRuleLevel_WARNING,
Engine: e,
@@ -361,7 +374,7 @@ func getSampleSQLReviewPolicy() *storepb.SQLReviewPolicy {
storepb.Engine_OCEANBASE, storepb.Engine_SNOWFLAKE, storepb.Engine_MSSQL,
storepb.Engine_MARIADB,
} {
- ruleList = append(ruleList, &storepb.SQLReviewRule{
+ payload.SqlReviewRules = append(payload.SqlReviewRules, &storepb.SQLReviewRule{
Type: string(advisor.SchemaRuleTableDropNamingConvention),
Level: storepb.SQLReviewRuleLevel_ERROR,
Engine: e,
@@ -369,6 +382,5 @@ func getSampleSQLReviewPolicy() *storepb.SQLReviewPolicy {
})
}
- policy.RuleList = ruleList
- return policy
+ return payload
}
diff --git a/backend/store/policy.go b/backend/store/policy.go
index 015ce84003..2eaf0e5f1e 100644
--- a/backend/store/policy.go
+++ b/backend/store/policy.go
@@ -63,10 +63,11 @@ func (s *Store) GetRolloutPolicy(ctx context.Context, environmentID int) (*store
return p, nil
}
-// GetSQLReviewPolicy will get the SQL review policy for an environment.
-func (s *Store) GetSQLReviewPolicy(ctx context.Context, environmentID int) (*storepb.SQLReviewPolicy, error) {
+// GetSQLReviewConfigByEnvironment will get the review config for an environment.
+func (s *Store) GetReviewConfigByEnvironment(ctx context.Context, environmentID int) (*storepb.ReviewConfigPayload, error) {
resourceType := api.PolicyResourceTypeEnvironment
- pType := api.PolicyTypeSQLReview
+ pType := api.PolicyTypeTag
+
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
ResourceUID: &environmentID,
@@ -82,12 +83,29 @@ func (s *Store) GetSQLReviewPolicy(ctx context.Context, environmentID int) (*sto
return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy is not enforced for environment %d", environmentID)}
}
- p := new(storepb.SQLReviewPolicy)
- if err := protojson.Unmarshal([]byte(policy.Payload), p); err != nil {
+ payload := &storepb.TagPolicy{}
+ if err := protojson.Unmarshal([]byte(policy.Payload), payload); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal tag policy payload")
+ }
+
+ reviewConfigName, ok := payload.Tags[string(api.ReservedTagReviewConfig)]
+ if !ok {
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config tag for environment %d not found", environmentID)}
+ }
+ reviewConfigID, err := common.GetReviewConfigID(reviewConfigName)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to extract review config uid from %s", reviewConfigName)
+ }
+
+ reviewConfig, err := s.GetReviewConfig(ctx, reviewConfigID)
+ if err != nil {
return nil, err
}
+ if reviewConfig == nil {
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config for environment %d not found", environmentID)}
+ }
- return p, nil
+ return reviewConfig.Payload, nil
}
// GetSlowQueryPolicy will get the slow query policy for instance ID.
@@ -211,7 +229,6 @@ type UpdatePolicyMessage struct {
InheritFromParent *bool
Payload *string
Enforce *bool
- Delete *bool
}
// GetPolicyV2 gets a policy.
diff --git a/backend/store/review_config.go b/backend/store/review_config.go
new file mode 100644
index 0000000000..035ba26c29
--- /dev/null
+++ b/backend/store/review_config.go
@@ -0,0 +1,289 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ api "github.com/bytebase/bytebase/backend/legacyapi"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+// ReviewConfigMessage is the API message for sql review.
+type ReviewConfigMessage struct {
+ ID string
+ CreatorUID int
+ UpdaterUID int
+ Enforce bool
+ Name string
+ Payload *storepb.ReviewConfigPayload
+
+ // Output only fields
+ CreatedTime time.Time
+ UpdatedTime time.Time
+}
+
+// FindReviewConfigMessage is the API message for finding sql review.
+type FindReviewConfigMessage struct {
+ ID *string
+}
+
+// PatchReviewConfigMessage is the message to patch a sql review.
+type PatchReviewConfigMessage struct {
+ ID string
+ UpdaterID int
+ Name *string
+ Enforce *bool
+ Payload *storepb.ReviewConfigPayload
+}
+
+// GetReviewConfig gets sql review by id.
+func (s *Store) GetReviewConfig(ctx context.Context, id string) (*ReviewConfigMessage, error) {
+ list, err := s.ListReviewConfigs(ctx, &FindReviewConfigMessage{ID: &id})
+ if err != nil {
+ return nil, err
+ }
+ if len(list) == 0 {
+ return nil, nil
+ }
+ if len(list) > 1 {
+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d sql review", len(list))}
+ }
+
+ return list[0], nil
+}
+
+// ListReviewConfigs lists all sql review.
+func (s *Store) ListReviewConfigs(ctx context.Context, find *FindReviewConfigMessage) ([]*ReviewConfigMessage, error) {
+ where, args := []string{"TRUE"}, []any{}
+
+ if v := find.ID; v != nil {
+ where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
+ }
+
+ tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
+ SELECT
+ id,
+ row_status,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ name,
+ payload
+ FROM review_config
+ WHERE %s`, strings.Join(where, " AND ")),
+ args...,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var sqlReviewList []*ReviewConfigMessage
+ for rows.Next() {
+ var sqlReview ReviewConfigMessage
+ var createdTs int64
+ var updatedTs int64
+ var payload []byte
+ var rowStatus string
+
+ if err := rows.Scan(
+ &sqlReview.ID,
+ &rowStatus,
+ &sqlReview.CreatorUID,
+ &createdTs,
+ &sqlReview.UpdaterUID,
+ &updatedTs,
+ &sqlReview.Name,
+ &payload,
+ ); err != nil {
+ return nil, err
+ }
+
+ reviewConfigPyload := &storepb.ReviewConfigPayload{}
+ if err := protojsonUnmarshaler.Unmarshal(payload, reviewConfigPyload); err != nil {
+ return nil, err
+ }
+
+ sqlReview.Enforce = rowStatus == string(api.Normal)
+ sqlReview.Payload = reviewConfigPyload
+ sqlReview.CreatedTime = time.Unix(createdTs, 0)
+ sqlReview.UpdatedTime = time.Unix(updatedTs, 0)
+ sqlReviewList = append(sqlReviewList, &sqlReview)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+
+ return sqlReviewList, nil
+}
+
+// CreateReviewConfig creates the sql review config.
+func (s *Store) CreateReviewConfig(ctx context.Context, create *ReviewConfigMessage) (*ReviewConfigMessage, error) {
+ if create.ID == "" {
+ return nil, errors.Errorf("empty config id")
+ }
+ payload, err := protojson.Marshal(create.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ query := `
+ INSERT INTO review_config (
+ id,
+ creator_id,
+ updater_id,
+ name,
+ payload
+ )
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING created_ts, updated_ts
+ `
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+ create.UpdaterUID = create.CreatorUID
+
+ var createdTs int64
+ var updatedTs int64
+ if err := tx.QueryRowContext(ctx, query,
+ create.ID,
+ create.CreatorUID,
+ create.CreatorUID,
+ create.Name,
+ payload,
+ ).Scan(
+ &createdTs,
+ &updatedTs,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, errors.Wrapf(err, "failed to commit transaction")
+ }
+
+ create.Enforce = true
+ create.CreatedTime = time.Unix(createdTs, 0)
+ create.UpdatedTime = time.Unix(updatedTs, 0)
+
+ return create, nil
+}
+
+// DeleteReviewConfig deletes sql review by ID.
+func (s *Store) DeleteReviewConfig(ctx context.Context, id string) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ if _, err := tx.ExecContext(ctx, `DELETE FROM review_config WHERE id = $1`, id); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+
+// UpdateReviewConfig updates the sql review.
+func (s *Store) UpdateReviewConfig(ctx context.Context, patch *PatchReviewConfigMessage) (*ReviewConfigMessage, error) {
+ set, args := []string{"updater_id = $1", "updated_ts = $2"}, []any{patch.UpdaterID, time.Now().Unix()}
+ if v := patch.Enforce; v != nil {
+ rowStatus := api.Normal
+ if !*patch.Enforce {
+ rowStatus = api.Archived
+ }
+ set, args = append(set, fmt.Sprintf(`"row_status" = $%d`, len(args)+1)), append(args, rowStatus)
+ }
+ if v := patch.Name; v != nil {
+ set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.Payload; v != nil {
+ payload, err := protojson.Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ set, args = append(set, fmt.Sprintf("payload = $%d", len(args)+1)), append(args, payload)
+ }
+ args = append(args, patch.ID)
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ query := fmt.Sprintf(`
+ UPDATE review_config
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = $%d
+ RETURNING
+ id,
+ row_status,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ name,
+ payload
+ `, len(args))
+
+ var sqlReview ReviewConfigMessage
+ var createdTs int64
+ var updatedTs int64
+ var payload []byte
+ var rowStatus string
+
+ if err := tx.QueryRowContext(ctx, query, args...).Scan(
+ &sqlReview.ID,
+ &rowStatus,
+ &sqlReview.CreatorUID,
+ &createdTs,
+ &sqlReview.UpdaterUID,
+ &updatedTs,
+ &sqlReview.Name,
+ &sqlReview,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return nil, err
+ }
+
+ reviewConfigPyload := &storepb.ReviewConfigPayload{}
+ if err := protojsonUnmarshaler.Unmarshal(payload, reviewConfigPyload); err != nil {
+ return nil, err
+ }
+
+ sqlReview.Enforce = rowStatus == string(api.Normal)
+ sqlReview.Payload = reviewConfigPyload
+ sqlReview.CreatedTime = time.Unix(createdTs, 0)
+ sqlReview.UpdatedTime = time.Unix(updatedTs, 0)
+
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+
+ return &sqlReview, nil
+}
diff --git a/backend/tests/sql.go b/backend/tests/sql.go
index 497e463c43..d7fa2dbb93 100644
--- a/backend/tests/sql.go
+++ b/backend/tests/sql.go
@@ -4,6 +4,7 @@ import (
"context"
"time"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -53,9 +54,11 @@ func (ctl *controller) GetSQLReviewResult(ctx context.Context, plan *v1pb.Plan)
return nil, nil
}
-func prodTemplateSQLReviewPolicyForPostgreSQL() (*v1pb.SQLReviewPolicy, error) {
- policy := &v1pb.SQLReviewPolicy{
- Name: "Prod",
+func prodTemplateReviewConfigForPostgreSQL() (*v1pb.ReviewConfig, error) {
+ config := &v1pb.ReviewConfig{
+ Name: common.FormatReviewConfig(generateRandomString("review", 10)),
+ Title: "Prod",
+ Enabled: true,
Rules: []*v1pb.SQLReviewRule{
// Naming
{
@@ -268,19 +271,21 @@ func prodTemplateSQLReviewPolicyForPostgreSQL() (*v1pb.SQLReviewPolicy, error) {
},
}
- for _, rule := range policy.Rules {
+ for _, rule := range config.Rules {
payload, err := advisor.SetDefaultSQLReviewRulePayload(advisor.SQLReviewRuleType(rule.Type), storepb.Engine_POSTGRES)
if err != nil {
return nil, err
}
rule.Payload = payload
}
- return policy, nil
+ return config, nil
}
-func prodTemplateSQLReviewPolicyForMySQL() (*v1pb.SQLReviewPolicy, error) {
- policy := &v1pb.SQLReviewPolicy{
- Name: "Prod",
+func prodTemplateReviewConfigForMySQL() (*v1pb.ReviewConfig, error) {
+ config := &v1pb.ReviewConfig{
+ Name: common.FormatReviewConfig(generateRandomString("review", 10)),
+ Title: "Prod",
+ Enabled: true,
Rules: []*v1pb.SQLReviewRule{
// Engine
{
@@ -544,14 +549,14 @@ func prodTemplateSQLReviewPolicyForMySQL() (*v1pb.SQLReviewPolicy, error) {
},
}
- for _, rule := range policy.Rules {
+ for _, rule := range config.Rules {
payload, err := advisor.SetDefaultSQLReviewRulePayload(advisor.SQLReviewRuleType(rule.Type), storepb.Engine_POSTGRES)
if err != nil {
return nil, err
}
rule.Payload = payload
}
- return policy, nil
+ return config, nil
}
// getSchemaDiff gets the schema diff.
diff --git a/backend/tests/sql_review_test.go b/backend/tests/sql_review_test.go
index 25053b0675..2161b2e37b 100644
--- a/backend/tests/sql_review_test.go
+++ b/backend/tests/sql_review_test.go
@@ -109,14 +109,25 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {
_, err = pgDB.Exec("ALTER USER bytebase WITH SUPERUSER")
a.NoError(err)
- reviewPolicy, err := prodTemplateSQLReviewPolicyForPostgreSQL()
+ reviewConfig, err := prodTemplateReviewConfigForPostgreSQL()
a.NoError(err)
+
+ createdConfig, err := ctl.reviewConfigServiceClient.CreateReviewConfig(ctx, &v1pb.CreateReviewConfigRequest{
+ ReviewConfig: reviewConfig,
+ })
+ a.NoError(err)
+ a.NotNil(createdConfig.Name)
+
policy, err := ctl.orgPolicyServiceClient.CreatePolicy(ctx, &v1pb.CreatePolicyRequest{
Parent: "environments/prod",
Policy: &v1pb.Policy{
- Type: v1pb.PolicyType_SQL_REVIEW,
- Policy: &v1pb.Policy_SqlReviewPolicy{
- SqlReviewPolicy: reviewPolicy,
+ Type: v1pb.PolicyType_TAG,
+ Policy: &v1pb.Policy_TagPolicy{
+ TagPolicy: &v1pb.TagPolicy{
+ Tags: map[string]string{
+ string(api.ReservedTagReviewConfig): createdConfig.Name,
+ },
+ },
},
},
})
@@ -272,15 +283,25 @@ func TestSQLReviewForMySQL(t *testing.T) {
_, err = mysqlDB.Exec("GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, SELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, REPLICATION CLIENT, REPLICATION SLAVE, LOCK TABLES, RELOAD ON *.* to bytebase")
a.NoError(err)
- reviewPolicy, err := prodTemplateSQLReviewPolicyForMySQL()
+ reviewConfig, err := prodTemplateReviewConfigForMySQL()
a.NoError(err)
+ createdConfig, err := ctl.reviewConfigServiceClient.CreateReviewConfig(ctx, &v1pb.CreateReviewConfigRequest{
+ ReviewConfig: reviewConfig,
+ })
+ a.NoError(err)
+ a.NotNil(createdConfig.Name)
+
policy, err := ctl.orgPolicyServiceClient.CreatePolicy(ctx, &v1pb.CreatePolicyRequest{
Parent: "environments/prod",
Policy: &v1pb.Policy{
- Type: v1pb.PolicyType_SQL_REVIEW,
- Policy: &v1pb.Policy_SqlReviewPolicy{
- SqlReviewPolicy: reviewPolicy,
+ Type: v1pb.PolicyType_TAG,
+ Policy: &v1pb.Policy_TagPolicy{
+ TagPolicy: &v1pb.TagPolicy{
+ Tags: map[string]string{
+ string(api.ReservedTagReviewConfig): createdConfig.Name,
+ },
+ },
},
},
})
diff --git a/backend/tests/tests.go b/backend/tests/tests.go
index c745c50dfe..8bb815288f 100644
--- a/backend/tests/tests.go
+++ b/backend/tests/tests.go
@@ -124,6 +124,7 @@ type controller struct {
rolloutServiceClient v1pb.RolloutServiceClient
planServiceClient v1pb.PlanServiceClient
orgPolicyServiceClient v1pb.OrgPolicyServiceClient
+ reviewConfigServiceClient v1pb.ReviewConfigServiceClient
projectServiceClient v1pb.ProjectServiceClient
vcsConnectorServiceClient v1pb.VCSConnectorServiceClient
authServiceClient v1pb.AuthServiceClient
@@ -385,6 +386,7 @@ func (ctl *controller) start(ctx context.Context, port int) (context.Context, er
ctl.rolloutServiceClient = v1pb.NewRolloutServiceClient(ctl.grpcConn)
ctl.planServiceClient = v1pb.NewPlanServiceClient(ctl.grpcConn)
ctl.orgPolicyServiceClient = v1pb.NewOrgPolicyServiceClient(ctl.grpcConn)
+ ctl.reviewConfigServiceClient = v1pb.NewReviewConfigServiceClient(ctl.grpcConn)
ctl.projectServiceClient = v1pb.NewProjectServiceClient(ctl.grpcConn)
ctl.vcsConnectorServiceClient = v1pb.NewVCSConnectorServiceClient(ctl.grpcConn)
ctl.authServiceClient = v1pb.NewAuthServiceClient(ctl.grpcConn)
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 937e50d73a..923836ba1d 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -671,7 +671,7 @@ func GetMatchedAndUnmatchedDatabasesInDatabaseGroup(ctx context.Context, databas
res, _, err := prog.ContextEval(ctx, map[string]any{
"resource": map[string]any{
"database_name": database.DatabaseName,
- "environment_name": fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, database.EffectiveEnvironmentID),
+ "environment_name": common.FormatEnvironment(database.EffectiveEnvironmentID),
"instance_id": database.InstanceID,
},
})