A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: pyiceberg catalog support (#4715)
Myles Scolnick2b9a0884f6f7
diff --git a/docs/guides/working_with_data/sql.md b/docs/guides/working_with_data/sql.mdindex bed1c670aa..1f3a579e04 100644--- a/docs/guides/working_with_data/sql.md+++ b/docs/guides/working_with_data/sql.md@@ -259,6 +259,31 @@ marimo will automatically discover the database connection and display the databauto_discover_columns = "auto" # Default: false```+## Catalogs++marimo supports connecting to Iceberg catalogs. You can click the "plus" button in the Datasources panel or manually create a [PyIceberg](https://py.iceberg.apache.org/) `Catalog` connection. PyIceberg supports a variety of catalog implementations including REST, SQL, Glue, DynamoDB, and more.++```python+from pyiceberg.catalog.rest import RestCatalog++catalog = RestCatalog(+ name="catalog",+ warehouse="1234567890",+ uri="https://my-catalog.com",+ token="my-token",+)+```++Catalogs will appear in the Datasources panel, but they cannot be used as an engine in SQL cells. However, you can still load the table into one cell and use it in subsequent Python or SQL cells.++```python+df = catalog.load_table(("my-namespace", "my-table")).to_polars()+```++```sql+SUMMARIZE df;+```+## Interactive tutorialFor an interactive tutorial, rundiff --git a/frontend/src/components/databases/display.tsx b/frontend/src/components/databases/display.tsxindex edd2e0ba59..00a135689c 100644--- a/frontend/src/components/databases/display.tsx+++ b/frontend/src/components/databases/display.tsx@@ -48,6 +48,8 @@ export function dbDisplayName(name: string) {return "Apache Cassandra";case "mongodb":return "MongoDB";+ case "iceberg":+ return "Apache Iceberg";default:return name;}diff --git a/frontend/src/components/databases/icon.tsx b/frontend/src/components/databases/icon.tsxindex 80f665c913..6ffda606ac 100644--- a/frontend/src/components/databases/icon.tsx+++ b/frontend/src/components/databases/icon.tsx@@ -10,6 +10,7 @@ import ClickhouseIcon from "./icons/clickhouse.svg";import TimeplusIcon from "./icons/timeplus.svg";import GoogleBigQueryIcon from "./icons/googlebigquery.svg";import TrinoIcon from "./icons/trino.svg";+import IcebergIcon from "./icons/iceberg.png";import { cn } from "@/utils/cn";export type DBLogoName =@@ -23,7 +24,8 @@ export type DBLogoName =| "clickhouse"| "timeplus"| "bigquery"- | "trino";+ | "trino"+ | "iceberg";/*** Icons are from https://simpleicons.org/@@ -46,6 +48,7 @@ const URLS: Record<DBLogoName, string | undefined> = {timeplus: TimeplusIcon,bigquery: GoogleBigQueryIcon,trino: TrinoIcon,+ iceberg: IcebergIcon,};export const DatabaseLogo: FC<DatabaseLogoProps> = ({ name, className }) => {@@ -61,7 +64,13 @@ export const DatabaseLogo: FC<DatabaseLogoProps> = ({ name, className }) => {<imgsrc={url}alt={name}- className={cn("invert-[.5] dark:invert-[.7]", className)}+ className={cn(+ "invert-[.5] dark:invert-[.7]",+ className,+ // Remove filters for PNG icons+ url.endsWith(".png") &&+ "brightness-100 dark:brightness-100 invert-0 dark:invert-0",+ )}/>);};diff --git a/frontend/src/components/databases/icons/iceberg.png b/frontend/src/components/databases/icons/iceberg.pngnew file mode 100644index 0000000000..e4a99c3951Binary files /dev/null and b/frontend/src/components/databases/icons/iceberg.png differdiff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsxindex 1c502d90d7..7f61db4be7 100644--- a/frontend/src/components/datasources/datasources.tsx+++ b/frontend/src/components/datasources/datasources.tsx@@ -135,7 +135,7 @@ export const DataSources: React.FC = () => {action={<AddDatabaseDialog><Button variant="outline" size="sm">- Add database+ Add database or catalog<PlusIcon className="h-4 w-4 ml-2" /></Button></AddDatabaseDialog>@@ -514,26 +514,32 @@ const DatasetTableItem: React.FC<{const handleAddTable = () => {maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);- let code = "";- if (sqlTableContext) {- code = sqlCode(table, "*", sqlTableContext);- } else {+ const getCode = () => {+ if (table.source_type === "catalog") {+ const identifier = sqlTableContext?.database+ ? `${sqlTableContext.database}.${table.name}`+ : table.name;+ return `${table.engine}.load_table("${identifier}")`;+ }++ if (sqlTableContext) {+ return sqlCode(table, "*", sqlTableContext);+ }+switch (table.source_type) {case "local":- code = `mo.ui.table(${table.name})`;- break;+ return `mo.ui.table(${table.name})`;case "duckdb":case "connection":- code = sqlCode(table, "*", sqlTableContext);- break;+ return sqlCode(table, "*", sqlTableContext);default:logNever(table.source_type);- break;+ return "";}- }+ };createNewCell({- code,+ code: getCode(),before: false,cellId: lastFocusedCellId ?? "__end__",});@@ -803,6 +809,14 @@ const DatasetColumnPreview: React.FC<{);}+ if (table.source_type === "catalog") {+ return (+ <span className="text-xs text-muted-foreground gap-2 flex items-center justify-between pl-7">+ {column.name} ({column.external_type})+ </span>+ );+ }+if (!preview) {return <span className="text-xs text-muted-foreground">Loading...</span>;}diff --git a/frontend/src/components/editor/database/__tests__/__snapshots__/as-code.test.ts.snap b/frontend/src/components/editor/database/__tests__/__snapshots__/as-code.test.ts.snapindex 942d29bf9f..986f74017d 100644--- a/frontend/src/components/editor/database/__tests__/__snapshots__/as-code.test.ts.snap+++ b/frontend/src/components/editor/database/__tests__/__snapshots__/as-code.test.ts.snap@@ -35,6 +35,68 @@ DATABASE_URL = "data.duckdb"engine = duckdb.connect(DATABASE_URL, read_only=True)"`;+exports[`generateDatabaseCode > basic connections > iceberg dynamodb 1`] = `+"from pyiceberg.catalog.dynamodb import DynamoDBCatalog++catalog = DynamoDBCatalog(+ "my_catalog",+ **{+ "dynamodb.profile-name": "my_profile",+ "dynamodb.region": "us-east-1",+ "dynamodb.access-key-id": "my_access_key_id",+ "dynamodb.secret-access-key": "my_secret_access_key",+ "dynamodb.session-token": "my_session_token"+ },+)"+`;++exports[`generateDatabaseCode > basic connections > iceberg glue 1`] = `+"from pyiceberg.catalog.glue import GlueCatalog++catalog = GlueCatalog(+ "my_catalog",+ **{+ "warehouse": "/path/to/warehouse"+ },+)"+`;++exports[`generateDatabaseCode > basic connections > iceberg hive 1`] = `+"from pyiceberg.catalog.hive import HiveCatalog++catalog = HiveCatalog(+ "my_catalog",+ **{+ "uri": "thrift://localhost:9083",+ "warehouse": "/path/to/warehouse"+ },+)"+`;++exports[`generateDatabaseCode > basic connections > iceberg rest 1`] = `+"from pyiceberg.catalog.rest import RestCatalog++catalog = RestCatalog(+ "my_catalog",+ **{+ "uri": "http://localhost:8181",+ "warehouse": "/path/to/warehouse"+ },+)"+`;++exports[`generateDatabaseCode > basic connections > iceberg sql 1`] = `+"from pyiceberg.catalog.sql import SqlCatalog++catalog = SqlCatalog(+ "my_catalog",+ **{+ "uri": "postgresql://localhost:5432/iceberg",+ "warehouse": "/path/to/warehouse"+ },+)"+`;+exports[`generateDatabaseCode > basic connections > mysql with SQLAlchemy 1`] = `"import osimport sqlalchemydiff --git a/frontend/src/components/editor/database/__tests__/as-code.test.ts b/frontend/src/components/editor/database/__tests__/as-code.test.tsindex 865b5187f2..45e7352955 100644--- a/frontend/src/components/editor/database/__tests__/as-code.test.ts+++ b/frontend/src/components/editor/database/__tests__/as-code.test.ts@@ -88,6 +88,58 @@ describe("generateDatabaseCode", () => {async_support: false,};+ const icebergRestConnection: DatabaseConnection = {+ type: "iceberg",+ name: "my_catalog",+ catalog: {+ type: "rest",+ uri: "http://localhost:8181",+ warehouse: "/path/to/warehouse",+ },+ };++ const icebergSqlConnection: DatabaseConnection = {+ type: "iceberg",+ name: "my_catalog",+ catalog: {+ type: "sql",+ uri: "postgresql://localhost:5432/iceberg",+ warehouse: "/path/to/warehouse",+ },+ };++ const icebergHiveConnection: DatabaseConnection = {+ type: "iceberg",+ name: "my_catalog",+ catalog: {+ type: "hive",+ uri: "thrift://localhost:9083",+ warehouse: "/path/to/warehouse",+ },+ };++ const icebergGlueConnection: DatabaseConnection = {+ type: "iceberg",+ name: "my_catalog",+ catalog: {+ type: "glue",+ warehouse: "/path/to/warehouse",+ },+ };++ const icebergDynamoDBConnection: DatabaseConnection = {+ type: "iceberg",+ name: "my_catalog",+ catalog: {+ type: "dynamodb",+ "dynamodb.profile-name": "my_profile",+ "dynamodb.region": "us-east-1",+ "dynamodb.access-key-id": "my_access_key_id",+ "dynamodb.secret-access-key": "my_secret_access_key",+ "dynamodb.session-token": "my_session_token",+ },+ };+describe("basic connections", () => {it.each([["postgres with SQLModel", basePostgres, "sqlmodel"],@@ -102,6 +154,11 @@ describe("generateDatabaseCode", () => {["chdb", chdbConnection, "chdb"],["timeplus", timeplusConnection, "sqlalchemy"],["trino", trinoConnection, "sqlmodel"],+ ["iceberg rest", icebergRestConnection, "pyiceberg"],+ ["iceberg sql", icebergSqlConnection, "pyiceberg"],+ ["iceberg hive", icebergHiveConnection, "pyiceberg"],+ ["iceberg glue", icebergGlueConnection, "pyiceberg"],+ ["iceberg dynamodb", icebergDynamoDBConnection, "pyiceberg"],])("%s", (name, connection, orm) => {expect(generateDatabaseCode(connection, orm as ConnectionLibrary),diff --git a/frontend/src/components/editor/database/add-database-form.tsx b/frontend/src/components/editor/database/add-database-form.tsxindex 59314f361e..9775786bc2 100644--- a/frontend/src/components/editor/database/add-database-form.tsx+++ b/frontend/src/components/editor/database/add-database-form.tsx@@ -17,6 +17,7 @@ import {TimeplusConnectionSchema,ChdbConnectionSchema,TrinoConnectionSchema,+ IcebergConnectionSchema,} from "./schemas";import {Dialog,@@ -51,8 +52,19 @@ interface Props {onSubmit: () => void;}+interface ConnectionSchema {+ name: string;+ schema: z.ZodType;+ color: string;+ logo: DBLogoName;+ connectionLibraries: {+ libraries: ConnectionLibrary[];+ preferred: ConnectionLibrary;+ };+}+// default to sqlalchemy because it has fewer dependencies-const SCHEMAS = [+const DATABASES = [{name: "PostgreSQL",schema: PostgresConnectionSchema,@@ -153,38 +165,55 @@ const SCHEMAS = [preferred: "sqlalchemy",},},-] satisfies Array<{- name: string;- schema: z.ZodType;- color: string;- logo: DBLogoName;- connectionLibraries: {- libraries: ConnectionLibrary[];- preferred: ConnectionLibrary;- };-}>;+] satisfies ConnectionSchema[];++const DATA_CATALOGS = [+ {+ name: "Iceberg",+ schema: IcebergConnectionSchema,+ color: "#000000",+ logo: "iceberg",+ connectionLibraries: {+ libraries: ["pyiceberg"],+ preferred: "pyiceberg",+ },+ },+] satisfies ConnectionSchema[];const DatabaseSchemaSelector: React.FC<{onSelect: (schema: z.ZodType) => void;}> = ({ onSelect }) => {+ const renderItem = ({ name, schema, color, logo }: ConnectionSchema) => {+ return (+ <button+ type="button"+ key={name}+ className="py-3 flex flex-col items-center justify-center gap-1 transition-all hover:scale-105 hover:brightness-110 rounded shadow-smSolid hover:shadow-mdSolid"+ style={{ backgroundColor: color }}+ onClick={() => onSelect(schema)}+ >+ <DatabaseLogo+ name={logo}+ className="w-8 h-8 text-white brightness-0 invert dark:invert"+ />+ <span className="text-white font-medium text-lg">{name}</span>+ </button>+ );+ };+return (- <div className="grid grid-cols-2 md:grid-cols-3 gap-6">- {SCHEMAS.map(({ name, schema, color, logo }) => (- <button- type="button"- key={name}- className="h-28 flex flex-col items-center justify-center gap-3 transition-all hover:scale-105 hover:brightness-110 rounded shadow-smSolid hover:shadow-mdSolid"- style={{ backgroundColor: color }}- onClick={() => onSelect(schema)}- >- <DatabaseLogo- name={logo}- className="w-10 h-10 text-white brightness-0 invert dark:invert"- />- <span className="text-white font-medium text-lg">{name}</span>- </button>- ))}- </div>+ <>+ <div className="grid grid-cols-2 md:grid-cols-3 gap-4">+ {DATABASES.map(renderItem)}+ </div>+ <h4 className="font-semibold text-muted-foreground text-lg flex items-center gap-4">+ Data Catalogs+ <hr className="flex-1" />+ </h4>+ <div className="grid grid-cols-2 md:grid-cols-3 gap-4">+ {DATA_CATALOGS.map(renderItem)}+ </div>+ </>);};@@ -201,7 +230,7 @@ const DatabaseForm: React.FC<{reValidateMode: "onChange",});- const connectionLibraries = SCHEMAS.find(+ const connectionLibraries = DATABASES.find((s) => s.schema === schema,)?.connectionLibraries;const [preferredConnection, setPreferredConnection] =@@ -305,12 +334,12 @@ export const AddDatabaseDialogContent: React.FC<{onClose: () => void;}> = ({ onClose }) => {return (- <DialogContent>+ <DialogContent className="max-h-[75vh] overflow-y-auto"><DialogHeader className="mb-4">- <DialogTitle>Add Database Connection</DialogTitle>+ <DialogTitle>Add Connection</DialogTitle><DialogDescription>- Connect to your database to query data directly from your notebook.- Learn more about how to connect to your database in our{" "}+ Connect to your database or data catalog to query data directly from+ your notebook. Learn more about how to connect to your database in our{" "}<ExternalLink href="https://docs.marimo.io/guides/working_with_data/sql/#connecting-to-a-custom-database">docs.</ExternalLink>diff --git a/frontend/src/components/editor/database/as-code.ts b/frontend/src/components/editor/database/as-code.tsindex cef5cf1674..603dfc1f14 100644--- a/frontend/src/components/editor/database/as-code.ts+++ b/frontend/src/components/editor/database/as-code.ts@@ -10,7 +10,8 @@ export type ConnectionLibrary =| "sqlalchemy"| "duckdb"| "clickhouse_connect"- | "chdb";+ | "chdb"+ | "pyiceberg";export const ConnectionDisplayNames: Record<ConnectionLibrary, string> = {sqlmodel: "SQLModel",@@ -18,6 +19,7 @@ export const ConnectionDisplayNames: Record<ConnectionLibrary, string> = {duckdb: "DuckDB",clickhouse_connect: "ClickHouse Connect",chdb: "chDB",+ pyiceberg: "PyIceberg",};abstract class CodeGenerator<T extends DatabaseConnection["type"]> {@@ -425,6 +427,98 @@ class TrinoGenerator extends CodeGenerator<"trino"> {}}+class PyIcebergGenerator extends CodeGenerator<"iceberg"> {+ generateImports(): string[] {+ switch (this.connection.catalog.type) {+ case "rest":+ return ["from pyiceberg.catalog.rest import RestCatalog"];+ case "sql":+ return ["from pyiceberg.catalog.sql import SqlCatalog"];+ case "hive":+ return ["from pyiceberg.catalog.hive import HiveCatalog"];+ case "glue":+ return ["from pyiceberg.catalog.glue import GlueCatalog"];+ case "dynamodb":+ return ["from pyiceberg.catalog.dynamodb import DynamoDBCatalog"];+ default:+ assertNever(this.connection.catalog);+ }+ }++ generateConnectionCode(): string {+ let options: Record<string, string | number | boolean> = {+ ...this.connection.catalog,+ };+ // Remove k='type' and v=nullish values+ options = Object.fromEntries(+ Object.entries(options).filter(+ ([k, v]) => v != null && v !== "" && k !== "type",+ ),+ );+ // Convert to secrets if they are secrets+ for (const [k, v] of Object.entries(options)) {+ if (isSecret(v)) {+ options[k] = this.secrets.print(k, v);+ } else if (typeof v === "string") {+ options[k] = `"${v}"`;+ }+ }++ const indent = " ";+ const optionsAsPython = formatDictionaryEntries(+ options,+ (line) => `${indent}${line}`,+ );++ const name = `"${this.connection.name}"`;++ switch (this.connection.catalog.type) {+ case "rest":+ return dedent(`+ catalog = RestCatalog(+ ${name},+ **{\n${optionsAsPython}+ },+ )+ `);+ case "sql":+ return dedent(`+ catalog = SqlCatalog(+ ${name},+ **{\n${optionsAsPython}+ },+ )+ `);+ case "hive":+ return dedent(`+ catalog = HiveCatalog(+ ${name},+ **{\n${optionsAsPython}+ },+ )+ `);+ case "glue":+ return dedent(`+ catalog = GlueCatalog(+ ${name},+ **{\n${optionsAsPython}+ },+ )+ `);+ case "dynamodb":+ return dedent(`+ catalog = DynamoDBCatalog(+ ${name},+ **{\n${optionsAsPython}+ },+ )+ `);+ default:+ assertNever(this.connection.catalog);+ }+ }+}+class CodeGeneratorFactory {public secrets = new SecretContainer();@@ -453,6 +547,8 @@ class CodeGeneratorFactory {return new ChDBGenerator(connection, orm, this.secrets);case "trino":return new TrinoGenerator(connection, orm, this.secrets);+ case "iceberg":+ return new PyIcebergGenerator(connection, orm, this.secrets);default:assertNever(connection);}@@ -512,3 +608,22 @@ function formatUrlParams(}).join(",\n");}++function formatDictionaryEntries(+ params: Record<string, string | number | boolean | undefined>,+ formatLine: (line: string) => string,+): string {+ return Object.entries(params)+ .filter(([, v]) => v != null && v !== "")+ .map(([k, v]) => {+ const key = `"${k}"`;+ if (typeof v === "boolean") {+ return formatLine(`${key}: ${formatBoolean(v)}`);+ }+ if (typeof v === "number") {+ return formatLine(`${key}: ${v}`);+ }+ return formatLine(`${key}: ${v}`);+ })+ .join(",\n");+}diff --git a/frontend/src/components/editor/database/schemas.ts b/frontend/src/components/editor/database/schemas.tsindex b72bf6469c..759ce2e9e3 100644--- a/frontend/src/components/editor/database/schemas.ts+++ b/frontend/src/components/editor/database/schemas.ts@@ -16,6 +16,40 @@ function passwordField() {);}+function tokenField() {+ return z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "Token",+ inputType: "password",+ placeholder: "token",+ optionRegex: ".*token.*",+ }),+ );+}++function warehouseNameField() {+ return z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "Warehouse Name",+ placeholder: "warehouse",+ optionRegex: ".*warehouse.*",+ }),+ );+}++function uriField() {+ return z+ .string()+ .optional()+ .describe(FieldOptions.of({ label: "URI", optionRegex: ".*uri.*" }));+}+function hostField() {return z.string()@@ -259,6 +293,87 @@ export const TrinoConnectionSchema = z}).describe(FieldOptions.of({ direction: "two-columns" }));+export const IcebergConnectionSchema = z.object({+ type: z.literal("iceberg"),+ name: z.string().describe(FieldOptions.of({ label: "Catalog Name" })),+ catalog: z+ .discriminatedUnion("type", [+ z.object({+ type: z.literal("rest"),+ warehouse: warehouseNameField(),+ uri: z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "URI",+ placeholder: "https://",+ optionRegex: ".*uri.*",+ }),+ ),+ token: tokenField(),+ }),+ z.object({+ type: z.literal("sql"),+ warehouse: warehouseNameField(),+ uri: z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "URI",+ placeholder: "jdbc:iceberg://host:port/database",+ optionRegex: ".*uri.*",+ }),+ ),+ }),+ z.object({+ type: z.literal("hive"),+ warehouse: warehouseNameField(),+ uri: uriField(),+ }),+ z.object({+ type: z.literal("glue"),+ warehouse: warehouseNameField(),+ uri: uriField(),+ }),+ z.object({+ type: z.literal("dynamodb"),+ "dynamodb.profile-name": z+ .string()+ .optional()+ .describe(FieldOptions.of({ label: "Profile Name" })),+ "dynamodb.region": z+ .string()+ .optional()+ .describe(FieldOptions.of({ label: "Region" })),+ "dynamodb.access-key-id": z+ .string()+ .optional()+ .describe(FieldOptions.of({ label: "Access Key ID" })),+ "dynamodb.secret-access-key": z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "Secret Access Key",+ inputType: "password",+ }),+ ),+ "dynamodb.session-token": z+ .string()+ .optional()+ .describe(+ FieldOptions.of({+ label: "Session Token",+ inputType: "password",+ }),+ ),+ }),+ ])+ .describe(FieldOptions.of({ special: "tabs" })),+});+export const DatabaseConnectionSchema = z.discriminatedUnion("type", [PostgresConnectionSchema,MySQLConnectionSchema,@@ -270,6 +385,7 @@ export const DatabaseConnectionSchema = z.discriminatedUnion("type", [TimeplusConnectionSchema,ChdbConnectionSchema,TrinoConnectionSchema,+ IcebergConnectionSchema,]);export type DatabaseConnection = z.infer<typeof DatabaseConnectionSchema>;diff --git a/frontend/src/components/forms/form-utils.ts b/frontend/src/components/forms/form-utils.tsindex cdcefeee43..ed18389a9a 100644--- a/frontend/src/components/forms/form-utils.ts+++ b/frontend/src/components/forms/form-utils.ts@@ -25,7 +25,10 @@ export function getDefaults<TSchema extends z.ZodType<T>, T>(};// If union, take the first one- if (schema instanceof z.ZodUnion) {+ if (+ schema instanceof z.ZodUnion ||+ schema instanceof z.ZodDiscriminatedUnion+ ) {return getDefaultValue(schema._def.options[0]) as T;}@@ -75,7 +78,10 @@ export function getUnionLiteral<T extends z.ZodType<unknown>>(}throw new Error(`Invalid schema: ${schema._type}`);}- if (schema instanceof z.ZodUnion) {+ if (+ schema instanceof z.ZodUnion ||+ schema instanceof z.ZodDiscriminatedUnion+ ) {return getUnionLiteral(schema._def.options[0]);}Logger.warn(schema);diff --git a/frontend/src/components/forms/form.tsx b/frontend/src/components/forms/form.tsxindex 76889e1758..b14e691d30 100644--- a/frontend/src/components/forms/form.tsx+++ b/frontend/src/components/forms/form.tsx@@ -327,6 +327,64 @@ export function renderZodSchema<T extends FieldValues, S>(</div>);}++ if (schema instanceof z.ZodDiscriminatedUnion) {+ const options = schema._def.options as Array<z.ZodType<unknown>>;+ const discriminator = schema._def.discriminator;+ const optionsMap = schema._def.optionsMap;+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => {+ const value = field.value;+ const types = options.map((option) => {+ return getUnionLiteral(option)._def.value;+ });++ const unionTypeValue: string =+ value && typeof value === "object" && discriminator in value+ ? value[discriminator]+ : types[0];++ const selectedOption = optionsMap.get(unionTypeValue) || options[0];++ return (+ <div className="flex flex-col">+ <FormLabel>{label}</FormLabel>+ <div className="flex border-b mb-4 -mt-2">+ {types.map((type: string) => (+ <button+ key={type}+ type="button"+ className={`px-4 py-2 ${+ unionTypeValue === type+ ? "border-b-2 border-primary font-medium"+ : "text-muted-foreground"+ }`}+ onClick={() => {+ const nextSchema = optionsMap.get(type);+ if (nextSchema) {+ field.onChange(getDefaults(nextSchema));+ } else {+ field.onChange({ [discriminator]: type });+ }+ }}+ >+ {type}+ </button>+ ))}+ </div>+ <div className="flex flex-col" key={unionTypeValue}>+ {selectedOption &&+ renderZodSchema(selectedOption, form, path, renderers)}+ </div>+ </div>+ );+ }}+ />+ );+ }if (schema instanceof z.ZodUnion) {return (<FormField@@ -349,7 +407,7 @@ export function renderZodSchema<T extends FieldValues, S>(});return (- <div className="flex flex-col">+ <div className="flex flex-col mb-4 gap-1"><FormLabel>{label}</FormLabel><NativeSelectdata-testid="marimo-plugin-data-frames-union-select"@@ -371,6 +429,7 @@ export function renderZodSchema<T extends FieldValues, S>(/>);}+if (schema instanceof z.ZodLiteral) {return (<FormFielddiff --git a/frontend/src/components/forms/options.ts b/frontend/src/components/forms/options.tsindex 8327866452..05d19cf87e 100644--- a/frontend/src/components/forms/options.ts+++ b/frontend/src/components/forms/options.ts@@ -26,7 +26,8 @@ export interface FieldOptions {| "column_values"| "date"| "datetime"- | "time";+ | "time"+ | "tabs";/*** Only show options that match the regex*/diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsxindex 17a4392e45..99e4ac8a38 100644--- a/frontend/src/core/codemirror/language/panel.tsx+++ b/frontend/src/core/codemirror/language/panel.tsx@@ -287,6 +287,12 @@ const SQLEngineSelect: React.FC<SelectProps> = ({};const renderConnections = (connections: DataSourceConnection[]) => {+ // HACK: Ignore iceberg connections+ // Ideally source_type should be on the DataSourceConnection object+ connections = connections.filter(+ (connection) => connection.source !== "iceberg",+ );+return connections.map((connection) => (<SelectItem key={connection.name} value={connection.name}><div className="flex items-center gap-1">diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex 0d8c3b12b9..e27356643f 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -44,7 +44,8 @@ class DataTableColumn:# Local -> Python dataframes# DuckDB -> DuckDB tables using the global in-memory DuckDB instance# Connection -> SQL tables using a named data source connection (e.g. SQLAlchemy, or a custom DuckDB connection)-DataTableSource = Literal["local", "duckdb", "connection"]+# Catalog -> Data catalog (e.g. iceberg)+DataTableSource = Literal["local", "duckdb", "connection", "catalog"]DataTableType = Literal["table", "view"]diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 5a8ca4304f..457273fbd0 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -176,6 +176,7 @@ class DependencyManager:plotly = Dependency("plotly")bokeh = Dependency("bokeh")pyarrow = Dependency("pyarrow")+ pyiceberg = Dependency("pyiceberg")openai = Dependency("openai")matplotlib = Dependency("matplotlib")anywidget = Dependency("anywidget")diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 279e44046d..82df2bacd1 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2105,6 +2105,13 @@ class DatasetCallbacks:table_name=table_name,).broadcast()return+ elif source_type == "catalog":+ DataColumnPreview(+ error="Column preview for catalog data sources is not supported",+ column_name=column_name,+ table_name=table_name,+ ).broadcast()+ returnelse:assert_never(source_type)diff --git a/marimo/_sql/engines/pyiceberg.py b/marimo/_sql/engines/pyiceberg.pynew file mode 100644index 0000000000..a28f48cfd2--- /dev/null+++ b/marimo/_sql/engines/pyiceberg.py@@ -0,0 +1,212 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Literal, Optional, Union++from marimo import _loggers+from marimo._data.models import (+ Database,+ DataTable,+ DataTableColumn,+ 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 pyiceberg.catalog import Catalog++NO_SCHEMA_NAME = ""+++@register_engine+class PyIcebergEngine(SQLEngine):+ """PyIceberg engine."""++ def __init__(+ self, connection: Catalog, engine_name: Optional[VariableName] = None+ ) -> None:+ self._catalog: Catalog = connection+ self._engine_name = engine_name+ self.default_database = self.get_default_database()+ self.default_schema = self.get_default_schema()++ @property+ def source(self) -> str:+ return "iceberg"++ @property+ def dialect(self) -> str:+ return "iceberg"++ def execute(self, query: str) -> Any:+ raise NotImplementedError(+ "PyIceberg does not support direct SQL execution"+ )++ @staticmethod+ def is_compatible(var: Any) -> bool:+ if not DependencyManager.pyiceberg.imported():+ return False++ from pyiceberg.catalog import Catalog++ return isinstance(var, Catalog)++ @property+ def inference_config(self) -> InferenceConfig:+ return InferenceConfig(+ auto_discover_schemas=True,+ auto_discover_tables="auto",+ auto_discover_columns=False,+ )++ def get_default_database(self) -> Optional[str]:+ return None++ def get_default_schema(self) -> Optional[str]:+ return None # Iceberg doesn't have schemas in the traditional sense++ 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 engine."""+ from pyiceberg.catalog import Catalog++ del include_schemas+ databases: list[Database] = []+ try:+ namespaces = self._catalog.list_namespaces()+ for namespace in namespaces:+ tables = []+ if self._resolve_should_auto_discover(include_tables):+ tables = self.get_tables_in_schema(+ schema=NO_SCHEMA_NAME,+ database=Catalog.identifier_to_database(namespace),+ include_table_details=self._resolve_should_auto_discover(+ include_table_details+ ),+ )++ databases.append(+ Database(+ name=Catalog.identifier_to_database(namespace),+ dialect=self.dialect,+ schemas=[+ Schema(+ name=NO_SCHEMA_NAME,+ tables=tables,+ )+ ],+ engine=self._engine_name,+ )+ )+ except Exception:+ LOGGER.warning("Failed to get databases", exc_info=True)++ return databases++ def get_tables_in_schema(+ self, *, schema: str, database: str, include_table_details: bool+ ) -> list[DataTable]:+ """Return all tables in a schema."""+ del schema # Not used since Iceberg doesn't have schemas++ from pyiceberg.catalog import Catalog++ try:+ tables = self._catalog.list_tables(database)+ if not include_table_details:+ return [+ DataTable(+ source_type="catalog",+ source=self.dialect,+ name=Catalog.table_name_from(table),+ num_rows=None,+ num_columns=None,+ variable_name=None,+ engine=self._engine_name,+ type="table",+ columns=[],+ primary_keys=[],+ indexes=[],+ )+ for table in tables+ ]++ data_tables: list[DataTable] = []+ for table_name in tables:+ table: DataTable | None = self.get_table_details(+ table_name=Catalog.table_name_from(table_name),+ schema_name=NO_SCHEMA_NAME,+ database_name=Catalog.identifier_to_database(database),+ )+ if table is not None:+ data_tables.append(table)++ return data_tables+ except Exception:+ LOGGER.warning("Failed to get tables in schema", exc_info=True)+ return []++ def get_table_details(+ self, *, table_name: str, schema_name: str, database_name: str+ ) -> Optional[DataTable]:+ """Get a single table from the engine."""+ del schema_name # Not used since Iceberg doesn't have schemas+ try:+ table = self._catalog.load_table((database_name, table_name))+ schema = table.schema()++ cols: list[DataTableColumn] = []+ for field in schema.fields:+ cols.append(+ DataTableColumn(+ name=field.name,+ type=sql_type_to_data_type(str(field.field_type)),+ external_type=str(field.field_type),+ sample_values=[],+ )+ )++ return DataTable(+ source_type="catalog",+ source=self.dialect,+ name=table_name,+ num_rows=None,+ num_columns=len(cols),+ variable_name=None,+ engine=self._engine_name,+ columns=cols,+ primary_keys=[],+ indexes=[],+ )+ except Exception:+ LOGGER.warning(+ f"Failed to get table {table_name} in namespace {database_name}",+ exc_info=True,+ )+ return None++ def _resolve_should_auto_discover(+ self,+ value: Union[bool, Literal["auto"]],+ ) -> bool:+ if value == "auto":+ return self._is_cheap_discovery()+ return value++ def _is_cheap_discovery(self) -> bool:+ return True # Iceberg metadata is generally fast to accessdiff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.pyindex 79fbdb1a70..f30dac44bd 100644--- a/marimo/_sql/get_engines.py+++ b/marimo/_sql/get_engines.py@@ -19,6 +19,7 @@ from marimo._sql.engines.duckdb import (INTERNAL_DUCKDB_ENGINE,DuckDBEngine,)+from marimo._sql.engines.pyiceberg import PyIcebergEnginefrom marimo._sql.engines.sqlalchemy import SQLAlchemyEnginefrom marimo._sql.engines.types import SQLEnginefrom marimo._types.ids import VariableName@@ -36,6 +37,7 @@ def get_engines_from_variables(DuckDBEngine,ClickhouseEmbedded,ClickhouseServer,+ PyIcebergEngine,]for variable_name, value in variables:diff --git a/openapi/api.yaml b/openapi/api.yamlindex 5165b12c25..1fd9e89f4b 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -537,6 +537,7 @@ components:- local- duckdb- connection+ - catalogtype: stringtype:enum:@@ -606,6 +607,7 @@ components:- local- duckdb- connection+ - catalognullable: truetype: stringname:@@ -1850,6 +1852,7 @@ components:- local- duckdb- connection+ - catalogtype: stringtableName:type: string@@ -2499,7 +2502,7 @@ components:type: objectinfo:title: marimo API- version: 0.12.9+ version: 0.13.2openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 33fb9c07c8..405fb3341b 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2534,7 +2534,7 @@ export interface components {primary_keys?: string[] | null;source: string;/** @enum {string} */- source_type: "local" | "duckdb" | "connection";+ source_type: "local" | "duckdb" | "connection" | "catalog";/** @enum {string} */type: "table" | "view";variable_name?: string | null;@@ -2563,7 +2563,7 @@ export interface components {};Datasets: {/** @enum {string|null} */- clear_channel?: "local" | "duckdb" | "connection" | null;+ clear_channel?: "local" | "duckdb" | "connection" | "catalog" | null;/** @enum {string} */name: "datasets";tables: components["schemas"]["DataTable"][];@@ -3119,7 +3119,7 @@ export interface components {fullyQualifiedTableName?: string | null;source: string;/** @enum {string} */- sourceType: "local" | "duckdb" | "connection";+ sourceType: "local" | "duckdb" | "connection" | "catalog";tableName: string;};PreviewSQLTableListRequest: {diff --git a/pyproject.toml b/pyproject.tomlindex 1936d13607..78832401ec 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -195,6 +195,7 @@ dependencies = ["sqlglot>=23.4","sqlalchemy>=2.0.40","pandas-stubs>=1.5.3.230321",+ "pyiceberg>=0.9.0","types-Pillow~=10.2.0.20240520","types-Pygments~=2.18.0.20240506","types-psutil~=5.9.5.20240516",@@ -258,6 +259,7 @@ extra-dependencies = ["polars~=1.24.0","sqlglot>=23.4","sqlalchemy>=2.0.40",+ "pyiceberg>=0.9.0",# For testing clickhouse"chdb>=3; platform_system != 'Windows'", # there is no suitable wheel for windows"clickhouse-connect>=0.8.16",diff --git a/tests/_sql/test_pyiceberg.py b/tests/_sql/test_pyiceberg.pynew file mode 100644index 0000000000..6313dc5608--- /dev/null+++ b/tests/_sql/test_pyiceberg.py@@ -0,0 +1,293 @@+"""Tests for PyIceberg engine."""++from __future__ import annotations++from typing import TYPE_CHECKING+from unittest import mock++import pytest++from marimo._data.models import DataTable, DataTableColumn+from marimo._dependencies.dependencies import DependencyManager+from marimo._sql.engines.pyiceberg import PyIcebergEngine+from marimo._types.ids import VariableName++HAS_PYICEBERG = DependencyManager.pyiceberg.has()++if TYPE_CHECKING:+ from pyiceberg.catalog import Catalog+++def memory_catalog() -> Catalog:+ """Create a mock PyIceberg catalog for testing."""+ if not HAS_PYICEBERG:+ return mock.MagicMock()++ from pyiceberg.catalog.memory import InMemoryCatalog+ from pyiceberg.schema import Schema as IcebergSchema+ from pyiceberg.types import (+ BooleanType,+ IntegerType,+ NestedField,+ StringType,+ )++ # Create mock catalog+ catalog = InMemoryCatalog("test_catalog")++ # Create namespaces+ catalog.create_namespace("default")+ catalog.create_namespace("test_namespace")++ # Create actual schema object with real fields+ schema = IcebergSchema(+ fields=[+ NestedField(+ field_id=1, name="id", field_type=IntegerType(), required=True+ ),+ NestedField(+ field_id=2, name="name", field_type=StringType(), required=True+ ),+ NestedField(+ field_id=3,+ name="active",+ field_type=BooleanType(),+ required=False,+ ),+ ]+ )++ catalog.create_table(("default", "table1"), schema)+ catalog.create_table(("default", "table2"), schema)+ catalog.create_table(("test_namespace", "table3"), schema)++ assert len(catalog.list_tables("default")) == 2+ assert len(catalog.list_tables("test_namespace")) == 1++ return catalog+++def get_expected_table(+ table_name: str, include_table_details: bool = True+) -> DataTable:+ """Return expected table structure for tests."""+ return DataTable(+ source_type="catalog",+ source="iceberg",+ name=table_name,+ num_rows=None,+ num_columns=3 if include_table_details else None,+ variable_name=None,+ engine=VariableName("my_iceberg"),+ type="table",+ primary_keys=[] if not include_table_details else None,+ indexes=[] if not include_table_details else None,+ columns=[+ DataTableColumn(+ name="id",+ type="integer",+ external_type="int",+ sample_values=[],+ ),+ DataTableColumn(+ name="name",+ type="string",+ external_type="string",+ sample_values=[],+ ),+ DataTableColumn(+ name="active",+ type="boolean",+ external_type="boolean",+ sample_values=[],+ ),+ ]+ if include_table_details+ else [],+ )++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_engine_compatibility() -> None:+ """Test engine compatibility checks."""+ from pyiceberg.catalog import Catalog++ obj = object()+ mock_catalog = mock.MagicMock(spec=Catalog)++ assert PyIcebergEngine.is_compatible(mock_catalog)+ assert not PyIcebergEngine.is_compatible(obj)++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_engine_name_initialization(memory_catalog: Catalog) -> None:+ """Test engine name initialization."""+ engine = PyIcebergEngine(+ memory_catalog, engine_name=VariableName("my_iceberg")+ )+ assert engine._engine_name == VariableName("my_iceberg")++ # Test default name+ engine = PyIcebergEngine(memory_catalog)+ assert engine._engine_name is None++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_engine_source_and_dialect(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine source and dialect properties."""+ engine = PyIcebergEngine(memory_catalog)+ assert engine.source == "iceberg"+ assert engine.dialect == "iceberg"++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_engine_get_database_name(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine get_database_name."""+ engine = PyIcebergEngine(+ memory_catalog, engine_name=VariableName("my_iceberg")+ )+ assert engine.get_default_database() is None+ assert engine.get_default_schema() is None++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_execute(memory_catalog: Catalog) -> None:+ """Test PyIceberg execute raises NotImplementedError."""+ engine = PyIcebergEngine(+ memory_catalog, engine_name=VariableName("my_iceberg")+ )+ with pytest.raises(NotImplementedError):+ engine.execute("SELECT * FROM table")++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_get_table_details(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine get_table_details method."""+ engine = PyIcebergEngine(+ memory_catalog, engine_name=VariableName("my_iceberg")+ )+ table = engine.get_table_details(+ table_name="table1", schema_name="", database_name="default"+ )++ assert table is not None+ assert table.source == "iceberg"+ assert table.name == "table1"+ assert table.num_columns == 3+ assert len(table.columns) == 3+ assert table.columns[0].name == "id"+ assert table.columns[0].type == "integer"+ assert table.columns[1].name == "name"+ assert table.columns[1].type == "string"+ assert table.columns[2].name == "active"+ assert table.columns[2].type == "boolean"++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_get_tables_in_schema(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine get_tables_in_schema method."""+ engine = PyIcebergEngine(+ memory_catalog, engine_name=VariableName("my_iceberg")+ )++ # Test with include_table_details=True+ tables = engine.get_tables_in_schema(+ schema="unused", database="default", include_table_details=True+ )++ assert isinstance(tables, list)+ assert len(tables) == 2+ assert tables[0].name == "table1"+ assert tables[1].name == "table2"+ assert tables[0].num_columns == 3+ assert tables[1].num_columns == 3++ # Test with include_table_details=False+ tables = engine.get_tables_in_schema(+ schema="unused", database="default", include_table_details=False+ )++ assert isinstance(tables, list)+ assert len(tables) == 2+ assert tables[0].name == "table1"+ assert tables[1].name == "table2"+ assert tables[0].num_columns is None+ assert tables[1].num_columns is None+ assert tables[0].columns == []+ assert tables[1].columns == []++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_get_databases(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine get_databases method."""+ engine_name = VariableName("my_iceberg")+ engine = PyIcebergEngine(memory_catalog, engine_name=engine_name)++ # Test with all parameters True+ databases = engine.get_databases(+ include_schemas=True, include_tables=True, include_table_details=True+ )++ assert isinstance(databases, list)+ assert len(databases) == 2+ assert databases[0].name == "default"+ assert databases[0].dialect == "iceberg"+ assert len(databases[0].schemas) == 1+ assert databases[0].schemas[0].name == ""+ assert len(databases[0].schemas[0].tables) == 2++ assert databases[1].name == "test_namespace"+ assert len(databases[1].schemas) == 1+ assert databases[1].schemas[0].name == ""+ assert len(databases[1].schemas[0].tables) == 1++ # Test with include_tables=False+ databases = engine.get_databases(+ include_schemas=True, include_tables=False, include_table_details=True+ )++ assert isinstance(databases, list)+ assert len(databases) == 2+ assert databases[0].name == "default"+ assert len(databases[0].schemas) == 1+ assert databases[0].schemas[0].name == ""+ assert len(databases[0].schemas[0].tables) == 0++ assert databases[1].name == "test_namespace"+ assert len(databases[1].schemas) == 1+ assert databases[1].schemas[0].name == ""+ assert len(databases[1].schemas[0].tables) == 0++[email protected](not HAS_PYICEBERG, reason="PyIceberg not installed")+def test_pyiceberg_auto_discovery(memory_catalog: Catalog) -> None:+ """Test PyIcebergEngine auto discovery behavior."""+ engine_name = VariableName("my_iceberg")+ engine = PyIcebergEngine(memory_catalog, engine_name=engine_name)++ # Test with auto parameters (should behave like True for PyIceberg)+ databases = engine.get_databases(+ include_schemas="auto",+ include_tables="auto",+ include_table_details="auto",+ )++ assert isinstance(databases, list)+ assert len(databases) == 2+ assert databases[0].schemas[0].name == ""+ assert len(databases[0].schemas[0].tables) == 2++ # Test with _is_cheap_discovery mocked to return False+ with mock.patch.object(+ PyIcebergEngine, "_is_cheap_discovery", return_value=False+ ):+ databases = engine.get_databases(+ include_schemas="auto",+ include_tables="auto",+ include_table_details="auto",+ )++ assert isinstance(databases, list)+ assert len(databases) == 2+ assert len(databases[0].schemas[0].tables) == 0