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.

improvement: better sql completions (#3930)

Shahmir Varqha3bd0fc213554
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index 69bfa3107f..a854c1843c 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -186,6 +186,7 @@ export const DataSources: React.FC = () => {
>
<SchemaList
schemas={database.schemas}
+ defaultSchema={connection.default_schema}
engineName={connection.name}
databaseName={database.name}
hasSearch={hasSearch}
@@ -285,11 +286,19 @@ const DatabaseItem: React.FC<{
const SchemaList: React.FC<{
schemas: DatabaseSchema[];
+ defaultSchema?: string | null;
engineName: string;
databaseName: string;
hasSearch: boolean;
searchValue?: string;
-}> = ({ schemas, engineName, databaseName, hasSearch, searchValue }) => {
+}> = ({
+ schemas,
+ defaultSchema,
+ engineName,
+ databaseName,
+ hasSearch,
+ searchValue,
+}) => {
if (schemas.length === 0) {
return <EmptyState content="No schemas available" className="pl-6" />;
}
@@ -319,6 +328,7 @@ const SchemaList: React.FC<{
engine: engineName,
database: databaseName,
schema: schema.name,
+ defaultSchema: defaultSchema,
}}
/>
</SchemaItem>
@@ -371,6 +381,7 @@ interface SQLTableContext {
engine: string;
database: string;
schema: string;
+ defaultSchema?: string | null;
}
const TableList: React.FC<{
@@ -454,8 +465,10 @@ const DatasetTableItem: React.FC<{
maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);
let code = "";
if (sqlTableContext) {
- const { engine, schema } = sqlTableContext;
- code = `_df = mo.sql(f"SELECT * FROM ${schema}.${table.name} LIMIT 100", engine=${engine})`;
+ const { engine, schema, defaultSchema } = sqlTableContext;
+ const tableName =
+ defaultSchema === schema ? table.name : `${schema}.${table.name}`;
+ code = `_df = mo.sql(f"SELECT * FROM ${tableName} LIMIT 100", engine=${engine})`;
} else {
switch (table.source_type) {
case "local":
@@ -633,6 +646,22 @@ const DatasetColumnItem: React.FC<{
});
};
+ const renderItemSubtext = ({
+ tooltipContent,
+ content,
+ }: {
+ tooltipContent: string;
+ content: string;
+ }) => {
+ return (
+ <Tooltip content={tooltipContent} delayDuration={100}>
+ <span className="text-xs text-black bg-gray-100 dark:invert rounded px-1">
+ {content}
+ </span>
+ </Tooltip>
+ );
+ };
+
return (
<>
<CommandItem
@@ -649,20 +678,10 @@ const DatasetColumnItem: React.FC<{
>
<Icon className="flex-shrink-0 h-3 w-3" strokeWidth={1.5} />
<span>{column.name}</span>
- {isPrimaryKey && (
- <Tooltip content="Primary Key" delayDuration={100}>
- <span className="text-xs text-black bg-gray-200 rounded px-1">
- PK
- </span>
- </Tooltip>
- )}
- {isIndexed && (
- <Tooltip content="Indexed" delayDuration={100}>
- <span className="text-xs text-black bg-gray-200 rounded px-1">
- IDX
- </span>
- </Tooltip>
- )}
+ {isPrimaryKey &&
+ renderItemSubtext({ tooltipContent: "Primary key", content: "PK" })}
+ {isIndexed &&
+ renderItemSubtext({ tooltipContent: "Indexed", content: "IDX" })}
</div>
<Tooltip content="Copy column name" delayDuration={400}>
<Button
@@ -850,8 +869,10 @@ function sqlCode(
sqlTableContext?: SQLTableContext,
) {
if (sqlTableContext) {
- const { engine, schema } = sqlTableContext;
- return `_df = mo.sql(f'SELECT ${column.name} FROM ${schema}.${table.name} LIMIT 100', engine=${engine})`;
+ const { engine, schema, defaultSchema } = sqlTableContext;
+ const tableName =
+ defaultSchema === schema ? table.name : `${schema}.${table.name}`;
+ return `_df = mo.sql(f"SELECT ${column.name} FROM ${tableName} LIMIT 100", engine=${engine})`;
}
return `_df = mo.sql(f'SELECT "${column.name}" FROM ${table.name} LIMIT 100')`;
}
diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
index d3f894d94e..f242ea6ad2 100644
--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
@@ -5,6 +5,10 @@ import { getCodes } from "@/core/codemirror/copilot/getCodes";
import { datasetsAtom } from "@/core/datasets/state";
import { store } from "@/core/state/jotai";
import type { DatasetsState } from "@/core/datasets/types";
+import {
+ dataSourceConnectionsAtom,
+ DEFAULT_ENGINE,
+} from "@/core/datasets/data-source-connections";
// Mock getCodes function
vi.mock("@/core/codemirror/copilot/getCodes", () => ({
@@ -17,6 +21,10 @@ describe("getAICompletionBody", () => {
store.set(datasetsAtom, {
tables: [],
} as unknown as DatasetsState);
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map(),
+ });
(getCodes as Mock).mockReturnValue("// Some other code");
});
@@ -149,4 +157,52 @@ describe("getAICompletionBody", () => {
},
});
});
+
+ it("should handle connections", () => {
+ // Set up test data in the Jotai store
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_schema: "default_schema",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "default_schema",
+ tables: [
+ { name: "table1", columns: [{ name: "col1", type: "number" }] },
+ { name: "table2", columns: [] },
+ ],
+ },
+ {
+ name: "other_schema",
+ tables: [{ name: "table3", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ const input = "Use @table1 for analysis";
+ const result = getAICompletionBody(input);
+
+ expect(result).toEqual({
+ includeOtherCode: "// Some other code",
+ context: {
+ schema: [
+ {
+ name: "table1",
+ columns: [{ name: "col1", type: "number" }],
+ },
+ ],
+ },
+ });
+ });
});
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
index 68e209e815..8c2fc83ede 100644
--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx
+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
@@ -17,7 +17,6 @@ import { Prec } from "@codemirror/state";
import { customPythonLanguageSupport } from "@/core/codemirror/language/python";
import { asURL } from "@/utils/url";
import { useMemo, useState } from "react";
-import { datasetTablesAtom } from "@/core/datasets/state";
import { useAtom, useAtomValue } from "jotai";
import type { Completion } from "@codemirror/autocomplete";
import {
@@ -31,7 +30,8 @@ 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";
+import { allTablesAtom } from "@/core/datasets/data-source-connections";
+import type { DataTable } from "@/core/kernel/messages";
const pythonExtensions = [
customPythonLanguageSupport(),
@@ -230,22 +230,14 @@ export const PromptInput = ({
}: PromptInputProps) => {
const handleSubmit = onSubmit;
const handleEscape = onClose;
- const tables = useAtomValue(datasetTablesAtom);
- const datasources = useAtomValue(dataSourceConnectionsAtom);
+ const tablesMap = useAtomValue(allTablesAtom);
const extensions = useMemo(() => {
- 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}`,
+ const completions = [...tablesMap.entries()].map(
+ ([tableName, table]): Completion => ({
+ label: `@${tableName}`,
detail: table.source,
+ boost: table.source_type === "local" ? 5 : 0,
info: () => {
const shape = [
table.num_rows == null ? undefined : `${table.num_rows} rows`,
@@ -285,7 +277,13 @@ export const PromptInput = ({
table.columns.forEach((column) => {
const row = columnsTable.insertRow();
const nameCell = row.insertCell();
+
nameCell.textContent = column.name;
+ const itemMetadata = getItemMetadata(table, column);
+ if (itemMetadata) {
+ nameCell.append(itemMetadata);
+ }
+
const typeCell = row.insertCell();
typeCell.textContent = column.type;
});
@@ -298,7 +296,8 @@ export const PromptInput = ({
}),
);
- const matchBeforeRegexes = [/@(\w+)?/]; // Trigger autocompletion for text that begins with @
+ // Trigger autocompletion for text that begins with @, can contain dots
+ const matchBeforeRegexes = [/@([\w.]+)?/];
if (additionalCompletions) {
matchBeforeRegexes.push(additionalCompletions.triggerCompletionRegex);
}
@@ -378,7 +377,7 @@ export const PromptInput = ({
},
]),
];
- }, [tables, datasources, additionalCompletions, handleSubmit, handleEscape]);
+ }, [tablesMap, additionalCompletions, handleSubmit, handleEscape]);
return (
<ReactCodeMirror
@@ -396,3 +395,25 @@ export const PromptInput = ({
/>
);
};
+
+function getItemMetadata(
+ table: DataTable,
+ column: DataTable["columns"][0],
+): HTMLSpanElement | undefined {
+ const isPrimaryKey = table.primary_keys?.includes(column.name);
+ const isIndexed = table.indexes?.includes(column.name);
+ if (isPrimaryKey || isIndexed) {
+ const subtext = document.createElement("span");
+ subtext.textContent = isPrimaryKey ? "PK" : "IDX";
+ subtext.classList.add(
+ "text-xs",
+ "text-black",
+ "bg-gray-100",
+ "dark:invert",
+ "rounded",
+ "px-1",
+ "ml-1",
+ );
+ return subtext;
+ }
+}
diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.ts
index 0fbc4e108e..cc7cf1b730 100644
--- a/frontend/src/components/editor/ai/completion-utils.ts
+++ b/frontend/src/components/editor/ai/completion-utils.ts
@@ -1,12 +1,10 @@
/* 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 { allTablesAtom } from "@/core/datasets/data-source-connections";
import type { DataTable } from "@/core/kernel/messages";
import type { AiCompletionRequest } from "@/core/network/types";
import { store } from "@/core/state/jotai";
import { Logger } from "@/utils/Logger";
-import { Maps } from "@/utils/maps";
import {
autocompletion,
type Completion,
@@ -43,17 +41,7 @@ export function getAICompletionBody(
* Datasets are referenced with @<dataset_name> in the input.
*/
function extractDatasets(input: string): DataTable[] {
- const datasets = store.get(datasetTablesAtom);
- 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);
+ const allTables = store.get(allTablesAtom);
// Extract dataset mentions from the input
const mentionedDatasets = input.match(/@([\w.]+)/g) || [];
@@ -61,7 +49,7 @@ function extractDatasets(input: string): DataTable[] {
// Filter to only include datasets that exist
return mentionedDatasets
.map((mention) => mention.slice(1))
- .map((name) => existingDatasets.get(name))
+ .map((name) => allTables.get(name))
.filter(Boolean);
}
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index 22a8392188..d9391d54d9 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -602,7 +602,7 @@ describe("tablesCompletionSource", () => {
expect(completionSource).toBe(null);
});
- it("should create schema with database.schema.table structure and short table names", () => {
+ it("should create schema with schema.table structure", () => {
const mockConnection: DataSourceConnection = {
name: "test_engine",
dialect: "duckdb",
@@ -691,30 +691,18 @@ describe("tablesCompletionSource", () => {
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",
- ],
- },
+ "public": {
+ "orders": [
+ "order_id",
+ "user_id",
+ "total",
+ ],
+ "users": [
+ "id",
+ "name",
+ "email",
+ ],
},
- "users": [
- "id",
- "name",
- "email",
- ],
}
`);
});
@@ -791,6 +779,8 @@ describe("tablesCompletionSource", () => {
const completionSource = completionStore.getCompletionSource(
"multi_db_engine" as ConnectionName,
);
+ // expect fully qualified 'database.schema.table' names
+ // as there is no default database
expect(completionSource?.schema).toMatchInlineSnapshot(`
{
"db1": {
@@ -807,17 +797,237 @@ describe("tablesCompletionSource", () => {
],
},
},
- "table1": [
- "col1",
- ],
- "table2": [
- "col2",
- ],
}
`);
expect(completionSource?.defaultTable).toBeUndefined();
});
+ it("should handle multiple databases and schemas with default", () => {
+ const mockConnection: DataSourceConnection = {
+ name: "multi_db_engine",
+ dialect: "postgres",
+ display_name: "postgres",
+ source: "postgres",
+ default_schema: "schema2",
+ default_database: "db1",
+ 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: "schema2",
+ tables: [
+ {
+ name: "table2",
+ source: "postgres",
+ source_type: "local",
+ type: "table",
+ columns: [
+ {
+ name: "col2",
+ 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: [],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ {
+ name: "db3",
+ 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(`
+ {
+ "db2": {
+ "schema2": {
+ "table2": [
+ "col2",
+ ],
+ },
+ },
+ "db3": {
+ "schema2": {
+ "table2": [
+ "col2",
+ ],
+ },
+ },
+ "schema1": {
+ "table1": [
+ "col1",
+ ],
+ },
+ "schema2": {
+ "table2": [
+ "col2",
+ ],
+ },
+ }
+ `);
+ expect(completionSource?.defaultTable).toBeUndefined();
+ expect(completionSource?.defaultSchema).toBe("schema2");
+ });
+
+ it("should handle default schema", () => {
+ const mockConnection: DataSourceConnection = {
+ name: "test_engine",
+ dialect: "postgres",
+ display_name: "postgres",
+ source: "postgres",
+ default_schema: "public",
+ default_database: "test_db",
+ 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: [],
+ },
+ {
+ name: "email",
+ 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 = "test_engine" as ConnectionName;
+ const completionSource = completionStore.getCompletionSource(
+ "test_engine" as ConnectionName,
+ );
+ expect(completionSource?.schema).toMatchInlineSnapshot(`
+ {
+ "public": {
+ "users": [
+ "id",
+ "name",
+ "email",
+ ],
+ },
+ }
+ `);
+ expect(completionSource?.defaultTable).toBe("users");
+ expect(completionSource?.defaultSchema).toBe("public");
+ });
+
it("should create a default table if there is only one table", () => {
const mockConnection: DataSourceConnection = {
name: "test_engine",
diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.ts
index ba2f0bd67a..78e9fd38e5 100644
--- a/frontend/src/core/codemirror/language/sql.ts
+++ b/frontend/src/core/codemirror/language/sql.ts
@@ -5,7 +5,6 @@ import {
sql,
StandardSQL,
schemaCompletionSource,
- type SQLNamespace,
MySQL,
PostgreSQL,
SQLite,
@@ -25,6 +24,7 @@ import { type QuotePrefixKind, upgradePrefixKind } from "./utils/quotes";
import { capabilitiesAtom } from "@/core/config/capabilities";
import { MarkdownLanguageAdapter } from "./markdown";
import {
+ dataConnectionsMapAtom,
dataSourceConnectionsAtom,
DEFAULT_ENGINE,
setLatestEngineSelected,
@@ -168,48 +168,61 @@ export class SQLLanguageAdapter implements LanguageAdapter {
}
}
+type TableToCols = Record<string, string[]>;
+type Schemas = Record<string, TableToCols>;
+
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);
+ const dataConnectionsMap = store.get(dataConnectionsMapAtom);
+ const connection = dataConnectionsMap.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[]> = {};
+ const schemaMap: Record<string, TableToCols> = {};
+ const databaseMap: Record<string, Schemas> = {};
+
+ // 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,
+ );
+
+ // 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;
+ }
+ }
+
+ // Otherwise, we need to use the fully qualified name
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) {
+ if (database.name === defaultDb?.name) {
+ continue;
+ }
+ databaseMap[database.name] = {};
+
+ for (const schema of database.schemas) {
+ databaseMap[database.name][schema.name] = {};
+
+ for (const table of schema.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;
+ databaseMap[database.name][schema.name][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,
+ schema: { ...databaseMap, ...schemaMap },
+ defaultSchema: connection.default_schema ?? undefined,
defaultTable: getSingleTable(connection),
};
this.cache.set(connection, cacheConfig);
diff --git a/frontend/src/core/datasets/__tests__/all-tables.test.ts b/frontend/src/core/datasets/__tests__/all-tables.test.ts
new file mode 100644
index 0000000000..0b441a785e
--- /dev/null
+++ b/frontend/src/core/datasets/__tests__/all-tables.test.ts
@@ -0,0 +1,371 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { datasetsAtom } from "../state";
+import {
+ allTablesAtom,
+ dataSourceConnectionsAtom,
+ DEFAULT_ENGINE,
+} from "../data-source-connections";
+import { store } from "@/core/state/jotai";
+import type { DatasetsState } from "../types";
+
+describe("allTablesAtom", () => {
+ beforeEach(() => {
+ // Reset the store before each test
+ store.set(datasetsAtom, {
+ tables: [],
+ } as unknown as DatasetsState);
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ databases: [],
+ }),
+ });
+ vi.clearAllMocks();
+ });
+
+ it("should return dataset tables when only datasets are present", () => {
+ // Set up test datasets
+ const testDatasets = [
+ {
+ name: "dataset1",
+ columns: [
+ { name: "col1", type: "number" },
+ { name: "col2", type: "string" },
+ ],
+ },
+ {
+ name: "dataset2",
+ columns: [
+ { name: "col3", type: "boolean" },
+ { name: "col4", type: "date" },
+ ],
+ },
+ ];
+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(2);
+ expect(tables.has("dataset1")).toBe(true);
+ expect(tables.has("dataset2")).toBe(true);
+ expect(tables.get("dataset1")).toEqual(testDatasets[0]);
+ expect(tables.get("dataset2")).toEqual(testDatasets[1]);
+ });
+
+ it("should return connection tables when only connections are present", () => {
+ // Set up test connections
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_schema: "main",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "main",
+ tables: [
+ { name: "table1", columns: [] },
+ { name: "table2", columns: [] },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(2);
+ expect(tables.has("table1")).toBe(true);
+ expect(tables.has("table2")).toBe(true);
+ expect(tables.get("table1")).toEqual({ name: "table1", columns: [] });
+ });
+
+ it("should use schema name when there is no default schema", () => {
+ // Set up test connection with no default schema
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "schema1",
+ tables: [{ name: "table1", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(1);
+ expect(tables.has("schema1.table1")).toBe(true);
+ });
+
+ it("should use default schema appropriately", () => {
+ // Set up test connection with a default schema
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_schema: "default_schema",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "default_schema",
+ tables: [
+ { name: "table1", columns: [] },
+ { name: "table2", columns: [] },
+ ],
+ },
+ {
+ name: "other_schema",
+ tables: [{ name: "table3", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(3);
+ expect(tables.has("table1")).toBe(true); // Using simple name due to default schema
+ expect(tables.has("table2")).toBe(true); // Using simple name due to default schema
+ expect(tables.has("other_schema.table3")).toBe(true); // Using schema-qualified name
+ });
+
+ it("should use fully qualified name when no default_database", () => {
+ // Set up test connections with colliding schema.table names in different databases
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "common_schema",
+ tables: [{ name: "common_table", columns: [] }],
+ },
+ ],
+ },
+ {
+ name: "db2",
+ schemas: [
+ {
+ name: "common_schema",
+ tables: [{ name: "common_table", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ const tables = store.get(allTablesAtom);
+
+ expect(tables.size).toBe(2);
+ expect(tables.has("db1.common_schema.common_table")).toBe(true);
+ expect(tables.has("db2.common_schema.common_table")).toBe(true);
+ });
+
+ it("should handle default database", () => {
+ // Set up test connection with a default database
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_database: "db1",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "main",
+ tables: [{ name: "table1", columns: [] }],
+ },
+ ],
+ },
+ {
+ name: "db2",
+ schemas: [
+ {
+ name: "main",
+ tables: [{ name: "table1", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(2);
+ expect(tables.has("main.table1")).toBe(true);
+ expect(tables.has("db2.main.table1")).toBe(true);
+ });
+
+ it("should handle multiple connections with progressive qualified names", () => {
+ const defaultConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ databases: [
+ {
+ name: "same_db",
+ schemas: [
+ {
+ name: "same_schema",
+ tables: [{ name: "same_table", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ const otherConnection = {
+ name: "other_engine",
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ databases: [
+ {
+ name: "same_db",
+ schemas: [
+ {
+ name: "same_schema",
+ tables: [{ name: "same_table", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map()
+ .set(DEFAULT_ENGINE, defaultConnection)
+ .set("other_engine", otherConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(2);
+ expect(tables.has("same_schema.same_table")).toBe(true);
+ expect(tables.has("same_db.same_schema.same_table")).toBe(true);
+ });
+
+ it("should handle both datasets and connection tables", () => {
+ // Set up test datasets
+ const testDatasets = [
+ { name: "dataset1", columns: [] },
+ { name: "table1", columns: [] }, // Intentional collision with connection table
+ ];
+ store.set(datasetsAtom, {
+ tables: testDatasets,
+ } as unknown as DatasetsState);
+
+ const connectionTables = [
+ { name: "table1", columns: [] }, // Collides with dataset
+ { name: "conn_table", columns: [] },
+ ];
+
+ // Set up test connection
+ const testConnection = {
+ name: DEFAULT_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_database: "db1",
+ default_schema: "main",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "main",
+ tables: connectionTables,
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DEFAULT_ENGINE,
+ connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results - dataset should take precedence
+ expect(tables.size).toBe(4);
+ expect(tables.has("dataset1")).toBe(true);
+ expect(tables.has("table1")).toBe(true); // Dataset takes precedence
+ expect(tables.get("table1")).toEqual(testDatasets[1]);
+
+ expect(tables.has("main.table1")).toBe(true); // Connection table gets schema-qualified
+ expect(tables.get("main.table1")).toEqual(connectionTables[0]);
+ expect(tables.has("conn_table")).toBe(true);
+ expect(tables.get("conn_table")).toEqual(connectionTables[1]);
+ });
+});
diff --git a/frontend/src/core/datasets/data-source-connections.ts b/frontend/src/core/datasets/data-source-connections.ts
index f0d87183a3..68e5e0d1c5 100644
--- a/frontend/src/core/datasets/data-source-connections.ts
+++ b/frontend/src/core/datasets/data-source-connections.ts
@@ -2,12 +2,15 @@
import { createReducerAndAtoms } from "@/utils/createReducer";
import type {
DataSourceConnection as DataSourceConnectionType,
+ DataTable,
SQLTablePreview,
} from "../kernel/messages";
import type { TypedString } from "@/utils/typed";
import type { VariableName } from "../variables/types";
import { atom } from "jotai";
import { store } from "../state/jotai";
+import { datasetTablesAtom } from "./state";
+import { Logger } from "@/utils/Logger";
export type ConnectionName = TypedString<"ConnectionName">;
@@ -141,3 +144,58 @@ export const exportedForTesting = {
export const tablePreviewsAtom = atom<ReadonlyMap<string, SQLTablePreview>>(
new Map<string, SQLTablePreview>(),
);
+
+// If you need to get table names from all connections & local datasets, use this atom
+// When a table name is used in multiple connections, we need to use a more qualified name
+export const allTablesAtom = atom((get) => {
+ const datasets = store.get(datasetTablesAtom);
+ const connections = get(dataSourceConnectionsAtom).connectionsMap;
+ const tableNames = new Map<string, DataTable>();
+
+ for (const dataset of datasets) {
+ tableNames.set(dataset.name, dataset);
+ }
+
+ for (const conn of connections.values()) {
+ for (const database of conn.databases) {
+ // If there is only one database, it is the default
+ const isDefaultDb =
+ database.name === conn.default_database || conn.databases.length === 1;
+
+ for (const schema of database.schemas) {
+ const isDefaultSchema = schema.name === conn.default_schema;
+
+ for (const table of schema.tables) {
+ let nameToSave: string;
+
+ // If the database and schema are default, we can use the table name directly
+ // Otherwise, we need to qualify the table name
+ // We also need to use the more qualified name if there are collisions
+ nameToSave = table.name;
+
+ if (isDefaultDb && isDefaultSchema && !tableNames.has(nameToSave)) {
+ tableNames.set(nameToSave, table);
+ continue;
+ }
+
+ nameToSave = `${schema.name}.${table.name}`;
+
+ if (isDefaultDb && !tableNames.has(nameToSave)) {
+ tableNames.set(nameToSave, table);
+ continue;
+ }
+
+ nameToSave = `${database.name}.${schema.name}.${table.name}`;
+
+ if (tableNames.has(nameToSave)) {
+ Logger.warn(`Table name collision for ${nameToSave}. Skipping.`);
+ } else {
+ tableNames.set(nameToSave, table);
+ }
+ }
+ }
+ }
+ }
+
+ return tableNames;
+});
diff --git a/marimo/_data/models.py b/marimo/_data/models.py
index 112ded7878..4efd2c862e 100644
--- a/marimo/_data/models.py
+++ b/marimo/_data/models.py
@@ -141,6 +141,8 @@ class DataSourceConnection:
name (str): The name of the data source connection. E.g 'engine'.
display_name (str): The display name of the data source connection. E.g 'PostgresQL (engine)'.
databases (List[Database]): The databases in the data source connection.
+ default_database (Optional[str]): The default database in the data source connection.
+ default_schema (Optional[str]): The default schema in the data source connection.
"""
source: str
@@ -148,3 +150,5 @@ class DataSourceConnection:
name: str
display_name: str
databases: list[Database] = field(default_factory=list)
+ default_database: Optional[str] = None
+ default_schema: Optional[str] = None
diff --git a/marimo/_sql/engines.py b/marimo/_sql/engines.py
index 7789b1b97a..d0c07efa4a 100644
--- a/marimo/_sql/engines.py
+++ b/marimo/_sql/engines.py
@@ -79,6 +79,32 @@ class DuckDBEngine(SQLEngine):
return isinstance(var, duckdb.DuckDBPyConnection)
+ def get_current_database(self) -> Optional[str]:
+ try:
+ import duckdb
+
+ connection = self._connection or duckdb
+ row = connection.sql("SELECT CURRENT_DATABASE()").fetchone()
+ if row is not None and row[0] is not None:
+ return str(row[0])
+ return None
+ except Exception:
+ LOGGER.info("Failed to get current database")
+ return None
+
+ def get_current_schema(self) -> Optional[str]:
+ try:
+ import duckdb
+
+ connection = self._connection or duckdb
+ row = connection.sql("SELECT CURRENT_SCHEMA()").fetchone()
+ if row is not None and row[0] is not None:
+ return str(row[0])
+ return None
+ except Exception:
+ LOGGER.info("Failed to get current schema")
+ return None
+
def get_databases(self) -> list[Database]:
"""Fetch all databases from the engine. At the moment, will fetch everything."""
return get_databases_from_duckdb(self._connection, self._engine_name)
@@ -95,12 +121,16 @@ class SQLAlchemyEngine(SQLEngine):
self._engine = engine
self._engine_name = engine_name
self.inspector: Optional[Inspector] = None
+
try:
self.inspector = inspect(self._engine)
except Exception:
LOGGER.warning("Failed to create inspector", exc_info=True)
self.inspector = None
+ self.default_database = self._get_current_database()
+ self.default_schema = self._get_default_schema()
+
@property
def source(self) -> str:
return str(self._engine.dialect.name)
@@ -155,34 +185,63 @@ class SQLAlchemyEngine(SQLEngine):
# Maybe in future we can enable this as a flag or for certain connection types.
return False
- def get_database_name(self) -> Optional[str]:
- """Get the current database name."""
+ def _get_current_database(self) -> Optional[str]:
+ """Get the current database name.
- from sqlalchemy import text
+ Returns:
+ - The database name from the connection URL if available
+ - The database name queried from the database if URL doesn't contain it
+ - An empty string if the connection is detached but valid
+ - None if the connection is invalid
+ """
- if self._engine.url.database is not None:
- return self._engine.url.database
+ from sqlalchemy import text
- # If there is no database name, the engine may connect to a default database.
- # which may not show up in the url
try:
- query: str
- if self.dialect in ("postgresql"):
- query = "SELECT current_database()"
- elif self.dialect in ("mssql"):
- query = "SELECT DB_NAME()"
- if query is None:
+ if self._engine.url.database is not None:
+ return self._engine.url.database
+ except Exception:
+ LOGGER.warning("Connection URL is invalid", exc_info=True)
+ return None
+
+ database_name: Optional[str] = None
+ dialect_queries = {
+ "postgresql": "SELECT current_database()",
+ "mssql": "SELECT DB_NAME()",
+ }
+
+ # Try to get the database name by querying the database directly
+ if query := dialect_queries.get(self.dialect):
+ try:
+ with self._engine.connect() as connection:
+ rows = connection.execute(text(query)).fetchone()
+ if rows is not None and rows[0] is not None:
+ database_name = str(rows[0])
+ except Exception:
+ LOGGER.warning(
+ "Failed to get current database name", exc_info=True
+ )
+
+ # If database_name is None, the connection might be detached or invalid.
+ # We check for existing schemas to verify the connection's validity.
+ if database_name is None:
+ schemas_found = self._get_schemas(
+ include_tables=False, include_table_details=False
+ )
+ if not schemas_found:
return None
- with self._engine.connect() as connection:
- rows = connection.execute(text(query)).fetchone()
- if rows is None or rows[0] is None:
- return None
- return str(rows[0])
+ return database_name or ""
+
+ def _get_default_schema(self) -> Optional[str]:
+ """Get the default schema name"""
+ if self.inspector is None:
+ return None
+
+ try:
+ return self.inspector.default_schema_name
except Exception:
- LOGGER.warning(
- "Failed to get current database name", exc_info=True
- )
+ LOGGER.warning("Failed to get default schema name", exc_info=True)
return None
def get_databases(
@@ -205,18 +264,10 @@ class SQLAlchemyEngine(SQLEngine):
Note: This operation can be performance intensive when fetching full metadata.
"""
databases: list[Database] = []
- database_name = self.get_database_name()
- # If database_name is None, the connection might be detached or invalid.
- # We check for existing schemas to verify the connection's validity.
- # If valid, set database_name to an empty string to indicate it's detached.
- if database_name is None:
- schemas_found = self._get_schemas(
- include_tables=False, include_table_details=False
- )
- if not schemas_found:
- return []
- database_name = ""
+ if self.default_database is None:
+ return databases
+ database_name = self.default_database
schemas = (
self._get_schemas(
diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.py
index de0cc834ce..c2851d94ad 100644
--- a/marimo/_sql/get_engines.py
+++ b/marimo/_sql/get_engines.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, cast
+from typing import Any, Optional, cast
from marimo import _loggers
from marimo._config.config import DatasourcesConfig
@@ -52,8 +52,13 @@ def engine_to_data_source_connection(
engine: SQLEngine,
) -> DataSourceConnection:
databases: list[Database] = []
+ default_database: Optional[str] = None
+ default_schema: Optional[str] = None
+
if isinstance(engine, SQLAlchemyEngine):
config = get_datasources_config()
+ default_database = engine.default_database
+ default_schema = engine.default_schema
databases = engine.get_databases(
include_schemas=config.get("auto_discover_schemas", True),
include_tables=config.get("auto_discover_tables", False),
@@ -61,6 +66,8 @@ def engine_to_data_source_connection(
)
elif isinstance(engine, DuckDBEngine):
databases = engine.get_databases()
+ default_database = engine.get_current_database()
+ default_schema = engine.get_current_schema()
else:
LOGGER.warning(
f"Unsupported engine type: {type(engine)}. Unable to get databases for {variable_name}."
@@ -78,6 +85,8 @@ def engine_to_data_source_connection(
name=variable_name,
display_name=display_name,
databases=databases,
+ default_database=default_database,
+ default_schema=default_schema,
)
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 722ec344ce..52d57eb072 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -412,6 +412,12 @@ components:
- schemas
type: object
type: array
+ default_database:
+ nullable: true
+ type: string
+ default_schema:
+ nullable: true
+ type: string
dialect:
type: string
display_name:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 93fd063b24..96ed5b4e6d 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2272,6 +2272,8 @@ export interface components {
tables: components["schemas"]["DataTable"][];
}[];
}[];
+ default_database?: string | null;
+ default_schema?: string | null;
dialect: string;
display_name: string;
name: string;
diff --git a/tests/_sql/test_duckdb.py b/tests/_sql/test_duckdb.py
index d9af35dd29..d3ce7fcdb6 100644
--- a/tests/_sql/test_duckdb.py
+++ b/tests/_sql/test_duckdb.py
@@ -133,6 +133,8 @@ def test_duckdb_engine_get_databases_no_conn() -> None:
engine = DuckDBEngine()
initial_databases = engine.get_databases()
assert initial_databases == []
+ assert engine.get_current_database() == "memory"
+ assert engine.get_current_schema() == "main"
engine.execute(
"CREATE TABLE test (id INTEGER PRIMARY KEY, name VARCHAR(255))"
@@ -156,3 +158,24 @@ def test_duckdb_engine_get_databases_no_conn() -> None:
assert databases == expected_databases
engine.execute("DROP TABLE test")
+
+
[email protected](not HAS_DUCKDB, reason="duckdb not installed")
+def test_get_current_database_schema() -> None:
+ import duckdb
+
+ engine = duckdb.connect(":memory:")
+ duckdb_engine = DuckDBEngine(engine)
+
+ assert duckdb_engine.get_current_database() == "memory"
+ assert duckdb_engine.get_current_schema() == "main"
+
+ sql("CREATE SCHEMA test_schema;", engine=engine)
+ sql("CREATE TABLE test_schema.test_table (id INTEGER);", engine=engine)
+ sql("USE test_schema;", engine=engine)
+
+ assert duckdb_engine.get_current_database() == "memory"
+ assert duckdb_engine.get_current_schema() == "test_schema"
+
+ sql("DROP TABLE test_schema.test_table;", engine=engine)
+ sql("DROP SCHEMA test_schema;", engine=engine)
diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.py
index 3726529308..2a3f9d0a3a 100644
--- a/tests/_sql/test_get_engines.py
+++ b/tests/_sql/test_get_engines.py
@@ -38,6 +38,8 @@ def test_engine_to_data_source_connection() -> None:
assert connection.dialect == "duckdb"
assert connection.name == "my_duckdb"
assert connection.display_name == "duckdb (my_duckdb)"
+ assert connection.default_database == "memory"
+ assert connection.default_schema == "main"
assert connection.databases == []
# Test with SQLAlchemy engine
@@ -75,14 +77,10 @@ def test_get_engines_from_variables_duckdb():
def test_get_engines_from_variables_sqlalchemy() -> None:
import sqlalchemy as sa
- mock_sqlalchemy_engine = MagicMock(spec=sa.Engine)
-
- variables: list[tuple[str, object]] = [
- ("sa_engine", mock_sqlalchemy_engine)
- ]
+ sqlalchemy_engine = sa.create_engine("sqlite:///:memory:")
+ variables: list[tuple[str, object]] = [("sa_engine", sqlalchemy_engine)]
- with patch("sqlalchemy.inspect", return_value=MagicMock()):
- engines = get_engines_from_variables(variables)
+ engines = get_engines_from_variables(variables)
assert len(engines) == 1
var_name, engine = engines[0]
@@ -109,16 +107,15 @@ def test_get_engines_from_variables_multiple():
import sqlalchemy as sa
mock_duckdb_conn = MagicMock(spec=duckdb.DuckDBPyConnection)
- mock_sqlalchemy_engine = MagicMock(spec=sa.Engine)
+ sqlalchemy_engine = sa.create_engine("sqlite:///:memory:")
variables: list[tuple[str, object]] = [
- ("sa_engine", mock_sqlalchemy_engine),
+ ("sa_engine", sqlalchemy_engine),
("duckdb_conn", mock_duckdb_conn),
("not_an_engine", "some string"),
]
- with patch("sqlalchemy.inspect", return_value=MagicMock()):
- engines = get_engines_from_variables(variables)
+ engines = get_engines_from_variables(variables)
assert len(engines) == 2
@@ -154,6 +151,8 @@ def test_get_engines_duckdb_databases() -> None:
assert connection.dialect == "duckdb"
assert connection.name == "my_duckdb"
assert connection.display_name == "duckdb (my_duckdb)"
+ assert connection.default_database == "memory"
+ assert connection.default_schema == "main"
sql("CREATE TABLE test_table (id INTEGER);")
@@ -194,6 +193,8 @@ def test_get_engines_sqlalchemy_databases() -> None:
assert connection.dialect == "sqlite"
assert connection.name == "sqlite"
assert connection.display_name == "sqlite (sqlite)"
+ assert connection.default_database == ":memory:"
+ assert connection.default_schema == "main"
assert connection.databases == [
Database(
diff --git a/tests/_sql/test_sqlalchemy.py b/tests/_sql/test_sqlalchemy.py
index 1f49ba57c4..7393c986c8 100644
--- a/tests/_sql/test_sqlalchemy.py
+++ b/tests/_sql/test_sqlalchemy.py
@@ -94,6 +94,8 @@ def test_sqlalchemy_invalid_engine() -> None:
engine = SQLAlchemyEngine(engine=None) # type: ignore
assert engine.inspector is None
+ assert engine.default_database is None
+ assert engine.default_schema is None
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
@@ -460,10 +462,10 @@ def test_sqlalchemy_engine_execute(sqlite_engine: sa.Engine) -> None:
def test_sqlalchemy_get_database_name(sqlite_engine: sa.Engine) -> None:
"""Test SQLAlchemyEngine get_database_name."""
engine = SQLAlchemyEngine(sqlite_engine)
- assert engine.get_database_name() == ":memory:"
+ assert engine._get_current_database() == ":memory:"
import sqlalchemy as sa
# Test with no database name
engine = SQLAlchemyEngine(sa.create_engine("sqlite:///"))
- assert engine.get_database_name() == ""
+ assert engine._get_current_database() == ""