Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: pg execute details (#10133)
Danny Xud4584628f07b
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 5d6dd54896..9bf2a33ae0 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -292,9 +292,8 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exereturn 0, nil}- var remainingStmts []string+ var remainingSQLs []base.SingleSQLvar nonTransactionStmts []string- totalRowsAffected := int64(0)for _, singleSQL := range singleSQLs {if isIgnoredStatement(singleSQL.Text) {continue@@ -315,35 +314,89 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe// Use superuser privilege to run privileged statements.singleSQL.Text = fmt.Sprintf("SET LOCAL ROLE NONE;%sSET LOCAL ROLE '%s';", singleSQL.Text, owner)}- remainingStmts = append(remainingStmts, singleSQL.Text)+ remainingSQLs = append(remainingSQLs, singleSQL)}- if len(remainingStmts) != 0 {+ totalRowsAffected := int64(0)+ if len(remainingSQLs) != 0 {+ var totalCommands int+ var chunks [][]base.SingleSQL+ if opts.ChunkedSubmission && len(statement) <= common.MaxSheetCheckSize {+ totalCommands = len(remainingSQLs)+ ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to chunk sql")+ }+ chunks = ret+ } else {+ chunks = [][]base.SingleSQL{+ remainingSQLs,+ }+ }+ currentIndex := 0+tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return 0, err}defer tx.Rollback()-// Set the current transaction role to the database owner so that the owner of created objects will be the same as the database owner.if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL ROLE '%s'", owner)); err != nil {return 0, err}- sqlResult, err := tx.ExecContext(ctx, strings.Join(remainingStmts, "\n"))- if err != nil {- return 0, 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{+ Line: int32(chunk[0].FirstStatementLine),+ Column: int32(chunk[0].FirstStatementColumn),+ },+ CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ })+ }++ chunkText, err := util.ConcatChunk(chunk)+ if err != nil {+ return 0, err+ }++ sqlResult, err := tx.ExecContext(ctx, chunkText)+ 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),+ },+ End: &storepb.TaskRunResult_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ }+ }+ 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)}+if err := tx.Commit(); err != nil {return 0, err}- 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))- } else {- totalRowsAffected += rowsAffected- }}// Run non-transaction statements at the end.diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.goindex 3a56d66440..07abfae678 100644--- a/backend/plugin/db/redshift/redshift.go+++ b/backend/plugin/db/redshift/redshift.go@@ -18,6 +18,7 @@ import ("golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"+ "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -186,9 +187,8 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exereturn 0, nil}- var remainingStmts []string+ var remainingSQLs []base.SingleSQLvar nonTransactionStmts []string- totalRowsAffected := int64(0)for _, singleSQL := range singleSQLs {if isNonTransactionStatement(singleSQL.Text) {nonTransactionStmts = append(nonTransactionStmts, singleSQL.Text)@@ -206,25 +206,86 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe// Use superuser privilege to run privileged statements.singleSQL.Text = fmt.Sprintf("SET SESSION AUTHORIZATION NONE;%sSET SESSION AUTHORIZATION '%s';", singleSQL.Text, owner)}- remainingStmts = append(remainingStmts, singleSQL.Text)+ remainingSQLs = append(remainingSQLs, singleSQL)}- if len(remainingStmts) != 0 {+ totalRowsAffected := int64(0)+ if len(remainingSQLs) != 0 {+ var totalCommands int+ var chunks [][]base.SingleSQL+ if opts.ChunkedSubmission && len(statement) <= common.MaxSheetCheckSize {+ totalCommands = len(remainingSQLs)+ ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to chunk sql")+ }+ chunks = ret+ } else {+ chunks = [][]base.SingleSQL{+ remainingSQLs,+ }+ }+ currentIndex := 0+tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return 0, err}defer tx.Rollback()-// Set the current transaction role to the database owner so that the owner of created objects will be the same as the database owner.if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET SESSION AUTHORIZATION '%s'", owner)); err != nil {return 0, err}- sqlResult, err := tx.ExecContext(ctx, strings.Join(remainingStmts, "\n"))- if err != nil {- return 0, 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{+ Line: int32(chunk[0].FirstStatementLine),+ Column: int32(chunk[0].FirstStatementColumn),+ },+ CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ })+ }++ chunkText, err := util.ConcatChunk(chunk)+ if err != nil {+ return 0, err+ }++ sqlResult, err := tx.ExecContext(ctx, chunkText)+ 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),+ },+ End: &storepb.TaskRunResult_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ }+ }+ 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)}+// Restore the current transaction role to the current user.if _, err := tx.ExecContext(ctx, "SET SESSION AUTHORIZATION DEFAULT"); err != nil {slog.Warn("Failed to restore the current transaction role to the current user", log.BBError(err))@@ -233,13 +294,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exeif err := tx.Commit(); err != nil {return 0, err}- 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))- } else {- totalRowsAffected += rowsAffected- }}// Run non-transaction statements at the end.diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.goindex 20e4f9bdab..91acd026d2 100644--- a/backend/plugin/db/risingwave/risingwave.go+++ b/backend/plugin/db/risingwave/risingwave.go@@ -253,39 +253,92 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exereturn 0, nil}- var remainingStmts []string+ var remainingSQLs []base.SingleSQLvar nonTransactionStmts []string- totalRowsAffected := int64(0)for _, singleSQL := range singleSQLs {if isNonTransactionStatement(singleSQL.Text) {nonTransactionStmts = append(nonTransactionStmts, singleSQL.Text)continue}-- remainingStmts = append(remainingStmts, singleSQL.Text)+ remainingSQLs = append(remainingSQLs, singleSQL)}- if len(remainingStmts) != 0 {+ totalRowsAffected := int64(0)+ if len(remainingSQLs) != 0 {+ var totalCommands int+ var chunks [][]base.SingleSQL+ if opts.ChunkedSubmission && len(statement) <= common.MaxSheetCheckSize {+ totalCommands = len(remainingSQLs)+ ret, err := util.ChunkedSQLScript(remainingSQLs, common.MaxSheetChunksCount)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to chunk sql")+ }+ chunks = ret+ } else {+ chunks = [][]base.SingleSQL{+ remainingSQLs,+ }+ }+ currentIndex := 0+tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return 0, err}defer tx.Rollback()- sqlResult, err := tx.ExecContext(ctx, strings.Join(remainingStmts, "\n"))- if err != nil {- return 0, 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{+ Line: int32(chunk[0].FirstStatementLine),+ Column: int32(chunk[0].FirstStatementColumn),+ },+ CommandEndPosition: &v1pb.TaskRun_ExecutionDetail_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ })+ }++ chunkText, err := util.ConcatChunk(chunk)+ if err != nil {+ return 0, err+ }++ sqlResult, err := tx.ExecContext(ctx, chunkText)+ 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),+ },+ End: &storepb.TaskRunResult_Position{+ Line: int32(chunk[len(chunk)-1].LastLine),+ Column: int32(chunk[len(chunk)-1].LastColumn),+ },+ }+ }+ 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)}+if err := tx.Commit(); err != nil {return 0, err}- 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))- } else {- totalRowsAffected += rowsAffected- }}// Run non-transaction statements at the end.@@ -347,39 +400,6 @@ func getDatabaseInCreateDatabaseStatement(createDatabaseStatement string) (strinreturn databaseName, nil}-// GetCurrentDatabaseOwner gets the role of the current database.-func (driver *Driver) GetCurrentDatabaseOwner() (string, error) {- const query = `- SELECT- u.rolname- FROM- pg_roles AS u JOIN pg_database AS d ON (d.datdba = u.oid)- WHERE- d.datname = current_database();- `- rows, err := driver.db.Query(query)- if err != nil {- return "", err- }- defer rows.Close()-- var owner string- for rows.Next() {- var o string- if err := rows.Scan(&o); err != nil {- return "", err- }- owner = o- }- if err := rows.Err(); err != nil {- return "", err- }- if owner == "" {- return "", errors.Errorf("owner not found for the current database")- }- return owner, nil-}-// QueryConn queries a SQL statement in a given connection.func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string, queryContext *db.QueryContext) ([]*v1pb.QueryResult, error) {singleSQLs, err := pgparser.SplitSQL(statement)diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 86090e0c4c..15220148c9 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -232,7 +232,7 @@ func executeMigration(switch task.Type {case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate:switch instance.Engine {- case storepb.Engine_MYSQL:+ case storepb.Engine_MYSQL, storepb.Engine_OCEANBASE, storepb.Engine_MARIADB, storepb.Engine_STARROCKS, storepb.Engine_POSTGRES, storepb.Engine_REDSHIFT, storepb.Engine_RISINGWAVE:opts.ChunkedSubmission = trueopts.UpdateExecutionStatus = func(detail *v1pb.TaskRun_ExecutionDetail) {stateCfg.TaskRunExecutionStatuses.Store(taskRunUID,