Skip to content

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

feat: add statement type task check to force separation of DDL and DML (#2181)

rebelicee199f0a11ce8
diff --git a/api/task_check_run.go b/api/task_check_run.go
index 774f966782..87ae7ddc22 100644
--- a/api/task_check_run.go
+++ b/api/task_check_run.go
@@ -67,6 +67,8 @@ const (
TaskCheckDatabaseStatementCompatibility TaskCheckType = "bb.task-check.database.statement.compatibility"
// TaskCheckDatabaseStatementAdvise is the task check type for schema system review policy.
TaskCheckDatabaseStatementAdvise TaskCheckType = "bb.task-check.database.statement.advise"
+ // TaskCheckDatabaseStatementType is the task check type for statement type.
+ TaskCheckDatabaseStatementType TaskCheckType = "bb.task-check.database.statement.type"
// TaskCheckDatabaseConnect is the task check type for database connection.
TaskCheckDatabaseConnect TaskCheckType = "bb.task-check.database.connect"
// TaskCheckInstanceMigrationSchema is the task check type for migrating schemas.
@@ -93,6 +95,12 @@ type TaskCheckDatabaseStatementAdvisePayload struct {
PolicyID int `json:"policyID,omitempty"`
}
+// TaskCheckDatabaseStatementTypePayload is the task check payload for SQL type.
+type TaskCheckDatabaseStatementTypePayload struct {
+ Statement string `json:"statement,omitempty"`
+ DbType db.Type `json:"dbType,omitempty"`
+}
+
// Namespace is the namespace for task check result.
type Namespace string
diff --git a/common/error.go b/common/error.go
index a7c0764e72..6bd1840556 100644
--- a/common/error.go
+++ b/common/error.go
@@ -34,6 +34,10 @@ const (
// 301 task error.
TaskTimingNotAllowed Code = 301
+
+ // 401 task sql type error.
+ TaskTypeNotDML Code = 401
+ TaskTypeNotDDL Code = 402
)
// Int returns the int type of code.
diff --git a/frontend/src/components/Issue/TaskCheckBadgeBar.vue b/frontend/src/components/Issue/TaskCheckBadgeBar.vue
index 5937f8e72f..7071fff5d2 100644
--- a/frontend/src/components/Issue/TaskCheckBadgeBar.vue
+++ b/frontend/src/components/Issue/TaskCheckBadgeBar.vue
@@ -230,6 +230,7 @@ const TaskCheckTypeOrderList: TaskCheckType[] = [
"bb.task-check.general.earliest-allowed-time",
"bb.task-check.database.statement.compatibility",
"bb.task-check.database.statement.syntax",
+ "bb.task-check.database.statement.type",
"bb.task-check.database.connect",
"bb.task-check.instance.migration-schema",
"bb.task-check.database.statement.advise",
@@ -252,6 +253,7 @@ const TaskCheckTypeNameDict = new Map<TaskCheckType, string>([
"task.check-type.compatibility",
],
["bb.task-check.database.statement.advise", "task.check-type.sql-review"],
+ ["bb.task-check.database.statement.type", "task.check-type.statement-type"],
["bb.task-check.database.connect", "task.check-type.connection"],
[
"bb.task-check.instance.migration-schema",
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 2d4f2876b8..1c9910d687 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -242,7 +242,8 @@
"migration-schema": "Migration schema",
"sql-review": "SQL review",
"earliest-allowed-time": "Earliest allowed time",
- "ghost-sync": "gh-ost sync"
+ "ghost-sync": "gh-ost sync",
+ "statement-type": "Statement type"
},
"earliest-allowed-time-hint": "'@:{'common.when'}' specifies the expected execution timing for this task. If this field is not specified, the task will be executed once it has passed all other gating criteria.",
"earliest-allowed-time-unset": "Unset",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index a54a078d43..f64c58f014 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -242,7 +242,8 @@
"migration-schema": "变更 schema",
"sql-review": "SQL 审查",
"earliest-allowed-time": "最早执行时间",
- "ghost-sync": "gh-ost 同步"
+ "ghost-sync": "gh-ost 同步",
+ "statement-type": "语句类型"
},
"earliest-allowed-time-hint": "'@:{'common.when'}' 指定了该任务最早允许执行的时间。如果该字段没有被指定,则任务会在满足其他条件后立即执行。",
"comment": "评论",
diff --git a/frontend/src/types/pipeline/task.ts b/frontend/src/types/pipeline/task.ts
index e3ec75e5a4..151efcf3f6 100644
--- a/frontend/src/types/pipeline/task.ts
+++ b/frontend/src/types/pipeline/task.ts
@@ -213,6 +213,7 @@ export type TaskCheckType =
| "bb.task-check.database.statement.syntax"
| "bb.task-check.database.statement.compatibility"
| "bb.task-check.database.statement.advise"
+ | "bb.task-check.database.statement.type"
| "bb.task-check.database.connect"
| "bb.task-check.instance.migration-schema"
| "bb.task-check.general.earliest-allowed-time"
@@ -234,6 +235,11 @@ export type TaskCheckDatabaseSchemaUpdateGhostCutoverPayload = {
// more to come
};
+export type TaskCheckDatabaseStatementTypePayload = {
+ statement: string;
+ dbType: string;
+};
+
export type TaskCheckStatus = "SUCCESS" | "WARN" | "ERROR";
export type TaskCheckNamespace = "bb.advisor" | "bb.core";
diff --git a/server/server.go b/server/server.go
index d09321b853..9096dd8f12 100644
--- a/server/server.go
+++ b/server/server.go
@@ -232,6 +232,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
statementCompositeExecutor := NewTaskCheckStatementAdvisorCompositeExecutor()
taskCheckScheduler.Register(api.TaskCheckDatabaseStatementAdvise, statementCompositeExecutor)
+ statementTypeExecutor := NewTaskCheckStatementTypeExecutor()
+ taskCheckScheduler.Register(api.TaskCheckDatabaseStatementType, statementTypeExecutor)
+
databaseConnectExecutor := NewTaskCheckDatabaseConnectExecutor()
taskCheckScheduler.Register(api.TaskCheckDatabaseConnect, databaseConnectExecutor)
diff --git a/server/task_check_executor_statement_type.go b/server/task_check_executor_statement_type.go
new file mode 100644
index 0000000000..27b82f6f5c
--- /dev/null
+++ b/server/task_check_executor_statement_type.go
@@ -0,0 +1,109 @@
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/plugin/parser"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+// NewTaskCheckStatementTypeExecutor creates a task check DML executor.
+func NewTaskCheckStatementTypeExecutor() TaskCheckExecutor {
+ return &TaskCheckStatementTypeExecutor{}
+}
+
+// TaskCheckStatementTypeExecutor is the task check DML executor.
+type TaskCheckStatementTypeExecutor struct {
+}
+
+// Run will run the task check database connector executor once.
+func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+ task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)
+ if err != nil {
+ return []api.TaskCheckResult{}, common.WithError(common.Internal, err)
+ }
+ if task == nil {
+ return []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Namespace: api.BBNamespace,
+ Code: common.Internal.Int(),
+ Title: fmt.Sprintf("Failed to find task %v", taskCheckRun.TaskID),
+ Content: err.Error(),
+ },
+ }, nil
+ }
+
+ payload := &api.TaskCheckDatabaseStatementTypePayload{}
+ if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {
+ return nil, common.Errorf(common.Invalid, "invalid check statement type payload: %w", err)
+ }
+
+ if payload.DbType != db.Postgres {
+ return nil, common.Errorf(common.Invalid, "invalid check statement type database type: %s", payload.DbType)
+ }
+
+ stmts, err := parser.Parse(parser.Postgres, parser.Context{}, payload.Statement)
+ if err != nil {
+ //nolint:nilerr
+ return []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Namespace: api.AdvisorNamespace,
+ Code: advisor.StatementSyntaxError.Int(),
+ Title: "Syntax error",
+ Content: err.Error(),
+ },
+ }, nil
+ }
+
+ switch task.Type {
+ case api.TaskDatabaseDataUpdate:
+ for _, node := range stmts {
+ if _, ok := node.(ast.DMLNode); !ok {
+ result = append(result, api.TaskCheckResult{
+ Status: api.TaskCheckStatusError,
+ Namespace: api.BBNamespace,
+ Code: common.TaskTypeNotDML.Int(),
+ Title: "Data change can only run DML",
+ Content: fmt.Sprintf("\"%s\" is not DML", node.Text()),
+ })
+ }
+ }
+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateGhostSync:
+ for _, node := range stmts {
+ _, isDML := node.(ast.DMLNode)
+ _, isSelect := node.(*ast.SelectStmt)
+ _, isExplain := node.(*ast.ExplainStmt)
+ if isDML || isSelect || isExplain {
+ result = append(result, api.TaskCheckResult{
+ Status: api.TaskCheckStatusError,
+ Namespace: api.BBNamespace,
+ Code: common.TaskTypeNotDDL.Int(),
+ Title: "Alter schema can only run DDL",
+ Content: fmt.Sprintf("\"%s\" is not DDL", node.Text()),
+ })
+ }
+ }
+ default:
+ return nil, common.Errorf(common.Invalid, "invalid check statement type task type: %s", task.Type)
+ }
+
+ if len(result) == 0 {
+ result = append(result, api.TaskCheckResult{
+ Status: api.TaskCheckStatusSuccess,
+ Namespace: api.BBNamespace,
+ Code: common.Ok.Int(),
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return result, nil
+}
diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.go
index 75e6cffdd3..c83e5c8775 100644
--- a/server/task_check_scheduler.go
+++ b/server/task_check_scheduler.go
@@ -10,6 +10,7 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/plugin/db"
"go.uber.org/zap"
)
@@ -359,6 +360,25 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *ap
}
}
+ if database.Instance.Engine == db.Postgres {
+ payload, err := json.Marshal(api.TaskCheckDatabaseStatementTypePayload{
+ Statement: statement,
+ DbType: database.Instance.Engine,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal statement type payload: %v, err: %w", task.Name, err)
+ }
+ if _, err := s.server.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{
+ CreatorID: creatorID,
+ TaskID: task.ID,
+ Type: api.TaskCheckDatabaseStatementType,
+ Payload: string(payload),
+ SkipIfAlreadyTerminated: skipIfAlreadyTerminated,
+ }); err != nil {
+ return nil, err
+ }
+ }
+
taskCheckRunFind := &api.TaskCheckRunFind{
TaskID: &task.ID,
}
diff --git a/server/task_scheduler.go b/server/task_scheduler.go
index 26b32e48b4..13f2d29c0e 100644
--- a/server/task_scheduler.go
+++ b/server/task_scheduler.go
@@ -11,6 +11,7 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/plugin/db"
"go.uber.org/zap"
)
@@ -294,6 +295,16 @@ func (s *TaskScheduler) canTransitTaskStatus(ctx context.Context, task *api.Task
return false, nil
}
}
+
+ if instance.Engine == db.Postgres {
+ pass, err = s.server.passCheck(ctx, task, api.TaskCheckDatabaseStatementType, allowedStatus)
+ if err != nil {
+ return false, err
+ }
+ if !pass {
+ return false, nil
+ }
+ }
}
if task.Type == api.TaskDatabaseSchemaUpdateGhostSync {