Skip to content

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

feat(query-span): support variables in function for PG (#14020)

rebeliced9f2fae1b823
diff --git a/backend/plugin/parser/pg/pg.go b/backend/plugin/parser/pg/pg.go
index 0d734bc38d..ddf1dc0783 100644
--- a/backend/plugin/parser/pg/pg.go
+++ b/backend/plugin/parser/pg/pg.go
@@ -226,6 +226,21 @@ func NormalizePostgreSQLColid(ctx parser.IColidContext) string {
return strings.ToLower(ctx.GetText())
}
+func normalizePostgreSQLAnyIdentifier(ctx parser.IAny_identifierContext) string {
+ if ctx == nil {
+ return ""
+ }
+
+ switch {
+ case ctx.Colid() != nil:
+ return NormalizePostgreSQLColid(ctx.Colid())
+ case ctx.Plsql_unreserved_keyword() != nil:
+ return strings.ToLower(ctx.Plsql_unreserved_keyword().GetText())
+ }
+
+ return ""
+}
+
func normalizePostgreSQLIdentifier(ctx parser.IIdentifierContext) string {
if ctx == nil {
return ""
diff --git a/backend/plugin/parser/pg/query_span_extractor.go b/backend/plugin/parser/pg/query_span_extractor.go
index 3be31cd431..5c0c9c171a 100644
--- a/backend/plugin/parser/pg/query_span_extractor.go
+++ b/backend/plugin/parser/pg/query_span_extractor.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"strings"
+ "github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
pgquery "github.com/pganalyze/pg_query_go/v5"
@@ -15,6 +16,8 @@ import (
"github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"
pgrawparser "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg"
+ pgparser "github.com/bytebase/postgresql-parser"
+
"github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -63,6 +66,9 @@ type querySpanExtractor struct {
// sourceColumnsInFunction is the source columns in the function.
// It's used to resolve defined functions body as a table source.
sourceColumnsInFunction base.SourceColumnSet
+
+ // variables are variables declared in the function.
+ variables map[string]*base.QuerySpanResult
}
// newQuerySpanExtractor creates a new query span extractor, the databaseMetadata and the ast are in the read guard.
@@ -661,6 +667,111 @@ func (q *querySpanExtractor) extractTableSourceFromPLPGSQLFunction(createFunc *p
return nil, errors.Wrapf(err, "failed to unmarshal JSON")
}
+ simpleResult, err := q.extractTableSourceFromSimplePLPGSQL(name, jsonData, columnNames)
+ if err == nil {
+ return simpleResult, nil
+ }
+
+ return q.extractTableSourceFromComplexPLPGSQL(name, columnNames, definition)
+}
+
+func (q *querySpanExtractor) extractTableSourceFromComplexPLPGSQL(name string, columnNames []string, definition string) ([]base.QuerySpanResult, error) {
+ res, err := ParsePostgreSQL(definition)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse PLpgSQL function body for function %s", name)
+ }
+
+ listener := &plpgSQLListener{
+ q: q,
+ variables: make(map[string]*base.QuerySpanResult),
+ }
+ antlr.ParseTreeWalkerDefault.Walk(listener, res.Tree)
+ if listener.err != nil {
+ return nil, errors.Wrapf(listener.err, "failed to extract table source from PLpgSQL function body for function %s", name)
+ }
+ if listener.span == nil {
+ return nil, errors.Errorf("failed to extract table source from PLpgSQL function body for function %s", name)
+ }
+ if len(columnNames) != len(listener.span.Results) {
+ return nil, errors.Errorf("expecting %d columns but got %d for function: %s", len(columnNames), len(listener.span.Results), name)
+ }
+ var result []base.QuerySpanResult
+ for i, columnName := range columnNames {
+ result = append(result, base.QuerySpanResult{
+ Name: columnName,
+ SourceColumns: listener.span.Results[i].SourceColumns,
+ })
+ }
+ return result, nil
+}
+
+type plpgSQLListener struct {
+ *pgparser.BasePostgreSQLParserListener
+ q *querySpanExtractor
+
+ variables map[string]*base.QuerySpanResult
+
+ span *base.QuerySpan
+ err error
+}
+
+func (l *plpgSQLListener) EnterFunc_as(ctx *pgparser.Func_asContext) {
+ antlr.ParseTreeWalkerDefault.Walk(l, ctx.Definition)
+}
+
+func (l *plpgSQLListener) EnterDecl_statement(ctx *pgparser.Decl_statementContext) {
+ vName := normalizePostgreSQLAnyIdentifier(ctx.Decl_varname().Any_identifier())
+ l.variables[vName] = &base.QuerySpanResult{
+ SourceColumns: base.SourceColumnSet{},
+ }
+}
+
+func (l *plpgSQLListener) EnterStmt_assign(ctx *pgparser.Stmt_assignContext) {
+ names := NormalizePostgreSQLAnyName(ctx.Assign_var().Any_name())
+ if len(names) != 1 {
+ return
+ }
+ assignVar := names[0]
+
+ newQ := newQuerySpanExtractor(l.q.defaultDatabase, l.q.defaultSchema, l.q.gCtx)
+ span, err := newQ.getQuerySpan(l.q.ctx, fmt.Sprintf("SELECT %s", ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Sql_expression())))
+ if err != nil {
+ return
+ }
+ for source := range span.SourceColumns {
+ l.q.sourceColumnsInFunction[source] = true
+ }
+ leftVarQuerySpan, exists := l.variables[assignVar]
+ if !exists {
+ leftVarQuerySpan = &base.QuerySpanResult{
+ SourceColumns: base.SourceColumnSet{},
+ }
+ l.variables[assignVar] = leftVarQuerySpan
+ }
+ if len(span.Results) != 1 {
+ return
+ }
+ newResourceColumns, _ := base.MergeSourceColumnSet(leftVarQuerySpan.SourceColumns, span.Results[0].SourceColumns)
+ l.variables[assignVar] = &base.QuerySpanResult{
+ SourceColumns: newResourceColumns,
+ }
+}
+
+func (l *plpgSQLListener) EnterStmt_return(ctx *pgparser.Stmt_returnContext) {
+ if ctx.QUERY() == nil {
+ return
+ }
+
+ if ctx.Selectstmt() == nil {
+ return
+ }
+
+ newQ := newQuerySpanExtractor(l.q.defaultDatabase, l.q.defaultSchema, l.q.gCtx)
+ newQ.variables = l.variables
+ l.span, l.err = newQ.getQuerySpan(l.q.ctx, ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Selectstmt()))
+}
+
+func (q *querySpanExtractor) extractTableSourceFromSimplePLPGSQL(name string, jsonData []any, columnNames []string) ([]base.QuerySpanResult, error) {
var sqlList []string
for _, value := range jsonData {
switch value := value.(type) {
@@ -688,14 +799,14 @@ func (q *querySpanExtractor) extractTableSourceFromPLPGSQLFunction(createFunc *p
if err != nil {
return nil, errors.Wrapf(err, "failed to get query span for function: %s", name)
}
- for source := range span.SourceColumns {
- q.sourceColumnsInFunction[source] = true
- }
rightQuerySpanResult := span.Results
if len(leftQuerySpanResult) != len(rightQuerySpanResult) {
return nil, errors.Errorf("expecting %d columns but got %d for function: %s", len(leftQuerySpanResult), len(rightQuerySpanResult), name)
}
+ for source := range span.SourceColumns {
+ q.sourceColumnsInFunction[source] = true
+ }
var result []base.QuerySpanResult
for i, leftSpanResult := range leftQuerySpanResult {
rightSpanResult := rightQuerySpanResult[i]
@@ -1557,6 +1668,12 @@ func (q *querySpanExtractor) getFieldColumnSource(schemaName, tableName, fieldNa
}
}
+ if schemaName == "" && tableName == "" && q.variables != nil {
+ if v, exists := q.variables[fieldName]; exists {
+ return v.SourceColumns, true
+ }
+ }
+
return base.SourceColumnSet{}, false
}
diff --git a/backend/plugin/parser/pg/test-data/query_span.yaml b/backend/plugin/parser/pg/test-data/query_span.yaml
index 76bc76bca4..903b5d0958 100644
--- a/backend/plugin/parser/pg/test-data/query_span.yaml
+++ b/backend/plugin/parser/pg/test-data/query_span.yaml
@@ -1,3 +1,70 @@
+- description: Function with variables
+ statement: SELECT plpgsql_t(1);
+ defaultDatabase: db
+ metadata: |-
+ {
+ "name": "db",
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "t",
+ "columns": [
+ {
+ "name": "a"
+ },
+ {
+ "name": "b"
+ }
+ ]
+ },
+ {
+ "name": "t2",
+ "columns": [
+ {
+ "name": "c"
+ },
+ {
+ "name": "d"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "plpgsql_t",
+ "definition": "CREATE OR REPLACE FUNCTION plpgsql_t (x int) RETURNS TABLE(a int, b int) LANGUAGE plpgsql AS $$ DECLARE v_1 int := 0; v_2 int := 0; BEGIN v_1 := (select sum(a) from t where b = x group by b); v_2 := (select sum(c) from t2 where d = x group by d); RETURN QUERY select v_1, v_2; END; $$"
+ }
+ ]
+ }
+ ]
+ }
+ querySpan:
+ results:
+ - name: plpgsql_t
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t
+ column: a
+ - server: ""
+ database: db
+ schema: public
+ table: t2
+ column: c
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t
+ column: ""
+ - server: ""
+ database: db
+ schema: public
+ table: t2
+ column: ""
- description: Function Overloading
statement: SELECT plpgsql_t(1, 2);
defaultDatabase: db
diff --git a/go.mod b/go.mod
index 693ee21f44..fec124d662 100644
--- a/go.mod
+++ b/go.mod
@@ -22,7 +22,7 @@ require (
github.com/bytebase/bq-parser v0.0.0-20240529032606-614a0230b8f7
github.com/bytebase/mysql-parser v0.0.0-20240810145851-ab2c11629c24
github.com/bytebase/plsql-parser v0.0.0-20240929073008-6b57c2e2525d
- github.com/bytebase/postgresql-parser v0.0.0-20231221075352-cf5025e0d56f
+ github.com/bytebase/postgresql-parser v0.0.0-20241008085234-a95eacac994a
github.com/bytebase/snowsql-parser v0.0.0-20240304100801-bb357ccb5535
github.com/bytebase/tidb-parser v0.0.0-20240821091609-162fffe2a839
github.com/cenkalti/backoff/v4 v4.3.0
diff --git a/go.sum b/go.sum
index f4204968c3..00d19850e3 100644
--- a/go.sum
+++ b/go.sum
@@ -831,8 +831,8 @@ github.com/bytebase/pkcs8 v0.0.0-20240612095628-fcd0a7484c94 h1:6PNsuNmSqCuR8Z61
github.com/bytebase/pkcs8 v0.0.0-20240612095628-fcd0a7484c94/go.mod h1:SQliXeA7Dhkt//vS29v3zpbEwoa+zb2Cn5xj5uO4K5U=
github.com/bytebase/plsql-parser v0.0.0-20240929073008-6b57c2e2525d h1:bfJbndIoSgPxUhYqAx0Ggv8D3Ib+YeNEiteGs4+82AU=
github.com/bytebase/plsql-parser v0.0.0-20240929073008-6b57c2e2525d/go.mod h1:sEtLYOfHyi8zz5vo5gKT//A8c4P8FnDZLNVSLtVPxj0=
-github.com/bytebase/postgresql-parser v0.0.0-20231221075352-cf5025e0d56f h1:mwn17HA984i5cz1vIkiF265a6LZplCAqIPqQn7c0V0s=
-github.com/bytebase/postgresql-parser v0.0.0-20231221075352-cf5025e0d56f/go.mod h1:Jft7oabwuwD+t5BYiUfTjcNVaihZ8F5KT8TsROG0EaE=
+github.com/bytebase/postgresql-parser v0.0.0-20241008085234-a95eacac994a h1:afCKpcKKi9PFB8SIFbFt5xEbNVbqYCkGZ/188eXqiGU=
+github.com/bytebase/postgresql-parser v0.0.0-20241008085234-a95eacac994a/go.mod h1:Jft7oabwuwD+t5BYiUfTjcNVaihZ8F5KT8TsROG0EaE=
github.com/bytebase/snowsql-parser v0.0.0-20240304100801-bb357ccb5535 h1:sgEzM1Y8WUAR8n8fOjVtx62Cz7HuUILtONkPQ8IvFNk=
github.com/bytebase/snowsql-parser v0.0.0-20240304100801-bb357ccb5535/go.mod h1:gJ1aclz1e9xLArQTbCpDjL+A79Jt3Ro9+/QEw8A6vMM=
github.com/bytebase/tidb-parser v0.0.0-20240821091609-162fffe2a839 h1:OLOEfNV20wqC4nPHQllr4mrMhchAhPrgXlKn0URgum8=