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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: bring back SQL schema completion and AI '@' reference for datasources (#3898)
Myles Scolnick339936bdbddd
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex 7ea6d4b057..68e209e815 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -31,6 +31,7 @@ import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";import { atomWithStorage } from "jotai/utils";import { type ResolvedTheme, useTheme } from "@/theme/useTheme";import { getAICompletionBody, mentions } from "./completion-utils";+import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections";const pythonExtensions = [customPythonLanguageSupport(),@@ -230,11 +231,21 @@ export const PromptInput = ({const handleSubmit = onSubmit;const handleEscape = onClose;const tables = useAtomValue(datasetTablesAtom);+ const datasources = useAtomValue(dataSourceConnectionsAtom);const extensions = useMemo(() => {- const completions = tables.map(+ const connections = [...datasources.connectionsMap.values()];+ const allTables = [+ ...tables,+ ...connections.flatMap((c) =>+ c.databases.flatMap((d) => d.schemas.flatMap((s) => s.tables)),+ ),+ ];++ const completions = allTables.map((table): Completion => ({label: `@${table.name}`,+ detail: table.source,info: () => {const shape = [table.num_rows == null ? undefined : `${table.num_rows} rows`,@@ -367,7 +378,7 @@ export const PromptInput = ({},]),];- }, [tables, additionalCompletions, handleSubmit, handleEscape]);+ }, [tables, datasources, additionalCompletions, handleSubmit, handleEscape]);return (<ReactCodeMirrordiff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.tsindex c8818c286e..0fbc4e108e 100644--- a/frontend/src/components/editor/ai/completion-utils.ts+++ b/frontend/src/components/editor/ai/completion-utils.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { getCodes } from "@/core/codemirror/copilot/getCodes";+import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections";import { datasetTablesAtom } from "@/core/datasets/state";import type { DataTable } from "@/core/kernel/messages";import type { AiCompletionRequest } from "@/core/network/types";@@ -43,7 +44,16 @@ export function getAICompletionBody(*/function extractDatasets(input: string): DataTable[] {const datasets = store.get(datasetTablesAtom);- const existingDatasets = Maps.keyBy(datasets, (dataset) => dataset.name);+ const connectionsMap = store.get(dataSourceConnectionsAtom).connectionsMap;+ const connections = [...connectionsMap.values()];+ const allTables = [+ ...datasets,+ ...connections.flatMap((c) =>+ c.databases.flatMap((d) => d.schemas.flatMap((s) => s.tables)),+ ),+ ];+ // TODO: This does not handle duplicates table names.+ const existingDatasets = Maps.keyBy(allTables, (dataset) => dataset.name);// Extract dataset mentions from the inputconst mentionedDatasets = input.match(/@([\w.]+)/g) || [];diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 889e1e02d2..075d4efacd 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -358,7 +358,7 @@ const AddCellButtons: React.FC<{onClick={isAiButtonOpenActions.toggle}><SparklesIcon className="mr-2 size-4 flex-shrink-0" />- Generate with AI!!!+ Generate with AI</Button></Tooltip></>diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.tsindex 847b353183..22a8392188 100644--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts@@ -1,6 +1,14 @@/* Copyright 2024 Marimo. All rights reserved. */-import { expect, describe, it, beforeAll, afterAll, afterEach } from "vitest";-import { SQLLanguageAdapter } from "../sql";+import {+ expect,+ describe,+ it,+ beforeAll,+ afterAll,+ afterEach,+ beforeEach,+} from "vitest";+import { SQLCompletionStore, SQLLanguageAdapter } from "../sql";import { store } from "@/core/state/jotai";import { capabilitiesAtom } from "@/core/config/capabilities";import {@@ -8,6 +16,8 @@ import {DEFAULT_ENGINE,type ConnectionName,} from "@/core/datasets/data-source-connections";+import type { DataSourceConnection } from "@/core/kernel/messages";+import { PostgreSQL } from "@codemirror/lang-sql";const adapter = new SQLLanguageAdapter();@@ -570,3 +580,285 @@ _df = mo.sql(});});});++describe("tablesCompletionSource", () => {+ const mockStore = store;+ const completionStore = new SQLCompletionStore();++ beforeEach(() => {+ // Reset the adapter engine+ adapter.engine = DEFAULT_ENGINE;+ });++ it("should return null if connection not found", () => {+ mockStore.set(dataSourceConnectionsAtom, {+ connectionsMap: new Map(),+ latestEngineSelected: DEFAULT_ENGINE,+ });++ const completionSource = completionStore.getCompletionSource(+ "test_engine" as ConnectionName,+ );+ expect(completionSource).toBe(null);+ });++ it("should create schema with database.schema.table structure and short table names", () => {+ const mockConnection: DataSourceConnection = {+ name: "test_engine",+ dialect: "duckdb",+ display_name: "duckdb",+ source: "duckdb",+ databases: [+ {+ dialect: "duckdb",+ name: "test_db",+ schemas: [+ {+ name: "public",+ tables: [+ {+ name: "users",+ source: "duckdb",+ source_type: "local",+ type: "table",+ columns: [+ {+ name: "id",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ {+ name: "name",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ {+ name: "email",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ ],+ },+ {+ name: "orders",+ source: "duckdb",+ source_type: "local",+ type: "table",+ columns: [+ {+ name: "order_id",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ {+ name: "user_id",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ {+ name: "total",+ external_type: "number",+ type: "number",+ sample_values: [],+ },+ ],+ },+ ],+ },+ ],+ },+ ],+ };++ 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,+ });++ adapter.engine = "test_engine" as ConnectionName;+ const completionSource = completionStore.getCompletionSource(+ "test_engine" as ConnectionName,+ );+ expect(completionSource?.defaultTable).toBeUndefined();+ expect(completionSource?.dialect).toBe(undefined);+ expect(completionSource?.schema).toMatchInlineSnapshot(`+ {+ "orders": [+ "order_id",+ "user_id",+ "total",+ ],+ "test_db": {+ "public": {+ "orders": [+ "order_id",+ "user_id",+ "total",+ ],+ "users": [+ "id",+ "name",+ "email",+ ],+ },+ },+ "users": [+ "id",+ "name",+ "email",+ ],+ }+ `);+ });++ it("should handle multiple databases and schemas", () => {+ const mockConnection: DataSourceConnection = {+ name: "multi_db_engine",+ dialect: "postgres",+ display_name: "postgres",+ source: "postgres",+ databases: [+ {+ name: "db1",+ dialect: "postgres",+ schemas: [+ {+ name: "schema1",+ tables: [+ {+ name: "table1",+ source: "postgres",+ source_type: "local",+ type: "table",+ columns: [+ {+ name: "col1",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ ],+ },+ ],+ },+ ],+ },+ {+ name: "db2",+ dialect: "postgres",+ schemas: [+ {+ name: "schema2",+ tables: [+ {+ name: "table2",+ source: "postgres",+ source_type: "local",+ type: "table",+ columns: [+ {+ name: "col2",+ external_type: "string",+ type: "string",+ sample_values: [],+ },+ ],+ },+ ],+ },+ ],+ },+ ],+ };++ 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,+ });++ adapter.engine = "multi_db_engine" as ConnectionName;+ const completionSource = completionStore.getCompletionSource(+ "multi_db_engine" as ConnectionName,+ );+ expect(completionSource?.schema).toMatchInlineSnapshot(`+ {+ "db1": {+ "schema1": {+ "table1": [+ "col1",+ ],+ },+ },+ "db2": {+ "schema2": {+ "table2": [+ "col2",+ ],+ },+ },+ "table1": [+ "col1",+ ],+ "table2": [+ "col2",+ ],+ }+ `);+ expect(completionSource?.defaultTable).toBeUndefined();+ });++ it("should create a default table if there is only one table", () => {+ 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: [],+ },+ ],+ },+ ],+ },+ ],+ };++ 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,+ });++ adapter.engine = "test_engine" as ConnectionName;+ const completionSource = completionStore.getCompletionSource(+ "test_engine" as ConnectionName,+ );+ expect(completionSource?.defaultTable).toBe("users");+ expect(completionSource?.dialect).toBe(PostgreSQL);+ });+});diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsindex 857d1028cb..ba2f0bd67a 100644--- a/frontend/src/core/codemirror/language/sql.ts+++ b/frontend/src/core/codemirror/language/sql.ts@@ -1,7 +1,17 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import type { LanguageAdapter } from "./types";-import { sql, StandardSQL, schemaCompletionSource } from "@codemirror/lang-sql";+import {+ sql,+ StandardSQL,+ schemaCompletionSource,+ type SQLNamespace,+ MySQL,+ PostgreSQL,+ SQLite,+ type SQLDialect,+ type SQLConfig,+} from "@codemirror/lang-sql";import dedent from "string-dedent";import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";@@ -11,7 +21,6 @@ import {type CompletionSource,} from "@codemirror/autocomplete";import { store } from "@/core/state/jotai";-import { datasetsAtom } from "@/core/datasets/state";import { type QuotePrefixKind, upgradePrefixKind } from "./utils/quotes";import { capabilitiesAtom } from "@/core/config/capabilities";import { MarkdownLanguageAdapter } from "./markdown";@@ -25,6 +34,8 @@ import { parser } from "@lezer/python";import type { SyntaxNode, TreeCursor } from "@lezer/common";import { parseArgsKwargs } from "./utils/ast";import { Logger } from "@/utils/Logger";+import { LRUCache } from "@/utils/lru";+import type { DataSourceConnection } from "@/core/kernel/messages";/*** Language adapter for SQL.@@ -151,27 +162,110 @@ export class SQLLanguageAdapter implements LanguageAdapter {activateOnTyping: true,}),StandardSQL.language.data.of({- autocomplete: tablesCompletionSource(),+ autocomplete: tablesCompletionSource(this),}),];}}-function tablesCompletionSource(): CompletionSource {+export class SQLCompletionStore {+ private cache = new LRUCache<DataSourceConnection, SQLConfig>(10);++ getCompletionSource(connectionName: ConnectionName): SQLConfig | null {+ const dataSourceConnections = store.get(dataSourceConnectionsAtom);+ const connection = dataSourceConnections.connectionsMap.get(connectionName);+ if (!connection) {+ return null;+ }++ let cacheConfig: SQLConfig | undefined = this.cache.get(connection);+ if (!cacheConfig) {+ // Verbose version with database.schema.table+ const schema: Record<+ string,+ Record<string, Record<string, string[]>>+ > = {};+ const tables: Record<string, string[]> = {};+ for (const database of connection.databases) {+ schema[database.name] = {};+ for (const dbSchema of database.schemas) {+ schema[database.name][dbSchema.name] = {};+ for (const table of dbSchema.tables) {+ const columns = table.columns.map((col) => col.name);+ schema[database.name][dbSchema.name][table.name] = columns;+ // Also add the table name at the top level+ tables[table.name] = columns;+ }+ }+ }++ const combinedSchema: SQLNamespace = {+ // Hierarchical schema: database.schema.table+ ...schema,+ // Tables at the top level+ // TODO: For better correctness, we can filter to only include the default schema+ ...tables,+ };++ cacheConfig = {+ dialect: guessDialect(connection),+ schema: combinedSchema,+ defaultTable: getSingleTable(connection),+ };+ this.cache.set(connection, cacheConfig);+ }++ return cacheConfig;+ }+}++const SCHEMA_CACHE = new SQLCompletionStore();++function tablesCompletionSource(adapter: SQLLanguageAdapter): CompletionSource {return (ctx) => {- const schema: Record<string, string[]> = {};- const datasets = store.get(datasetsAtom);- for (const table of datasets.tables) {- schema[table.name] = table.columns.map((column) => column.name);+ const connectionName = adapter.engine;+ const config = SCHEMA_CACHE.getCompletionSource(connectionName);++ if (!config) {+ return null;}- return schemaCompletionSource({- schema,- })(ctx);+ return schemaCompletionSource(config)(ctx);};}-interface SQLConfig {+function getSingleTable(connection: DataSourceConnection): string | undefined {+ if (connection.databases.length !== 1) {+ return undefined;+ }+ const database = connection.databases[0];+ if (database.schemas.length !== 1) {+ return undefined;+ }+ const schema = database.schemas[0];+ if (schema.tables.length !== 1) {+ return undefined;+ }+ return schema.tables[0].name;+}++function guessDialect(+ connection: DataSourceConnection,+): SQLDialect | undefined {+ switch (connection.dialect) {+ case "postgresql":+ case "postgres":+ return PostgreSQL;+ case "mysql":+ return MySQL;+ case "sqlite":+ return SQLite;+ default:+ return undefined;+ }+}++interface SQLParseInfo {dfName: string;sqlString: string;engine: string | undefined;@@ -216,7 +310,7 @@ function getStringContent(node: SyntaxNode, code: string): string | null {* @param code - The Python code string to parse.* @returns The parsed SQL statement or null if parsing fails.*/-export function parseSQLStatement(code: string): SQLConfig | null {+export function parseSQLStatement(code: string): SQLParseInfo | null {try {const tree = parser.parse(code);const cursor = tree.cursor();diff --git a/frontend/src/utils/__tests__/lru.test.ts b/frontend/src/utils/__tests__/lru.test.tsnew file mode 100644index 0000000000..19c05a9572--- /dev/null+++ b/frontend/src/utils/__tests__/lru.test.ts@@ -0,0 +1,74 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, test, expect } from "vitest";+import { LRUCache } from "../lru";++describe("LRUCache", () => {+ test("basic get/set operations", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ expect(cache.get("a")).toBe(1);+ expect(cache.get("b")).toBe(2);+ expect(cache.get("c")).toBe(3);+ });++ test("evicts least recently used item when over capacity", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);+ cache.set("d", 4);++ // "a" should be evicted as it was the least recently used+ expect(cache.get("a")).toBeUndefined();+ expect(cache.get("b")).toBe(2);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("accessing an item makes it most recently used", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ // Access "a", making it most recently used+ cache.get("a");+ cache.set("d", 4);++ // "b" should be evicted as it becomes the least recently used+ expect(cache.get("b")).toBeUndefined();+ expect(cache.get("a")).toBe(1);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("updating existing key maintains order", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ // Update "a"+ cache.set("a", 10);+ cache.set("d", 4);++ // "b" should be evicted as "a" was moved to most recent+ expect(cache.get("b")).toBeUndefined();+ expect(cache.get("a")).toBe(10);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("keys() returns iterator in order", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ const keys = [...cache.keys()];+ expect(keys).toEqual(["a", "b", "c"]);+ });+});diff --git a/frontend/src/utils/lru.ts b/frontend/src/utils/lru.tsnew file mode 100644index 0000000000..7db0691eab--- /dev/null+++ b/frontend/src/utils/lru.ts@@ -0,0 +1,40 @@+/* Copyright 2024 Marimo. All rights reserved. */++export class LRUCache<K, V> {+ private maxSize: number;+ private cache = new Map<K, V>();++ constructor(maxSize: number) {+ this.maxSize = maxSize;+ }++ public get(key: K) {+ const item = this.cache.get(key);+ if (item !== undefined) {+ // re-insert for LRU effect+ this.cache.delete(key);+ this.cache.set(key, item);+ }+ return item;+ }++ public set(key: K, value: V) {+ // if key already in cache, remove it so we move it to the "fresh" position+ if (this.cache.has(key)) {+ this.cache.delete(key);+ }+ this.cache.set(key, value);++ // evict oldest+ if (this.cache.size > this.maxSize) {+ const oldestKey = this.cache.keys().next().value;+ if (oldestKey !== undefined) {+ this.cache.delete(oldestKey);+ }+ }+ }++ public keys() {+ return this.cache.keys();+ }+}