Skip to content

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

feat: implement dynamodb execute (#12217)

h3n4l73ce4d93b720
diff --git a/backend/component/sheet/sheet.go b/backend/component/sheet/sheet.go
index 08e56fc824..5d83c1ded6 100644
--- a/backend/component/sheet/sheet.go
+++ b/backend/component/sheet/sheet.go
@@ -33,6 +33,7 @@ func getSheetCommands(engine storepb.Engine, statement string) []*storepb.SheetC
case storepb.Engine_POSTGRES:
case storepb.Engine_ORACLE:
case storepb.Engine_MSSQL:
+ case storepb.Engine_DYNAMODB:
default:
return nil
}
diff --git a/backend/plugin/db/dynamodb/dynamodb.go b/backend/plugin/db/dynamodb/dynamodb.go
index b19000c1cd..5bba51163a 100644
--- a/backend/plugin/db/dynamodb/dynamodb.go
+++ b/backend/plugin/db/dynamodb/dynamodb.go
@@ -8,9 +8,11 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
+ "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
)
@@ -81,8 +83,67 @@ func (*Driver) GetDB() *sql.DB {
}
// Execute executes a SQL statement.
-func (*Driver) Execute(_ context.Context, _ string, _ db.ExecuteOptions) (int64, error) {
- panic("implement me")
+// Execute is usually used for DDL/DML statements without read-operation. The dynamodb driver supports three types of execute:
+//
+// BatchExecuteStatement: This operation allows you to perform batch reads or writes on data stored in DynamoDB, using PartiQL. Each read statement in a BatchExecuteStatement must specify an equality condition on all key attributes. This enforces that each SELECT statement in a batch returns at most a single item.
+//
+// ExecuteStatement: This operation allows you to perform reads and singleton writes on data stored in DynamoDB, using PartiQL.
+// For PartiQL reads ( SELECT statement), if the total number of processed items exceeds the maximum dataset size limit of 1 MB, the read stops and results are returned to the user as a LastEvaluatedKey value to continue the read in a subsequent operation. If the filter criteria in WHERE clause does not match any data, the read will return an empty result set.
+// A single SELECT statement response can return up to the maximum number of items (if using the Limit parameter) or a maximum of 1 MB of data (and then apply any filtering to the results using WHERE clause).
+//
+// ExecuteTransaction: This operation allows you to perform transactional reads or writes on data stored in DynamoDB, using PartiQL.
+// The entire transaction must consist of either read statements or write statements, you cannot mix both in one transaction. The EXISTS function is an exception and can be used to check the condition of specific attributes of the item in a similar manner to ConditionCheck in the TransactWriteItems API.
+//
+// NOTE: Each api contains some constraints which do not be described in api docs. For example, in ExecuteTransaction, cannot include multiple operations on one item.
+// So we use a simple solution here, use parser to split the statement and execute them one by one, unfortunately, we lose the transaction feature.
+func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
+ statements, err := base.SplitMultiSQL(d.GetType(), statement)
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to split multi statement")
+ }
+ nonEmptyStatements, idxMap := base.FilterEmptySQLWithIndexes(statements)
+ commandsTotal := len(nonEmptyStatements)
+
+ for currentIndex, statement := range nonEmptyStatements {
+ if opts.UpdateExecutionStatus != nil {
+ opts.UpdateExecutionStatus(&v1pb.TaskRun_ExecutionDetail{
+ CommandsTotal: int32(commandsTotal),
+ CommandsCompleted: int32(idxMap[currentIndex]),
+ CommandStartPosition: &v1pb.TaskRun_ExecutionDetail_Position{
+ Line: int32(statement.FirstStatementLine),
+ Column: int32(statement.FirstStatementColumn),
+ },
+ CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{
+ Line: int32(statement.LastLine),
+ Column: int32(statement.LastColumn),
+ },
+ })
+ }
+ opts.LogCommandExecute([]int32{int32(idxMap[currentIndex])})
+ _, err := d.client.ExecuteTransaction(ctx, &dynamodb.ExecuteTransactionInput{
+ TransactStatements: []types.ParameterizedStatement{
+ {
+ Statement: &statement.Text,
+ },
+ },
+ })
+ if err != nil {
+ return 0, &db.ErrorWithPosition{
+ Err: errors.Wrapf(err, "failed to execute statement: %s", statement.Text),
+ Start: &storepb.TaskRunResult_Position{
+ Line: int32(statement.FirstStatementLine),
+ Column: int32(statement.FirstStatementColumn),
+ },
+ End: &storepb.TaskRunResult_Position{
+ Line: int32(statement.LastLine),
+ Column: int32(statement.LastColumn),
+ },
+ }
+ }
+ opts.LogCommandResponse([]int32{int32(currentIndex)}, 0, []int32{}, "")
+ }
+
+ return 0, nil
}
// QueryConn queries a SQL statement in a given connection.
diff --git a/backend/plugin/parser/partiql/split.go b/backend/plugin/parser/partiql/split.go
new file mode 100644
index 0000000000..a931bb4c12
--- /dev/null
+++ b/backend/plugin/parser/partiql/split.go
@@ -0,0 +1,83 @@
+package partiql
+
+import (
+ "errors"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/partiql-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ base.RegisterSplitterFunc(storepb.Engine_DYNAMODB, SplitSQL)
+}
+
+func SplitSQL(statement string) ([]base.SingleSQL, error) {
+ lexer := parser.NewPartiQLLexer(antlr.NewInputStream(statement))
+ lexerErrorListener := &base.ParseErrorListener{}
+ lexer.RemoveErrorListeners()
+ lexer.AddErrorListener(lexerErrorListener)
+
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+
+ p := parser.NewPartiQLParserParser(stream)
+ parserErrorListener := &base.ParseErrorListener{}
+ p.RemoveErrorListeners()
+ p.AddErrorListener(parserErrorListener)
+
+ p.BuildParseTrees = true
+ p.SetErrorHandler(antlr.NewBailErrorStrategy())
+
+ tree := p.Script()
+ if lexerErrorListener.Err != nil {
+ return nil, lexerErrorListener.Err
+ }
+
+ if parserErrorListener.Err != nil {
+ return nil, parserErrorListener.Err
+ }
+
+ if tree == nil {
+ return nil, errors.New("failed to split multiple statements")
+ }
+
+ var result []base.SingleSQL
+ tokens := stream.GetAllTokens()
+
+ start := 0
+ for _, semi := range tree.AllCOLON_SEMI() {
+ pos := semi.GetSymbol().GetTokenIndex()
+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start : pos+1])
+ // From antlr4, the line is ONE based, and the column is ZERO based.
+ // So we should minus 1 for the line.
+ result = append(result, base.SingleSQL{
+ Text: stream.GetTextFromTokens(tokens[start], tokens[pos]),
+ BaseLine: tokens[start].GetLine() - 1,
+ LastLine: tokens[pos].GetLine() - 1,
+ LastColumn: tokens[pos].GetColumn(),
+ FirstStatementLine: line,
+ FirstStatementColumn: col,
+ Empty: base.IsEmpty(tokens[start:pos+1], parser.PartiQLLexerCOLON_SEMI),
+ })
+ start = pos + 1
+ }
+ // For the last statement, it may not end with semicolon symbol, EOF symbol instead.
+ eofPos := len(tokens) - 1
+ if start < eofPos {
+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:])
+ // From antlr4, the line is ONE based, and the column is ZERO based.
+ // So we should minus 1 for the line.
+ result = append(result, base.SingleSQL{
+ Text: stream.GetTextFromTokens(tokens[start], tokens[eofPos-1]),
+ BaseLine: tokens[start].GetLine() - 1,
+ LastLine: tokens[eofPos-1].GetLine() - 1,
+ LastColumn: tokens[eofPos-1].GetColumn(),
+ FirstStatementLine: line,
+ FirstStatementColumn: col,
+ Empty: base.IsEmpty(tokens[start:eofPos], parser.PartiQLLexerCOLON_SEMI),
+ })
+ }
+ return result, nil
+}
diff --git a/backend/plugin/parser/partiql/split_test.go b/backend/plugin/parser/partiql/split_test.go
new file mode 100644
index 0000000000..8fbf00ad15
--- /dev/null
+++ b/backend/plugin/parser/partiql/split_test.go
@@ -0,0 +1,49 @@
+package partiql
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+func TestSplitSQL(t *testing.T) {
+ statement := `
+SELECT * FROM my_table;
+SELECT * FROM my_table;
+foobar();`
+ want := []base.SingleSQL{
+ {
+ Text: "\nSELECT * FROM my_table;",
+ BaseLine: 0,
+ FirstStatementLine: 1,
+ FirstStatementColumn: 0,
+ LastLine: 1,
+ LastColumn: 22,
+ Empty: false,
+ },
+ {
+ Text: "\nSELECT * FROM my_table;",
+ BaseLine: 1,
+ FirstStatementLine: 2,
+ FirstStatementColumn: 0,
+ LastLine: 2,
+ LastColumn: 22,
+ Empty: false,
+ },
+ {
+ Text: "\nfoobar();",
+ BaseLine: 2,
+ FirstStatementLine: 3,
+ FirstStatementColumn: 0,
+ LastLine: 3,
+ LastColumn: 8,
+ Empty: false,
+ },
+ }
+
+ list, err := SplitSQL(statement)
+ require.NoError(t, err)
+ require.Equal(t, want, list)
+}
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index abaf712d97..34c3ce7e00 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -233,7 +233,11 @@ func executeMigration(
switch task.Type {
case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate:
switch instance.Engine {
- case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_OCEANBASE, storepb.Engine_STARROCKS, storepb.Engine_DORIS, storepb.Engine_POSTGRES, storepb.Engine_REDSHIFT, storepb.Engine_RISINGWAVE, storepb.Engine_ORACLE, storepb.Engine_DM, storepb.Engine_OCEANBASE_ORACLE, storepb.Engine_MSSQL:
+ case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_OCEANBASE,
+ storepb.Engine_STARROCKS, storepb.Engine_DORIS, storepb.Engine_POSTGRES,
+ storepb.Engine_REDSHIFT, storepb.Engine_RISINGWAVE, storepb.Engine_ORACLE,
+ storepb.Engine_DM, storepb.Engine_OCEANBASE_ORACLE, storepb.Engine_MSSQL,
+ storepb.Engine_DYNAMODB:
opts.ChunkedSubmission = true
opts.UpdateExecutionStatus = func(detail *v1pb.TaskRun_ExecutionDetail) {
stateCfg.TaskRunExecutionStatuses.Store(taskRunUID,
diff --git a/backend/server/minimal.go b/backend/server/minimal.go
index dc33be2fed..84ce774e3e 100644
--- a/backend/server/minimal.go
+++ b/backend/server/minimal.go
@@ -9,6 +9,7 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/db/pg"
// Parsers.
+ _ "github.com/bytebase/bytebase/backend/plugin/parser/partiql"
_ "github.com/bytebase/bytebase/backend/plugin/parser/pg"
// Schema designer.
diff --git a/go.mod b/go.mod
index d93067d517..a2b95f9974 100644
--- a/go.mod
+++ b/go.mod
@@ -212,6 +212,7 @@ require (
github.com/aws/smithy-go v1.20.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
+ github.com/bytebase/partiql-parser v0.0.0-20240531072247-305e29b89661
github.com/bytebase/tsql-parser v0.0.0-20240517092106-72be97694442
github.com/census-instrumentation/opencensus-proto v0.4.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
diff --git a/go.sum b/go.sum
index c259b39e21..fb7709ae0f 100644
--- a/go.sum
+++ b/go.sum
@@ -792,6 +792,8 @@ github.com/bytebase/gosasl v0.0.0-20240422091407-6b7481e86f08 h1:S1GgjJLspz4E4z4
github.com/bytebase/gosasl v0.0.0-20240422091407-6b7481e86f08/go.mod h1:Qx8cW6jkI8riyzmklj80kAIkv+iezFUTBiGU0qHhHes=
github.com/bytebase/mysql-parser v0.0.0-20240315091443-ac59cc21115a h1:XThmcLuTweSq+V7jkdEMc5zvA8p1gEf/YNOxxIed6y4=
github.com/bytebase/mysql-parser v0.0.0-20240315091443-ac59cc21115a/go.mod h1:n22yoTeLcphIYQlV6nbufQbHMxNceOjeGDOrpaRIhiY=
+github.com/bytebase/partiql-parser v0.0.0-20240531072247-305e29b89661 h1:fmifz2ujSuM+K7gRa0zHb8UHThaa+d2Sbv2R8xqV9ZE=
+github.com/bytebase/partiql-parser v0.0.0-20240531072247-305e29b89661/go.mod h1:hNMKtZBMCbNyhUFR47Ct9mqmpzZVtHgC0OsOIQhR27k=
github.com/bytebase/pg_query_go2/v5 v5.0.0-20240429070353-41837024e3d6 h1:BzWyLTYLMT4H9fmqTQOD/hCvTNAxAJAIjQ8Q+KyOi2s=
github.com/bytebase/pg_query_go2/v5 v5.0.0-20240429070353-41837024e3d6/go.mod h1:FsglvxidZsVN+Ltw3Ai6nTgPVcK2BPukH3jCDEqc1Ug=
github.com/bytebase/plsql-parser v0.0.0-20240523082029-22d555243c06 h1:tUYLQqQh/G2E0jR7LqayrVpr5SXhH35az7TM7dEXLH0=