Skip to content

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

feat(Completion): support Common Table Expression(CTE) (#9760)

rebelice0531e96ffe7d
diff --git a/backend/plugin/parser/base/c3.go b/backend/plugin/parser/base/c3.go
index 0f5dab2c75..77afa1631f 100644
--- a/backend/plugin/parser/base/c3.go
+++ b/backend/plugin/parser/base/c3.go
@@ -18,6 +18,9 @@ type CodeCompletionCore struct {
QueryRule int
ShadowQueryRule int
SelectItemAliasRule int
+ // CTERule is used to determine the CTE alias for the completion candidates.
+ // Currently, it always uses in ShadowQueryRule for MySQL.
+ CTERule int
parser antlr.Parser
atn *antlr.ATN
@@ -47,6 +50,7 @@ func NewCodeCompletionCore(
queryRule int,
shadowQueryRule int,
selectItemAliasRule int,
+ cteRule int,
) *CodeCompletionCore {
return &CodeCompletionCore{
IgnoredTokens: ignoredTokens,
@@ -54,6 +58,7 @@ func NewCodeCompletionCore(
QueryRule: queryRule,
ShadowQueryRule: shadowQueryRule,
SelectItemAliasRule: selectItemAliasRule,
+ CTERule: cteRule,
parser: parser,
atn: parser.GetATN(),
followSetsByState: followSets,
@@ -72,6 +77,7 @@ type RuleContext struct {
// SelectItemAliases is the map of token index of select item aliases.
// Only the QueryRule has the SelectItemAliases.
SelectItemAliases map[int]bool
+ CTEList []int
}
// RuleList is the list of rules.
@@ -93,9 +99,12 @@ func NewRuleList() *RuleList {
func (l *RuleList) Copy() *RuleList {
rules := make([]*RuleContext, len(l.rules))
for i, rule := range l.rules {
+ var cteList []int
+ cteList = append(cteList, rule.CTEList...)
rules[i] = &RuleContext{
ID: rule.ID,
SelectItemAliases: rule.SelectItemAliases,
+ CTEList: cteList,
}
}
bitSet := antlr.NewBitSet()
@@ -485,7 +494,8 @@ func (c *CodeCompletionCore) fetchEndStatus(startState antlr.ATNState, tokenInde
TokenIndex: status,
})
}
- if startState.GetRuleIndex() == c.SelectItemAliasRule {
+ switch startState.GetRuleIndex() {
+ case c.SelectItemAliasRule:
if c.lastQueryRuleContext != nil {
if c.lastQueryRuleContext.SelectItemAliases == nil {
c.lastQueryRuleContext.SelectItemAliases = make(map[int]bool)
@@ -498,6 +508,10 @@ func (c *CodeCompletionCore) fetchEndStatus(startState antlr.ATNState, tokenInde
}
c.lastShadowQueryRuleContext.SelectItemAliases[c.tokens[currentEntry.TokenIndex].StartPosition] = true
}
+ case c.CTERule:
+ if c.lastShadowQueryRuleContext != nil {
+ c.lastShadowQueryRuleContext.CTEList = append(c.lastShadowQueryRuleContext.CTEList, c.tokens[currentEntry.TokenIndex].StartPosition)
+ }
}
case *antlr.PredicateTransition:
if checkPredicate(c.parser, transition) {
diff --git a/backend/plugin/parser/mysql/completion.go b/backend/plugin/parser/mysql/completion.go
index 74d9946468..032c40fdfd 100644
--- a/backend/plugin/parser/mysql/completion.go
+++ b/backend/plugin/parser/mysql/completion.go
@@ -232,6 +232,8 @@ type Completer struct {
// references is the flattened table references.
// It's helpful to look up the table reference.
references []TableReference
+ cteCache map[int][]*VirtualTableReference
+ cteTables []*VirtualTableReference
}
func NewCompleter(ctx context.Context, statement string, caretLine int, caretOffset int, defaultDatabase string, metadata base.GetDatabaseMetadataFunc) *Completer {
@@ -246,6 +248,7 @@ func NewCompleter(ctx context.Context, statement string, caretLine int, caretOff
mysql.MySQLParserRULE_querySpecification,
mysql.MySQLParserRULE_queryExpression,
mysql.MySQLParserRULE_selectAlias,
+ mysql.MySQLParserRULE_withClause,
)
return &Completer{
ctx: ctx,
@@ -257,6 +260,7 @@ func NewCompleter(ctx context.Context, statement string, caretLine int, caretOff
getMetadata: metadata,
metadataCache: make(map[string]*model.DatabaseMetadata),
noSeparatorRequired: newNoSeparatorRequired(),
+ cteCache: make(map[int][]*VirtualTableReference),
}
}
@@ -357,6 +361,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
c.scanner.PopAndRestore()
c.scanner.Push()
+ c.fetchCommonTableExpression(candidates.Rules[candidate])
+
switch candidate {
case mysql.MySQLParserRULE_runtimeFunctionCall:
runtimeFunctionEntries.insertFunctions()
@@ -373,6 +379,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
schemas := make(map[string]bool)
if len(schema) == 0 {
schemas[c.defaultDatabase] = true
+ // User didn't specify a schema, so we need to append cte tables.
+ schemas[""] = true
} else {
schemas[schema] = true
}
@@ -391,6 +399,7 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
schemas := make(map[string]bool)
if len(qualifier) == 0 {
schemas[c.defaultDatabase] = true
+ schemas[""] = true // User didn't specify a schema, so we need to append cte tables.
} else {
schemas[qualifier] = true
}
@@ -419,6 +428,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
if len(schemas) == 0 {
schemas[c.defaultDatabase] = true
+ // User didn't specify a schema, so we need to append cte tables.
+ schemas[""] = true
}
if flags&ObjectFlagsShowTables != 0 {
@@ -459,6 +470,8 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
if flags&ObjectFlagsShowColumns != 0 {
if database == table { // Schema and table are equal if it's not clear if we see a schema or table qualifier.
schemas[c.defaultDatabase] = true
+ // User didn't specify a schema, so we need to append cte tables.
+ schemas[""] = true
}
tables := make(map[string]bool)
@@ -496,6 +509,7 @@ func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]
for _, reference := range c.references {
switch reference := reference.(type) {
case *PhysicalTableReference:
+ schemas[""] = true
tables[reference.Table] = true
case *VirtualTableReference:
for _, column := range reference.Columns {
@@ -545,6 +559,77 @@ 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 == mysql.MySQLParserRULE_queryExpression {
+ for _, pos := range rule.CTEList {
+ c.cteTables = append(c.cteTables, c.extractCTETables(pos)...)
+ }
+ }
+ }
+}
+
+func (c *Completer) extractCTETables(pos int) []*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 := mysql.NewMySQLLexer(input)
+ tokens := antlr.NewCommonTokenStream(lexer, 0)
+ parser := mysql.NewMySQLParser(tokens)
+
+ parser.BuildParseTrees = true
+ parser.RemoveErrorListeners()
+ tree := parser.WithClause()
+
+ listener := &CTETableListener{context: c}
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ c.cteCache[pos] = listener.tables
+ return listener.tables
+}
+
+type CTETableListener struct {
+ *mysql.BaseMySQLParserListener
+
+ context *Completer
+ tables []*VirtualTableReference
+}
+
+func (l *CTETableListener) EnterCommonTableExpression(ctx *mysql.CommonTableExpressionContext) {
+ table := &VirtualTableReference{}
+ if ctx.Identifier() != nil {
+ table.Table = unquote(ctx.Identifier().GetText())
+ }
+ if ctx.ColumnInternalRefList() != nil {
+ for _, column := range ctx.ColumnInternalRefList().AllColumnInternalRef() {
+ table.Columns = append(table.Columns, unquote(column.Identifier().GetText()))
+ }
+ } else {
+ // User didn't specify the column list, so we need to fetch the column list from the database.
+ // TODO(zp): GetQuerySpan doesn't support MySQL yet.
+ if span, err := base.GetQuerySpan(
+ l.context.ctx,
+ store.Engine_MYSQL,
+ fmt.Sprintf("SELECT * FROM %s;", ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Subquery())),
+ 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-- {
@@ -1071,6 +1156,16 @@ func (m CompletionMap) insertDatabases(c *Completer) {
func (m CompletionMap) insertTables(c *Completer, schemas map[string]bool) {
for schema := range schemas {
+ if len(schema) == 0 {
+ // User didn't specify a schema, so 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,
@@ -1093,6 +1188,20 @@ func (m CompletionMap) insertViews(c *Completer, schemas map[string]bool) {
func (m CompletionMap) insertColumns(c *Completer, databases, tables map[string]bool) {
for database := range databases {
+ if len(database) == 0 {
+ // User didn't specify a schema, so 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
+ }
if _, exists := c.metadataCache[database]; !exists {
metadata, err := c.getMetadata(c.ctx, database)
if err != nil || metadata == nil {
diff --git a/backend/plugin/parser/mysql/test-data/test_completion.yaml b/backend/plugin/parser/mysql/test-data/test_completion.yaml
index 90bb700887..428ccab706 100644
--- a/backend/plugin/parser/mysql/test-data/test_completion.yaml
+++ b/backend/plugin/parser/mysql/test-data/test_completion.yaml
@@ -1,3 +1,43 @@
+- 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: db
+ type: DATABASE
+ definition: ""
+ comment: ""
+ - text: t1
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: t2
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: x
+ type: TABLE
+ definition: ""
+ comment: ""
+ - text: x1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: x2
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: v1
+ type: VIEW
+ definition: ""
+ comment: ""
- input: SELECT c1 as eid, c2 as xid FROM t2 ORDER BY |
want:
- text: db
diff --git a/go.mod b/go.mod
index 6c8a93bf62..f3702c374c 100644
--- a/go.mod
+++ b/go.mod
@@ -14,7 +14,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/licensemanager v1.23.1
github.com/aws/aws-sdk-go-v2/service/s3 v1.40.0
github.com/blang/semver/v4 v4.0.0
- github.com/bytebase/mysql-parser v0.0.0-20231117080012-40c25c7c076c
+ github.com/bytebase/mysql-parser v0.0.0-20231208095055-182de2379272
github.com/bytebase/plsql-parser v0.0.0-20231110065312-688a51648c4a
github.com/bytebase/postgresql-parser v0.0.0-20230926094140-aa337757cdd0
github.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9
diff --git a/go.sum b/go.sum
index 459e3a75db..1f595e1781 100644
--- a/go.sum
+++ b/go.sum
@@ -165,8 +165,8 @@ github.com/bytebase/gh-ost v1.1.3-0.20230915044519-b37a6525f8f9 h1:Sk8tTyttWhoKj
github.com/bytebase/gh-ost v1.1.3-0.20230915044519-b37a6525f8f9/go.mod h1:/HsnX0+34LXVz3MxtZoW15GiwEOXz/PrEhutjb3icfE=
github.com/bytebase/go-obo v0.0.0-20231026081615-705a7fffbfd2 h1:nEHZi8S7PHT4GxP9GfJiuhO8KkYcHmePvy5BfiYxwNk=
github.com/bytebase/go-obo v0.0.0-20231026081615-705a7fffbfd2/go.mod h1:wjDx6Xm9q7dFtHJvIlrI99JytznLw5wQ4R+9mNXJwGI=
-github.com/bytebase/mysql-parser v0.0.0-20231117080012-40c25c7c076c h1:cBlwIfQ8WJkz7XyBOUBw5dmFVhom65jPHlCaR9UzYlw=
-github.com/bytebase/mysql-parser v0.0.0-20231117080012-40c25c7c076c/go.mod h1:n22yoTeLcphIYQlV6nbufQbHMxNceOjeGDOrpaRIhiY=
+github.com/bytebase/mysql-parser v0.0.0-20231208095055-182de2379272 h1:nBidUCDZS6hEIW90zGs4C6skFGqgxDchAgqTTGh6EQM=
+github.com/bytebase/mysql-parser v0.0.0-20231208095055-182de2379272/go.mod h1:n22yoTeLcphIYQlV6nbufQbHMxNceOjeGDOrpaRIhiY=
github.com/bytebase/pg_query_go/v4 v4.0.0-20230802100607-2f34e68d96f5 h1:3Ihj6fsBY7rAKzOO2nxJocq9uOxARAwoalhC84ntjec=
github.com/bytebase/pg_query_go/v4 v4.0.0-20230802100607-2f34e68d96f5/go.mod h1:aEkDNOXNM5j0YGzaAapwJ7LB3dLNj+bvbWcLv1hOVqA=
github.com/bytebase/plsql-parser v0.0.0-20231110065312-688a51648c4a h1:2t4nAguPYBm7HWz8TA+HM6FWCdldfk7nmjTiksP2ZuE=