Skip to content

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

feat: support attach sql review config to project and database (#12488)

ecmadaoa4a85cb44fc1
diff --git a/backend/api/v1/review_config_service.go b/backend/api/v1/review_config_service.go
index 0efe47c7a9..4dd948703a 100644
--- a/backend/api/v1/review_config_service.go
+++ b/backend/api/v1/review_config_service.go
@@ -189,12 +189,10 @@ func (s *ReviewConfigService) convertToV1ReviewConfig(ctx context.Context, revie
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,
+ Type: &policyType,
+ ShowDeleted: false,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list tag policy, error %v", err)
@@ -218,17 +216,45 @@ func (s *ReviewConfigService) convertToV1ReviewConfig(ctx context.Context, revie
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
+
+ switch policy.ResourceType {
+ case api.PolicyResourceTypeEnvironment:
+ 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))
+ case api.PolicyResourceTypeProject:
+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
+ UID: &policy.ResourceUID,
+ ShowDeleted: false,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get project %d with error: %v", policy.ResourceUID, err)
+ }
+ if project == nil {
+ continue
+ }
+ config.Resources = append(config.Resources, common.FormatProject(project.ResourceID))
+ case api.PolicyResourceTypeDatabase:
+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ UID: &policy.ResourceUID,
+ ShowDeleted: false,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get database %d with error: %v", policy.ResourceUID, err)
+ }
+ if database == nil {
+ continue
+ }
+ config.Resources = append(config.Resources, common.FormatDatabase(database.InstanceID, database.DatabaseName))
}
- config.Resources = append(config.Resources, common.FormatEnvironment(environment.ResourceID))
}
return config, nil
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 4d28d11b0d..457a36efdd 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -170,7 +170,7 @@ func (*SQLService) doAdminExecute(ctx context.Context, driver db.Driver, conn *s
}
func (s *SQLService) preAdminExecute(ctx context.Context, request *v1pb.AdminExecuteRequest) (*store.InstanceMessage, *store.DatabaseMessage, *store.UserMessage, error) {
- user, _, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
+ user, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
if err != nil {
return nil, nil, nil, err
}
@@ -179,14 +179,14 @@ func (s *SQLService) preAdminExecute(ctx context.Context, request *v1pb.AdminExe
// Execute executes the SQL statement.
func (s *SQLService) Execute(ctx context.Context, request *v1pb.ExecuteRequest) (*v1pb.ExecuteResponse, error) {
- environment, instance, database, err := s.preExecute(ctx, request)
+ instance, database, err := s.preExecute(ctx, request)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to prepare execute: %v", err)
}
statement := request.Statement
// Run SQL review.
- adviceStatus, advices, err := s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, environment, instance, database, nil /* Override Metadata */)
+ adviceStatus, advices, err := s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, instance, database, nil /* Override Metadata */)
if err != nil {
return nil, err
}
@@ -208,19 +208,19 @@ func (s *SQLService) Execute(ctx context.Context, request *v1pb.ExecuteRequest)
return response, nil
}
-func (s *SQLService) preExecute(ctx context.Context, request *v1pb.ExecuteRequest) (*store.EnvironmentMessage, *store.InstanceMessage, *store.DatabaseMessage, error) {
+func (s *SQLService) preExecute(ctx context.Context, request *v1pb.ExecuteRequest) (*store.InstanceMessage, *store.DatabaseMessage, error) {
hasDatabase := strings.Contains(request.Name, "/databases/")
var err error
var instanceID, databaseName string
if hasDatabase {
instanceID, databaseName, err = common.GetInstanceDatabaseID(request.Name)
if err != nil {
- return nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
+ return nil, nil, status.Error(codes.InvalidArgument, err.Error())
}
} else {
instanceID, err = common.GetInstanceID(request.Name)
if err != nil {
- return nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
+ return nil, nil, status.Error(codes.InvalidArgument, err.Error())
}
}
@@ -234,10 +234,10 @@ func (s *SQLService) preExecute(ctx context.Context, request *v1pb.ExecuteReques
instance, err := s.store.GetInstanceV2(ctx, find)
if err != nil {
- return nil, nil, nil, status.Errorf(codes.Internal, err.Error())
+ return nil, nil, status.Errorf(codes.Internal, err.Error())
}
if instance == nil {
- return nil, nil, nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
+ return nil, nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
}
var database *store.DatabaseMessage
@@ -248,25 +248,14 @@ func (s *SQLService) preExecute(ctx context.Context, request *v1pb.ExecuteReques
IgnoreCaseSensitive: store.IgnoreDatabaseAndTableCaseSensitive(instance),
})
if err != nil {
- return nil, nil, nil, status.Errorf(codes.Internal, "failed to fetch database: %v", err)
+ return nil, nil, status.Errorf(codes.Internal, "failed to fetch database: %v", err)
}
if database == nil {
- return nil, nil, nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
+ return nil, nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
}
}
- environmentID := instance.EnvironmentID
- if database != nil {
- environmentID = database.EffectiveEnvironmentID
- }
- environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &environmentID})
- if err != nil {
- return nil, nil, nil, status.Errorf(codes.Internal, "failed to fetch environment: %v", err)
- }
- if environment == nil {
- return nil, nil, nil, status.Errorf(codes.NotFound, "environment ID not found: %s", environmentID)
- }
- return environment, instance, database, nil
+ return instance, database, nil
}
func (s *SQLService) doExecute(ctx context.Context, instance *store.InstanceMessage, database *store.DatabaseMessage, request *v1pb.ExecuteRequest) ([]*v1pb.QueryResult, int64, error) {
@@ -309,7 +298,7 @@ func (s *SQLService) Export(ctx context.Context, request *v1pb.ExportRequest) (*
return s.doExportFromIssue(ctx, request.Name)
}
// Prepare related message.
- user, environment, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
+ user, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
if err != nil {
return nil, err
}
@@ -349,7 +338,7 @@ func (s *SQLService) Export(ctx context.Context, request *v1pb.ExportRequest) (*
}
// Run SQL review.
- if _, _, err = s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, environment, instance, database, nil /* Override Metadata */); err != nil {
+ if _, _, err = s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, instance, database, nil /* Override Metadata */); err != nil {
return nil, err
}
@@ -684,7 +673,7 @@ func (s *SQLService) convertToV1QueryHistory(ctx context.Context, history *store
// 3. post-query
func (s *SQLService) Query(ctx context.Context, request *v1pb.QueryRequest) (*v1pb.QueryResponse, error) {
// Prepare related message.
- user, environment, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
+ user, instance, database, err := s.prepareRelatedMessage(ctx, request.Name, request.ConnectionDatabase)
if err != nil {
return nil, err
}
@@ -725,7 +714,7 @@ func (s *SQLService) Query(ctx context.Context, request *v1pb.QueryRequest) (*v1
}
// Run SQL review.
- adviceStatus, advices, err := s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, environment, instance, database, nil /* Override Metadata */)
+ adviceStatus, advices, err := s.sqlReviewCheck(ctx, statement, v1pb.CheckRequest_CHANGE_TYPE_UNSPECIFIED, instance, database, nil /* Override Metadata */)
if err != nil {
return nil, err
}
@@ -1012,22 +1001,22 @@ func sanitizeResults(results []*v1pb.QueryResult) {
}
}
-func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName string, requestDatabaseName string) (*store.UserMessage, *store.EnvironmentMessage, *store.InstanceMessage, *store.DatabaseMessage, error) {
+func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName string, requestDatabaseName string) (*store.UserMessage, *store.InstanceMessage, *store.DatabaseMessage, error) {
user, err := s.getUser(ctx)
if err != nil {
- return nil, nil, nil, nil, status.Errorf(codes.Internal, err.Error())
+ return nil, nil, nil, status.Errorf(codes.Internal, err.Error())
}
var instanceID, databaseName string
if strings.Contains(requestName, "/databases/") {
instanceID, databaseName, err = common.GetInstanceDatabaseID(requestName)
if err != nil {
- return nil, nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
+ return nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
}
} else {
instanceID, err = common.GetInstanceID(requestName)
if err != nil {
- return nil, nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
+ return nil, nil, nil, status.Error(codes.InvalidArgument, err.Error())
}
databaseName = requestDatabaseName
}
@@ -1042,10 +1031,10 @@ func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName stri
instance, err := s.store.GetInstanceV2(ctx, find)
if err != nil {
- return nil, nil, nil, nil, status.Errorf(codes.Internal, err.Error())
+ return nil, nil, nil, status.Errorf(codes.Internal, err.Error())
}
if instance == nil {
- return nil, nil, nil, nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
+ return nil, nil, nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
}
database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
@@ -1054,21 +1043,13 @@ func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName stri
IgnoreCaseSensitive: store.IgnoreDatabaseAndTableCaseSensitive(instance),
})
if err != nil {
- return nil, nil, nil, nil, status.Errorf(codes.Internal, "failed to fetch database: %v", err)
+ return nil, nil, nil, status.Errorf(codes.Internal, "failed to fetch database: %v", err)
}
if database == nil {
- return nil, nil, nil, nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
- }
-
- environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})
- if err != nil {
- return nil, nil, nil, nil, status.Errorf(codes.Internal, "failed to fetch environment: %v", err)
- }
- if environment == nil {
- return nil, nil, nil, nil, status.Errorf(codes.NotFound, "environment ID not found: %s", database.EffectiveEnvironmentID)
+ return nil, nil, nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
}
- return user, environment, instance, database, nil
+ return user, instance, database, nil
}
func validateQueryRequest(instance *store.InstanceMessage, statement string) error {
@@ -1196,16 +1177,6 @@ func (s *SQLService) Check(ctx context.Context, request *v1pb.CheckRequest) (*v1
return nil, status.Errorf(codes.NotFound, "database %q not found", request.Database)
}
- environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{
- ResourceID: &database.EffectiveEnvironmentID,
- })
- if err != nil {
- return nil, status.Errorf(codes.Internal, "failed to get environment, error: %v", err)
- }
- if environment == nil {
- return nil, status.Errorf(codes.NotFound, "environment %q not found", database.EffectiveEnvironmentID)
- }
-
var overideMetadata *storepb.DatabaseSchemaMetadata
if request.Metadata != nil {
overideMetadata, _, err = convertV1DatabaseMetadata(ctx, request.Metadata, nil /* optionalStores */)
@@ -1213,7 +1184,7 @@ func (s *SQLService) Check(ctx context.Context, request *v1pb.CheckRequest) (*v1
return nil, err
}
}
- _, adviceList, err := s.sqlReviewCheck(ctx, request.Statement, request.ChangeType, environment, instance, database, overideMetadata)
+ _, adviceList, err := s.sqlReviewCheck(ctx, request.Statement, request.ChangeType, instance, database, overideMetadata)
if err != nil {
return nil, err
}
@@ -1226,7 +1197,7 @@ func (s *SQLService) Check(ctx context.Context, request *v1pb.CheckRequest) (*v1
// sqlReviewCheck checks the SQL statement against the SQL review policy bind to given environment,
// against the database schema bind to the given database, if the overrideMetadata is provided,
// it will be used instead of fetching the database schema from the store.
-func (s *SQLService) sqlReviewCheck(ctx context.Context, statement string, changeType v1pb.CheckRequest_ChangeType, environment *store.EnvironmentMessage, instance *store.InstanceMessage, database *store.DatabaseMessage, overrideMetadata *storepb.DatabaseSchemaMetadata) (storepb.Advice_Status, []*v1pb.Advice, error) {
+func (s *SQLService) sqlReviewCheck(ctx context.Context, statement string, changeType v1pb.CheckRequest_ChangeType, instance *store.InstanceMessage, database *store.DatabaseMessage, overrideMetadata *storepb.DatabaseSchemaMetadata) (storepb.Advice_Status, []*v1pb.Advice, error) {
if !IsSQLReviewSupported(instance.Engine) || database == nil {
return storepb.Advice_SUCCESS, nil, nil
}
@@ -1267,12 +1238,11 @@ func (s *SQLService) sqlReviewCheck(ctx context.Context, statement string, chang
ctx,
instance.Engine,
dbMetadata,
- environment.UID,
statement,
changeType,
catalog,
connection,
- database.DatabaseName,
+ database,
)
if err != nil {
return storepb.Advice_ERROR, nil, status.Errorf(codes.Internal, "Failed to check SQL review policy: %v", err)
@@ -1314,15 +1284,14 @@ func (s *SQLService) sqlCheck(
ctx context.Context,
dbType storepb.Engine,
dbSchema *storepb.DatabaseSchemaMetadata,
- environmentID int,
statement string,
changeType v1pb.CheckRequest_ChangeType,
catalog *catalog.Catalog,
driver *sql.DB,
- currentDatabase string,
+ database *store.DatabaseMessage,
) (storepb.Advice_Status, []*storepb.Advice, error) {
var adviceList []*storepb.Advice
- reviewConfig, err := s.store.GetReviewConfigByEnvironment(ctx, environmentID)
+ reviewConfig, err := s.store.GetReviewConfigForDatabase(ctx, database)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
return storepb.Advice_SUCCESS, nil, nil
@@ -1339,7 +1308,7 @@ func (s *SQLService) sqlCheck(
Catalog: catalog,
Driver: driver,
Context: ctx,
- CurrentDatabase: currentDatabase,
+ CurrentDatabase: database.DatabaseName,
})
if err != nil {
return storepb.Advice_ERROR, nil, err
diff --git a/backend/legacyapi/policy.go b/backend/legacyapi/policy.go
index 6cceb9149d..debfc6c2d9 100644
--- a/backend/legacyapi/policy.go
+++ b/backend/legacyapi/policy.go
@@ -86,7 +86,7 @@ var (
AllowedResourceTypes = map[PolicyType][]PolicyResourceType{
PolicyTypeRollout: {PolicyResourceTypeEnvironment},
PolicyTypeEnvironmentTier: {PolicyResourceTypeEnvironment},
- PolicyTypeTag: {PolicyResourceTypeEnvironment},
+ PolicyTypeTag: {PolicyResourceTypeEnvironment, PolicyResourceTypeProject, PolicyResourceTypeDatabase},
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 f047d1907e..690f6e1935 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -85,14 +85,6 @@ func (e *StatementAdviseExecutor) runForDatabaseTarget(ctx context.Context, conf
return nil, errors.Errorf("database not found %q", config.DatabaseName)
}
- environment, err := e.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})
- if err != nil {
- return nil, err
- }
- if environment == nil {
- return nil, errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)
- }
-
if err := e.licenseService.IsFeatureEnabled(api.FeatureSQLReview); err != nil {
// nolint:nilerr
return []*storepb.PlanCheckRunResult_Result{
@@ -140,7 +132,7 @@ func (e *StatementAdviseExecutor) runForDatabaseTarget(ctx context.Context, conf
return nil, errors.Wrapf(err, "failed to get sheet statement %d", sheetUID)
}
- reviewConfig, err := e.store.GetReviewConfigByEnvironment(ctx, environment.UID)
+ reviewConfig, err := e.store.GetReviewConfigForDatabase(ctx, database)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
reviewConfig = &storepb.ReviewConfigPayload{}
@@ -296,14 +288,6 @@ func (e *StatementAdviseExecutor) runForDatabaseGroupTarget(ctx context.Context,
continue
}
- environment, err := e.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})
- if err != nil {
- return nil, err
- }
- if environment == nil {
- return nil, errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)
- }
-
if err := e.licenseService.IsFeatureEnabled(api.FeatureSQLReview); err != nil {
// nolint:nilerr
return []*storepb.PlanCheckRunResult_Result{
@@ -328,7 +312,7 @@ func (e *StatementAdviseExecutor) runForDatabaseGroupTarget(ctx context.Context,
return nil, errors.Wrapf(err, "failed to get db schema %q", database.UID)
}
- reviewConfig, err := e.store.GetReviewConfigByEnvironment(ctx, environment.UID)
+ reviewConfig, err := e.store.GetReviewConfigForDatabase(ctx, database)
if err != nil {
if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {
reviewConfig = &storepb.ReviewConfigPayload{}
diff --git a/backend/store/policy.go b/backend/store/policy.go
index 2beecb5cc3..8f78eccfce 100644
--- a/backend/store/policy.go
+++ b/backend/store/policy.go
@@ -4,12 +4,14 @@ import (
"context"
"database/sql"
"fmt"
+ "log/slog"
"strings"
"time"
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
api "github.com/bytebase/bytebase/backend/legacyapi"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -62,24 +64,53 @@ func (s *Store) GetRolloutPolicy(ctx context.Context, environmentID int) (*store
return p, nil
}
-// GetSQLReviewConfigByEnvironment will get the review config for an environment.
-func (s *Store) GetReviewConfigByEnvironment(ctx context.Context, environmentID int) (*storepb.ReviewConfigPayload, error) {
- resourceType := api.PolicyResourceTypeEnvironment
+// GetReviewConfigForDatabase will get the review config for a database.
+func (s *Store) GetReviewConfigForDatabase(ctx context.Context, database *DatabaseMessage) (*storepb.ReviewConfigPayload, error) {
+ resources := []DatabaseReviewConfig{
+ &databaseReviewConfigResource{},
+ &databaseProjectReviewConfigResource{},
+ &databaseEnvironmentReviewConfigResource{},
+ }
+
+ for _, resource := range resources {
+ resourceType := resource.GetResourceType()
+ resourceUID, err := resource.GetResourceUID(ctx, s, database)
+ if err != nil {
+ slog.Debug("failed to resource id", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
+ continue
+ }
+
+ reviewConfig, err := s.getReviewConfigByResource(ctx, resourceType, resourceUID)
+ if err != nil {
+ slog.Debug("failed to get review config", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
+ continue
+ }
+ if reviewConfig == nil {
+ slog.Debug("review config is empty", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
+ continue
+ }
+ return reviewConfig, nil
+ }
+
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy for database %s not found", database.DatabaseName)}
+}
+
+func (s *Store) getReviewConfigByResource(ctx context.Context, resourceType api.PolicyResourceType, resourceUID int) (*storepb.ReviewConfigPayload, error) {
pType := api.PolicyTypeTag
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &environmentID,
+ ResourceUID: &resourceUID,
Type: &pType,
})
if err != nil {
return nil, err
}
if policy == nil {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy for environment %d not found", environmentID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy for resource %v/%d not found", resourceType, resourceUID)}
}
if !policy.Enforce {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy is not enforced for environment %d", environmentID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy is not enforced for resource %v/%d", resourceType, resourceUID)}
}
payload := &storepb.TagPolicy{}
@@ -89,7 +120,7 @@ func (s *Store) GetReviewConfigByEnvironment(ctx context.Context, environmentID
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)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config tag for resource %v/%d not found", resourceType, resourceUID)}
}
reviewConfigID, err := common.GetReviewConfigID(reviewConfigName)
if err != nil {
@@ -101,7 +132,10 @@ func (s *Store) GetReviewConfigByEnvironment(ctx context.Context, environmentID
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 nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config for resource %v/%d not found", resourceType, resourceUID)}
+ }
+ if !reviewConfig.Enforce {
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config is not enforced for resource %v/%d", resourceType, resourceUID)}
}
return reviewConfig.Payload, nil
diff --git a/backend/store/sql_review.go b/backend/store/sql_review.go
new file mode 100644
index 0000000000..f9dee80b85
--- /dev/null
+++ b/backend/store/sql_review.go
@@ -0,0 +1,60 @@
+package store
+
+import (
+ "context"
+
+ "github.com/pkg/errors"
+
+ api "github.com/bytebase/bytebase/backend/legacyapi"
+)
+
+type DatabaseReviewConfig interface {
+ GetResourceType() api.PolicyResourceType
+ GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error)
+}
+
+type databaseEnvironmentReviewConfigResource struct{}
+
+func (*databaseEnvironmentReviewConfigResource) GetResourceType() api.PolicyResourceType {
+ return api.PolicyResourceTypeEnvironment
+}
+
+func (*databaseEnvironmentReviewConfigResource) GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error) {
+ environment, err := store.GetEnvironmentV2(ctx, &FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})
+ if err != nil {
+ return 0, err
+ }
+ if environment == nil {
+ return 0, errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)
+ }
+
+ return environment.UID, nil
+}
+
+type databaseProjectReviewConfigResource struct{}
+
+func (*databaseProjectReviewConfigResource) GetResourceType() api.PolicyResourceType {
+ return api.PolicyResourceTypeProject
+}
+
+func (*databaseProjectReviewConfigResource) GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error) {
+ project, err := store.GetProjectV2(ctx, &FindProjectMessage{ResourceID: &database.ProjectID})
+ if err != nil {
+ return 0, err
+ }
+ if project == nil {
+ return 0, errors.Errorf("project %q not found", database.ProjectID)
+ }
+
+ return project.UID, nil
+}
+
+type databaseReviewConfigResource struct{}
+
+func (*databaseReviewConfigResource) GetResourceType() api.PolicyResourceType {
+ return api.PolicyResourceTypeDatabase
+}
+
+func (*databaseReviewConfigResource) GetResourceUID(_ context.Context, _ *Store, database *DatabaseMessage) (int, error) {
+ return database.UID, nil
+}
diff --git a/frontend/src/components/Branch/BaselineSchemaSelector.vue b/frontend/src/components/Branch/BaselineSchemaSelector.vue
index 94c7db517f..179190d89b 100644
--- a/frontend/src/components/Branch/BaselineSchemaSelector.vue
+++ b/frontend/src/components/Branch/BaselineSchemaSelector.vue
@@ -3,8 +3,6 @@
<EnvironmentSelect
name="environment"
:disabled="readonly || props.loading"
- :selected-id="state.environmentId"
- :select-default="false"
:environment="state.environmentId"
@update:environment="handleEnvironmentSelect"
/>
diff --git a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
index 4dd6da1997..7c3673c8e7 100644
--- a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
+++ b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
@@ -90,12 +90,11 @@
{{ $t("common.environment") }}
</label>
<EnvironmentSelect
+ v-model:environment="state.environment"
class="mt-1"
required
name="environment"
- :environment="state.environment"
:use-resource-id="true"
- @update:environment="selectEnvironment"
/>
</div>
@@ -312,10 +311,6 @@ const selectProject = (projectId: string | undefined) => {
state.projectId = projectId;
};
-const selectEnvironment = (environment: string | undefined) => {
- state.environment = environment;
-};
-
const selectInstance = (instance: string | undefined) => {
state.instance = instance;
state.environment = selectedInstance.value.environment;
diff --git a/frontend/src/components/Database/context.ts b/frontend/src/components/Database/context.ts
index 986e1060d4..516089c2a9 100644
--- a/frontend/src/components/Database/context.ts
+++ b/frontend/src/components/Database/context.ts
@@ -40,16 +40,15 @@ export const useDatabaseDetailContext = () => {
};
export const provideDatabaseDetailContext = (
- projectId: string,
- instanceId: string,
- databaseName: string
+ instanceId: Ref<string>,
+ databaseName: Ref<string>
) => {
const me = useCurrentUserV1();
const databaseV1Store = useDatabaseV1Store();
const database: Ref<ComposedDatabase> = computed(() => {
return databaseV1Store.getDatabaseByName(
- `${instanceNamePrefix}${instanceId}/${databaseNamePrefix}${databaseName}`
+ `${instanceNamePrefix}${instanceId.value}/${databaseNamePrefix}${databaseName.value}`
);
});
diff --git a/frontend/src/components/Environment/EnvironmentName.vue b/frontend/src/components/Environment/EnvironmentName.vue
deleted file mode 100644
index ceb8782819..0000000000
--- a/frontend/src/components/Environment/EnvironmentName.vue
+++ /dev/null
@@ -1,25 +0,0 @@
-<template>
- <component :is="tag">
- {{ environmentName(environment) }}
- <ProductionEnvironmentIcon
- :environment="environment"
- class="!text-current"
- />
- </component>
-</template>
-
-<script lang="ts" setup>
-import type { Environment } from "@/types";
-import { environmentName } from "@/utils";
-import ProductionEnvironmentIcon from "./ProductionEnvironmentIcon.vue";
-
-withDefaults(
- defineProps<{
- environment: Environment;
- tag?: string;
- }>(),
- {
- tag: "span",
- }
-);
-</script>
diff --git a/frontend/src/components/Environment/ProductionEnvironmentIcon.vue b/frontend/src/components/Environment/ProductionEnvironmentIcon.vue
deleted file mode 100644
index aa1997dc2f..0000000000
--- a/frontend/src/components/Environment/ProductionEnvironmentIcon.vue
+++ /dev/null
@@ -1,60 +0,0 @@
-<template>
- <NTooltip
- v-if="enabled"
- :disabled="!tooltip"
- :delay="0"
- :show-arrow="false"
- :animated="false"
- placement="top-start"
- >
- <template #trigger>
- <heroicons-solid:shield-exclamation
- class="text-control inline-block"
- :class="tooltip ? 'pointer-events-auto' : 'pointer-events-none'"
- v-bind="$attrs"
- />
- </template>
-
- <span>{{ $t("environment.production-environment") }}</span>
- </NTooltip>
-</template>
-
-<script lang="ts">
-import type { PropType } from "vue";
-import { computed, defineComponent } from "vue";
-import { featureToRef } from "@/store";
-import type { Environment } from "@/types";
-
-export default defineComponent({
- name: "ProductionEnvironmentIcon",
- inheritAttrs: false,
- props: {
- environment: {
- type: Object as PropType<Environment>,
- default: undefined,
- },
- tier: {
- type: String,
- default: "",
- },
- tooltip: {
- type: Boolean,
- default: false,
- },
- },
- setup(props) {
- const hasEnvironmentTierPolicyFeature = featureToRef(
- "bb.feature.environment-tier-policy"
- );
-
- const enabled = computed((): boolean => {
- if (!hasEnvironmentTierPolicyFeature.value) {
- return false;
- }
- return (props.environment?.tier || props.tier) === "PROTECTED";
- });
-
- return { enabled };
- },
-});
-</script>
diff --git a/frontend/src/components/EnvironmentForm/Form.vue b/frontend/src/components/EnvironmentForm/Form.vue
index 68fd8def77..7eafd31104 100644
--- a/frontend/src/components/EnvironmentForm/Form.vue
+++ b/frontend/src/components/EnvironmentForm/Form.vue
@@ -81,44 +81,19 @@
/>
</div>
- <div v-if="!create" class="flex flex-col gap-y-2">
- <label class="textlabel">
- {{ $t("sql-review.title") }}
- </label>
- <div>
- <div
- v-if="sqlReviewPolicy"
- class="inline-flex items-center gap-x-2"
- >
- <Switch
- v-if="allowEditSQLReviewPolicy"
- :value="sqlReviewPolicy.enforce"
- :text="true"
- @update:value="toggleSQLReviewPolicy"
- />
- <span
- class="textlabel normal-link !text-accent"
- @click="onSQLReviewPolicyClick"
- >{{ sqlReviewPolicy.name }}</span
- >
- </div>
- <NButton
- v-else-if="hasPermission('bb.policies.update')"
- @click.prevent="onSQLReviewPolicyClick"
- >
- {{ $t("sql-review.configure-policy") }}
- </NButton>
- <span v-else class="textinfolabel">
- {{ $t("sql-review.no-policy-set") }}
- </span>
- </div>
- </div>
+ <SQLReviewForResource
+ v-if="!create"
+ :resource="environment.name"
+ :allow-edit="allowEdit"
+ />
<div v-if="!create" class="flex flex-col gap-y-2">
- <label class="textlabel flex items-center">
- {{ $t("environment.access-control.title") }}
+ <div class="textlabel flex items-center space-x-1">
+ <label>
+ {{ $t("environment.access-control.title") }}
+ </label>
<FeatureBadge feature="bb.feature.access-control" />
- </label>
+ </div>
<div>
<div class="inline-flex items-center gap-x-2">
<Switch
@@ -180,19 +155,12 @@ import { NCheckbox } from "naive-ui";
import { Status } from "nice-grpc-common";
import { computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import {
- WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
- WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
-} from "@/router/dashboard/workspaceRoutes";
import {
hasFeature,
pushNotification,
useEnvironmentV1List,
useEnvironmentV1Store,
usePolicyV1Store,
- useReviewPolicyByEnvironmentName,
- useSQLReviewStore,
} from "@/store";
import { environmentNamePrefix } from "@/store/modules/v1/common";
import type { ResourceId, ValidatedMessage } from "@/types";
@@ -202,7 +170,7 @@ import {
PolicyResourceType,
PolicyType,
} from "@/types/proto/v1/org_policy_service";
-import { extractEnvironmentResourceName, sqlReviewPolicySlug } from "@/utils";
+import { extractEnvironmentResourceName } from "@/utils";
import { getErrorCode } from "@/utils/grpcweb";
import { useEnvironmentFormContext } from "./context";
@@ -212,7 +180,6 @@ defineProps<{
}>();
const { t } = useI18n();
-const router = useRouter();
const {
create,
environment,
@@ -226,16 +193,6 @@ const {
const policyStore = usePolicyV1Store();
const environmentList = useEnvironmentV1List();
-const sqlReviewPolicy = useReviewPolicyByEnvironmentName(
- computed(() => {
- return create.value ? undefined : environment.value.name;
- })
-);
-
-const allowEditSQLReviewPolicy = computed(() => {
- return hasPermission("bb.policies.update");
-});
-
const disableCopyDataPolicy = computed(() => {
const policies = policyStore.policyList.filter(
(policy) =>
@@ -298,40 +255,6 @@ const validateResourceId = async (
return [];
};
-const toggleSQLReviewPolicy = async (on: boolean) => {
- const policy = sqlReviewPolicy.value;
- if (!policy) return;
- const originalOn = policy.enforce;
- if (on === originalOn) return;
- await useSQLReviewStore().updateReviewPolicy({
- id: policy.id,
- enforce: on,
- });
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("sql-review.policy-updated"),
- });
-};
-
-const onSQLReviewPolicyClick = () => {
- if (sqlReviewPolicy.value) {
- router.push({
- name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
- params: {
- sqlReviewPolicySlug: sqlReviewPolicySlug(sqlReviewPolicy.value),
- },
- });
- } else {
- router.push({
- name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
- query: {
- environmentId: environment.value.uid,
- },
- });
- }
-};
-
const upsertPolicy = async (on: boolean) => {
if (!hasFeature("bb.feature.access-control")) {
state.value.missingRequiredFeature = "bb.feature.access-control";
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
index 9915f637d7..b66229aaea 100644
--- a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
@@ -117,7 +117,7 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { SQLRuleEditDialog } from "@/components/SQLReview/components";
import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/router/dashboard/workspaceRoutes";
-import { useReviewPolicyByEnvironmentName } from "@/store";
+import { useReviewPolicyByResource } from "@/store";
import type { RuleTemplate } from "@/types";
import {
GeneralErrorCode,
@@ -292,7 +292,7 @@ const showCategoryColumn = computed((): boolean =>
tableRows.value.some((row) => row.category !== "")
);
-const reviewPolicy = useReviewPolicyByEnvironmentName(
+const reviewPolicy = useReviewPolicyByResource(
computed(() => {
return props.environment || UNKNOWN_ENVIRONMENT_NAME;
})
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
index ab9fa1ecc6..89309e28ef 100644
--- a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
@@ -117,7 +117,7 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { SQLRuleEditDialog } from "@/components/SQLReview/components";
import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/router/dashboard/workspaceRoutes";
-import { useReviewPolicyByEnvironmentName } from "@/store";
+import { useReviewPolicyByResource } from "@/store";
import type { RuleTemplate } from "@/types";
import {
GeneralErrorCode,
@@ -292,7 +292,7 @@ const showCategoryColumn = computed((): boolean =>
tableRows.value.some((row) => row.category !== "")
);
-const reviewPolicy = useReviewPolicyByEnvironmentName(
+const reviewPolicy = useReviewPolicyByResource(
computed(() => {
return props.environment || UNKNOWN_ENVIRONMENT_NAME;
})
diff --git a/frontend/src/components/Project/ProjectGeneralSettingPanel.vue b/frontend/src/components/Project/ProjectGeneralSettingPanel.vue
index 01af3b8377..4615f7ead6 100644
--- a/frontend/src/components/Project/ProjectGeneralSettingPanel.vue
+++ b/frontend/src/components/Project/ProjectGeneralSettingPanel.vue
@@ -61,43 +61,6 @@
</div>
</div>
- <div class="flex flex-col">
- <div for="name" class="text-sm font-medium text-control-light">
- {{ $t("common.issue") }}
- </div>
- <div class="mt-2">
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
- <label
- class="flex items-center gap-x-2"
- :class="[allowEdit ? 'cursor-pointer' : 'cursor-not-allowed']"
- >
- <NCheckbox
- :disabled="!allowEdit"
- :checked="restrictIssueCreationForSQLReview"
- :label="
- $t(
- 'settings.general.workspace.restrict-issue-creation-for-sql-review.title'
- )
- "
- @update:checked="handleRestrictIssueCreationForSQLReviewToggle"
- />
- </label>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
- <div class="mb-3 text-sm text-gray-400">
- {{
- $t(
- "settings.general.workspace.restrict-issue-creation-for-sql-review.description"
- )
- }}
- </div>
- </div>
- </div>
-
<div v-if="allowEdit" class="flex justify-end">
<NButton type="primary" :disabled="!allowSave" @click.prevent="save">
{{ $t("common.update") }}
@@ -114,22 +77,13 @@
<script lang="ts" setup>
import { cloneDeep, isEmpty } from "lodash-es";
-import { NTooltip, NCheckbox } from "naive-ui";
-import { computed, reactive, watchEffect } from "vue";
+import { NTooltip } from "naive-ui";
+import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";
import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";
-import {
- hasFeature,
- pushNotification,
- useProjectV1Store,
- usePolicyV1Store,
-} from "@/store";
+import { hasFeature, pushNotification, useProjectV1Store } from "@/store";
import type { FeatureType } from "@/types";
import { DEFAULT_PROJECT_ID } from "@/types";
-import {
- PolicyResourceType,
- PolicyType,
-} from "@/types/proto/v1/org_policy_service";
import type { Project } from "@/types/proto/v1/project_service";
import { TenantMode } from "@/types/proto/v1/project_service";
import { extractProjectResourceName } from "@/utils";
@@ -148,14 +102,6 @@ const props = defineProps<{
const { t } = useI18n();
const projectV1Store = useProjectV1Store();
-const policyV1Store = usePolicyV1Store();
-
-watchEffect(async () => {
- await policyV1Store.getOrFetchPolicyByParentAndType({
- parentPath: props.project.name,
- policyType: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
- });
-});
const state = reactive<LocalState>({
title: props.project.title,
@@ -174,31 +120,6 @@ const allowSave = computed((): boolean => {
);
});
-const restrictIssueCreationForSQLReview = computed((): boolean => {
- return (
- policyV1Store.getPolicyByParentAndType({
- parentPath: props.project.name,
- policyType: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
- })?.restrictIssueCreationForSqlReviewPolicy?.disallow ?? false
- );
-});
-
-const handleRestrictIssueCreationForSQLReviewToggle = async (on: boolean) => {
- await policyV1Store.createPolicy(props.project.name, {
- type: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
- resourceType: PolicyResourceType.PROJECT,
- restrictIssueCreationForSqlReviewPolicy: {
- disallow: on,
- },
- });
-
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("settings.general.workspace.config-updated"),
- });
-};
-
const save = () => {
const projectPatch = cloneDeep(props.project);
const updateMask: string[] = [];
diff --git a/frontend/src/components/Project/ProjectSecuritySettingPanel.vue b/frontend/src/components/Project/ProjectSecuritySettingPanel.vue
new file mode 100644
index 0000000000..a18655ed61
--- /dev/null
+++ b/frontend/src/components/Project/ProjectSecuritySettingPanel.vue
@@ -0,0 +1,91 @@
+<template>
+ <div class="w-full flex flex-col justify-start items-start pt-6 space-y-4">
+ <h3 class="text-lg font-medium leading-7 text-main">
+ {{ $t("settings.sidebar.security-and-policy") }}
+ </h3>
+ <SQLReviewForResource :resource="project.name" :allow-edit="allowEdit" />
+ <div class="mt-2">
+ <NTooltip placement="top-start" :disabled="allowEdit">
+ <template #trigger>
+ <label
+ class="flex items-center gap-x-2"
+ :class="[allowEdit ? 'cursor-pointer' : 'cursor-not-allowed']"
+ >
+ <NCheckbox
+ :disabled="!allowEdit"
+ :checked="restrictIssueCreationForSQLReview"
+ :label="
+ $t(
+ 'settings.general.workspace.restrict-issue-creation-for-sql-review.title'
+ )
+ "
+ @update:checked="handleRestrictIssueCreationForSQLReviewToggle"
+ />
+ </label>
+ </template>
+ <span class="text-sm text-gray-400 -translate-y-2">
+ {{ $t("settings.general.workspace.only-admin-can-edit") }}
+ </span>
+ </NTooltip>
+ <div class="mb-3 text-sm text-gray-400">
+ {{
+ $t(
+ "settings.general.workspace.restrict-issue-creation-for-sql-review.description"
+ )
+ }}
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { NTooltip, NCheckbox } from "naive-ui";
+import { computed, watchEffect } from "vue";
+import { useI18n } from "vue-i18n";
+import { pushNotification, usePolicyV1Store } from "@/store";
+import type { ComposedProject } from "@/types";
+import {
+ PolicyResourceType,
+ PolicyType,
+} from "@/types/proto/v1/org_policy_service";
+
+const props = defineProps<{
+ project: ComposedProject;
+ allowEdit: boolean;
+}>();
+
+const { t } = useI18n();
+const policyV1Store = usePolicyV1Store();
+
+watchEffect(async () => {
+ await policyV1Store.getOrFetchPolicyByParentAndType({
+ parentPath: props.project.name,
+ policyType: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
+ });
+});
+
+const restrictIssueCreationForSQLReview = computed((): boolean => {
+ return (
+ policyV1Store.getPolicyByParentAndType({
+ parentPath: props.project.name,
+ policyType: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
+ })?.restrictIssueCreationForSqlReviewPolicy?.disallow ?? false
+ );
+});
+
+const handleRestrictIssueCreationForSQLReviewToggle = async (on: boolean) => {
+ await policyV1Store.createPolicy(props.project.name, {
+ type: PolicyType.RESTRICT_ISSUE_CREATION_FOR_SQL_REVIEW,
+ resourceType: PolicyResourceType.PROJECT,
+ restrictIssueCreationForSqlReviewPolicy: {
+ disallow: on,
+ },
+ });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("settings.general.workspace.config-updated"),
+ });
+};
+</script>
diff --git a/frontend/src/components/ProjectSettingPanel.vue b/frontend/src/components/ProjectSettingPanel.vue
index c6f731962d..386087a7f5 100644
--- a/frontend/src/components/ProjectSettingPanel.vue
+++ b/frontend/src/components/ProjectSettingPanel.vue
@@ -2,6 +2,7 @@
<div class="w-full space-y-6 mb-6">
<div class="divide-y divide-block-border space-y-6">
<ProjectGeneralSettingPanel :project="project" :allow-edit="allowEdit" />
+ <ProjectSecuritySettingPanel :project="project" :allow-edit="allowEdit" />
<ProjectBranchProtectionRulesSettingPanel
:project="project"
:allow-edit="allowEdit"
@@ -21,6 +22,7 @@
import type { ComposedProject } from "@/types";
import ProjectArchiveRestoreButton from "./Project/ProjectArchiveRestoreButton.vue";
import ProjectGeneralSettingPanel from "./Project/ProjectGeneralSettingPanel.vue";
+import ProjectSecuritySettingPanel from "./Project/ProjectSecuritySettingPanel.vue";
defineProps<{
project: ComposedProject;
diff --git a/frontend/src/components/SQLCheck/SQLCheckButton.vue b/frontend/src/components/SQLCheck/SQLCheckButton.vue
index 1999615b52..404e3e0393 100644
--- a/frontend/src/components/SQLCheck/SQLCheckButton.vue
+++ b/frontend/src/components/SQLCheck/SQLCheckButton.vue
@@ -121,7 +121,7 @@ const context = useSQLCheckContext();
const confirmDialog = ref<Defer<boolean>>();
const reviewPolicy = computedAsync(async () => {
- return await useSQLReviewStore().getOrFetchReviewPolicyByEnvironmentName(
+ return await useSQLReviewStore().getOrFetchReviewPolicyByResource(
props.database.effectiveEnvironment
);
}, undefined);
diff --git a/frontend/src/components/SQLReview/SQLReviewCreation.vue b/frontend/src/components/SQLReview/SQLReviewCreation.vue
index 6cd24971fa..4df783e50d 100644
--- a/frontend/src/components/SQLReview/SQLReviewCreation.vue
+++ b/frontend/src/components/SQLReview/SQLReviewCreation.vue
@@ -17,16 +17,19 @@
<SQLReviewInfo
:name="state.name"
:resource-id="state.resourceId"
- :selected-environment="props.selectedEnvironment"
- :available-environment-list="availableEnvironmentList"
+ :attached-resources="state.attachedResources"
:selected-template="
state.pendingApplyTemplate || state.selectedTemplate
"
:is-edit="!!policy"
:is-create="!isUpdate"
+ :allow-change-attached-resource="allowChangeAttachedResource"
@select-template="tryApplyTemplate"
@name-change="(val: string) => (state.name = val)"
@resource-id-change="(val: string) => (state.resourceId = val)"
+ @attached-resources-change="
+ (val: string[]) => (state.attachedResources = val)
+ "
/>
</template>
<template #1>
@@ -53,9 +56,11 @@ import {
pushNotification,
useSQLReviewStore,
useSubscriptionV1Store,
- useEnvironmentV1List,
} from "@/store";
-import { reviewConfigNamePrefix } from "@/store/modules/v1/common";
+import {
+ reviewConfigNamePrefix,
+ getReviewConfigId,
+} from "@/store/modules/v1/common";
import type {
RuleTemplate,
SQLReviewPolicyTemplate,
@@ -67,7 +72,6 @@ import {
convertRuleTemplateToPolicyRule,
ruleIsAvailableInSubscription,
} from "@/types";
-import type { Environment } from "@/types/proto/v1/environment_service";
import { SQLReviewRuleLevel } from "@/types/proto/v1/org_policy_service";
import { hasWorkspacePermissionV2 } from "@/utils";
import SQLReviewConfig from "./SQLReviewConfig.vue";
@@ -78,6 +82,7 @@ interface LocalState {
currentStep: number;
name: string;
resourceId: string;
+ attachedResources: string[];
selectedRuleList: RuleTemplate[];
selectedTemplate: SQLReviewPolicyTemplate | undefined;
ruleUpdated: boolean;
@@ -88,7 +93,7 @@ const props = withDefaults(
defineProps<{
policy?: SQLReviewPolicy;
name?: string;
- selectedEnvironment: Environment;
+ selectedResources: string[];
selectedRuleList?: RuleTemplate[];
}>(),
{
@@ -119,7 +124,8 @@ const STEP_LIST = [
const state = reactive<LocalState>({
currentStep: BASIC_INFO_STEP,
name: props.name || t("sql-review.create.basic-info.display-name-default"),
- resourceId: "",
+ resourceId: props.policy ? getReviewConfigId(props.policy.id) : "",
+ attachedResources: props.selectedResources,
selectedRuleList: [...props.selectedRuleList],
selectedTemplate: props.policy
? rulesToTemplate(props.policy, false /* withDisabled=false */)
@@ -130,6 +136,13 @@ const state = reactive<LocalState>({
const isUpdate = computed(() => !!props.policy);
+const allowChangeAttachedResource = computed(() => {
+ if (isUpdate.value) {
+ return (props.policy?.resources ?? []).length === 0;
+ }
+ return props.selectedResources.length === 0;
+});
+
const onTemplateApply = (template: SQLReviewPolicyTemplate | undefined) => {
if (!template) {
return;
@@ -157,16 +170,6 @@ const onTemplateApply = (template: SQLReviewPolicyTemplate | undefined) => {
);
};
-const availableEnvironmentList = computed((): Environment[] => {
- const environmentList = useEnvironmentV1List();
- const filteredList = store.availableEnvironments(
- environmentList.value,
- props.policy?.id
- );
-
- return filteredList;
-});
-
const onCancel = () => {
if (props.policy) {
emit("cancel");
@@ -182,8 +185,9 @@ const allowNext = computed((): boolean => {
case BASIC_INFO_STEP:
return (
!!state.name &&
- state.selectedRuleList.length > 0 &&
- !!props.selectedEnvironment
+ !!state.resourceId &&
+ state.attachedResources.length > 0 &&
+ state.selectedRuleList.length > 0
);
case CONFIGURE_RULE_STEP:
return state.selectedRuleList.length > 0;
@@ -230,6 +234,7 @@ const tryFinishSetup = async () => {
const upsert = {
title: state.name,
ruleList,
+ resources: state.attachedResources,
};
if (isUpdate.value) {
@@ -237,20 +242,20 @@ const tryFinishSetup = async () => {
id: props.policy!.id,
...upsert,
});
+
pushNotification({
module: "bytebase",
style: "SUCCESS",
title: t("sql-review.policy-updated"),
});
} else {
- if (!props.selectedEnvironment) {
+ if (state.attachedResources.length === 0) {
return;
}
try {
await store.createReviewPolicy({
...upsert,
id: `${reviewConfigNamePrefix}${state.resourceId}`,
- environmentPath: props.selectedEnvironment.name,
});
pushNotification({
module: "bytebase",
diff --git a/frontend/src/components/SQLReview/SQLReviewInfo.vue b/frontend/src/components/SQLReview/SQLReviewInfo.vue
index df892915db..eb83d6900d 100644
--- a/frontend/src/components/SQLReview/SQLReviewInfo.vue
+++ b/frontend/src/components/SQLReview/SQLReviewInfo.vue
@@ -1,26 +1,70 @@
<template>
<div class="space-y-6">
- <div v-if="selectedEnvironment">
+ <div>
<label class="textlabel">
- {{ $t("sql-review.create.basic-info.environments") }}
+ {{ $t("sql-review.create.basic-info.attach-resource") }}
<span style="color: red">*</span>
</label>
<p class="mt-1 textinfolabel">
- {{ $t("sql-review.create.basic-info.environments-label") }}
+ {{ $t("sql-review.create.basic-info.attach-resource-label") }}
</p>
- <BBAttention
- v-if="availableEnvironmentList.length === 0"
+ <NRadioGroup
+ v-model:value="attachResourceType"
+ :disabled="!allowChangeAttachedResource"
+ class="space-x-2 mt-2"
+ >
+ <NRadio value="environment">{{ $t("common.environment") }}</NRadio>
+ <NRadio value="project">{{ $t("common.project") }}</NRadio>
+ </NRadioGroup>
+ <EnvironmentSelect
+ v-if="attachResourceType === 'environment'"
class="mt-2"
- type="warning"
- :title="$t('common.environment')"
- :description="
- $t('sql-review.create.basic-info.no-available-environment-desc')
+ required
+ name="environment"
+ :environment="attachedResources[0]"
+ :use-resource-id="true"
+ :disabled="!allowChangeAttachedResource"
+ :filter="(env: Environment, _: number) => filterResource(env.name)"
+ @update:environment="
+ (val: string | undefined) => {
+ if (!val) {
+ $emit('attached-resources-change', []);
+ } else {
+ $emit('attached-resources-change', [val]);
+ }
+ }
"
/>
- <BBTextField
- class="mt-2 w-full"
- :value="environmentV1Name(selectedEnvironment)"
- :disabled="true"
+ <ProjectSelect
+ v-if="attachResourceType === 'project'"
+ class="mt-2"
+ style="width: 100%"
+ required
+ :project="attachedResources[0]"
+ :use-resource-id="true"
+ :disabled="!allowChangeAttachedResource"
+ :filter="(proj: Project, _: number) => filterResource(proj.name)"
+ @update:project="
+ (val: string | undefined) => {
+ if (!val) {
+ $emit('attached-resources-change', []);
+ } else {
+ $emit('attached-resources-change', [val]);
+ }
+ }
+ "
+ />
+ <DatabaseSelect
+ v-if="attachResourceType === 'database'"
+ class="mt-2"
+ style="width: 100%"
+ required
+ :multiple="true"
+ :databases="attachedResources"
+ :use-resource-id="true"
+ :disabled="!allowChangeAttachedResource"
+ :filter="(db: Database, _: number) => filterResource(db.name)"
+ @update:databases="$emit('attached-resources-change', $event)"
/>
</div>
<div>
@@ -45,7 +89,7 @@
editing-class="mt-6"
resource-type="review-config"
:value="resourceId"
- :readonly="false"
+ :readonly="!isCreate"
:resource-title="name"
:suffix="true"
:validate="validateResourceId"
@@ -65,58 +109,76 @@
<script lang="ts" setup>
import { Status } from "nice-grpc-common";
-import { type PropType, ref } from "vue";
+import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { BBTextField } from "@/bbkit";
import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";
-import { reviewConfigServiceClient } from "@/grpcweb";
-import { reviewConfigNamePrefix } from "@/store/modules/v1/common";
+import { useSQLReviewStore } from "@/store";
+import {
+ reviewConfigNamePrefix,
+ projectNamePrefix,
+ isDatabaseName,
+} from "@/store/modules/v1/common";
import type { SQLReviewPolicyTemplate } from "@/types";
import type { ResourceId, ValidatedMessage } from "@/types";
+import type { Database } from "@/types/proto/v1/database_service";
import type { Environment } from "@/types/proto/v1/environment_service";
-import { environmentV1Name } from "@/utils";
+import type { Project } from "@/types/proto/v1/project_service";
import { getErrorCode } from "@/utils/grpcweb";
import { SQLReviewTemplateSelector } from "./components";
+import { type ResourceType } from "./components/useReviewConfigAttachedResource";
-const props = defineProps({
- name: {
- required: true,
- type: String,
- },
- resourceId: {
- required: true,
- type: String,
- },
- isCreate: {
- required: true,
- type: Boolean,
- },
- selectedEnvironment: {
- required: true,
- type: Object as PropType<Environment>,
- },
- availableEnvironmentList: {
- required: true,
- type: Array as PropType<Environment[]>,
- },
- selectedTemplate: {
- type: Object as PropType<SQLReviewPolicyTemplate>,
- default: undefined,
- },
- isEdit: {
- required: true,
- type: Boolean,
- },
-});
+const props = defineProps<{
+ name: string;
+ resourceId: string;
+ attachedResources: string[];
+ isCreate: boolean;
+ selectedTemplate?: SQLReviewPolicyTemplate;
+ isEdit: boolean;
+ allowChangeAttachedResource: boolean;
+}>();
const emit = defineEmits<{
(event: "name-change", name: string): void;
(event: "resource-id-change", resourceId: string): void;
+ (event: "attached-resources-change", resourceId: string[]): void;
(event: "select-template", template: SQLReviewPolicyTemplate): void;
}>();
+const sqlReviewStore = useSQLReviewStore();
+
+const attachResourceType = ref<ResourceType>(
+ (function (): ResourceType {
+ if (props.attachedResources.length === 0) {
+ return "environment";
+ }
+ if (props.attachedResources.every((resource) => isDatabaseName(resource))) {
+ return "database";
+ }
+ if (
+ props.attachedResources.every((resource) =>
+ resource.startsWith(projectNamePrefix)
+ )
+ ) {
+ return "project";
+ }
+ return "environment";
+ })()
+);
const { t } = useI18n();
+watch(
+ () => attachResourceType.value,
+ () => emit("attached-resources-change", [])
+);
+
+const filterResource = (name: string): boolean => {
+ if (!props.allowChangeAttachedResource) {
+ return true;
+ }
+ return !sqlReviewStore.getReviewPolicyByResouce(name);
+};
+
const onTemplatesChange = (templates: {
policy: SQLReviewPolicyTemplate[];
builtin: SQLReviewPolicyTemplate[];
@@ -136,12 +198,10 @@ const validateResourceId = async (
}
try {
- const existed = await reviewConfigServiceClient.getReviewConfig(
- {
- name: `${reviewConfigNamePrefix}${resourceId}`,
- },
- { silent: true }
- );
+ const existed = await sqlReviewStore.fetchReviewPolicyByName({
+ name: `${reviewConfigNamePrefix}${resourceId}`,
+ silent: true,
+ });
if (existed) {
return [
{
diff --git a/frontend/src/components/SQLReview/components/SQLReviewAttachedResource.vue b/frontend/src/components/SQLReview/components/SQLReviewAttachedResource.vue
new file mode 100644
index 0000000000..88789901ab
--- /dev/null
+++ b/frontend/src/components/SQLReview/components/SQLReviewAttachedResource.vue
@@ -0,0 +1,63 @@
+<template>
+ <div class="flex items-center space-x-1">
+ <span v-if="showPrefix && resourcePrefix">{{ `${resourcePrefix}: ` }}</span>
+ <component :is="reviewPolicyResourceComponent" />
+ </div>
+</template>
+
+<script setup lang="tsx">
+import { computed } from "vue";
+import { EnvironmentV1Name, RichDatabaseName } from "@/components/v2";
+import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import {
+ useEnvironmentV1Store,
+ useDatabaseV1Store,
+ useProjectV1Store,
+} from "@/store";
+import { useReviewConfigAttachedResource } from "./useReviewConfigAttachedResource";
+
+const props = defineProps<{
+ resource: string;
+ link?: boolean;
+ showPrefix?: boolean;
+}>();
+
+const environmentV1Store = useEnvironmentV1Store();
+const databaseStore = useDatabaseV1Store();
+const projectStore = useProjectV1Store();
+
+const { resourceType, resourcePrefix } = useReviewConfigAttachedResource(
+ computed(() => props.resource)
+);
+
+const reviewPolicyResourceComponent = computed(() => {
+ switch (resourceType.value) {
+ case "environment": {
+ const environment = environmentV1Store.getEnvironmentByName(
+ props.resource
+ );
+ if (!environment) {
+ return;
+ }
+ return <EnvironmentV1Name environment={environment} link={props.link} />;
+ }
+ case "database": {
+ const database = databaseStore.getDatabaseByName(props.resource);
+ return (
+ <RichDatabaseName
+ database={database}
+ showArrow={false}
+ showInstance={false}
+ />
+ );
+ }
+ case "project": {
+ const project = projectStore.getProjectByName(props.resource);
+ return (
+ <ProjectNameCell mode="ALL_SHORT" project={project} link={props.link} />
+ );
+ }
+ }
+ return null;
+});
+</script>
diff --git a/frontend/src/components/SQLReview/components/SQLReviewForResource.vue b/frontend/src/components/SQLReview/components/SQLReviewForResource.vue
new file mode 100644
index 0000000000..d178f54d45
--- /dev/null
+++ b/frontend/src/components/SQLReview/components/SQLReviewForResource.vue
@@ -0,0 +1,109 @@
+<template>
+ <div class="flex flex-col gap-y-2">
+ <label class="textlabel">
+ {{ $t("sql-review.title") }}
+ </label>
+ <div>
+ <div v-if="sqlReviewPolicy" class="inline-flex items-center gap-x-2">
+ <Switch
+ v-if="allowEditSQLReviewPolicy"
+ :value="sqlReviewPolicy.enforce"
+ :text="true"
+ @update:value="toggleSQLReviewPolicy"
+ />
+ <span
+ class="textlabel normal-link !text-accent"
+ @click="onSQLReviewPolicyClick"
+ >
+ {{ sqlReviewPolicy.name }}
+ </span>
+ </div>
+ <NButton
+ v-else-if="allowCreateSQLReviewPolicy"
+ @click.prevent="onSQLReviewPolicyClick"
+ >
+ {{ $t("sql-review.configure-policy") }}
+ </NButton>
+ <span v-else class="textinfolabel">
+ {{ $t("sql-review.no-policy-set") }}
+ </span>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import {
+ WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+} from "@/router/dashboard/workspaceRoutes";
+import {
+ useCurrentUserV1,
+ pushNotification,
+ useSQLReviewStore,
+ useReviewPolicyByResource,
+} from "@/store";
+import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
+
+const props = defineProps<{
+ resource: string;
+ allowEdit: boolean;
+}>();
+
+const { t } = useI18n();
+const router = useRouter();
+const me = useCurrentUserV1();
+const reviewStore = useSQLReviewStore();
+
+const allowEditSQLReviewPolicy = computed(() => {
+ return (
+ props.allowEdit && hasWorkspacePermissionV2(me.value, "bb.policies.update")
+ );
+});
+
+const allowCreateSQLReviewPolicy = computed(() => {
+ return (
+ props.allowEdit && hasWorkspacePermissionV2(me.value, "bb.policies.create")
+ );
+});
+
+const toggleSQLReviewPolicy = async (on: boolean) => {
+ const policy = sqlReviewPolicy.value;
+ if (!policy) return;
+ const originalOn = policy.enforce;
+ if (on === originalOn) return;
+ await reviewStore.updateReviewPolicy({
+ id: policy.id,
+ enforce: on,
+ });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("sql-review.policy-updated"),
+ });
+};
+
+const onSQLReviewPolicyClick = () => {
+ if (sqlReviewPolicy.value) {
+ router.push({
+ name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ params: {
+ sqlReviewPolicySlug: sqlReviewPolicySlug(sqlReviewPolicy.value),
+ },
+ });
+ } else {
+ router.push({
+ name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ query: {
+ attachedResource: props.resource,
+ },
+ });
+ }
+};
+
+const sqlReviewPolicy = useReviewPolicyByResource(
+ computed(() => props.resource)
+);
+</script>
diff --git a/frontend/src/components/SQLReview/SQLReviewPolicyTable.vue b/frontend/src/components/SQLReview/components/SQLReviewPolicyTable.vue
similarity index 66%
rename from frontend/src/components/SQLReview/SQLReviewPolicyTable.vue
rename to frontend/src/components/SQLReview/components/SQLReviewPolicyTable.vue
index 94e64abae7..c5c000284b 100644
--- a/frontend/src/components/SQLReview/SQLReviewPolicyTable.vue
+++ b/frontend/src/components/SQLReview/components/SQLReviewPolicyTable.vue
@@ -2,27 +2,26 @@
<div>
<BBGrid
:column-list="columnList"
- :data-source="combinedList"
+ :data-source="reviewList"
:row-clickable="false"
class="border hidden md:grid"
>
- <template
- #item="{
- item: { environment, review },
- }: {
- item: EnvironmentReviewPolicy;
- }"
- >
+ <template #item="{ item: review }: { item: SQLReviewPolicy }">
<div class="bb-grid-cell">
- <EnvironmentV1Name
- :environment="environment"
- :link="true"
- :plain="true"
- />
+ <span v-if="review.resources.length === 0">-</span>
+ <div v-else>
+ <SQLReviewAttachedResource
+ v-for="resource in review.resources"
+ :key="resource"
+ :resource="resource"
+ :show-prefix="true"
+ :link="true"
+ />
+ </div>
</div>
<div class="bb-grid-cell">
- <template v-if="review">
- {{ review.name }}
+ <template v-if="review.id">
+ <div :innerHTML="highlight(review.name)" />
</template>
<span v-else class="italic textinfo text-gray-400">
{{ $t("sql-review.no-policy-set") }}
@@ -30,16 +29,16 @@
</div>
<div class="bb-grid-cell justify-center">
<NCheckbox
- :disabled="!review || !hasUpdatePolicyPermission"
- :checked="review?.enforce ?? false"
- @update:checked="toggleReviewEnabled(review!, $event)"
+ :disabled="!review.id || !hasUpdatePolicyPermission"
+ :checked="review.enforce ?? false"
+ @update:checked="toggleReviewEnabled(review, $event)"
/>
</div>
<div class="bb-grid-cell gap-x-2 !pr-[3rem]">
- <template v-if="!review">
+ <template v-if="!review.id">
<NButton
:disabled="!hasUpdatePolicyPermission"
- @click.prevent="handleClickCreate(environment)"
+ @click.prevent="handleClickCreate(review.resources[0])"
>
{{ $t("sql-review.configure-policy") }}
</NButton>
@@ -54,6 +53,7 @@
</NButton>
<BBButtonConfirm
+ v-if="hasDeletePolicyPermission"
type="default"
:disabled="!hasUpdatePolicyPermission"
:style="'DELETE'"
@@ -68,50 +68,50 @@
</div>
</template>
</BBGrid>
+
<div
class="flex flex-col md:hidden border px-2 pb-4 divide-y space-y-4 divide-block-border"
>
<div
- v-for="policy in combinedList"
- :key="policy.review?.id"
+ v-for="(review, i) in reviewList"
+ :key="`${i}-${review.id}`"
class="pt-4 space-y-3"
>
+ <div>
+ <span v-if="review.id" class="text-md">
+ {{ review.name }}
+ </span>
+ <span v-else class="italic textinfo text-gray-400">
+ {{ $t("sql-review.no-policy-set") }}
+ </span>
+ </div>
<div class="flex items-center gap-x-2">
<BBBadge
- v-if="policy.environment"
+ v-for="resource in review.resources"
+ :key="resource"
:can-remove="false"
- :link="`/${policy.environment.name}`"
>
- <EnvironmentV1Name
- :environment="policy.environment"
- :link="false"
- />
+ <SQLReviewAttachedResource :resource="resource" />
</BBBadge>
<BBBadge
- v-if="policy.review && !policy.review.enforce"
+ v-if="review.id && !review.enforce"
:text="$t('sql-review.disabled')"
:can-remove="false"
:badge-style="'DISABLED'"
::badge-style="'DISABLED'"
/>
- <span v-if="policy.review" class="text-md">
- {{ policy.review?.name }}
- </span>
- <span v-else class="italic textinfo text-gray-400">
- {{ $t("sql-review.no-policy-set") }}
- </span>
</div>
<div class="flex items-center gap-x-2">
- <template v-if="!policy.review">
+ <template v-if="!review.id">
<NButton
:disabled="!hasUpdatePolicyPermission"
- @click.prevent="handleClickCreate(policy.environment)"
+ @click.prevent="handleClickCreate(review.resources[0])"
>
{{ $t("sql-review.configure-policy") }}
</NButton>
</template>
<template v-else>
- <NButton @click.prevent="handleClickEdit(policy.review)">
+ <NButton @click.prevent="handleClickEdit(review)">
{{
hasUpdatePolicyPermission
? $t("common.edit")
@@ -120,15 +120,16 @@
</NButton>
<BBButtonConfirm
+ v-if="hasDeletePolicyPermission"
type="default"
- :disabled="!hasDeletePolicyPermission"
+ :disabled="!hasUpdatePolicyPermission"
:style="'DELETE'"
:hide-icon="true"
:button-text="$t('common.delete')"
:ok-text="$t('common.delete')"
- :confirm-title="$t('common.delete') + ` '${policy.review.name}'?`"
+ :confirm-title="$t('common.delete') + ` '${review.name}'?`"
:require-confirm="true"
- @confirm="handleClickDelete(policy.review)"
+ @confirm="handleClickDelete(review)"
/>
</template>
</div>
@@ -137,50 +138,36 @@
</div>
</template>
-<script lang="ts" setup>
+<script setup lang="ts">
import { NCheckbox } from "naive-ui";
-import { computed, onMounted } from "vue";
+import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import type { BBGridColumn } from "@/bbkit";
import { BBButtonConfirm, BBGrid } from "@/bbkit";
-import { EnvironmentV1Name } from "@/components/v2";
import {
WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
} from "@/router/dashboard/workspaceRoutes";
-import {
- pushNotification,
- useCurrentUserV1,
- useSQLReviewStore,
- useEnvironmentV1List,
-} from "@/store";
+import { pushNotification, useCurrentUserV1, useSQLReviewStore } from "@/store";
import type { SQLReviewPolicy } from "@/types";
-import type { Environment } from "@/types/proto/v1/environment_service";
-import {
- extractEnvironmentResourceName,
- hasWorkspacePermissionV2,
- sqlReviewPolicySlug,
-} from "@/utils";
+import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
+import { getHighlightHTMLByRegExp } from "@/utils";
-type EnvironmentReviewPolicy = {
- environment: Environment;
- review: SQLReviewPolicy | undefined;
-};
+const props = defineProps<{
+ reviewList: SQLReviewPolicy[];
+ filter: string;
+}>();
const { t } = useI18n();
const router = useRouter();
const currentUserV1 = useCurrentUserV1();
const sqlReviewStore = useSQLReviewStore();
-onMounted(() => {
- sqlReviewStore.fetchReviewPolicyList();
-});
-
const columnList = computed((): BBGridColumn[] => {
return [
{
- title: t("common.environment"),
+ title: t("common.resource"),
width: "minmax(min-content, auto)",
class: "capitalize",
},
@@ -202,6 +189,19 @@ const columnList = computed((): BBGridColumn[] => {
];
});
+const highlight = (content: string) => {
+ return getHighlightHTMLByRegExp(
+ content,
+ props.filter.toLowerCase().split(" "),
+ /* !caseSensitive */ false,
+ /* className */ "bg-yellow-100"
+ );
+};
+
+const hasCreatePolicyPermission = computed(() => {
+ return hasWorkspacePermissionV2(currentUserV1.value, "bb.policies.create");
+});
+
const hasUpdatePolicyPermission = computed(() => {
return hasWorkspacePermissionV2(currentUserV1.value, "bb.policies.update");
});
@@ -210,39 +210,12 @@ const hasDeletePolicyPermission = computed(() => {
return hasWorkspacePermissionV2(currentUserV1.value, "bb.policies.delete");
});
-const environmentList = useEnvironmentV1List();
-const reviewPolicyList = computed(() => sqlReviewStore.reviewPolicyList);
-
-const combinedList = computed(() => {
- return environmentList.value.map<EnvironmentReviewPolicy>((environment) => {
- const review = reviewPolicyList.value.find(
- (review) => review.environment.name === environment.name
- );
- return {
- environment,
- review,
- };
- });
-});
-
-const toggleReviewEnabled = async (review: SQLReviewPolicy, on: boolean) => {
- await sqlReviewStore.updateReviewPolicy({
- id: review.id,
- enforce: on,
- });
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
-};
-
-const handleClickCreate = (environment: Environment) => {
- if (hasUpdatePolicyPermission.value) {
+const handleClickCreate = (attachedResource: string | undefined) => {
+ if (hasCreatePolicyPermission.value) {
router.push({
name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
query: {
- environmentId: extractEnvironmentResourceName(environment.name),
+ attachedResource,
},
});
} else {
@@ -271,4 +244,16 @@ const handleClickDelete = async (review: SQLReviewPolicy) => {
title: t("sql-review.policy-removed"),
});
};
+
+const toggleReviewEnabled = async (review: SQLReviewPolicy, on: boolean) => {
+ await sqlReviewStore.updateReviewPolicy({
+ id: review.id,
+ enforce: on,
+ });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
</script>
diff --git a/frontend/src/components/SQLReview/components/SQLReviewTemplateSelector.vue b/frontend/src/components/SQLReview/components/SQLReviewTemplateSelector.vue
index c8f9cde59e..17d908221c 100644
--- a/frontend/src/components/SQLReview/components/SQLReviewTemplateSelector.vue
+++ b/frontend/src/components/SQLReview/components/SQLReviewTemplateSelector.vue
@@ -23,13 +23,18 @@
<span class="text-base mt-4 font-medium">
{{ template.review.name }}
</span>
- <p class="text-sm">
- <span class="mr-2">{{ $t("common.environment") }}:</span>
- <EnvironmentV1Name
- :environment="template.review.environment"
- :link="false"
- />
- </p>
+ <div>
+ <BBBadge
+ v-for="resource in template.review.resources"
+ :key="resource"
+ :can-remove="false"
+ >
+ <SQLReviewAttachedResource
+ :resource="resource"
+ :show-prefix="true"
+ />
+ </BBBadge>
+ </div>
<p class="text-sm">
<span class="mr-2">{{ $t("sql-review.enabled-rules") }}:</span>
<span>{{ enabledRuleCount(template) }}</span>
@@ -91,7 +96,6 @@
<script lang="ts" setup>
import { computed, watch } from "vue";
-import { EnvironmentV1Name } from "@/components/v2";
import { useSQLReviewPolicyList } from "@/store";
import type { SQLReviewPolicyTemplate } from "@/types";
import { TEMPLATE_LIST as builtInTemplateList } from "@/types";
diff --git a/frontend/src/components/SQLReview/components/useReviewConfigAttachedResource.ts b/frontend/src/components/SQLReview/components/useReviewConfigAttachedResource.ts
new file mode 100644
index 0000000000..91434225e8
--- /dev/null
+++ b/frontend/src/components/SQLReview/components/useReviewConfigAttachedResource.ts
@@ -0,0 +1,61 @@
+import { type Ref, watchEffect, computed } from "vue";
+import { t } from "@/plugins/i18n";
+import {
+ useEnvironmentV1Store,
+ useDatabaseV1Store,
+ useProjectV1Store,
+} from "@/store";
+import {
+ environmentNamePrefix,
+ projectNamePrefix,
+ isDatabaseName,
+} from "@/store/modules/v1/common";
+
+export type ResourceType = "environment" | "project" | "database";
+
+export const useReviewConfigAttachedResource = (resource: Ref<string>) => {
+ const environmentV1Store = useEnvironmentV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const projectStore = useProjectV1Store();
+
+ const resourceType = computed((): ResourceType | undefined => {
+ if (resource.value.startsWith(environmentNamePrefix)) {
+ return "environment";
+ } else if (isDatabaseName(resource.value)) {
+ return "database";
+ } else if (resource.value.startsWith(projectNamePrefix)) {
+ return "project";
+ }
+ return undefined;
+ });
+
+ const resourcePrefix = computed(() => {
+ switch (resourceType.value) {
+ case "environment":
+ return t("common.environment");
+ case "project":
+ return t("common.project");
+ default:
+ return "";
+ }
+ });
+
+ watchEffect(async () => {
+ switch (resourceType.value) {
+ case "database":
+ await databaseStore.getOrFetchDatabaseByName(resource.value);
+ return;
+ case "environment":
+ await environmentV1Store.getOrFetchEnvironmentByName(resource.value);
+ return;
+ case "project":
+ await projectStore.getOrFetchProjectByName(resource.value);
+ return;
+ }
+ });
+
+ return {
+ resourceType,
+ resourcePrefix,
+ };
+};
diff --git a/frontend/src/components/SQLReview/components/utils.ts b/frontend/src/components/SQLReview/components/utils.ts
index 8eb6cdd701..37d4c306cd 100644
--- a/frontend/src/components/SQLReview/components/utils.ts
+++ b/frontend/src/components/SQLReview/components/utils.ts
@@ -7,14 +7,9 @@ import type {
} from "@/types";
import { convertPolicyRuleToRuleTemplate, TEMPLATE_LIST } from "@/types";
import { Engine } from "@/types/proto/v1/common";
-import type { Environment } from "@/types/proto/v1/environment_service";
import { SQLReviewRuleLevel } from "@/types/proto/v1/org_policy_service";
import type { PayloadForEngine } from "./RuleConfigComponents";
-export const templateIdForEnvironment = (environment: Environment): string => {
- return `bb.sql-review.environment-policy.${environment.name}`;
-};
-
export const rulesToTemplate = (
review: SQLReviewPolicy,
withDisabled = false
@@ -56,7 +51,7 @@ export const rulesToTemplate = (
}
return {
- id: templateIdForEnvironment(review.environment),
+ id: `bb.sql-review.${review.id}`,
review,
ruleList: ruleTemplateList,
};
diff --git a/frontend/src/components/v2/Model/DatabaseName.vue b/frontend/src/components/v2/Model/DatabaseName.vue
deleted file mode 100644
index f6ef98037a..0000000000
--- a/frontend/src/components/v2/Model/DatabaseName.vue
+++ /dev/null
@@ -1,52 +0,0 @@
-<template>
- <component
- :is="link ? 'router-link' : tag"
- v-bind="bindings"
- class="inline-flex items-center gap-x-1"
- :class="link && 'normal-link'"
- >
- <span v-if="prefix" class="ml-1 text-gray-400">{{ prefix }}</span>
- <span>{{ database.name }}</span>
- </component>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import type { ComposedDatabase } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import { databaseV1Url } from "@/utils";
-
-const props = withDefaults(
- defineProps<{
- database: ComposedDatabase;
- tag?: string;
- link?: boolean;
- }>(),
- {
- tag: "span",
- link: true,
- }
-);
-
-const bindings = computed(() => {
- if (props.link) {
- return {
- to: databaseV1Url(props.database),
- activeClass: "",
- exactActiveClass: "",
- onClick: (e: MouseEvent) => {
- e.stopPropagation();
- },
- };
- }
- return {};
-});
-
-const prefix = computed(() => {
- const { database } = props;
- if (database.instanceEntity.engine === Engine.REDIS) {
- return database.instanceEntity.title;
- }
- return "";
-});
-</script>
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue b/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue
index caa17fee31..221cb1f3d3 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue
+++ b/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue
@@ -1,6 +1,6 @@
<template>
<div class="flex flex-row space-x-2 items-center">
- <ProjectV1Name :project="project" :link="false" tag="div" />
+ <ProjectV1Name :project="project" :link="link" tag="div" />
<NTooltip
v-if="
showTenantIcon && project.tenantMode === TenantMode.TENANT_MODE_ENABLED
@@ -50,9 +50,11 @@ const props = withDefaults(
defineProps<{
project: Project;
mode?: Mode;
+ link?: boolean;
}>(),
{
mode: "ALL",
+ link: false,
}
);
diff --git a/frontend/src/components/v2/Model/EnvironmentName.vue b/frontend/src/components/v2/Model/EnvironmentName.vue
deleted file mode 100644
index 0f40094af5..0000000000
--- a/frontend/src/components/v2/Model/EnvironmentName.vue
+++ /dev/null
@@ -1,47 +0,0 @@
-<template>
- <component
- :is="link ? 'router-link' : tag"
- v-bind="bindings"
- class="inline-flex items-center gap-x-1"
- :class="link && 'normal-link'"
- >
- <span>{{ environmentName(environment) }}</span>
- <ProductionEnvironmentIcon
- :environment="environment"
- class="!text-current"
- />
- </component>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import ProductionEnvironmentIcon from "@/components/Environment/ProductionEnvironmentIcon.vue";
-import type { Environment } from "@/types";
-import { environmentName } from "@/utils";
-
-const props = withDefaults(
- defineProps<{
- environment: Environment;
- tag?: string;
- link?: boolean;
- }>(),
- {
- tag: "span",
- link: true,
- }
-);
-
-const bindings = computed(() => {
- if (props.link) {
- return {
- to: `/${props.environment.name}`,
- activeClass: "",
- exactActiveClass: "",
- onClick: (e: MouseEvent) => {
- e.stopPropagation();
- },
- };
- }
- return {};
-});
-</script>
diff --git a/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue b/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
index 672efe6b05..760fb071f5 100644
--- a/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
+++ b/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
@@ -12,45 +12,32 @@
</NTooltip>
</template>
-<script lang="ts">
-import type { PropType } from "vue";
-import { computed, defineComponent } from "vue";
+<script lang="ts" setup>
+import { computed } from "vue";
import { featureToRef } from "@/store";
import type { Environment } from "@/types/proto/v1/environment_service";
import { EnvironmentTier } from "@/types/proto/v1/environment_service";
-export default defineComponent({
- name: "ProductionEnvironmentV1Icon",
- inheritAttrs: false,
- props: {
- environment: {
- type: Object as PropType<Environment>,
- default: undefined,
- },
- tier: {
- type: String as PropType<EnvironmentTier>,
- default: EnvironmentTier.UNPROTECTED,
- },
- tooltip: {
- type: Boolean,
- default: false,
- },
- },
- setup(props) {
- const hasEnvironmentTierPolicyFeature = featureToRef(
- "bb.feature.environment-tier-policy"
- );
+const props = withDefaults(
+ defineProps<{
+ environment: Environment;
+ tier?: EnvironmentTier;
+ tooltip?: boolean;
+ }>(),
+ {
+ tier: EnvironmentTier.UNPROTECTED,
+ tooltip: false,
+ }
+);
- const enabled = computed((): boolean => {
- if (!hasEnvironmentTierPolicyFeature.value) {
- return false;
- }
- return (
- (props.environment?.tier ?? props.tier) === EnvironmentTier.PROTECTED
- );
- });
+const hasEnvironmentTierPolicyFeature = featureToRef(
+ "bb.feature.environment-tier-policy"
+);
- return { enabled };
- },
+const enabled = computed((): boolean => {
+ if (!hasEnvironmentTierPolicyFeature.value) {
+ return false;
+ }
+ return (props.environment?.tier ?? props.tier) === EnvironmentTier.PROTECTED;
});
</script>
diff --git a/frontend/src/components/v2/Model/ProjectName.vue b/frontend/src/components/v2/Model/ProjectName.vue
deleted file mode 100644
index 6a89fc68c8..0000000000
--- a/frontend/src/components/v2/Model/ProjectName.vue
+++ /dev/null
@@ -1,42 +0,0 @@
-<template>
- <component
- :is="link ? 'router-link' : tag"
- v-bind="bindings"
- class="inline-flex items-center gap-x-1"
- :class="link && 'normal-link'"
- >
- <span>{{ projectName(project) }}</span>
- </component>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import type { Project } from "@/types";
-import { projectName } from "@/utils";
-
-const props = withDefaults(
- defineProps<{
- project: Project;
- tag?: string;
- link?: boolean;
- }>(),
- {
- tag: "span",
- link: true,
- }
-);
-
-const bindings = computed(() => {
- if (props.link) {
- return {
- to: `/${props.project.name}`,
- activeClass: "",
- exactActiveClass: "",
- onClick: (e: MouseEvent) => {
- e.stopPropagation();
- },
- };
- }
- return {};
-});
-</script>
diff --git a/frontend/src/components/v2/Model/index.ts b/frontend/src/components/v2/Model/index.ts
index a346d39ee7..7d6cb92584 100644
--- a/frontend/src/components/v2/Model/index.ts
+++ b/frontend/src/components/v2/Model/index.ts
@@ -1,11 +1,8 @@
-import DatabaseName from "./DatabaseName.vue";
import DatabaseV1Name from "./DatabaseV1Name.vue";
import DatabaseView from "./DatabaseView.vue";
-import EnvironmentName from "./EnvironmentName.vue";
import EnvironmentV1Name from "./EnvironmentV1Name.vue";
import EnvironmentV1Table from "./EnvironmentV1Table.vue";
import ProductionEnvironmentV1Icon from "./ProductionEnvironmentV1Icon.vue";
-import ProjectName from "./ProjectName.vue";
import ProjectV1Name from "./ProjectV1Name.vue";
import ProjectV1Table from "./ProjectV1Table.vue";
import RichDatabaseName from "./RichDatabaseName.vue";
@@ -14,14 +11,11 @@ export * from "./Instance";
export * from "./User";
export * from "./DatabaseV1Table";
export {
- DatabaseName,
DatabaseV1Name,
RichDatabaseName,
- EnvironmentName,
EnvironmentV1Name,
EnvironmentV1Table,
ProductionEnvironmentV1Icon,
- ProjectName,
ProjectV1Name,
ProjectV1Table,
DatabaseView,
diff --git a/frontend/src/components/v2/Select/DatabaseSelect.vue b/frontend/src/components/v2/Select/DatabaseSelect.vue
index 247a7ce19c..c7b28e6589 100644
--- a/frontend/src/components/v2/Select/DatabaseSelect.vue
+++ b/frontend/src/components/v2/Select/DatabaseSelect.vue
@@ -1,16 +1,17 @@
<template>
<NSelect
- :value="database ?? null"
+ :value="value"
:options="options"
:placeholder="placeholder ?? $t('database.select')"
:virtual-scroll="true"
+ :multiple="multiple"
:filter="filterByDatabaseName"
:filterable="true"
class="bb-database-select"
style="width: 12rem"
v-bind="$attrs"
:render-label="renderLabel"
- @update:value="$emit('update:database', $event)"
+ @update:value="handleValueUpdated"
/>
</template>
@@ -40,6 +41,7 @@ const slots = useSlots();
const props = withDefaults(
defineProps<{
database?: string;
+ databases?: string[];
environment?: string;
instance?: string;
project?: string;
@@ -48,9 +50,12 @@ const props = withDefaults(
autoReset?: boolean;
placeholder?: string;
filter?: (database: ComposedDatabase, index: number) => boolean;
+ useResourceId?: boolean;
+ multiple?: boolean;
}>(),
{
database: undefined,
+ databases: undefined,
environment: undefined,
instance: undefined,
project: undefined,
@@ -59,11 +64,14 @@ const props = withDefaults(
autoReset: true,
placeholder: undefined,
filter: undefined,
+ useResourceId: false,
+ multiple: false,
}
);
const emit = defineEmits<{
(event: "update:database", value: string | undefined): void;
+ (event: "update:databases", value: string[]): void;
}>();
const { t } = useI18n();
@@ -72,6 +80,34 @@ const { ready } = useSearchDatabaseV1List({
filter: "instance = instances/-",
});
+const value = computed(() => {
+ if (props.multiple) {
+ return props.databases || [];
+ } else {
+ return props.database;
+ }
+});
+
+const handleValueUpdated = (value: string | string[]) => {
+ if (props.multiple) {
+ if (!value) {
+ // normalize value
+ value = [];
+ }
+ emit("update:databases", value as string[]);
+ } else {
+ if (value === null) {
+ // normalize value
+ value = "";
+ }
+ emit("update:database", value as string);
+ }
+};
+
+const getDatabaseValue = (database: ComposedDatabase): string => {
+ return props.useResourceId ? database.name : database.uid;
+};
+
const rawDatabaseList = computed(() => {
const list = useDatabaseV1Store().databaseListByUser(currentUserV1.value);
@@ -117,7 +153,7 @@ const options = computed(() => {
return combinedDatabaseList.value.map<DatabaseSelectOption>((database) => {
return {
database,
- value: database.uid,
+ value: getDatabaseValue(database),
label: database.databaseName,
};
});
@@ -175,7 +211,9 @@ const resetInvalidSelection = () => {
if (
ready.value &&
props.database &&
- !combinedDatabaseList.value.find((item) => item.uid === props.database)
+ !combinedDatabaseList.value.find(
+ (item) => getDatabaseValue(item) === props.database
+ )
) {
emit("update:database", undefined);
}
diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vue
index 9a196c2df4..d1c197a478 100644
--- a/frontend/src/components/v2/Select/ProjectSelect.vue
+++ b/frontend/src/components/v2/Select/ProjectSelect.vue
@@ -49,6 +49,7 @@ const props = withDefaults(
includeAll?: boolean;
includeDefaultProject?: boolean;
includeArchived?: boolean;
+ useResourceId?: boolean;
filter?: (project: ComposedProject, index: number) => boolean;
}>(),
{
@@ -63,6 +64,7 @@ const props = withDefaults(
includeAll: false,
includeDefaultProject: false,
includeArchived: false,
+ useResourceId: false,
filter: () => true,
}
);
@@ -97,10 +99,14 @@ const rawProjectList = computed(() => {
});
});
+const getValue = (project: Project): string => {
+ return props.useResourceId ? project.name : project.uid;
+};
+
const isOrphanValue = computed(() => {
if (props.project === undefined) return false;
- return !rawProjectList.value.find((proj) => proj.uid === props.project);
+ return !rawProjectList.value.find((proj) => getValue(proj) === props.project);
});
const combinedProjectList = computed(() => {
@@ -108,7 +114,7 @@ const combinedProjectList = computed(() => {
if (props.includeArchived) return true;
if (project.state === State.ACTIVE) return true;
// ARCHIVED
- if (project.uid === props.project) return true;
+ if (getValue(project) === props.project) return true;
return false;
});
@@ -168,7 +174,7 @@ const options = computed(() => {
return combinedProjectList.value.map<ProjectSelectOption>((project) => {
return {
project,
- value: project.uid,
+ value: getValue(project),
label:
project.uid === String(DEFAULT_PROJECT_ID)
? t("common.unassigned")
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index d969595dc0..807182c4a7 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -273,7 +273,8 @@
"leave-without-saving": "Leave without saving?",
"configure-now": "Configure now",
"connection": "Connection",
- "permission-denied": "Permission denied"
+ "permission-denied": "Permission denied",
+ "resource": "Resource"
},
"error-page": {
"go-back-home": "Go back home"
@@ -2760,6 +2761,8 @@
"input-then-press-enter": "Input the value then press enter to add",
"not-available-for-free": "Rule is not available for {plan}",
"unlock-full-feature": "Unlock 100+ SQL lint rules",
+ "search-by-name": "Search by name",
+ "no-linked-resources": "No linked resources",
"create": {
"breadcrumb": "Create SQL review policy",
"basic-info": {
@@ -2768,8 +2771,8 @@
"display-name-placeholder": "The review policy name",
"display-name-default": "SQL review policy",
"display-name-label": "A display name to help identifying among different review policies.",
- "environments": "Environments",
- "environments-label": "Apply the review policy to the selected environments. One environment can only link one policy.",
+ "attach-resource": "Attach to resource",
+ "attach-resource-label": "Apply the review policy to the selected resource. One resource can only link one policy.",
"environments-select": "Select environments",
"no-linked-environments": "No linked environment",
"no-available-environment": "No available environment",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a5956e66cf..63a31fff3a 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -273,7 +273,8 @@
"leave-without-saving": "¿Salir sin ahorrar?",
"configure-now": "Configurar ahora",
"connection": "Conexión",
- "permission-denied": "Permiso denegado"
+ "permission-denied": "Permiso denegado",
+ "resource": "Recurso"
},
"error-page": {
"go-back-home": "Volver al inicio"
@@ -2760,6 +2761,8 @@
"input-then-press-enter": "Ingrese el valor y luego presione enter para agregar",
"not-available-for-free": "La regla no está disponible para {plan}",
"unlock-full-feature": "Desbloquear más de 100 reglas de validación de SQL",
+ "search-by-name": "Buscar por nombre",
+ "no-linked-resources": "No hay recursos vinculados",
"create": {
"breadcrumb": "Crear política de revisión SQL",
"basic-info": {
@@ -2768,8 +2771,8 @@
"display-name-placeholder": "El nombre de la política de revisión",
"display-name-default": "Política de revisión SQL",
"display-name-label": "Un nombre para mostrar que ayuda a identificar entre diferentes políticas de revisión.",
- "environments": "Entornos",
- "environments-label": "Aplicar la política de revisión a los entornos seleccionados. Un entorno solo puede estar vinculado a una política.",
+ "attach-resource": "Adjuntar al recurso",
+ "attach-resource-label": "Aplicar la política de revisión al recurso seleccionado. Un recurso sólo puede vincular una política.",
"environments-select": "Seleccionar entornos",
"no-linked-environments": "Ningún entorno vinculado",
"no-available-environment": "Ningún entorno disponible",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 3f3cadd7cc..bbb2b0f013 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -273,7 +273,8 @@
"leave-without-saving": "変更を保存していませんか?",
"configure-now": "今すぐ設定する",
"connection": "接続する",
- "permission-denied": "許可が拒否されました"
+ "permission-denied": "許可が拒否されました",
+ "resource": "リソース"
},
"error-page": {
"go-back-home": "ホームページに戻る"
@@ -2760,6 +2761,8 @@
"input-then-press-enter": "入力後、Enterを押して追加します",
"not-available-for-free": "{plan}定期購入ではこのルールを使用できません",
"unlock-full-feature": "100 を超える SQL レビュー ルールのロックを解除する",
+ "search-by-name": "名前で検索",
+ "no-linked-resources": "リンクされたリソースはありません",
"create": {
"breadcrumb": "監査ポリシーを作成する",
"basic-info": {
@@ -2768,8 +2771,8 @@
"display-name-placeholder": "監査ポリシー名",
"display-name-default": "SQL監査ポリシー",
"display-name-label": "さまざまな監査ポリシーを区別するために使用される名前。",
- "environments": "環境",
- "environments-label": "この監査ポリシーが適用される環境。 1 つの環境に関連付けることができる監査ポリシーは 1 つだけです。",
+ "attach-resource": "リソースにアタッチする",
+ "attach-resource-label": "選択したリソースにレビュー ポリシーを適用します。リソースは 1 つのポリシーにのみ関連付けることができます。",
"environments-select": "環境を選ぶ",
"no-linked-environments": "環境が選択されていません",
"no-available-environment": "代わりの環境がない",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index cc1ee9f076..4d9bd73e33 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -273,7 +273,8 @@
"leave-without-saving": "不保存变动?",
"configure-now": "现在配置",
"connection": "连接",
- "permission-denied": "您没有权限执行此操作"
+ "permission-denied": "您没有权限执行此操作",
+ "resource": "资源"
},
"error-page": {
"go-back-home": "回到主页"
@@ -2760,6 +2761,8 @@
"input-then-press-enter": "输入后按下回车来添加",
"not-available-for-free": "{plan}订阅不能使用该规则",
"unlock-full-feature": "解锁 100+ SQL Review 规则",
+ "search-by-name": "按名称搜索",
+ "no-linked-resources": "没有绑定的资源",
"create": {
"breadcrumb": "创建审核策略",
"basic-info": {
@@ -2768,8 +2771,8 @@
"display-name-placeholder": "审核策略名称",
"display-name-default": "SQL 审核策略",
"display-name-label": "用以区分不同审核策略的名称。",
- "environments": "环境",
- "environments-label": "将该审核策略应用于哪些环境。一个环境只能关联一个审核策略。",
+ "attach-resource": "附加到资源",
+ "attach-resource-label": "将审核政策应用到选定的资源。一个资源只能关联一个政策。",
"environments-select": "选择环境",
"no-linked-environments": "没有选择环境",
"no-available-environment": "没有可供选择的环境",
diff --git a/frontend/src/store/modules/sqlReview.ts b/frontend/src/store/modules/sqlReview.ts
index 92ebca2761..0e184cdeb6 100644
--- a/frontend/src/store/modules/sqlReview.ts
+++ b/frontend/src/store/modules/sqlReview.ts
@@ -1,38 +1,54 @@
-import { pullAt } from "lodash-es";
+import { pullAt, isEqual } from "lodash-es";
import { defineStore } from "pinia";
import { computed, unref, watchEffect } from "vue";
import { reviewConfigServiceClient } from "@/grpcweb";
-import {
- policyNamePrefix,
- environmentNamePrefix,
-} from "@/store/modules/v1/common";
-import type {
- SchemaPolicyRule,
- SQLReviewPolicy,
- IdType,
- MaybeRef,
-} from "@/types";
-import type { Environment } from "@/types/proto/v1/environment_service";
+import { policyNamePrefix } from "@/store/modules/v1/common";
+import type { SchemaPolicyRule, SQLReviewPolicy, MaybeRef } from "@/types";
import {
PolicyType,
policyTypeToJSON,
} from "@/types/proto/v1/org_policy_service";
import { ReviewConfig } from "@/types/proto/v1/review_config_service";
-import { useEnvironmentV1Store } from "./v1/environment";
import { usePolicyV1Store } from "./v1/policy";
const reviewConfigTagName = "bb.tag.review_config";
-const convertToSQLReviewPolicy = async (
- reviewConfig: ReviewConfig
-): Promise<SQLReviewPolicy | undefined> => {
- const environmentName = reviewConfig.resources.find((resource) =>
- resource.startsWith(environmentNamePrefix)
+const upsertReviewConfigTag = async (
+ resources: string[],
+ configName: string
+) => {
+ const policyStore = usePolicyV1Store();
+ await Promise.all(
+ resources.map(async (resourcePath) => {
+ await policyStore.upsertPolicy({
+ updateMask: ["payload"],
+ parentPath: resourcePath,
+ policy: {
+ name: getTagPolicyName(resourcePath),
+ type: PolicyType.TAG,
+ tagPolicy: {
+ tags: {
+ [reviewConfigTagName]: configName,
+ },
+ },
+ },
+ });
+ })
);
- if (!environmentName) {
- return;
- }
+};
+
+const removeReviewConfigTag = async (resources: string[]) => {
+ const policyStore = usePolicyV1Store();
+ await Promise.all(
+ resources.map((resource) =>
+ policyStore.deletePolicy(getTagPolicyName(resource))
+ )
+ );
+};
+const convertToSQLReviewPolicy = (
+ reviewConfig: ReviewConfig
+): SQLReviewPolicy | undefined => {
const ruleList: SchemaPolicyRule[] = [];
for (const r of reviewConfig.rules) {
const rule: SchemaPolicyRule = {
@@ -47,13 +63,10 @@ const convertToSQLReviewPolicy = async (
ruleList.push(rule);
}
- const environment =
- await useEnvironmentV1Store().getOrFetchEnvironmentByName(environmentName);
-
return {
id: reviewConfig.name,
name: reviewConfig.title,
- environment,
+ resources: reviewConfig.resources,
ruleList,
enforce: reviewConfig.enabled,
};
@@ -91,35 +104,15 @@ export const useSQLReviewStore = defineStore("sqlReview", {
];
}
},
- availableEnvironments(
- environmentList: Environment[],
- reviewPolicyId: string | undefined
- ): Environment[] {
- const envMap = environmentList.reduce((map, env) => {
- map.set(env.name, env);
- return map;
- }, new Map<IdType, Environment>());
-
- for (const reviewPolicy of this.reviewPolicyList) {
- if (reviewPolicy.id === reviewPolicyId || !reviewPolicy.environment) {
- continue;
- }
- if (envMap.has(reviewPolicy.environment.name)) {
- envMap.delete(reviewPolicy.environment.name);
- }
- }
-
- return [...envMap.values()];
- },
async createReviewPolicy({
id,
title,
- environmentPath,
+ resources,
ruleList,
}: {
id: string;
title: string;
- environmentPath: string;
+ resources: string[];
ruleList: SchemaPolicyRule[];
}) {
const reviewConfig = await reviewConfigServiceClient.createReviewConfig({
@@ -139,23 +132,10 @@ export const useSQLReviewStore = defineStore("sqlReview", {
},
});
- const policyStore = usePolicyV1Store();
- await policyStore.upsertPolicy({
- updateMask: ["payload"],
- parentPath: environmentPath,
- policy: {
- name: getTagPolicyName(environmentPath),
- type: PolicyType.TAG,
- tagPolicy: {
- tags: {
- [reviewConfigTagName]: reviewConfig.name,
- },
- },
- },
- });
+ await upsertReviewConfigTag(resources, reviewConfig.name);
- reviewConfig.resources = [environmentPath];
- const reviewPolicy = await convertToSQLReviewPolicy(reviewConfig);
+ reviewConfig.resources = resources;
+ const reviewPolicy = convertToSQLReviewPolicy(reviewConfig);
if (!reviewPolicy) {
throw new Error(
`invalid review config ${JSON.stringify(reviewConfig)}`
@@ -175,15 +155,7 @@ export const useSQLReviewStore = defineStore("sqlReview", {
name: targetPolicy.id,
});
- if (!targetPolicy.environment) {
- return;
- }
-
- // TODO(ed): for now, we can just simply delete the tag policy for environment.
- const policyStore = usePolicyV1Store();
- await policyStore.deletePolicy(
- getTagPolicyName(targetPolicy.environment.name)
- );
+ await removeReviewConfigTag(targetPolicy.resources);
pullAt(this.reviewPolicyList, index);
},
@@ -192,11 +164,13 @@ export const useSQLReviewStore = defineStore("sqlReview", {
title,
enforce,
ruleList,
+ resources,
}: {
id: string;
title?: string;
enforce?: boolean;
ruleList?: SchemaPolicyRule[];
+ resources?: string[];
}) {
const index = this.reviewPolicyList.findIndex((g) => g.id === id);
if (index < 0) {
@@ -234,15 +208,27 @@ export const useSQLReviewStore = defineStore("sqlReview", {
reviewConfig: patch,
updateMask,
});
- const reviewPolicy = await convertToSQLReviewPolicy(updated);
+
+ if (resources && !isEqual(resources, targetPolicy.resources)) {
+ await removeReviewConfigTag(targetPolicy.resources);
+ await upsertReviewConfigTag(resources, targetPolicy.id);
+ updated.resources = resources;
+ }
+
+ const reviewPolicy = convertToSQLReviewPolicy(updated);
if (reviewPolicy) {
this.setReviewPolicy(reviewPolicy);
}
},
- getReviewPolicyByEnvironmentName(
- name: string
+ getReviewPolicyByName(name: string) {
+ return this.reviewPolicyList.find((g) => g.id === name);
+ },
+ getReviewPolicyByResouce(
+ resourcePath: string
): SQLReviewPolicy | undefined {
- return this.reviewPolicyList.find((g) => g.environment.name === name);
+ return this.reviewPolicyList.find((policy) => {
+ return policy.resources.find((resource) => resource === resourcePath);
+ });
},
async fetchReviewPolicyList(): Promise<SQLReviewPolicy[]> {
@@ -251,7 +237,7 @@ export const useSQLReviewStore = defineStore("sqlReview", {
const reviewPolicyList: SQLReviewPolicy[] = [];
for (const config of reviewConfigs) {
- const reviewPolicy = await convertToSQLReviewPolicy(config);
+ const reviewPolicy = convertToSQLReviewPolicy(config);
if (reviewPolicy) {
reviewPolicyList.push(reviewPolicy);
}
@@ -259,40 +245,50 @@ export const useSQLReviewStore = defineStore("sqlReview", {
this.reviewPolicyList = reviewPolicyList;
return reviewPolicyList;
},
+ async fetchReviewPolicyByName({
+ name,
+ silent = false,
+ }: {
+ name: string;
+ silent?: boolean;
+ }) {
+ const reviewConfig = await reviewConfigServiceClient.getReviewConfig(
+ {
+ name,
+ },
+ { silent }
+ );
+ if (!reviewConfig) {
+ return;
+ }
+ const reviewPolicy = convertToSQLReviewPolicy(reviewConfig);
+ if (reviewPolicy) {
+ this.setReviewPolicy(reviewPolicy);
+ }
+ return reviewPolicy;
+ },
async getOrFetchReviewPolicyByName(name: string) {
- const policy = this.reviewPolicyList.find((g) => g.id === name);
+ const policy = this.getReviewPolicyByName(name);
if (policy) {
return policy;
}
- const reviewConfig = await reviewConfigServiceClient.getReviewConfig({
+ const reviewPolicy = await this.fetchReviewPolicyByName({
name,
});
- if (!reviewConfig) {
- return;
- }
- const reviewPolicy = await convertToSQLReviewPolicy(reviewConfig);
- if (reviewPolicy) {
- this.setReviewPolicy(reviewPolicy);
- }
return reviewPolicy;
},
- async getOrFetchReviewPolicyByEnvironmentName(
- name: string
+ async getOrFetchReviewPolicyByResource(
+ resourcePath: string
): Promise<SQLReviewPolicy | undefined> {
- const cached = this.getReviewPolicyByEnvironmentName(name);
+ const cached = this.getReviewPolicyByResouce(resourcePath);
if (cached) {
return cached;
}
- const environmentV1Store = useEnvironmentV1Store();
- const environment = await environmentV1Store.getOrFetchEnvironmentByName(
- name,
- true /* silent */
- );
const policyStore = usePolicyV1Store();
const policy = await policyStore.getOrFetchPolicyByName(
- getTagPolicyName(environment.name)
+ getTagPolicyName(resourcePath)
);
if (!policy) {
@@ -318,17 +314,17 @@ export const useSQLReviewPolicyList = () => {
return computed(() => store.reviewPolicyList);
};
-export const useReviewPolicyByEnvironmentName = (
- name: MaybeRef<string | undefined>
+export const useReviewPolicyByResource = (
+ resourcePath: MaybeRef<string | undefined>
) => {
const store = useSQLReviewStore();
watchEffect(() => {
- if (!unref(name)) return;
- store.getOrFetchReviewPolicyByEnvironmentName(unref(name)!);
+ if (!unref(resourcePath)) return;
+ store.getOrFetchReviewPolicyByResource(unref(resourcePath)!);
});
return computed(() => {
- if (!unref(name)) return undefined;
- return store.getReviewPolicyByEnvironmentName(unref(name)!);
+ if (!unref(resourcePath)) return undefined;
+ return store.getReviewPolicyByResouce(unref(resourcePath)!);
});
};
diff --git a/frontend/src/store/modules/v1/common.ts b/frontend/src/store/modules/v1/common.ts
index 0da2506ee8..265d32b7b9 100644
--- a/frontend/src/store/modules/v1/common.ts
+++ b/frontend/src/store/modules/v1/common.ts
@@ -175,3 +175,13 @@ export const getIssueCommentId = (name: string) => {
}
return tokens[2];
};
+
+export const getReviewConfigId = (name: string) => {
+ const tokens = getNameParentTokens(name, [reviewConfigNamePrefix]);
+ return tokens[0];
+};
+
+export const isDatabaseName = (name: string): boolean => {
+ const regex = /^instances\/([^/]+)\/databases\/(.+)$/;
+ return regex.test(name);
+};
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index a29dab64bb..a8bc47ae04 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -1,4 +1,3 @@
-import { Environment as EnvironmentV1 } from "@/types/proto/v1/environment_service";
import { EMPTY_ID, UNKNOWN_ID } from "./const";
import type { DataSource } from "./dataSource";
import type { Database } from "./database";
@@ -251,7 +250,7 @@ const makeUnknown = (type: ResourceType) => {
enforce: false,
name: "",
ruleList: [],
- environment: EnvironmentV1.fromJSON({}),
+ resources: [],
};
switch (type) {
diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.ts
index 2254bc282c..e853bf5a09 100644
--- a/frontend/src/types/sqlReview.ts
+++ b/frontend/src/types/sqlReview.ts
@@ -2,7 +2,6 @@ import { pullAt, cloneDeep, groupBy } from "lodash-es";
import { t } from "@/plugins/i18n";
import type { Engine } from "@/types/proto/v1/common";
import { engineFromJSON } from "@/types/proto/v1/common";
-import type { Environment } from "@/types/proto/v1/environment_service";
import {
SQLReviewRuleLevel,
sQLReviewRuleLevelFromJSON,
@@ -149,7 +148,7 @@ export interface SQLReviewPolicy {
// Domain specific fields
name: string;
ruleList: SchemaPolicyRule[];
- environment: Environment;
+ resources: string[];
}
// RuleTemplate is the rule template. Used by the frontend
diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.ts
index 63d3116405..69d8a4cd4b 100644
--- a/frontend/src/utils/slug.ts
+++ b/frontend/src/utils/slug.ts
@@ -61,7 +61,7 @@ export function taskSlug(name: string, id: IdType): string {
}
export function sqlReviewPolicySlug(reviewPolicy: SQLReviewPolicy): string {
- return [slug(reviewPolicy.name), reviewPolicy.environment.uid].join("-");
+ return reviewPolicy.id;
}
export function worksheetSlugV1(sheet: Worksheet): string {
diff --git a/frontend/src/views/SettingWorkspaceSQLReview.vue b/frontend/src/views/SettingWorkspaceSQLReview.vue
index d2b86b0d34..fb63e55e41 100644
--- a/frontend/src/views/SettingWorkspaceSQLReview.vue
+++ b/frontend/src/views/SettingWorkspaceSQLReview.vue
@@ -1,5 +1,20 @@
<template>
<div class="mx-auto space-y-4">
+ <div class="flex justify-end items-center space-x-2">
+ <SearchBox
+ v-model:value="searchText"
+ :autofocus="true"
+ :placeholder="$t('sql-review.search-by-name')"
+ />
+ <NButton
+ v-if="hasCreatePolicyPermission"
+ type="primary"
+ @click="createSQLReview"
+ >
+ {{ $t("common.add") }}
+ </NButton>
+ </div>
+
<div class="textinfolabel">
{{ $t("sql-review.description") }}
<a
@@ -12,18 +27,102 @@
</a>
</div>
- <SQLReviewPolicyTable />
+ <div class="space-y-6">
+ <SQLReviewPolicyTable
+ :review-list="reviewConfigWithResourceList"
+ :filter="searchText"
+ />
+ <div v-if="reviewConfigWithoutResourceList.length > 0">
+ <h2 class="mb-3">{{ $t("sql-review.no-linked-resources") }}</h2>
+ <SQLReviewPolicyTable
+ :review-list="reviewConfigWithoutResourceList"
+ :filter="searchText"
+ />
+ </div>
+ </div>
</div>
</template>
<script lang="ts" setup>
-import { watchEffect } from "vue";
-import SQLReviewPolicyTable from "@/components/SQLReview/SQLReviewPolicyTable.vue";
-import { useSQLReviewStore } from "@/store";
+import { watchEffect, ref, computed } from "vue";
+import { useRouter } from "vue-router";
+import { WORKSPACE_ROUTE_SQL_REVIEW_CREATE } from "@/router/dashboard/workspaceRoutes";
+import {
+ useSQLReviewStore,
+ useCurrentUserV1,
+ useEnvironmentV1List,
+} from "@/store";
+import { environmentNamePrefix } from "@/store/modules/v1/common";
+import type { SQLReviewPolicy } from "@/types";
+import { hasWorkspacePermissionV2 } from "@/utils";
-const store = useSQLReviewStore();
+const router = useRouter();
+const sqlReviewStore = useSQLReviewStore();
+const searchText = ref("");
+const currentUserV1 = useCurrentUserV1();
+const environmentList = useEnvironmentV1List();
watchEffect(() => {
- store.fetchReviewPolicyList();
+ sqlReviewStore.fetchReviewPolicyList();
+});
+
+const hasCreatePolicyPermission = computed(() => {
+ return hasWorkspacePermissionV2(currentUserV1.value, "bb.policies.create");
+});
+
+const createSQLReview = () => {
+ router.push({
+ name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ });
+};
+
+const filteredReviewConfigList = computed(() => {
+ if (!searchText.value) {
+ return sqlReviewStore.reviewPolicyList;
+ }
+ return sqlReviewStore.reviewPolicyList.filter((config) => {
+ return config.name.toLowerCase().includes(searchText.value.toLowerCase());
+ });
+});
+
+const reviewConfigWithResourceList = computed(() => {
+ const reviewConfigWithEnvironmentList = environmentList.value
+ .map<SQLReviewPolicy>((environment) => {
+ const review = sqlReviewStore.getReviewPolicyByResouce(environment.name);
+
+ return (
+ review ?? {
+ id: "",
+ enforce: false,
+ name: "",
+ ruleList: [],
+ resources: [environment.name],
+ }
+ );
+ })
+ .filter((review) => {
+ if (!searchText.value) {
+ return true;
+ }
+ return review.name.toLowerCase().includes(searchText.value.toLowerCase());
+ });
+
+ return [
+ ...reviewConfigWithEnvironmentList,
+ ...filteredReviewConfigList.value.filter((review) => {
+ return (
+ review.resources.length > 0 &&
+ !review.resources.some((resource) =>
+ resource.startsWith(environmentNamePrefix)
+ )
+ );
+ }),
+ ];
+});
+
+const reviewConfigWithoutResourceList = computed(() => {
+ return filteredReviewConfigList.value.filter((review) => {
+ return review.resources.length === 0;
+ });
});
</script>
diff --git a/frontend/src/views/SettingWorkspaceSQLReviewCreate.vue b/frontend/src/views/SettingWorkspaceSQLReviewCreate.vue
index 7c7a644060..4f8d7fe2e2 100644
--- a/frontend/src/views/SettingWorkspaceSQLReviewCreate.vue
+++ b/frontend/src/views/SettingWorkspaceSQLReviewCreate.vue
@@ -2,8 +2,9 @@
<div class="space-y-4">
<FeatureAttention custom-class="mb-4" feature="bb.feature.sql-review" />
<SQLReviewCreation
+ class="mt-1"
:selected-rule-list="[]"
- :selected-environment="environment"
+ :selected-resources="attachedResources"
/>
</div>
</template>
@@ -11,26 +12,18 @@
<script lang="ts" setup>
import { computed, watchEffect } from "vue";
import { useSQLReviewStore } from "@/store";
-import { environmentNamePrefix } from "@/store/modules/v1/common";
-import { useEnvironmentV1Store } from "@/store/modules/v1/environment";
-import { unknownEnvironment } from "@/types";
-const url = new URL(window.location.href);
-const params = new URLSearchParams(url.search);
-const environmentId = params.get("environmentId") ?? "";
-const envStore = useEnvironmentV1Store();
-
-watchEffect(() => {
- Promise.all([
- useSQLReviewStore().fetchReviewPolicyList(),
- envStore.getEnvironmentByName(`${environmentNamePrefix}${environmentId}`),
- ]);
+const attachedResources = computed(() => {
+ const url = new URL(window.location.href);
+ const params = new URLSearchParams(url.search);
+ const resource = params.get("attachedResource") ?? "";
+ if (resource) {
+ return [resource];
+ }
+ return [];
});
-const environment = computed(() => {
- return (
- envStore.getEnvironmentByName(`${environmentNamePrefix}${environmentId}`) ??
- unknownEnvironment()
- );
+watchEffect(async () => {
+ await useSQLReviewStore().fetchReviewPolicyList();
});
</script>
diff --git a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
index 2644c098bb..bdbecb4d22 100644
--- a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
+++ b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
@@ -6,7 +6,7 @@
class="mt-1"
:policy="reviewPolicy"
:name="reviewPolicy.name"
- :selected-environment="reviewPolicy.environment"
+ :selected-resources="reviewPolicy.resources"
:selected-rule-list="ruleListOfPolicy"
@cancel="state.editMode = false"
/>
@@ -15,16 +15,6 @@
class="flex flex-col gap-y-2 items-start md:items-center gap-x-2 justify-center md:flex-row"
>
<div class="flex-1 flex space-x-2 items-center justify-start">
- <BBBadge
- v-if="reviewPolicy.environment"
- :can-remove="false"
- :link="`/${reviewPolicy.environment.name}`"
- >
- <EnvironmentV1Name
- :environment="reviewPolicy.environment"
- :link="false"
- />
- </BBBadge>
<div v-if="!reviewPolicy.enforce" class="whitespace-nowrap">
<BBBadge
:text="$t('sql-review.disabled')"
@@ -61,12 +51,21 @@
</NButton>
</div>
</div>
- <BBAttention
- v-if="!reviewPolicy.environment"
- class="my-4"
- type="warning"
- :title="$t('sql-review.create.basic-info.no-linked-environments')"
- />
+ <div class="mt-4 space-y-4">
+ <BBAttention v-if="reviewPolicy.resources.length === 0" type="warning">
+ {{ $t("sql-review.no-linked-resources") }}
+ </BBAttention>
+ <div class="flex space-x-2 items-center">
+ <BBBadge
+ v-for="resource in reviewPolicy.resources"
+ :key="resource"
+ :can-remove="false"
+ :link="`/${resource}`"
+ >
+ <SQLReviewAttachedResource :resource="resource" :show-prefix="true" />
+ </BBBadge>
+ </div>
+ </div>
<SQLRuleFilter
:rule-list="state.ruleList"
:params="filterParams"
@@ -133,7 +132,7 @@
/>
</template>
-<script lang="ts" setup>
+<script lang="tsx" setup>
import { useTitle } from "@vueuse/core";
import { cloneDeep, groupBy } from "lodash-es";
import { computed, reactive, toRef, watch, watchEffect } from "vue";
@@ -147,13 +146,11 @@ import {
SQLRuleTable,
} from "@/components/SQLReview/components";
import type { PayloadForEngine } from "@/components/SQLReview/components/RuleConfigComponents";
-import { EnvironmentV1Name } from "@/components/v2";
import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/router/dashboard/workspaceRoutes";
import {
pushNotification,
useCurrentUserV1,
useSQLReviewStore,
- useEnvironmentV1Store,
useSubscriptionV1Store,
} from "@/store";
import type { RuleTemplate, SchemaPolicyRule } from "@/types";
@@ -166,7 +163,7 @@ import {
} from "@/types";
import type { Engine } from "@/types/proto/v1/common";
import { SQLReviewRuleLevel } from "@/types/proto/v1/org_policy_service";
-import { idFromSlug, hasWorkspacePermissionV2 } from "@/utils";
+import { hasWorkspacePermissionV2 } from "@/utils";
const props = defineProps<{
sqlReviewPolicySlug: string;
@@ -189,7 +186,6 @@ const { t } = useI18n();
const store = useSQLReviewStore();
const router = useRouter();
const currentUserV1 = useCurrentUserV1();
-const environmentV1Store = useEnvironmentV1Store();
const subscriptionStore = useSubscriptionV1Store();
const state = reactive<LocalState>({
@@ -208,18 +204,13 @@ const hasPermission = computed(() => {
return hasWorkspacePermissionV2(currentUserV1.value, "bb.policies.update");
});
-const environment = computed(() => {
- const environmentUID = idFromSlug(props.sqlReviewPolicySlug);
- return environmentV1Store.getEnvironmentByUID(environmentUID);
-});
-
watchEffect(async () => {
- await store.getOrFetchReviewPolicyByEnvironmentName(environment.value.name);
+ await store.getOrFetchReviewPolicyByName(props.sqlReviewPolicySlug);
});
const reviewPolicy = computed(() => {
return (
- store.getReviewPolicyByEnvironmentName(environment.value.name) ??
+ store.getReviewPolicyByName(props.sqlReviewPolicySlug) ??
unknown("SQL_REVIEW")
);
});
diff --git a/frontend/src/views/project/ProjectDatabaseLayout.vue b/frontend/src/views/project/ProjectDatabaseLayout.vue
index 72855066ac..20b2afd4a3 100644
--- a/frontend/src/views/project/ProjectDatabaseLayout.vue
+++ b/frontend/src/views/project/ProjectDatabaseLayout.vue
@@ -7,7 +7,7 @@
</template>
<script lang="ts" setup>
-import { onMounted } from "vue";
+import { onMounted, computed } from "vue";
import { provideDatabaseDetailContext } from "@/components/Database/context";
import { useDBSchemaV1Store, useDatabaseV1Store } from "@/store";
import {
@@ -25,9 +25,8 @@ const props = defineProps<{
const databaseStore = useDatabaseV1Store();
const dbSchemaStore = useDBSchemaV1Store();
provideDatabaseDetailContext(
- props.projectId,
- props.instanceId,
- props.databaseName
+ computed(() => props.instanceId),
+ computed(() => props.databaseName)
);
onMounted(async () => {