The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Improve SQL Editor auto completion for column names (#48734)
Joshen Lim558bee9ebf53
diff --git a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.tsindex d398f6d010b..bd0eb330bbb 100644--- a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts@@ -9,10 +9,14 @@ import { addAPIMock } from '@/tests/lib/msw'import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'vi.mock('@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider', () => ({- default: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({ __pgInfoRef: pgInfoRef })),+ getPgsqlCompletionProvider: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({+ __pgInfoRef: pgInfoRef,+ })),}))vi.mock('@/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider', () => ({- default: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({ __pgInfoRef: pgInfoRef })),+ getPgsqlSignatureHelpProvider: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({+ __pgInfoRef: pgInfoRef,+ })),}))describe('acquireSharedRegistration', () => {@@ -94,9 +98,10 @@ describe('useAddDefinitions', () => {}) as anyit('keeps the registered provider reading fresh data after the registering editor unmounts, as long as a sibling editor is still active', async () => {- const getPgsqlCompletionProvider = (- await import('@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider')- ).default as unknown as ReturnType<typeof vi.fn>+ const { getPgsqlCompletionProvider } =+ (await import('@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider')) as unknown as {+ getPgsqlCompletionProvider: ReturnType<typeof vi.fn>+ }let keywordWords = ['select']setupSqlEditorMocks()diff --git a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.tsindex 8e903636956..b6c9546786a 100644--- a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts+++ b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts@@ -2,10 +2,11 @@ import { Monaco } from '@monaco-editor/react'import { useQueryClient } from '@tanstack/react-query'import { LOCAL_STORAGE_KEYS } from 'common'import type { IDisposable } from 'monaco-editor'-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'-import getPgsqlCompletionProvider from '@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider'-import getPgsqlSignatureHelpProvider from '@/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider'+import { getPgsqlCompletionProvider } from '@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider'+import { getPgsqlSignatureHelpProvider } from '@/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider'+import type { PgInfo } from '@/components/ui/CodeEditor/Providers/Providers.types'import { useDatabaseFunctionsQuery } from '@/data/database-functions/database-functions-query'import { databaseKeys } from '@/data/database/keys'import { useKeywordsQuery } from '@/data/database/keywords-query'@@ -95,6 +96,8 @@ export const useAddDefinitions = ({ enabled: enabled && intellisenseEnabled })+ const pgInfoRef = useRef<PgInfo | null>(null)+const filteredSchemas = useSchemasFilteredForHighAvailability(schemas)const isPgInfoReady =@@ -105,6 +108,15 @@ export const useAddDefinitions = (isKeywordsSuccess &&isFunctionsSuccess+ if (isPgInfoReady && tableColumns && keywords && functions) {+ pgInfoRef.current = {+ tableColumns,+ schemas: filteredSchemas,+ keywords,+ functions,+ }+ }+// Keeps `sharedPgInfoRef` current for the registered pgsql completion/signature-help// providers. Runs in an effect — not render — so only committed tree state writes the// shared, module-level ref; mutating it directly during render risked a discarded ordiff --git a/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.test.ts b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.test.tsnew file mode 100644index 00000000000..d51dc961a52--- /dev/null+++ b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.test.ts@@ -0,0 +1,368 @@+import type { Monaco } from '@monaco-editor/react'+import type { editor, languages } from 'monaco-editor'+import { describe, expect, it } from 'vitest'++import { getPgsqlCompletionProvider } from './PgSQLCompletionProvider'+import type { PgInfo } from './Providers.types'++// A minimal stand-in for the parts of `Monaco` this provider actually reads.+const monaco = {+ languages: {+ CompletionItemKind: {+ Keyword: 1,+ Class: 2,+ Interface: 3,+ Field: 4,+ Function: 5,+ Property: 6,+ },+ },+} as unknown as Monaco++function createModel(sql: string): editor.ITextModel {+ return {+ getValue: () => sql,+ getOffsetAt: () => sql.length,+ getLineContent: () => sql,+ getWordUntilPosition: () => ({+ word: '',+ startColumn: sql.length + 1,+ endColumn: sql.length + 1,+ }),+ } as unknown as editor.ITextModel+}++// Simulates the cursor sitting mid-identifier between an already-present pair of double quotes,+// e.g. `where "OrderD|"` (the closing quote auto-closed by the editor when `"` was typed).+function createQuotedIdentModel(line: string, word: string): editor.ITextModel {+ const wordStartColumn = line.indexOf(`"${word}`) + 2+ const wordEndColumn = wordStartColumn + word.length++ return {+ getValue: () => line,+ getOffsetAt: () => wordEndColumn - 1,+ getLineContent: () => line,+ getWordUntilPosition: () => ({+ word,+ startColumn: wordStartColumn,+ endColumn: wordEndColumn,+ }),+ } as unknown as editor.ITextModel+}++function createQuotedIdentPosition(line: string, word: string): ProvideCompletionItemsParams[1] {+ const wordEndColumn = line.indexOf(`"${word}`) + 2 + word.length+ return { column: wordEndColumn, lineNumber: 1 } as unknown as ProvideCompletionItemsParams[1]+}++type ProvideCompletionItemsParams = Parameters<+ languages.CompletionItemProvider['provideCompletionItems']+>++function createPosition(sql: string): ProvideCompletionItemsParams[1] {+ // Monaco columns are 1-indexed; column = length + 1 places the cursor at the end.+ return { column: sql.length + 1, lineNumber: 1 } as unknown as ProvideCompletionItemsParams[1]+}++// Minimal fixtures — only the fields this provider reads, cast to the real (much larger) zod types.+function createPgInfoRef(): { current: PgInfo } {+ return {+ current: {+ keywords: ['abort', 'absent', 'absolute'],+ schemas: [{ name: 'public' }] as unknown as PgInfo['schemas'],+ functions: [+ { name: '_crypto_aead_det_decrypt', return_type: 'bytea' },+ ] as unknown as PgInfo['functions'],+ tableColumns: [+ {+ schemaname: 'public',+ tablename: 'colors',+ quoted_name: 'colors',+ is_table: true,+ columns: [+ { attname: 'id', data_type: 'bigint' },+ { attname: 'hex', data_type: 'text' },+ ],+ },+ {+ schemaname: 'public',+ tablename: 'shapes',+ quoted_name: 'shapes',+ is_table: true,+ columns: [{ attname: 'sides', data_type: 'smallint' }],+ },+ ],+ },+ }+}++function getSuggestions(pgInfoRef: { current: PgInfo }, sql: string): languages.CompletionItem[] {+ return provideSuggestions(pgInfoRef, sql, ' ')+}++function getDotSuggestions(+ pgInfoRef: { current: PgInfo },+ sql: string+): languages.CompletionItem[] {+ return provideSuggestions(pgInfoRef, sql, '.')+}++function provideSuggestions(+ pgInfoRef: { current: PgInfo },+ sql: string,+ triggerCharacter: string+): languages.CompletionItem[] {+ const provider = getPgsqlCompletionProvider(monaco, pgInfoRef)+ const context = { triggerCharacter } as unknown as ProvideCompletionItemsParams[2]+ const token = {} as ProvideCompletionItemsParams[3]++ const result = provider.provideCompletionItems(+ createModel(sql),+ createPosition(sql),+ context,+ token+ ) as languages.CompletionList++ return result.suggestions+}++describe('getPgsqlCompletionProvider - default scenario', () => {+ it('suggests only the FROM-clause table columns, ranked above keywords/functions', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getSuggestions(pgInfoRef, 'select * from colors where ')++ const columnSuggestions = suggestions.filter(+ (s) => s.kind === monaco.languages.CompletionItemKind.Field+ )+ expect(columnSuggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])++ // Every in-scope column must be ranked (sortText) ahead of keywords/functions+ columnSuggestions.forEach((s) => expect(s.sortText).toMatch(/^0_/))+ const nonColumnSuggestions = suggestions.filter(+ (s) => s.kind !== monaco.languages.CompletionItemKind.Field+ )+ nonColumnSuggestions.forEach((s) => expect(s.sortText).toBeUndefined())+ })++ it('falls back to every table column when no FROM clause is resolved yet', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getSuggestions(pgInfoRef, 'select ')++ const columnSuggestions = suggestions.filter(+ (s) => s.kind === monaco.languages.CompletionItemKind.Field+ )+ expect(columnSuggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id', 'sides'])+ columnSuggestions.forEach((s) => expect(s.sortText).toBeUndefined())+ })++ it('narrows columns per-table across a join', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getSuggestions(+ pgInfoRef,+ 'select * from colors c join shapes s on s.id = c.id where '+ )++ const columnSuggestions = suggestions.filter(+ (s) => s.kind === monaco.languages.CompletionItemKind.Field+ )+ expect(columnSuggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id', 'sides'])+ })++ it('scopes to a single alias when the statement ends with `alias.`', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getSuggestions(+ pgInfoRef,+ 'select * from colors c join shapes s on s.id = c.id where c.'+ )++ const columnSuggestions = suggestions.filter(+ (s) => s.kind === monaco.languages.CompletionItemKind.Field+ )+ expect(columnSuggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])+ })+})++describe('getPgsqlCompletionProvider - dot scenario', () => {+ it('scopes to a table alias in a single-table query', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getDotSuggestions(pgInfoRef, 'select * from colors c where c.')+ expect(suggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])+ })++ it('scopes to the aliased table only, not every table joined in', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getDotSuggestions(+ pgInfoRef,+ 'select * from colors c join shapes s on s.id = c.id where c.'+ )+ expect(suggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])+ })++ it('still resolves a plain (un-aliased) table name', () => {+ const pgInfoRef = createPgInfoRef()+ const suggestions = getDotSuggestions(+ pgInfoRef,+ 'select * from colors join shapes s on s.id = colors.id where colors.'+ )+ expect(suggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])+ })++ it('resolves an alias when there is no `public` schema at all', () => {+ const pgInfoRef: { current: PgInfo } = {+ current: {+ keywords: [],+ schemas: [{ name: 'app' }] as unknown as PgInfo['schemas'],+ functions: [] as unknown as PgInfo['functions'],+ tableColumns: [+ {+ schemaname: 'app',+ tablename: 'colors',+ quoted_name: 'colors',+ is_table: true,+ columns: [+ { attname: 'id', data_type: 'bigint' },+ { attname: 'hex', data_type: 'text' },+ ],+ },+ ],+ },+ }+ const suggestions = getDotSuggestions(pgInfoRef, 'select * from app.colors c where c.')+ expect(suggestions.map((s) => s.label).sort()).toStrictEqual(['hex', 'id'])+ })+})++describe('getPgsqlCompletionProvider - quoted identifiers', () => {+ function createQuotedPgInfoRef(): { current: PgInfo } {+ return {+ current: {+ keywords: [],+ schemas: [{ name: 'public' }] as unknown as PgInfo['schemas'],+ functions: [] as unknown as PgInfo['functions'],+ tableColumns: [+ {+ schemaname: 'public',+ tablename: 'test_orders',+ quoted_name: 'test_orders',+ is_table: true,+ columns: [+ { attname: 'OrderDate', data_type: 'date' },+ { attname: 'id', data_type: 'bigint' },+ ],+ },+ ],+ },+ }+ }++ it('replaces the whole existing quote pair instead of doubling up quotes on a mixed-case column', () => {+ // Regression test for: typing `where "OrderD` with the editor auto-closing the quote to+ // `where "OrderD|"`, then accepting the `OrderDate` suggestion produced `""OrderDate""`.+ const pgInfoRef = createQuotedPgInfoRef()+ const line = 'select * from test_orders where "OrderDate"'+ const word = 'OrderDate'++ const provider = getPgsqlCompletionProvider(monaco, pgInfoRef)+ const context = { triggerCharacter: undefined } as unknown as ProvideCompletionItemsParams[2]+ const token = {} as ProvideCompletionItemsParams[3]++ const result = provider.provideCompletionItems(+ createQuotedIdentModel(line, word),+ createQuotedIdentPosition(line, word),+ context,+ token+ ) as languages.CompletionList++ const suggestion = result.suggestions.find((s) => s.label === 'OrderDate')+ expect(suggestion?.insertText).toBe('"OrderDate"')++ // The range must swallow both surrounding quotes, otherwise the quoted insertText lands+ // inside the pre-existing, untouched quote pair and doubles them up.+ const quoteStart = line.indexOf('"')+ const quoteEnd = line.indexOf('"', quoteStart + 1)+ const range = suggestion?.range as { startColumn: number; endColumn: number }+ expect(range.startColumn).toBe(quoteStart + 1)+ expect(range.endColumn).toBe(quoteEnd + 2)+ })++ it('sets filterText with the leading quote so Monaco does not filter out every suggestion while typing inside an auto-closed quote pair', () => {+ // Regression test for: with the range widened to swallow the opening quote (above), Monaco+ // fuzzy-matches the typed prefix (e.g. `"OrderD`) against each item's filterText/label. A plain+ // label like `OrderDate` has no leading quote to match, so every suggestion got filtered out —+ // the widget showed no suggestions at all, even on an explicit Ctrl+Space re-invoke.+ const pgInfoRef = createQuotedPgInfoRef()+ // Only `OrderD` has been typed so far; the closing quote is auto-closed immediately after it.+ const line = 'select * from test_orders where "OrderD"'+ const word = 'OrderD'++ const provider = getPgsqlCompletionProvider(monaco, pgInfoRef)+ const context = { triggerCharacter: undefined } as unknown as ProvideCompletionItemsParams[2]+ const token = {} as ProvideCompletionItemsParams[3]++ const result = provider.provideCompletionItems(+ createQuotedIdentModel(line, word),+ createQuotedIdentPosition(line, word),+ context,+ token+ ) as languages.CompletionList++ const suggestion = result.suggestions.find((s) => s.label === 'OrderDate')+ expect(suggestion?.filterText).toBe('"OrderDate')+ })++ it('replaces only the pre-existing opening quote instead of doubling it up when the closing quote has been deleted', () => {+ // Regression test for: type `"OrderD` (auto-closed to `"OrderD|"`), delete the closing quote+ // (leaving `"OrderD` with no closing quote at all), then accept the `OrderDate` suggestion —+ // previously produced `""OrderDate` because `isQuoted` required both quotes to be present, so+ // the range left the existing opening quote untouched while the quoted insertText added another.+ const pgInfoRef = createQuotedPgInfoRef()+ const line = 'select * from test_orders where "OrderD'+ const word = 'OrderD'++ const provider = getPgsqlCompletionProvider(monaco, pgInfoRef)+ const context = { triggerCharacter: undefined } as unknown as ProvideCompletionItemsParams[2]+ const token = {} as ProvideCompletionItemsParams[3]++ const result = provider.provideCompletionItems(+ createQuotedIdentModel(line, word),+ createQuotedIdentPosition(line, word),+ context,+ token+ ) as languages.CompletionList++ const suggestion = result.suggestions.find((s) => s.label === 'OrderDate')+ expect(suggestion?.insertText).toBe('"OrderDate"')+ expect(suggestion?.filterText).toBe('"OrderDate')++ // Only the opening quote gets swallowed — there's no closing quote to swallow, so the end+ // boundary stays at the word's own end (the cursor position).+ const quoteStart = line.indexOf('"')+ const range = suggestion?.range as { startColumn: number; endColumn: number }+ expect(range.startColumn).toBe(quoteStart + 1)+ expect(range.endColumn).toBe(line.length + 1)+ })++ it('still quotes an all-lowercase column when the closing quote is missing', () => {+ // formatInsertText only force-quotes on `isQuoted`, since a mixed-case column already forces+ // quoting via its own `hasUpperCase` check regardless of `isQuoted`. An all-lowercase column+ // has no such fallback, so this exercises `isQuoted` being detected from the opening quote alone.+ const pgInfoRef = createQuotedPgInfoRef()+ pgInfoRef.current.tableColumns[0].columns.push({ attname: 'orderdate', data_type: 'date' })+ const line = 'select * from test_orders where "orderd'+ const word = 'orderd'++ const provider = getPgsqlCompletionProvider(monaco, pgInfoRef)+ const context = { triggerCharacter: undefined } as unknown as ProvideCompletionItemsParams[2]+ const token = {} as ProvideCompletionItemsParams[3]++ const result = provider.provideCompletionItems(+ createQuotedIdentModel(line, word),+ createQuotedIdentPosition(line, word),+ context,+ token+ ) as languages.CompletionList++ const suggestion = result.suggestions.find((s) => s.label === 'orderdate')+ expect(suggestion?.insertText).toBe('"orderdate"')+ })+})diff --git a/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.ts b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.tsindex d8b9d6334a9..eab3eacb94a 100644--- a/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.ts+++ b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.ts@@ -1,27 +1,59 @@+import type { Monaco } from '@monaco-editor/react'+import type { editor, languages, Position } from 'monaco-editor'import type { RefObject } from 'react'import BackwardIterator from './BackwardIterator'-import type { DatabaseFunction } from '@/data/database-functions/database-functions-query'+import {+ filterTablesByReferences,+ getFromClauseTables,+ getStatementAtOffset,+ parseTrailingDotIdent,+ resolveTablesForIdent,+} from './PgSQLCompletionProvider.utils'+import type { PgInfo } from './Providers.types'+import type { SavedDatabaseFunction } from '@/data/database-functions/database-functions-query'import type { Schema } from '@/data/database/schemas-query'import type { TableColumn } from '@/data/database/table-columns-query'-// [Joshen] Needs to be fixed+type TableColumnField = {+ attname: string+ data_type: string+}++type QuotableIdent = {+ isQuoted: boolean+ name: string+}++const EMPTY_IDENT: QuotableIdent = { isQuoted: false, name: '' }-export default function getPgsqlCompletionProvider(monaco: any, pgInfoRef: RefObject<any>) {+export function getPgsqlCompletionProvider(+ monaco: Monaco,+ pgInfoRef: RefObject<PgInfo | null>+): languages.CompletionItemProvider {return {triggerCharacters: [' ', '.', '"'],- provideCompletionItems: function (model: any, position: any, context: any) {+ provideCompletionItems: function (+ model: editor.ITextModel,+ position: Position,+ context: languages.CompletionContext+ ) {try {+ const pgInfo = pgInfoRef.current+ if (!pgInfo) return { suggestions: [] }+// position.column should minus 2 as it returns 2 for first char// position.lineNumber should minus 1- let iterator = new BackwardIterator(model, position.column - 2, position.lineNumber - 1)+ const iterator = new BackwardIterator(model, position.column - 2, position.lineNumber - 1)+ const { range, isQuoted } = getReplacementRange(model, position)+ const statement = getStatementAtOffset(model.getValue(), model.getOffsetAt(position))if (context.triggerCharacter === '"') {- return startingQuoteScenarioSuggestions(monaco, pgInfoRef, iterator)+ return startingQuoteScenarioSuggestions(monaco, pgInfo, iterator, range, isQuoted)} else if (context.triggerCharacter === '.') {- return dotScenarioSuggestions(monaco, pgInfoRef, iterator)+ return dotScenarioSuggestions(monaco, pgInfo, iterator, range, statement, isQuoted)} else {- return defaultScenarioSuggestions(monaco, pgInfoRef)+ return defaultScenarioSuggestions(monaco, pgInfo, statement, range, isQuoted)}} catch (_) {// any error, returns empty suggestion@@ -31,10 +63,49 @@ export default function getPgsqlCompletionProvider(monaco: any, pgInfoRef: RefOb}}-function startingQuoteScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>, iterator: any) {- const items: any[] = []+// Monaco requires a range on every completion item; when one isn't supplied it falls back to+// replacing the current word anyway, so we compute that explicitly rather than leave it implicit.+//+// `"` is a word separator for Monaco, so `getWordUntilPosition` never includes surrounding double+// quotes in the word it finds. When the identifier being completed already sits next to one —+// typed by hand, auto-closed by the editor as you type the opening quote, or with the closing+// quote since deleted (e.g. `"OrderD` at end of line, no closing quote at all) — we expand the+// range to swallow whichever quote(s) are actually there and flag `isQuoted` so callers always+// emit fully-quoted insertText. Each side is checked independently: swallowing only the side that+// has a quote (and leaving the other side's boundary untouched when there's nothing to swallow)+// is what stops a quoted insertText from landing next to an untouched pre-existing quote and+// doubling it up.+function getReplacementRange(+ model: editor.ITextModel,+ position: Position+): { range: languages.CompletionItem['range']; isQuoted: boolean } {+ const word = model.getWordUntilPosition(position)+ const line = model.getLineContent(position.lineNumber)+ const hasLeadingQuote = line.charAt(word.startColumn - 2) === '"'+ const hasTrailingQuote = line.charAt(word.endColumn - 1) === '"'+ const isQuoted = hasLeadingQuote || hasTrailingQuote++ return {+ range: {+ startLineNumber: position.lineNumber,+ endLineNumber: position.lineNumber,+ startColumn: hasLeadingQuote ? word.startColumn - 1 : word.startColumn,+ endColumn: hasTrailingQuote ? word.endColumn + 1 : word.endColumn,+ },+ isQuoted,+ }+}++function startingQuoteScenarioSuggestions(+ monaco: Monaco,+ pgInfo: PgInfo,+ iterator: BackwardIterator,+ range: languages.CompletionItem['range'],+ isQuoted: boolean+) {+ const items: languages.CompletionItem[] = []- let startingQuotedIdent = iterator.isFowardDQuote()+ const startingQuotedIdent = iterator.isFowardDQuote()if (!startingQuotedIdent) return { suggestions: items }iterator.next() // get passed the starting quote@@ -46,7 +117,7 @@ function startingQuoteScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>isQuotedIdent = trueident = fixQuotedIdent(ident)}- let table = pgInfoRef.current.tableColumns.find((tbl: TableColumn) => {+ const table = pgInfo.tableColumns.find((tbl: TableColumn) => {return ((isQuotedIdent && tbl.tablename === ident) ||(!isQuotedIdent && tbl.tablename.toLocaleLowerCase() == ident.toLocaleLowerCase())@@ -54,21 +125,26 @@ function startingQuoteScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>})if (!table) return { suggestions: items }- table.columns.forEach((field: any) => {+ table.columns.forEach((field: TableColumnField | null) => {+ if (!field) returnitems.push({label: field.attname,kind: monaco.languages.CompletionItemKind.Property,detail: field.data_type,- insertText: field.attname,+ insertText: formatInsertText(field.attname, isQuoted),+ filterText: formatFilterText(field.attname, isQuoted),+ range,})})} else {// probably a table - list the tables- pgInfoRef.current.tableColumns.forEach((table: TableColumn) => {+ pgInfo.tableColumns.forEach((table: TableColumn) => {items.push({label: table.tablename,kind: monaco.languages.CompletionItemKind.Class,- insertText: table.tablename,+ insertText: formatInsertText(table.tablename, isQuoted),+ filterText: formatFilterText(table.tablename, isQuoted),+ range,})})}@@ -76,58 +152,99 @@ function startingQuoteScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>return { suggestions: items }}-function dotScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>, iterator: any) {- const items: any[] = []+function dotScenarioSuggestions(+ monaco: Monaco,+ pgInfo: PgInfo,+ iterator: BackwardIterator,+ range: languages.CompletionItem['range'],+ statement: string,+ isQuoted: boolean+) {+ const items: languages.CompletionItem[] = []- let idents = readIdents(iterator, 3)+ const idents = readIdents(iterator, 3)let pos = 0- let schema = pgInfoRef.current.schemas.find((sch: Schema) => {- const _ident = idents && idents.length > pos ? idents[pos] : {}+ let schema = pgInfo.schemas.find((sch: Schema) => {+ const _ident = idents.length > pos ? idents[pos] : EMPTY_IDENTreturn ((_ident.isQuoted && sch.name === _ident.name) ||- (!_ident.isQuoted && sch.name?.toLocaleLowerCase() == _ident.name?.toLocaleLowerCase())+ (!_ident.isQuoted && sch.name.toLocaleLowerCase() == _ident.name.toLocaleLowerCase()))})+ // A schema can't be part of an alias (`myschema.c.id` isn't valid SQL), so only+ // attempt alias resolution when nothing before this ident was consumed as a schema.+ // This must happen before the `public`-schema fallback/early-return below, so `c.`+ // resolves via the FROM/JOIN alias even in a database with no `public` schema.if (!schema) {- schema = pgInfoRef.current.schemas.find((sch: Schema) => {- return sch.name == 'public'- })+ const tableIdent = idents.length > pos ? idents[pos] : EMPTY_IDENT+ const aliasedTables = resolveTablesForIdent(+ pgInfo.tableColumns,+ getFromClauseTables(statement),+ tableIdent+ )+ if (aliasedTables.length > 0) {+ aliasedTables[0].columns.forEach((field: TableColumnField | null) => {+ if (!field) return+ items.push({+ label: field.attname,+ kind: monaco.languages.CompletionItemKind.Property,+ detail: field.data_type,+ insertText: formatInsertText(field.attname, isQuoted),+ filterText: formatFilterText(field.attname, isQuoted),+ range,+ })+ })+ return { suggestions: items }+ }} else {pos++}+ if (!schema) {+ schema = pgInfo.schemas.find((sch: Schema) => sch.name == 'public')+ }++ // No custom schema and no `public` schema either — nothing sensible to suggest.+ if (!schema) return { suggestions: items }+if (idents.length == pos) {- pgInfoRef.current.tableColumns.forEach((tbl: TableColumn) => {+ pgInfo.tableColumns.forEach((tbl: TableColumn) => {if (tbl.schemaname != schema.name) {return}items.push({label: tbl.tablename,kind: monaco.languages.CompletionItemKind.Class,- detail: tbl.schemaname !== 'public' ? tbl.schemaname : null,- insertText: formatInsertText(tbl.tablename),+ detail: tbl.schemaname !== 'public' ? tbl.schemaname : undefined,+ insertText: formatInsertText(tbl.tablename, isQuoted),+ filterText: formatFilterText(tbl.tablename, isQuoted),+ range,})})return { suggestions: items }}- let table = pgInfoRef.current.tableColumns.find((tbl: TableColumn) => {- const _ident = idents && idents.length > pos ? idents[pos] : {}- return (- (tbl.schemaname == schema.name && _ident.isQuoted && tbl.tablename === _ident.name) ||- (!_ident.isQuoted && tbl.tablename?.toLocaleLowerCase() == _ident.name?.toLocaleLowerCase())- )+ const tableIdent = idents.length > pos ? idents[pos] : EMPTY_IDENT++ const table = pgInfo.tableColumns.find((tbl: TableColumn) => {+ if (tbl.schemaname !== schema.name) return false+ return tableIdent.isQuoted+ ? tbl.tablename === tableIdent.name+ : tbl.tablename.toLocaleLowerCase() == tableIdent.name.toLocaleLowerCase()})if (table) {- table.columns.forEach((field: any) => {+ table.columns.forEach((field: TableColumnField | null) => {+ if (!field) returnitems.push({label: field.attname,kind: monaco.languages.CompletionItemKind.Property,detail: field.data_type,- insertText: formatInsertText(field.attname),+ insertText: formatInsertText(field.attname, isQuoted),+ filterText: formatFilterText(field.attname, isQuoted),+ range,})})}@@ -135,77 +252,115 @@ function dotScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>, iteratorreturn { suggestions: items }}-function defaultScenarioSuggestions(monaco: any, pgInfoRef: RefObject<any>) {- const items: any = []+function defaultScenarioSuggestions(+ monaco: Monaco,+ pgInfo: PgInfo,+ statement: string,+ range: languages.CompletionItem['range'],+ isQuoted: boolean+) {+ const items: languages.CompletionItem[] = []- if (pgInfoRef.current.keywords?.length > 0) {- pgInfoRef.current.keywords.forEach((x: string) => {- items.push({- label: x,- kind: monaco.languages.CompletionItemKind.Keyword,- insertText: x,- })+ pgInfo.keywords.forEach((x: string) => {+ items.push({+ label: x,+ kind: monaco.languages.CompletionItemKind.Keyword,+ insertText: x,+ range,})- }+ })- if (pgInfoRef.current.schemas?.length > 0) {- pgInfoRef.current.schemas.forEach((x: Schema) => {- items.push({- label: x.name,- kind: monaco.languages.CompletionItemKind.Keyword,- insertText: x.name,- })+ pgInfo.schemas.forEach((x: Schema) => {+ items.push({+ label: x.name,+ kind: monaco.languages.CompletionItemKind.Keyword,+ insertText: x.name,+ range,})- }+ })- if (pgInfoRef.current.tableColumns?.length > 0) {- pgInfoRef.current.tableColumns.forEach((x: TableColumn) => {- const insertText = x.schemaname == 'public' ? x.tablename : x.schemaname + '.' + x.tablename- items.push({- label: x.tablename,- detail: x.schemaname !== 'public' ? x.schemaname : null,- kind: x.is_table- ? monaco.languages.CompletionItemKind.Class- : monaco.languages.CompletionItemKind.Interface,- insertText: formatInsertText(insertText),- })- x.columns.forEach((field: any) => {- if (!field) return+ const allTableColumns = pgInfo.tableColumns- let foundItem = items.find(- (i: any) =>- i.label === field?.attname &&- i.kind === monaco.languages.CompletionItemKind.Field &&- i.detail === field?.data_type- )- if (foundItem) {- foundItem.tables.push(x.tablename)- foundItem.tables.sort()- foundItem.documentation = foundItem.tables.join(', ')- } else {- items.push({- label: field.attname,- kind: monaco.languages.CompletionItemKind.Field,- detail: field.data_type,- documentation: x.tablename,- tables: [x.tablename],- insertText: formatInsertText(field.attname),- })+ allTableColumns.forEach((x: TableColumn) => {+ const insertText = x.schemaname == 'public' ? x.tablename : x.schemaname + '.' + x.tablename+ items.push({+ label: x.tablename,+ detail: x.schemaname !== 'public' ? x.schemaname : undefined,+ kind: x.is_table+ ? monaco.languages.CompletionItemKind.Class+ : monaco.languages.CompletionItemKind.Interface,+ insertText: formatInsertText(insertText, isQuoted),+ filterText: formatFilterText(x.tablename, isQuoted),+ range,+ })+ })++ // Narrow column suggestions down to the table(s) referenced in the current+ // statement's FROM/JOIN clauses (e.g. `select * from colors where |` should+ // only suggest colors' columns). Falls back to every table's columns when+ // none can be resolved, e.g. before a FROM clause has been typed.+ const fromClauseTables = getFromClauseTables(statement)++ // If the statement ends with `alias.` (Monaco can re-request suggestions this way+ // right after the dot, without going through the dot-trigger scenario), scope+ // strictly to that one alias/table instead of every FROM/JOIN table — otherwise+ // e.g. `c.` after `orders o join customers c` would suggest orders' columns too.+ const trailingDotIdent = parseTrailingDotIdent(statement)+ const aliasScopedTableColumns = trailingDotIdent+ ? resolveTablesForIdent(allTableColumns, fromClauseTables, trailingDotIdent)+ : []++ const inScopeTableColumns =+ aliasScopedTableColumns.length > 0+ ? aliasScopedTableColumns+ : filterTablesByReferences(allTableColumns, fromClauseTables)+ const hasResolvedFromTables = inScopeTableColumns.length > 0+ const relevantTableColumns = hasResolvedFromTables ? inScopeTableColumns : allTableColumns++ // Monaco sorts suggestions by sortText (falling back to label) when nothing has been typed+ // yet, so without this, columns get buried alphabetically amongst keywords/functions. Rank+ // them first once we know which table(s) are in scope; leave sorting untouched otherwise+ // (e.g. before FROM is typed). Columns sharing a name+type across in-scope tables are merged+ // into one suggestion, tracked here rather than on the item itself so the item stays a plain+ // Monaco CompletionItem.+ const columnItemsByKey = new Map<string, { item: languages.CompletionItem; tables: string[] }>()++ relevantTableColumns.forEach((x: TableColumn) => {+ x.columns.forEach((field: TableColumnField | null) => {+ if (!field) return++ const key = `${field.attname}::${field.data_type}`+ const existing = columnItemsByKey.get(key)+ if (existing) {+ existing.tables.push(x.tablename)+ existing.tables.sort()+ existing.item.documentation = existing.tables.join(', ')+ } else {+ const item: languages.CompletionItem = {+ label: field.attname,+ kind: monaco.languages.CompletionItemKind.Field,+ detail: field.data_type,+ documentation: x.tablename,+ insertText: formatInsertText(field.attname, isQuoted),+ filterText: formatFilterText(field.attname, isQuoted),+ range,+ sortText: hasResolvedFromTables ? `0_${field.attname}` : undefined,}- })+ columnItemsByKey.set(key, { item, tables: [x.tablename] })+ items.push(item)+ }})- }+ })- if (pgInfoRef.current.functions?.length > 0) {- pgInfoRef.current.functions.forEach((x: DatabaseFunction) => {- items.push({- label: x.name,- kind: monaco.languages.CompletionItemKind.Function,- detail: x.return_type,- insertText: x.name,- })+ pgInfo.functions.forEach((x: SavedDatabaseFunction) => {+ items.push({+ label: x.name,+ kind: monaco.languages.CompletionItemKind.Function,+ detail: x.return_type,+ insertText: x.name,+ range,})- }+ })return { suggestions: items }}@@ -214,18 +369,28 @@ function fixQuotedIdent(str: string) {return str.replace(/^\"/, '').replace(/\"$/, '').replace(/\"\"/, '"')}-function readIdents(iterator: any, maxlvl: number) {+function readIdents(iterator: BackwardIterator, maxlvl: number): QuotableIdent[] {return iterator.readIdents(maxlvl).map((name: string) => {let isQuoted = falseif (name.match(/^\".*?\"$/)) {isQuoted = truename = fixQuotedIdent(name)}- return { isQuoted: isQuoted, name: name }+ return { isQuoted, name }})}-function formatInsertText(value: string) {+function formatInsertText(value: string, forceQuote = false) {const hasUpperCase = !(value == value.toLowerCase())- return hasUpperCase ? `"${value}"` : value+ return hasUpperCase || forceQuote ? `"${value}"` : value+}++// Monaco filters/scores suggestions by fuzzy-matching the label against the text between the+// completion item's range start and the cursor. When `isQuoted` is true that range start sits on+// the literal opening `"` (see getReplacementRange), so the typed prefix looks like `"OrderD` while+// a plain label like `OrderDate` has no quote to match — every suggestion gets filtered out, even+// on an explicit Ctrl+Space re-invoke. Mirroring the leading quote into `filterText` keeps it aligned+// with what's actually been typed.+function formatFilterText(value: string, isQuoted: boolean) {+ return isQuoted ? `"${value}` : value}diff --git a/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.test.ts b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.test.tsnew file mode 100644index 00000000000..80cb12de366--- /dev/null+++ b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.test.ts@@ -0,0 +1,257 @@+import { describe, expect, it } from 'vitest'++import {+ filterTablesByReferences,+ getFromClauseTables,+ getStatementAtOffset,+ parseTrailingDotIdent,+ resolveTablesForIdent,+} from './PgSQLCompletionProvider.utils'++describe('getFromClauseTables', () => {+ it('returns empty array when there is no FROM clause', () => {+ expect(getFromClauseTables('select 1')).toStrictEqual([])+ })++ it('parses a single table', () => {+ expect(getFromClauseTables('select * from colors where id = 1')).toStrictEqual([+ { name: 'colors', alias: undefined },+ ])+ })++ it('parses a table with an implicit alias (no AS)', () => {+ expect(getFromClauseTables('select * from colors c where c.id = 1')).toStrictEqual([+ { name: 'colors', alias: 'c' },+ ])+ })++ it('parses a table with an explicit AS alias', () => {+ expect(getFromClauseTables('select * from colors as c where c.id = 1')).toStrictEqual([+ { name: 'colors', alias: 'c' },+ ])+ })++ it('parses a schema-qualified table', () => {+ expect(getFromClauseTables('select * from public.colors where id = 1')).toStrictEqual([+ { schema: 'public', name: 'colors', alias: undefined },+ ])+ })++ it('parses a schema-qualified table with an alias', () => {+ expect(getFromClauseTables('select * from public.colors c where c.id = 1')).toStrictEqual([+ { schema: 'public', name: 'colors', alias: 'c' },+ ])+ })++ it('parses multiple comma-separated tables', () => {+ expect(+ getFromClauseTables('select * from colors, shapes where colors.id = shapes.id')+ ).toStrictEqual([+ { name: 'colors', alias: undefined },+ { name: 'shapes', alias: undefined },+ ])+ })++ it('parses quoted identifiers, unquoting the result', () => {+ expect(getFromClauseTables('select * from "Colors" "C" where "C".id = 1')).toStrictEqual([+ { name: 'Colors', alias: 'C' },+ ])+ })++ it('parses tables across inner/left/right/full/cross joins', () => {+ expect(+ getFromClauseTables(+ `select * from colors+ inner join a on a.id = colors.id+ left join b on b.id = colors.id+ left outer join c on c.id = colors.id+ right join d on d.id = colors.id+ full outer join e on e.id = colors.id+ cross join f`+ )+ ).toStrictEqual([+ { name: 'colors', alias: undefined },+ { name: 'a', alias: undefined },+ { name: 'b', alias: undefined },+ { name: 'c', alias: undefined },+ { name: 'd', alias: undefined },+ { name: 'e', alias: undefined },+ { name: 'f', alias: undefined },+ ])+ })++ it('parses a plain JOIN (no join-type keyword)', () => {+ expect(+ getFromClauseTables('select * from colors join shapes on shapes.color_id = colors.id')+ ).toStrictEqual([+ { name: 'colors', alias: undefined },+ { name: 'shapes', alias: undefined },+ ])+ })++ it('is case-insensitive for FROM/JOIN keywords', () => {+ expect(+ getFromClauseTables('SELECT * FROM Colors C INNER JOIN Shapes S ON S.id = C.id')+ ).toStrictEqual([+ { name: 'Colors', alias: 'C' },+ { name: 'Shapes', alias: 'S' },+ ])+ })++ it('skips a subquery table source instead of mis-parsing it', () => {+ expect(getFromClauseTables('select * from (select * from shapes) x')).toStrictEqual([])+ })++ it('still resolves real tables alongside a skipped subquery', () => {+ expect(getFromClauseTables('select * from colors, (select * from shapes) x')).toStrictEqual([+ { name: 'colors', alias: undefined },+ ])+ })++ it('skips a function table source instead of mis-parsing it', () => {+ expect(getFromClauseTables('select * from generate_series(1, 10) g')).toStrictEqual([])+ })++ it('stops the FROM clause at WHERE/GROUP BY/ORDER BY/LIMIT', () => {+ expect(+ getFromClauseTables('select * from colors group by id order by id limit 10')+ ).toStrictEqual([{ name: 'colors', alias: undefined }])+ })+})++describe('getStatementAtOffset', () => {+ it('returns the whole string when there is a single statement', () => {+ const sql = 'select * from colors where id = 1'+ expect(getStatementAtOffset(sql, 10)).toBe(sql)+ })++ it('returns only the statement containing the given offset', () => {+ const sql = 'select * from colors; select * from shapes where id = 1;'+ const offset = sql.indexOf('shapes')+ expect(getStatementAtOffset(sql, offset).trim()).toBe('select * from shapes where id = 1')+ })++ it('returns the first statement when the offset is before any semicolon', () => {+ const sql = 'select * from colors; select * from shapes;'+ const offset = sql.indexOf('colors')+ expect(getStatementAtOffset(sql, offset).trim()).toBe('select * from colors')+ })++ it('does not treat a semicolon inside a single-quoted string as a boundary', () => {+ const sql = "select * from colors where name = 'a;b' and id = 1"+ expect(getStatementAtOffset(sql, sql.length - 1)).toBe(sql)+ })++ it('does not treat a semicolon inside a double-quoted identifier as a boundary', () => {+ const sql = 'select * from "weird;table" where id = 1'+ expect(getStatementAtOffset(sql, sql.length - 1)).toBe(sql)+ })++ it('does not treat a semicolon inside a line comment as a boundary', () => {+ const sql = 'select * from colors -- comment; still comment\nwhere id = 1'+ expect(getStatementAtOffset(sql, sql.length - 1)).toBe(sql)+ })++ it('does not treat a semicolon inside a block comment as a boundary', () => {+ const sql = 'select * from colors /* comment; still comment */ where id = 1'+ expect(getStatementAtOffset(sql, sql.length - 1)).toBe(sql)+ })+})++describe('filterTablesByReferences', () => {+ const tables = [+ { schemaname: 'public', tablename: 'colors' },+ { schemaname: 'public', tablename: 'shapes' },+ { schemaname: 'internal', tablename: 'colors' },+ ]++ it('returns an empty array when there are no references', () => {+ expect(filterTablesByReferences(tables, [])).toStrictEqual([])+ })++ it('matches by table name only when no schema is specified', () => {+ expect(filterTablesByReferences(tables, [{ name: 'colors' }])).toStrictEqual([+ { schemaname: 'public', tablename: 'colors' },+ { schemaname: 'internal', tablename: 'colors' },+ ])+ })++ it('matches by schema and table name when a schema is specified', () => {+ expect(+ filterTablesByReferences(tables, [{ schema: 'internal', name: 'colors' }])+ ).toStrictEqual([{ schemaname: 'internal', tablename: 'colors' }])+ })++ it('is case-insensitive when matching names', () => {+ expect(filterTablesByReferences(tables, [{ schema: 'PUBLIC', name: 'COLORS' }])).toStrictEqual([+ { schemaname: 'public', tablename: 'colors' },+ ])+ })++ it('returns an empty array when no table matches', () => {+ expect(filterTablesByReferences(tables, [{ name: 'nonexistent' }])).toStrictEqual([])+ })+})++describe('parseTrailingDotIdent', () => {+ it('returns null when the text does not end with an identifier and a dot', () => {+ expect(parseTrailingDotIdent('select * from colors where ')).toBeNull()+ })++ it('extracts an unquoted identifier immediately before a trailing dot', () => {+ expect(parseTrailingDotIdent('select * from colors c where c.')).toStrictEqual({+ isQuoted: false,+ name: 'c',+ })+ })++ it('extracts and unquotes a quoted identifier before a trailing dot', () => {+ expect(parseTrailingDotIdent('select * from "Colors" "C" where "C".')).toStrictEqual({+ isQuoted: true,+ name: 'C',+ })+ })++ it('allows whitespace between the identifier and the dot', () => {+ expect(parseTrailingDotIdent('select * from colors c where c .')).toStrictEqual({+ isQuoted: false,+ name: 'c',+ })+ })+})++describe('resolveTablesForIdent', () => {+ const tables = [+ { schemaname: 'public', tablename: 'orders' },+ { schemaname: 'public', tablename: 'customers' },+ ]++ it('resolves an alias to its table, ignoring other referenced tables', () => {+ const refs = [+ { name: 'orders', alias: 'o' },+ { name: 'customers', alias: 'c' },+ ]+ expect(resolveTablesForIdent(tables, refs, { isQuoted: false, name: 'c' })).toStrictEqual([+ { schemaname: 'public', tablename: 'customers' },+ ])+ })++ it('resolves a plain table name when there is no alias', () => {+ const refs = [{ name: 'customers', alias: undefined }]+ expect(+ resolveTablesForIdent(tables, refs, { isQuoted: false, name: 'customers' })+ ).toStrictEqual([{ schemaname: 'public', tablename: 'customers' }])+ })++ it('does not fall back to the table name once it has an alias', () => {+ const refs = [{ name: 'customers', alias: 'c' }]+ expect(+ resolveTablesForIdent(tables, refs, { isQuoted: false, name: 'customers' })+ ).toStrictEqual([])+ })++ it('returns an empty array when the ident matches nothing', () => {+ const refs = [{ name: 'customers', alias: 'c' }]+ expect(resolveTablesForIdent(tables, refs, { isQuoted: false, name: 'x' })).toStrictEqual([])+ })+})diff --git a/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.ts b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.tsnew file mode 100644index 00000000000..21f4ed29ae9--- /dev/null+++ b/apps/studio/components/ui/CodeEditor/Providers/PgSQLCompletionProvider.utils.ts@@ -0,0 +1,238 @@+// Heuristic (non-AST) helpers used to scope column suggestions to the table(s)+// referenced by the SQL statement the cursor is currently in, e.g. so that+// `select * from colors where |` only suggests `colors`' columns.++export type SqlTableReference = {+ schema?: string+ name: string+ alias?: string+}++export type SqlIdent = {+ isQuoted: boolean+ name: string+}++const CLAUSE_STOP_KEYWORDS =+ 'where|group|order|having|limit|offset|union|intersect|except|join|inner|left|right|full|cross|lateral|natural|window|for|returning|set|on|using'++const JOIN_START = '(?:(?:inner|left|right|full|cross|lateral|natural)\\s+(?:outer\\s+)?)?join'++const IDENT = '(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)'++const TABLE_REF_PATTERN = new RegExp(+ `^(${IDENT})(?:\\s*\\.\\s*(${IDENT}))?(?:\\s+(?:as\\s+)?(${IDENT}))?$`,+ 'i'+)++function unquoteIdent(raw: string): string {+ const trimmed = raw.trim()+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {+ return trimmed.slice(1, -1).replace(/""/g, '"')+ }+ return trimmed+}++// Splits a comma-separated list of table references on top-level commas only+// (ignores commas nested inside parentheses, e.g. function-call table sources).+function splitTopLevelCommas(text: string): string[] {+ const parts: string[] = []+ let depth = 0+ let current = ''++ for (const char of text) {+ if (char === '(') depth+++ if (char === ')') depth--+ if (char === ',' && depth === 0) {+ parts.push(current)+ current = ''+ continue+ }+ current += char+ }+ parts.push(current)+ return parts+}++function parseTableRef(segment: string): SqlTableReference | null {+ const trimmed = segment.trim()+ if (!trimmed || trimmed.startsWith('(')) return null++ const match = trimmed.match(TABLE_REF_PATTERN)+ if (!match) return null++ const [, first, second, alias] = match+ if (second) {+ return {+ schema: unquoteIdent(first),+ name: unquoteIdent(second),+ alias: alias ? unquoteIdent(alias) : undefined,+ }+ }+ return { name: unquoteIdent(first), alias: alias ? unquoteIdent(alias) : undefined }+}++function parseTableRefList(segment: string): SqlTableReference[] {+ return splitTopLevelCommas(segment)+ .map(parseTableRef)+ .filter((ref): ref is SqlTableReference => ref !== null)+}++function matchClauseSegments(statement: string, startPattern: string): string[] {+ const pattern = new RegExp(+ `\\b${startPattern}\\b([\\s\\S]*?)(?=\\b(?:${CLAUSE_STOP_KEYWORDS})\\b|;|$)`,+ 'gi'+ )+ const segments: string[] = []+ let match: RegExpExecArray | null+ while ((match = pattern.exec(statement)) !== null) {+ segments.push(match[1])+ // avoid infinite loops on zero-length matches+ if (match[1].length === 0) pattern.lastIndex+++ }+ return segments+}++// Extracts the table (and join) references from the `FROM`/`JOIN` clauses of+// a single SQL statement. Best-effort: subquery table sources and function+// table sources are skipped rather than mis-parsed.+export function getFromClauseTables(statement: string): SqlTableReference[] {+ const refs: SqlTableReference[] = []++ for (const segment of matchClauseSegments(statement, 'from')) {+ refs.push(...parseTableRefList(segment))+ }+ for (const segment of matchClauseSegments(statement, JOIN_START)) {+ refs.push(...parseTableRefList(segment))+ }++ return refs+}++// Returns the SQL statement that contains `offset`, where statements are+// delimited by semicolons that are not inside a string literal or comment.+export function getStatementAtOffset(sql: string, offset: number): string {+ let start = 0+ let end = sql.length+ let inSingleQuote = false+ let inDoubleQuote = false+ let inLineComment = false+ let inBlockComment = false++ for (let i = 0; i < sql.length; i++) {+ const char = sql[i]+ const next = sql[i + 1]++ if (inLineComment) {+ if (char === '\n') inLineComment = false+ continue+ }+ if (inBlockComment) {+ if (char === '*' && next === '/') {+ inBlockComment = false+ i+++ }+ continue+ }+ if (inSingleQuote) {+ if (char === "'") {+ if (next === "'") {+ i+++ } else {+ inSingleQuote = false+ }+ }+ continue+ }+ if (inDoubleQuote) {+ if (char === '"') {+ if (next === '"') {+ i+++ } else {+ inDoubleQuote = false+ }+ }+ continue+ }++ if (char === "'") {+ inSingleQuote = true+ } else if (char === '"') {+ inDoubleQuote = true+ } else if (char === '-' && next === '-') {+ inLineComment = true+ i+++ } else if (char === '/' && next === '*') {+ inBlockComment = true+ i+++ } else if (char === ';') {+ if (i < offset) {+ start = i + 1+ } else {+ end = i+ break+ }+ }+ }++ return sql.slice(start, end)+}++// Filters a list of tables (or table-columns) down to just the ones referenced+// in `refs`, matching on table name (case-insensitive) and, when a ref+// specifies a schema, on schema too.+export function filterTablesByReferences<T extends { schemaname: string; tablename: string }>(+ tables: T[],+ refs: SqlTableReference[]+): T[] {+ if (refs.length === 0) return []++ return tables.filter((table) =>+ refs.some((ref) => {+ if (table.tablename.toLowerCase() !== ref.name.toLowerCase()) return false+ if (ref.schema) return table.schemaname.toLowerCase() === ref.schema.toLowerCase()+ return true+ })+ )+}++// Matches a trailing `ident.` (quoted or unquoted), capturing the identifier.+const TRAILING_DOT_IDENT_PATTERN = new RegExp(`(${IDENT})\\s*\\.\\s*$`)++// Detects an identifier immediately followed by a dot at the very end of the+// text (e.g. `... where c.`), so completion can be scoped to that specific+// alias/table rather than every table referenced in the statement.+export function parseTrailingDotIdent(text: string): SqlIdent | null {+ const match = text.match(TRAILING_DOT_IDENT_PATTERN)+ if (!match) return null++ const raw = match[1]+ return { isQuoted: raw.startsWith('"'), name: unquoteIdent(raw) }+}++// Resolves `ident` (typically the identifier typed right before a dot)+// against `refs`, matching on alias first and falling back to the table's own+// name for un-aliased references — so `c.` after `... customers c` (or+// `customers.` with no alias) both resolve to the `customers` table, but a+// join's other table doesn't leak in.+export function resolveTablesForIdent<T extends { schemaname: string; tablename: string }>(+ tables: T[],+ refs: SqlTableReference[],+ ident: SqlIdent+): T[] {+ const matchingRefs = refs.filter((ref) => {+ const candidate = ref.alias ?? ref.name+ return ident.isQuoted+ ? candidate === ident.name+ : candidate.toLocaleLowerCase() === ident.name.toLocaleLowerCase()+ })+ if (matchingRefs.length === 0) return []++ return tables.filter((table) =>+ matchingRefs.some((ref) => {+ if (table.tablename.toLowerCase() !== ref.name.toLowerCase()) return false+ if (ref.schema) return table.schemaname.toLowerCase() === ref.schema.toLowerCase()+ return true+ })+ )+}diff --git a/apps/studio/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider.ts b/apps/studio/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider.tsindex 9da570ddc35..1342bd6671b 100644--- a/apps/studio/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider.ts+++ b/apps/studio/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider.ts@@ -1,14 +1,20 @@-import { RefObject } from 'react'+import type { Monaco } from '@monaco-editor/react'+import type { editor, Position } from 'monaco-editor'+import type { RefObject } from 'react'import BackwardIterator from './BackwardIterator'-import type { DatabaseFunction } from '@/data/database-functions/database-functions-query'+import type { PgInfo } from './Providers.types'-// [Joshen] Needs to be fixed--export default function getPgsqlSignatureHelpProvider(_monaco: any, pgInfoRef: RefObject<any>) {+export function getPgsqlSignatureHelpProvider(+ _monaco: Monaco,+ pgInfoRef: RefObject<PgInfo | null>+) {return {signatureHelpTriggerCharacters: ['(', ','],- provideSignatureHelp: function (model: any, position: any) {+ provideSignatureHelp: function (model: editor.ITextModel, position: Position) {+ const pgInfo = pgInfoRef.current+ if (!pgInfo) return null+// position.column should minus 2 as it returns 2 for first char// position.lineNumber should minus 1const iterator = new BackwardIterator(model, position.column - 2, position.lineNumber - 1)@@ -19,7 +25,7 @@ export default function getPgsqlSignatureHelpProvider(_monaco: any, pgInfoRef: Rlet ident = iterator.readIdent()if (!ident || ident.match(/^\".*?\"$/)) return null- let fn = (pgInfoRef.current.functions as DatabaseFunction[]).find(+ let fn = pgInfo.functions.find((f) => f.name.toLocaleLowerCase() === ident.toLocaleLowerCase())if (!fn) return nulldiff --git a/apps/studio/components/ui/CodeEditor/Providers/Providers.types.ts b/apps/studio/components/ui/CodeEditor/Providers/Providers.types.tsnew file mode 100644index 00000000000..bbcbb557462--- /dev/null+++ b/apps/studio/components/ui/CodeEditor/Providers/Providers.types.ts@@ -0,0 +1,13 @@+import type { DatabaseFunctionsData } from '@/data/database-functions/database-functions-query'+import type { Schema } from '@/data/database/schemas-query'+import type { TableColumn } from '@/data/database/table-columns-query'++// Table/schema/keyword/function metadata for SQL IntelliSense, held in a ref (see+// useAddDefinitions.ts) so Monaco's completion/signature-help providers can read the latest+// value without re-registering on every fetch.+export type PgInfo = {+ keywords: string[]+ schemas: Schema[]+ functions: DatabaseFunctionsData+ tableColumns: TableColumn[]+}