Skip to content

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

feat(completion): support CTE for pg (#10008)

rebelice426af708cfaf
diff --git a/backend/plugin/parser/pg/completion.go b/backend/plugin/parser/pg/completion.go
index 26113bc3eb..fa5b821ed0 100644
--- a/backend/plugin/parser/pg/completion.go
+++ b/backend/plugin/parser/pg/completion.go
@@ -148,7 +148,7 @@ type Completer struct {
// It's helpful to look up the table reference.
references []base.TableReference
cteCache map[int][]*base.VirtualTableReference
- // cteTables []*base.VirtualTableReference
+ cteTables []*base.VirtualTableReference
}
func NewCompleter(ctx context.Context, statement string, caretLine int, caretOffset int, defaultDatabase string, getMetadata base.GetDatabaseMetadataFunc) *Completer {
@@ -228,6 +228,16 @@ func (m CompletionMap) insertSchemas(c *Completer) {
func (m CompletionMap) insertTables(c *Completer, schemas map[string]bool) {
for schema := range schemas {
+ if len(schema) == 0 {
+ // User didn't specify the schema, we need to append cte tables.
+ for _, table := range c.cteTables {
+ m.Insert(base.Candidate{
+ Type: base.CandidateTypeTable,
+ Text: table.Table,
+ })
+ }
+ continue
+ }
for _, table := range c.listTables(schema) {
m.Insert(base.Candidate{
Type: base.CandidateTypeTable,
@@ -258,6 +268,20 @@ func (m CompletionMap) insertColumns(c *Completer, schemas, tables map[string]bo
}
for schema := range schemas {
+ if len(schema) == 0 {
+ // User didn't specify the schema, we need to append cte tables.
+ for _, table := range c.cteTables {
+ if tables[table.Table] {
+ for _, column := range table.Columns {
+ m.Insert(base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: column,
+ })
+ }
+ }
+ }
+ continue
+ }
schemaMeta := c.metadataCache[c.defaultDatabase].GetSchema(schema)
if schemaMeta == nil {
continue
@@ -357,6 +381,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
c.scanner.PopAndRestore()
c.scanner.Push()
+ c.fetchCommonTableExpression(candidates.Rules[candidate])
+
switch candidate {
case pg.PostgreSQLParserRULE_func_name:
runtimeFunctionEntries.insertFunctions()
@@ -371,6 +397,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
schemas := make(map[string]bool)
if len(qualifier) == 0 {
schemas[defaultSchema] = true
+ // User didn't specify the schema, we need to append cte tables.
+ schemas[""] = true
} else {
schemas[qualifier] = true
}
@@ -399,6 +427,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
if len(schema) == 0 {
schemas[defaultSchema] = true
+ // User didn't specify the schema, we need to append cte tables.
+ schemas[""] = true
}
if flags&ObjectFlagsShowTables != 0 {
@@ -437,6 +467,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
if flags&ObjectFlagsShowColumns != 0 {
if schema == table {
schemas[defaultSchema] = true
+ // User didn't specify the schema, we need to append cte tables.
+ schemas[""] = true
}
tables := make(map[string]bool)
@@ -504,6 +536,76 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
return result, nil
}
+func (c *Completer) fetchCommonTableExpression(ruleStack []*base.RuleContext) {
+ c.cteTables = nil
+ for _, rule := range ruleStack {
+ if rule.ID == pg.PostgreSQLParserRULE_select_no_parens {
+ for _, pos := range rule.CTEList {
+ c.cteTables = append(c.cteTables, c.extractCTETables(pos)...)
+ }
+ }
+ }
+}
+
+func (c *Completer) extractCTETables(pos int) []*base.VirtualTableReference {
+ if metadata, exists := c.cteCache[pos]; exists {
+ return metadata
+ }
+ followingText := c.scanner.GetFollowingTextAfter(pos)
+ if len(followingText) == 0 {
+ return nil
+ }
+
+ input := antlr.NewInputStream(followingText)
+ lexer := pg.NewPostgreSQLLexer(input)
+ tokens := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := pg.NewPostgreSQLParser(tokens)
+
+ parser.BuildParseTrees = true
+ parser.RemoveErrorListeners()
+ lexer.RemoveErrorListeners()
+ tree := parser.With_clause()
+
+ listener := &CTETableListener{context: c}
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ c.cteCache[pos] = listener.tables
+ return listener.tables
+}
+
+type CTETableListener struct {
+ *pg.BasePostgreSQLParserListener
+
+ context *Completer
+ tables []*base.VirtualTableReference
+}
+
+func (l *CTETableListener) EnterCommon_table_expr(ctx *pg.Common_table_exprContext) {
+ table := &base.VirtualTableReference{}
+ if ctx.Name() != nil {
+ table.Table = normalizePostgreSQLName(ctx.Name())
+ }
+ if ctx.Opt_name_list() != nil {
+ for _, column := range ctx.Opt_name_list().Name_list().AllName() {
+ table.Columns = append(table.Columns, normalizePostgreSQLName(column))
+ }
+ } else {
+ if span, err := base.GetQuerySpan(
+ l.context.ctx,
+ store.Engine_POSTGRES,
+ ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Preparablestmt()),
+ l.context.defaultDatabase,
+ l.context.getMetadata,
+ ); err == nil && len(span) == 1 {
+ for _, column := range span[0].Results {
+ table.Columns = append(table.Columns, column.Name)
+ }
+ }
+ }
+
+ l.tables = append(l.tables, table)
+}
+
func (c *Completer) fetchSelectItemAliases(ruleStack []*base.RuleContext) []string {
canUseAliases := false
for i := len(ruleStack) - 1; i >= 0; i-- {
@@ -852,7 +954,7 @@ func (l *TableRefListener) EnterTable_ref(ctx *pg.Table_refContext) {
if span, err := base.GetQuerySpan(
l.context.ctx,
store.Engine_POSTGRES,
- fmt.Sprintf("SELECT * FROM %s;", ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Select_with_parens())),
+ fmt.Sprintf("SELECT * FROM %s AS %s;", ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Select_with_parens()), tableAlias),
l.context.defaultDatabase,
l.context.getMetadata,
); err == nil && len(span) == 1 {
diff --git a/backend/plugin/parser/pg/test-data/test_completion.yaml b/backend/plugin/parser/pg/test-data/test_completion.yaml
index 3500c25812..a54edc5a34 100644
--- a/backend/plugin/parser/pg/test-data/test_completion.yaml
+++ b/backend/plugin/parser/pg/test-data/test_completion.yaml
@@ -1,3 +1,63 @@
+- input: SELECT x.| FROM (SELECT * FROM t2) x
+ want:
+ - text: c1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: c2
+ type: COLUMN
+ definition: ""
+ comment: ""
+- input: WITH x AS (SELECT * FROM t2) SELECT x.| FROM x;
+ want:
+ - text: c1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: c2
+ type: COLUMN
+ definition: ""
+ comment: ""
+- input: WITH x(x1, x2) AS (SELECT * FROM t2) SELECT x.| FROM x;
+ want:
+ - text: x1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: x2
+ type: COLUMN
+ definition: ""
+ comment: ""
+- input: WITH x(x1, x2) AS (SELECT * FROM t2) SELECT | FROM x
+ want:
+ - text: public
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ - text: t1
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: t2
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: x
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: v1
+ type: VIEW
+ definition: ""
+ comment: ""
+ - text: x1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: x2
+ type: COLUMN
+ definition: ""
+ comment: ""
- input: SELECT c1 as eid, c2 as xid FROM t2 ORDER BY |
want:
- text: public
@@ -102,6 +162,10 @@
type: VIEW
definition: ""
comment: ""
+ - text: c1
+ type: COLUMN
+ definition: ""
+ comment: ""
- input: SELECT cc1.| FROM t1 cc1 JOIN t2 on NOT cc1.c1 = t2.c1
want:
- text: c1