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: database GUI to create connections (#3737)

Myles Scolnick10f96fda30e6
diff --git a/frontend/src/components/databases/icon.tsx b/frontend/src/components/databases/icon.tsx
index d83fecb5ee..e9ccf60bba 100644
--- a/frontend/src/components/databases/icon.tsx
+++ b/frontend/src/components/databases/icon.tsx
@@ -7,7 +7,7 @@ import MySQLIcon from "./icons/mysql.svg";
import SnowflakeIcon from "./icons/snowflake.svg";
import DatabricksIcon from "./icons/databricks.svg";
import ClickhouseIcon from "./icons/clickhouse.svg";
-
+import GoogleBigQueryIcon from "./icons/googlebigquery.svg";
import { cn } from "@/utils/cn";
/**
@@ -31,6 +31,7 @@ export const DatabaseLogo: FC<DatabaseLogoProps> = ({ name, className }) => {
snowflake: SnowflakeIcon,
databricks: DatabricksIcon,
clickhouse: ClickhouseIcon,
+ googlebigquery: GoogleBigQueryIcon,
};
const url = URLS[lowerName];
@@ -43,7 +44,7 @@ export const DatabaseLogo: FC<DatabaseLogoProps> = ({ name, className }) => {
<img
src={url}
alt={name}
- className={cn(className, "invert-[.5] dark:invert-[.7]")}
+ className={cn("invert-[.5] dark:invert-[.7]", className)}
/>
);
};
diff --git a/frontend/src/components/databases/icons/googlebigquery.svg b/frontend/src/components/databases/icons/googlebigquery.svg
new file mode 100644
index 0000000000..5aa562ba11
--- /dev/null
+++ b/frontend/src/components/databases/icons/googlebigquery.svg
@@ -0,0 +1 @@
+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google BigQuery</title><path d="M5.676 10.595h2.052v5.244a5.892 5.892 0 0 1-2.052-2.088v-3.156zm18.179 10.836a.504.504 0 0 1 0 .708l-1.716 1.716a.504.504 0 0 1-.708 0l-4.248-4.248a.206.206 0 0 1-.007-.007c-.02-.02-.028-.045-.043-.066a10.736 10.736 0 0 1-6.334 2.065C4.835 21.599 0 16.764 0 10.799S4.835 0 10.8 0s10.799 4.835 10.799 10.8c0 2.369-.772 4.553-2.066 6.333.025.017.052.028.074.05l4.248 4.248zm-5.028-10.632a8.015 8.015 0 1 0-8.028 8.028h.024a8.016 8.016 0 0 0 8.004-8.028zm-4.86 4.98a6.002 6.002 0 0 0 2.04-2.184v-1.764h-2.04v3.948zm-4.5.948c.442.057.887.08 1.332.072.4.025.8.025 1.2 0V7.692H9.468v9.035z"/></svg>
\ No newline at end of file
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index a05a71412a..10788d66bc 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -30,6 +30,7 @@ import {
XCircleIcon,
FilePlus2Icon,
FastForwardIcon,
+ DatabaseIcon,
} from "lucide-react";
import { commandPaletteAtom } from "../controls/command-palette";
import {
@@ -71,6 +72,7 @@ import { copyToClipboard } from "@/utils/copy";
import { newNotebookURL } from "@/utils/urls";
import { useRunAllCells } from "../cell/useRunCells";
import { settingDialogAtom } from "@/components/app-config/state";
+import { AddDatabaseDialogContent } from "../database/add-database-form";
const NOOP_HANDLER = (event?: Event) => {
event?.preventDefault();
@@ -376,6 +378,13 @@ export function useNotebookActions() {
undoDeleteCell();
},
},
+ {
+ icon: <DatabaseIcon size={14} strokeWidth={1.5} />,
+ label: "Add database connection",
+ handle: () => {
+ openModal(<AddDatabaseDialogContent onClose={closeModal} />);
+ },
+ },
{
divider: true,
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
index f1e899392f..773c8e4898 100644
--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -3,6 +3,7 @@ import React from "react";
import {
ChevronRightIcon,
DatabaseIcon,
+ PlusIcon,
PlusSquareIcon,
XIcon,
} from "lucide-react";
@@ -48,6 +49,7 @@ import { DatabaseLogo } from "@/components/databases/icon";
import { EngineVariable } from "@/components/databases/engine-variable";
import type { VariableName } from "@/core/variables/types";
import { dbDisplayName } from "@/components/databases/display";
+import { AddDatabaseDialog } from "../../database/add-database-form";
const sortedTablesAtom = atom((get) => {
const tables = get(datasetTablesAtom);
@@ -90,6 +92,14 @@ export const DataSourcesPanel: React.FC = () => {
<PanelEmptyState
title="No tables found"
description="Any datasets/dataframes in the global scope will be shown here."
+ action={
+ <AddDatabaseDialog>
+ <Button variant="outline" size="sm">
+ Add database
+ <PlusIcon className="h-4 w-4 ml-2" />
+ </Button>
+ </AddDatabaseDialog>
+ }
icon={<DatabaseIcon />}
/>
);
@@ -158,6 +168,12 @@ export const DataSourcesPanel: React.FC = () => {
<XIcon className="h-4 w-4" />
</button>
)}
+
+ <AddDatabaseDialog>
+ <button className="float-right border-b px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground">
+ <PlusIcon className="h-4 w-4" />
+ </button>
+ </AddDatabaseDialog>
</div>
<TableList
diff --git a/frontend/src/components/editor/chrome/panels/empty-state.tsx b/frontend/src/components/editor/chrome/panels/empty-state.tsx
index f6376425cb..7e1d7ccfb7 100644
--- a/frontend/src/components/editor/chrome/panels/empty-state.tsx
+++ b/frontend/src/components/editor/chrome/panels/empty-state.tsx
@@ -4,11 +4,16 @@ import React from "react";
interface Props {
title: string;
description?: React.ReactNode;
- color?: string;
icon?: React.ReactElement;
+ action?: React.ReactNode;
}
-export const PanelEmptyState = ({ title, description, color, icon }: Props) => {
+export const PanelEmptyState = ({
+ title,
+ description,
+ icon,
+ action,
+}: Props) => {
return (
<div className="mx-6 my-6 flex flex-col gap-2">
<div className="flex flex-row gap-2 items-center">
@@ -17,6 +22,7 @@ export const PanelEmptyState = ({ title, description, color, icon }: Props) => {
<span className="mt-1 text-accent-foreground">{title}</span>
</div>
<span className="text-muted-foreground text-sm">{description}</span>
+ {action && <div className="mt-2">{action}</div>}
</div>
);
};
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.snap
new file mode 100644
index 0000000000..d50b548633
--- /dev/null
+++ b/frontend/src/components/editor/database/__tests__/__snapshots__/as-code.test.ts.snap
@@ -0,0 +1,303 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`generateDatabaseCode > basic connections > bigquery 1`] = `
+"from sqlmodel import create_engine
+import os
+import json
+credentials = json.loads("""{"type": "service_account", "project_id": "test"}""")
+engine = create_engine(f"bigquery://my-project/my_dataset", credentials_info=credentials)"
+`;
+
+exports[`generateDatabaseCode > basic connections > duckdb 1`] = `
+"from sqlmodel import create_engine
+import os
+engine = create_engine("duckdb:data.duckdb", read_only=True)"
+`;
+
+exports[`generateDatabaseCode > basic connections > mysql with SQLAlchemy 1`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "pass")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:3306/test"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > basic connections > mysql with SQLModel 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "pass")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:3306/test"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > basic connections > postgres with SQLAlchemy 1`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > basic connections > postgres with SQLModel 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > basic connections > snowflake 1`] = `
+"from sqlmodel import create_engine
+import os
+from snowflake.sqlalchemy import URL
+import sqlalchemy as sa
+password = os.environ.get("SNOWFLAKE_PASSWORD", "pass")
+engine = sa.create_engine(
+ URL(
+ account=account,
+ user=user,
+ password=os.environ.get("SNOWFLAKE_PASSWORD", "pass"),
+ database=db,
+ warehouse=warehouse,
+ schema=schema,
+ role=role
+ )
+)"
+`;
+
+exports[`generateDatabaseCode > basic connections > sqlite 1`] = `
+"from sqlmodel import create_engine
+import os
+DATABASE_URL = "sqlite:////path/to/db.sqlite"
+engine = create_engine(DATABASE_URL)"
+`;
+
+exports[`generateDatabaseCode > edge cases > bigquery with long credentials 1`] = `
+"from sqlmodel import create_engine
+import os
+import json
+credentials = json.loads("""xxxxxxxxxx""")
+engine = create_engine(f"bigquery://my-project/my_dataset", credentials_info=credentials)"
+`;
+
+exports[`generateDatabaseCode > edge cases > duckdb with relative path 1`] = `
+"from sqlmodel import create_engine
+import os
+engine = create_engine("duckdb:./relative/path/db.duckdb")"
+`;
+
+exports[`generateDatabaseCode > edge cases > mysql with extremely long database name 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "pass")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:3306/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > edge cases > mysql with max port 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "pass")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:65535/test"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with IPv6 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@2001:0db8:85a3:0000:0000:8a2e:0370:7334:5432/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with URL-encoded characters 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass%20word")
+DATABASE_URL = f"postgresql://user%20name:{password}@localhost:5432/test%20db"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with domain socket 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@/var/run/postgresql:undefined/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with non-standard port 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@localhost:54321/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with special chars SQLAlchemy 1`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass@#$%^&*")
+DATABASE_URL = f"postgresql://user-name.special:{password}@localhost:5432/test-db.special"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with special chars SQLModel 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass@#$%^&*")
+DATABASE_URL = f"postgresql://user-name.special:{password}@localhost:5432/test-db.special"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > postgres with unicode 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "密码")
+DATABASE_URL = f"postgresql://用户:{password}@localhost:5432/测试数据库"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > edge cases > snowflake with all optional fields filled 1`] = `
+"from sqlmodel import create_engine
+import os
+from snowflake.sqlalchemy import URL
+import sqlalchemy as sa
+password = os.environ.get("SNOWFLAKE_PASSWORD", "pass")
+engine = sa.create_engine(
+ URL(
+ account=org-account,
+ user=user,
+ password=os.environ.get("SNOWFLAKE_PASSWORD", "pass"),
+ database=db,
+ warehouse=compute_wh,
+ schema=public,
+ role=accountadmin
+ )
+)"
+`;
+
+exports[`generateDatabaseCode > edge cases > snowflake with minimal config SQLModel 1`] = `
+"from sqlmodel import create_engine
+import os
+from snowflake.sqlalchemy import URL
+import sqlalchemy as sa
+password = os.environ.get("SNOWFLAKE_PASSWORD", "pass")
+engine = sa.create_engine(
+ URL(
+ account=account,
+ user=user,
+ password=os.environ.get("SNOWFLAKE_PASSWORD", "pass"),
+ database=db
+ )
+)"
+`;
+
+exports[`generateDatabaseCode > edge cases > sqlite with empty path 1`] = `
+"from sqlmodel import create_engine
+import os
+DATABASE_URL = "sqlite:///"
+engine = create_engine(DATABASE_URL)"
+`;
+
+exports[`generateDatabaseCode > security cases > bigquery with malformed JSON 1`] = `
+"from sqlmodel import create_engine
+import os
+import json
+credentials = json.loads("""{"type": "service_account", "project_id": "test"""")
+engine = create_engine(f"bigquery://my-project/my_dataset", credentials_info=credentials)"
+`;
+
+exports[`generateDatabaseCode > security cases > bigquery with malformed JSON 2`] = `
+"from sqlalchemy import create_engine
+import os
+import json
+credentials = json.loads("""{"type": "service_account", "project_id": "test"""")
+engine = create_engine(f"bigquery://my-project/my_dataset", credentials_info=credentials)"
+`;
+
+exports[`generateDatabaseCode > security cases > mysql with very long password 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "xxxxxxxxxx")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:3306/test"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > security cases > mysql with very long password 2`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("MYSQL_PASSWORD", "xxxxxxxxxx")
+DATABASE_URL = f"mysql+pymysql://user:{password}@localhost:3306/test"
+engine = create_engine(DATABASE_URL, connect_args={'ssl': {'ssl-mode': 'preferred'}})"
+`;
+
+exports[`generateDatabaseCode > security cases > postgres with SQL injection attempt in database name 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/db'; DROP TABLE users;--"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > security cases > postgres with SQL injection attempt in database name 2`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "pass")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/db'; DROP TABLE users;--"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > security cases > postgres with empty password 1`] = `
+"from sqlmodel import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > security cases > postgres with empty password 2`] = `
+"from sqlalchemy import create_engine
+import os
+password = os.environ.get("POSTGRES_PASSWORD", "")
+DATABASE_URL = f"postgresql://user:{password}@localhost:5432/test"
+engine = create_engine(DATABASE_URL, connect_args={'sslmode': 'require'})"
+`;
+
+exports[`generateDatabaseCode > security cases > snowflake with sensitive info in account 1`] = `
+"from sqlmodel import create_engine
+import os
+from snowflake.sqlalchemy import URL
+import sqlalchemy as sa
+password = os.environ.get("SNOWFLAKE_PASSWORD", "pass")
+engine = sa.create_engine(
+ URL(
+ account=account-with-password123,
+ user=user,
+ password=os.environ.get("SNOWFLAKE_PASSWORD", "pass"),
+ database=db,
+ warehouse=warehouse,
+ schema=schema,
+ role=role
+ )
+)"
+`;
+
+exports[`generateDatabaseCode > security cases > snowflake with sensitive info in account 2`] = `
+"from sqlalchemy import create_engine
+import os
+from snowflake.sqlalchemy import URL
+import sqlalchemy as sa
+password = os.environ.get("SNOWFLAKE_PASSWORD", "pass")
+engine = sa.create_engine(
+ URL(
+ account=account-with-password123,
+ user=user,
+ password=os.environ.get("SNOWFLAKE_PASSWORD", "pass"),
+ database=db,
+ warehouse=warehouse,
+ schema=schema,
+ role=role
+ )
+)"
+`;
diff --git a/frontend/src/components/editor/database/__tests__/as-code.test.ts b/frontend/src/components/editor/database/__tests__/as-code.test.ts
new file mode 100644
index 0000000000..cbd2baf1de
--- /dev/null
+++ b/frontend/src/components/editor/database/__tests__/as-code.test.ts
@@ -0,0 +1,305 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { type ConnectionLibrary, generateDatabaseCode } from "../as-code";
+import type { DatabaseConnection } from "../schemas";
+
+describe("generateDatabaseCode", () => {
+ // Test fixtures
+ const basePostgres: DatabaseConnection = {
+ type: "postgres",
+ host: "localhost",
+ port: 5432,
+ database: "test",
+ username: "user",
+ password: "pass",
+ ssl: true,
+ };
+
+ const baseMysql: DatabaseConnection = {
+ type: "mysql",
+ host: "localhost",
+ port: 3306,
+ database: "test",
+ username: "user",
+ password: "pass",
+ ssl: true,
+ };
+
+ const sqliteConnection: DatabaseConnection = {
+ type: "sqlite",
+ database: "/path/to/db.sqlite",
+ };
+
+ const duckdbConnection: DatabaseConnection = {
+ type: "duckdb",
+ database: "data.duckdb",
+ read_only: true,
+ };
+
+ const snowflakeConnection: DatabaseConnection = {
+ type: "snowflake",
+ account: "account",
+ username: "user",
+ password: "pass",
+ warehouse: "warehouse",
+ database: "db",
+ schema: "schema",
+ role: "role",
+ };
+
+ const bigqueryConnection: DatabaseConnection = {
+ type: "bigquery",
+ project: "my-project",
+ dataset: "my_dataset",
+ credentials_json: '{"type": "service_account", "project_id": "test"}',
+ };
+
+ describe("basic connections", () => {
+ it.each([
+ ["postgres with SQLModel", basePostgres, "sqlmodel"],
+ ["postgres with SQLAlchemy", basePostgres, "sqlalchemy"],
+ ["mysql with SQLModel", baseMysql, "sqlmodel"],
+ ["mysql with SQLAlchemy", baseMysql, "sqlalchemy"],
+ ["sqlite", sqliteConnection, "sqlmodel"],
+ ["duckdb", duckdbConnection, "sqlmodel"],
+ ["snowflake", snowflakeConnection, "sqlmodel"],
+ ["bigquery", bigqueryConnection, "sqlmodel"],
+ ])("%s", (name, connection, orm) => {
+ expect(
+ generateDatabaseCode(connection, orm as ConnectionLibrary),
+ ).toMatchSnapshot();
+ });
+ });
+
+ describe("edge cases", () => {
+ const testCases: Array<[string, DatabaseConnection, string]> = [
+ [
+ "postgres with special chars SQLModel",
+ {
+ ...basePostgres,
+ password: "pass@#$%^&*",
+ username: "user-name.special",
+ database: "test-db.special",
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with special chars SQLAlchemy",
+ {
+ ...basePostgres,
+ password: "pass@#$%^&*",
+ username: "user-name.special",
+ database: "test-db.special",
+ },
+ "sqlalchemy",
+ ],
+ [
+ "snowflake with minimal config SQLModel",
+ {
+ type: "snowflake",
+ account: "account",
+ username: "user",
+ password: "pass",
+ database: "db",
+ warehouse: "",
+ schema: "",
+ role: "",
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with unicode",
+ {
+ ...basePostgres,
+ database: "测试数据库",
+ username: "用户",
+ password: "密码",
+ },
+ "sqlmodel",
+ ],
+ [
+ "bigquery with long credentials",
+ {
+ ...bigqueryConnection,
+ credentials_json: "x".repeat(10),
+ },
+ "sqlmodel",
+ ],
+ [
+ "sqlite with empty path",
+ {
+ type: "sqlite",
+ // sqlite allows empty path
+ database: "",
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with IPv6",
+ {
+ ...basePostgres,
+ host: "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with non-standard port",
+ {
+ ...basePostgres,
+ port: 54_321,
+ },
+ "sqlmodel",
+ ],
+ [
+ "mysql with max port",
+ {
+ ...baseMysql,
+ port: 65_535,
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with URL-encoded characters",
+ {
+ ...basePostgres,
+ database: "test%20db",
+ username: "user%20name",
+ password: "pass%20word",
+ },
+ "sqlmodel",
+ ],
+ [
+ "mysql with extremely long database name",
+ {
+ ...baseMysql,
+ database: "x".repeat(64),
+ },
+ "sqlmodel",
+ ],
+ [
+ "snowflake with all optional fields filled",
+ {
+ type: "snowflake",
+ account: "org-account",
+ username: "user",
+ password: "pass",
+ database: "db",
+ warehouse: "compute_wh",
+ schema: "public",
+ role: "accountadmin",
+ },
+ "sqlmodel",
+ ],
+ [
+ "duckdb with relative path",
+ {
+ type: "duckdb",
+ database: "./relative/path/db.duckdb",
+ read_only: false,
+ },
+ "sqlmodel",
+ ],
+ [
+ "postgres with domain socket",
+ {
+ ...basePostgres,
+ host: "/var/run/postgresql",
+ // @ts-expect-error - Testing invalid input
+ port: undefined,
+ },
+ "sqlmodel",
+ ],
+ ];
+
+ it.each(testCases)("%s", (name, connection, orm) => {
+ expect(
+ generateDatabaseCode(connection, orm as ConnectionLibrary),
+ ).toMatchSnapshot();
+ });
+ });
+
+ describe("security cases", () => {
+ it.each([
+ [
+ "postgres with empty password",
+ {
+ ...basePostgres,
+ password: "",
+ },
+ ],
+ [
+ "mysql with very long password",
+ {
+ ...baseMysql,
+ password: "x".repeat(10),
+ },
+ ],
+ [
+ "postgres with SQL injection attempt in database name",
+ {
+ ...basePostgres,
+ database: "db'; DROP TABLE users;--",
+ },
+ ],
+ [
+ "snowflake with sensitive info in account",
+ {
+ ...snowflakeConnection,
+ account: "account-with-password123",
+ },
+ ],
+ [
+ "bigquery with malformed JSON",
+ {
+ ...bigqueryConnection,
+ credentials_json: '{"type": "service_account", "project_id": "test"',
+ },
+ ],
+ ])("%s", (name, connection) => {
+ expect(generateDatabaseCode(connection, "sqlmodel")).toMatchSnapshot();
+ expect(generateDatabaseCode(connection, "sqlalchemy")).toMatchSnapshot();
+ });
+ });
+
+ describe("invalid cases", () => {
+ it.each([
+ [
+ "throws for unsupported ORMs",
+ () =>
+ // @ts-expect-error - Testing invalid input
+ generateDatabaseCode(basePostgres, "polars"),
+ ],
+ [
+ "throws for invalid port",
+ () => generateDatabaseCode({ ...basePostgres, port: -1 }, "sqlmodel"),
+ ],
+ [
+ "throws for invalid host",
+ () => generateDatabaseCode({ ...basePostgres, host: "" }, "sqlmodel"),
+ ],
+ [
+ "throws for port out of range",
+ () =>
+ generateDatabaseCode({ ...basePostgres, port: 65_536 }, "sqlmodel"),
+ ],
+ [
+ "throws for invalid snowflake account",
+ () =>
+ generateDatabaseCode(
+ { ...snowflakeConnection, account: "" },
+ "sqlmodel",
+ ),
+ ],
+ [
+ "throws for invalid bigquery project",
+ () =>
+ generateDatabaseCode(
+ { ...bigqueryConnection, project: "" },
+ "sqlmodel",
+ ),
+ ],
+ ])("%s", (name, fn) => {
+ expect(fn).toThrow();
+ });
+ });
+});
diff --git a/frontend/src/components/editor/database/add-database-form.tsx b/frontend/src/components/editor/database/add-database-form.tsx
new file mode 100644
index 0000000000..a95727206e
--- /dev/null
+++ b/frontend/src/components/editor/database/add-database-form.tsx
@@ -0,0 +1,255 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { z } from "zod";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@/components/ui/button";
+import { ZodForm } from "@/components/forms/form";
+import {
+ PostgresConnectionSchema,
+ MySQLConnectionSchema,
+ SQLiteConnectionSchema,
+ DuckDBConnectionSchema,
+ SnowflakeConnectionSchema,
+ BigQueryConnectionSchema,
+ type DatabaseConnection,
+} from "./schemas";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DatabaseLogo } from "@/components/databases/icon";
+import { useCellActions } from "@/core/cells/cells";
+import { useLastFocusedCellId } from "@/core/cells/focus";
+import {
+ ConnectionDisplayNames,
+ type ConnectionLibrary,
+ generateDatabaseCode,
+} from "./as-code";
+import { FormErrorsBanner } from "@/components/ui/form";
+import { getDefaults } from "@/components/forms/form-utils";
+import { atomWithStorage } from "jotai/utils";
+import { useAtom, useAtomValue } from "jotai";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+
+const KEY = "marimo:preferred-connection";
+
+const preferredConnectionAtom = atomWithStorage<ConnectionLibrary>(
+ KEY,
+ // default to sqlalchemy because it has fewer dependencies
+ "sqlalchemy",
+);
+
+interface Props {
+ onSubmit: (data: DatabaseConnection) => void;
+}
+
+const SCHEMAS = [
+ {
+ name: "PostgreSQL",
+ schema: PostgresConnectionSchema,
+ color: "#336791",
+ logo: "postgres",
+ },
+ {
+ name: "MySQL",
+ schema: MySQLConnectionSchema,
+ color: "#00758F",
+ logo: "mysql",
+ },
+ {
+ name: "SQLite",
+ schema: SQLiteConnectionSchema,
+ color: "#003B57",
+ logo: "sqlite",
+ },
+ {
+ name: "DuckDB",
+ schema: DuckDBConnectionSchema,
+ color: "#FFD700",
+ logo: "duckdb",
+ },
+ {
+ name: "Snowflake",
+ schema: SnowflakeConnectionSchema,
+ color: "#29B5E8",
+ logo: "snowflake",
+ },
+ {
+ name: "BigQuery",
+ schema: BigQueryConnectionSchema,
+ color: "#4285F4",
+ logo: "googlebigquery",
+ },
+];
+
+const DatabaseSchemaSelector: React.FC<{
+ onSelect: (schema: z.ZodType) => void;
+}> = ({ onSelect }) => {
+ 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>
+ );
+};
+
+const DatabaseForm: React.FC<{
+ schema: z.ZodType;
+ onSubmit: (data: DatabaseConnection) => void;
+ onBack: () => void;
+}> = ({ schema, onSubmit, onBack }) => {
+ const form = useForm<DatabaseConnection>({
+ defaultValues: getDefaults(schema),
+ resolver: zodResolver(schema),
+ reValidateMode: "onChange",
+ });
+ const [preferredConnection, setPreferredConnection] = useAtom(
+ preferredConnectionAtom,
+ );
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <ZodForm schema={schema} form={form}>
+ <FormErrorsBanner />
+ </ZodForm>
+ <div className="flex gap-2 justify-between">
+ <div className="flex gap-2">
+ <Button type="button" variant="outline" onClick={onBack}>
+ Back
+ </Button>
+ <Button type="submit" disabled={!form.formState.isValid}>
+ Add
+ </Button>
+ </div>
+ <div>
+ <Select
+ value={preferredConnection}
+ onValueChange={(value) =>
+ setPreferredConnection(value as ConnectionLibrary)
+ }
+ >
+ <div className="flex flex-col gap-1 items-end">
+ <SelectTrigger>
+ <SelectValue placeholder="Select a library" />
+ </SelectTrigger>
+ <span className="text-xs text-muted-foreground">
+ Preferred connection library
+ </span>
+ </div>
+ <SelectContent>
+ <SelectGroup>
+ {Object.entries(ConnectionDisplayNames).map(([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ </form>
+ );
+};
+
+const AddDatabaseForm: React.FC<Props> = ({ onSubmit }) => {
+ const [selectedSchema, setSelectedSchema] = useState<z.ZodType | null>(null);
+
+ if (!selectedSchema) {
+ return <DatabaseSchemaSelector onSelect={setSelectedSchema} />;
+ }
+
+ return (
+ <DatabaseForm
+ schema={selectedSchema}
+ onSubmit={onSubmit}
+ onBack={() => setSelectedSchema(null)}
+ />
+ );
+};
+
+export const AddDatabaseDialog: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild={true}>{children}</DialogTrigger>
+ <AddDatabaseDialogContent onClose={() => setOpen(false)} />
+ </Dialog>
+ );
+};
+
+export const AddDatabaseDialogContent: React.FC<{
+ onClose: () => void;
+}> = ({ onClose }) => {
+ const { createNewCell } = useCellActions();
+ const lastFocusedCellId = useLastFocusedCellId();
+ const preferredConnection = useAtomValue(preferredConnectionAtom);
+
+ const handleInsertCode = (code: string) => {
+ createNewCell({
+ code,
+ before: false,
+ cellId: lastFocusedCellId ?? "__end__",
+ skipIfCodeExists: true,
+ autoFocus: true,
+ });
+ };
+
+ const onSubmit = (values: DatabaseConnection) => {
+ handleInsertCode(generateDatabaseCode(values, preferredConnection));
+ onClose();
+ };
+
+ return (
+ <DialogContent>
+ <DialogHeader className="mb-4">
+ <DialogTitle>Add Database 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{" "}
+ <a
+ href="http://docs.marimo.io/guides/working_with_data/sql/#connecting-to-a-custom-database"
+ target="_blank"
+ rel="noreferrer"
+ className="text-link hover:underline"
+ >
+ docs.
+ </a>
+ </DialogDescription>
+ </DialogHeader>
+ <AddDatabaseForm
+ onSubmit={(values) => {
+ onSubmit(values);
+ }}
+ />
+ </DialogContent>
+ );
+};
diff --git a/frontend/src/components/editor/database/as-code.ts b/frontend/src/components/editor/database/as-code.ts
new file mode 100644
index 0000000000..f131ea913d
--- /dev/null
+++ b/frontend/src/components/editor/database/as-code.ts
@@ -0,0 +1,101 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { assertNever } from "@/utils/assertNever";
+import { DatabaseConnectionSchema, type DatabaseConnection } from "./schemas";
+
+export type ConnectionLibrary = "sqlmodel" | "sqlalchemy";
+export const ConnectionDisplayNames: Record<ConnectionLibrary, string> = {
+ sqlmodel: "SQLModel",
+ sqlalchemy: "SQLAlchemy",
+};
+
+export function generateDatabaseCode(
+ connection: DatabaseConnection,
+ orm: ConnectionLibrary,
+): string {
+ if (!(orm in ConnectionDisplayNames)) {
+ throw new Error(`Unsupported library: ${orm}`);
+ }
+
+ // Parse the connection to ensure it's valid
+ DatabaseConnectionSchema.parse(connection);
+
+ const imports =
+ orm === "sqlmodel"
+ ? ["from sqlmodel import create_engine", "import os"]
+ : ["from sqlalchemy import create_engine", "import os"];
+
+ let code = "";
+ switch (connection.type) {
+ case "postgres":
+ code = `
+password = os.environ.get("POSTGRES_PASSWORD", "${connection.password}")
+DATABASE_URL = f"postgresql://${connection.username}:{password}@${connection.host}:${connection.port}/${connection.database}"
+engine = create_engine(DATABASE_URL${connection.ssl ? ", connect_args={'sslmode': 'require'}" : ""})
+`;
+ break;
+
+ case "mysql":
+ code = `
+password = os.environ.get("MYSQL_PASSWORD", "${connection.password}")
+DATABASE_URL = f"mysql+pymysql://${connection.username}:{password}@${connection.host}:${connection.port}/${connection.database}"
+engine = create_engine(DATABASE_URL${connection.ssl ? ", connect_args={'ssl': {'ssl-mode': 'preferred'}}" : ""})
+`;
+ break;
+
+ case "sqlite":
+ code = `
+DATABASE_URL = "sqlite:///${connection.database}"
+engine = create_engine(DATABASE_URL)
+`;
+ break;
+
+ case "snowflake": {
+ imports.push("from snowflake.sqlalchemy import URL");
+ imports.push("import sqlalchemy as sa");
+
+ const params = {
+ account: connection.account,
+ user: connection.username,
+ password: `os.environ.get("SNOWFLAKE_PASSWORD", "${connection.password}")`,
+ database: connection.database,
+ warehouse: connection.warehouse,
+ schema: connection.schema,
+ role: connection.role,
+ };
+
+ const urlParams = Object.entries(params)
+ .filter(([, v]) => v)
+ .map(([k, v]) => ` ${k}=${v}`)
+ .join(",\n");
+
+ code = `
+password = os.environ.get("SNOWFLAKE_PASSWORD", "${connection.password}")
+engine = sa.create_engine(
+ URL(
+${urlParams}
+ )
+)
+`;
+ break;
+ }
+
+ case "bigquery":
+ imports.push("import json");
+ code = `
+credentials = json.loads("""${connection.credentials_json}""")
+engine = create_engine(f"bigquery://${connection.project}/${connection.dataset}", credentials_info=credentials)
+`;
+ break;
+
+ case "duckdb":
+ code = `
+engine = create_engine("duckdb:${connection.database || ":memory:"}"${connection.read_only ? ", read_only=True" : ""})
+`;
+ break;
+
+ default:
+ assertNever(connection);
+ }
+
+ return `${imports.join("\n")}\n${code.trim()}`;
+}
diff --git a/frontend/src/components/editor/database/schemas.ts b/frontend/src/components/editor/database/schemas.ts
new file mode 100644
index 0000000000..f488ad0219
--- /dev/null
+++ b/frontend/src/components/editor/database/schemas.ts
@@ -0,0 +1,160 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { z } from "zod";
+import { FieldOptions } from "@/components/forms/options";
+
+function passwordField() {
+ return z
+ .string()
+ .optional()
+ .describe(
+ FieldOptions.of({
+ label: "Password",
+ inputType: "password",
+ placeholder: "password",
+ }),
+ );
+}
+
+function hostField() {
+ return z
+ .string()
+ .nonempty()
+ .describe(FieldOptions.of({ label: "Host", placeholder: "localhost" }));
+}
+
+function databaseField() {
+ return z
+ .string()
+ .describe(FieldOptions.of({ label: "Database", placeholder: "db name" }));
+}
+
+function usernameField() {
+ return z
+ .string()
+ .nonempty()
+ .describe(FieldOptions.of({ label: "Username", placeholder: "username" }));
+}
+
+function portField(defaultPort: number) {
+ return z.coerce
+ .string()
+ .default(defaultPort.toString())
+ .describe(
+ FieldOptions.of({
+ label: "Port",
+ inputType: "number",
+ placeholder: defaultPort.toString(),
+ }),
+ )
+ .transform(Number)
+ .refine((n) => n >= 0 && n <= 65_535, {
+ message: "Port must be between 0 and 65535",
+ });
+}
+
+export const PostgresConnectionSchema = z
+ .object({
+ type: z.literal("postgres"),
+ host: hostField(),
+ port: portField(5432),
+ database: databaseField(),
+ username: usernameField(),
+ password: passwordField(),
+ ssl: z
+ .boolean()
+ .default(false)
+ .describe(FieldOptions.of({ label: "Use SSL" })),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const MySQLConnectionSchema = z
+ .object({
+ type: z.literal("mysql"),
+ host: hostField(),
+ port: portField(3306),
+ database: databaseField(),
+ username: usernameField(),
+ password: passwordField(),
+ ssl: z
+ .boolean()
+ .default(false)
+ .describe(FieldOptions.of({ label: "Use SSL" })),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const SQLiteConnectionSchema = z
+ .object({
+ type: z.literal("sqlite"),
+ database: databaseField().describe(
+ FieldOptions.of({ label: "Database Path" }),
+ ),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const DuckDBConnectionSchema = z
+ .object({
+ type: z.literal("duckdb"),
+ database: databaseField().describe(
+ FieldOptions.of({ label: "Database Path" }),
+ ),
+ read_only: z
+ .boolean()
+ .default(false)
+ .describe(FieldOptions.of({ label: "Read Only" })),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const SnowflakeConnectionSchema = z
+ .object({
+ type: z.literal("snowflake"),
+ account: z
+ .string()
+ .nonempty()
+ .describe(FieldOptions.of({ label: "Account" })),
+ warehouse: z
+ .string()
+ .optional()
+ .describe(FieldOptions.of({ label: "Warehouse" })),
+ database: databaseField(),
+ schema: z
+ .string()
+ .optional()
+ .describe(FieldOptions.of({ label: "Schema" })),
+ username: usernameField(),
+ password: passwordField(),
+ role: z
+ .string()
+ .optional()
+ .describe(FieldOptions.of({ label: "Role" })),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const BigQueryConnectionSchema = z
+ .object({
+ type: z.literal("bigquery"),
+ project: z
+ .string()
+ .nonempty()
+ .describe(FieldOptions.of({ label: "Project ID" })),
+ dataset: z
+ .string()
+ .nonempty()
+ .describe(FieldOptions.of({ label: "Dataset" })),
+ credentials_json: z
+ .string()
+ .describe(
+ FieldOptions.of({ label: "Credentials JSON", inputType: "textarea" }),
+ ),
+ })
+ .describe(FieldOptions.of({ direction: "two-columns" }));
+
+export const DatabaseConnectionSchema = z.discriminatedUnion("type", [
+ PostgresConnectionSchema,
+ MySQLConnectionSchema,
+ SQLiteConnectionSchema,
+ DuckDBConnectionSchema,
+ SnowflakeConnectionSchema,
+ BigQueryConnectionSchema,
+]);
+
+export type DatabaseConnection = z.infer<typeof DatabaseConnectionSchema>;
diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.ts b/frontend/src/components/forms/__tests__/form-utils.test.ts
similarity index 97%
rename from frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.ts
rename to frontend/src/components/forms/__tests__/form-utils.test.ts
index a93569b698..ff37e8ef78 100644
--- a/frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.ts
+++ b/frontend/src/components/forms/__tests__/form-utils.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { getDefaults } from "@/plugins/impl/data-frames/forms/form-utils";
+import { getDefaults } from "@/components/forms/form-utils";
import { z } from "zod";
describe("getDefaults", () => {
diff --git a/frontend/src/plugins/impl/data-frames/forms/form-utils.ts b/frontend/src/components/forms/form-utils.ts
similarity index 100%
rename from frontend/src/plugins/impl/data-frames/forms/form-utils.ts
rename to frontend/src/components/forms/form-utils.ts
diff --git a/frontend/src/plugins/impl/data-frames/forms/form.tsx b/frontend/src/components/forms/form.tsx
similarity index 56%
rename from frontend/src/plugins/impl/data-frames/forms/form.tsx
rename to frontend/src/components/forms/form.tsx
index 56da3c2deb..1d09c3954a 100644
--- a/frontend/src/plugins/impl/data-frames/forms/form.tsx
+++ b/frontend/src/components/forms/form.tsx
@@ -1,17 +1,13 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { z } from "zod";
-import {
- DebouncedInput,
- DebouncedNumberInput,
-} from "../../../../components/ui/input";
-import { Checkbox } from "../../../../components/ui/checkbox";
+import { DebouncedInput, DebouncedNumberInput } from "../ui/input";
+import { Checkbox } from "../ui/checkbox";
import {
type FieldValues,
FormProvider,
type Path,
type UseFormReturn,
- useController,
useFieldArray,
} from "react-hook-form";
import {
@@ -20,26 +16,16 @@ import {
FormLabel,
FormControl,
FormMessage,
- FormMessageTooltip,
FormDescription,
-} from "../../../../components/ui/form";
-import { Objects } from "../../../../utils/objects";
-import { Button } from "../../../../components/ui/button";
+} from "../ui/form";
+import { Objects } from "../../utils/objects";
+import { Button } from "../ui/button";
import { getDefaults, getUnionLiteral } from "./form-utils";
import { PlusIcon, RefreshCcw, Trash2Icon } from "lucide-react";
-import {
- FieldOptions,
- randomNumber,
-} from "@/plugins/impl/data-frames/forms/options";
+import { FieldOptions, randomNumber } from "@/components/forms/options";
import { cn } from "@/utils/cn";
-import React, { useContext, useEffect } from "react";
-import {
- ColumnFetchValuesContext,
- ColumnInfoContext,
- ColumnNameContext,
-} from "@/plugins/impl/data-frames/forms/context";
+import React from "react";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
-import { getOperatorForDtype, getSchemaForOperator } from "../utils/operators";
import { Strings } from "@/utils/strings";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
@@ -51,38 +37,60 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
-import { DataTypeIcon } from "./datatype-icon";
-import { Events } from "@/utils/events";
-import { useAsyncData } from "@/hooks/useAsyncData";
import { Combobox, ComboboxItem } from "@/components/ui/combobox";
+import { Events } from "@/utils/events";
import {
- SwitchableMultiSelect,
TextAreaMultiSelect,
ensureStringArray,
-} from "@/components/forms/switchable-multi-select";
-import type { ColumnId } from "../types";
+ SwitchableMultiSelect,
+} from "./switchable-multi-select";
+import { Textarea } from "../ui/textarea";
+export interface FormRenderer<T extends FieldValues = any, S = any> {
+ isMatch: (schema: z.ZodType) => schema is z.ZodType<S, z.ZodTypeDef, unknown>;
+ Component: React.ComponentType<{
+ schema: z.ZodType<S, z.ZodTypeDef, unknown>;
+ form: UseFormReturn<T>;
+ path: Path<T>;
+ }>;
+}
interface Props<T extends FieldValues> {
form: UseFormReturn<T>;
schema: z.ZodType;
path?: Path<T>;
+ renderers?: Array<FormRenderer<T>>;
+ children?: React.ReactNode;
}
export const ZodForm = <T extends FieldValues>({
schema,
form,
path = "" as Path<T>,
+ renderers = [],
+ children,
}: Props<T>) => {
return (
- <FormProvider {...form}>{renderZodSchema(schema, form, path)}</FormProvider>
+ <FormProvider {...form}>
+ {children}
+ {renderZodSchema(schema, form, path, renderers)}
+ </FormProvider>
);
};
-function renderZodSchema<T extends FieldValues, S>(
+export function renderZodSchema<T extends FieldValues, S>(
schema: z.ZodType<S>,
form: UseFormReturn<T>,
path: Path<T>,
+ renderers: Array<FormRenderer<T>>,
) {
+ // Try custom renderers first
+ for (const renderer of renderers) {
+ const { isMatch, Component } = renderer;
+ if (isMatch(schema)) {
+ return <Component schema={schema} form={form} path={path} />;
+ }
+ }
+
const {
label,
description,
@@ -92,27 +100,32 @@ function renderZodSchema<T extends FieldValues, S>(
if (schema instanceof z.ZodDefault) {
let inner = schema._def.innerType as z.ZodType<unknown>;
- // pass along the description
inner =
!inner.description && schema.description
? inner.describe(schema.description)
: inner;
- return renderZodSchema(inner, form, path);
+ return renderZodSchema(inner, form, path, renderers);
}
- if (special === "column_id") {
- return <ColumnFormField schema={schema} form={form} path={path} />;
+
+ if (schema instanceof z.ZodOptional) {
+ let inner = schema._def.innerType as z.ZodType<unknown>;
+ inner =
+ !inner.description && schema.description
+ ? inner.describe(schema.description)
+ : inner;
+ return renderZodSchema(inner, form, path, renderers);
}
if (schema instanceof z.ZodObject) {
- if (special === "column_filter") {
- return <FilterForm schema={schema} form={form} path={path} />;
- }
-
return (
<div
className={cn(
"flex",
- direction === "row" ? "flex-row gap-6 items-start" : "flex-col gap-6",
+ direction === "row"
+ ? "flex-row gap-6 items-start"
+ : direction === "two-columns"
+ ? "grid grid-cols-2 gap-y-6"
+ : "flex-col gap-6",
)}
>
<FormLabel>{label}</FormLabel>
@@ -121,7 +134,8 @@ function renderZodSchema<T extends FieldValues, S>(
const childForm = renderZodSchema(
value as z.ZodType<unknown>,
form,
- `${path}.${key}` as Path<T>,
+ joinPath(path, key),
+ renderers,
);
if (isLiteral) {
@@ -137,10 +151,8 @@ function renderZodSchema<T extends FieldValues, S>(
</div>
);
}
+
if (schema instanceof z.ZodString) {
- if (special === "column_values") {
- return <ColumnValuesFormField schema={schema} form={form} path={path} />;
- }
if (special === "time") {
return (
<FormField
@@ -282,27 +294,9 @@ function renderZodSchema<T extends FieldValues, S>(
if (special === "text_area_multiline") {
return <MultiStringFormField schema={schema} form={form} path={path} />;
}
- if (special === "column_values") {
- return (
- <MultiColumnValuesFormField schema={schema} form={form} path={path} />
- );
- }
// Inspect child type for a better input
const childType = schema._def.type;
- const childSpecial = FieldOptions.parse(childType._def.description).special;
-
- // Show column multi-select for array with column_id
- if (childSpecial === "column_id") {
- return (
- <MultiColumnFormField
- schema={childType}
- form={form}
- path={path}
- itemLabel={label}
- />
- );
- }
// Show multi-select for enum array
if (childType instanceof z.ZodEnum) {
@@ -368,7 +362,8 @@ function renderZodSchema<T extends FieldValues, S>(
);
})}
</NativeSelect>
- {selectedOption && renderZodSchema(selectedOption, form, path)}
+ {selectedOption &&
+ renderZodSchema(selectedOption, form, path, renderers)}
</div>
);
}}
@@ -380,7 +375,9 @@ function renderZodSchema<T extends FieldValues, S>(
<FormField
control={form.control}
name={path}
- render={({ field }) => <input {...field} type="hidden" />}
+ render={({ field }) => (
+ <input {...field} type="hidden" value={schema._def.value} />
+ )}
/>
);
}
@@ -388,8 +385,9 @@ function renderZodSchema<T extends FieldValues, S>(
schema instanceof z.ZodEffects &&
["refinement", "transform"].includes(schema._def.effect.type)
) {
- return renderZodSchema(schema._def.schema, form, path);
+ return renderZodSchema(schema._def.schema, form, path, renderers);
}
+
return (
<div>
Unknown schema type{" "}
@@ -398,17 +396,6 @@ function renderZodSchema<T extends FieldValues, S>(
);
}
-const StyledFormMessage = ({ className }: { className?: string }) => {
- return (
- <FormMessageTooltip
- className={cn(
- "absolute -left-6 bottom-0 text-destructive text-xs w-[16px]",
- className,
- )}
- />
- );
-};
-
/**
* Type: T[]
*/
@@ -448,7 +435,7 @@ const FormArray = ({
key={field.id}
onKeyDown={Events.onEnter((e) => e.preventDefault())}
>
- {renderZodSchema(schema, form, `${path}[${index}]`)}
+ {renderZodSchema(schema, form, `${path}[${index}]`, [])}
{canRemove && (
<Trash2Icon
className="w-4 h-4 ml-2 my-1 text-muted-foreground hover:text-destructive cursor-pointer absolute right-0 top-5"
@@ -484,297 +471,46 @@ const FormArray = ({
};
/**
- * Type: string | number
- * Special: column_id
+ * Type: string
*/
-const ColumnFormField = ({
+const StringFormField = ({
schema,
form,
path,
- onChange,
}: {
- schema: z.ZodSchema;
+ schema: z.ZodAny | z.ZodString;
form: UseFormReturn<any>;
path: Path<any>;
- onChange?: (value: ColumnId) => void;
}) => {
- const columns = useContext(ColumnInfoContext);
- const { label, description } = FieldOptions.parse(schema._def.description);
-
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <StyledFormMessage />
- <FormControl>
- <Select
- data-testid="marimo-plugin-data-frames-column-select"
- value={
- field.value == null ? field.value : JSON.stringify(field.value)
- }
- onValueChange={(value) => {
- const realValue = JSON.parse(value) as ColumnId;
- onChange?.(realValue);
- field.onChange(realValue);
- }}
- >
- <SelectTrigger className="min-w-[180px]">
- <SelectValue placeholder="--" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {[...columns.entries()].map(([name, dtype]) => {
- return (
- <SelectItem key={name} value={JSON.stringify(name)}>
- <span className="flex items-center gap-2 flex-1">
- <DataTypeIcon type={dtype} />
- <span className="flex-1">{name}</span>
- <span className="text-muted-foreground text-xs font-semibold">
- ({dtype})
- </span>
- </span>
- </SelectItem>
- );
- })}
- {columns.size === 0 && (
- <SelectItem disabled={true} value="--">
- No columns
- </SelectItem>
- )}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- </FormItem>
- )}
- />
- );
-};
+ const { label, description, placeholder, disabled, inputType } =
+ FieldOptions.parse(schema._def.description);
-/**
- * Type: (string | number)[]
- * Special: column_ids
- */
-const MultiColumnFormField = ({
- schema,
- form,
- path,
- itemLabel,
-}: {
- schema: z.ZodSchema;
- form: UseFormReturn<any>;
- path: Path<any>;
- itemLabel?: string;
-}) => {
- const columns = useContext(ColumnInfoContext);
- const { description } = FieldOptions.parse(schema._def.description);
- const placeholder = itemLabel
- ? `Select ${itemLabel.toLowerCase()}`
- : undefined;
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => {
- const values = ensureStringArray(field.value);
- return (
+ if (inputType === "textarea") {
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
<FormItem>
- <FormLabel>{itemLabel}</FormLabel>
+ <FormLabel>{label}</FormLabel>
<FormDescription>{description}</FormDescription>
<FormControl>
- <Combobox<ColumnId>
- className="min-w-[180px]"
+ <Textarea
+ {...field}
+ value={field.value}
+ onChange={field.onChange}
+ className="my-0"
placeholder={placeholder}
- displayValue={String}
- multiple={true}
- chips={true}
- keepPopoverOpenOnSelect={true}
- value={values}
- onValueChange={(v) => {
- field.onChange(v);
- }}
- >
- {[...columns.entries()].map(([name, dtype]) => {
- return (
- <ComboboxItem key={name} value={name}>
- <span className="flex items-center gap-2 flex-1">
- <DataTypeIcon type={dtype} />
- <span className="flex-1">{name}</span>
- <span className="text-muted-foreground text-xs font-semibold">
- ({dtype})
- </span>
- </span>
- </ComboboxItem>
- );
- })}
- </Combobox>
+ disabled={disabled}
+ />
</FormControl>
<FormMessage />
</FormItem>
- );
- }}
- />
- );
-};
-
-/**
- * Type: { column_id: string; operator: string; value: any }
- * Special: column_filter
- */
-const FilterForm = ({
- path,
- form,
- schema,
-}: {
- schema: z.ZodObject<{}>;
- form: UseFormReturn<any>;
- path: Path<any>;
-}) => {
- const { description } = FieldOptions.parse(schema._def.description);
- const columns = useContext(ColumnInfoContext);
- const { field } = useController({ name: path });
-
- const columnIdSchema = Objects.entries(schema._def.shape()).find(
- ([key, value]) => {
- return key === "column_id";
- },
- )?.[1] as unknown as z.ZodString;
-
- // existing values
- const { column_id: columnId, operator } = field.value ?? {};
-
- const children = [
- <ColumnFormField
- key={"column_id"}
- schema={columnIdSchema}
- form={form}
- path={`${path}.column_id`}
- onChange={(value) => {
- // Reset operator and value if the column type changes
- const currentDtype = columns.get(columnId);
- const nextDtype = columns.get(value);
- if (nextDtype !== currentDtype) {
- form.setValue(`${path}.value`, undefined);
- }
- }}
- />,
- ];
-
- // When column ID changes, get the new dtype and reset the operator
- useEffect(() => {
- const dtype = columns.get(columnId);
- const operators = getOperatorForDtype(dtype);
-
- const currentOperator = form.getValues(`${path}.operator`);
- if (!operators.includes(currentOperator)) {
- form.setValue(`${path}.operator`, operators[0]);
- form.setValue(`${path}.value`, undefined);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [columnId]);
-
- if (columnId != null) {
- const dtype = columns.get(columnId);
- const operators = getOperatorForDtype(dtype);
-
- if (operators.length === 0) {
- children.push(
- <div
- key={"no_operator"}
- className="text-muted-foreground text-xs font-semibold"
- >
- <FormLabel className="whitespace-pre"> </FormLabel>
- <div>This column type does not support filtering.</div>
- </div>,
- );
- } else {
- children.push(
- <FormField
- key={"operator"}
- control={form.control}
- name={`${path}.operator`}
- render={({ field }) => (
- <FormItem>
- <FormLabel className="whitespace-pre"> </FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <Select
- data-testid="marimo-plugin-data-frames-filter-operator-select"
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger className="min-w-[140px]">
- <SelectValue placeholder="--" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {operators.map((value: string) => {
- return (
- <SelectItem key={value} value={value}>
- {Strings.startCase(value)}
- </SelectItem>
- );
- })}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />,
- );
- }
- }
-
- if (operator != null) {
- const dtype = columns.get(columnId);
- const operandSchemas = getSchemaForOperator(dtype, operator);
- if (operandSchemas.length === 1) {
- children.push(
- <React.Fragment key={"value"}>
- <ColumnNameContext.Provider value={columnId}>
- {renderZodSchema(operandSchemas[0], form, `${path}.value`)}
- </ColumnNameContext.Provider>
- </React.Fragment>,
- );
- }
+ )}
+ />
+ );
}
- return (
- <FormField
- control={form.control}
- name={path}
- render={() => (
- <div className="flex flex-col gap-2 bg-red">
- <div className={cn("flex flex-row gap-2")}>{children}</div>
- <FormMessage />
- </div>
- )}
- />
- );
-};
-
-/**
- * Type: string
- */
-const StringFormField = ({
- schema,
- form,
- path,
-}: {
- schema: z.ZodAny | z.ZodString;
- form: UseFormReturn<any>;
- path: Path<any>;
-}) => {
- const { label, description, placeholder, disabled } = FieldOptions.parse(
- schema._def.description,
- );
-
return (
<FormField
control={form.control}
@@ -786,6 +522,7 @@ const StringFormField = ({
<FormControl>
<DebouncedInput
{...field}
+ type={inputType}
value={field.value}
onValueChange={field.onChange}
className="my-0"
@@ -1012,105 +749,6 @@ const MultiSelectFormField = ({
);
};
-/**
- * Type: string
- * Special: column_values
- */
-const ColumnValuesFormField = ({
- schema,
- form,
- path,
-}: {
- schema: z.ZodString;
- form: UseFormReturn<any>;
- path: Path<any>;
-}) => {
- const { label, description, placeholder } = FieldOptions.parse(
- schema._def.description,
- );
- const column = useContext(ColumnNameContext);
- const fetchValues = useContext(ColumnFetchValuesContext);
- const { data, loading } = useAsyncData(() => {
- return fetchValues({ column });
- }, [column]);
-
- const options = data?.values || [];
-
- // loaded with no options
- if (options.length === 0 && !loading) {
- return <StringFormField schema={schema} form={form} path={path} />;
- }
-
- const optionsAsStrings = options.map(String);
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => {
- return (
- <FormItem>
- <FormLabel className="whitespace-pre">{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <Combobox
- className="min-w-[180px]"
- placeholder={placeholder}
- multiple={false}
- displayValue={(option: string) => option}
- value={
- Array.isArray(field.value) ? field.value[0] : field.value
- }
- onValueChange={field.onChange}
- >
- {optionsAsStrings.map((option) => (
- <ComboboxItem key={option} value={option}>
- {option}
- </ComboboxItem>
- ))}
- </Combobox>
- </FormControl>
- <FormMessage />
- </FormItem>
- );
- }}
- />
- );
-};
-
-/**
- * Type: string[]
- * Special: column_values
- */
-const MultiColumnValuesFormField = ({
- schema,
- form,
- path,
-}: {
- schema: z.ZodString | z.ZodArray<any>;
- form: UseFormReturn<any>;
- path: Path<any>;
-}) => {
- const column = useContext(ColumnNameContext);
- const fetchValues = useContext(ColumnFetchValuesContext);
- const { data, loading } = useAsyncData(() => {
- return fetchValues({ column });
- }, [column]);
-
- const options = data?.values || [];
-
- // loaded with no options
- if (options.length === 0 && !loading) {
- return <MultiStringFormField schema={schema} form={form} path={path} />;
- }
-
- const optionsAsStrings = options.map(String);
- return (
- <MultiSelectFormField
- schema={schema}
- form={form}
- path={path}
- showSwitchable={true}
- options={optionsAsStrings}
- />
- );
-};
+function joinPath<T>(...parts: Array<string | number>): Path<T> {
+ return parts.filter((part) => part !== "").join(".") as Path<T>;
+}
diff --git a/frontend/src/plugins/impl/data-frames/forms/options.ts b/frontend/src/components/forms/options.ts
similarity index 82%
rename from frontend/src/plugins/impl/data-frames/forms/options.ts
rename to frontend/src/components/forms/options.ts
index 4e042f1fce..8363225088 100644
--- a/frontend/src/plugins/impl/data-frames/forms/options.ts
+++ b/frontend/src/components/forms/options.ts
@@ -5,7 +5,17 @@ export interface FieldOptions {
placeholder?: string;
disabled?: boolean;
hidden?: boolean;
- direction?: "row" | "column";
+ direction?: "row" | "column" | "two-columns";
+ /**
+ * Only valid for string fields
+ */
+ inputType?:
+ | "password"
+ | "text"
+ | "number"
+ | "checkbox"
+ | "select"
+ | "textarea";
special?:
| "column_id"
| "random_number_button"
diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsx
index c6edd96caf..b4ce46dfe8 100644
--- a/frontend/src/components/ui/form.tsx
+++ b/frontend/src/components/ui/form.tsx
@@ -18,6 +18,22 @@ import { AlertCircleIcon } from "lucide-react";
const Form = FormProvider;
+export const FormErrorsBanner = () => {
+ const ctx = useFormContext();
+ const errors = ctx.formState.errors;
+ if (Object.keys(errors).length === 0) {
+ return null;
+ }
+ return (
+ <div className="text-destructive p-2 rounded-md bg-red-500/10">
+ {Object.values(errors)
+ .map((error) => error?.message)
+ .filter(Boolean)
+ .join(", ")}
+ </div>
+ );
+};
+
interface FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap
index 5c04f58cd1..167011babe 100644
--- a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap
+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap
@@ -6,9 +6,9 @@ exports[`renderZodSchema > should render a form 1`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="filter_rows"
/>
<div
class="flex flex-row align-start"
@@ -35,7 +35,7 @@ exports[`renderZodSchema > should render a form 1`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".operation-keep_rows"
+ id="operation-keep_rows"
role="radio"
tabindex="-1"
type="button"
@@ -43,7 +43,7 @@ exports[`renderZodSchema > should render a form 1`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".operation-keep_rows"
+ for="operation-keep_rows"
>
Keep Rows
</label>
@@ -56,7 +56,7 @@ exports[`renderZodSchema > should render a form 1`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".operation-remove_rows"
+ id="operation-remove_rows"
role="radio"
tabindex="-1"
type="button"
@@ -64,7 +64,7 @@ exports[`renderZodSchema > should render a form 1`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".operation-remove_rows"
+ for="operation-remove_rows"
>
Remove Rows
</label>
@@ -131,9 +131,9 @@ exports[`renderZodSchema > should render a form 2`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="select_columns"
/>
<div
class="flex flex-row align-start"
@@ -195,9 +195,9 @@ exports[`renderZodSchema > should render a form 3`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="rename_column"
/>
<div
class="flex flex-row align-start"
@@ -261,7 +261,7 @@ exports[`renderZodSchema > should render a form 3`] = `
aria-invalid="false"
class="shadow-xsSolid hover:shadow-smSolid disabled:shadow-xsSolid focus-visible:shadow-mdSolid flex h-6 w-full rounded-sm border border-input bg-background px-1.5 py-1 text-sm font-code ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 my-0"
id=":r7:-form-item"
- name=".new_column_id"
+ name="new_column_id"
value=""
/>
</div>
@@ -277,9 +277,9 @@ exports[`renderZodSchema > should render a form 4`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="column_conversion"
/>
<div
class="flex flex-row align-start"
@@ -408,7 +408,7 @@ exports[`renderZodSchema > should render a form 4`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".errors-ignore"
+ id="errors-ignore"
role="radio"
tabindex="-1"
type="button"
@@ -416,7 +416,7 @@ exports[`renderZodSchema > should render a form 4`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".errors-ignore"
+ for="errors-ignore"
>
Ignore
</label>
@@ -429,7 +429,7 @@ exports[`renderZodSchema > should render a form 4`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".errors-raise"
+ id="errors-raise"
role="radio"
tabindex="-1"
type="button"
@@ -437,7 +437,7 @@ exports[`renderZodSchema > should render a form 4`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".errors-raise"
+ for="errors-raise"
>
Raise
</label>
@@ -455,9 +455,9 @@ exports[`renderZodSchema > should render a form 5`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="sort_column"
/>
<div
class="flex flex-row align-start"
@@ -568,7 +568,7 @@ exports[`renderZodSchema > should render a form 5`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".na_position-first"
+ id="na_position-first"
role="radio"
tabindex="-1"
type="button"
@@ -576,7 +576,7 @@ exports[`renderZodSchema > should render a form 5`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".na_position-first"
+ for="na_position-first"
>
First
</label>
@@ -589,7 +589,7 @@ exports[`renderZodSchema > should render a form 5`] = `
class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
data-radix-collection-item=""
data-state="unchecked"
- id=".na_position-last"
+ id="na_position-last"
role="radio"
tabindex="-1"
type="button"
@@ -597,7 +597,7 @@ exports[`renderZodSchema > should render a form 5`] = `
/>
<label
class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
- for=".na_position-last"
+ for="na_position-last"
>
Last
</label>
@@ -615,9 +615,9 @@ exports[`renderZodSchema > should render a form 6`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="group_by"
/>
<div
class="flex flex-row align-start"
@@ -757,9 +757,9 @@ exports[`renderZodSchema > should render a form 7`] = `
class="flex flex-row gap-6 items-start"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="aggregate"
/>
<div
class="flex flex-row align-start"
@@ -871,9 +871,9 @@ exports[`renderZodSchema > should render a form 8`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="sample_rows"
/>
<div
class="flex flex-row align-start"
@@ -974,7 +974,7 @@ exports[`renderZodSchema > should render a form 8`] = `
</div>
</div>
<input
- name=".n"
+ name="n"
type="hidden"
value=""
/>
@@ -1055,9 +1055,9 @@ exports[`renderZodSchema > should render a form 9`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="shuffle_rows"
/>
<div
class="flex flex-row align-start"
@@ -1104,9 +1104,9 @@ exports[`renderZodSchema > should render a form 10`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="explode_columns"
/>
<div
class="flex flex-row align-start"
@@ -1168,9 +1168,9 @@ exports[`renderZodSchema > should render a form 11`] = `
class="flex flex-col gap-6"
>
<input
- name=".type"
+ name="type"
type="hidden"
- value=""
+ value="expand_dict"
/>
<div
class="flex flex-row align-start"
diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx b/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx
index b19c5777fd..d18fd847f7 100644
--- a/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx
+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { ZodForm } from "../form";
+import { ZodForm } from "../../../../../components/forms/form";
import { TransformTypeSchema } from "../../schema";
import { render } from "@testing-library/react";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -8,6 +8,7 @@ import { useForm } from "react-hook-form";
import type { z } from "zod";
import type { ColumnId } from "../../types";
import { ColumnInfoContext } from "../context";
+import { DATAFRAME_FORM_RENDERERS } from "../renderers";
const ColumnTypes = new Map([
[0 as ColumnId, "str"],
@@ -25,7 +26,11 @@ const Subject = (props: { schema: z.ZodType }) => {
});
return (
<ColumnInfoContext.Provider value={ColumnTypes}>
- <ZodForm form={form} schema={props.schema} />
+ <ZodForm
+ form={form}
+ schema={props.schema}
+ renderers={DATAFRAME_FORM_RENDERERS}
+ />
</ColumnInfoContext.Provider>
);
};
diff --git a/frontend/src/plugins/impl/data-frames/forms/renderers.tsx b/frontend/src/plugins/impl/data-frames/forms/renderers.tsx
new file mode 100644
index 0000000000..6ccb1ef07b
--- /dev/null
+++ b/frontend/src/plugins/impl/data-frames/forms/renderers.tsx
@@ -0,0 +1,517 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import {
+ type Path,
+ useController,
+ type UseFormReturn,
+ type FieldValues,
+} from "react-hook-form";
+import { z } from "zod";
+import { renderZodSchema, type FormRenderer } from "@/components/forms/form";
+import { FieldOptions } from "@/components/forms/options";
+import { useContext, useEffect } from "react";
+import {
+ ColumnInfoContext,
+ ColumnNameContext,
+ ColumnFetchValuesContext,
+} from "./context";
+import {
+ FormField,
+ FormItem,
+ FormLabel,
+ FormDescription,
+ FormControl,
+ FormMessage,
+ FormMessageTooltip,
+} from "@/components/ui/form";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { DataTypeIcon } from "./datatype-icon";
+import { Combobox, ComboboxItem } from "@/components/ui/combobox";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import {
+ SwitchableMultiSelect,
+ TextAreaMultiSelect,
+ ensureStringArray,
+} from "@/components/forms/switchable-multi-select";
+import { DebouncedInput } from "@/components/ui/input";
+import { cn } from "@/utils/cn";
+import { Objects } from "@/utils/objects";
+import { Strings } from "@/utils/strings";
+import React from "react";
+import { getOperatorForDtype, getSchemaForOperator } from "../utils/operators";
+import type { ColumnId } from "../types";
+
+export const columnIdRenderer = <T extends FieldValues>(): FormRenderer<
+ T,
+ string
+> => ({
+ isMatch: (schema: z.ZodType): schema is z.ZodString => {
+ const { special } = FieldOptions.parse(schema._def.description || "");
+ return special === "column_id";
+ },
+ Component: ({ schema, form, path }) => {
+ const columns = useContext(ColumnInfoContext);
+ const { label, description } = FieldOptions.parse(schema._def.description);
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <StyledFormMessage />
+ <FormControl>
+ <Select
+ data-testid="marimo-plugin-data-frames-column-select"
+ value={
+ field.value == null
+ ? field.value
+ : JSON.stringify(field.value)
+ }
+ onValueChange={(value) => {
+ const realValue = JSON.parse(value);
+ field.onChange(realValue);
+ }}
+ >
+ <SelectTrigger className="min-w-[180px]">
+ <SelectValue placeholder="--" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {[...columns.entries()].map(([name, dtype]) => (
+ <SelectItem key={name} value={JSON.stringify(name)}>
+ <span className="flex items-center gap-2 flex-1">
+ <DataTypeIcon type={dtype} />
+ <span className="flex-1">{name}</span>
+ <span className="text-muted-foreground text-xs font-semibold">
+ ({dtype})
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ {columns.size === 0 && (
+ <SelectItem disabled={true} value="--">
+ No columns
+ </SelectItem>
+ )}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+ },
+});
+
+export const multiColumnIdRenderer = <T extends FieldValues>(): FormRenderer<
+ T,
+ string[]
+> => ({
+ isMatch: (schema: z.ZodType): schema is z.ZodArray<z.ZodString> => {
+ if (schema instanceof z.ZodArray) {
+ const childType = schema._def.type;
+ const { special } = FieldOptions.parse(childType._def.description || "");
+ return special === "column_id";
+ }
+ return false;
+ },
+ Component: ({ schema, form, path }) => {
+ const { label } = FieldOptions.parse(schema._def.description);
+ return (
+ <MultiColumnFormField
+ schema={schema}
+ form={form}
+ path={path}
+ itemLabel={label}
+ />
+ );
+ },
+});
+
+/**
+ * Type: (string | number)[]
+ * Special: column_ids
+ */
+const MultiColumnFormField = ({
+ schema,
+ form,
+ path,
+ itemLabel,
+}: {
+ schema: z.ZodSchema;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+ itemLabel?: string;
+}) => {
+ const columns = useContext(ColumnInfoContext);
+ const { description } = FieldOptions.parse(schema._def.description);
+ const placeholder = itemLabel
+ ? `Select ${itemLabel.toLowerCase()}`
+ : undefined;
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => {
+ const values = ensureStringArray(field.value);
+ return (
+ <FormItem>
+ <FormLabel>{itemLabel}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Combobox<ColumnId>
+ className="min-w-[180px]"
+ placeholder={placeholder}
+ displayValue={String}
+ multiple={true}
+ chips={true}
+ keepPopoverOpenOnSelect={true}
+ value={values}
+ onValueChange={(v) => {
+ field.onChange(v);
+ }}
+ >
+ {[...columns.entries()].map(([name, dtype]) => {
+ return (
+ <ComboboxItem key={name} value={name}>
+ <span className="flex items-center gap-2 flex-1">
+ <DataTypeIcon type={dtype} />
+ <span className="flex-1">{name}</span>
+ <span className="text-muted-foreground text-xs font-semibold">
+ ({dtype})
+ </span>
+ </span>
+ </ComboboxItem>
+ );
+ })}
+ </Combobox>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ );
+};
+
+export const columnValuesRenderer = <T extends FieldValues>(): FormRenderer<
+ T,
+ string[]
+> => ({
+ isMatch: (schema: z.ZodType): schema is z.ZodArray<z.ZodString> => {
+ if (schema instanceof z.ZodArray) {
+ const { special } = FieldOptions.parse(schema._def.description || "");
+ return special === "column_values";
+ }
+ return false;
+ },
+ Component: ({ schema, form, path }) => {
+ const { label, description, placeholder } = FieldOptions.parse(
+ schema._def.description,
+ );
+ const column = useContext(ColumnNameContext);
+ const fetchValues = useContext(ColumnFetchValuesContext);
+ const { data, loading } = useAsyncData(
+ () => fetchValues({ column }),
+ [column],
+ );
+
+ const options = data?.values || [];
+
+ if (options.length === 0 && !loading) {
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <DebouncedInput
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ className="my-0"
+ placeholder={placeholder}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+ }
+
+ const optionsAsStrings = options.map(String);
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="whitespace-pre">{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Combobox
+ className="min-w-[180px]"
+ placeholder={placeholder}
+ multiple={false}
+ displayValue={(option: string) => option}
+ value={
+ Array.isArray(field.value) ? field.value[0] : field.value
+ }
+ onValueChange={field.onChange}
+ >
+ {optionsAsStrings.map((option) => (
+ <ComboboxItem key={option} value={option}>
+ {option}
+ </ComboboxItem>
+ ))}
+ </Combobox>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+ },
+});
+
+export const multiColumnValuesRenderer = <
+ T extends FieldValues,
+>(): FormRenderer<T> => ({
+ isMatch: (schema: z.ZodType): schema is z.ZodArray<z.ZodString> => {
+ const { special } = FieldOptions.parse(schema._def.description || "");
+ return special === "column_values" && schema instanceof z.ZodArray;
+ },
+ Component: ({ schema, form, path }) => {
+ const column = useContext(ColumnNameContext);
+ const fetchValues = useContext(ColumnFetchValuesContext);
+ const { data, loading } = useAsyncData(
+ () => fetchValues({ column }),
+ [column],
+ );
+
+ const options = data?.values || [];
+
+ if (options.length === 0 && !loading) {
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{schema.description}</FormLabel>
+ <FormControl>
+ <TextAreaMultiSelect {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+ }
+
+ const optionsAsStrings = options.map(String);
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => {
+ const valueAsArray = ensureStringArray(field.value);
+ return (
+ <FormItem>
+ <FormLabel>{schema.description}</FormLabel>
+ <FormControl>
+ <SwitchableMultiSelect
+ {...field}
+ value={valueAsArray}
+ options={optionsAsStrings}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ );
+ },
+});
+
+const StyledFormMessage = ({ className }: { className?: string }) => {
+ return (
+ <FormMessageTooltip
+ className={cn(
+ "absolute -left-6 bottom-0 text-destructive text-xs w-[16px]",
+ className,
+ )}
+ />
+ );
+};
+
+export const filterFormRenderer = <T extends FieldValues>(): FormRenderer<
+ T,
+ {}
+> => ({
+ isMatch: (schema: z.ZodType): schema is z.ZodObject<{}> => {
+ if (schema instanceof z.ZodObject) {
+ const { special } = FieldOptions.parse(schema._def.description || "");
+ return special === "column_filter";
+ }
+ return false;
+ },
+ Component: ({ schema, form, path }) => {
+ return (
+ <ColumnFilterForm
+ schema={schema as z.ZodObject<{}>}
+ form={form}
+ path={path}
+ />
+ );
+ },
+});
+
+const ColumnFilterForm = <T extends FieldValues>({
+ path,
+ form,
+ schema,
+}: {
+ schema: z.ZodObject<{}>;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+}) => {
+ const { description } = FieldOptions.parse(schema._def.description);
+ const columns = useContext(ColumnInfoContext);
+ const { field } = useController({ name: path });
+
+ const columnIdSchema = Objects.entries(schema._def.shape()).find(
+ ([key]) => key === "column_id",
+ )?.[1] as unknown as z.ZodString;
+
+ // existing values
+ const { column_id: columnId, operator } = (field.value ?? {}) as {
+ column_id: ColumnId;
+ operator: string;
+ };
+
+ const columnRenderer = columnIdRenderer<T>();
+ const children = [
+ renderZodSchema(columnIdSchema, form, `${path}.column_id` as Path<T>, [
+ columnRenderer,
+ ]),
+ ];
+
+ // When column ID changes, get the new dtype and reset the operator
+ useEffect(() => {
+ const dtype = columns.get(columnId);
+ const operators = getOperatorForDtype(dtype);
+
+ const currentOperator = form.getValues(`${path}.operator`);
+ if (!operators.includes(currentOperator)) {
+ form.setValue(`${path}.operator`, operators[0]);
+ form.setValue(`${path}.value`, undefined);
+ }
+ }, [columnId, columns, form, path]);
+
+ if (columnId != null) {
+ const dtype = columns.get(columnId);
+ const operators = getOperatorForDtype(dtype);
+
+ if (operators.length === 0) {
+ children.push(
+ <div
+ key="no_operator"
+ className="text-muted-foreground text-xs font-semibold"
+ >
+ <FormLabel className="whitespace-pre"> </FormLabel>
+ <div>This column type does not support filtering.</div>
+ </div>,
+ );
+ } else {
+ children.push(
+ <FormField
+ key="operator"
+ control={form.control}
+ name={`${path}.operator` as Path<T>}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="whitespace-pre"> </FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Select
+ data-testid="marimo-plugin-data-frames-filter-operator-select"
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger className="min-w-[140px]">
+ <SelectValue placeholder="--" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {operators.map((value: string) => (
+ <SelectItem key={value} value={value}>
+ {Strings.startCase(value)}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />,
+ );
+ }
+ }
+
+ if (operator != null) {
+ const dtype = columns.get(columnId);
+ const operandSchemas = getSchemaForOperator(dtype, operator);
+ if (operandSchemas.length === 1) {
+ children.push(
+ <React.Fragment key="value">
+ {renderZodSchema(
+ operandSchemas[0],
+ form,
+ `${path}.value` as Path<T>,
+ [],
+ )}
+ </React.Fragment>,
+ );
+ }
+ }
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={() => (
+ <div className="flex flex-col gap-2">
+ <div className={cn("flex flex-row gap-2")}>{children}</div>
+ <FormMessage />
+ </div>
+ )}
+ />
+ );
+};
+
+export const DATAFRAME_FORM_RENDERERS: FormRenderer[] = [
+ columnIdRenderer(),
+ multiColumnIdRenderer(),
+ columnValuesRenderer(),
+ multiColumnValuesRenderer(),
+ filterFormRenderer(),
+];
diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsx
index 7b58978c27..91418eb514 100644
--- a/frontend/src/plugins/impl/data-frames/panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/panel.tsx
@@ -19,8 +19,11 @@ import { Button } from "../../../components/ui/button";
import { zodResolver } from "@hookform/resolvers/zod";
import { useFieldArray, useForm } from "react-hook-form";
import type { z } from "zod";
-import { ZodForm } from "./forms/form";
-import { getDefaults, getUnionLiteral } from "./forms/form-utils";
+import { ZodForm } from "../../../components/forms/form";
+import {
+ getDefaults,
+ getUnionLiteral,
+} from "../../../components/forms/form-utils";
import {
ArrowUpDownIcon,
ColumnsIcon,
@@ -46,6 +49,7 @@ import useEvent from "react-use-event-hook";
import type { ColumnDataTypes } from "./types";
import { getUpdatedColumnTypes } from "./utils/getUpdatedColumnTypes";
import { Strings } from "@/utils/strings";
+import { DATAFRAME_FORM_RENDERERS } from "./forms/renderers";
interface Props {
columns: ColumnDataTypes;
@@ -151,6 +155,7 @@ export const TransformPanel: React.FC<Props> = ({
form={form}
schema={selectedTransformSchema}
path={`transforms.${selectedTransform}`}
+ renderers={DATAFRAME_FORM_RENDERERS}
/>
)}
{(selectedTransform === undefined || !selectedTransformSchema) && (
diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.ts
index 3ef2a8a212..eec1891c73 100644
--- a/frontend/src/plugins/impl/data-frames/schema.ts
+++ b/frontend/src/plugins/impl/data-frames/schema.ts
@@ -4,10 +4,7 @@ import {
type ColumnId,
NUMPY_DTYPES,
} from "@/plugins/impl/data-frames/types";
-import {
- FieldOptions,
- randomNumber,
-} from "@/plugins/impl/data-frames/forms/options";
+import { FieldOptions, randomNumber } from "@/components/forms/options";
import { z } from "zod";
import {
ALL_OPERATORS,
diff --git a/frontend/src/plugins/impl/data-frames/utils/operators.ts b/frontend/src/plugins/impl/data-frames/utils/operators.ts
index 02c6f00dd9..c8d2f508d1 100644
--- a/frontend/src/plugins/impl/data-frames/utils/operators.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/operators.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { z } from "zod";
-import { FieldOptions } from "../forms/options";
+import { FieldOptions } from "../../../../components/forms/options";
import type { DataType } from "@/core/kernel/messages";
const Schema = {