Skip to content

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

chore: run single do statement without txn for pg (#12327)

rebelicec5b201f7e9e4
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index c8147d0ecf..9f5264b00c 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -24,6 +24,8 @@ import (
"golang.org/x/crypto/ssh"
"google.golang.org/protobuf/types/known/durationpb"
+ pgquery "github.com/pganalyze/pg_query_go/v5"
+
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -367,6 +369,31 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe
return 0, nil
}
+ // If the statement is a single statement and is a PL/pgSQL block,
+ // we should execute it as a single statement without transaction.
+ if len(singleSQLs) == 1 && isPlSQLBlock(singleSQLs[0].Text) {
+ // If the statement is a PL/pgSQL block, we should execute it as a single statement.
+ // https://www.postgresql.org/docs/current/plpgsql-control-structures.html
+ conn, err := driver.db.Conn(ctx)
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to get connection")
+ }
+ defer conn.Close()
+
+ // USE SET SESSION ROLE to set the role for the current session.
+ if _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner)); err != nil {
+ return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)
+ }
+ opts.LogCommandExecute([]int32{0})
+ if _, err := conn.ExecContext(ctx, singleSQLs[0].Text); err != nil {
+ opts.LogCommandResponse([]int32{0}, 0, []int32{0}, err.Error())
+ return 0, err
+ }
+ opts.LogCommandResponse([]int32{0}, 0, []int32{0}, "")
+
+ return 0, nil
+ }
+
var remainingSQLs []base.SingleSQL
remainingSQLsIndex := map[int]int{}
@@ -709,3 +736,20 @@ func (*Driver) querySingleSQL(ctx context.Context, conn *sql.Conn, singleSQL bas
func (*Driver) RunStatement(ctx context.Context, conn *sql.Conn, statement string) ([]*v1pb.QueryResult, error) {
return util.RunStatement(ctx, storepb.Engine_POSTGRES, conn, statement)
}
+
+func isPlSQLBlock(stmt string) bool {
+ tree, err := pgquery.Parse(stmt)
+ if err != nil {
+ return false
+ }
+
+ if len(tree.Stmts) != 1 {
+ return false
+ }
+
+ if _, ok := tree.Stmts[0].Stmt.Node.(*pgquery.Node_DoStmt); ok {
+ return true
+ }
+
+ return false
+}