Skip to content

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

chore: pg execute sql one at a time (#12443)

Danny Xu91dc28f18827
diff --git a/backend/common/util.go b/backend/common/util.go
index 5b120c25df..f7b76917cf 100644
--- a/backend/common/util.go
+++ b/backend/common/util.go
@@ -25,12 +25,6 @@ const (
MaxSheetSize = 1024 * 1024
// MaxSheetCheckSize is the maximum size of a sheet for checking changes.
MaxSheetCheckSize = 1024 * 1024
- // MaxSheetSizeForRollback is the maximum size of a sheet for rollback generator to run.
- MaxSheetSizeForRollback = 8 * 1024 * 1024
- // MaxBinlogSizeLimit defines the upper limit for scanning the binlog text body size in search of a transaction..
- MaxBinlogSizeLimit = 32 * 1024 * 1024
- // MaxChunksCount is the maximum number of chunks for a sheet.
- MaxSheetChunksCount = 200
// The maximum number of bytes for sql results in response body.
// 100 MB.
MaximumSQLResultSize = 100 * 1024 * 1024
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index 4faf2ed65d..94b000f77b 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -310,7 +310,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
var totalCommands int
var commands []base.SingleSQL
- var originalIndex []int
+ var originalIndex []int32
if len(statement) <= common.MaxSheetCheckSize {
singleSQLs, err := mysqlparser.SplitSQL(statement)
if err != nil {
@@ -328,7 +328,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
Text: statement,
},
}
- originalIndex = []int{0}
+ originalIndex = []int32{0}
}
tx, err := conn.BeginTx(ctx, nil)
@@ -367,7 +367,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
})
}
- indexes := []int32{int32(originalIndex[i])}
+ indexes := []int32{originalIndex[i]}
opts.LogCommandExecute(indexes)
sqlResult, err := exer.ExecContext(ctx, command.Text, nil)
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index 9833d59a02..6d34bcad03 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -365,7 +365,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
}
var commands []base.SingleSQL
- var originalIndex []int
+ var originalIndex []int32
var isPlsql bool
if len(statement) <= common.MaxSheetCheckSize {
singleSQLs, err := pgparser.SplitSQL(statement)
@@ -387,7 +387,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
Text: statement,
},
}
- originalIndex = []int{0}
+ originalIndex = []int32{0}
}
if isPlsql {
@@ -465,14 +465,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
defer conn.Close()
if len(remainingSQLs) != 0 {
- var chunks [][]base.SingleSQL
totalCommands := len(remainingSQLs)
- ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)
- if err != nil {
- return 0, errors.Wrapf(err, "failed to chunk sql")
- }
- chunks = ret
- currentIndex := 0
err = conn.Raw(func(driverConn any) error {
conn := driverConn.(*stdlib.Conn).Conn()
@@ -488,39 +481,28 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
return err
}
- for _, chunk := range chunks {
- if len(chunk) == 0 {
- continue
- }
+ for i, command := range remainingSQLs {
// 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),
+ CommandsCompleted: int32(i),
CommandStartPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
})
}
- chunkText, err := util.ConcatChunk(chunk)
- if err != nil {
- return err
- }
-
- var indexes []int32
- for i := currentIndex; i < currentIndex+len(chunk); i++ {
- indexes = append(indexes, int32(originalIndex[remainingSQLsIndex[i]]))
- }
+ indexes := []int32{int32(originalIndex[remainingSQLsIndex[i]])}
opts.LogCommandExecute(indexes)
- rr := tx.Conn().PgConn().Exec(ctx, chunkText)
+ rr := tx.Conn().PgConn().Exec(ctx, command.Text)
results, err := rr.ReadAll()
if err != nil {
opts.LogCommandResponse(indexes, 0, nil, err.Error())
@@ -528,12 +510,12 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
return &db.ErrorWithPosition{
Err: errors.Wrapf(err, "failed to execute context in a transaction"),
Start: &storepb.TaskRunResult_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
End: &storepb.TaskRunResult_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
}
}
@@ -548,7 +530,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
opts.LogCommandResponse(indexes, int32(rowsAffected), allRowsAffected, "")
totalRowsAffected += rowsAffected
- currentIndex += len(chunk)
}
if err := tx.Commit(ctx); err != nil {
diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.go
index 2614b61cdb..ba7b12bbfb 100644
--- a/backend/plugin/db/redshift/redshift.go
+++ b/backend/plugin/db/redshift/redshift.go
@@ -218,15 +218,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
totalRowsAffected := int64(0)
if len(remainingSQLs) != 0 {
- var chunks [][]base.SingleSQL
totalCommands := len(remainingSQLs)
- ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)
- if err != nil {
- return 0, errors.Wrapf(err, "failed to chunk sql")
- }
- chunks = ret
- currentIndex := 0
-
tx, err := driver.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
@@ -237,43 +229,35 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
return 0, err
}
- for _, chunk := range chunks {
- if len(chunk) == 0 {
- continue
- }
+ for i, command := range remainingSQLs {
// 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),
+ CommandsCompleted: int32(i),
CommandStartPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
})
}
- chunkText, err := util.ConcatChunk(chunk)
- if err != nil {
- return 0, err
- }
-
- sqlResult, err := tx.ExecContext(ctx, chunkText)
+ sqlResult, err := tx.ExecContext(ctx, command.Text)
if err != nil {
return 0, &db.ErrorWithPosition{
Err: errors.Wrapf(err, "failed to execute context in a transaction"),
Start: &storepb.TaskRunResult_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
End: &storepb.TaskRunResult_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
}
}
@@ -283,7 +267,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
slog.Debug("rowsAffected returns error", log.BBError(err))
}
totalRowsAffected += rowsAffected
- currentIndex += len(chunk)
}
// Restore the current transaction role to the current user.
diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.go
index 8814037410..20bda64c03 100644
--- a/backend/plugin/db/risingwave/risingwave.go
+++ b/backend/plugin/db/risingwave/risingwave.go
@@ -271,58 +271,42 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
totalRowsAffected := int64(0)
if len(remainingSQLs) != 0 {
- var chunks [][]base.SingleSQL
totalCommands := len(remainingSQLs)
- ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)
- if err != nil {
- return 0, errors.Wrapf(err, "failed to chunk sql")
- }
- chunks = ret
- currentIndex := 0
-
tx, err := driver.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
- for _, chunk := range chunks {
- if len(chunk) == 0 {
- continue
- }
+ for i, command := range remainingSQLs {
// 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),
+ CommandsCompleted: int32(i),
CommandStartPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
})
}
- chunkText, err := util.ConcatChunk(chunk)
- if err != nil {
- return 0, err
- }
-
- sqlResult, err := tx.ExecContext(ctx, chunkText)
+ sqlResult, err := tx.ExecContext(ctx, command.Text)
if err != nil {
return 0, &db.ErrorWithPosition{
Err: errors.Wrapf(err, "failed to execute context in a transaction"),
Start: &storepb.TaskRunResult_Position{
- Line: int32(chunk[0].FirstStatementLine),
- Column: int32(chunk[0].FirstStatementColumn),
+ Line: int32(command.FirstStatementLine),
+ Column: int32(command.FirstStatementColumn),
},
End: &storepb.TaskRunResult_Position{
- Line: int32(chunk[len(chunk)-1].LastLine),
- Column: int32(chunk[len(chunk)-1].LastColumn),
+ Line: int32(command.LastLine),
+ Column: int32(command.LastColumn),
},
}
}
@@ -332,7 +316,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
slog.Debug("rowsAffected returns error", log.BBError(err))
}
totalRowsAffected += rowsAffected
- currentIndex += len(chunk)
}
if err := tx.Commit(); err != nil {
diff --git a/backend/plugin/db/util/chunk.go b/backend/plugin/db/util/chunk.go
deleted file mode 100644
index 345622503c..0000000000
--- a/backend/plugin/db/util/chunk.go
+++ /dev/null
@@ -1,54 +0,0 @@
-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
deleted file mode 100644
index 14f9a99ef9..0000000000
--- a/backend/plugin/db/util/chunk_test.go
+++ /dev/null
@@ -1,247 +0,0 @@
-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/plugin/parser/base/base.go b/backend/plugin/parser/base/base.go
index a59ff69893..6f1aec05f6 100644
--- a/backend/plugin/parser/base/base.go
+++ b/backend/plugin/parser/base/base.go
@@ -104,13 +104,13 @@ func FilterEmptySQL(list []SingleSQL) []SingleSQL {
return result
}
-func FilterEmptySQLWithIndexes(list []SingleSQL) ([]SingleSQL, []int) {
+func FilterEmptySQLWithIndexes(list []SingleSQL) ([]SingleSQL, []int32) {
var result []SingleSQL
- var originalIndex []int
+ var originalIndex []int32
for i, sql := range list {
if !sql.Empty {
result = append(result, sql)
- originalIndex = append(originalIndex, i)
+ originalIndex = append(originalIndex, int32(i))
}
}
return result, originalIndex