Skip to content

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

feat: add MySQL execution detail (#9492)

rebelice0ecc3899971e
diff --git a/backend/api/v1/rollout_service_converter.go b/backend/api/v1/rollout_service_converter.go
index 56750c934d..de5a44ab9d 100644
--- a/backend/api/v1/rollout_service_converter.go
+++ b/backend/api/v1/rollout_service_converter.go
@@ -490,6 +490,7 @@ func convertToTaskRun(stateCfg *state.State, taskRun *store.TaskRunMessage) *v1p
if s, ok := v.(state.TaskRunExecutionStatus); ok {
t.ExecutionStatus = s.ExecutionStatus
t.ExecutionStatusUpdateTime = timestamppb.New(s.UpdateTime)
+ t.ExecutionDetail = s.ExecutionDetail
}
}
diff --git a/backend/common/util.go b/backend/common/util.go
index 40d176fb03..0f7e42021c 100644
--- a/backend/common/util.go
+++ b/backend/common/util.go
@@ -28,6 +28,8 @@ const (
MaxSheetCheckSize = 512 * 1024
// MaxSheetSizeForRollback is the maximum size of a sheet for rollback generator to run.
MaxSheetSizeForRollback = 8 * 1024 * 1024
+ // MaxChunksCount is the maximum number of chunks for a sheet.
+ MaxSheetChunksCount = 200
// ExternalURLPlaceholder is the docs link to configure --external-url.
ExternalURLPlaceholder = "https://www.bytebase.com/docs/get-started/install/external-url"
diff --git a/backend/component/state/state.go b/backend/component/state/state.go
index 6e2042fc1e..44a05baa9d 100644
--- a/backend/component/state/state.go
+++ b/backend/component/state/state.go
@@ -103,5 +103,6 @@ type InstanceSlowQuerySyncMessage struct {
type TaskRunExecutionStatus struct {
ExecutionStatus v1pb.TaskRun_ExecutionStatus
+ ExecutionDetail *v1pb.TaskRun_ExecutionDetail
UpdateTime time.Time
}
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index 452c945010..143a63a240 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -483,4 +483,9 @@ func Open(ctx context.Context, dbType storepb.Engine, driverConfig DriverConfig,
type ExecuteOptions struct {
BeginFunc func(ctx context.Context, conn *sql.Conn) error
EndTransactionFunc func(tx *sql.Tx) error
+ // ChunkedSubmission is the flag to indicate if we should use chunked submission for the statement.
+ // If true, we will submit each statement chunk, otherwise we will submit all statements in a batch.
+ // For both cases, we will use one transaction to wrap the statements.
+ ChunkedSubmission bool
+ UpdateExecutionStatus func(*v1pb.TaskRun_ExecutionDetail)
}
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index 5656dbaf6b..aa265aaf56 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -177,23 +177,82 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, opt
return 0, err
}
}
+
+ var totalCommands int
+ var chunks [][]base.SingleSQL
+ if opts.ChunkedSubmission && len(statement) <= common.MaxSheetCheckSize {
+ list, err := mysqlparser.SplitSQL(statement)
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to split sql")
+ }
+ if len(list) == 0 {
+ return 0, nil
+ }
+ totalCommands = len(list)
+ ret, err := util.ChunkedSQLScript(list, common.MaxSheetCheckSize)
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to chunk sql")
+ }
+ chunks = ret
+ } else {
+ chunks = [][]base.SingleSQL{
+ {
+ base.SingleSQL{
+ Text: statement,
+ },
+ },
+ }
+ }
+
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return 0, errors.Wrapf(err, "failed to begin execute transaction")
}
defer tx.Rollback()
+ currentIndex := 0
var totalRowsAffected int64
- sqlResult, err := tx.ExecContext(ctx, statement)
- if err != nil {
- return 0, errors.Wrapf(err, "failed to execute context in a transaction")
- }
- rowsAffected, err := sqlResult.RowsAffected()
- if err != nil {
- // Since we cannot differentiate DDL and DML yet, we have to ignore the error.
- slog.Debug("rowsAffected returns error", log.BBError(err))
+ for _, chunk := range chunks {
+ if len(chunk) == 0 {
+ continue
+ }
+ // Start the current chunk.
+
+ // Set the progress information for the current chunk.
+ if opts.UpdateExecutionStatus != nil {
+ opts.UpdateExecutionStatus(&v1pb.TaskRun_ExecutionDetail{
+ CommandsTotal: int32(totalCommands),
+ CommandsCompleted: int32(currentIndex),
+ CommandStartPosition: &v1pb.TaskRun_ExecutionDetail_Position{
+ // TODO(rebelice): should find the first non-comment and blank line.
+ Line: int32(chunk[0].BaseLine),
+ // TODO(rebelice): we should also set the column position.
+ },
+ CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{
+ // TODO(rebelice): should find the first non-comment and blank line.
+ Line: int32(chunk[len(chunk)-1].BaseLine),
+ // TODO(rebelice): we should also set the column position.
+ },
+ })
+ }
+
+ chunkText, err := util.ConcatChunk(chunk)
+ if err != nil {
+ return 0, err
+ }
+
+ sqlResult, err := tx.ExecContext(ctx, chunkText)
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to execute context in a transaction")
+ }
+ rowsAffected, err := sqlResult.RowsAffected()
+ if err != nil {
+ // Since we cannot differentiate DDL and DML yet, we have to ignore the error.
+ slog.Debug("rowsAffected returns error", log.BBError(err))
+ }
+ totalRowsAffected += rowsAffected
+ currentIndex += len(chunk)
}
- totalRowsAffected += rowsAffected
if err := tx.Commit(); err != nil {
return 0, errors.Wrapf(err, "failed to commit execute transaction")
diff --git a/backend/plugin/db/util/chunk.go b/backend/plugin/db/util/chunk.go
new file mode 100644
index 0000000000..345622503c
--- /dev/null
+++ b/backend/plugin/db/util/chunk.go
@@ -0,0 +1,54 @@
+package util
+
+import (
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+// ChunkedSQLScript splits a SQL script into chunks.
+func ChunkedSQLScript(slice []base.SingleSQL, n int) ([][]base.SingleSQL, error) {
+ if n <= 0 {
+ return nil, errors.Errorf("invalid number of chunks: %d", n)
+ }
+
+ length := len(slice)
+ chunkSize := length / n
+ remainder := length % n
+
+ chunks := make([][]base.SingleSQL, n)
+ start := 0
+
+ for i := 0; i < n; i++ {
+ end := start + chunkSize
+ if i < remainder {
+ end++
+ }
+
+ if start >= end {
+ // Empty chunk.
+ // We can stop here because the remaining chunks will also be empty.
+ break
+ }
+ chunks[i] = slice[start:end]
+ start = end
+ }
+
+ return chunks, nil
+}
+
+// ConcatChunk is the optimization in the case that we have a 100MB text.
+func ConcatChunk(chunk []base.SingleSQL) (string, error) {
+ if len(chunk) == 1 {
+ return chunk[0].Text, nil
+ }
+ var chunkBuf strings.Builder
+ for _, sql := range chunk {
+ if _, err := chunkBuf.WriteString(sql.Text); err != nil {
+ return "", errors.Wrapf(err, "failed to write chunk buffer")
+ }
+ }
+ return chunkBuf.String(), nil
+}
diff --git a/backend/plugin/db/util/chunk_test.go b/backend/plugin/db/util/chunk_test.go
new file mode 100644
index 0000000000..14f9a99ef9
--- /dev/null
+++ b/backend/plugin/db/util/chunk_test.go
@@ -0,0 +1,247 @@
+package util
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+func TestChunkedSQLScript(t *testing.T) {
+ type args struct {
+ script []base.SingleSQL
+ maxChunksCount int
+ }
+ tests := []struct {
+ args args
+ want [][]base.SingleSQL
+ wantErr bool
+ }{
+ {
+ args: args{
+ script: []base.SingleSQL{
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ {
+ Text: "3",
+ },
+ {
+ Text: "4",
+ },
+ {
+ Text: "5",
+ },
+ },
+ maxChunksCount: 2,
+ },
+ want: [][]base.SingleSQL{
+ {
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ {
+ Text: "3",
+ },
+ },
+ {
+ {
+ Text: "4",
+ },
+ {
+ Text: "5",
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ args: args{
+ script: []base.SingleSQL{
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ {
+ Text: "3",
+ },
+ {
+ Text: "4",
+ },
+ {
+ Text: "5",
+ },
+ },
+ maxChunksCount: 3,
+ },
+ want: [][]base.SingleSQL{
+ {
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ },
+ {
+ {
+ Text: "3",
+ },
+ {
+ Text: "4",
+ },
+ },
+ {
+ {
+ Text: "5",
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ args: args{
+ script: []base.SingleSQL{
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ {
+ Text: "3",
+ },
+ {
+ Text: "4",
+ },
+ {
+ Text: "5",
+ },
+ },
+ maxChunksCount: 5,
+ },
+ want: [][]base.SingleSQL{
+
+ {
+ {
+ Text: "1",
+ },
+ },
+ {
+ {
+ Text: "2",
+ },
+ },
+ {
+ {
+ Text: "3",
+ },
+ },
+ {
+ {
+ Text: "4",
+ },
+ },
+ {
+ {
+ Text: "5",
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ args: args{
+ script: []base.SingleSQL{
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ {
+ Text: "3",
+ },
+ {
+ Text: "4",
+ },
+ {
+ Text: "5",
+ },
+ },
+ maxChunksCount: 4,
+ },
+ want: [][]base.SingleSQL{
+
+ {
+ {
+ Text: "1",
+ },
+ {
+ Text: "2",
+ },
+ },
+ {
+ {
+ Text: "3",
+ },
+ },
+ {
+ {
+ Text: "4",
+ },
+ },
+ {
+ {
+ Text: "5",
+ },
+ },
+ },
+ wantErr: false,
+ },
+ }
+
+ for i, tt := range tests {
+ got, err := ChunkedSQLScript(tt.args.script, tt.args.maxChunksCount)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("ChunkedSQLScript() error = %v, wantErr %v", err, tt.wantErr)
+ continue
+ }
+ require.Equal(t, tt.want, got, i)
+ }
+}
+
+func TestRandomChunkedSQLScript(t *testing.T) {
+ length := rand.Int()%10000 + 1
+ var script []base.SingleSQL
+ for i := 0; i < length; i++ {
+ script = append(script, base.SingleSQL{
+ Text: fmt.Sprintf("%d", rand.Int()),
+ })
+ }
+
+ maxChunksCount := rand.Int()%200 + 1
+
+ list, err := ChunkedSQLScript(script, maxChunksCount)
+ require.NoErrorf(t, err, "length %d with maxChunksCount %d", length, maxChunksCount)
+ require.LessOrEqualf(t, len(list), maxChunksCount, "length %d with maxChunksCount %d", length, maxChunksCount)
+ id := 0
+ for _, l := range list {
+ for _, s := range l {
+ require.Equalf(t, script[id].Text, s.Text, "length %d with maxChunksCount %d", length, maxChunksCount)
+ id++
+ }
+ }
+ require.Equalf(t, len(script), id, "length %d with maxChunksCount %d", length, maxChunksCount)
+}
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index 902a9cca65..882d599aa1 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"sort"
"strings"
+ "time"
"github.com/gosimple/slug"
"github.com/pkg/errors"
@@ -29,6 +30,7 @@ import (
"github.com/bytebase/bytebase/backend/store/model"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
)
// Executor is the task executor.
@@ -172,7 +174,7 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.P
return mi, nil
}
-func executeMigration(ctx context.Context, driverCtx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, task *store.TaskMessage, taskRunUID int, statement string, sheetID *int, mi *db.MigrationInfo) (string, string, error) {
+func executeMigration(ctx context.Context, driverCtx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, profile config.Profile, task *store.TaskMessage, taskRunUID int, statement string, sheetID *int, mi *db.MigrationInfo) (string, string, error) {
instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})
if err != nil {
return "", "", err
@@ -214,6 +216,26 @@ func executeMigration(ctx context.Context, driverCtx context.Context, stores *st
opts.EndTransactionFunc = getSetOracleTransactionIDFunc(ctx, task, stores)
}
+ if profile.Mode == common.ReleaseModeDev && stateCfg != nil {
+ switch task.Type {
+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate:
+ switch instance.Engine {
+ case storepb.Engine_MYSQL:
+ opts.ChunkedSubmission = true
+ opts.UpdateExecutionStatus = func(detail *v1pb.TaskRun_ExecutionDetail) {
+ stateCfg.TaskRunExecutionStatuses.Store(taskRunUID,
+ state.TaskRunExecutionStatus{
+ ExecutionStatus: v1pb.TaskRun_EXECUTING,
+ ExecutionDetail: detail,
+ UpdateTime: time.Now(),
+ })
+ }
+ default:
+ // do nothing
+ }
+ }
+ }
+
migrationID, schema, err := utils.ExecuteMigrationDefault(ctx, driverCtx, stores, stateCfg, taskRunUID, driver, mi, statement, sheetID, opts)
if err != nil {
return "", "", err
@@ -632,7 +654,7 @@ func runMigration(ctx context.Context, driverCtx context.Context, store *store.S
return true, nil, err
}
- migrationID, schema, err := executeMigration(ctx, driverCtx, store, dbFactory, stateCfg, task, taskRunUID, statement, sheetID, mi)
+ migrationID, schema, err := executeMigration(ctx, driverCtx, store, dbFactory, stateCfg, profile, task, taskRunUID, statement, sheetID, mi)
if err != nil {
return true, nil, err
}
diff --git a/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue
index 6c991e0e5b..79b911062e 100644
--- a/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue
@@ -68,6 +68,14 @@ const comment = computed(() => {
if (taskRun.executionStatus === TaskRun_ExecutionStatus.PRE_EXECUTING) {
return t("task-run.status.dumping-schema-before-executing-sql");
} else if (taskRun.executionStatus === TaskRun_ExecutionStatus.EXECUTING) {
+ if (taskRun.executionDetail) {
+ return t("task-run.status.executing-sql-detail", {
+ current: taskRun.executionDetail.commandsCompleted + 1,
+ total: taskRun.executionDetail.commandsTotal,
+ start: taskRun.executionDetail.commandStartPosition?.line ?? 0 + 1,
+ end: taskRun.executionDetail.commandEndPosition?.line ?? 0 + 1,
+ });
+ }
return t("task-run.status.executing-sql");
} else if (
taskRun.executionStatus === TaskRun_ExecutionStatus.POST_EXECUTING
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index e7880ad8c1..2f013155fc 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -409,6 +409,7 @@
"enqueued-with-rollout-time": "Waiting to execute after {time}.",
"dumping-schema-before-executing-sql": "Preparing to execute, dumping schema.",
"executing-sql": "Executing SQL.",
+ "executing-sql-detail": "Executing SQL {current} of {total}, from line {start} to line {end}.",
"dumping-schema-after-executing-sql": "SQL execution completed, dumping schema."
}
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 296c34e1af..678d018073 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -409,7 +409,8 @@
"enqueued-with-rollout-time": "Esperando para ejecutar, {time} para ejecutar.",
"dumping-schema-before-executing-sql": "Listo para ejecutar, exportando esquema.",
"executing-sql": "Ejecutando SQL.",
- "dumping-schema-after-executing-sql": "Ejecución SQL completada, exportando esquema ahora."
+ "dumping-schema-after-executing-sql": "Ejecución SQL completada, exportando esquema ahora.",
+ "executing-sql-detail": "Ejecutando SQL {current} de {total}, desde la línea {start} hasta la línea {end}."
}
},
"banner": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 519c187654..507c02ad5a 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -407,6 +407,7 @@
"enqueued-with-rollout-time": "等待执行,{time}后执行。",
"dumping-schema-before-executing-sql": "准备执行,正在导出 schema。",
"executing-sql": "正在执行 SQL。",
+ "executing-sql-detail": "正在执行 SQL {current} / {total}。 SQL 语句位于 {start} 行到 {end} 行。",
"dumping-schema-after-executing-sql": "SQL 执行完毕,正在导出 schema。"
}
},