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.

feat: add clickhouse connect & chdb (#4185)

Shahmir Varqha4e6a62aed20f
diff --git a/frontend/src/components/datasources/__tests__/utils.test.ts b/frontend/src/components/datasources/__tests__/utils.test.ts
index d87e56eea7..c2e32bc6c1 100644
--- a/frontend/src/components/datasources/__tests__/utils.test.ts
+++ b/frontend/src/components/datasources/__tests__/utils.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import {
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
type SQLTableContext,
} from "@/core/datasets/data-source-connections";
import type { DataTable, DataTableColumn } from "@/core/kernel/messages";
@@ -28,7 +28,7 @@ describe("sqlCode", () => {
it("should generate SQL with default schema", () => {
const sqlTableContext: SQLTableContext = {
- engine: DEFAULT_ENGINE,
+ engine: DUCKDB_ENGINE,
schema: "public",
defaultSchema: "public",
defaultDatabase: "mydb",
@@ -41,7 +41,7 @@ describe("sqlCode", () => {
it("should generate SQL with non-default schema", () => {
const sqlTableContext: SQLTableContext = {
- engine: DEFAULT_ENGINE,
+ engine: DUCKDB_ENGINE,
schema: "analytics",
defaultSchema: "public",
defaultDatabase: "mydb",
@@ -86,7 +86,7 @@ describe("sqlCode", () => {
it("should generate SQL with non-default database", () => {
const sqlTableContext: SQLTableContext = {
- engine: DEFAULT_ENGINE,
+ engine: DUCKDB_ENGINE,
schema: "public",
defaultSchema: "public",
defaultDatabase: "memory",
@@ -113,4 +113,28 @@ describe("sqlCode", () => {
'_df = mo.sql(f"SELECT email FROM remote.sales.users LIMIT 100", engine=bigquery)',
);
});
+
+ it("should generate SQL for schemaless tables", () => {
+ const sqlTableContext: SQLTableContext = {
+ engine: DUCKDB_ENGINE,
+ schema: "",
+ defaultDatabase: "mydb",
+ database: "mydb",
+ };
+
+ const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);
+ expect(result).toBe('_df = mo.sql(f"SELECT email FROM users LIMIT 100")');
+
+ const sqlTableContext2: SQLTableContext = {
+ engine: DUCKDB_ENGINE,
+ schema: "",
+ defaultDatabase: "remote",
+ database: "another_db",
+ };
+
+ const result2 = sqlCode(mockTable, mockColumn.name, sqlTableContext2);
+ expect(result2).toBe(
+ '_df = mo.sql(f"SELECT email FROM another_db.users LIMIT 100")',
+ );
+ });
});
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index c54dbe7455..f5a4ebc339 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -56,7 +56,7 @@ import { dbDisplayName } from "@/components/databases/display";
import { AddDatabaseDialog } from "../editor/database/add-database-form";
import {
dataConnectionsMapAtom,
- DEFAULT_ENGINE,
+ INTERNAL_SQL_ENGINES,
type SQLTableContext,
useDataSourceActions,
} from "@/core/datasets/data-source-connections";
@@ -74,7 +74,7 @@ import {
RotatingChevron,
} from "./components";
import { InstallPackageButton } from "./install-package-button";
-import { sqlCode } from "./utils";
+import { isSchemaless, sqlCode } from "./utils";
import { useOnMount } from "@/hooks/useLifecycle";
const sortedTablesAtom = atom((get) => {
@@ -105,16 +105,18 @@ const sortedTablesAtom = atom((get) => {
const connectionsAtom = atom((get) => {
const dataConnections = new Map(get(dataConnectionsMapAtom));
- const defaultEngine = dataConnections.get(DEFAULT_ENGINE);
- // Filter out the internal duckdb engine if it has no databases
- if (defaultEngine && defaultEngine.databases.length === 0) {
- dataConnections.delete(DEFAULT_ENGINE);
+ // Filter out the internal engines if it has no databases
+ for (const engine of INTERNAL_SQL_ENGINES) {
+ const connection = dataConnections.get(engine);
+ if (connection && connection.databases.length === 0) {
+ dataConnections.delete(engine);
+ }
}
- // Sort by name, but put the default engine at the top
+ // Put internal engines last to prioritize user-defined connections
return sortBy([...dataConnections.values()], (connection) =>
- connection.name === DEFAULT_ENGINE ? "" : connection.name,
+ INTERNAL_SQL_ENGINES.has(connection.name) ? 1 : 0,
);
});
@@ -367,6 +369,10 @@ const SchemaItem: React.FC<{
setIsExpanded(hasSearch);
}, [hasSearch]);
+ if (isSchemaless(schema.name)) {
+ return children;
+ }
+
return (
<>
<CommandItem
@@ -598,7 +604,8 @@ const DatasetTableItem: React.FC<{
<CommandItem
className={cn(
"rounded-none group h-8 cursor-pointer",
- sqlTableContext && "pl-12",
+ sqlTableContext &&
+ (isSchemaless(sqlTableContext.schema) ? "pl-9" : "pl-12"),
(isExpanded || isSearching) && "font-semibold",
)}
value={uniqueId}
diff --git a/frontend/src/components/datasources/utils.ts b/frontend/src/components/datasources/utils.ts
index cb9dbb5a76..2282a4ea95 100644
--- a/frontend/src/components/datasources/utils.ts
+++ b/frontend/src/components/datasources/utils.ts
@@ -1,10 +1,15 @@
/* Copyright 2024 Marimo. All rights reserved. */
import {
type SQLTableContext,
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
} from "@/core/datasets/data-source-connections";
import type { DataTable } from "@/core/kernel/messages";
+// Some databases have no schemas, so we don't show it (eg. Clickhouse)
+export function isSchemaless(schemaName: string) {
+ return schemaName === "";
+}
+
export function sqlCode(
table: DataTable,
columnName: string,
@@ -15,16 +20,23 @@ export function sqlCode(
sqlTableContext;
let tableName = table.name;
- // If the schema is not the default schema, we need to include the schema in the table name
- if (schema !== defaultSchema) {
- tableName = `${schema}.${tableName}`;
- }
- // If the database is not the default database, we need to include the database in the table name
- if (database !== defaultDatabase) {
- tableName = `${database}.${tableName}`;
+ // Set the fully qualified table name based on schema and database
+ if (isSchemaless(schema)) {
+ tableName =
+ database === defaultDatabase ? tableName : `${database}.${tableName}`;
+ } else {
+ // Include schema if it's not the default schema
+ if (schema !== defaultSchema) {
+ tableName = `${schema}.${tableName}`;
+ }
+
+ // Include database if it's not the default database
+ if (database !== defaultDatabase) {
+ tableName = `${database}.${tableName}`;
+ }
}
- if (engine === DEFAULT_ENGINE) {
+ if (engine === DUCKDB_ENGINE) {
return `_df = mo.sql(f"SELECT ${columnName} FROM ${tableName} 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 f242ea6ad2..e2bdcb6ac4 100644
--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
@@ -7,7 +7,7 @@ import { store } from "@/core/state/jotai";
import type { DatasetsState } from "@/core/datasets/types";
import {
dataSourceConnectionsAtom,
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
} from "@/core/datasets/data-source-connections";
// Mock getCodes function
@@ -22,7 +22,7 @@ describe("getAICompletionBody", () => {
tables: [],
} as unknown as DatasetsState);
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
+ latestEngineSelected: DUCKDB_ENGINE,
connectionsMap: new Map(),
});
(getCodes as Mock).mockReturnValue("// Some other code");
@@ -161,7 +161,7 @@ describe("getAICompletionBody", () => {
it("should handle connections", () => {
// Set up test data in the Jotai store
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -186,8 +186,8 @@ describe("getAICompletionBody", () => {
],
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
const input = "Use @table1 for analysis";
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index d22ee0f121..db62be4d1c 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -4,7 +4,7 @@ import { SQLCompletionStore, SQLLanguageAdapter } from "../sql";
import { store } from "@/core/state/jotai";
import {
dataSourceConnectionsAtom,
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
type ConnectionName,
} from "@/core/datasets/data-source-connections";
import type { DataSourceConnection } from "@/core/kernel/messages";
@@ -15,7 +15,7 @@ const adapter = new SQLLanguageAdapter();
describe("SQLLanguageAdapter", () => {
describe("transformIn", () => {
afterAll(() => {
- adapter.engine = DEFAULT_ENGINE;
+ adapter.engine = DUCKDB_ENGINE;
adapter.showOutput = true;
});
@@ -239,7 +239,7 @@ _df = mo.sql(
describe("transformOut", () => {
afterEach(() => {
- adapter.engine = DEFAULT_ENGINE;
+ adapter.engine = DUCKDB_ENGINE;
adapter.showOutput = true;
adapter.dataframeName = "_df";
});
@@ -473,8 +473,8 @@ _df = mo.sql(
dialect: "mysql",
databases: [],
})
- .set(DEFAULT_ENGINE, {
- name: DEFAULT_ENGINE,
+ .set(DUCKDB_ENGINE, {
+ name: DUCKDB_ENGINE,
source: "duckdb",
display_name: "DuckDB",
dialect: "duckdb",
@@ -487,7 +487,7 @@ _df = mo.sql(
});
it("should use default engine initially", () => {
- expect(adapter.engine).toBe(DEFAULT_ENGINE);
+ expect(adapter.engine).toBe(DUCKDB_ENGINE);
});
it("should persist the selected engine", () => {
@@ -525,7 +525,7 @@ _df = mo.sql(
// Don't update for unspecified engine
const pythonCode2 = '_df = mo.sql("""SELECT 1""")';
adapter.transformIn(pythonCode2);
- expect(adapter.engine).toBe(DEFAULT_ENGINE);
+ expect(adapter.engine).toBe(DUCKDB_ENGINE);
expect(store.get(dataSourceConnectionsAtom).latestEngineSelected).toBe(
"postgres_engine",
);
@@ -566,11 +566,11 @@ _df = mo.sql(
it("should restore previous engine when selecting default", () => {
const engine = "postgres_engine" as ConnectionName;
adapter.selectEngine(engine);
- adapter.selectEngine(DEFAULT_ENGINE);
+ adapter.selectEngine(DUCKDB_ENGINE);
- expect(adapter.engine).toBe(DEFAULT_ENGINE);
+ expect(adapter.engine).toBe(DUCKDB_ENGINE);
expect(store.get(dataSourceConnectionsAtom).latestEngineSelected).toBe(
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
);
});
});
@@ -585,7 +585,7 @@ _df = mo.sql(
});
it("should not include engine in getDefaultCode when using default engine", () => {
- adapter.selectEngine(DEFAULT_ENGINE);
+ adapter.selectEngine(DUCKDB_ENGINE);
expect(adapter.getDefaultCode()).toBe(
`_df = mo.sql(f"""SELECT * FROM """)`,
);
@@ -599,13 +599,13 @@ describe("tablesCompletionSource", () => {
beforeEach(() => {
// Reset the adapter engine
- adapter.engine = DEFAULT_ENGINE;
+ adapter.engine = DUCKDB_ENGINE;
});
it("should return null if connection not found", () => {
mockStore.set(dataSourceConnectionsAtom, {
connectionsMap: new Map(),
- latestEngineSelected: DEFAULT_ENGINE,
+ latestEngineSelected: DUCKDB_ENGINE,
});
const completionSource = completionStore.getCompletionSource(
@@ -1083,4 +1083,93 @@ describe("tablesCompletionSource", () => {
expect(completionSource?.defaultTable).toBe("users");
expect(completionSource?.dialect).toBe(PostgreSQL);
});
+
+ it("should handle schemaless databases", () => {
+ const mockConnection: DataSourceConnection = {
+ name: "test_engine",
+ dialect: "postgres",
+ display_name: "postgres",
+ default_database: "test_db",
+ source: "postgres",
+ databases: [
+ {
+ name: "test_db",
+ dialect: "postgres",
+ schemas: [
+ {
+ name: "", // lack of name indicates schemaless
+ tables: [
+ {
+ name: "users",
+ source: "postgres",
+ source_type: "local",
+ type: "table",
+ columns: [
+ {
+ name: "id",
+ external_type: "string",
+ type: "string",
+ sample_values: [],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ {
+ name: "test_db2",
+ dialect: "postgres",
+ schemas: [
+ {
+ name: "",
+ tables: [
+ {
+ name: "orders",
+ source: "postgres",
+ source_type: "local",
+ type: "table",
+ columns: [
+ {
+ name: "order_id",
+ 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?.defaultTable).toBe(undefined);
+ expect(completionSource?.dialect).toBe(PostgreSQL);
+ expect(completionSource?.schema).toMatchInlineSnapshot(`
+ {
+ "test_db2": {
+ "orders": [
+ "order_id",
+ ],
+ },
+ "users": [
+ "id",
+ ],
+ }
+ `);
+ });
});
diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsx
index 861a67ca96..e8b2d9a1f5 100644
--- a/frontend/src/core/codemirror/language/panel.tsx
+++ b/frontend/src/core/codemirror/language/panel.tsx
@@ -7,6 +7,7 @@ import { useAutoGrowInputProps } from "@/hooks/useAutoGrowInputProps";
import {
type ConnectionName,
dataConnectionsMapAtom,
+ INTERNAL_SQL_ENGINES,
} from "@/core/datasets/data-source-connections";
import { useAtomValue } from "jotai";
import { AlertCircle, CircleHelpIcon } from "lucide-react";
@@ -23,6 +24,7 @@ import {
import { DatabaseLogo } from "@/components/databases/icon";
import { transformDisplayName } from "@/components/databases/display";
import { useNonce } from "@/hooks/useNonce";
+import type { DataSourceConnection } from "@/core/kernel/messages";
export const LanguagePanelComponent: React.FC<{
view: EditorView;
@@ -116,6 +118,14 @@ const SQLEngineSelect: React.FC<SelectProps> = ({
}) => {
const connectionsMap = useAtomValue(dataConnectionsMapAtom);
+ const internalEngineConnections: DataSourceConnection[] = [];
+ const userDefinedConnections: DataSourceConnection[] = [];
+ for (const [connName, connection] of connectionsMap.entries()) {
+ INTERNAL_SQL_ENGINES.has(connName)
+ ? internalEngineConnections.push(connection)
+ : userDefinedConnections.push(connection);
+ }
+
// Use nonce to force re-render as languageAdapter.engine may not trigger change
// If it's disconnected, we display the engine variable.
const selectedEngine = languageAdapter.engine;
@@ -138,6 +148,19 @@ const SQLEngineSelect: React.FC<SelectProps> = ({
}
};
+ const renderConnections = (connections: DataSourceConnection[]) => {
+ return connections.map((connection) => (
+ <SelectItem key={connection.name} value={connection.name}>
+ <div className="flex items-center gap-1">
+ <DatabaseLogo className="h-3 w-3" name={connection.source} />
+ <span className="truncate">
+ {transformDisplayName(connection.display_name)}
+ </span>
+ </div>
+ </SelectItem>
+ ));
+ };
+
return (
<div className="flex flex-row gap-1 items-center">
<Select value={selectedEngine} onValueChange={handleSelectEngine}>
@@ -157,16 +180,10 @@ const SQLEngineSelect: React.FC<SelectProps> = ({
</div>
</SelectItem>
)}
- {[...connectionsMap.entries()].map(([key, value]) => (
- <SelectItem key={key} value={value.name}>
- <div className="flex items-center gap-1">
- <DatabaseLogo className="h-3 w-3" name={value.source} />
- <span className="truncate">
- {transformDisplayName(value.display_name)}
- </span>
- </div>
- </SelectItem>
- ))}
+ {/* Prioritize showing user-defined connections */}
+ {renderConnections(userDefinedConnections)}
+ {userDefinedConnections.length > 0 && <SelectSeparator />}
+ {renderConnections(internalEngineConnections)}
<SelectSeparator />
<SelectItem className="text-muted-foreground" value={HELP_KEY}>
<a
diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.ts
index 49d39e8416..621b464f77 100644
--- a/frontend/src/core/codemirror/language/sql.ts
+++ b/frontend/src/core/codemirror/language/sql.ts
@@ -16,7 +16,7 @@ import { MarkdownLanguageAdapter } from "./markdown";
import {
dataConnectionsMapAtom,
dataSourceConnectionsAtom,
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
setLatestEngineSelected,
type ConnectionName,
} from "@/core/datasets/data-source-connections";
@@ -34,9 +34,11 @@ import {
PostgreSQL,
MySQL,
SQLite,
+ MSSQL,
} from "@codemirror/lang-sql";
import { LRUCache } from "@/utils/lru";
import type { DataSourceConnection } from "@/core/kernel/messages";
+import { isSchemaless } from "@/components/datasources/utils";
/**
* Language adapter for SQL.
@@ -44,6 +46,7 @@ import type { DataSourceConnection } from "@/core/kernel/messages";
export class SQLLanguageAdapter implements LanguageAdapter {
readonly type = "sql";
readonly defaultCode = `_df = mo.sql(f"""SELECT * FROM """)`;
+ readonly defaultEngine = DUCKDB_ENGINE;
static fromQuery = (query: string) => `_df = mo.sql(f"""${query.trim()}""")`;
dataframeName = "_df";
@@ -53,7 +56,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
engine = store.get(dataSourceConnectionsAtom).latestEngineSelected;
getDefaultCode(): string {
- if (this.engine === DEFAULT_ENGINE) {
+ if (this.engine === this.defaultEngine) {
return this.defaultCode;
}
return `_df = mo.sql(f"""SELECT * FROM """, engine=${this.engine})`;
@@ -84,9 +87,10 @@ export class SQLLanguageAdapter implements LanguageAdapter {
if (sqlStatement) {
this.dataframeName = sqlStatement.dfName;
this.showOutput = sqlStatement.output ?? true;
- this.engine = (sqlStatement.engine as ConnectionName) ?? DEFAULT_ENGINE;
+ this.engine =
+ (sqlStatement.engine as ConnectionName) ?? this.defaultEngine;
- if (this.engine !== DEFAULT_ENGINE) {
+ if (this.engine !== this.defaultEngine) {
// User selected a new engine, set it as latest.
// This makes new SQL statements use the new engine by default.
setLatestEngineSelected(this.engine);
@@ -123,7 +127,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
const showOutputParam = this.showOutput ? "" : ",\n output=False";
const engineParam =
- this.engine === DEFAULT_ENGINE ? "" : `,\n engine=${this.engine}`;
+ this.engine === this.defaultEngine ? "" : `,\n engine=${this.engine}`;
const end = `\n """${showOutputParam}${engineParam}\n)`;
return [
@@ -200,6 +204,13 @@ export class SQLCompletionStore {
const schemaMap: Record<string, TableToCols> = {};
const databaseMap: Record<string, Schemas> = {};
+ const baseConfig: SQLConfig = {
+ dialect: guessDialect(connection),
+ schema: schemaMap,
+ defaultSchema: connection.default_schema ?? undefined,
+ defaultTable: getSingleTable(connection),
+ };
+
// When there is only one database, it is the default
const defaultDb = connection.databases.find(
(db) =>
@@ -207,6 +218,43 @@ export class SQLCompletionStore {
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;
+ }
+ }
+ }
+ }
+
+ cacheConfig = {
+ ...baseConfig,
+ schema: dbToTablesMap,
+ defaultSchema: defaultDb?.name,
+ };
+ return cacheConfig;
+ }
+
// For default db, we can use the schema name directly
for (const schema of defaultDb?.schemas ?? []) {
schemaMap[schema.name] = {};
@@ -234,10 +282,9 @@ export class SQLCompletionStore {
}
cacheConfig = {
- dialect: guessDialect(connection),
+ ...baseConfig,
schema: { ...databaseMap, ...schemaMap },
defaultSchema: connection.default_schema ?? undefined,
- defaultTable: getSingleTable(connection),
};
this.cache.set(connection, cacheConfig);
}
@@ -287,6 +334,9 @@ function guessDialect(
return MySQL;
case "sqlite":
return SQLite;
+ case "mssql":
+ case "sqlserver":
+ return MSSQL;
default:
return undefined;
}
diff --git a/frontend/src/core/datasets/__tests__/all-tables.test.ts b/frontend/src/core/datasets/__tests__/all-tables.test.ts
index 0b441a785e..28afbffc41 100644
--- a/frontend/src/core/datasets/__tests__/all-tables.test.ts
+++ b/frontend/src/core/datasets/__tests__/all-tables.test.ts
@@ -5,7 +5,7 @@ import { datasetsAtom } from "../state";
import {
allTablesAtom,
dataSourceConnectionsAtom,
- DEFAULT_ENGINE,
+ DUCKDB_ENGINE,
} from "../data-source-connections";
import { store } from "@/core/state/jotai";
import type { DatasetsState } from "../types";
@@ -17,9 +17,9 @@ describe("allTablesAtom", () => {
tables: [],
} as unknown as DatasetsState);
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, {
- name: DEFAULT_ENGINE,
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, {
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -63,7 +63,7 @@ describe("allTablesAtom", () => {
it("should return connection tables when only connections are present", () => {
// Set up test connections
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -85,8 +85,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
// Get tables from the atom
@@ -102,7 +102,7 @@ describe("allTablesAtom", () => {
it("should use schema name when there is no default schema", () => {
// Set up test connection with no default schema
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -120,8 +120,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
// Get tables from the atom
@@ -135,7 +135,7 @@ describe("allTablesAtom", () => {
it("should use default schema appropriately", () => {
// Set up test connection with a default schema
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -161,8 +161,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
// Get tables from the atom
@@ -178,7 +178,7 @@ describe("allTablesAtom", () => {
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,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -205,8 +205,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
const tables = store.get(allTablesAtom);
@@ -219,7 +219,7 @@ describe("allTablesAtom", () => {
it("should handle default database", () => {
// Set up test connection with a default database
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -247,8 +247,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
// Get tables from the atom
@@ -260,9 +260,104 @@ describe("allTablesAtom", () => {
expect(tables.has("db2.main.table1")).toBe(true);
});
+ it("should handle schemaless databases", () => {
+ // Set up test connection with a schemaless database
+ const testConnection = {
+ name: DUCKDB_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_database: "db1",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "",
+ tables: [{ name: "table1", columns: [] }],
+ },
+ ],
+ },
+ {
+ name: "db2",
+ schemas: [
+ {
+ name: "",
+ tables: [{ name: "table2", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(2);
+ expect(tables.get("table1")).toEqual({ name: "table1", columns: [] });
+ expect(tables.get("db2.table2")).toEqual({ name: "table2", columns: [] });
+ });
+
+ it("should handle mixed schemaless and schema databases", () => {
+ const testConnection = {
+ name: DUCKDB_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB In-Memory",
+ default_database: "db1",
+ databases: [
+ {
+ name: "db1",
+ schemas: [
+ {
+ name: "central",
+ tables: [{ name: "table1", columns: [] }],
+ },
+ {
+ name: "main",
+ tables: [{ name: "table2", columns: [] }],
+ },
+ ],
+ },
+ {
+ name: "db2",
+ schemas: [
+ {
+ name: "",
+ tables: [{ name: "table3", columns: [] }],
+ },
+ ],
+ },
+ ],
+ };
+
+ store.set(dataSourceConnectionsAtom, {
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
+ });
+
+ // Get tables from the atom
+ const tables = store.get(allTablesAtom);
+
+ // Verify results
+ expect(tables.size).toBe(3);
+ expect(tables.get("central.table1")).toEqual({
+ name: "table1",
+ columns: [],
+ });
+ expect(tables.get("main.table2")).toEqual({ name: "table2", columns: [] });
+ expect(tables.get("db2.table3")).toEqual({ name: "table3", columns: [] });
+ });
+
it("should handle multiple connections with progressive qualified names", () => {
const defaultConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -298,9 +393,9 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
+ latestEngineSelected: DUCKDB_ENGINE,
connectionsMap: new Map()
- .set(DEFAULT_ENGINE, defaultConnection)
+ .set(DUCKDB_ENGINE, defaultConnection)
.set("other_engine", otherConnection),
});
@@ -330,7 +425,7 @@ describe("allTablesAtom", () => {
// Set up test connection
const testConnection = {
- name: DEFAULT_ENGINE,
+ name: DUCKDB_ENGINE,
dialect: "duckdb",
source: "duckdb",
display_name: "DuckDB In-Memory",
@@ -350,8 +445,8 @@ describe("allTablesAtom", () => {
};
store.set(dataSourceConnectionsAtom, {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, testConnection),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: new Map().set(DUCKDB_ENGINE, testConnection),
});
// Get tables from the atom
diff --git a/frontend/src/core/datasets/__tests__/data-source.test.ts b/frontend/src/core/datasets/__tests__/data-source.test.ts
index 5cfc80f148..a4e84215a5 100644
--- a/frontend/src/core/datasets/__tests__/data-source.test.ts
+++ b/frontend/src/core/datasets/__tests__/data-source.test.ts
@@ -4,8 +4,8 @@ import {
type ConnectionName,
type DataSourceConnection,
type DataSourceState,
- DEFAULT_ENGINE,
exportedForTesting,
+ INTERNAL_SQL_ENGINES,
type SQLTableContext,
} from "../data-source-connections";
import type { VariableName } from "@/core/variables/types";
@@ -26,6 +26,8 @@ function addConnection(
});
}
+const defaultConnSize = 1;
+
describe("data source connections", () => {
let state: DataSourceState;
@@ -34,8 +36,10 @@ describe("data source connections", () => {
});
it("starts with default connections map", () => {
- expect(initialState().connectionsMap.size).toBe(1);
- expect(initialState().connectionsMap.has(DEFAULT_ENGINE)).toBe(true);
+ expect(initialState().connectionsMap.size).toBe(defaultConnSize);
+ for (const engine of INTERNAL_SQL_ENGINES) {
+ expect(initialState().connectionsMap.has(engine)).toBe(true);
+ }
});
it("can add new connections", () => {
@@ -50,7 +54,7 @@ describe("data source connections", () => {
];
const newState = addConnection(newConnections, state);
- expect(newState.connectionsMap.size).toBe(2);
+ expect(newState.connectionsMap.size).toBe(defaultConnSize + 1);
expect(newState.connectionsMap.get("conn1" as ConnectionName)).toEqual(
newConnections[0],
);
@@ -73,7 +77,7 @@ describe("data source connections", () => {
let newState = addConnection([connection], state);
newState = addConnection([updatedConnection], state);
- expect(newState.connectionsMap.size).toBe(2);
+ expect(newState.connectionsMap.size).toBe(defaultConnSize + 1);
expect(newState.connectionsMap.get("conn1" as ConnectionName)).toEqual(
updatedConnection,
);
@@ -98,13 +102,13 @@ describe("data source connections", () => {
];
let newState = addConnection(connections, state);
- expect(newState.connectionsMap.size).toBe(3);
+ expect(newState.connectionsMap.size).toBe(defaultConnSize + 2);
newState = reducer(newState, {
type: "removeDataSourceConnection",
payload: "conn1" as ConnectionName,
});
- expect(newState.connectionsMap.size).toBe(2);
+ expect(newState.connectionsMap.size).toBe(defaultConnSize + 1);
expect(newState.connectionsMap.has("conn2" as ConnectionName)).toBe(true);
});
@@ -127,7 +131,7 @@ describe("data source connections", () => {
];
let newState = addConnection(connections, state);
- expect(newState.connectionsMap.size).toBe(3);
+ expect(newState.connectionsMap.size).toBe(defaultConnSize + 2);
newState = reducer(newState, {
type: "clearDataSourceConnections",
@@ -167,27 +171,31 @@ describe("filtering data sources", () => {
beforeEach(() => {
baseState = addConnection(connections, baseState);
- expect(baseState.connectionsMap.size).toBe(3); // 2 + 1 (default) connections
+ expect(baseState.connectionsMap.size).toBe(defaultConnSize + 2); // 2 + 2 (default) connections
});
- it("keeps only DEFAULT_ENGINE when no variables", () => {
+ it("keeps only internal engines when no variables", () => {
const filtered = filterDataSources([]);
- expect(filtered.connectionsMap.size).toBe(1);
- expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);
+ expect(filtered.connectionsMap.size).toBe(defaultConnSize);
+ for (const engine of INTERNAL_SQL_ENGINES) {
+ expect(filtered.connectionsMap.has(engine)).toBe(true);
+ }
});
- it("keeps matching variables and DEFAULT_ENGINE", () => {
+ it("keeps matching variables and internal engines", () => {
const filtered = filterDataSources(["conn1" as unknown as VariableName]);
- expect(filtered.connectionsMap.size).toBe(2);
+ expect(filtered.connectionsMap.size).toBe(defaultConnSize + 1);
expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);
- expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);
+ for (const engine of INTERNAL_SQL_ENGINES) {
+ expect(filtered.connectionsMap.has(engine)).toBe(true);
+ }
});
it("filters out non-matching variables", () => {
const filtered = filterDataSources([
"non_existent" as unknown as VariableName,
]);
- expect(filtered.connectionsMap.size).toBe(1);
+ expect(filtered.connectionsMap.size).toBe(defaultConnSize);
});
it("handles mix of matching and non-matching variables", () => {
@@ -195,9 +203,11 @@ describe("filtering data sources", () => {
"conn1" as unknown as VariableName,
"non_existent" as unknown as VariableName,
]);
- expect(filtered.connectionsMap.size).toBe(2);
+ expect(filtered.connectionsMap.size).toBe(defaultConnSize + 1);
expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);
- expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);
+ for (const engine of INTERNAL_SQL_ENGINES) {
+ expect(filtered.connectionsMap.has(engine)).toBe(true);
+ }
});
});
@@ -241,7 +251,7 @@ describe("add table list", () => {
beforeEach(() => {
baseState = addConnection(connections, baseState);
- expect(baseState.connectionsMap.size).toBe(2);
+ expect(baseState.connectionsMap.size).toBe(defaultConnSize + 1);
});
it("adds table list to a specific connection", () => {
@@ -368,7 +378,7 @@ describe("add table", () => {
beforeEach(() => {
baseState = addConnection(connections, baseState);
- expect(baseState.connectionsMap.size).toBe(2);
+ expect(baseState.connectionsMap.size).toBe(defaultConnSize + 1);
});
it("adds table to a specific connection", () => {
diff --git a/frontend/src/core/datasets/data-source-connections.ts b/frontend/src/core/datasets/data-source-connections.ts
index c9023e635e..1c1a8e3558 100644
--- a/frontend/src/core/datasets/data-source-connections.ts
+++ b/frontend/src/core/datasets/data-source-connections.ts
@@ -10,10 +10,27 @@ import { atom } from "jotai";
import { store } from "../state/jotai";
import { datasetTablesAtom } from "./state";
import { Logger } from "@/utils/Logger";
+import { isSchemaless } from "@/components/datasources/utils";
export type ConnectionName = TypedString<"ConnectionName">;
-export const DEFAULT_ENGINE = "__marimo_duckdb" as ConnectionName;
+// duckdb engine is treated as the default engine
+// as it doesn't require passing an engine variable to the backend
+export const DUCKDB_ENGINE = "__marimo_duckdb" as ConnectionName;
+export const INTERNAL_SQL_ENGINES = new Set([DUCKDB_ENGINE]);
+
+const initialConnections: ConnectionsMap = new Map([
+ [
+ DUCKDB_ENGINE,
+ {
+ name: DUCKDB_ENGINE,
+ dialect: "duckdb",
+ source: "duckdb",
+ display_name: "DuckDB (In-Memory)",
+ databases: [],
+ },
+ ],
+]);
// Extend the backend type but override the name property with the strongly typed ConnectionName
export interface DataSourceConnection
@@ -21,9 +38,11 @@ export interface DataSourceConnection
name: ConnectionName;
}
+type ConnectionsMap = ReadonlyMap<ConnectionName, DataSourceConnection>;
+
export interface DataSourceState {
latestEngineSelected: ConnectionName;
- connectionsMap: ReadonlyMap<ConnectionName, DataSourceConnection>;
+ connectionsMap: ConnectionsMap;
}
export interface SQLTableContext {
@@ -36,14 +55,8 @@ export interface SQLTableContext {
function initialState(): DataSourceState {
return {
- latestEngineSelected: DEFAULT_ENGINE,
- connectionsMap: new Map().set(DEFAULT_ENGINE, {
- name: DEFAULT_ENGINE,
- dialect: "duckdb",
- source: "duckdb",
- display_name: "DuckDB In-Memory",
- databases: [],
- }),
+ latestEngineSelected: DUCKDB_ENGINE,
+ connectionsMap: initialConnections,
};
}
@@ -77,7 +90,7 @@ const {
};
},
- // Keep default engine and any connections that are used by variables
+ // Keep internal engines and any connections that are used by variables
filterDataSourcesFromVariables: (
state: DataSourceState,
variableNames: VariableName[],
@@ -86,7 +99,7 @@ const {
const names = new Set(variableNames);
const newMap = new Map(
[...connectionsMap].filter(([name]) => {
- if (name === DEFAULT_ENGINE) {
+ if (INTERNAL_SQL_ENGINES.has(name)) {
return true;
}
return names.has(name as unknown as VariableName);
@@ -96,13 +109,13 @@ const {
// If the latest engine selected is not in the new map, use the default engine
latestEngineSelected: newMap.has(latestEngineSelected)
? latestEngineSelected
- : DEFAULT_ENGINE,
+ : DUCKDB_ENGINE,
connectionsMap: newMap,
};
},
clearDataSourceConnections: (): DataSourceState => ({
- latestEngineSelected: DEFAULT_ENGINE,
+ latestEngineSelected: DUCKDB_ENGINE,
connectionsMap: new Map(),
}),
@@ -117,7 +130,7 @@ const {
return {
latestEngineSelected: newMap.has(latestEngineSelected)
? latestEngineSelected
- : DEFAULT_ENGINE,
+ : DUCKDB_ENGINE,
connectionsMap: newMap,
};
},
@@ -267,6 +280,7 @@ export const allTablesAtom = atom((get) => {
for (const schema of database.schemas) {
const isDefaultSchema = schema.name === conn.default_schema;
+ const schemalessDb = isSchemaless(schema.name);
for (const table of schema.tables) {
let nameToSave: string;
@@ -276,6 +290,20 @@ export const allTablesAtom = atom((get) => {
// We also need to use the more qualified name if there are collisions
nameToSave = table.name;
+ // Save either dbName.table / tableName
+ if (schemalessDb) {
+ nameToSave = isDefaultDb
+ ? table.name
+ : `${database.name}.${table.name}`;
+
+ if (tableNames.has(nameToSave)) {
+ Logger.warn(`Table name collision for ${nameToSave}. Skipping.`);
+ } else {
+ tableNames.set(nameToSave, table);
+ }
+ continue;
+ }
+
if (isDefaultDb && isDefaultSchema && !tableNames.has(nameToSave)) {
tableNames.set(nameToSave, table);
continue;
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 825cdd1e47..3eab36d528 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -168,6 +168,8 @@ class DependencyManager:
numpy = Dependency("numpy")
altair = Dependency("altair", min_version="5.3.0", max_version="6.0.0")
duckdb = Dependency("duckdb")
+ chdb = Dependency("chdb")
+ clickhouse_connect = Dependency("clickhouse_connect")
sqlglot = Dependency("sqlglot")
pillow = Dependency("PIL")
plotly = Dependency("plotly")
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 5cd8bb7f78..b5a10979cd 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -33,7 +33,10 @@ from marimo._runtime.context.types import get_context, get_global_context
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.runner import cell_runner
from marimo._server.model import SessionMode
-from marimo._sql.engines import INTERNAL_DUCKDB_ENGINE, DuckDBEngine
+from marimo._sql.engines.duckdb import (
+ INTERNAL_DUCKDB_ENGINE,
+ DuckDBEngine,
+)
from marimo._sql.get_engines import (
engine_to_data_source_connection,
get_engines_from_variables,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index d40997b81e..35f9acae02 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -142,9 +142,8 @@ from marimo._runtime.validate_graph import check_for_errors
from marimo._runtime.win32_interrupt_handler import Win32InterruptHandler
from marimo._server.model import SessionMode
from marimo._server.types import QueueType
-from marimo._sql.engines import SQLAlchemyEngine
+from marimo._sql.engines.types import SQLEngine
from marimo._sql.get_engines import get_engines_from_variables
-from marimo._sql.types import SQLEngine
from marimo._tracer import kernel_tracer
from marimo._types.ids import CellId_t, UIElementId, VariableName
from marimo._utils.assert_never import assert_never
@@ -2187,7 +2186,7 @@ class Kernel:
- table_name: Name of the table
"""
engine_name = cast(VariableName, request.engine)
- _database_name = request.database
+ database_name = request.database
schema_name = request.schema
table_name = request.table_name
@@ -2198,18 +2197,26 @@ class Kernel:
).broadcast()
return
- if isinstance(engine, SQLAlchemyEngine):
- table = engine.get_table_details(table_name, schema_name)
- if table is None:
- LOGGER.warning("Table %s not found", table_name)
+ try:
+ table = engine.get_table_details(
+ table_name=table_name,
+ schema_name=schema_name,
+ database_name=database_name,
+ )
+
SQLTablePreview(
request_id=request.request_id, table=table
).broadcast()
- else:
+ except Exception as e:
+ LOGGER.exception(
+ "Failed to get preview for table %s in schema %s",
+ table_name,
+ schema_name,
+ )
SQLTablePreview(
request_id=request.request_id,
table=None,
- error="Not an SQLAlchemyEngine",
+ error="Failed to get table details: " + str(e),
).broadcast()
@kernel_tracer.start_as_current_span("preview_sql_table_list")
@@ -2225,7 +2232,7 @@ class Kernel:
- schema: Name of the schema
"""
engine_name = cast(VariableName, request.engine)
- _database_name = request.database
+ database_name = request.database
schema_name = request.schema
engine, error = self._get_sql_engine(engine_name)
@@ -2235,19 +2242,24 @@ class Kernel:
).broadcast()
return
- if isinstance(engine, SQLAlchemyEngine):
+ try:
table_list = engine.get_tables_in_schema(
- schema=schema_name, include_table_details=False
+ schema=schema_name,
+ database=database_name,
+ include_table_details=False,
)
SQLTableListPreview(
request_id=request.request_id, tables=table_list
).broadcast()
- else:
+ except Exception as e:
+ LOGGER.exception(
+ "Failed to get table list for schema %s", schema_name
+ )
SQLTableListPreview(
request_id=request.request_id,
tables=[],
- error="Not an SQLAlchemyEngine",
- ).broadcast()
+ error="Failed to get table list: " + str(e),
+ )
async def handle_message(self, request: ControlRequest) -> None:
"""Handle a message from the client.
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 2aeb9d8a3c..1ee4477a7d 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -26,7 +26,7 @@ from marimo._runtime.requests import (
ExecutionRequest,
SetUIElementValueRequest,
)
-from marimo._sql.engines import INTERNAL_DUCKDB_ENGINE
+from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from marimo._types.ids import CellId_t
from marimo._utils.lists import as_list
from marimo._utils.parse_dataclass import parse_raw
@@ -185,7 +185,7 @@ class SessionView:
self.datasets = Datasets(tables=list(next_tables.values()))
# Remove any data source connections that are no longer in scope.
- # Keep the default duckdb connection if it exists
+ # Keep internal connections if they exist as these are not defined in variables
next_connections: dict[str, DataSourceConnection] = {}
for connection in self.data_connectors.connections:
if (
diff --git a/marimo/_sql/engines/clickhouse.py b/marimo/_sql/engines/clickhouse.py
new file mode 100644
index 0000000000..4602641f82
--- /dev/null
+++ b/marimo/_sql/engines/clickhouse.py
@@ -0,0 +1,474 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
+
+from marimo import _loggers
+from marimo._data.models import (
+ Database,
+ DataTable,
+ DataTableColumn,
+ DataTableType,
+ Schema,
+)
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.types import (
+ InferenceConfig,
+ SQLEngine,
+ register_engine,
+)
+from marimo._sql.utils import sql_type_to_data_type
+from marimo._types.ids import VariableName
+
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ from chdb.state.sqlitelike import Connection as ChdbConnection # type: ignore # noqa: I001
+ from clickhouse_connect.driver.client import Client as ClickhouseClient # type: ignore
+
+
+PANDAS_REQUIRED_MSG = (
+ "Pandas is required to convert Clickhouse results to a DataFrame"
+)
+
+
+@register_engine
+class ClickhouseEmbedded(SQLEngine):
+ """Use chdb to connect to an embedded Clickhouse"""
+
+ def __init__(
+ self,
+ connection: Optional[ChdbConnection] = None,
+ engine_name: Optional[VariableName] = None,
+ ) -> None:
+ self._connection = connection
+ self._engine_name = engine_name
+ self._cursor = None if connection is None else connection.cursor()
+
+ @property
+ def source(self) -> str:
+ return "clickhouse"
+
+ @property
+ def dialect(self) -> str:
+ return "clickhouse"
+
+ def execute(self, query: str) -> Any:
+ # chdb currently only supports pandas
+ DependencyManager.pandas.require(PANDAS_REQUIRED_MSG)
+
+ import chdb # type: ignore
+ import pandas as pd
+
+ # TODO: this will fail weirdly / silently when there is another connection
+
+ if self._cursor:
+ try:
+ self._cursor.execute(query)
+ rows = self._cursor.fetchall()
+ return pd.DataFrame(rows)
+ except Exception:
+ LOGGER.exception("Failed to execute query")
+ return None
+
+ try:
+ result = chdb.query(query, "Dataframe")
+ except Exception:
+ LOGGER.exception("Failed to execute query")
+ return None
+ if isinstance(result, pd.DataFrame):
+ return result
+ return None
+
+ # TODO: Implement the following functionalities
+ def get_databases(
+ self,
+ *,
+ include_schemas: Union[bool, Literal["auto"]],
+ include_tables: Union[bool, Literal["auto"]],
+ include_table_details: Union[bool, Literal["auto"]],
+ ) -> list[Database]:
+ _, _, _ = include_schemas, include_tables, include_table_details
+ return []
+
+ def get_tables_in_schema(
+ self, *, database: str, schema: str, include_table_details: bool
+ ) -> list[DataTable]:
+ """Return all tables in a schema."""
+ _, _, _ = database, schema, include_table_details
+ return []
+
+ def get_table_details(
+ self, *, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """Get a single table from the engine."""
+ _, _, _ = table_name, schema_name, database_name
+ return None
+
+ def get_default_database(self) -> Optional[str]:
+ return None
+
+ def get_default_schema(self) -> Optional[str]:
+ return None
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ if not DependencyManager.chdb.imported():
+ return False
+
+ from chdb.state.sqlitelike import Connection
+
+ return isinstance(var, Connection)
+
+ @property
+ def inference_config(self) -> InferenceConfig:
+ # Because chdb is a local connection, we can auto-discover everything
+ return InferenceConfig(
+ auto_discover_schemas=True,
+ auto_discover_tables=True,
+ auto_discover_columns=True,
+ )
+
+
+@register_engine
+class ClickhouseServer(SQLEngine):
+ """Use clickhouse.connect to connect to a Clickhouse server"""
+
+ def __init__(
+ self,
+ connection: Optional[ClickhouseClient] = None,
+ engine_name: Optional[VariableName] = None,
+ ) -> None:
+ self._connection = connection
+ self._engine_name = engine_name
+
+ @property
+ def source(self) -> str:
+ return "clickhouse"
+
+ @property
+ def dialect(self) -> str:
+ return "clickhouse"
+
+ def execute(self, query: str) -> Any:
+ if self._connection is None:
+ return None
+
+ # clickhouse connect supports pandas and arrow format
+ DependencyManager.pandas.require(PANDAS_REQUIRED_MSG)
+
+ import pandas as pd
+
+ # queries will not work unless they are stripped and comments are removed
+ # TODO: remove comments
+ query = query.strip()
+
+ # If wrapped with try/catch, an error may not be caught
+ result = self._connection.query_df(query)
+
+ if isinstance(result, pd.DataFrame):
+ return result
+ return None
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ if not DependencyManager.clickhouse_connect.imported():
+ return False
+
+ from clickhouse_connect.driver.client import Client
+
+ return isinstance(var, Client)
+
+ @property
+ def inference_config(self) -> InferenceConfig:
+ return InferenceConfig(
+ auto_discover_schemas=False,
+ auto_discover_tables="auto",
+ auto_discover_columns="auto",
+ )
+
+ def get_databases(
+ self,
+ *,
+ include_schemas: Union[bool, Literal["auto"]],
+ include_tables: Union[bool, Literal["auto"]],
+ include_table_details: Union[bool, Literal["auto"]],
+ ) -> list[Database]:
+ """
+ Get all databases from the ClickHouse server.
+
+ Args:
+ include_schemas: Whether to include schema information. (ignored for ClickHouse)
+ include_tables: Whether to include table information.
+ include_table_details: Whether to include detailed table metadata.
+
+ Returns:
+ List of Database objects representing the server's databases.
+ """
+ _ = include_schemas # ClickHouse doesn't have schemas
+
+ if self._connection is None:
+ return []
+
+ if not DependencyManager.pandas.has():
+ LOGGER.info("Unable to get databases without pandas")
+ return []
+
+ import pandas as pd
+
+ databases: list[Database] = []
+ try:
+ db_df = self._connection.query_df("SHOW DATABASES")
+ except Exception:
+ LOGGER.warning("Failed to get databases", exc_info=True)
+ return databases
+
+ if not isinstance(db_df, pd.DataFrame):
+ LOGGER.warning(
+ f"Failed to convert database result to DataFrame, result: {str(db_df)}"
+ )
+ return databases
+
+ include_table_details = self._resolve_should_auto_discover(
+ include_table_details
+ )
+
+ # Assume the first column contains the database names.
+ if db_df.empty:
+ return databases
+
+ db_names = db_df[db_df.columns[0]].tolist()
+ for db in db_names:
+ db_name = cast(str, db)
+ if (
+ # Skip meta db's, TODO: do this for other engines too.
+ db_name.lower() in ["system", "information_schema"]
+ or not include_tables
+ ):
+ tables = []
+ else:
+ tables = self.get_tables_in_schema(
+ schema="",
+ database=db,
+ include_table_details=include_table_details,
+ )
+ databases.append(
+ Database(
+ name=db,
+ dialect=self.dialect,
+ engine=self._engine_name,
+ # ClickHouse does not have schemas
+ schemas=[Schema(name="", tables=tables)],
+ )
+ )
+ return databases
+
+ def _resolve_should_auto_discover(
+ self, value: Union[bool, Literal["auto"]]
+ ) -> bool:
+ if value == "auto":
+ # TODO: Smartly determine if we should auto-discover
+ return False
+ return value
+
+ def get_tables_in_schema(
+ self,
+ *,
+ schema: str,
+ database: str,
+ include_table_details: bool,
+ ) -> list[DataTable]:
+ """
+ Return all tables in a given ClickHouse database.
+
+ Args:
+ schema: The schema name. (ignored for ClickHouse)
+ database: The name of the database.
+ include_table_details: Whether to retrieve detailed table metadata.
+
+ Returns:
+ List of DataTable objects.
+ """
+ _ = schema # ClickHouse does not have schemas
+ if self._connection is None:
+ return []
+
+ tables: list[DataTable] = []
+ try:
+ query = f"SHOW TABLES FROM {database}"
+ table_df = self._connection.query_df(query)
+ except Exception:
+ LOGGER.warning(
+ f"Failed to get tables from database {database}", exc_info=True
+ )
+ return tables
+
+ import pandas as pd
+
+ if not isinstance(table_df, pd.DataFrame):
+ LOGGER.warning("Failed to convert table result to DataFrame")
+ return tables
+
+ if table_df.empty:
+ return tables
+
+ # Assume the first column contains table names.
+ table_names = table_df[table_df.columns[0]].tolist()
+ for table in table_names:
+ if include_table_details:
+ table_detail = self.get_table_details(
+ table_name=table, schema_name="", database_name=database
+ )
+ if table_detail is not None:
+ tables.append(table_detail)
+ else:
+ tables.append(
+ DataTable(
+ source_type="connection",
+ source=self.dialect,
+ name=table,
+ num_rows=None,
+ num_columns=None,
+ variable_name=None,
+ engine=self._engine_name,
+ type="table",
+ columns=[],
+ primary_keys=[],
+ indexes=[],
+ )
+ )
+ return tables
+
+ def get_table_details(
+ self, *, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """
+ Get detailed metadata for a given table in a database.
+
+ Args:
+ database_name: The database name.
+ schema_name: The schema name. (ignored for ClickHouse)
+ table_name: The table name.
+
+ Returns:
+ A DataTable object with detailed metadata,
+ or None if the table cannot be described.
+ """
+ _ = schema_name
+ if self._connection is None:
+ return None
+
+ try:
+ query = f"SELECT * FROM system.tables WHERE name = '{table_name}' AND database = '{database_name}'"
+ table_df = self._connection.query_df(query)
+ except Exception:
+ LOGGER.warning(
+ f"Failed to get table details for {table_name} in database {database_name}",
+ exc_info=True,
+ )
+ return None
+
+ import pandas as pd
+
+ if not isinstance(table_df, pd.DataFrame):
+ LOGGER.warning(
+ "Failed to convert table description result to DataFrame"
+ )
+ return None
+
+ primary_keys: list[str] = []
+ total_rows = None
+ table_type: DataTableType = "table"
+ try:
+ primary_key = table_df["primary_key"].iloc[0]
+ if primary_key:
+ primary_keys.append(primary_key)
+
+ engine = table_df["engine"].iloc[0]
+ if engine and str(engine).lower() == "view":
+ table_type = "view" # TODO: We should add support for general table types
+
+ total_rows = table_df["total_rows"].iloc[0]
+ except Exception:
+ pass
+
+ try:
+ query = f"DESCRIBE TABLE {database_name}.{table_name}"
+ desc_df = self._connection.query_df(query)
+ except Exception:
+ LOGGER.warning(
+ f"Failed to get table description for {table_name} in database {database_name}",
+ exc_info=True,
+ )
+ return None
+
+ if not isinstance(desc_df, pd.DataFrame):
+ LOGGER.warning(
+ "Failed to convert table description result to DataFrame"
+ )
+ return None
+
+ if desc_df.empty:
+ return None
+
+ cols: list[DataTableColumn] = []
+ for _, row in desc_df.iterrows():
+ col_name = row.get("name")
+ if col_name is None:
+ continue
+ col_type_str = str(row.get("type", "string"))
+ data_type = sql_type_to_data_type(col_type_str)
+ cols.append(
+ DataTableColumn(
+ name=str(col_name),
+ type=data_type,
+ external_type=col_type_str,
+ sample_values=[],
+ )
+ )
+
+ try:
+ total_rows = int(total_rows) if total_rows is not None else None
+ except Exception:
+ total_rows = None
+
+ return DataTable(
+ source_type="connection",
+ source=self.dialect,
+ name=table_name,
+ num_rows=total_rows,
+ num_columns=len(cols),
+ variable_name=None,
+ engine=self._engine_name,
+ type=table_type,
+ columns=cols,
+ primary_keys=primary_keys,
+ indexes=[], # TODO
+ )
+
+ def get_default_database(self) -> Optional[str]:
+ if self._connection is None:
+ return None
+
+ if not DependencyManager.pandas.has():
+ return None
+
+ try:
+ query = "SELECT currentDatabase()"
+ db_name = self._connection.query_df(query)
+ except Exception:
+ LOGGER.warning("Failed to get current database", exc_info=True)
+ return None
+
+ import pandas as pd
+
+ if not isinstance(db_name, pd.DataFrame):
+ return None
+
+ if db_name.empty:
+ return None
+ return str(db_name.iloc[0, 0])
+
+ def get_default_schema(self) -> Optional[str]:
+ # ClickHouse does not have schemas
+ return None
diff --git a/marimo/_sql/engines/duckdb.py b/marimo/_sql/engines/duckdb.py
new file mode 100644
index 0000000000..2950bbd454
--- /dev/null
+++ b/marimo/_sql/engines/duckdb.py
@@ -0,0 +1,128 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
+
+from marimo import _loggers
+from marimo._data.get_datasets import get_databases_from_duckdb
+from marimo._data.models import Database, DataTable
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.types import (
+ InferenceConfig,
+ SQLEngine,
+ register_engine,
+)
+from marimo._sql.utils import raise_df_import_error, wrapped_sql
+from marimo._types.ids import VariableName
+
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ import duckdb
+
+# Internal engine names
+INTERNAL_DUCKDB_ENGINE = cast(VariableName, "__marimo_duckdb")
+
+
+@register_engine
+class DuckDBEngine(SQLEngine):
+ """DuckDB SQL engine."""
+
+ def __init__(
+ self,
+ connection: Optional[duckdb.DuckDBPyConnection] = None,
+ engine_name: Optional[VariableName] = None,
+ ) -> None:
+ self._connection = connection
+ self._engine_name = engine_name
+
+ @property
+ def source(self) -> str:
+ return "duckdb"
+
+ @property
+ def dialect(self) -> str:
+ return "duckdb"
+
+ def execute(self, query: str) -> Any:
+ relation = wrapped_sql(query, self._connection)
+
+ # Invalid / empty query
+ if relation is None:
+ return None
+
+ if DependencyManager.polars.has():
+ return relation.pl()
+ elif DependencyManager.pandas.has():
+ return relation.df()
+ else:
+ raise_df_import_error("polars[pyarrow]")
+
+ @staticmethod
+ def is_compatible(var: Any) -> bool:
+ if not DependencyManager.duckdb.imported():
+ return False
+
+ import duckdb
+
+ return isinstance(var, duckdb.DuckDBPyConnection)
+
+ @property
+ def inference_config(self) -> InferenceConfig:
+ # At the moment this isn't being used for duckdb
+ return InferenceConfig(
+ auto_discover_schemas=True,
+ auto_discover_tables="auto",
+ auto_discover_columns=False,
+ )
+
+ def get_default_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_default_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,
+ *,
+ include_schemas: Union[bool, Literal["auto"]],
+ include_tables: Union[bool, Literal["auto"]],
+ include_table_details: Union[bool, Literal["auto"]],
+ ) -> list[Database]:
+ """Fetch all databases from the engine. At the moment, will fetch everything."""
+ _, _, _ = include_schemas, include_tables, include_table_details
+ return get_databases_from_duckdb(self._connection, self._engine_name)
+
+ def get_tables_in_schema(
+ self, *, schema: str, database: str, include_table_details: bool
+ ) -> list[DataTable]:
+ """Return all tables in a schema. This is currently implemented in get_databases_from_duckdb."""
+ _, _, _ = database, schema, include_table_details
+ return []
+
+ def get_table_details(
+ self, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """Get a single table from the engine. This is currently implemented in get_databases_from_duckdb."""
+ _, _, _ = table_name, schema_name, database_name
+ return None
diff --git a/marimo/_sql/engines.py b/marimo/_sql/engines/sqlalchemy.py
similarity index 72%
rename from marimo/_sql/engines.py
rename to marimo/_sql/engines/sqlalchemy.py
index b1a3f61da6..4fc0340d08 100644
--- a/marimo/_sql/engines.py
+++ b/marimo/_sql/engines/sqlalchemy.py
@@ -1,10 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union
from marimo import _loggers
-from marimo._data.get_datasets import get_databases_from_duckdb
from marimo._data.models import (
Database,
DataTable,
@@ -14,111 +13,31 @@ from marimo._data.models import (
Schema,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.types import SQLEngine
-from marimo._sql.utils import wrapped_sql
+from marimo._sql.engines.types import (
+ InferenceConfig,
+ SQLEngine,
+ register_engine,
+)
+from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
- import duckdb
from sqlalchemy import Engine
from sqlalchemy.sql.type_api import TypeEngine
-# Internal engine name for DuckDB, we need to ensure this is unique
-INTERNAL_DUCKDB_ENGINE = cast(VariableName, "__marimo_duckdb")
-
-
-def raise_df_import_error(pkg: str) -> None:
- raise ModuleNotFoundError(
- "pandas or polars is required to execute sql. "
- + "You can install them with 'pip install pandas polars'",
- name=pkg,
- )
-
-
-class DuckDBEngine(SQLEngine):
- """DuckDB SQL engine."""
-
- def __init__(
- self,
- connection: Optional[duckdb.DuckDBPyConnection] = None,
- engine_name: Optional[VariableName] = None,
- ) -> None:
- self._connection = connection
- self._engine_name = engine_name
-
- @property
- def source(self) -> str:
- return "duckdb"
-
- @property
- def dialect(self) -> str:
- return "duckdb"
-
- def execute(self, query: str) -> Any:
- relation = wrapped_sql(query, self._connection)
-
- # Invalid / empty query
- if relation is None:
- return None
-
- if DependencyManager.polars.has():
- return relation.pl()
- elif DependencyManager.pandas.has():
- return relation.df()
- else:
- raise_df_import_error("polars[pyarrow]")
-
- @staticmethod
- def is_compatible(var: Any) -> bool:
- if not DependencyManager.duckdb.imported():
- return False
-
- import duckdb
-
- 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)
-
+@register_engine
class SQLAlchemyEngine(SQLEngine):
"""SQLAlchemy engine."""
def __init__(
- self, engine: Engine, engine_name: Optional[VariableName] = None
+ self, connection: Engine, engine_name: Optional[VariableName] = None
) -> None:
from sqlalchemy import Inspector, inspect
- self._engine = engine
+ self._engine = connection
self._engine_name = engine_name
self.inspector: Optional[Inspector] = None
@@ -128,8 +47,8 @@ class SQLAlchemyEngine(SQLEngine):
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()
+ self.default_database = self.get_default_database()
+ self.default_schema = self.get_default_schema()
@property
def source(self) -> str:
@@ -179,13 +98,15 @@ class SQLAlchemyEngine(SQLEngine):
return isinstance(var, Engine)
- def _should_include_columns(self) -> bool:
- # Including columns can fan out to a lot of requests,
- # so this is disabled for now.
- # Maybe in future we can enable this as a flag or for certain connection types.
- return False
+ @property
+ def inference_config(self) -> InferenceConfig:
+ return InferenceConfig(
+ auto_discover_schemas=True,
+ auto_discover_tables="auto",
+ auto_discover_columns=False,
+ )
- def _get_current_database(self) -> Optional[str]:
+ def get_default_database(self) -> Optional[str]:
"""Get the current database name.
Returns:
@@ -226,14 +147,16 @@ class SQLAlchemyEngine(SQLEngine):
# 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
+ database=None,
+ include_tables=False,
+ include_table_details=False,
)
if not schemas_found:
return None
return database_name or ""
- def _get_default_schema(self) -> Optional[str]:
+ def get_default_schema(self) -> Optional[str]:
"""Get the default schema name"""
if self.inspector is None:
return None
@@ -271,6 +194,7 @@ class SQLAlchemyEngine(SQLEngine):
schemas = (
self._get_schemas(
+ database=database_name,
include_tables=self._resolve_should_auto_discover(
include_tables
),
@@ -294,6 +218,7 @@ class SQLAlchemyEngine(SQLEngine):
def _get_schemas(
self,
*,
+ database: Optional[str],
include_tables: bool,
include_table_details: bool,
) -> list[Schema]:
@@ -314,6 +239,7 @@ class SQLAlchemyEngine(SQLEngine):
name=schema,
tables=self.get_tables_in_schema(
schema=schema,
+ database=database if database is not None else "",
include_table_details=include_table_details,
)
if include_tables
@@ -324,9 +250,10 @@ class SQLAlchemyEngine(SQLEngine):
return schemas
def get_tables_in_schema(
- self, *, schema: str, include_table_details: bool
+ self, *, schema: str, database: str, include_table_details: bool
) -> list[DataTable]:
"""Return all tables in a schema."""
+ _ = database
if self.inspector is None:
return []
@@ -360,7 +287,9 @@ class SQLAlchemyEngine(SQLEngine):
data_tables: list[DataTable] = []
for t_type, t_name in tables:
- table = self.get_table_details(t_name, schema)
+ table = self.get_table_details(
+ table_name=t_name, schema_name=schema, database_name=database
+ )
if table is not None:
table.type = t_type
data_tables.append(table)
@@ -368,9 +297,10 @@ class SQLAlchemyEngine(SQLEngine):
return data_tables
def get_table_details(
- self, table_name: str, schema_name: str
+ self, *, table_name: str, schema_name: str, database_name: str
) -> Optional[DataTable]:
"""Get a single table from the engine."""
+ _ = database_name
if self.inspector is None:
return None
@@ -445,7 +375,7 @@ class SQLAlchemyEngine(SQLEngine):
) -> DataType | None:
try:
col_type = engine_type.python_type
- return _sql_type_to_data_type(str(col_type))
+ return sql_type_to_data_type(str(col_type))
except NotImplementedError:
return None
except Exception:
@@ -457,7 +387,7 @@ class SQLAlchemyEngine(SQLEngine):
) -> DataType | None:
try:
col_type = engine_type.as_generic()
- return _sql_type_to_data_type(str(col_type))
+ return sql_type_to_data_type(str(col_type))
except NotImplementedError:
return None
except Exception:
@@ -474,22 +404,3 @@ class SQLAlchemyEngine(SQLEngine):
def _is_cheap_discovery(self) -> bool:
return self.dialect.lower() in ("sqlite", "mysql", "postgresql")
-
-
-def _sql_type_to_data_type(type_str: str) -> DataType:
- """Convert SQL type string to DataType"""
- type_str = type_str.lower()
- if any(x in type_str for x in ("int", "serial")):
- return "integer"
- elif any(x in type_str for x in ("float", "double", "decimal", "numeric")):
- return "number"
- elif any(x in type_str for x in ("timestamp", "datetime")):
- return "datetime"
- elif "date" in type_str:
- return "date"
- elif "bool" in type_str:
- return "boolean"
- elif any(x in type_str for x in ("char", "text")):
- return "string"
- else:
- return "string"
diff --git a/marimo/_sql/engines/types.py b/marimo/_sql/engines/types.py
new file mode 100644
index 0000000000..28e55338ae
--- /dev/null
+++ b/marimo/_sql/engines/types.py
@@ -0,0 +1,94 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, Literal, Optional, Union
+
+from marimo._data.models import Database, DataTable
+
+ENGINE_REGISTRY: list[type[SQLEngine]] = []
+
+
+def register_engine(cls: type[SQLEngine]) -> type[SQLEngine]:
+ ENGINE_REGISTRY.append(cls)
+ return cls
+
+
+@dataclass
+class InferenceConfig(ABC):
+ auto_discover_schemas: Union[bool | Literal["auto"]]
+ auto_discover_tables: Union[bool | Literal["auto"]]
+ auto_discover_columns: Union[bool | Literal["auto"]]
+
+
+class SQLEngine(ABC):
+ """Protocol for SQL engines that can execute queries."""
+
+ @abstractmethod
+ def __init__(self, connection: Any, engine_name: str) -> None:
+ pass
+
+ @property
+ @abstractmethod
+ def source(self) -> str:
+ """Return the source of the engine."""
+ pass
+
+ @property
+ @abstractmethod
+ def dialect(self) -> str:
+ """Return the sqlglot dialect for this engine."""
+ pass
+
+ @property
+ @abstractmethod
+ def inference_config(self) -> InferenceConfig:
+ """Return the inference config for the engine."""
+ pass
+
+ @abstractmethod
+ def execute(self, query: str) -> Any:
+ """Execute a SQL query and return a dataframe."""
+ pass
+
+ @staticmethod
+ @abstractmethod
+ def is_compatible(var: Any) -> bool:
+ """Check if a variable is a compatible engine."""
+ pass
+
+ @abstractmethod
+ def get_default_database(self) -> Optional[str]:
+ """Return the default database for the engine."""
+ pass
+
+ @abstractmethod
+ def get_default_schema(self) -> Optional[str]:
+ """Return the default schema for the engine."""
+ pass
+
+ @abstractmethod
+ def get_databases(
+ self,
+ *,
+ include_schemas: Union[bool, Literal["auto"]],
+ include_tables: Union[bool, Literal["auto"]],
+ include_table_details: Union[bool, Literal["auto"]],
+ ) -> list[Database]:
+ """Return the databases for the engine."""
+ pass
+
+ @abstractmethod
+ def get_tables_in_schema(
+ self, *, schema: str, database: str, include_table_details: bool
+ ) -> list[DataTable]:
+ """Return all tables in a schema."""
+ pass
+
+ @abstractmethod
+ def get_table_details(
+ self, *, table_name: str, schema_name: str, database_name: str
+ ) -> Optional[DataTable]:
+ """Get a single table from the engine."""
+ pass
diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.py
index c71af0d076..79fbdb1a70 100644
--- a/marimo/_sql/get_engines.py
+++ b/marimo/_sql/get_engines.py
@@ -11,12 +11,16 @@ from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
)
-from marimo._sql.engines import (
+from marimo._sql.engines.clickhouse import (
+ ClickhouseEmbedded,
+ ClickhouseServer,
+)
+from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
- SQLAlchemyEngine,
)
-from marimo._sql.types import SQLEngine
+from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
+from marimo._sql.engines.types import SQLEngine
from marimo._types.ids import VariableName
LOGGER = _loggers.marimo_logger()
@@ -26,23 +30,25 @@ def get_engines_from_variables(
variables: list[tuple[VariableName, object]],
) -> list[tuple[VariableName, SQLEngine]]:
engines: list[tuple[VariableName, SQLEngine]] = []
+
+ supported_engines: list[type[SQLEngine]] = [
+ SQLAlchemyEngine,
+ DuckDBEngine,
+ ClickhouseEmbedded,
+ ClickhouseServer,
+ ]
+
for variable_name, value in variables:
- if SQLAlchemyEngine.is_compatible(value):
- engines.append(
- (
- variable_name,
- SQLAlchemyEngine(
- cast(Any, value), engine_name=variable_name
- ),
+ for sql_engine in supported_engines:
+ if sql_engine.is_compatible(value):
+ engines.append(
+ (
+ variable_name,
+ sql_engine(
+ cast(Any, value), engine_name=variable_name
+ ),
+ )
)
- )
- elif DuckDBEngine.is_compatible(value):
- engines.append(
- (
- variable_name,
- DuckDBEngine(cast(Any, value), engine_name=variable_name),
- )
- )
return engines
@@ -55,23 +61,22 @@ def engine_to_data_source_connection(
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", "auto"),
- include_table_details=config.get("auto_discover_columns", False),
- )
- 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}."
- )
+ default_database = engine.get_default_database()
+ default_schema = engine.get_default_schema()
+ inference_config = engine.inference_config
+
+ config = get_datasources_config()
+ databases = engine.get_databases(
+ include_schemas=config.get(
+ "auto_discover_schemas", inference_config.auto_discover_schemas
+ ),
+ include_tables=config.get(
+ "auto_discover_tables", inference_config.auto_discover_tables
+ ),
+ include_table_details=config.get(
+ "auto_discover_columns", inference_config.auto_discover_columns
+ ),
+ )
display_name = (
f"{engine.dialect} ({variable_name})"
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 2fa437f081..4d9efffc82 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -7,11 +7,9 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
from marimo._runtime.output import replace
-from marimo._sql.engines import (
- DuckDBEngine,
- SQLAlchemyEngine,
- raise_df_import_error,
-)
+from marimo._sql.engines.duckdb import DuckDBEngine
+from marimo._sql.engines.types import ENGINE_REGISTRY
+from marimo._sql.utils import raise_df_import_error
def get_default_result_limit() -> Optional[int]:
@@ -20,8 +18,10 @@ def get_default_result_limit() -> Optional[int]:
if TYPE_CHECKING:
- import duckdb
- import sqlalchemy
+ from chdb.state.sqlitelike import Connection as ChdbConnection # type: ignore # noqa: I001
+ from clickhouse_connect.driver.client import Client as ClickhouseClient # type: ignore
+ from duckdb import DuckDBPyConnection
+ from sqlalchemy.engine import Engine as SAEngine
@mddoc
@@ -29,7 +29,9 @@ def sql(
query: str,
*,
output: bool = True,
- engine: Optional[sqlalchemy.Engine | duckdb.DuckDBPyConnection] = None,
+ engine: Optional[
+ SAEngine | DuckDBPyConnection | ClickhouseClient | ChdbConnection
+ ] = None,
) -> Any:
"""
Execute a SQL query.
@@ -44,7 +46,7 @@ def sql(
Args:
query: The SQL query to execute.
output: Whether to display the result in the UI. Defaults to True.
- engine: Optional SQL engine to use. Can be a SQLAlchemy engine or DuckDB connection.
+ engine: Optional SQL engine to use. Can be a SQLAlchemy, Clickhouse, or DuckDB engine.
If None, uses DuckDB.
Returns:
@@ -60,14 +62,17 @@ def sql(
DependencyManager.sqlglot,
)
sql_engine = DuckDBEngine(connection=None)
- elif SQLAlchemyEngine.is_compatible(engine):
- sql_engine = SQLAlchemyEngine(engine) # type: ignore
- elif DuckDBEngine.is_compatible(engine):
- sql_engine = DuckDBEngine(engine) # type: ignore
else:
- raise ValueError(
- "Unsupported engine. Must be a SQLAlchemy engine or DuckDB connection."
- )
+ for engine_cls in ENGINE_REGISTRY:
+ if engine_cls.is_compatible(engine):
+ sql_engine = engine_cls(
+ connection=engine, engine_name="custom"
+ ) # type: ignore
+ break
+ else:
+ raise ValueError(
+ "Unsupported engine. Must be a SQLAlchemy, Clickhouse, or DuckDB engine."
+ )
df = sql_engine.execute(query)
if df is None:
diff --git a/marimo/_sql/types.py b/marimo/_sql/types.py
deleted file mode 100644
index 259c7cb1aa..0000000000
--- a/marimo/_sql/types.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-from abc import ABC, abstractmethod
-from typing import Any
-
-
-class SQLEngine(ABC):
- """Protocol for SQL engines that can execute queries."""
-
- @property
- @abstractmethod
- def source(self) -> str:
- """Return the source of the engine."""
- pass
-
- @property
- @abstractmethod
- def dialect(self) -> str:
- """Return the sqlglot dialect for this engine."""
- pass
-
- @abstractmethod
- def execute(self, query: str) -> Any:
- """Execute a SQL query and return a dataframe."""
- pass
-
- @staticmethod
- @abstractmethod
- def is_compatible(var: Any) -> bool:
- """Check if a variable is a compatible engine."""
- pass
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
index cc9f577620..b5642c172a 100644
--- a/marimo/_sql/utils.py
+++ b/marimo/_sql/utils.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Optional, cast
+from marimo._data.models import DataType
from marimo._dependencies.dependencies import DependencyManager
from marimo._runtime.context.types import (
ContextNotInitializedError,
@@ -41,3 +42,30 @@ def wrapped_sql(
{"query": query, "connection": connection},
)
return relation
+
+
+def raise_df_import_error(pkg: str) -> None:
+ raise ModuleNotFoundError(
+ "pandas or polars is required to execute sql. "
+ + "You can install them with 'pip install pandas polars'",
+ name=pkg,
+ )
+
+
+def sql_type_to_data_type(type_str: str) -> DataType:
+ """Convert SQL type string to DataType"""
+ type_str = type_str.lower()
+ if any(x in type_str for x in ("int", "serial")):
+ return "integer"
+ elif any(x in type_str for x in ("float", "double", "decimal", "numeric")):
+ return "number"
+ elif any(x in type_str for x in ("timestamp", "datetime")):
+ return "datetime"
+ elif "date" in type_str:
+ return "date"
+ elif "bool" in type_str:
+ return "boolean"
+ elif any(x in type_str for x in ("char", "text")):
+ return "string"
+ else:
+ return "string"
diff --git a/pyproject.toml b/pyproject.toml
index 6e8340edda..a5fe3e5a57 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -254,6 +254,9 @@ extra-dependencies = [
"polars~=1.24.0",
"sqlglot>=23.4",
"sqlalchemy>=2.0.38",
+ # For testing clickhouse
+ "chdb>=3; platform_system != 'Windows'", # there is no suitable wheel for windows
+ "clickhouse-connect>=0.8",
"pandas>=1.5.3",
"hvplot~=0.11.2",
# Causes issues installing `shapely` (v2.0.7)
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index f08831c510..1a2aba63a2 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -27,7 +27,7 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
)
from marimo._server.session.session_view import SessionView
-from marimo._sql.engines import INTERNAL_DUCKDB_ENGINE
+from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
diff --git a/tests/_sql/test_clickhouse.py b/tests/_sql/test_clickhouse.py
new file mode 100644
index 0000000000..93fe6fe126
--- /dev/null
+++ b/tests/_sql/test_clickhouse.py
@@ -0,0 +1,82 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._data.models import DataSourceConnection
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._sql.engines.clickhouse import ClickhouseEmbedded, ClickhouseServer
+from marimo._sql.get_engines import engine_to_data_source_connection
+from marimo._sql.sql import sql
+
+HAS_CHDB = DependencyManager.chdb.has() and DependencyManager.pandas.has()
+HAS_CLICKHOUSE_CONNECT = (
+ DependencyManager.clickhouse_connect.has()
+ and DependencyManager.pandas.has()
+)
+
+
+ not HAS_CLICKHOUSE_CONNECT, reason="Clickhouse and Pandas not installed"
+)
+def test_clickhouse_server_creation() -> None:
+ engine = ClickhouseServer(None)
+ connection = engine_to_data_source_connection("clickhouse", engine=engine)
+ assert isinstance(connection, DataSourceConnection)
+
+ assert connection.databases == []
+ # assert connection.default_database == "default"
+ # assert connection.default_schema == "default"
+ assert connection.display_name == "clickhouse (clickhouse)"
+ assert connection.dialect == "clickhouse"
+ assert connection.name == "clickhouse"
+ assert connection.source == "clickhouse"
+
+
[email protected](not HAS_CHDB, reason="chdb and pandas not installed")
+def test_clickhouse_embedded_creation() -> None:
+ import chdb
+
+ chdb_conn = chdb.connect(":memory:")
+ engine = ClickhouseEmbedded(
+ connection=chdb_conn, engine_name="clickhouse_embedded"
+ )
+ assert engine.dialect == "clickhouse"
+ assert engine._engine_name == "clickhouse_embedded"
+
+ connection = engine_to_data_source_connection("clickhouse", engine=engine)
+ assert isinstance(connection, DataSourceConnection)
+
+ assert connection.databases == []
+ # assert connection.default_database == "default"
+ # assert connection.default_schema == "default"
+ assert connection.display_name == "clickhouse (clickhouse)"
+ assert connection.dialect == "clickhouse"
+ assert connection.name == "clickhouse"
+ assert connection.source == "clickhouse"
+
+ chdb_conn.close()
+
+
[email protected](not HAS_CHDB, reason="chdb and pandas not installed")
[email protected](reason="Flaky test")
+def test_clickhouse_execute() -> None:
+ import chdb
+ import pandas as pd
+
+ chdb_conn = chdb.connect(":memory:")
+
+ sql(
+ "CREATE TABLE test (id Int32, name String) ENGINE = Memory",
+ engine=chdb_conn,
+ )
+ sql(
+ "INSERT INTO test VALUES (1, 'Alice'), (2, 'Bob')",
+ engine=chdb_conn,
+ )
+ result = sql("SELECT * FROM test", engine=chdb_conn)
+
+ assert isinstance(result, pd.DataFrame)
+ expected = pd.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})
+ assert result.equals(expected)
+
+ chdb_conn.close()
diff --git a/tests/_sql/test_duckdb.py b/tests/_sql/test_duckdb.py
index d3ce7fcdb6..3c45e9705b 100644
--- a/tests/_sql/test_duckdb.py
+++ b/tests/_sql/test_duckdb.py
@@ -9,9 +9,7 @@ import pytest
from marimo._data.models import Database, DataTable, DataTableColumn, Schema
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines import (
- DuckDBEngine,
-)
+from marimo._sql.engines.duckdb import DuckDBEngine
from marimo._sql.sql import sql
HAS_DUCKDB = DependencyManager.duckdb.has()
@@ -122,7 +120,9 @@ def test_duckdb_engine_get_databases(
"""Test DuckDBEngine get_databases method."""
engine = DuckDBEngine(duckdb_connection, engine_name="test_duckdb")
- databases = engine.get_databases()
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=True, include_table_details=True
+ )
assert databases == expected_databases_with_conn
@@ -131,10 +131,14 @@ def test_duckdb_engine_get_databases(
def test_duckdb_engine_get_databases_no_conn() -> None:
"""Test DuckDBEngine get_databases method."""
engine = DuckDBEngine()
- initial_databases = engine.get_databases()
+ initial_databases = engine.get_databases(
+ include_schemas=False,
+ include_table_details=False,
+ include_tables=False,
+ )
assert initial_databases == []
- assert engine.get_current_database() == "memory"
- assert engine.get_current_schema() == "main"
+ assert engine.get_default_database() == "memory"
+ assert engine.get_default_schema() == "main"
engine.execute(
"CREATE TABLE test (id INTEGER PRIMARY KEY, name VARCHAR(255))"
@@ -147,7 +151,9 @@ def test_duckdb_engine_get_databases_no_conn() -> None:
(3, 'Charlie');
"""
)
- databases = engine.get_databases()
+ databases = engine.get_databases(
+ include_schemas=True, include_tables=True, include_table_details=True
+ )
expected_databases = deepcopy(expected_databases_with_conn)
expected_databases[0].engine = None
@@ -167,15 +173,15 @@ def test_get_current_database_schema() -> None:
engine = duckdb.connect(":memory:")
duckdb_engine = DuckDBEngine(engine)
- assert duckdb_engine.get_current_database() == "memory"
- assert duckdb_engine.get_current_schema() == "main"
+ assert duckdb_engine.get_default_database() == "memory"
+ assert duckdb_engine.get_default_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"
+ assert duckdb_engine.get_default_database() == "memory"
+ assert duckdb_engine.get_default_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_engines.py b/tests/_sql/test_engines.py
index 356aa877c3..00e3aca221 100644
--- a/tests/_sql/test_engines.py
+++ b/tests/_sql/test_engines.py
@@ -7,18 +7,19 @@ from unittest.mock import MagicMock
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines import (
- DuckDBEngine,
- SQLAlchemyEngine,
- _sql_type_to_data_type,
- raise_df_import_error,
-)
+from marimo._sql.engines.clickhouse import ClickhouseEmbedded
+from marimo._sql.engines.duckdb import DuckDBEngine
+from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
+from marimo._sql.utils import raise_df_import_error, sql_type_to_data_type
HAS_DUCKDB = DependencyManager.duckdb.has()
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
+HAS_CLICKHOUSE = DependencyManager.chdb.has()
HAS_PANDAS = DependencyManager.pandas.has()
HAS_POLARS = DependencyManager.polars.has()
+UNUSED_DB_NAME = "unused_db"
+
@pytest.mark.skipif(
not HAS_DUCKDB or not HAS_SQLALCHEMY or not HAS_PANDAS,
@@ -45,31 +46,40 @@ def test_raise_df_import_error() -> None:
@pytest.mark.skipif(
- not HAS_DUCKDB or not HAS_SQLALCHEMY,
- reason="Duckdb and sqlalchemy not installed",
+ not (HAS_DUCKDB and HAS_SQLALCHEMY and HAS_CLICKHOUSE),
+ reason="Duckdb, sqlalchemy and Clickhouse not installed",
)
def test_engine_name_initialization() -> None:
"""Test engine name initialization."""
+ import chdb
import duckdb
import sqlalchemy as sa
duckdb_conn = duckdb.connect(":memory:")
sqlite_engine = sa.create_engine("sqlite:///:memory:")
+ clickhouse_conn = chdb.connect(":memory:")
duck_engine = DuckDBEngine(duckdb_conn, engine_name="my_duck")
sql_engine = SQLAlchemyEngine(sqlite_engine, engine_name="my_sql")
+ clickhouse_engine = SQLAlchemyEngine(
+ clickhouse_conn, engine_name="my_clickhouse"
+ )
assert duck_engine._engine_name == "my_duck"
assert sql_engine._engine_name == "my_sql"
+ assert clickhouse_engine._engine_name == "my_clickhouse"
# Test default names
duck_engine_default = DuckDBEngine(duckdb_conn)
sql_engine_default = SQLAlchemyEngine(sqlite_engine)
+ clickhouse_engine_default = ClickhouseEmbedded(clickhouse_conn)
assert duck_engine_default._engine_name is None
assert sql_engine_default._engine_name is None
+ assert clickhouse_engine_default._engine_name is None
duckdb_conn.close()
+ clickhouse_conn.close()
@pytest.mark.skipif(not HAS_DUCKDB, reason="Duckdb not installed")
@@ -116,13 +126,13 @@ def test_duckdb_get_current_database_and_schema() -> None:
engine = DuckDBEngine(duckdb_conn)
# These should return values for an in-memory database
- assert engine.get_current_database() is not None
- assert engine.get_current_schema() is not None
+ assert engine.get_default_database() is not None
+ assert engine.get_default_schema() is not None
# Test error handling by closing the connection before calling methods
duckdb_conn.close()
- assert engine.get_current_database() is None
- assert engine.get_current_schema() is None
+ assert engine.get_default_database() is None
+ assert engine.get_default_schema() is None
# Connection already closed, no need to close again
@@ -208,7 +218,9 @@ def test_sqlalchemy_get_table_details() -> None:
# Get table details
table_details = engine.get_table_details(
- "test_table", "main"
+ table_name="test_table",
+ schema_name="main",
+ database_name=UNUSED_DB_NAME,
) # main is default schema in SQLite
assert table_details is not None
@@ -290,32 +302,32 @@ def test_sqlalchemy_execute() -> None:
def test_sql_type_to_data_type() -> None:
- """Test _sql_type_to_data_type function."""
+ """Test sql_type_to_data_type function."""
# Now that the raise statement is removed, we can test directly
# Test integer types
for int_type in ["INTEGER", "INT", "BIGINT", "SERIAL"]:
- assert _sql_type_to_data_type(int_type) == "integer"
+ assert sql_type_to_data_type(int_type) == "integer"
# Test float types
for float_type in ["FLOAT", "DOUBLE", "DECIMAL", "NUMERIC"]:
- assert _sql_type_to_data_type(float_type) == "number"
+ assert sql_type_to_data_type(float_type) == "number"
# Test datetime types
for dt_type in ["TIMESTAMP", "DATETIME"]:
- assert _sql_type_to_data_type(dt_type) == "datetime"
+ assert sql_type_to_data_type(dt_type) == "datetime"
# Test date type
- assert _sql_type_to_data_type("DATE") == "date"
+ assert sql_type_to_data_type("DATE") == "date"
# Test boolean type
- assert _sql_type_to_data_type("BOOLEAN") == "boolean"
+ assert sql_type_to_data_type("BOOLEAN") == "boolean"
# Test string types
for str_type in ["VARCHAR", "CHAR", "TEXT"]:
- assert _sql_type_to_data_type(str_type) == "string"
+ assert sql_type_to_data_type(str_type) == "string"
# Test unknown type
- assert _sql_type_to_data_type("UNKNOWN_TYPE") == "string"
+ assert sql_type_to_data_type("UNKNOWN_TYPE") == "string"
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.py
index 2a3f9d0a3a..b0b2f0ab0e 100644
--- a/tests/_sql/test_get_engines.py
+++ b/tests/_sql/test_get_engines.py
@@ -11,11 +11,12 @@ from marimo._data.models import (
Schema,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines import (
+from marimo._sql.engines.clickhouse import ClickhouseEmbedded
+from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
DuckDBEngine,
- SQLAlchemyEngine,
)
+from marimo._sql.engines.sqlalchemy import SQLAlchemyEngine
from marimo._sql.get_engines import (
engine_to_data_source_connection,
get_engines_from_variables,
@@ -24,6 +25,7 @@ from marimo._sql.sql import sql
HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()
HAS_DUCKDB = DependencyManager.duckdb.has()
+HAS_CLICKHOUSE = DependencyManager.chdb.has()
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
@@ -42,6 +44,20 @@ def test_engine_to_data_source_connection() -> None:
assert connection.default_schema == "main"
assert connection.databases == []
+ # Test with ClickhouseEmbedded engine
+ clickhouse_engine = ClickhouseEmbedded(None)
+ connection = engine_to_data_source_connection(
+ "my_clickhouse", clickhouse_engine
+ )
+ assert isinstance(connection, DataSourceConnection)
+ assert connection.source == "clickhouse"
+ assert connection.dialect == "clickhouse"
+ assert connection.name == "my_clickhouse"
+ assert connection.display_name == "clickhouse (my_clickhouse)"
+ # assert connection.default_database == "default"
+ # assert connection.default_schema == "default"
+ assert connection.databases == []
+
# Test with SQLAlchemy engine
mock_sqlalchemy_engine = MagicMock()
mock_sqlalchemy_engine.dialect.name = "postgresql"
@@ -73,6 +89,22 @@ def test_get_engines_from_variables_duckdb():
assert isinstance(engine, DuckDBEngine)
[email protected](not HAS_CLICKHOUSE, reason="Clickhouse not installed")
+def test_get_engines_from_variables_clickhouse():
+ import chdb
+
+ mock_clickhouse_conn = MagicMock(spec=chdb.state.sqlitelike.Connection)
+ variables: list[tuple[str, object]] = [
+ ("clickhouse_conn", mock_clickhouse_conn)
+ ]
+
+ engines = get_engines_from_variables(variables)
+ assert len(engines) == 1
+ var_name, engine = engines[0]
+ assert var_name == "clickhouse_conn"
+ assert isinstance(engine, ClickhouseEmbedded)
+
+
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
def test_get_engines_from_variables_sqlalchemy() -> None:
import sqlalchemy as sa
@@ -99,25 +131,28 @@ def test_get_engines_from_variables_mixed():
@pytest.mark.skipif(
- not (HAS_SQLALCHEMY and HAS_DUCKDB),
+ not (HAS_SQLALCHEMY and HAS_DUCKDB and HAS_CLICKHOUSE),
reason="SQLAlchemy or DuckDB not installed",
)
def test_get_engines_from_variables_multiple():
+ import chdb
import duckdb
import sqlalchemy as sa
mock_duckdb_conn = MagicMock(spec=duckdb.DuckDBPyConnection)
+ mock_clickhouse = MagicMock(spec=chdb.state.sqlitelike.Connection)
sqlalchemy_engine = sa.create_engine("sqlite:///:memory:")
variables: list[tuple[str, object]] = [
("sa_engine", sqlalchemy_engine),
("duckdb_conn", mock_duckdb_conn),
+ ("clickhouse_conn", mock_clickhouse),
("not_an_engine", "some string"),
]
engines = get_engines_from_variables(variables)
- assert len(engines) == 2
+ assert len(engines) == 3
# Check SQLAlchemy engine
sa_var_name, _sa_engine = next(
@@ -133,6 +168,14 @@ def test_get_engines_from_variables_multiple():
)
assert duckdb_var_name == "duckdb_conn"
+ # Check Clickhouse engine
+ ch_var_name, _ch_engine = next(
+ (name, eng)
+ for name, eng in engines
+ if isinstance(eng, ClickhouseEmbedded)
+ )
+ assert ch_var_name == "clickhouse_conn"
+
@pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")
def test_get_engines_duckdb_databases() -> None:
@@ -203,3 +246,23 @@ def test_get_engines_sqlalchemy_databases() -> None:
schemas=[Schema(name="main", tables=[])],
)
]
+
+
[email protected](not HAS_CLICKHOUSE, reason="Clickhouse not installed")
+def test_get_engines_clickhouse() -> None:
+ import chdb
+
+ clickhouse_conn = chdb.connect(":memory:")
+ engine = ClickhouseEmbedded(clickhouse_conn, engine_name="clickhouse")
+ variable_name = "clickhouse_conn"
+
+ connection = engine_to_data_source_connection(variable_name, engine)
+ assert isinstance(connection, DataSourceConnection)
+
+ assert connection.source == "clickhouse"
+ assert connection.dialect == "clickhouse"
+ assert connection.name == variable_name
+ assert connection.display_name == f"clickhouse ({variable_name})"
+ # assert connection.default_database == "default"
+ # assert connection.default_schema == "default"
+ assert connection.databases == []
diff --git a/tests/_sql/test_sqlalchemy.py b/tests/_sql/test_sqlalchemy.py
index aaa4882570..922f6c0085 100644
--- a/tests/_sql/test_sqlalchemy.py
+++ b/tests/_sql/test_sqlalchemy.py
@@ -9,7 +9,7 @@ import pytest
from marimo._data.models import Database, DataTable, DataTableColumn, Schema
from marimo._dependencies.dependencies import DependencyManager
-from marimo._sql.engines import (
+from marimo._sql.engines.sqlalchemy import (
SQLAlchemyEngine,
)
from marimo._sql.sql import sql
@@ -22,6 +22,8 @@ HAS_PANDAS = DependencyManager.pandas.has()
if TYPE_CHECKING:
import sqlalchemy as sa
+UNUSED_DB_NAME = "unused_db_name"
+
@pytest.fixture
def empty_sqlite_engine() -> sa.Engine:
@@ -93,7 +95,7 @@ def test_sqlalchemy_engine_dialect(sqlite_engine: sa.Engine) -> None:
def test_sqlalchemy_invalid_engine() -> None:
"""Test SQLAlchemyEngine with an invalid engine and inspector does not raise errors."""
- engine = SQLAlchemyEngine(engine=None) # type: ignore
+ engine = SQLAlchemyEngine(connection=None) # type: ignore
assert engine.inspector is None
assert engine.default_database is None
assert engine.default_schema is None
@@ -103,7 +105,7 @@ def test_sqlalchemy_invalid_engine() -> None:
def test_sqlalchemy_empty_engine(empty_sqlite_engine: sa.Engine) -> None:
"""Test SQLAlchemyEngine with an empty engine."""
engine = SQLAlchemyEngine(
- engine=empty_sqlite_engine, engine_name=VariableName("sqlite")
+ connection=empty_sqlite_engine, engine_name=VariableName("sqlite")
)
databases = engine.get_databases(
@@ -119,11 +121,13 @@ def test_sqlalchemy_empty_engine(empty_sqlite_engine: sa.Engine) -> None:
]
tables = engine.get_tables_in_schema(
- schema="main", include_table_details=False
+ schema="main", database=UNUSED_DB_NAME, include_table_details=False
)
assert tables == []
- table_info = engine.get_table_details("test", "main")
+ table_info = engine.get_table_details(
+ table_name="test", schema_name="main", database_name=UNUSED_DB_NAME
+ )
assert table_info is None
@@ -172,7 +176,7 @@ def test_sqlalchemy_sql_types() -> None:
sqlite_engine, engine_name=VariableName("test_sqlite")
)
tables = engine.get_tables_in_schema(
- schema="main", include_table_details=True
+ schema="main", database=UNUSED_DB_NAME, include_table_details=True
)
assert len(tables) == 1
@@ -255,18 +259,38 @@ def test_sqlalchemy_engine_get_table_details(sqlite_engine: sa.Engine) -> None:
engine = SQLAlchemyEngine(
sqlite_engine, engine_name=VariableName("test_sqlite")
)
- table = engine.get_table_details("test", "main")
+ table = engine.get_table_details(
+ table_name="test", schema_name="main", database_name=UNUSED_DB_NAME
+ )
assert table == get_expected_table("test")
# different schema
- table = engine.get_table_details("test2", "my_schema")
+ table = engine.get_table_details(
+ table_name="test2",
+ schema_name="my_schema",
+ database_name=UNUSED_DB_NAME,
+ )
assert table == get_expected_table("test2")
# non-existent table
- assert engine.get_table_details("non_existent", "main") is None
+ assert (
+ engine.get_table_details(
+ table_name="non_existent",
+ schema_name="main",
+ database_name=UNUSED_DB_NAME,
+ )
+ is None
+ )
# non-existent schema
- assert engine.get_table_details("test", "non_existent") is None
+ assert (
+ engine.get_table_details(
+ table_name="test",
+ schema_name="non_existent",
+ database_name=UNUSED_DB_NAME,
+ )
+ is None
+ )
@pytest.mark.skipif(not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")
@@ -278,7 +302,7 @@ def test_sqlalchemy_engine_get_tables_in_schema(
sqlite_engine, engine_name=VariableName("test_sqlite")
)
tables = engine.get_tables_in_schema(
- schema="main", include_table_details=True
+ schema="main", database=UNUSED_DB_NAME, include_table_details=True
)
assert isinstance(tables, list)
@@ -287,7 +311,7 @@ def test_sqlalchemy_engine_get_tables_in_schema(
# Test with other schema
tables = engine.get_tables_in_schema(
- schema="my_schema", include_table_details=True
+ schema="my_schema", database=UNUSED_DB_NAME, include_table_details=True
)
assert isinstance(tables, list)
assert len(tables) == 1
@@ -296,14 +320,16 @@ def test_sqlalchemy_engine_get_tables_in_schema(
# Test with non-existent schema
assert (
engine.get_tables_in_schema(
- schema="non_existent", include_table_details=True
+ schema="non_existent",
+ database=UNUSED_DB_NAME,
+ include_table_details=True,
)
== []
)
# Test with include_table_details false
tables = engine.get_tables_in_schema(
- schema="main", include_table_details=False
+ schema="main", database=UNUSED_DB_NAME, include_table_details=False
)
assert isinstance(tables, list)
assert len(tables) == 1
@@ -318,7 +344,9 @@ def test_sqlalchemy_engine_get_schemas(sqlite_engine: sa.Engine) -> None:
sqlite_engine, engine_name=VariableName("test_sqlite")
)
schemas = engine._get_schemas(
- include_tables=True, include_table_details=True
+ database=UNUSED_DB_NAME,
+ include_tables=True,
+ include_table_details=True,
)
assert isinstance(schemas, list)
@@ -332,7 +360,9 @@ def test_sqlalchemy_engine_get_schemas(sqlite_engine: sa.Engine) -> None:
# Test with include_table_details false
schemas = engine._get_schemas(
- include_tables=True, include_table_details=False
+ database=UNUSED_DB_NAME,
+ include_tables=True,
+ include_table_details=False,
)
assert isinstance(schemas, list)
assert len(schemas) == 2
@@ -346,7 +376,9 @@ def test_sqlalchemy_engine_get_schemas(sqlite_engine: sa.Engine) -> None:
# Test with include_tables false
schemas = engine._get_schemas(
- include_tables=False, include_table_details=True
+ database=UNUSED_DB_NAME,
+ include_tables=False,
+ include_table_details=True,
)
assert isinstance(schemas, list)
assert len(schemas) == 2
@@ -515,10 +547,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_current_database() == ":memory:"
+ assert engine.get_default_database() == ":memory:"
import sqlalchemy as sa
# Test with no database name
engine = SQLAlchemyEngine(sa.create_engine("sqlite:///"))
- assert engine._get_current_database() == ""
+ assert engine.get_default_database() == ""