Skip to content

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

feat: detect plsql block by using antlr (#17163)

h3n4l6e77cf7f997f
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index 4b1e80c34d..28a2eb6937 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -22,8 +22,6 @@ import (
"golang.org/x/crypto/ssh"
"google.golang.org/protobuf/types/known/durationpb"
- pgquery "github.com/pganalyze/pg_query_go/v6"
-
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -393,7 +391,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
// we should execute it as a single statement without transaction.
// 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
- if len(singleSQLs) == 1 && isPlSQLBlock(singleSQLs[0].Text) {
+ if len(singleSQLs) == 1 && pgparser.IsPlSQLBlock(singleSQLs[0].Text) {
isPlsql = true
}
@@ -657,13 +655,14 @@ func (d *Driver) executeInAutoCommitMode(
}
}
- if isPlsql {
- if d.connectionCtx.UseDatabaseOwner {
- // 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)
- }
+ if d.connectionCtx.UseDatabaseOwner {
+ // 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)
}
+ }
+
+ if isPlsql {
opts.LogCommandExecute([]int32{0}, statement)
if _, err := conn.ExecContext(ctx, statement); err != nil {
opts.LogCommandResponse(0, []int32{0}, err.Error())
@@ -673,13 +672,6 @@ func (d *Driver) executeInAutoCommitMode(
return 0, nil
}
- if d.connectionCtx.UseDatabaseOwner {
- // 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)
- }
- }
-
totalRowsAffected := int64(0)
// Execute all statements individually in auto-commit mode
for i, stmt := range nonTransactionAndSetRoleStmts {
@@ -920,31 +912,3 @@ func getPgError(e error) *v1pb.QueryResult_PostgresError_ {
}
return nil
}
-
-func isPlSQLBlock(stmt string) bool {
- defer func() {
- if r := recover(); r != nil {
- perr, ok := r.(error)
- if !ok {
- perr = errors.Errorf("%v", r)
- }
- err := errors.Errorf("PANIC RECOVER, err: %v", perr)
- stmtT, _ := common.TruncateString(stmt, 1000)
- slog.Info("isPlSQLBlock panic", log.BBError(err), "stmt_truncated", stmtT)
- }
- }()
- 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
-}
diff --git a/backend/plugin/parser/pg/plsql.go b/backend/plugin/parser/pg/plsql.go
new file mode 100644
index 0000000000..681881de68
--- /dev/null
+++ b/backend/plugin/parser/pg/plsql.go
@@ -0,0 +1,40 @@
+package pg
+
+import (
+ parser "github.com/bytebase/parser/postgresql"
+)
+
+// IsPlSQLBlock checks if the given statement is a PL/pgSQL anonymous code block (DO statement).
+// Returns true if the statement is a DO block only, false otherwise.
+func IsPlSQLBlock(stmt string) bool {
+ // Parse using the existing ANTLR-based parser
+ result, err := ParsePostgreSQL(stmt)
+ if err != nil {
+ return false
+ }
+
+ // Check if the parsed tree is a single DO statement
+ root, ok := result.Tree.(*parser.RootContext)
+ if !ok || root == nil {
+ return false
+ }
+
+ stmtblock := root.Stmtblock()
+ if stmtblock == nil {
+ return false
+ }
+
+ stmtmulti := stmtblock.Stmtmulti()
+ if stmtmulti == nil {
+ return false
+ }
+
+ stmts := stmtmulti.AllStmt()
+ // Must be exactly one statement
+ if len(stmts) != 1 {
+ return false
+ }
+
+ // Check if the single statement is a DO statement
+ return stmts[0].Dostmt() != nil
+}
diff --git a/backend/plugin/parser/pg/plsql_test.go b/backend/plugin/parser/pg/plsql_test.go
new file mode 100644
index 0000000000..999c42229a
--- /dev/null
+++ b/backend/plugin/parser/pg/plsql_test.go
@@ -0,0 +1,217 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestIsPlSQLBlock(t *testing.T) {
+ tests := []struct {
+ name string
+ stmt string
+ expected bool
+ }{
+ // DO blocks - should return true
+ {
+ name: "simple DO block with dollar quotes",
+ stmt: `DO $$
+BEGIN
+ RAISE NOTICE 'Hello World';
+END
+$$;`,
+ expected: true,
+ },
+ {
+ name: "DO block with single quotes",
+ stmt: `DO '
+BEGIN
+ RAISE NOTICE ''Hello World'';
+END
+';`,
+ expected: true,
+ },
+ {
+ name: "DO block with language specification",
+ stmt: `DO $$
+BEGIN
+ RAISE NOTICE 'Hello World';
+END
+$$ LANGUAGE plpgsql;`,
+ expected: true,
+ },
+ {
+ name: "DO block with complex logic",
+ stmt: `DO $$
+DECLARE
+ r record;
+BEGIN
+ FOR r IN SELECT table_name FROM information_schema.tables
+ WHERE table_schema = 'public'
+ LOOP
+ RAISE NOTICE 'Table: %', r.table_name;
+ END LOOP;
+END
+$$;`,
+ expected: true,
+ },
+ {
+ name: "DO block with nested dollar quotes",
+ stmt: `DO $outer$
+BEGIN
+ EXECUTE $inner$
+ SELECT 1;
+ $inner$;
+END
+$outer$;`,
+ expected: true,
+ },
+ {
+ name: "DO block in single line",
+ stmt: `DO $$ BEGIN RAISE NOTICE 'test'; END $$;`,
+ expected: true,
+ },
+ {
+ name: "DO block with whitespace",
+ stmt: ` DO $$ BEGIN RAISE NOTICE 'test'; END $$ ; `,
+ expected: true,
+ },
+ {
+ name: "DO block with exception handling",
+ stmt: `DO $$
+BEGIN
+ INSERT INTO test_table VALUES (1);
+EXCEPTION
+ WHEN unique_violation THEN
+ RAISE NOTICE 'Duplicate key';
+END
+$$;`,
+ expected: true,
+ },
+
+ // Non-DO blocks - should return false
+ {
+ name: "SELECT statement",
+ stmt: `SELECT * FROM users;`,
+ expected: false,
+ },
+ {
+ name: "CREATE FUNCTION statement",
+ stmt: `CREATE FUNCTION test_func() RETURNS void AS $$
+BEGIN
+ RAISE NOTICE 'Hello';
+END
+$$ LANGUAGE plpgsql;`,
+ expected: false,
+ },
+ {
+ name: "INSERT statement",
+ stmt: `INSERT INTO users (name) VALUES ('John');`,
+ expected: false,
+ },
+ {
+ name: "UPDATE statement",
+ stmt: `UPDATE users SET name = 'Jane' WHERE id = 1;`,
+ expected: false,
+ },
+ {
+ name: "DELETE statement",
+ stmt: `DELETE FROM users WHERE id = 1;`,
+ expected: false,
+ },
+ {
+ name: "CREATE PROCEDURE statement",
+ stmt: `CREATE PROCEDURE test_proc() AS $$
+BEGIN
+ RAISE NOTICE 'Hello';
+END
+$$ LANGUAGE plpgsql;`,
+ expected: false,
+ },
+ {
+ name: "BEGIN transaction block",
+ stmt: `BEGIN; SELECT 1; COMMIT;`,
+ expected: false,
+ },
+ {
+ name: "DECLARE CURSOR statement",
+ stmt: `DECLARE my_cursor CURSOR FOR SELECT * FROM users;`,
+ expected: false,
+ },
+ {
+ name: "Anonymous block in string (not DO)",
+ stmt: `SELECT 'DO $$ BEGIN RAISE NOTICE ''test''; END $$;' AS query;`,
+ expected: false,
+ },
+ {
+ name: "Comment containing DO",
+ stmt: `-- DO something here\nSELECT 1;`,
+ expected: false,
+ },
+ {
+ name: "Table named 'do'",
+ stmt: `SELECT * FROM do WHERE id = 1;`,
+ expected: false,
+ },
+ {
+ name: "Column named 'do'",
+ stmt: `SELECT do FROM tasks;`,
+ expected: false,
+ },
+
+ // Edge cases
+ {
+ name: "Empty statement",
+ stmt: ``,
+ expected: false,
+ },
+ {
+ name: "Only whitespace",
+ stmt: ` `,
+ expected: false,
+ },
+ {
+ name: "Only DO keyword",
+ stmt: `DO`,
+ expected: false,
+ },
+ {
+ name: "DO without body",
+ stmt: `DO;`,
+ expected: false,
+ },
+ {
+ name: "Malformed DO block",
+ stmt: `DO $$ BEGIN`,
+ expected: false,
+ },
+ {
+ name: "Multiple statements with DO block",
+ stmt: `SELECT 1;
+DO $$ BEGIN RAISE NOTICE 'test'; END $$;`,
+ expected: false, // Should be false because it's not a single statement
+ },
+ {
+ name: "DO in uppercase",
+ stmt: `DO $$ BEGIN RAISE NOTICE 'test'; END $$;`,
+ expected: true,
+ },
+ {
+ name: "do in lowercase",
+ stmt: `do $$ BEGIN RAISE NOTICE 'test'; END $$;`,
+ expected: true,
+ },
+ {
+ name: "Do in mixed case",
+ stmt: `Do $$ BEGIN RAISE NOTICE 'test'; END $$;`,
+ expected: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := IsPlSQLBlock(tt.stmt)
+ require.Equal(t, tt.expected, result, "Statement: %s", tt.stmt)
+ })
+ }
+}