Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: dynamic SQL keyword completion based on dialect (#5775)

Myles Scolnick74214b89a48d
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index faf3f3e0c2..f67f89da7d 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -1,7 +1,13 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import type {
+ CompletionContext,
+ CompletionResult,
+} from "@codemirror/autocomplete";
import { PostgreSQL } from "@codemirror/lang-sql";
+import { EditorState, type Extension } from "@codemirror/state";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { DataSourceConnection } from "@/core/datasets/data-source-connections";
import {
dataSourceConnectionsAtom,
setLatestEngineSelected,
@@ -9,16 +15,18 @@ import {
import { type ConnectionName, DUCKDB_ENGINE } from "@/core/datasets/engines";
import { datasetsAtom } from "@/core/datasets/state";
import type { DatasetsState } from "@/core/datasets/types";
-import type { DataSourceConnection } from "@/core/kernel/messages";
import { store } from "@/core/state/jotai";
import {
SQLCompletionStore,
SQLLanguageAdapter,
type SQLLanguageAdapterMetadata,
} from "../languages/sql";
+import { languageMetadataField } from "../metadata";
const adapter = new SQLLanguageAdapter();
+const TEST_ENGINE = "test_engine" as ConnectionName;
+
describe("SQLLanguageAdapter", () => {
describe("defaultMetadata", () => {
it("should be set", () => {
@@ -632,15 +640,13 @@ describe("tablesCompletionSource", () => {
latestEngineSelected: DUCKDB_ENGINE,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource).toBe(null);
});
it("should create schema with schema.table structure", () => {
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "duckdb",
display_name: "duckdb",
source: "duckdb",
@@ -712,16 +718,11 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- ["test_engine" as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: "test_engine" as ConnectionName,
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.defaultTable).toBeUndefined();
expect(completionSource?.dialect).toBe(undefined);
expect(completionSource?.schema).toMatchInlineSnapshot(`
@@ -744,7 +745,7 @@ describe("tablesCompletionSource", () => {
it("should handle multiple databases and schemas", () => {
const mockConnection: DataSourceConnection = {
- name: "multi_db_engine",
+ name: "multi_db_engine" as ConnectionName,
dialect: "postgres",
display_name: "postgres",
source: "postgres",
@@ -803,11 +804,8 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- [mockConnection.name as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: mockConnection.name as ConnectionName,
+ connectionsMap: new Map([[mockConnection.name, mockConnection]]),
+ latestEngineSelected: mockConnection.name,
});
const completionSource = completionStore.getCompletionSource(
@@ -838,7 +836,7 @@ describe("tablesCompletionSource", () => {
it("should handle multiple databases and schemas with default", () => {
const mockConnection: DataSourceConnection = {
- name: "multi_db_engine",
+ name: "multi_db_engine" as ConnectionName,
dialect: "postgres",
display_name: "postgres",
source: "postgres",
@@ -943,11 +941,8 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- [mockConnection.name as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: mockConnection.name as ConnectionName,
+ connectionsMap: new Map([[mockConnection.name, mockConnection]]),
+ latestEngineSelected: mockConnection.name,
});
const completionSource = completionStore.getCompletionSource(
@@ -987,7 +982,7 @@ describe("tablesCompletionSource", () => {
it("should handle default schema", () => {
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "postgres",
display_name: "postgres",
source: "postgres",
@@ -1035,16 +1030,11 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- [mockConnection.name as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: mockConnection.name as ConnectionName,
+ connectionsMap: new Map([[mockConnection.name, mockConnection]]),
+ latestEngineSelected: mockConnection.name,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.schema).toMatchInlineSnapshot(`
{
"public": {
@@ -1062,7 +1052,7 @@ describe("tablesCompletionSource", () => {
it("should create a default table if there is only one table", () => {
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "postgres",
display_name: "postgres",
source: "postgres",
@@ -1089,23 +1079,18 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- [mockConnection.name as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: mockConnection.name as ConnectionName,
+ connectionsMap: new Map([[mockConnection.name, mockConnection]]),
+ latestEngineSelected: mockConnection.name,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.defaultTable).toBe("users");
expect(completionSource?.dialect).toBe(PostgreSQL);
});
it("should handle schemaless databases", () => {
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "postgres",
display_name: "postgres",
default_database: "test_db",
@@ -1165,16 +1150,11 @@ describe("tablesCompletionSource", () => {
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- [mockConnection.name as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: mockConnection.name as ConnectionName,
+ connectionsMap: new Map([[mockConnection.name, mockConnection]]),
+ latestEngineSelected: mockConnection.name,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.defaultTable).toBe(undefined);
expect(completionSource?.dialect).toBe(PostgreSQL);
expect(completionSource?.schema).toMatchInlineSnapshot(`
@@ -1201,10 +1181,275 @@ describe("tablesCompletionSource", () => {
],
},
];
+
+ describe("SQL Completions", () => {
+ const completionStore = new SQLCompletionStore();
+
+ beforeEach(() => {
+ // Reset state
+ setLatestEngineSelected(DUCKDB_ENGINE);
+ store.set(datasetsAtom, {
+ tables: [],
+ } as unknown as DatasetsState);
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map(),
+ latestEngineSelected: DUCKDB_ENGINE,
+ });
+ });
+
+ const createEditorState = (
+ doc: string,
+ metadata?: Partial<SQLLanguageAdapterMetadata>,
+ ) => {
+ const defaultMetadata: SQLLanguageAdapterMetadata = {
+ dataframeName: "_df",
+ quotePrefix: "f",
+ commentLines: [],
+ showOutput: true,
+ engine: DUCKDB_ENGINE,
+ ...metadata,
+ };
+
+ return EditorState.create({
+ doc,
+ extensions: [languageMetadataField.init(() => defaultMetadata)],
+ });
+ };
+
+ const createCompletionContext = (
+ state: EditorState,
+ pos: number,
+ matchText?: string,
+ matchFrom?: number,
+ ): CompletionContext => {
+ return {
+ pos,
+ explicit: false,
+ matchBefore: matchText
+ ? () => ({
+ from: matchFrom || pos - matchText.length,
+ to: pos,
+ text: matchText,
+ })
+ : () => null,
+ state,
+ aborted: false,
+ tokenBefore: () => null,
+ } as unknown as CompletionContext;
+ };
+
+ const getCompletion = (extensions: Extension[]) => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const ext = extensions.find((ext) => (ext as any).facet === undefined);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return (ext as any)?.value?.override?.[0];
+ };
+
+ describe("tablesCompletionSource", () => {
+ it("should return null when no connection exists", () => {
+ const state = createEditorState("SELECT * FROM ");
+ const ctx = createCompletionContext(state, 14);
+
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ const result = completion!(ctx);
+ expect(result).toBeNull();
+ });
+
+ it("should provide table completions when connection exists", () => {
+ const mockConnection: DataSourceConnection = {
+ name: TEST_ENGINE,
+ dialect: "postgres",
+ display_name: "postgres",
+ source: "postgres",
+ databases: [
+ {
+ name: "test_db",
+ dialect: "postgres",
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "users",
+ source: "postgres",
+ source_type: "local",
+ type: "table",
+ columns: [
+ {
+ name: "id",
+ external_type: "string",
+ type: "string",
+ sample_values: [],
+ },
+ {
+ name: "name",
+ external_type: "string",
+ type: "string",
+ sample_values: [],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
+ });
+
+ const state = createEditorState("SELECT * FROM u", {
+ engine: TEST_ENGINE,
+ });
+ const ctx = createCompletionContext(state, 15, "u", 14);
+
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ const result = completion!(ctx);
+ expect(result).toBeDefined();
+ expect(result?.options.length).toBeGreaterThan(0);
+ });
+
+ it("should include local datasets in completions", () => {
+ const mockConnection: DataSourceConnection = {
+ name: TEST_ENGINE,
+ dialect: "duckdb",
+ display_name: "duckdb",
+ source: "duckdb",
+ databases: [],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
+ });
+
+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
+
+ const state = createEditorState("SELECT * FROM d", {
+ engine: TEST_ENGINE,
+ });
+ const ctx = createCompletionContext(state, 15, "d", 14);
+
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ const result: CompletionResult = completion!(ctx);
+ expect(result).toBeDefined();
+ expect(result?.options.some((opt) => opt.label === "dataset1")).toBe(
+ true,
+ );
+ });
+ });
+
+ describe("customKeywordCompletionSource", () => {
+ it("should provide SQL keyword completions", () => {
+ const mockConnection: DataSourceConnection = {
+ name: TEST_ENGINE,
+ dialect: "postgres",
+ display_name: "postgres",
+ source: "postgres",
+ databases: [],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
+ });
+
+ const state = createEditorState("SEL", {
+ engine: TEST_ENGINE,
+ });
+ const ctx = createCompletionContext(state, 3, "SEL", 0);
+
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ const result: CompletionResult = completion!(ctx);
+ expect(result).toBeDefined();
+ expect(result?.options.some((opt) => opt.label === "SELECT")).toBe(
+ true,
+ );
+ });
+
+ it("should not provide keyword completions after dot", () => {
+ const mockConnection: DataSourceConnection = {
+ name: TEST_ENGINE,
+ dialect: "postgres",
+ display_name: "postgres",
+ source: "postgres",
+ databases: [],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
+ });
+
+ const state = createEditorState("SELECT users.n", {
+ engine: TEST_ENGINE,
+ });
+ const ctx = createCompletionContext(state, 14, ".n", 12);
+
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ const result = completion!(ctx);
+ expect(result).toBeNull();
+ });
+
+ it("should use correct dialect for different engines", () => {
+ const mysqlConnection: DataSourceConnection = {
+ name: "mysql_engine" as ConnectionName,
+ dialect: "mysql",
+ display_name: "mysql",
+ source: "mysql",
+ databases: [],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ connectionsMap: new Map([[mysqlConnection.name, mysqlConnection]]),
+ latestEngineSelected: mysqlConnection.name,
+ });
+
+ // Test that the correct dialect is used
+ const dialect = completionStore.getDialect(mysqlConnection.name);
+ expect(dialect).toBeDefined();
+ expect(dialect?.spec.keywords).toBeDefined();
+ });
+ });
+
+ describe("variableCompletionSource", () => {
+ it("should be included in extension overrides", () => {
+ const adapter = new SQLLanguageAdapter();
+ const extensions = adapter.getExtension();
+ const completion = getCompletion(extensions);
+
+ expect(completion).toBeDefined();
+ expect(completion).toHaveLength(3); // tablesCompletionSource, variableCompletionSource, customKeywordCompletionSource
+ });
+ });
+ });
mockStore.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "duckdb",
display_name: "duckdb",
default_database: "test_db",
@@ -1239,16 +1484,11 @@ describe("tablesCompletionSource", () => {
],
};
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- ["test_engine" as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: "test_engine" as ConnectionName,
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.schema).toMatchInlineSnapshot(`
{
"dataset1": [
@@ -1266,16 +1506,11 @@ describe("tablesCompletionSource", () => {
it("should return new connection tables when connection is updated", () => {
mockStore.set(dataSourceConnectionsAtom, {
- connectionsMap: new Map([
- ["test_engine" as ConnectionName, mockConnection],
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ]) as any,
- latestEngineSelected: "test_engine" as ConnectionName,
+ connectionsMap: new Map([[TEST_ENGINE, mockConnection]]),
+ latestEngineSelected: TEST_ENGINE,
});
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.schema).toMatchInlineSnapshot(`
{
"test_schema": {
@@ -1294,30 +1529,26 @@ describe("tablesCompletionSource", () => {
mockStore.set(dataSourceConnectionsAtom, {
...mockStore.get(dataSourceConnectionsAtom),
connectionsMap: new Map([
- ["test_engine" as ConnectionName, newConnection],
+ [TEST_ENGINE, newConnection],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
]) as any,
- latestEngineSelected: "test_engine" as ConnectionName,
+ latestEngineSelected: TEST_ENGINE,
});
- const completionSource2 = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource2 = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource2?.defaultSchema).toBe("new_schema");
});
it("should return new local tables when local tables are updated", () => {
mockStore.set(dataSourceConnectionsAtom, {
connectionsMap: new Map([
- ["test_engine" as ConnectionName, mockConnection],
+ [TEST_ENGINE, mockConnection],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
]) as any,
- latestEngineSelected: "test_engine" as ConnectionName,
+ latestEngineSelected: TEST_ENGINE,
});
mockStore.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
- const completionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const completionSource = completionStore.getCompletionSource(TEST_ENGINE);
expect(completionSource?.schema).toMatchInlineSnapshot(`
{
"dataset1": [
@@ -1343,9 +1574,8 @@ describe("tablesCompletionSource", () => {
];
mockStore.set(datasetsAtom, { tables: newTestDatasets } as DatasetsState);
- const newCompletionSource = completionStore.getCompletionSource(
- "test_engine" as ConnectionName,
- );
+ const newCompletionSource =
+ completionStore.getCompletionSource(TEST_ENGINE);
expect(newCompletionSource?.schema).toMatchInlineSnapshot(`
{
"dataset3": [
@@ -1363,7 +1593,7 @@ describe("tablesCompletionSource", () => {
});
const mockConnection: DataSourceConnection = {
- name: "test_engine",
+ name: TEST_ENGINE,
dialect: "duckdb",
display_name: "duckdb",
default_database: "test_db",
diff --git a/frontend/src/core/codemirror/language/languages/sql.ts b/frontend/src/core/codemirror/language/languages/sql.ts
index 5c834fa484..5a4e844da1 100644
--- a/frontend/src/core/codemirror/language/languages/sql.ts
+++ b/frontend/src/core/codemirror/language/languages/sql.ts
@@ -16,7 +16,7 @@ import {
schemaCompletionSource,
sql,
} from "@codemirror/lang-sql";
-import type { Extension } from "@codemirror/state";
+import type { EditorState, Extension } from "@codemirror/state";
import type { SyntaxNode, TreeCursor } from "@lezer/common";
import { parser } from "@lezer/python";
import dedent from "string-dedent";
@@ -185,34 +185,20 @@ export class SQLLanguageAdapter
}
getExtension(): Extension[] {
- const keywordCompletion = keywordCompletionSource(StandardSQL);
return [
- sql({
- dialect: StandardSQL,
- }),
+ sql({}),
autocompletion({
// We remove the default keymap because we use our own which
// handles the Escape key correctly in Vim
defaultKeymap: false,
activateOnTyping: true,
override: [
+ // Completions for schema
tablesCompletionSource(),
// Complete for variables in SQL {} blocks
variableCompletionSource,
- (ctx) => {
- // We want to ignore keyword completions on something like
- // `WHERE my_table.col`
- // ^cursor
- const textBefore = ctx.matchBefore(/\.\w*/);
- if (textBefore) {
- // If there is a match, we are typing after a dot,
- // so we don't want to trigger SQL keyword completion
- return null;
- }
-
- const result = keywordCompletion(ctx);
- return result;
- },
+ // Completions for dialect keywords
+ customKeywordCompletionSource(),
],
}),
];
@@ -221,135 +207,185 @@ export class SQLLanguageAdapter
type TableToCols = Record<string, string[]>;
type Schemas = Record<string, TableToCols>;
+type CachedSchema = Pick<SQLConfig, "schema" | "defaultSchema"> & {
+ shouldAddLocalTables: boolean;
+};
export class SQLCompletionStore {
- private cache = new LRUCache<[DataSourceConnection, TableToCols], SQLConfig>(
- 10,
- );
+ private cache: LRUCache<DataSourceConnection, CachedSchema>;
- getCompletionSource(connectionName: ConnectionName): SQLConfig | null {
+ constructor() {
+ this.cache = new LRUCache(10, {
+ create: (connection) => this.getConnectionSchema(connection),
+ });
+ }
+
+ private getConnection(
+ connectionName: ConnectionName,
+ ): DataSourceConnection | undefined {
const dataConnectionsMap = store.get(dataConnectionsMapAtom);
- const connection = dataConnectionsMap.get(connectionName);
- if (!connection) {
- return null;
- }
+ return dataConnectionsMap.get(connectionName);
+ }
- const localTables = store.get(datasetTablesAtom);
+ private getConnectionSchema(connection: DataSourceConnection): CachedSchema {
+ const schemaMap: Record<string, TableToCols> = {};
+ const databaseMap: Record<string, Schemas> = {};
- // If there is a conflict with connection tables,
- // the engine will prioritize the connection tables without special handling
- const tablesMap: TableToCols = {};
- for (const table of localTables) {
- const tableColumns = table.columns.map((col) => col.name);
- tablesMap[table.name] = tableColumns;
- }
+ // When there is only one database, it is the default
+ const defaultDb = connection.databases.find(
+ (db) =>
+ db.name === connection.default_database ||
+ connection.databases.length === 1,
+ );
- const cacheKey: [DataSourceConnection, TableToCols] = [
- connection,
- tablesMap,
- ];
+ const dbToVerify = defaultDb ?? connection.databases[0];
+ const isSchemalessDb =
+ dbToVerify?.schemas.some((schema) => isSchemaless(schema.name)) ?? false;
- let cacheConfig: SQLConfig | undefined = this.cache.get(cacheKey);
- if (!cacheConfig) {
- const schemaMap: Record<string, TableToCols> = {};
- const databaseMap: Record<string, Schemas> = {};
+ // For schemaless databases, treat databases as schemas
+ if (isSchemalessDb) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const dbToTablesMap: Record<string, any> = {};
- const baseConfig: SQLConfig = {
- dialect: guessDialect(connection),
- schema: schemaMap,
- defaultSchema: connection.default_schema ?? undefined,
- defaultTable: getSingleTable(connection),
- };
+ for (const db of connection.databases) {
+ const isDefaultDb = db.name === defaultDb?.name;
- // When there is only one database, it is the default
- const defaultDb = connection.databases.find(
- (db) =>
- db.name === connection.default_database ||
- connection.databases.length === 1,
- );
-
- const dbToVerify = defaultDb ?? connection.databases[0];
- const isSchemalessDb =
- dbToVerify?.schemas.some((schema) => isSchemaless(schema.name)) ??
- false;
-
- // For schemaless databases, treat databases as schemas
- if (isSchemalessDb) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const dbToTablesMap: Record<string, any> = {};
-
- for (const db of connection.databases) {
- const isDefaultDb = db.name === defaultDb?.name;
-
- for (const schema of db.schemas) {
- for (const table of schema.tables) {
- const columns = table.columns.map((col) => col.name);
-
- if (isDefaultDb) {
- // For default database, add tables directly to top level
- dbToTablesMap[table.name] = columns;
- } else {
- // Otherwise nest under database name
- dbToTablesMap[db.name] = dbToTablesMap[db.name] || {};
- dbToTablesMap[db.name][table.name] = columns;
- }
+ for (const schema of db.schemas) {
+ for (const table of schema.tables) {
+ const columns = table.columns.map((col) => col.name);
+
+ if (isDefaultDb) {
+ // For default database, add tables directly to top level
+ dbToTablesMap[table.name] = columns;
+ } else {
+ // Otherwise nest under database name
+ dbToTablesMap[db.name] = dbToTablesMap[db.name] || {};
+ dbToTablesMap[db.name][table.name] = columns;
}
}
}
+ }
+
+ return {
+ shouldAddLocalTables: false,
+ schema: dbToTablesMap,
+ defaultSchema: defaultDb?.name,
+ };
+ }
+
+ // For default db, we can use the schema name directly
+ for (const schema of defaultDb?.schemas ?? []) {
+ schemaMap[schema.name] = {};
+ for (const table of schema.tables) {
+ const columns = table.columns.map((col) => col.name);
+ schemaMap[schema.name][table.name] = columns;
+ }
+ }
- cacheConfig = {
- ...baseConfig,
- schema: dbToTablesMap,
- defaultSchema: defaultDb?.name,
- };
- return cacheConfig;
+ // Otherwise, we need to use the fully qualified name
+ for (const database of connection.databases) {
+ if (database.name === defaultDb?.name) {
+ continue;
}
+ databaseMap[database.name] = {};
+
+ for (const schema of database.schemas) {
+ databaseMap[database.name][schema.name] = {};
- // For default db, we can use the schema name directly
- for (const schema of defaultDb?.schemas ?? []) {
- schemaMap[schema.name] = {};
for (const table of schema.tables) {
const columns = table.columns.map((col) => col.name);
- schemaMap[schema.name][table.name] = columns;
+ databaseMap[database.name][schema.name][table.name] = columns;
}
}
+ }
- // Otherwise, we need to use the fully qualified name
- for (const database of connection.databases) {
- if (database.name === defaultDb?.name) {
- continue;
- }
- databaseMap[database.name] = {};
+ return {
+ shouldAddLocalTables: true,
+ schema: { ...databaseMap, ...schemaMap },
+ defaultSchema: connection.default_schema ?? undefined,
+ };
+ }
- for (const schema of database.schemas) {
- databaseMap[database.name][schema.name] = {};
+ /**
+ * Get the dialect for a connection.
+ * If the connection is not found, return the standard SQL dialect.
+ */
+ getDialect(connectionName: ConnectionName): SQLDialect {
+ const connection = this.getConnection(connectionName);
+ if (!connection) {
+ return StandardSQL;
+ }
+ return guessDialect(connection) ?? StandardSQL;
+ }
- for (const table of schema.tables) {
- const columns = table.columns.map((col) => col.name);
- databaseMap[database.name][schema.name][table.name] = columns;
- }
- }
+ getCompletionSource(connectionName: ConnectionName): SQLConfig | null {
+ const connection = this.getConnection(connectionName);
+ if (!connection) {
+ return null;
+ }
+
+ const getTablesMap = () => {
+ const localTables = store.get(datasetTablesAtom);
+ // If there is a conflict with connection tables,
+ // the engine will prioritize the connection tables without special handling
+ const tablesMap: TableToCols = {};
+ for (const table of localTables) {
+ const tableColumns = table.columns.map((col) => col.name);
+ tablesMap[table.name] = tableColumns;
}
+ return tablesMap;
+ };
- cacheConfig = {
- ...baseConfig,
- schema: { ...databaseMap, ...schemaMap, ...tablesMap },
- defaultSchema: connection.default_schema ?? undefined,
- };
- this.cache.set(cacheKey, cacheConfig);
- }
+ const schema = this.cache.getOrCreate(connection);
- return cacheConfig;
+ return {
+ dialect: guessDialect(connection),
+ schema: schema.shouldAddLocalTables
+ ? { ...schema.schema, ...getTablesMap() }
+ : schema.schema,
+ defaultSchema: schema.defaultSchema,
+ defaultTable: getSingleTable(connection),
+ };
}
}
const SCHEMA_CACHE = new SQLCompletionStore();
+function getSQLMetadata(state: EditorState): SQLLanguageAdapterMetadata {
+ return state.field(languageMetadataField) as SQLLanguageAdapterMetadata;
+}
+
+/**
+ * Custom keyword completion source that dynamically gets the Dialect.
+ * This also ignores keyword completions on table columns.
+ */
+function customKeywordCompletionSource(): CompletionSource {
+ return (ctx) => {
+ const metadata = getSQLMetadata(ctx.state);
+ const connectionName = metadata.engine;
+ const dialect = SCHEMA_CACHE.getDialect(connectionName);
+
+ // We want to ignore keyword completions on something like
+ // `WHERE my_table.col`
+ // ^cursor
+ const textBefore = ctx.matchBefore(/\.\w*/);
+ if (textBefore) {
+ // If there is a match, we are typing after a dot,
+ // so we don't want to trigger SQL keyword completion
+ return null;
+ }
+
+ const result = keywordCompletionSource(dialect)(ctx);
+ return result;
+ };
+}
+
+/**
+ * Custom schema completion source that dynamically gets the Dialect and SQL tables.
+ */
function tablesCompletionSource(): CompletionSource {
return (ctx) => {
- const metadata = ctx.state.field(
- languageMetadataField,
- ) as SQLLanguageAdapterMetadata;
+ const metadata = getSQLMetadata(ctx.state);
const connectionName = metadata.engine;
const config = SCHEMA_CACHE.getCompletionSource(connectionName);
diff --git a/frontend/src/utils/lru.ts b/frontend/src/utils/lru.ts
index a70c853286..9607a0ad3a 100644
--- a/frontend/src/utils/lru.ts
+++ b/frontend/src/utils/lru.ts
@@ -1,14 +1,34 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { invariant } from "./invariant";
+
+interface LRUCacheOptions<K, V> {
+ create?: (key: K) => V;
+}
+
export class LRUCache<K, V> {
private maxSize: number;
private cache = new Map<K, V>();
+ private options: LRUCacheOptions<K, V>;
- constructor(maxSize: number) {
+ constructor(maxSize: number, options: LRUCacheOptions<K, V> = {}) {
this.maxSize = maxSize;
+ this.options = options;
+ }
+
+ public getOrCreate(key: K): V {
+ invariant(this.options.create, "create function is required");
+
+ const item = this.cache.get(key);
+ if (item !== undefined) {
+ return item;
+ }
+ const newItem = this.options.create(key);
+ this.cache.set(key, newItem);
+ return newItem;
}
- public get(key: K) {
+ public get(key: K): V | undefined {
const item = this.cache.get(key);
if (item !== undefined) {
// re-insert for LRU effect