Skip to content

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

chore: add completion (#15936)

Vincent Huang19536c971f4d
diff --git a/backend/base/engine.go b/backend/base/engine.go
index e4719270ac..5c28651c1a 100644
--- a/backend/base/engine.go
+++ b/backend/base/engine.go
@@ -147,7 +147,8 @@ func EngineSupportAutoComplete(e storepb.Engine) bool {
storepb.Engine_DM,
storepb.Engine_OCEANBASE_ORACLE,
storepb.Engine_SNOWFLAKE,
- storepb.Engine_DYNAMODB:
+ storepb.Engine_DYNAMODB,
+ storepb.Engine_TRINO:
return true
case
storepb.Engine_ENGINE_UNSPECIFIED,
@@ -160,8 +161,7 @@ func EngineSupportAutoComplete(e storepb.Engine) bool {
storepb.Engine_HIVE,
storepb.Engine_ELASTICSEARCH,
storepb.Engine_DATABRICKS,
- storepb.Engine_COSMOSDB,
- storepb.Engine_TRINO:
+ storepb.Engine_COSMOSDB:
return false
default:
return false
diff --git a/backend/plugin/parser/trino/completion.go b/backend/plugin/parser/trino/completion.go
new file mode 100644
index 0000000000..54dcc21477
--- /dev/null
+++ b/backend/plugin/parser/trino/completion.go
@@ -0,0 +1,1678 @@
+package trino
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/antlr4-go/antlr/v4"
+ trinoparser "github.com/bytebase/trino-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ base.RegisterCompleteFunc(storepb.Engine_TRINO, Completion)
+}
+
+var (
+ // Check tableRefListener is implementing the TrinoParserListener interface.
+ _ trinoparser.TrinoParserListener = &tableRefListener{}
+ _ trinoparser.TrinoParserListener = &cteExtractor{}
+
+ globalFellowSetsByState = base.NewFollowSetsByState()
+ ignoredTokens = map[int]bool{
+ // // Common EOF
+ // trinoparser.TrinoParserEOF: true,
+
+ // // Whitespace and comments
+ // trinoparser.TrinoLexerWS_: true,
+ // trinoparser.TrinoLexerSIMPLE_COMMENT_: true,
+ // trinoparser.TrinoLexerBRACKETED_COMMENT_: true,
+
+ // // Identifiers and literals
+ // trinoparser.TrinoLexerIDENTIFIER_: true,
+ // trinoparser.TrinoLexerQUOTED_IDENTIFIER_: true,
+ // trinoparser.TrinoLexerDIGIT_IDENTIFIER_: true,
+ // trinoparser.TrinoLexerBACKQUOTED_IDENTIFIER_: true,
+ // trinoparser.TrinoLexerSTRING_: true,
+ // trinoparser.TrinoLexerUNICODE_STRING_: true,
+ // trinoparser.TrinoLexerDECIMAL_VALUE_: true,
+ // trinoparser.TrinoLexerDOUBLE_VALUE_: true,
+ // trinoparser.TrinoLexerINTEGER_VALUE_: true,
+ // trinoparser.TrinoLexerBINARY_LITERAL_: true,
+
+ // // Type related tokens
+ // trinoparser.TrinoLexerDOUBLE_: true,
+ // trinoparser.TrinoLexerPRECISION_: true,
+
+ // // Parameter token
+ // trinoparser.TrinoLexerQUESTION_MARK_: true,
+
+ // // Operators and punctuation
+ // trinoparser.TrinoLexerEQ_: true,
+ // trinoparser.TrinoLexerNEQ_: true,
+ // trinoparser.TrinoLexerLT_: true,
+ // trinoparser.TrinoLexerLTE_: true,
+ // trinoparser.TrinoLexerGT_: true,
+ // trinoparser.TrinoLexerGTE_: true,
+ // trinoparser.TrinoLexerPLUS_: true,
+ // trinoparser.TrinoLexerMINUS_: true,
+ // trinoparser.TrinoLexerASTERISK_: true,
+ // trinoparser.TrinoLexerSLASH_: true,
+ // trinoparser.TrinoLexerPERCENT_: true,
+ // trinoparser.TrinoLexerCONCAT_: true,
+ // trinoparser.TrinoLexerDOT_: true,
+ // trinoparser.TrinoLexerCOLON_: true,
+ // trinoparser.TrinoLexerSEMICOLON_: true,
+ // trinoparser.TrinoLexerCOMMA_: true,
+ // trinoparser.TrinoLexerLPAREN_: true,
+ // trinoparser.TrinoLexerRPAREN_: true,
+ // trinoparser.TrinoLexerLSQUARE_: true,
+ // trinoparser.TrinoLexerRSQUARE_: true,
+ // trinoparser.TrinoLexerLCURLY_: true,
+ // trinoparser.TrinoLexerRCURLY_: true,
+ // trinoparser.TrinoLexerLCURLYHYPHEN_: true,
+ // trinoparser.TrinoLexerRCURLYHYPHEN_: true,
+ // trinoparser.TrinoLexerLARROW_: true,
+ // trinoparser.TrinoLexerRARROW_: true,
+ // trinoparser.TrinoLexerRDOUBLEARROW_: true,
+ // trinoparser.TrinoLexerVBAR_: true,
+ // trinoparser.TrinoLexerDOLLAR_: true,
+ // trinoparser.TrinoLexerCARET_: true,
+ // trinoparser.TrinoLexerAT_: true,
+ }
+ preferredRules = map[int]bool{
+ // // Function call related rules - for function completion
+ // trinoparser.TrinoParserRULE_functionSpecification: true,
+ // trinoparser.TrinoParserRULE_functionDeclaration: true,
+
+ // // Table/Object name related rules - for table/view completion
+ trinoparser.TrinoParserRULE_qualifiedName: true,
+ // trinoparser.TrinoParserRULE_aliasedRelation: true,
+ // trinoparser.TrinoParserRULE_relationPrimary: true,
+ // trinoparser.TrinoParserRULE_sampledRelation: true,
+ // trinoparser.TrinoParserRULE_relation: true,
+
+ // // Column related rules - for column completion
+ // trinoparser.TrinoParserRULE_expression: true,
+ // trinoparser.TrinoParserRULE_primaryExpression: true,
+ // trinoparser.TrinoParserRULE_valueExpression: true,
+ // trinoparser.TrinoParserRULE_booleanExpression: true,
+
+ // // Specific query component rules
+ // trinoparser.TrinoParserRULE_selectItem: true,
+ // trinoparser.TrinoParserRULE_sortItem: true,
+ // trinoparser.TrinoParserRULE_groupBy: true,
+
+ // // Table function and related elements
+ // trinoparser.TrinoParserRULE_tableFunctionCall: true,
+ // trinoparser.TrinoParserRULE_tableFunctionArgument: true,
+
+ // // Alias related rules
+ // trinoparser.TrinoParserRULE_columnAliases: true,
+ // trinoparser.TrinoParserRULE_identifier: true,
+
+ // // Query related rules
+ // trinoparser.TrinoParserRULE_query: true,
+ // trinoparser.TrinoParserRULE_querySpecification: true,
+ // trinoparser.TrinoParserRULE_queryNoWith: true,
+ // trinoparser.TrinoParserRULE_queryTerm: true,
+ // trinoparser.TrinoParserRULE_queryPrimary: true,
+
+ // // CTE and WITH related rules
+ // trinoparser.TrinoParserRULE_with: true,
+ // trinoparser.TrinoParserRULE_namedQuery: true,
+ }
+)
+
+type CompletionMap map[string]base.Candidate
+
+func (m CompletionMap) Insert(entry base.Candidate) {
+ m[entry.String()] = entry
+}
+
+func (m CompletionMap) toSlice() []base.Candidate {
+ var result []base.Candidate
+ for _, candidate := range m {
+ result = append(result, candidate)
+ }
+ sort.Slice(result, func(i, j int) bool {
+ if result[i].Type != result[j].Type {
+ return result[i].Type < result[j].Type
+ }
+ return result[i].Text < result[j].Text
+ })
+ return result
+}
+
+// // insertFunctions inserts the built-in functions into the completion map.
+// func (m CompletionMap) insertBuiltinFunctions() {
+// for key := range trinoBuiltinFunctionsMap {
+// m[key] = base.Candidate{
+// Type: base.CandidateTypeFunction,
+// Text: key + "()",
+// }
+// }
+// }
+
+func (m CompletionMap) insertMetadataCatalogs(c *Completer) {
+ if c.defaultCatalog != "" {
+ m[c.defaultCatalog] = base.Candidate{
+ Type: base.CandidateTypeDatabase,
+ Text: c.quotedIdentifierIfNeeded(c.defaultCatalog),
+ }
+ }
+
+ allCatalogs, err := c.catalogNamesLister(c.ctx, c.instanceID)
+ if err != nil {
+ return
+ }
+
+ for _, catalog := range allCatalogs {
+ if _, ok := m[catalog]; !ok {
+ m[catalog] = base.Candidate{
+ Type: base.CandidateTypeDatabase,
+ Text: c.quotedIdentifierIfNeeded(catalog),
+ }
+ }
+ }
+}
+
+func (m CompletionMap) insertMetadataSchemas(c *Completer, catalog string) {
+ anchor := c.defaultCatalog
+ if catalog != "" {
+ anchor = catalog
+ }
+ if anchor == "" {
+ return
+ }
+
+ allCatalogNames, err := c.catalogNamesLister(c.ctx, c.instanceID)
+ if err != nil {
+ return
+ }
+ for _, catalogName := range allCatalogNames {
+ if strings.EqualFold(catalogName, anchor) {
+ anchor = catalogName
+ break
+ }
+ }
+
+ _, catalogMetadata, err := c.metadataGetter(c.ctx, c.instanceID, anchor)
+ if err != nil {
+ return
+ }
+
+ for _, schema := range catalogMetadata.ListSchemaNames() {
+ if _, ok := m[schema]; !ok {
+ m[schema] = base.Candidate{
+ Type: base.CandidateTypeSchema,
+ Text: c.quotedIdentifierIfNeeded(schema),
+ }
+ }
+ }
+}
+
+func (m CompletionMap) insertMetadataTables(c *Completer, catalog string, schema string) {
+ catalogName, schemaName := c.defaultCatalog, c.defaultSchema
+ if catalog != "" {
+ catalogName = catalog
+ }
+ if schema != "" {
+ schemaName = schema
+ }
+ if catalogName == "" || schemaName == "" {
+ return
+ }
+
+ _, catalogMetadata, err := c.metadataGetter(c.ctx, c.instanceID, catalogName)
+ if err != nil {
+ return
+ }
+ if catalogMetadata == nil {
+ return
+ }
+ for _, schema := range catalogMetadata.ListSchemaNames() {
+ if strings.EqualFold(schema, schemaName) {
+ schemaName = schema
+ break
+ }
+ }
+
+ schemaMetadata := catalogMetadata.GetSchema(schemaName)
+ if schemaMetadata == nil {
+ return
+ }
+ for _, table := range schemaMetadata.ListTableNames() {
+ if _, ok := m[table]; !ok {
+ m[table] = base.Candidate{
+ Type: base.CandidateTypeTable,
+ Text: c.quotedIdentifierIfNeeded(table),
+ }
+ }
+ }
+}
+
+func (m CompletionMap) insertAllColumns(c *Completer) {
+ _, catalogMeta, err := c.metadataGetter(c.ctx, c.instanceID, c.defaultCatalog)
+ if err != nil {
+ return
+ }
+ for _, schema := range catalogMeta.ListSchemaNames() {
+ schemaMeta := catalogMeta.GetSchema(schema)
+ if schemaMeta == nil {
+ continue
+ }
+ for _, table := range schemaMeta.ListTableNames() {
+ tableMeta := schemaMeta.GetTable(table)
+ if tableMeta == nil {
+ continue
+ }
+ for _, column := range tableMeta.GetColumns() {
+ columnID := getColumnID(c.defaultCatalog, schema, table, column.Name)
+ if _, ok := m[columnID]; !ok {
+ definition := fmt.Sprintf("%s.%s.%s | %s", c.defaultCatalog, schema, table, column.Type)
+ if !column.Nullable {
+ definition += ", NOT NULL"
+ }
+ comment := column.UserComment
+ m[columnID] = base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: c.quotedIdentifierIfNeeded(column.Name),
+ Definition: definition,
+ Comment: comment,
+ Priority: c.getPriority(c.defaultCatalog, schema, table),
+ }
+ }
+ }
+ }
+ }
+}
+
+func (c *Completer) getPriority(catalog string, schema string, table string) int {
+ if catalog == "" {
+ catalog = c.defaultCatalog
+ }
+ if schema == "" {
+ schema = c.defaultSchema
+ }
+ if c.referenceMap == nil {
+ return 1
+ }
+ if c.referenceMap[fmt.Sprintf("%s.%s.%s", catalog, schema, table)] {
+ // The higher priority.
+ return 0
+ }
+ return 1
+}
+
+func (m CompletionMap) insertMetadataColumns(c *Completer, catalog string, schema string, table string) {
+ catalogName, schemaName, tableName := c.defaultCatalog, c.defaultSchema, ""
+ if catalog != "" {
+ catalogName = catalog
+ }
+ if schema != "" {
+ schemaName = schema
+ }
+ if table != "" {
+ tableName = table
+ }
+ if catalogName == "" || schemaName == "" {
+ return
+ }
+ catalogNames, err := c.catalogNamesLister(c.ctx, c.instanceID)
+ if err != nil {
+ return
+ }
+ for _, catName := range catalogNames {
+ if strings.EqualFold(catName, catalogName) {
+ catalogName = catName
+ break
+ }
+ }
+ _, catalogMetadata, err := c.metadataGetter(c.ctx, c.instanceID, catalogName)
+ if err != nil {
+ return
+ }
+ if catalogMetadata == nil {
+ return
+ }
+ for _, schema := range catalogMetadata.ListSchemaNames() {
+ if strings.EqualFold(schema, schemaName) {
+ schemaName = schema
+ break
+ }
+ }
+ schemaMetadata := catalogMetadata.GetSchema(schemaName)
+ if schemaMetadata == nil {
+ return
+ }
+ var tableNames []string
+ for _, table := range schemaMetadata.ListTableNames() {
+ if tableName == "" {
+ tableNames = append(tableNames, table)
+ } else if strings.EqualFold(table, tableName) {
+ tableNames = append(tableNames, table)
+ break
+ }
+ }
+ for _, table := range tableNames {
+ tableMetadata := schemaMetadata.GetTable(table)
+ for _, column := range tableMetadata.GetColumns() {
+ columnID := getColumnID(catalogName, schemaName, table, column.Name)
+ if _, ok := m[columnID]; !ok {
+ definition := fmt.Sprintf("%s.%s.%s | %s", catalogName, schemaName, table, column.Type)
+ if !column.Nullable {
+ definition += ", NOT NULL"
+ }
+ comment := column.UserComment
+ m[columnID] = base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: c.quotedIdentifierIfNeeded(column.Name),
+ Definition: definition,
+ Comment: comment,
+ Priority: c.getPriority(c.defaultCatalog, schema, table),
+ }
+ }
+ }
+ }
+}
+
+func getColumnID(catalogName, schemaName, tableName, columnName string) string {
+ return fmt.Sprintf("%s.%s.%s.%s", catalogName, schemaName, tableName, columnName)
+}
+
+func (m CompletionMap) insertCTEs(c *Completer) {
+ for _, cte := range c.cteTables {
+ if _, ok := m[cte.Table]; !ok {
+ m[cte.Table] = base.Candidate{
+ Type: base.CandidateTypeTable,
+ Text: c.quotedIdentifierIfNeeded(cte.Table),
+ }
+ }
+ }
+}
+
+func (m CompletionMap) insertMetadataViews(c *Completer, catalog string, schema string) {
+ catalogName, schemaName := c.defaultCatalog, c.defaultSchema
+ if catalog != "" {
+ catalogName = catalog
+ }
+ if schema != "" {
+ schemaName = schema
+ }
+
+ if catalogName == "" || schemaName == "" {
+ return
+ }
+
+ _, catalogMetadata, err := c.metadataGetter(c.ctx, c.instanceID, catalogName)
+ if err != nil {
+ return
+ }
+ if catalogMetadata == nil {
+ return
+ }
+
+ schemaNames := catalogMetadata.ListSchemaNames()
+
+ var foundMatch bool
+ for _, schema := range schemaNames {
+ if strings.EqualFold(schema, schemaName) {
+ schemaName = schema
+ foundMatch = true
+ break
+ }
+ }
+
+ if !foundMatch {
+ return
+ }
+
+ schemaMetadata := catalogMetadata.GetSchema(schemaName)
+ if schemaMetadata == nil {
+ return
+ }
+
+ viewNames := schemaMetadata.ListViewNames()
+
+ for _, view := range viewNames {
+ if _, ok := m[view]; !ok {
+ m[view] = base.Candidate{
+ Type: base.CandidateTypeView,
+ Text: c.quotedIdentifierIfNeeded(view),
+ }
+ }
+ }
+
+ matViewNames := schemaMetadata.ListMaterializedViewNames()
+
+ for _, materializeView := range matViewNames {
+ if _, ok := m[materializeView]; !ok {
+ m[materializeView] = base.Candidate{
+ Type: base.CandidateTypeView,
+ Text: c.quotedIdentifierIfNeeded(materializeView),
+ }
+ }
+ }
+
+ foreignTableNames := schemaMetadata.ListForeignTableNames()
+
+ for _, foreignTable := range foreignTableNames {
+ if _, ok := m[foreignTable]; !ok {
+ m[foreignTable] = base.Candidate{
+ Type: base.CandidateTypeView,
+ Text: c.quotedIdentifierIfNeeded(foreignTable),
+ }
+ }
+ }
+}
+
+// quotedType is the type of quoted token
+type quotedType int
+
+const (
+ quotedTypeNone quotedType = iota
+ quotedTypeQuote // ""
+ quotedTypeBackQuote // ``
+)
+
+type Completer struct {
+ ctx context.Context
+ core *base.CodeCompletionCore
+ scene base.SceneType
+ parser *trinoparser.TrinoParser
+ lexer *trinoparser.TrinoLexer
+ scanner *base.Scanner
+
+ instanceID string
+ defaultCatalog string
+ defaultSchema string
+ metadataGetter base.GetDatabaseMetadataFunc
+ catalogNamesLister base.ListDatabaseNamesFunc
+
+ noSeparatorRequired map[int]bool
+ // referencesStack is a hierarchical stack of table references.
+ // We'll update the stack when we encounter a new FROM clauses.
+ referencesStack [][]base.TableReference
+ // references is the flattened table references.
+ // It's helpful to look up the table reference.
+ references []base.TableReference
+ referenceMap map[string]bool
+ cteCache map[int][]*base.VirtualTableReference
+ cteTables []*base.VirtualTableReference
+ caretTokenIsQuoted quotedType
+}
+
+func Completion(ctx context.Context, cCtx base.CompletionContext, statement string, caretLine int, caretOffset int) ([]base.Candidate, error) {
+ completer := NewStandardCompleter(ctx, cCtx, statement, caretLine, caretOffset)
+ completer.fetchCommonTableExpression(statement)
+ result, err := completer.complete()
+
+ if err != nil {
+ return nil, err
+ }
+ if len(result) > 0 {
+ return result, nil
+ }
+
+ trickyCompleter := NewTrickyCompleter(ctx, cCtx, statement, caretLine, caretOffset)
+ trickyCompleter.fetchCommonTableExpression(statement)
+ return trickyCompleter.complete()
+}
+
+func NewStandardCompleter(ctx context.Context, cCtx base.CompletionContext, statement string, caretLine int, caretOffset int) *Completer {
+ parser, lexer, scanner := prepareParserAndScanner(statement, caretLine, caretOffset)
+ core := base.NewCodeCompletionCore(
+ parser,
+ ignoredTokens, /* IgnoredTokens */
+ preferredRules, /* PreferredRules */
+ &globalFellowSetsByState,
+ trinoparser.TrinoParserRULE_queryNoWith,
+ trinoparser.TrinoParserRULE_query,
+ trinoparser.TrinoParserRULE_aliasedRelation,
+ trinoparser.TrinoParserRULE_with,
+ )
+
+ return &Completer{
+ ctx: ctx,
+ core: core,
+ scene: cCtx.Scene,
+ parser: parser,
+ lexer: lexer,
+ scanner: scanner,
+ instanceID: cCtx.InstanceID,
+ defaultCatalog: cCtx.DefaultDatabase,
+ defaultSchema: "dbo",
+ metadataGetter: cCtx.Metadata,
+ catalogNamesLister: cCtx.ListDatabaseNames,
+ noSeparatorRequired: nil,
+ cteCache: nil,
+ }
+}
+
+func NewTrickyCompleter(ctx context.Context, cCtx base.CompletionContext, statement string, caretLine int, caretOffset int) *Completer {
+ parser, lexer, scanner := prepareTrickyParserAndScanner(statement, caretLine, caretOffset)
+ core := base.NewCodeCompletionCore(
+ parser,
+ ignoredTokens, /* IgnoredTokens */
+ preferredRules, /* PreferredRules */
+ &globalFellowSetsByState,
+ trinoparser.TrinoParserRULE_queryNoWith,
+ trinoparser.TrinoParserRULE_query,
+ trinoparser.TrinoParserRULE_aliasedRelation,
+ trinoparser.TrinoParserRULE_with,
+ )
+
+ return &Completer{
+ ctx: ctx,
+ core: core,
+ scene: cCtx.Scene,
+ parser: parser,
+ lexer: lexer,
+ scanner: scanner,
+ instanceID: cCtx.InstanceID,
+ defaultCatalog: cCtx.DefaultDatabase,
+ defaultSchema: "dbo",
+ metadataGetter: cCtx.Metadata,
+ catalogNamesLister: cCtx.ListDatabaseNames,
+ noSeparatorRequired: nil,
+ cteCache: nil,
+ }
+}
+
+func prepareParserAndScanner(statement string, caretLine int, caretOffset int) (*trinoparser.TrinoParser, *trinoparser.TrinoLexer, *base.Scanner) {
+ statement, caretLine, caretOffset = skipHeadingSQLs(statement, caretLine, caretOffset)
+ input := antlr.NewInputStream(statement)
+ lexer := trinoparser.NewTrinoLexer(input)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := trinoparser.NewTrinoParser(stream)
+ parser.RemoveErrorListeners()
+ lexer.RemoveErrorListeners()
+ scanner := base.NewScanner(stream, true /* fillInput */)
+ scanner.SeekPosition(caretLine, caretOffset)
+ scanner.Push()
+ return parser, lexer, scanner
+}
+
+func prepareTrickyParserAndScanner(statement string, caretLine int, caretOffset int) (*trinoparser.TrinoParser, *trinoparser.TrinoLexer, *base.Scanner) {
+ statement, caretLine, caretOffset = skipHeadingSQLs(statement, caretLine, caretOffset)
+ // statement, caretLine, caretOffset = skipHeadingSQLWithoutSemicolon(statement, caretLine, caretOffset)
+ input := antlr.NewInputStream(statement)
+ lexer := trinoparser.NewTrinoLexer(input)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := trinoparser.NewTrinoParser(stream)
+ parser.RemoveErrorListeners()
+ lexer.RemoveErrorListeners()
+ scanner := base.NewScanner(stream, true /* fillInput */)
+ scanner.SeekPosition(caretLine, caretOffset)
+ scanner.Push()
+ return parser, lexer, scanner
+}
+
+// // caretLine is 1-based and caretOffset is 0-based.
+// func skipHeadingSQLWithoutSemicolon(statement string, caretLine int, caretOffset int) (string, int, int) {
+// input := antlr.NewInputStream(statement)
+// lexer := trinoparser.NewTrinoLexer(input)
+// stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+// lexer.RemoveErrorListeners()
+// lexerErrorListener := &base.ParseErrorListener{
+// Statement: statement,
+// }
+// lexer.AddErrorListener(lexerErrorListener)
+
+// stream.Fill()
+// tokens := stream.GetAllTokens()
+// latestSelect := 0
+// newCaretLine, newCaretOffset := caretLine, caretOffset
+// for _, token := range tokens {
+// if token.GetLine() > caretLine || (token.GetLine() == caretLine && token.GetColumn() >= caretOffset) {
+// break
+// }
+// if token.GetTokenType() == trinoparser.TrinoParserSELECT_ && token.GetColumn() == 0 {
+// latestSelect = token.GetTokenIndex()
+// newCaretLine = caretLine - token.GetLine() + 1 // convert to 1-based.
+// newCaretOffset = caretOffset
+// }
+// }
+
+// if latestSelect == 0 {
+// return statement, caretLine, caretOffset
+// }
+// return stream.GetTextFromInterval(antlr.NewInterval(latestSelect, stream.Size())), newCaretLine, newCaretOffset
+// }
+
+func (c *Completer) complete() ([]base.Candidate, error) {
+ if c.scanner.IsTokenType(trinoparser.TrinoParserQUOTED_IDENTIFIER_) {
+ c.caretTokenIsQuoted = quotedTypeQuote
+ }
+
+ caretIndex := c.scanner.GetIndex()
+
+ // Initialize noSeparatorRequired to avoid nil map issues
+ if c.noSeparatorRequired == nil {
+ c.noSeparatorRequired = make(map[int]bool)
+ }
+
+ if caretIndex > 0 && !c.noSeparatorRequired[c.scanner.GetPreviousTokenType(true)] {
+ caretIndex--
+ }
+
+ c.referencesStack = append([][]base.TableReference{{}}, c.referencesStack...)
+ c.parser.Reset()
+
+ var context antlr.ParserRuleContext
+ if c.scene == base.SceneTypeQuery {
+ context = c.parser.SingleStatement()
+ } else {
+ context = c.parser.Parse()
+ }
+
+ candidates := c.core.CollectCandidates(caretIndex, context)
+
+ for ruleName := range candidates.Rules {
+ if ruleName == trinoparser.TrinoParserRULE_primaryExpression {
+ c.collectLeadingTableReferences(caretIndex)
+ c.takeReferencesSnapshot()
+ c.collectRemainingTableReferences()
+ c.takeReferencesSnapshot()
+ break
+ }
+ }
+
+ result, err := c.convertCandidates(candidates)
+ return result, err
+}
+
+func (c *Completer) convertCandidates(candidates *base.CandidatesCollection) ([]base.Candidate, error) {
+ keywordEntries := make(CompletionMap)
+ functionEntries := make(CompletionMap)
+ catalogEntries := make(CompletionMap)
+ schemaEntries := make(CompletionMap)
+ tableEntries := make(CompletionMap)
+ columnEntries := make(CompletionMap)
+ viewEntries := make(CompletionMap)
+
+ // Check if noSeparatorRequired is initialized to avoid nil map access
+ if c.noSeparatorRequired == nil {
+ c.noSeparatorRequired = make(map[int]bool)
+ }
+
+ // Initialize reference map if nil to avoid issues
+ if c.referenceMap == nil {
+ c.referenceMap = make(map[string]bool)
+ }
+
+ for tokenCandidate, continuous := range candidates.Tokens {
+ if tokenCandidate < 0 || tokenCandidate >= len(c.parser.SymbolicNames) {
+ continue
+ }
+
+ candidateText := c.parser.SymbolicNames[tokenCandidate]
+ for _, continuous := range continuous {
+ if continuous < 0 || continuous >= len(c.parser.SymbolicNames) {
+ continue
+ }
+ continuousText := c.parser.SymbolicNames[continuous]
+ candidateText += " " + continuousText
+ }
+ keywordEntries.Insert(base.Candidate{
+ Type: base.CandidateTypeKeyword,
+ Text: candidateText,
+ })
+ }
+
+ // Store these in the completer so we can reference them elsewhere
+ c.noSeparatorRequired = make(map[int]bool)
+
+ for ruleCandidate, ruleStack := range candidates.Rules {
+ c.scanner.PopAndRestore()
+ c.scanner.Push()
+
+ switch ruleCandidate {
+ case trinoparser.TrinoParserRULE_qualifiedName:
+ // qualifiedName also appears in the columnReference rule, we would handle it in the columnReference rule in this case.
+ if len(ruleStack) > 0 && ruleStack[len(ruleStack)-1].ID == trinoparser.TrinoParserRULE_aliasedRelation {
+ continue
+ }
+ completionContexts := c.determineQualifiedNameContext()
+
+ for _, context := range completionContexts {
+ if context.flags&objectFlagShowCatalog != 0 {
+ catalogEntries.insertMetadataCatalogs(c)
+ }
+ if context.flags&objectFlagShowSchema != 0 {
+ schemaEntries.insertMetadataSchemas(c, context.catalog)
+ }
+ if context.flags&objectFlagShowObject != 0 {
+ tableEntries.insertMetadataTables(c, context.catalog, context.schema)
+ viewEntries.insertMetadataViews(c, context.catalog, context.schema)
+ }
+ if context.catalog == "" && context.schema == "" && context.flags&objectFlagShowObject != 0 {
+ // User do not specify the catalog and schema, and want us complete the objects, we should also insert the ctes.
+ tableEntries.insertCTEs(c)
+ }
+ }
+ case trinoparser.TrinoParserRULE_aliasedRelation:
+ completionContexts := c.determineColumnReference()
+ for _, context := range completionContexts {
+ if context.flags&objectFlagShowCatalog != 0 {
+ catalogEntries.insertMetadataCatalogs(c)
+ }
+ if context.flags&objectFlagShowSchema != 0 {
+ schemaEntries.insertMetadataSchemas(c, context.catalog)
+ }
+ if context.flags&objectFlagShowObject != 0 {
+ tableEntries.insertMetadataTables(c, context.catalog, context.schema)
+ viewEntries.insertMetadataViews(c, context.catalog, context.schema)
+ for _, reference := range c.references {
+ switch reference := reference.(type) {
+ case *base.PhysicalTableReference:
+ tableName := reference.Table
+ if reference.Alias != "" {
+ tableName = reference.Alias
+ }
+ if strings.EqualFold(reference.Database, context.catalog) &&
+ strings.EqualFold(reference.Schema, context.schema) {
+ if _, ok := tableEntries[tableName]; !ok {
+ tableEntries[tableName] = base.Candidate{
+ Type: base.CandidateTypeTable,
+ Text: c.quotedIdentifierIfNeeded(tableName),
+ }
+ }
+ }
+ case *base.VirtualTableReference:
+ // We only append the virtual table reference to the completion list when the catalog and schema are all empty.
+ if context.catalog == "" && context.schema == "" {
+ tableEntries[reference.Table] = base.Candidate{
+ Type: base.CandidateTypeTable,
+ Text: c.quotedIdentifierIfNeeded(reference.Table),
+ }
+ }
+ }
+ }
+ if context.catalog == "" && context.schema == "" {
+ // User do not specify the catalog and schema, and want us complete the objects, we should also insert the ctes.
+ tableEntries.insertCTEs(c)
+ }
+ }
+ if context.flags&objectFlagShowColumn != 0 {
+ list := c.fetchSelectItemAliases(ruleStack)
+ for _, alias := range list {
+ columnEntries.Insert(base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: c.quotedIdentifierIfNeeded(alias),
+ })
+ }
+ columnEntries.insertMetadataColumns(c, context.catalog, context.schema, context.object)
+ for _, reference := range c.references {
+ switch reference := reference.(type) {
+ case *base.PhysicalTableReference:
+ inputCatalogName := context.catalog
+ if inputCatalogName == "" {
+ inputCatalogName = c.defaultCatalog
+ }
+ inputSchemaName := context.schema
+ if inputSchemaName == "" {
+ inputSchemaName = c.defaultSchema
+ }
+ inputTableName := context.object
+
+ referenceCatalogName := reference.Database
+ if referenceCatalogName == "" {
+ referenceCatalogName = c.defaultCatalog
+ }
+ referenceSchemaName := reference.Schema
+ if referenceSchemaName == "" {
+ referenceSchemaName = c.defaultSchema
+ }
+ referenceTableName := reference.Table
+ if reference.Alias != "" {
+ referenceTableName = reference.Alias
+ }
+
+ if strings.EqualFold(referenceCatalogName, inputCatalogName) &&
+ strings.EqualFold(referenceSchemaName, inputSchemaName) &&
+ strings.EqualFold(referenceTableName, inputTableName) {
+ columnEntries.insertMetadataColumns(c, reference.Database, reference.Schema, reference.Table)
+ }
+ case *base.VirtualTableReference:
+ // Reference could be a physical table reference or a virtual table reference, if the reference is a virtual table reference,
+ // and users do not specify the catalog and schema, we should also insert the columns.
+ if context.catalog == "" && context.schema == "" {
+ for _, column := range reference.Columns {
+ if _, ok := columnEntries[column]; !ok {
+ columnEntries[column] = base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: c.quotedIdentifierIfNeeded(column),
+ }
+ }
+ }
+ }
+ }
+ }
+ if context.catalog == "" && context.schema == "" {
+ for _, cte := range c.cteTables {
+ if strings.EqualFold(cte.Table, context.object) {
+ for _, column := range cte.Columns {
+ if _, ok := columnEntries[column]; !ok {
+ columnEntries[column] = base.Candidate{
+ Type: base.CandidateTypeColumn,
+ Text: c.quotedIdentifierIfNeeded(column),
+ }
+ }
+ }
+ }
+ }
+ }
+ if context.empty() {
+ columnEntries.insertAllColumns(c)
+ }
+ }
+ }
+ }
+ }
+
+ c.scanner.PopAndRestore()
+ var result []base.Candidate
+ result = append(result, keywordEntries.toSlice()...)
+ result = append(result, functionEntries.toSlice()...)
+ result = append(result, catalogEntries.toSlice()...)
+ result = append(result, schemaEntries.toSlice()...)
+ result = append(result, tableEntries.toSlice()...)
+ result = append(result, columnEntries.toSlice()...)
+ result = append(result, viewEntries.toSlice()...)
+
+ return result, nil
+}
+
+type objectFlag int
+
+const (
+ objectFlagShowCatalog objectFlag = 1 << iota
+ objectFlagShowSchema
+ objectFlagShowObject
+ objectFlagShowColumn
+)
+
+type objectRefContextOption func(*objectRefContext)
+
+func withColumn() objectRefContextOption {
+ return func(c *objectRefContext) {
+ c.column = ""
+ c.flags |= objectFlagShowColumn
+ }
+}
+
+func newObjectRefContext(options ...objectRefContextOption) *objectRefContext {
+ o := &objectRefContext{
+ flags: objectFlagShowCatalog | objectFlagShowSchema | objectFlagShowObject,
+ }
+ for _, option := range options {
+ option(o)
+ }
+ return o
+}
+
+// objectRefContext provides precise completion context about the object reference,
+// check the flags and the fields to determine what kind of object should be included in the completion list.
+// Caller should call the newObjectRefContext to create a new objectRefContext, and modify it based on function it provides.
+type objectRefContext struct {
+ catalog string
+ schema string
+ object string
+
+ // column is optional considering field, for example, it should be not applicable for qualified name rule.
+ column string
+
+ flags objectFlag
+}
+
+func (o *objectRefContext) empty() bool {
+ return o.catalog == "" && o.schema == "" && o.object == "" && o.column == ""
+}
+
+func (o *objectRefContext) clone() *objectRefContext {
+ return &objectRefContext{
+ catalog: o.catalog,
+ schema: o.schema,
+ object: o.object,
+ column: o.column,
+ flags: o.flags,
+ }
+}
+
+func (o *objectRefContext) setCatalog(catalog string) *objectRefContext {
+ o.catalog = catalog
+ o.flags &= ^objectFlagShowCatalog
+ return o
+}
+
+func (o *objectRefContext) setSchema(schema string) *objectRefContext {
+ o.schema = schema
+ o.flags &= ^objectFlagShowSchema
+ return o
+}
+
+func (o *objectRefContext) setObject(object string) *objectRefContext {
+ o.object = object
+ o.flags &= ^objectFlagShowObject
+ return o
+}
+
+func (o *objectRefContext) setColumn(column string) *objectRefContext {
+ o.column = column
+ o.flags &= ^objectFlagShowColumn
+ return o
+}
+
+func (c *Completer) determineColumnReference() []*objectRefContext {
+ tokenIndex := c.scanner.GetIndex()
+ if c.scanner.GetTokenChannel() != antlr.TokenDefaultChannel {
+ // Skip to the next non-hidden token.
+ c.scanner.Forward(true /* skipHidden */)
+ }
+
+ // tokenType := c.scanner.GetTokenType()
+ if c.scanner.GetTokenText() != "." && !isIdentifier(c.scanner.GetTokenType()) {
+ c.scanner.Backward(true /* skipHidden */)
+ }
+
+ if tokenIndex > 0 {
+ // Go backward until we hit a non-identifier token.
+ for {
+ curID := isIdentifier(c.scanner.GetTokenType()) && c.scanner.GetPreviousTokenText(false /* skipHidden */) == "."
+ curDOT := c.scanner.GetTokenText() == "." && isIdentifier(c.scanner.GetPreviousTokenType(false /* skipHidden */))
+ if curID || curDOT {
+ c.scanner.Backward(true /* skipHidden */)
+ continue
+ }
+ break
+ }
+ }
+
+ // The c.scanner is now on the leading identifier (or dot?) if there's no leading id.
+ var candidates []string
+ var temp string
+ var count int
+ for {
+ count++
+ if isIdentifier(c.scanner.GetTokenType()) {
+ temp = normalizeIdentifierText(c.scanner.GetTokenText())
+ c.scanner.Forward(true /* skipHidden */)
+ if !c.scanner.IsTokenType(trinoparser.TrinoParserDOT_) || tokenIndex <= c.scanner.GetIndex() {
+ return deriveObjectRefContextsFromCandidates(candidates, true /* includeColumn */)
+ }
+ candidates = append(candidates, temp)
+ }
+ c.scanner.Forward(true /* skipHidden */)
+ if count > 3 {
+ break
+ }
+ }
+
+ return deriveObjectRefContextsFromCandidates(candidates, true /* includeColumn */)
+}
+
+func (c *Completer) determineQualifiedNameContext() []*objectRefContext {
+ tokenIndex := c.scanner.GetIndex()
+ if c.scanner.GetTokenChannel() != antlr.TokenDefaultChannel {
+ // Skip to the next non-hidden token.
+ c.scanner.Forward(true /* skipHidden */)
+ }
+
+ if c.scanner.GetTokenText() != "." && !isIdentifier(c.scanner.GetTokenType()) {
+ // We are at the end of an incomplete identifier spec. Jump back.
+ c.scanner.Backward(true /* skipHidden */)
+ }
+
+ if tokenIndex > 0 {
+ // Go backward until we hit a non-identifier token.
+ for {
+ curID := isIdentifier(c.scanner.GetTokenType()) && c.scanner.GetPreviousTokenText(false /* skipHidden */) == "."
+ curDOT := c.scanner.GetTokenText() == "." && isIdentifier(c.scanner.GetPreviousTokenType(false /* skipHidden */))
+ if curID || curDOT {
+ c.scanner.Backward(true /* skipHidden */)
+ continue
+ }
+ break
+ }
+ }
+
+ // The c.scanner is now on the leading identifier (or dot?) if there's no leading id.
+ var candidates []string
+ var temp string
+ var count int
+ for {
+ count++
+ if isIdentifier(c.scanner.GetTokenType()) {
+ temp = normalizeIdentifierText(c.scanner.GetTokenText())
+ c.scanner.Forward(true /* skipHidden */)
+ }
+ if !c.scanner.IsTokenType(trinoparser.TrinoParserDOT_) || tokenIndex <= c.scanner.GetIndex() {
+ return deriveObjectRefContextsFromCandidates(candidates, false /* includeColumn */)
+ }
+ candidates = append(candidates, temp)
+ c.scanner.Forward(true /* skipHidden */)
+ if count > 2 {
+ break
+ }
+ }
+
+ return deriveObjectRefContextsFromCandidates(candidates, false /* includeColumn */)
+}
+
+// deriveObjectRefContextsFromCandidates derives the object reference contexts from the candidates.
+// The Trino grammar's object reference likes [catalog_name.][schema_name.][object_name]
+// The size of candidates is the window size in the object reference,
+// for example, if the candidates are ["a", "b"], the size is 2,
+// and objectRefContext would be [catalog_name: "a", schema_name: "b", object_name: ""] or
+// [catalog_name: "", schema_name: "a", object_name: "b"].
+func deriveObjectRefContextsFromCandidates(candidates []string, includeColumn bool) []*objectRefContext {
+ var options []objectRefContextOption
+ if includeColumn {
+ options = append(options, withColumn())
+ }
+ refCtx := newObjectRefContext(options...)
+ if len(candidates) == 0 {
+ return []*objectRefContext{
+ refCtx.clone(),
+ }
+ }
+
+ var results []*objectRefContext
+ switch len(candidates) {
+ case 1:
+ results = append(
+ results,
+ refCtx.clone().setCatalog(candidates[0]),
+ refCtx.clone().setCatalog("").setSchema(candidates[0]),
+ refCtx.clone().setCatalog("").setSchema("").setObject(candidates[0]),
+ )
+ if includeColumn {
+ results = append(results, refCtx.clone().setCatalog("").setSchema("").setObject("").setColumn(candidates[0]))
+ }
+ case 2:
+ results = append(
+ results,
+ refCtx.clone().setCatalog(candidates[0]).setSchema(candidates[1]),
+ refCtx.clone().setCatalog("").setSchema(candidates[0]).setObject(candidates[1]),
+ )
+ if includeColumn {
+ results = append(results, refCtx.clone().setCatalog("").setSchema(candidates[0]).setObject("").setColumn(candidates[1]))
+ }
+ case 3:
+ results = append(
+ results,
+ refCtx.clone().setCatalog(candidates[0]).setSchema(candidates[1]).setObject(candidates[2]),
+ )
+ if includeColumn {
+ results = append(results, refCtx.clone().setCatalog(candidates[0]).setSchema(candidates[1]).setObject("").setColumn(candidates[2]))
+ }
+ case 4:
+ if includeColumn {
+ results = append(results, refCtx.clone().setCatalog(candidates[0]).setSchema(candidates[1]).setObject(candidates[2]).setColumn(candidates[3]))
+ }
+ }
+
+ if len(results) == 0 {
+ results = append(results, refCtx.clone())
+ }
+
+ return results
+}
+
+// skipHeadingSQLs skips the SQL statements which before the caret position.
+// caretLine is 1-based and caretOffset is 0-based.
+func skipHeadingSQLs(statement string, caretLine int, caretOffset int) (string, int, int) {
+ newCaretLine, newCaretOffset := caretLine, caretOffset
+ list, err := SplitSQL(statement)
+ if err != nil || notEmptySQLCount(list) <= 1 {
+ return statement, caretLine, caretOffset
+ }
+
+ caretLine-- // Convert to 0-based.
+
+ start := 0
+ for i, sql := range list {
+ sqlEndLine := int(sql.End.GetLine())
+ sqlEndColumn := int(sql.End.GetColumn())
+ if sqlEndLine > caretLine || (sqlEndLine == caretLine && sqlEndColumn >= caretOffset) {
+ start = i
+ if i == 0 {
+ // The caret is in the first SQL statement, so we don't need to skip any SQL statements.
+ break
+ }
+ previousSQLEndLine := int(list[i-1].End.GetLine())
+ previousSQLEndColumn := int(list[i-1].End.GetColumn())
+ newCaretLine = caretLine - previousSQLEndLine + 1 // Convert to 1-based.
+ if caretLine == previousSQLEndLine {
+ // The caret is in the same line as the last line of the previous SQL statement.
+ // We need to adjust the caret offset.
+ newCaretOffset = caretOffset - previousSQLEndColumn - 1 // Convert to 0-based.
+ }
+ break
+ }
+ }
+
+ var buf strings.Builder
+ for i := start; i < len(list); i++ {
+ if _, err := buf.WriteString(list[i].Text); err != nil {
+ return statement, caretLine, caretOffset
+ }
+ }
+
+ return buf.String(), newCaretLine, newCaretOffset
+}
+
+func notEmptySQLCount(list []base.SingleSQL) int {
+ count := 0
+ for _, sql := range list {
+ if !sql.Empty {
+ count++
+ }
+ }
+ return count
+}
+
+func (c *Completer) takeReferencesSnapshot() {
+ if c.referenceMap == nil {
+ c.referenceMap = make(map[string]bool)
+ }
+ for _, references := range c.referencesStack {
+ c.references = append(c.references, references...)
+ for _, reference := range references {
+ if r, ok := reference.(*base.PhysicalTableReference); ok {
+ catalog := r.Database
+ if catalog == "" {
+ catalog = c.defaultCatalog
+ }
+ schema := r.Schema
+ if schema == "" {
+ schema = c.defaultSchema
+ }
+ tableID := fmt.Sprintf("%s.%s.%s", catalog, schema, r.Table)
+ c.referenceMap[tableID] = true
+ }
+ }
+ }
+}
+
+func (c *Completer) collectLeadingTableReferences(caretIndex int) {
+ c.scanner.Push()
+
+ c.scanner.SeekIndex(0)
+
+ level := 0
+ for {
+ found := c.scanner.GetTokenType() == trinoparser.TrinoParserFROM_
+ for !found {
+ if !c.scanner.Forward(false) || c.scanner.GetIndex() >= caretIndex {
+ break
+ }
+
+ switch c.scanner.GetTokenType() {
+ case trinoparser.TrinoParserLPAREN_:
+ level++
+ c.referencesStack = append([][]base.TableReference{{}}, c.referencesStack...)
+ case trinoparser.TrinoParserRPAREN_:
+ if level == 0 {
+ c.scanner.PopAndRestore()
+ return // We cannot go above the initial nesting level.
+ }
+ case trinoparser.TrinoParserFROM_:
+ found = true
+ }
+ }
+ if !found {
+ c.scanner.PopAndRestore()
+ return // No FROM clause found.
+ }
+ c.parseTableReferences(c.scanner.GetFollowingText())
+ if c.scanner.GetTokenType() == trinoparser.TrinoParserFROM_ {
+ c.scanner.Forward(false /* skipHidden */)
+ }
+ }
+}
+
+func (c *Completer) collectRemainingTableReferences() {
+ c.scanner.Push()
+
+ level := 0
+ for {
+ found := c.scanner.GetTokenType() == trinoparser.TrinoParserFROM_
+ for !found {
+ if !c.scanner.Forward(false /* skipHidden */) {
+ break
+ }
+
+ switch c.scanner.GetTokenType() {
+ case trinoparser.TrinoParserLPAREN_:
+ level++
+ c.referencesStack = append([][]base.TableReference{{}}, c.referencesStack...)
+ case trinoparser.TrinoParserRPAREN_:
+ if level > 0 {
+ level--
+ }
+
+ case trinoparser.TrinoParserFROM_:
+ if level == 0 {
+ found = true
+ }
+ }
+ }
+
+ if !found {
+ c.scanner.PopAndRestore()
+ return // No more FROM clause found.
+ }
+
+ c.parseTableReferences(c.scanner.GetFollowingText())
+ if c.scanner.GetTokenType() == trinoparser.TrinoParserFROM_ {
+ c.scanner.Forward(false /* skipHidden */)
+ }
+ }
+}
+
+func (c *Completer) parseTableReferences(fromClause string) {
+ input := antlr.NewInputStream(fromClause)
+ lexer := trinoparser.NewTrinoLexer(input)
+ tokens := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := trinoparser.NewTrinoParser(tokens)
+
+ parser.BuildParseTrees = true
+ parser.RemoveErrorListeners()
+ tree := parser.Relation()
+ listener := &tableRefListener{
+ context: c,
+ fromClauseMode: true,
+ }
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+}
+
+type tableRefListener struct {
+ *trinoparser.BaseTrinoParserListener
+
+ context *Completer
+ fromClauseMode bool
+ done bool
+ level int
+}
+
+func (l *tableRefListener) ExitAliasedRelation(ctx *trinoparser.AliasedRelationContext) {
+ if l.done {
+ return
+ }
+ if l.level == 0 && len(l.context.referencesStack) != 0 && len(l.context.referencesStack[0]) != 0 {
+ if ctx.Identifier() != nil {
+ alias := unquote(ctx.Identifier().GetText())
+ if physicalTable, ok := l.context.referencesStack[0][len(l.context.referencesStack[0])-1].(*base.PhysicalTableReference); ok {
+ physicalTable.Alias = alias
+ return
+ }
+ if virtualTable, ok := l.context.referencesStack[0][len(l.context.referencesStack[0])-1].(*base.VirtualTableReference); ok {
+ virtualTable.Table = alias
+ }
+ }
+ }
+}
+
+func (l *tableRefListener) ExitColumnAliases(ctx *trinoparser.ColumnAliasesContext) {
+ if l.done {
+ return
+ }
+
+ if l.level == 0 && len(l.context.referencesStack) != 0 && len(l.context.referencesStack[0]) != 0 {
+ if virtualTable, ok := l.context.referencesStack[0][len(l.context.referencesStack[0])-1].(*base.VirtualTableReference); ok {
+ var newColumns []string
+ for _, column := range ctx.AllIdentifier() {
+ newColumns = append(newColumns, unquote(column.GetText()))
+ }
+ virtualTable.Columns = newColumns
+ }
+ }
+}
+
+func (l *tableRefListener) ExitQualifiedName(ctx *trinoparser.QualifiedNameContext) {
+ if l.done {
+ return
+ }
+
+ if !l.fromClauseMode || l.level == 0 {
+ reference := &base.PhysicalTableReference{}
+ catalog, schema, table := normalizeQualifiedNameFallback(ctx, "", "")
+ reference.Database = catalog // Using Database field for Catalog in Trino
+ reference.Schema = schema
+ reference.Table = table
+ l.context.referencesStack[0] = append(l.context.referencesStack[0], reference)
+ }
+}
+
+func (l *tableRefListener) ExitTableFunctionInvocation(_ *trinoparser.TableFunctionInvocationContext) {
+ if l.done {
+ return
+ }
+
+ if !l.fromClauseMode || l.level == 0 {
+ reference := &base.VirtualTableReference{}
+ l.context.referencesStack[0] = append(l.context.referencesStack[0], reference)
+ }
+}
+
+func (l *tableRefListener) ExitSubquery(ctx *trinoparser.SubqueryContext) {
+ if l.done {
+ return
+ }
+
+ // In Trino, subqueries must be aliased in an aliasedRelation
+ pCtx, ok := ctx.GetParent().(*trinoparser.SubqueryRelationContext)
+ if !ok {
+ return
+ }
+
+ // Check for grandparent context which should be an aliasedRelation
+ gCtx, ok := pCtx.GetParent().(*trinoparser.AliasedRelationContext)
+ if !ok {
+ return
+ }
+
+ var derivedTableName string
+ if gCtx.Identifier() != nil {
+ derivedTableName = unquote(gCtx.Identifier().GetText())
+ } else {
+ // If no explicit alias, we can't reference this subquery's columns
+ return
+ }
+
+ reference := &base.VirtualTableReference{
+ Table: derivedTableName,
+ }
+
+ if gCtx.ColumnAliases() == nil {
+ // User did not specify the column alias, we should use query span to get the column alias.
+ if span, err := GetQuerySpan(
+ l.context.ctx,
+ base.GetQuerySpanContext{
+ InstanceID: l.context.instanceID,
+ GetDatabaseMetadataFunc: l.context.metadataGetter,
+ ListDatabaseNamesFunc: l.context.catalogNamesLister,
+ },
+ fmt.Sprintf("SELECT * FROM (%s);", ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)),
+ l.context.defaultCatalog,
+ l.context.defaultSchema,
+ true,
+ ); err == nil && span.NotFoundError == nil {
+ for _, column := range span.Results {
+ reference.Columns = append(reference.Columns, column.Name)
+ }
+ }
+ } else {
+ // If column aliases are specified, use them
+ for _, identifier := range gCtx.ColumnAliases().AllIdentifier() {
+ reference.Columns = append(reference.Columns, unquote(identifier.GetText()))
+ }
+ }
+ l.context.referencesStack[0] = append(l.context.referencesStack[0], reference)
+}
+
+func (l *tableRefListener) EnterSubqueryRelation(*trinoparser.SubqueryRelationContext) {
+ if l.done {
+ return
+ }
+
+ if l.fromClauseMode {
+ l.level++
+ } else {
+ l.context.referencesStack = append([][]base.TableReference{{}}, l.context.referencesStack...)
+ }
+}
+
+func (l *tableRefListener) ExitSubqueryRelation(*trinoparser.SubqueryRelationContext) {
+ if l.done {
+ return
+ }
+
+ if l.fromClauseMode {
+ l.level--
+ } else {
+ l.context.referencesStack = l.context.referencesStack[1:]
+ }
+}
+
+func (c *Completer) fetchCommonTableExpression(statement string) {
+ c.cteTables = nil
+
+ // Extract CTEs using the cteExtractor
+ extractor := &cteExtractor{
+ completer: c,
+ }
+ input := antlr.NewInputStream(statement)
+ lexer := trinoparser.NewTrinoLexer(input)
+ tokens := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := trinoparser.NewTrinoParser(tokens)
+ parser.BuildParseTrees = true
+ parser.RemoveErrorListeners()
+ tree := parser.Parse()
+ antlr.ParseTreeWalkerDefault.Walk(extractor, tree)
+ c.cteTables = extractor.virtualReferences
+}
+
+type cteExtractor struct {
+ *trinoparser.BaseTrinoParserListener
+
+ completer *Completer
+ handled bool
+ virtualReferences []*base.VirtualTableReference
+}
+
+func (c *cteExtractor) EnterWith(ctx *trinoparser.WithContext) {
+ if c.handled {
+ return
+ }
+ c.handled = true
+
+ for _, namedQuery := range ctx.AllNamedQuery() {
+ cteName := namedQuery.Identifier().GetText()
+ if cteName == "" {
+ continue
+ }
+
+ var columns []string
+ if namedQuery.ColumnAliases() != nil {
+ for _, columnID := range namedQuery.ColumnAliases().AllIdentifier() {
+ columns = append(columns, unquote(columnID.GetText()))
+ }
+ c.virtualReferences = append(c.virtualReferences, &base.VirtualTableReference{
+ Table: unquote(cteName),
+ Columns: columns,
+ })
+ continue
+ }
+
+ // If column aliases are not specified, use query span to get the column names
+ cteBody := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(namedQuery.Query())
+ statement := fmt.Sprintf("WITH %s AS (%s) SELECT * FROM %s", cteName, cteBody, cteName)
+ if span, err := GetQuerySpan(
+ c.completer.ctx,
+ base.GetQuerySpanContext{
+ InstanceID: c.completer.instanceID,
+ GetDatabaseMetadataFunc: c.completer.metadataGetter,
+ ListDatabaseNamesFunc: c.completer.catalogNamesLister,
+ },
+ statement,
+ c.completer.defaultCatalog,
+ c.completer.defaultSchema,
+ true,
+ ); err == nil && span.NotFoundError == nil {
+ var columns []string
+ for _, column := range span.Results {
+ columns = append(columns, column.Name)
+ }
+ c.virtualReferences = append(c.virtualReferences, &base.VirtualTableReference{
+ Table: unquote(cteName),
+ Columns: columns,
+ })
+ }
+ }
+}
+
+func (c *Completer) fetchSelectItemAliases(ruleStack []*base.RuleContext) []string {
+ canUseAliases := false
+ for i := len(ruleStack) - 1; i >= 0; i-- {
+ switch ruleStack[i].ID {
+ case trinoparser.TrinoParserRULE_query, trinoparser.TrinoParserRULE_querySpecification:
+ if !canUseAliases {
+ return nil
+ }
+ aliasMap := make(map[string]bool)
+ for pos := range ruleStack[i].SelectItemAliases {
+ if aliasText := c.extractAliasText(pos); len(aliasText) > 0 {
+ aliasMap[aliasText] = true
+ }
+ }
+
+ var result []string
+ for alias := range aliasMap {
+ result = append(result, alias)
+ }
+ sort.Slice(result, func(i, j int) bool {
+ return result[i] < result[j]
+ })
+ return result
+ case trinoparser.TrinoParserRULE_groupBy, trinoparser.TrinoParserRULE_sortItem, trinoparser.TrinoParserRULE_booleanExpression:
+ // These represent ORDER BY, GROUP BY, and HAVING contexts
+ canUseAliases = true
+ }
+ }
+
+ return nil
+}
+
+func (c *Completer) extractAliasText(pos int) string {
+ followingText := c.scanner.GetFollowingTextAfter(pos)
+ if len(followingText) == 0 {
+ return ""
+ }
+
+ input := antlr.NewInputStream(followingText)
+ lexer := trinoparser.NewTrinoLexer(input)
+ tokens := antlr.NewCommonTokenStream(lexer, 0)
+ parser := trinoparser.NewTrinoParser(tokens)
+
+ parser.BuildParseTrees = true
+ parser.RemoveErrorListeners()
+ // For Trino we'll use expression as the entry point for column aliases
+ tree := parser.Identifier()
+
+ listener := &SelectAliasListener{}
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ return listener.result
+}
+
+type SelectAliasListener struct {
+ *trinoparser.BaseTrinoParserListener
+
+ result string
+}
+
+func (l *SelectAliasListener) EnterIdentifier(ctx *trinoparser.IdentifierContext) {
+ // For Trino, we'll just take the first identifier we find in the column alias
+ if l.result == "" {
+ l.result = unquote(ctx.GetText())
+ }
+}
+
+func (c *Completer) quotedIdentifierIfNeeded(identifier string) string {
+ if c.caretTokenIsQuoted != quotedTypeNone {
+ return identifier
+ }
+ // if !isRegularIdentifier(identifier) {
+ // return fmt.Sprintf("\"%s\"", identifier)
+ // }
+ return identifier
+}
+
+// Helper functions
+func isIdentifier(tokenType int) bool {
+ return tokenType == trinoparser.TrinoParserIDENTIFIER_ ||
+ tokenType == trinoparser.TrinoParserQUOTED_IDENTIFIER_ ||
+ tokenType == trinoparser.TrinoParserDIGIT_IDENTIFIER_
+}
+
+func normalizeIdentifierText(text string) string {
+ return unquote(text)
+}
+
+func unquote(text string) string {
+ // Remove quotes from identifiers if present
+ if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' {
+ return text[1 : len(text)-1]
+ }
+ return text
+}
+
+func normalizeQualifiedNameFallback(ctx *trinoparser.QualifiedNameContext, _ string, _ string) (string, string, string) {
+ parts := []string{}
+
+ for _, identifier := range ctx.AllIdentifier() {
+ parts = append(parts, unquote(identifier.GetText()))
+ }
+
+ catalog, schema, table := "", "", ""
+
+ switch len(parts) {
+ case 1:
+ table = parts[0]
+ case 2:
+ schema = parts[0]
+ table = parts[1]
+ case 3:
+ catalog = parts[0]
+ schema = parts[1]
+ table = parts[2]
+ }
+
+ return catalog, schema, table
+}
+
+// func isRegularIdentifier(identifier string) bool {
+// // https://trino.io/docs/current/language/reserved.html
+// // Regular identifiers in Trino have these rules:
+// // - Start with a letter (a-z)
+// // - Can contain letters, digits, underscore
+// // - Not a reserved word
+// if len(identifier) == 0 {
+// return true
+// }
+
+// firstChar := rune(identifier[0])
+// isFirstCharValid := unicode.IsLetter(firstChar)
+// if !isFirstCharValid {
+// return false
+// }
+
+// for _, r := range identifier[1:] {
+// isValidChar := unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
+// if !isValidChar {
+// return false
+// }
+// }
+
+// // Check if the identifier is a reserved word
+// if IsTrinoReservedKeyword(identifier) {
+// return false
+// }
+
+// // Check for embedded spaces or special characters
+// for _, r := range identifier {
+// if r == ' ' || !unicode.IsPrint(r) {
+// return false
+// }
+// }
+
+// return utf8.ValidString(identifier)
+// }
diff --git a/backend/plugin/parser/trino/completion_test.go b/backend/plugin/parser/trino/completion_test.go
new file mode 100644
index 0000000000..dd49069673
--- /dev/null
+++ b/backend/plugin/parser/trino/completion_test.go
@@ -0,0 +1,210 @@
+package trino
+
+import (
+ "context"
+ "io"
+ "os"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/store/model"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+type candidatesTest struct {
+ Description string `yaml:"description"`
+ Input string `yaml:"input"`
+ Want []base.Candidate `yaml:"want"`
+}
+
+// TestCompletion tests the Transact-SQL auto-completion, all the test cases are stored in the file.
+//
+// - Description: The description of the test case.
+//
+// - Input: The input statement with the caret position marked by "|".
+//
+// - Want: The expected completion candidates.
+//
+// Our Test suite will determine the caret position - line(0-based) and column(1-based) by the position of the "|", actually,
+// this caret position is as same as the position in the monaco-editor(LSP?).
+func TestCompletion(t *testing.T) {
+ tests := []candidatesTest{}
+
+ const (
+ record = true
+ )
+ var (
+ filepath = "test-data/completion/t_cc.yaml"
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(yamlFile.Close())
+ a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
+
+ for i, t := range tests {
+ statement, caretLine, caretPosition := getCaretPosition(t.Input)
+ getter, lister := buildMockDatabaseMetadataGetterLister()
+ results, err := Completion(context.Background(), base.CompletionContext{
+ Scene: base.SceneTypeAll,
+ DefaultDatabase: "Company",
+ Metadata: getter,
+ ListDatabaseNames: lister,
+ }, statement, caretLine, caretPosition)
+ a.NoErrorf(err, "Case %02d: %s", i, t.Description)
+ var filteredResult []base.Candidate
+ for _, r := range results {
+ switch r.Type {
+ case base.CandidateTypeKeyword, base.CandidateTypeFunction:
+ continue
+ default:
+ filteredResult = append(filteredResult, r)
+ }
+ }
+ sort.Slice(filteredResult, func(i, j int) bool {
+ if filteredResult[i].Type != filteredResult[j].Type {
+ return filteredResult[i].Type < filteredResult[j].Type
+ }
+ if filteredResult[i].Text != filteredResult[j].Text {
+ return filteredResult[i].Text < filteredResult[j].Text
+ }
+ return filteredResult[i].Definition < filteredResult[j].Definition
+ })
+
+ if record {
+ tests[i].Want = filteredResult
+ } else {
+ a.Equalf(t.Want, filteredResult, t.Input, "Case %02d: %s", i, t.Description)
+ }
+ }
+
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
+
+func getCaretPosition(statement string) (string, int, int) {
+ lines := strings.Split(statement, "\n")
+ for i, line := range lines {
+ if offset := strings.Index(line, "|"); offset != -1 {
+ newLine := strings.Replace(line, "|", "", 1)
+ lines[i] = newLine
+ return strings.Join(lines, "\n"), i + 1, offset
+ }
+ }
+ panic("caret position not found")
+}
+
+var databaseMetadatas = []*storepb.DatabaseSchemaMetadata{
+ {
+ Name: "Company",
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: "dbo",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "Employees",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "Id",
+ Type: "int",
+ },
+ {
+ Name: "Name",
+ Type: "varchar",
+ },
+ },
+ },
+ {
+ Name: "Address",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "EmployeeId",
+ Type: "int",
+ },
+ {
+ Name: "Street",
+ Type: "varchar",
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: "MySchema",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "SalaryLevel",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "Id",
+ Type: "int",
+ },
+ {
+ Name: "SalaryUpBound",
+ Type: "int",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: "School",
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: "dbo",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "Student",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "Id",
+ Type: "int",
+ },
+ {
+ Name: "ParentName",
+ Type: "varchar",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+}
+
+func buildMockDatabaseMetadataGetterLister() (base.GetDatabaseMetadataFunc, base.ListDatabaseNamesFunc) {
+ return func(_ context.Context, _, databaseName string) (string, *model.DatabaseMetadata, error) {
+ m := make(map[string]*model.DatabaseMetadata)
+ for _, metadata := range databaseMetadatas {
+ m[metadata.Name] = model.NewDatabaseMetadata(metadata, false /* isObjectCaseSensitive */, false /* isDetailCaseSensitive */)
+ }
+
+ if databaseMetadata, ok := m[databaseName]; ok {
+ return "", databaseMetadata, nil
+ }
+
+ return "", nil, errors.Errorf("database %q not found", databaseName)
+ }, func(context.Context, string) ([]string, error) {
+ var names []string
+ for _, metadata := range databaseMetadatas {
+ names = append(names, metadata.Name)
+ }
+ return names, nil
+ }
+}
diff --git a/backend/plugin/parser/trino/test-data/completion/t_c.yaml b/backend/plugin/parser/trino/test-data/completion/t_c.yaml
new file mode 100644
index 0000000000..16ef2dda37
--- /dev/null
+++ b/backend/plugin/parser/trino/test-data/completion/t_c.yaml
@@ -0,0 +1,277 @@
+- input: |-
+ select count(1) from users where id = 1; SELECT * FROM |
+ select * from orders where order_id like '%123';
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+
+- input: "|"
+ want:
+ - text: SELECT
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: CREATE
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: INSERT
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: ALTER
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: DROP
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SEL|"
+ want:
+ - text: SELECT
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM |"
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM catalog1.|"
+ want:
+ - text: public
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: analytics
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM catalog1.public.|"
+ want:
+ - text: orders
+ type: TABLE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT | FROM users"
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+
+- input: "SELECT users.| FROM users"
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM users u WHERE u.|"
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR
+ comment: ""
+ priority: 0
+
+- input: "SELECT u.id, o.total FROM users u JOIN orders o ON u.id = o.|"
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.orders | INT
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.public.orders | INT
+ comment: ""
+ priority: 0
+ - text: total
+ type: COLUMN
+ definition: catalog1.public.orders | DECIMAL
+ comment: ""
+ priority: 0
+
+- input: "WITH cte_test AS (SELECT id, name FROM users) SELECT | FROM cte_test"
+ want:
+ - text: id
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "WITH cte_test AS (SELECT id, name FROM users) SELECT * FROM |"
+ want:
+ - text: cte_test
+ type: TABLE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM (SELECT id, name FROM users) AS subq WHERE subq.|"
+ want:
+ - text: id
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT id AS user_id, name FROM users ORDER BY |"
+ want:
+ - text: user_id
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT metrics.| FROM catalog1.analytics.metrics"
+ want:
+ - text: timestamp
+ type: COLUMN
+ definition: catalog1.analytics.metrics | TIMESTAMP
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.analytics.metrics | INT
+ comment: ""
+ priority: 0
+ - text: value
+ type: COLUMN
+ definition: catalog1.analytics.metrics | DOUBLE
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM catalog2.|"
+ want:
+ - text: test
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ priority: 0
+
+- input: "SELECT * FROM catalog2.test.external_data WHERE |"
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog2.test.external_data | VARCHAR
+ comment: ""
+ priority: 0
+ - text: data
+ type: COLUMN
+ definition: catalog2.test.external_data | JSON
+ comment: ""
+ priority: 0
\ No newline at end of file
diff --git a/backend/plugin/parser/trino/test-data/completion/t_cc.yaml b/backend/plugin/parser/trino/test-data/completion/t_cc.yaml
new file mode 100644
index 0000000000..8be91760b9
--- /dev/null
+++ b/backend/plugin/parser/trino/test-data/completion/t_cc.yaml
@@ -0,0 +1,33 @@
+- description: Multiple statements
+ input: SELECT * FROM |
+ want:
+ - text: Company
+ type: DATABASE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: School
+ type: DATABASE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: MySchema
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: dbo
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: Address
+ type: TABLE
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: Employees
+ type: TABLE
+ definition: ""
+ comment: ""
+ priority: 0
diff --git a/backend/plugin/parser/trino/test-data/completion/test_completion.yaml b/backend/plugin/parser/trino/test-data/completion/test_completion.yaml
new file mode 100644
index 0000000000..bbdbd5b23a
--- /dev/null
+++ b/backend/plugin/parser/trino/test-data/completion/test_completion.yaml
@@ -0,0 +1,267 @@
+- input: |-
+ select count(1) from users where id 'invalid'; SELECT * FROM |
+ select * from orders where order_id like '%123';
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+- input: SELECT * FROM |
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+- input: SELECT | FROM users
+ want:
+ - text: '"timestamp"'
+ type: COLUMN
+ definition: catalog1.analytics.metrics | TIMESTAMP, NOT NULL
+ comment: ""
+ priority: 0
+ - text: '"value"'
+ type: COLUMN
+ definition: catalog1.analytics.metrics | DOUBLE, NOT NULL
+ comment: ""
+ priority: 0
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ priority: 0
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.orders | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ priority: 0
+ - text: total
+ type: COLUMN
+ definition: catalog1.public.orders | DECIMAL, NOT NULL
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.analytics.metrics | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.public.orders | INT, NOT NULL
+ comment: ""
+ priority: 0
+- input: SELECT * FROM catalog1.|
+ want:
+ - text: analytics
+ type: SCHEMA
+ definition: ""
+ comment: ""
+ - text: public
+ type: SCHEMA
+ definition: ""
+ comment: ""
+- input: SELECT * FROM catalog1.public.|
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+- input: SELECT * FROM analytics.|
+ want:
+ - text: metrics
+ type: TABLE
+ definition: catalog1.analytics.metrics
+ comment: ""
+- input: SELECT * FROM catalog2.test.|
+ want:
+ - text: external_data
+ type: TABLE
+ definition: catalog2.test.external_data
+ comment: ""
+- input: SELECT u.| FROM users u
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT, NOT NULL
+ comment: ""
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+- input: WITH x(x1, x2) AS (SELECT id, name FROM users) SELECT x.| FROM x;
+ want:
+ - text: x1
+ type: COLUMN
+ definition: ""
+ comment: ""
+ - text: x2
+ type: COLUMN
+ definition: ""
+ comment: ""
+- input: WITH x(x1, x2) AS (SELECT id, name FROM users) SELECT | FROM x;
+ want:
+ - text: '"timestamp"'
+ type: COLUMN
+ definition: catalog1.analytics.metrics | TIMESTAMP, NOT NULL
+ comment: ""
+ priority: 0
+ - text: '"value"'
+ type: COLUMN
+ definition: catalog1.analytics.metrics | DOUBLE, NOT NULL
+ comment: ""
+ priority: 0
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ priority: 0
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.orders | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ priority: 0
+ - text: total
+ type: COLUMN
+ definition: catalog1.public.orders | DECIMAL, NOT NULL
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.analytics.metrics | INT, NOT NULL
+ comment: ""
+ priority: 0
+ - text: user_id
+ type: COLUMN
+ definition: catalog1.public.orders | INT, NOT NULL
+ comment: ""
+ priority: 0
+- input: SELECT catalog1.public.users.|
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT, NOT NULL
+ comment: ""
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+- input: SELECT id as user_id FROM users ORDER BY |
+ want:
+ - text: id
+ type: COLUMN
+ definition: catalog1.public.users | INT, NOT NULL
+ comment: ""
+ - text: name
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ - text: email
+ type: COLUMN
+ definition: catalog1.public.users | VARCHAR, NOT NULL
+ comment: ""
+ - text: user_id
+ type: COLUMN
+ definition: ""
+ comment: ""
+- input: SELECT * FROM users JOIN |
+ want:
+ - text: orders
+ type: TABLE
+ definition: catalog1.public.orders
+ comment: ""
+ priority: 0
+ - text: users
+ type: TABLE
+ definition: catalog1.public.users
+ comment: ""
+ priority: 0
+ - text: active_users
+ type: VIEW
+ definition: catalog1.public.active_users
+ comment: ""
+ priority: 0
+- input: '|'
+ want:
+ - text: ALTER
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: CREATE
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: DROP
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+ - text: INSERT
+ type: KEYWORD
+ definition: ""
+ comment: ""
+ priority: 0
+- input: SEL|
+ want:
+ - text: SELECT
+ type: KEYWORD
+ definition: ""
+ comment: ""
diff --git a/backend/server/ultimate.go b/backend/server/ultimate.go
index 15c5822ee4..eb5856d1d3 100644
--- a/backend/server/ultimate.go
+++ b/backend/server/ultimate.go
@@ -39,6 +39,7 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/parser/snowflake"
_ "github.com/bytebase/bytebase/backend/plugin/parser/standard"
_ "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
+ _ "github.com/bytebase/bytebase/backend/plugin/parser/trino"
_ "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
// Advisors.