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: SQL engines (#3563)
Myles Scolnick07ac53d92470
diff --git a/.gitignore b/.gitignoreindex 9a3912a742..34815b9531 100644--- a/.gitignore+++ b/.gitignore@@ -91,6 +91,9 @@ env.bak/venv.bak/uv.lock+# WIP files+.wip/+# editors*.swpdiff --git a/development_docs/openapi.md b/development_docs/openapi.mdindex f576e0b566..0f98e714ed 100644--- a/development_docs/openapi.md+++ b/development_docs/openapi.md@@ -1,5 +1,7 @@# marimo + openapi+The frontend of marimo communicates with the backend through an OpenAPI specification, which can be found in [`openapi/api.yaml`](/openapi/api.yaml).+## Printing the OpenAPI schema```bash@@ -8,6 +10,8 @@ marimo development openapi## Writing a new OpenAPI schema+To modify the schema, add the type under `_generate_schema` in [`commands.py`](/marimo/_cli/development/commands.py) and run+```bashmarimo development openapi > openapi/api.yaml```diff --git a/docs/_static/docs-sql-engine-dropdown.png b/docs/_static/docs-sql-engine-dropdown.pngnew file mode 100644index 0000000000..97a536fc09Binary files /dev/null and b/docs/_static/docs-sql-engine-dropdown.png differdiff --git a/docs/guides/working_with_data/sql.md b/docs/guides/working_with_data/sql.mdindex f716487726..0ac42996ac 100644--- a/docs/guides/working_with_data/sql.md+++ b/docs/guides/working_with_data/sql.md@@ -131,6 +131,33 @@ To escape real `{`/`}` that you don't want parameterized, use double `{{...}}`:SELECT unnest([{{'a': 42, 'b': 84}}, {{'a': 100, 'b': NULL}}]);```+## Connecting to a custom database++marimo supports bringing your own database via a **connection engine** created with a library like [SQLAlchemy](https://docs.sqlalchemy.org/en/20/core/connections.html#basic-usage), [SQLModel](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/?h=create+engine#create-the-engine), or a [custom DuckDB connection](https://duckdb.org/docs/api/python/overview.html#connection-options). By default, marimo uses the [In-Memory duckdb connection](https://duckdb.org/docs/connect/overview.html#in-memory-database).++First, you need to define the engine as a Python variable in a cell.+marimo will auto-discover the engine and let you select it in a dropdown in the SQL cell.++```python+import sqlalchemy+import sqlmodel+import duckdb++# Create an in-memory SQLite database with SQLAlchemy+sqlite_engine = sqlachemy.create_engine("sqlite:///:memory:")+# Create a Postgres database with SQLModel+postgres_engine = sqlmodel.create_engine("postgresql://username:password@server:port/database")+# Create a DuckDB connection+duckdb_conn = duckdb.connect("file.db")+```++<div align="center">+ <figure>+ <img src="/_static/docs-sql-engine-dropdown.png"/>+ <figcaption>Choose a custom database connection</figcaption>+ </figure>+</div>+## Interactive tutorialFor an interactive tutorial, rundiff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex b4c15f12fc..aeaae5daf1 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -320,7 +320,7 @@ importers:version: 0.27.1react-arborist:specifier: ^3.4.0- version: 3.4.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ version: 3.4.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])react-aria-components:specifier: ^1.5.0@@ -392,7 +392,7 @@ importers:version: 5.21.0([email protected])vega-loader:specifier: ^4.5.2- version: 4.5.2+ version: 4.5.3vscode-languageserver-protocol:specifier: ^3.17.5version: 3.17.5@@ -450,7 +450,7 @@ importers:version: 8.5.2(@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])'@storybook/react-vite':specifier: ^8.5.1- version: 8.5.2(@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ version: 8.5.2(@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))'@swc-jotai/react-refresh':specifier: ^0.1.1version: 0.1.1@@ -471,7 +471,7 @@ importers:version: 4.17.12'@types/node':specifier: ^20.16.1- version: 20.17.14+ version: 20.17.16'@types/react':specifier: ^18.3.3version: 18.3.12@@ -492,10 +492,10 @@ importers:version: 7.15.0([email protected])([email protected])'@vitejs/plugin-react':specifier: ^4.3.4'@vitejs/plugin-react-swc':specifier: ^3.7.2- version: 3.7.2(@swc/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ version: 3.7.2(@swc/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))autoprefixer:specifier: ^10.4.20version: 10.4.20([email protected])@@ -537,7 +537,7 @@ importers:version: 54.0.0([email protected])eslint-plugin-vitest:specifier: ^0.4.1- version: 0.4.1(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ version: 0.4.1(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))jsdom:specifier: ^24.1.1version: 24.1.1@@ -582,13 +582,13 @@ importers:version: 5.7.3vite:specifier: ^5.4.13vite-tsconfig-paths:specifier: ^4.3.2- version: 4.3.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ version: 4.3.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))vitest:specifier: ^3.0.2packages:@@ -3654,8 +3654,8 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==}- '@types/[email protected]':- resolution: {integrity: sha512-w6qdYetNL5KRBiSClK/KWai+2IMEJuAj+EujKCumalFOwXtvOXaEan9AuwcRID2IcOIAWSIfR495hBtgKlx2zg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-vOTpLduLkZXePLxHiHsBLp98mHGnl8RptV4YAO3HfKO5UHjDvySGbxKtpYfy8Sx5+WKcgc45qNreJJRVM3L6mw==}'@types/[email protected]':resolution: {integrity: sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==}@@ -6754,8 +6754,8 @@ packages:resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==}- resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==}+ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}engines: {node: 4.x || >=6.0.0}peerDependencies:encoding: ^0.1.0@@ -8628,11 +8628,11 @@ packages:resolution: {integrity: sha512-OkJ9CACVcN9R5Pi9uF6MZBF06pO6qFpDYHWSKBJsdHP5o724KrsgR6UvbnXFH82FdsiTOff/HqjuaG8C7FL+9Q==}- resolution: {integrity: sha512-J7KVEXkpfRJBfRvwLxn5vNCzQCNkrnzmDvkvwhuiwT4gPm5sk7MK5TuUP8GCl/iKYw+kWeVXEtrVHwWtug+bcQ==}+ resolution: {integrity: sha512-nyPJAXAUABc3EocUXvAL1J/IWotZVsApIcvOeZaUdEQEtZ7bt8VtP2nj3CLbHBA8FZZVV+K6SmdwvCOaAD4wFQ==}- resolution: {integrity: sha512-9Md8+5iUC1MVKPKDyZ7pCEHk6I9am+DgaMzZqo/27O/KI4f23/WQXPyuI8jbNmc/mkm340P0TKREmzL5M7+2Dg==}+ resolution: {integrity: sha512-R2NX2HvgXL+u4E6u+L5lKvvRiCtnE6N6l+umgojfi53suhhkFP+zB+2UAQo4syxuZ4763H1csfkKc4xpqLzKnw==}resolution: {integrity: sha512-8Iava57LdROsatqsOhMLErHYaBpZBB7yZJlSVU3/xOK3l8Ft5WFnj5fm3OOAVML97/0yULE7LRVjXW5hV3fSpg==}@@ -8642,8 +8642,8 @@ packages:bundledDependencies:- yallist- resolution: {integrity: sha512-d25nVKZDrg109rC65M8uxE+7iUrTxktaqgK4fU3XZBgpWlh1K4UbU5nDag7kiHVVN4tKqwgd+synEotra9TiVQ==}+ resolution: {integrity: sha512-fsjEY1VaBAmqwt7Jlpz0dpPtfQFiBdP9igEefvumSpy7XUxOJmDQcRDnT3Qh9ctkv3itfPfI9g8FSnGcv2b4jQ==}resolution: {integrity: sha512-UwCu50Sqd8kNZ1X/XgiAY+QAyQUmGFAwyDu7y0T5fs6/TPQnDo/Bo346NgSgINBEhEKOAMY1Nd/rPOk4UEm/ew==}@@ -8654,29 +8654,32 @@ packages:resolution: {integrity: sha512-zxPzXO33FawU3WQHRmHJaRreyJlyMaNMn1uuCFSouJttPkBBWB5gCrha2f5+pF3t4NMFWTnSrgCkR6mcaubnng==}- resolution: {integrity: sha512-zv9L1Hm0KHE9M7mldHyz8sXbGu3KmC0Cdk7qfHkcTNS75Jpsem6jkbu6ZAwx5cNUeW91AxUQOu77r4mygq2wUQ==}+ resolution: {integrity: sha512-fFeDTh4UtOxlZWL54jf1ZqJHinyerWq/ROiqrQxqLkNJRJ86RmxYTgXwt65UoZ/l4VUv9eAd2qoJeDEf610Umw==}- resolution: {integrity: sha512-2BcuuqFr77vcCyKfcpedNFeYMxi+XEFCrlgLWNx7YV0PI8pdP5y/yPkzyuE9Tb894+KkRAvfQHZRAshcnFNcMw==}+ resolution: {integrity: sha512-cHZVaY2VNNIG2RyihhSiWniPd2W9R9kJq0znxzV602CgUVgxEfTKtx/lxnVCn8nNrdKAYrGiqIsBzIeKG1GWHw==}- resolution: {integrity: sha512-0kUfAj0dg0U6GcEY0Kp6LiSTCZ8l8jl1qVdQyToMyKmtZg/q56qsiJQZy3WWRr1MtWkTIZL71xSJXgjwjeUaAw==}+ resolution: {integrity: sha512-wQhw7KR46wKJAip28FF/CicW+oiJaPAwMKdrxlnTA0Nv8Bf7bloRlc+O3kON4b4H1iALLr9KgRcYTOeXNs2MOA==}resolution: {integrity: sha512-pCqmm5efd+3M65jrJGxEy3UGuRksmK6DnWijoSNocnxdCBxez+yqUUVX9o2pN8VxMe3648vZnR9/Vk5CXqRvIQ==}- resolution: {integrity: sha512-unuV/UxUHf6UJu6GYxMZonC3SZlMfFXYLOkgEsRSvmsMPt3+CVv8FmG88dXNRUJUrdROrJepgecqx0jOwMSnGA==}+ resolution: {integrity: sha512-uXjSDbbGcFLCQTZZI+OiZK0U+2dLWC26ONdO0g9RhPzXXzR3niPcFOA0bc/OeiHdTexqsLjOiXxR/K2BckB8gQ==}- resolution: {integrity: sha512-m+xDtT5092YPSnV0rdTLW+AWmoCb+A54JQ66MUJwiDBpKxvfKnTiQeuiWDU2YudjUoXZN9EBOcI6QHF8H2Lu2A==}+ resolution: {integrity: sha512-+WnnzEPKIU1/xTFUK3EMu2htN35gp9usNZcC0ZFg2up1/Vqu6JyZsX0PIO51oXSIeXn9bwk6VgzlOmJUcx92tA==}++ resolution: {integrity: sha512-0Z+TYKRgOEo8XYXnJc2HWg1EGpcbNAhJ9Wpi9ubIbEyEHqIgjCIyFVN8d4nSfsJOcWDzsSmRqohBztxAhOCSaw==}resolution: {integrity: sha512-po6oTOmeQqr1tzTCdD15tYxAQLeUnOVirAysgVEemzl+vfmvcEP7jQmlc51jz0jMA+WsbmE6oJywisQPu/H0Bg==}- resolution: {integrity: sha512-EfSFSCWAwVPsklM5g0gUEuohALgryuGC/SKMmsOH7dYT/bywmLBZhLVbrE+IHJAUauoGrMhYw1mqnXL/0giJBg==}+ resolution: {integrity: sha512-Emx4b5s7pvuRj3fBkAJ/E2snCoZACfKAwxVId7f/4kYVlAYLb5Swq6W8KZHrH4M9Qds1XJRUYW9/Y3cceqzEFA==}resolution: {integrity: sha512-RJg9uBNh5g0hA8xTzAcALUfNx0cEq7E7xx+vxPEGSMgI8z+A5KlE9u4jUx6nKu7Mjg1qZO8WOyWCmBS1kdFWPg==}@@ -8691,32 +8694,32 @@ packages:peerDependencies:vega: ^5.24.0- resolution: {integrity: sha512-ktIdGz3DRIS3XfTP9lJ6oMT5cKwC86nQkjUbXZbOtwXQFVNE2xVWBuH13GP6FKUZxg5hJCMtb5v/e/fwTvhKsQ==}+ resolution: {integrity: sha512-dUfIpxTLF2magoMaur+jXGvwMxjtdlDZaIS8lFj6N7IhUST6nIvBzuUlRM+zLYepI5GHtCLOnqdKU4XV0NggCA==}- resolution: {integrity: sha512-/hFIJs0yITxfvLIfhhcpUrcbKvu4UZYoMGmly5PSsbgo60oAsVQW8ZbX2Ji3iNFqZJh1ifoX/P0j+9wep1OISw==}+ resolution: {integrity: sha512-ZjF5aQfRe3yD5e2zYZcWWkUn9zGzUonMIirWTp3S3UBCujz+aT0+Ls6wbHdAH6hCPj3PVVkSWuuLkGEIUpWqyQ==}- resolution: {integrity: sha512-sqfnAAHumU7MWU1tQN3b6HNgKGF3legek0uLHhjLKcDJQxEc7kwcD18txFz2ffQks6d5j+AUhBiq4GARWf0DEQ==}+ resolution: {integrity: sha512-3pcVaQL9R3Zfk6PzopLX6awzrQUeYOXJzlfLGP2Xd93mqUepBa6m/reVrTUoSFXA3v9lfK4W/PS2AcVzD/MIcQ==}- resolution: {integrity: sha512-gxOQfmV7Ft/MYKpXDEo09WZyBuKOBqxqDRWay9KtfGq/E0Y4vbTPsWLv2cB1ToPJdKE6XSN6Re9tCIw5M/yMUg==}+ resolution: {integrity: sha512-AmccF++Z9uw4HNZC/gmkQGe6JsRxTG/R4QpbcSepyMvQN1Rj5KtVqMcmVFP1r3ivM4dYGFuPlzMWvuqp0iKMkQ==}- resolution: {integrity: sha512-30UXbujWjKNd5aeP+oeHuwFmzuyVYlBj4aDy9+AjfWLECu8wJt4K01vwegcaGPdCWcPLVIv4Oa9Lob4mcXn5KQ==}+ resolution: {integrity: sha512-b4eot3tWKCk++INWqot+6sLn3wDTj/HE+tRSbiaf8aecuniPMlwJEK7wWuhVGeW2Ae5n8fI/8TeTViaC94bNHA==}- resolution: {integrity: sha512-dArA28DbV/M92O2QvswnzCmQ4bq9WwLKUoyhqFYWCltmDwkmvX7yhqiFLFMWPItIm7mi4Qyoygby6r4DKd1X2A==}+ resolution: {integrity: sha512-o6Hl76aU1jlCK7Q8DPYZ8OGsp4PtzLdzI6nGpLt8rxoE78QuB3GBGEwGAQJitp4IF7Lb2rL5oAXEl3ZP6xf9jg==}- resolution: {integrity: sha512-nfl45XtuqB5CxyIZJ+bbJ+dofzosPCRlmF+eUQo+0J23NkNXsTzur+1krJDSdhcw0SOYs4sbYRoMz1cpuOM4+Q==}+ resolution: {integrity: sha512-LFY9+sLIxRfdDI9ZTKjLoijMkIAzPLBWHpPkwv4NPYgdyx+0qFmv+puBpAUGUY9VZqAZ736Uj5NJY9zw+/M3yQ==}resolution: {integrity: sha512-yAtdBnfYOhECv9YC70H2gEiqfIbVkq09aaE4y/9V/ovEFmH9gPKaEgzIZqgT7PSPQjKhsNkb6jk6XvSoboxOBw==}- resolution: {integrity: sha512-99FUhYmg0jOJr2/K4TcEURmJRkuibrCDc8KBUX7qcQEITzrZ5R6a4QE+sarCvbb3hi8aA9GV2oyST6MQeA9mgQ==}+ resolution: {integrity: sha512-TkpklUg9yhKjnTEs3Ls0eSI2aMJ8+tRicrFAKlDyrEBNMSSEaMsSJ84Ro5xpRra+GMBkGXFYgwTPC7y3tj20Gg==}resolution: {integrity: sha512-GAqS7mkatpXcMCQKWtFu1eMUKLUymjInU0O8kXshWaQrVWjPIO2lllZ1VNhdgE0qGj4oOIRRS11kzuijLshGXQ==}@@ -8727,14 +8730,14 @@ packages:vega: '*'vega-lite: '*'- resolution: {integrity: sha512-6rXc6JdDt8MnCRy6UzUCsa6EeFycPDmvioMddLfKw38OYCV8pRQC5nw44gyddOwXgUTJLiCtn/sp53P0iA542A==}+ resolution: {integrity: sha512-hFcWPdTV844IiY0m97+WUoMLADCp+8yUQR1NStWhzBzwDDA7QEGGwYGxALhdMOaDTwkyoNj3V/nox2rQAJD/vQ==}resolution: {integrity: sha512-jMcvH2lP20UfyvO2KAEdloiwRyasikaiLuNFhzwrrzf2RamGTxP4G7B2OZ2QENfrGUH05Z9ei5tn/eErdzOaZQ==}- resolution: {integrity: sha512-bh/2Qbj85O70mjfLRgPKAsABArgSUP0k+GjmaY54zukIRxoGxKju+85nigeX/aR/INpEqNWif+5lL+NvmyWA5w==}+ resolution: {integrity: sha512-Qxo+xeEEftY1jYyKgzOGc9NuW4/MqGm1YPZ5WrL9eXg2G0410Ne+xL/MFIjHF4hRX+3mgFF4Io2hPpfy/thjLg==}resolution: {integrity: sha512-BReB2qRERA/Ke+QoxKDQ7fES25A9Q3qKRm1CJxwvpLGhAl4k5cGDORx6yW+J3rFHMzpJlmdRM+kb489EuphxZQ==}@@ -8745,20 +8748,20 @@ packages:resolution: {integrity: sha512-fTGnTG7FhtTG9tiYDL3k5s8YHqB71Ml5+aC9B7eaBygeB8GKXBrcbTXLOzoCRxT3Jr5cRhr99PMBu0AkqmhBog==}- resolution: {integrity: sha512-omNmGiZBdjm/jnHjZlywyYqafscDdHaELHx1q96n5UOz/FlO9JO99P4B3jZg391EFG8dqhWjQilSf2JH6F1mIw==}+ resolution: {integrity: sha512-nSNpZLUrRvFo46M5OK4O6x6f08WD1yOcEzHNlqivF+sDLSsVpstaF6fdJYwrbf/debFi2L9Tkp4gZQtssup9iQ==}- resolution: {integrity: sha512-z3z66aJTA3ZRo4oBY4iBXnn+A4KqBGZT/UrlKDbm+7Ec+Ip+hK2tF8Kmhp/WNcMsDZoUWFqLJgR2VgOgvJk9RA==}+ resolution: {integrity: sha512-RYlyMJu5kZV4XXjmyTQKADJWDB25SMHsiF+B1rbE1p+pmdQPlp5tGdPl9r5dUJOp3p8mSt/NGI8GPGucmPMxtw==}resolution: {integrity: sha512-ZPAAQ3iYz6YrQjJoDT+0bcxJkXt9PKF5v4OO7Omw8PFhkIv++jFXeKlQTW1bBtyQ92dkdGGHv5lYY67Djqjf3A==}- resolution: {integrity: sha512-aYYYM+3UGqwsOx+TkVtF1IZfguy0H7AN79dR8H0nONRIc+vhk/lbnlkgwY2nSzEu0EZ4b5wZxeGoDBEVmdDEcg==}+ resolution: {integrity: sha512-lWNimgJAXGeRFu2Pz8axOUqVf1moYhD+5yhBzDSmckE9I5jLOyZc/XvgFTXwFnsVkMd1QW1vxJa+y9yfUblzYw==}- resolution: {integrity: sha512-p+qXU3cb9VeWzJ/HEdax0TX2mqDJcSbrCIfo2d/EalOXGkvfSLKobsmMQ8DxPbtVp0uhnpvfCGDyMJw+AzcI2A==}+ resolution: {integrity: sha512-lFmF3u9/ozU0P+WqPjeThQfZm0PigdbXDwpIUCxczrCXKYJLYFmZuZLZR7cxtmpZ0/yuvRvAJ4g123LXbSZF8A==}resolution: {integrity: sha512-ZGoC8LdfEUV0LlXIuz7hup9jxuQYhSaWek2M7r9dEHAPbPrzSQvKXZ0BbsJbrarM100TGRpTVN/l1AFxCwDkWw==}@@ -10245,11 +10248,11 @@ snapshots:'@types/istanbul-reports': 1.1.2'@types/yargs': 13.0.12- '@joshwooding/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':+ '@joshwooding/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:magic-string: 0.27.0react-docgen-typescript: 2.2.2([email protected])optionalDependencies:typescript: 5.7.3@@ -12450,13 +12453,13 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])- '@storybook/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':+ '@storybook/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@storybook/csf-plugin': 8.5.2([email protected])browser-assert: 1.2.1storybook: 8.5.2ts-dedent: 2.2.0'@storybook/[email protected]([email protected])':dependencies:@@ -12516,11 +12519,11 @@ snapshots:react-dom: 18.3.1([email protected])storybook: 8.5.2- '@storybook/[email protected](@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':+ '@storybook/[email protected](@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:- '@joshwooding/vite-plugin-react-docgen-typescript': 0.4.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ '@joshwooding/vite-plugin-react-docgen-typescript': 0.4.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))'@rollup/pluginutils': 5.0.2- '@storybook/builder-vite': 8.5.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ '@storybook/builder-vite': 8.5.2([email protected])([email protected](@types/[email protected])([email protected])([email protected]))'@storybook/react': 8.5.2(@storybook/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])find-up: 5.0.0magic-string: 0.30.17@@ -12530,7 +12533,7 @@ snapshots:resolve: 1.22.8storybook: 8.5.2tsconfig-paths: 4.2.0optionalDependencies:'@storybook/test': 8.5.2([email protected])transitivePeerDependencies:@@ -12953,7 +12956,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.17.14+ '@types/node': 20.17.16'@types/tough-cookie': 4.0.4parse5: 7.1.2@@ -12983,7 +12986,7 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]':+ '@types/[email protected]':dependencies:undici-types: 6.19.8@@ -13244,21 +13247,21 @@ snapshots:'@connectrpc/connect': 1.4.0(@bufbuild/[email protected])'@connectrpc/connect-web': 1.4.0(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))- '@vitejs/[email protected](@swc/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))':+ '@vitejs/[email protected](@swc/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@swc/core': 1.7.39(@swc/[email protected])transitivePeerDependencies:- '@swc/helpers'- '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.26.0'@babel/plugin-transform-react-jsx-self': 7.25.9(@babel/[email protected])'@babel/plugin-transform-react-jsx-source': 7.25.9(@babel/[email protected])'@types/babel__core': 7.20.5react-refresh: 0.14.2transitivePeerDependencies:- supports-color@@ -13276,13 +13279,13 @@ snapshots:chai: 5.1.2tinyrainbow: 2.0.0- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 3.0.2estree-walker: 3.0.3magic-string: 0.30.17optionalDependencies:'@vitest/[email protected]':dependencies:@@ -15068,13 +15071,13 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])):+ [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])):dependencies:'@typescript-eslint/utils': 7.15.0([email protected])([email protected])eslint: 8.57.0optionalDependencies:'@typescript-eslint/eslint-plugin': 7.15.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- supports-color- typescript@@ -15967,7 +15970,7 @@ snapshots:dependencies:- node-fetch: 2.6.7+ node-fetch: 2.7.0whatwg-fetch: 3.6.17transitivePeerDependencies:- encoding@@ -15996,7 +15999,7 @@ snapshots:dependencies:- '@types/node': 20.17.14+ '@types/node': 20.17.16merge-stream: 2.0.0supports-color: 8.1.1@@ -16760,7 +16763,7 @@ snapshots:dependencies:whatwg-url: 5.0.0@@ -17461,10 +17464,10 @@ snapshots:dependencies:safe-buffer: 5.2.1- [email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]):dependencies:react: 18.3.1react-dnd-html5-backend: 14.1.0react-dom: 18.3.1([email protected])@@ -17581,7 +17584,7 @@ snapshots:dependencies:dnd-core: 14.0.1dependencies:'@react-dnd/invariant': 2.0.0'@react-dnd/shallowequal': 2.0.0@@ -17590,7 +17593,7 @@ snapshots:hoist-non-react-statics: 3.3.2react: 18.3.1optionalDependencies:- '@types/node': 20.17.14+ '@types/node': 20.17.16'@types/react': 18.3.12@@ -19015,19 +19018,19 @@ snapshots:dependencies:d3-array: 3.2.4- vega-dataflow: 5.7.6- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:- vega-format: 1.1.2- vega-loader: 4.5.2- vega-util: 1.17.2+ vega-format: 1.1.3+ vega-loader: 4.5.3+ vega-util: 1.17.3transitivePeerDependencies:- encoding@@ -19044,13 +19047,13 @@ snapshots:vega-tooltip: 0.33.0dependencies:d3-array: 3.2.4d3-interpolate: 3.0.1- vega-dataflow: 5.7.6- vega-scale: 7.4.1- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-scale: 7.4.2+ vega-util: 1.17.3transitivePeerDependencies:- encoding@@ -19060,74 +19063,90 @@ snapshots:dependencies:- vega-util: 1.17.2+ vega-util: 1.17.3dependencies:'@types/estree': 1.0.6- vega-util: 1.17.2+ vega-util: 1.17.3dependencies:d3-force: 3.0.0- vega-dataflow: 5.7.6- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-array: 3.2.4d3-format: 3.1.0d3-time-format: 4.1.0- vega-time: 2.1.2- vega-util: 1.17.2+ vega-time: 2.1.3+ vega-util: 1.17.3dependencies:d3-array: 3.2.4d3-color: 3.1.0d3-geo: 3.1.1- vega-dataflow: 5.7.6- vega-expression: 5.1.1- vega-scale: 7.4.1- vega-scenegraph: 4.13.0- vega-selections: 5.4.2+ vega-dataflow: 5.7.7+ vega-expression: 5.1.2+ vega-scale: 7.4.2+ vega-scenegraph: 4.13.1+ vega-selections: 5.5.0vega-statistics: 1.9.0- vega-time: 2.1.2- vega-util: 1.17.2+ vega-time: 2.1.3+ vega-util: 1.17.3transitivePeerDependencies:- encoding+ dependencies:+ d3-array: 3.2.4+ d3-color: 3.1.0+ d3-geo: 3.1.1+ vega-dataflow: 5.7.7+ vega-expression: 5.1.2+ vega-scale: 7.4.2+ vega-scenegraph: 4.13.1+ vega-selections: 5.5.0+ vega-statistics: 1.9.0+ vega-time: 2.1.3+ vega-util: 1.17.3+ transitivePeerDependencies:+ - encoding+dependencies:d3-array: 3.2.4d3-color: 3.1.0d3-geo: 3.1.1vega-canvas: 1.2.7- vega-dataflow: 5.7.6- vega-projection: 1.6.1+ vega-dataflow: 5.7.7+ vega-projection: 1.6.2vega-statistics: 1.9.0- vega-util: 1.17.2+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-hierarchy: 3.1.2- vega-dataflow: 5.7.6- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:vega-canvas: 1.2.7- vega-dataflow: 5.7.6- vega-scenegraph: 4.13.0- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-scenegraph: 4.13.1+ vega-util: 1.17.3transitivePeerDependencies:- encoding@@ -19153,79 +19172,79 @@ snapshots:tslib: 2.6.3vega: 5.30.0vega-event-selector: 3.0.1- vega-expression: 5.1.1- vega-util: 1.17.2+ vega-expression: 5.1.2+ vega-util: 1.17.3yargs: 17.7.2dependencies:d3-dsv: 3.0.1- node-fetch: 2.6.7+ node-fetch: 2.7.0topojson-client: 3.1.0- vega-format: 1.1.2- vega-util: 1.17.2+ vega-format: 1.1.3+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:- vega-dataflow: 5.7.6+ vega-dataflow: 5.7.7vega-event-selector: 3.0.1- vega-functions: 5.15.0- vega-scale: 7.4.1- vega-util: 1.17.2+ vega-functions: 5.16.0+ vega-scale: 7.4.2+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-geo: 3.1.1d3-geo-projection: 4.0.0- vega-scale: 7.4.1+ vega-scale: 7.4.2dependencies:d3-array: 3.2.4- vega-dataflow: 5.7.6+ vega-dataflow: 5.7.7vega-statistics: 1.9.0- vega-util: 1.17.2+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:- vega-dataflow: 5.7.6- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-array: 3.2.4d3-interpolate: 3.0.1d3-scale: 4.0.2d3-scale-chromatic: 3.1.0- vega-time: 2.1.2- vega-util: 1.17.2+ vega-time: 2.1.3+ vega-util: 1.17.3dependencies:d3-path: 3.1.0d3-shape: 3.2.0vega-canvas: 1.2.7- vega-loader: 4.5.2- vega-scale: 7.4.1- vega-util: 1.17.2+ vega-loader: 4.5.3+ vega-scale: 7.4.2+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-array: 3.2.4- vega-expression: 5.1.1- vega-util: 1.17.2+ vega-expression: 5.1.2+ vega-util: 1.17.3dependencies:@@ -19236,46 +19255,46 @@ snapshots:vega: 5.30.0vega-lite: 5.21.0([email protected])dependencies:d3-array: 3.2.4d3-time: 3.1.0- vega-util: 1.17.2+ vega-util: 1.17.3dependencies:- vega-util: 1.17.2+ vega-util: 1.17.3dependencies:d3-array: 3.2.4- vega-dataflow: 5.7.6+ vega-dataflow: 5.7.7vega-statistics: 1.9.0- vega-time: 2.1.2- vega-util: 1.17.2+ vega-time: 2.1.3+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:- vega-util: 1.17.2+ vega-util: 1.17.3dependencies:'@types/geojson': 7946.0.4vega-event-selector: 3.0.1- vega-expression: 5.1.1- vega-util: 1.17.2+ vega-expression: 5.1.2+ vega-util: 1.17.3- [email protected]: {}+ [email protected]: {}dependencies:- vega-dataflow: 5.7.6- vega-scenegraph: 4.13.0- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-scenegraph: 4.13.1+ vega-util: 1.17.3transitivePeerDependencies:- encoding@@ -19283,62 +19302,62 @@ snapshots:dependencies:d3-array: 3.2.4d3-timer: 3.0.1- vega-dataflow: 5.7.6- vega-format: 1.1.2- vega-functions: 5.15.0- vega-runtime: 6.2.0- vega-scenegraph: 4.13.0- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-format: 1.1.3+ vega-functions: 5.16.0+ vega-runtime: 6.2.1+ vega-scenegraph: 4.13.1+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:d3-delaunay: 6.0.4- vega-dataflow: 5.7.6- vega-util: 1.17.2+ vega-dataflow: 5.7.7+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:vega-canvas: 1.2.7- vega-dataflow: 5.7.6- vega-scale: 7.4.1+ vega-dataflow: 5.7.7+ vega-scale: 7.4.2vega-statistics: 1.9.0- vega-util: 1.17.2+ vega-util: 1.17.3transitivePeerDependencies:- encodingdependencies:- vega-crossfilter: 4.1.2- vega-dataflow: 5.7.6- vega-encode: 4.10.1+ vega-crossfilter: 4.1.3+ vega-dataflow: 5.7.7+ vega-encode: 4.10.2vega-event-selector: 3.0.1- vega-expression: 5.1.1- vega-force: 4.2.1- vega-format: 1.1.2+ vega-expression: 5.1.2+ vega-force: 4.2.2+ vega-format: 1.1.3vega-functions: 5.15.0- vega-geo: 4.4.2- vega-hierarchy: 4.1.2- vega-label: 1.3.0- vega-loader: 4.5.2- vega-parser: 6.4.0- vega-projection: 1.6.1- vega-regression: 1.3.0- vega-runtime: 6.2.0- vega-scale: 7.4.1- vega-scenegraph: 4.13.0+ vega-geo: 4.4.3+ vega-hierarchy: 4.1.3+ vega-label: 1.3.1+ vega-loader: 4.5.3+ vega-parser: 6.4.1+ vega-projection: 1.6.2+ vega-regression: 1.3.1+ vega-runtime: 6.2.1+ vega-scale: 7.4.2+ vega-scenegraph: 4.13.1vega-statistics: 1.9.0- vega-time: 2.1.2- vega-transforms: 4.12.0+ vega-time: 2.1.3+ vega-transforms: 4.12.1vega-typings: 1.3.1- vega-util: 1.17.2+ vega-util: 1.17.3vega-view: 5.13.0- vega-view-transforms: 4.6.0- vega-voronoi: 4.2.3- vega-wordcloud: 4.1.5+ vega-view-transforms: 4.6.1+ vega-voronoi: 4.2.4+ vega-wordcloud: 4.1.6transitivePeerDependencies:- encoding@@ -19358,13 +19377,13 @@ snapshots:'@types/unist': 3.0.3vfile-message: 4.0.2dependencies:cac: 6.7.14debug: 4.4.0es-module-lexer: 1.6.0pathe: 2.0.2transitivePeerDependencies:- '@types/node'- less@@ -19376,32 +19395,32 @@ snapshots:- supports-color- terser- [email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])):+ [email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])):dependencies:debug: 4.4.0globrex: 0.1.2tsconfck: 3.0.3([email protected])optionalDependencies:transitivePeerDependencies:- supports-color- typescriptdependencies:esbuild: 0.21.5postcss: 8.5.1rollup: 4.31.0optionalDependencies:- '@types/node': 20.17.14+ '@types/node': 20.17.16fsevents: 2.3.3less: 4.2.0terser: 5.37.0- [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 3.0.2- '@vitest/mocker': 3.0.2([email protected](@types/[email protected])([email protected])([email protected]))+ '@vitest/mocker': 3.0.2([email protected](@types/[email protected])([email protected])([email protected]))'@vitest/pretty-format': 3.0.2'@vitest/runner': 3.0.2'@vitest/snapshot': 3.0.2@@ -19417,11 +19436,11 @@ snapshots:tinyexec: 0.3.2tinypool: 1.0.2tinyrainbow: 2.0.0why-is-node-running: 2.3.0optionalDependencies:- '@types/node': 20.17.14+ '@types/node': 20.17.16jsdom: 24.1.1transitivePeerDependencies:- lessdiff --git a/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts b/frontend/src/__tests__/components/editor/cell/CellStatus.test.tsindex ce4740f93e..d3b5c5f801 100644--- a/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts+++ b/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts@@ -1,3 +1,4 @@+/* Copyright 2024 Marimo. All rights reserved. */import { formatElapsedTime } from "../../../../components/editor/cell/CellStatus";import { describe, expect, test } from "vitest";diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex c81f7d5e91..483ef3ec98 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1089,24 +1089,21 @@ export const UserConfigForm: React.FC = () => {/><FormFieldcontrol={form.control}- name="experimental.tracing"+ name="experimental.sql_engines"render={({ field }) => (<div className="flex flex-col gap-y-1"><FormItem className={formItemClasses}>- <FormLabel className="font-normal">- Tracing sidebar- </FormLabel>+ <FormLabel className="font-normal">SQL Engine</FormLabel><FormControl><Checkbox- data-testid="tracing-sidebar-checkbox"+ data-testid="sqlengine-sidebar-checkbox"checked={field.value === true}onCheckedChange={field.onChange}/></FormControl></FormItem><FormDescription>- Enable experimental tracing sidebar to debug cell execution- times and dependencies.+ Define your own engine and use it in an SQL cell.</FormDescription></div>)}diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsxindex 77067c2823..b070d8fb59 100644--- a/frontend/src/components/editor/cell/CreateCellButton.tsx+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx@@ -88,7 +88,7 @@ const CreateCellButtonContextMenu = (props: {key="sql"onSelect={(evt) => {evt.stopPropagation();- onClick({ code: new SQLLanguageAdapter().defaultCode });+ onClick({ code: new SQLLanguageAdapter().getDefaultCode() });}}><div className="mr-3 text-muted-foreground">diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsxindex 7454e81c2a..c416a800eb 100644--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx@@ -112,6 +112,10 @@ export const DataSourcesPanel: React.FC = () => {case "duckdb":code = `_df = mo.sql(f"SELECT * FROM ${table.name} LIMIT 100")`;break;+ case "connection":+ // TODO: Handle connection source+ code = `_df = mo.sql("SELECT 1", engine=${table.source_type})`;+ break;default:logNever(table.source_type);break;diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 99ac8e05d0..075d4efacd 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -335,7 +335,7 @@ const AddCellButtons: React.FC<{createNewCell({cellId: { type: "__end__", columnId },before: false,- code: new SQLLanguageAdapter().defaultCode,+ code: new SQLLanguageAdapter().getDefaultCode(),});}}>diff --git a/frontend/src/core/cells/__tests__/data-source.test.ts b/frontend/src/core/cells/__tests__/data-source.test.tsnew file mode 100644index 0000000000..492c1d2b3a--- /dev/null+++ b/frontend/src/core/cells/__tests__/data-source.test.ts@@ -0,0 +1,192 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { expect, it, describe, beforeEach } from "vitest";+import {+ type ConnectionName,+ type DataSourceConnection,+ type DataSourceState,+ exportedForTesting,+} from "../data-source-connections";+import { DEFAULT_ENGINE } from "@/core/codemirror/language/sql";+import type { VariableName } from "@/core/variables/types";++const { reducer, initialState } = exportedForTesting;++// Helper function to add connections+function addConnection(+ connections: DataSourceConnection[],+ state: DataSourceState,+): DataSourceState {+ return reducer(state, {+ type: "addDataSourceConnection",+ payload: {+ connections: connections,+ },+ });+}++describe("data source connections", () => {+ let state: DataSourceState;++ beforeEach(() => {+ state = initialState();+ });++ it("starts with empty connections map", () => {+ expect(initialState().connectionsMap.size).toBe(1);+ });++ it("can add new connections", () => {+ const newConnections = [+ {+ name: "conn1" as ConnectionName,+ source: "sqlite",+ display_name: "SQLite DB",+ dialect: "sqlite",+ },+ ];++ const newState = addConnection(newConnections, state);+ expect(newState.connectionsMap.size).toBe(2);+ expect(newState.connectionsMap.get("conn1" as ConnectionName)).toEqual(+ newConnections[0],+ );+ });++ it("updates existing connections", () => {+ const connection = {+ name: "conn1" as ConnectionName,+ source: "sqlite",+ display_name: "SQLite DB",+ dialect: "sqlite",+ };++ const updatedConnection = {+ ...connection,+ display_name: "Updated SQLite",+ };++ let newState = addConnection([connection], state);+ newState = addConnection([updatedConnection], state);++ expect(newState.connectionsMap.size).toBe(2);+ expect(newState.connectionsMap.get("conn1" as ConnectionName)).toEqual(+ updatedConnection,+ );+ });++ it("can remove connections", () => {+ const connections = [+ {+ name: "conn1" as ConnectionName,+ source: "sqlite",+ display_name: "SQLite DB",+ dialect: "sqlite",+ },+ {+ name: "conn2" as ConnectionName,+ source: "postgres",+ dialect: "postgres",+ display_name: "Postgres DB",+ },+ ];++ let newState = addConnection(connections, state);+ expect(newState.connectionsMap.size).toBe(3);++ newState = reducer(newState, {+ type: "removeDataSourceConnection",+ payload: "conn1" as ConnectionName,+ });+ expect(newState.connectionsMap.size).toBe(2);+ expect(newState.connectionsMap.has("conn2" as ConnectionName)).toBe(true);+ });++ it("can clear all connections", () => {+ const connections = [+ {+ name: "conn1" as ConnectionName,+ source: "sqlite",+ display_name: "SQLite DB",+ dialect: "sqlite",+ },+ {+ name: "conn2" as ConnectionName,+ source: "postgres",+ display_name: "Postgres DB",+ dialect: "postgres",+ },+ ];++ let newState = addConnection(connections, state);+ expect(newState.connectionsMap.size).toBe(3);++ newState = reducer(newState, {+ type: "clearDataSourceConnections",+ payload: {},+ });+ expect(newState.connectionsMap.size).toBe(0);+ });+});++describe("filtering data sources", () => {+ // helper function to filter data sources by variable names+ function filterDataSources(payload: VariableName[]) {+ return reducer(baseState, {+ type: "filterDataSourcesFromVariables",+ payload: payload,+ });+ }++ const connections = [+ {+ name: "conn1" as ConnectionName,+ source: "sqlite",+ display_name: "SQLite DB",+ dialect: "sqlite",+ },+ {+ name: "conn2" as ConnectionName,+ source: "postgres",+ display_name: "Postgres DB",+ dialect: "postgres",+ },+ ];++ let baseState: DataSourceState;++ beforeEach(() => {+ baseState = addConnection(connections, baseState);+ expect(baseState.connectionsMap.size).toBe(3); // 2 + 1 (default) connections+ });++ it("keeps only DEFAULT_ENGINE when no variables", () => {+ const filtered = filterDataSources([]);+ expect(filtered.connectionsMap.size).toBe(1);+ expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);+ });++ it("keeps matching variables and DEFAULT_ENGINE", () => {+ const filtered = filterDataSources(["conn1" as unknown as VariableName]);+ expect(filtered.connectionsMap.size).toBe(2);+ expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);+ expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);+ });++ it("filters out non-matching variables", () => {+ const filtered = filterDataSources([+ "non_existent" as unknown as VariableName,+ ]);+ expect(filtered.connectionsMap.size).toBe(1);+ expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);+ });++ it("handles mix of matching and non-matching variables", () => {+ const filtered = filterDataSources([+ "conn1" as unknown as VariableName,+ "non_existent" as unknown as VariableName,+ ]);+ expect(filtered.connectionsMap.size).toBe(2);+ expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);+ expect(filtered.connectionsMap.has(DEFAULT_ENGINE)).toBe(true);+ });+});diff --git a/frontend/src/core/cells/__tests__/runs.test.ts b/frontend/src/core/cells/__tests__/runs.test.tsindex e5145d5e9f..319c9d0996 100644--- a/frontend/src/core/cells/__tests__/runs.test.ts+++ b/frontend/src/core/cells/__tests__/runs.test.ts@@ -13,7 +13,7 @@ import { invariant } from "@/utils/invariant";const { reducer, initialState, isPureMarkdown } = exportedForTesting;-function first<T>(map: Map<string, T> | undefined): T {+function first<T>(map: ReadonlyMap<string, T> | undefined): T {invariant(map, "Map is undefined");return map.values().next().value as T;}diff --git a/frontend/src/core/cells/data-source-connections.ts b/frontend/src/core/cells/data-source-connections.tsnew file mode 100644index 0000000000..6f3a545470--- /dev/null+++ b/frontend/src/core/cells/data-source-connections.ts@@ -0,0 +1,98 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { createReducerAndAtoms } from "@/utils/createReducer";+import type { TypedString } from "@/utils/typed";+import { DEFAULT_ENGINE } from "../codemirror/language/sql";+import type { VariableName } from "../variables/types";+import { atom } from "jotai";++export type ConnectionName = TypedString<"ConnectionName">;++export interface DataSourceConnection {+ name: ConnectionName;+ source: string;+ display_name: string;+ dialect: string;+}++export interface DataSourceState {+ connectionsMap: ReadonlyMap<ConnectionName, DataSourceConnection>;+}++function initialState(): DataSourceState {+ return {+ connectionsMap: new Map().set(DEFAULT_ENGINE, {+ name: DEFAULT_ENGINE,+ source: "duckdb",+ dialect: "duckdb",+ display_name: "DuckDB In-Memory",+ }),+ };+}++const {+ reducer,+ createActions,+ valueAtom: dataSourceConnectionsAtom,+ useActions: useDataSourceActions,+} = createReducerAndAtoms(initialState, {+ addDataSourceConnection: (+ state: DataSourceState,+ opts: { connections: DataSourceConnection[] },+ ): DataSourceState => {+ if (opts.connections.length === 0) {+ return state;+ }++ // update existing connections with latest values+ // add new ones if they don't exist+ // Backend will dedupe by connection name & keep the latest, so we use this as the key+ const newMap = new Map(state.connectionsMap);+ for (const conn of opts.connections) {+ newMap.set(conn.name, conn);+ }++ return { connectionsMap: newMap };+ },++ // Keep default engine and any connections that are used by variables+ filterDataSourcesFromVariables: (+ state: DataSourceState,+ variableNames: VariableName[],+ ) => {+ const names = new Set(variableNames);+ const newMap = new Map(+ [...state.connectionsMap].filter(([name]) => {+ if (name === DEFAULT_ENGINE) {+ return true;+ }+ return names.has(name as unknown as VariableName);+ }),+ );+ return { connectionsMap: newMap };+ },++ clearDataSourceConnections: (): DataSourceState => ({+ connectionsMap: new Map(),+ }),++ removeDataSourceConnection: (+ state: DataSourceState,+ connectionName: ConnectionName,+ ): DataSourceState => {+ const newMap = new Map(state.connectionsMap);+ newMap.delete(connectionName);+ return { connectionsMap: newMap };+ },+});++export { dataSourceConnectionsAtom, useDataSourceActions };++export const dataConnectionsMapAtom = atom(+ (get) => get(dataSourceConnectionsAtom).connectionsMap,+);++export const exportedForTesting = {+ reducer,+ createActions,+ initialState,+};diff --git a/frontend/src/core/cells/runs.ts b/frontend/src/core/cells/runs.tsindex 73611c3e96..2d67f4267f 100644--- a/frontend/src/core/cells/runs.ts+++ b/frontend/src/core/cells/runs.ts@@ -15,13 +15,13 @@ export interface CellRun {export interface Run {runId: RunId;- cellRuns: Map<CellId, CellRun>;+ cellRuns: ReadonlyMap<CellId, CellRun>;runStartTime: number;}export interface RunsState {runIds: RunId[];- runMap: Map<RunId, Run>;+ runMap: ReadonlyMap<RunId, Run>;}function initialState(): RunsState {diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.tsindex 86a1b37bc8..e65266adbe 100644--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts@@ -1,8 +1,13 @@/* Copyright 2024 Marimo. All rights reserved. */-import { expect, describe, it, beforeAll } from "vitest";-import { SQLLanguageAdapter } from "../sql";+import { expect, describe, it, beforeAll, afterAll, afterEach } from "vitest";+import {+ DEFAULT_ENGINE,+ latestEngineSelected,+ SQLLanguageAdapter,+} from "../sql";import { store } from "@/core/state/jotai";import { capabilitiesAtom } from "@/core/config/capabilities";+import type { ConnectionName } from "@/core/cells/data-source-connections";const adapter = new SQLLanguageAdapter();@@ -15,6 +20,11 @@ describe("SQLLanguageAdapter", () => {});describe("transformIn", () => {+ afterAll(() => {+ adapter.engine = DEFAULT_ENGINE;+ adapter.showOutput = true;+ });+it("empty", () => {const [innerCode, offset] = adapter.transformIn("");expect(innerCode).toBe("");@@ -66,7 +76,7 @@ describe("SQLLanguageAdapter", () => {const pythonCode = 'next_df = mo.sql("")';const [innerCode, offset] = adapter.transformIn(pythonCode);expect(innerCode).toBe("");- expect(offset).toBe(0);+ expect(offset).toBe(18);});it("simple sql", () => {@@ -105,6 +115,12 @@ describe("SQLLanguageAdapter", () => {expect(innerCode).toBe("SELECT * FROM table");expect(adapter.showOutput).toBe(false);expect(offset).toBe(16);++ // handle trailing comma+ const pythonCode2 =+ '_df = mo.sql("""SELECT * FROM table""", output=False,)';+ const [innerCode2] = adapter.transformIn(pythonCode2);+ expect(innerCode2).toBe("SELECT * FROM table");});it("should default to showing output when flag is not specified", () => {@@ -112,9 +128,128 @@ describe("SQLLanguageAdapter", () => {adapter.transformIn(pythonCode);expect(adapter.showOutput).toBe(true);});++ it("should handle engine param when provided", () => {+ const pythonCode =+ '_df = mo.sql("""SELECT * FROM table""", engine=postgres_engine)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("SELECT * FROM table");+ expect(offset).toBe(16);+ expect(adapter.engine).toBe("postgres_engine");++ // handle trailing comma+ const pythonCode2 =+ '_df = mo.sql("""SELECT * FROM table""", engine=postgres_engine,)';+ const [innerCode2] = adapter.transformIn(pythonCode2);+ expect(innerCode2).toBe("SELECT * FROM table");+ });++ it("should handle engine param with output flag", () => {+ const pythonCode =+ '_df = mo.sql("""SELECT * FROM table""", output=False, engine=postgres_engine)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("SELECT * FROM table");+ expect(offset).toBe(16);+ expect(adapter.showOutput).toBe(false);+ expect(adapter.engine).toBe("postgres_engine");+ });++ it("should handle reversed order of params", () => {+ const pythonCode =+ '_df = mo.sql("""SELECT * FROM table""", engine=postgres_engine, output=False)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("SELECT * FROM table");+ expect(offset).toBe(16);+ expect(adapter.showOutput).toBe(false);+ expect(adapter.engine).toBe("postgres_engine");+ });++ it("should handle parametrized sql", () => {+ const pythonCode = `+_df = mo.sql(+ f"""+ SELECT name, price, category+ FROM products+ WHERE price < {price_threshold.value}+ ORDER BY price DESC+ """,+ engine=sqlite,+)+`;+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe(+ `+SELECT name, price, category+FROM products+WHERE price < {price_threshold.value}+ORDER BY price DESC+ `.trim(),+ );+ expect(offset).toBe(22);+ expect(adapter.showOutput).toBe(true);+ expect(adapter.engine).toBe("sqlite");+ });++ it("should handle parametrized sql with triple single quotes f-string", () => {+ const pythonCode = `+_df = mo.sql(+ f'''+ SELECT name, price, category+ FROM products+ WHERE price < {price_threshold.value}+ ORDER BY price DESC+ ''',+ engine=sqlite,+)+`;+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe(+ `+SELECT name, price, category+FROM products+WHERE price < {price_threshold.value}+ORDER BY price DESC+ `.trim(),+ );+ expect(offset).toBe(22);+ });++ it("should handle parametrized sql with inline double quotes f-string", () => {+ const pythonCode = `+_df = mo.sql(+ f"FROM products WHERE price < {price_threshold.value}",+ engine=sqlite,+)+`;+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe(+ "FROM products WHERE price < {price_threshold.value}",+ );+ expect(offset).toBe(20);+ });++ it("should handle parametrized sql with inline single quotes f-string", () => {+ const pythonCode = `+_df = mo.sql(+ f"FROM products WHERE price < {price_threshold.value}",+ engine=sqlite,+)+`;+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe(+ "FROM products WHERE price < {price_threshold.value}",+ );+ expect(offset).toBe(20);+ });});describe("transformOut", () => {+ afterEach(() => {+ adapter.engine = DEFAULT_ENGINE;+ adapter.showOutput = true;+ adapter.dataframeName = "_df";+ });+it("should wrap SQL code with triple double-quoted string format", () => {const code = "SELECT * FROM {df}";adapter.lastQuotePrefix = "";@@ -141,7 +276,7 @@ describe("SQLLanguageAdapter", () => {f"""SELECT * FROM table""",- output=False,+ output=False)"`);expect(offset).toBe(26);@@ -162,6 +297,38 @@ describe("SQLLanguageAdapter", () => {`);expect(offset).toBe(26);});++ it("should add engine connection when provided", () => {+ const code = "SELECT * FROM table";+ adapter.engine = "postgres_engine" as ConnectionName;+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toMatchInlineSnapshot(`+ "_df = mo.sql(+ f"""+ SELECT * FROM table+ """,+ engine=postgres_engine+ )"+ `);+ expect(offset).toBe(24);+ });++ it("should add engine connection and output flag when provided", () => {+ const code = "SELECT * FROM table";+ adapter.showOutput = false;+ adapter.engine = "postgres_engine" as ConnectionName;+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toMatchInlineSnapshot(`+ "_df = mo.sql(+ f"""+ SELECT * FROM table+ """,+ output=False,+ engine=postgres_engine+ )"+ `);+ expect(offset).toBe(24);+ });});describe("isSupported", () => {@@ -239,4 +406,91 @@ describe("SQLLanguageAdapter", () => {).toBe(true);});});++ describe("latestEngineSelected", () => {+ afterEach(() => {+ adapter.engine = DEFAULT_ENGINE;+ });++ it("should use default engine initially", () => {+ expect(adapter.engine).toBe(DEFAULT_ENGINE);+ });++ it("should persist the selected engine", () => {+ const engine = "postgres_engine" as ConnectionName;+ adapter.selectEngine(engine);+ expect(adapter.engine).toBe(engine);+ expect(store.get(latestEngineSelected)).toBe(engine);+ });++ it("should allow switching between engines", () => {+ const engine1 = "postgres_engine" as ConnectionName;+ const engine2 = "mysql_engine" as ConnectionName;++ adapter.selectEngine(engine1);+ expect(adapter.engine).toBe(engine1);+ expect(store.get(latestEngineSelected)).toBe(engine1);++ adapter.selectEngine(engine2);+ expect(adapter.engine).toBe(engine2);+ expect(store.get(latestEngineSelected)).toBe(engine2);+ });++ it("should update engine in transformIn when specified", () => {+ const pythonCode = '_df = mo.sql("""SELECT 1""", engine=postgres_engine)';+ adapter.transformIn(pythonCode);+ expect(adapter.engine).toBe("postgres_engine");+ expect(store.get(latestEngineSelected)).toBe("postgres_engine");+ });++ it("should maintain engine selection across transformIn/transformOut", () => {+ const engine = "postgres_engine" as ConnectionName;+ adapter.selectEngine(engine);++ const [innerCode] = adapter.transformIn(+ `_df = mo.sql("""SELECT 1""", engine=${engine})`,+ );+ expect(adapter.engine).toBe(engine);++ const [outCode] = adapter.transformOut(innerCode);+ expect(outCode).toContain(`engine=${engine}`);+ });++ it("should maintain engine when transforming empty string", () => {+ const engine = "postgres_engine" as ConnectionName;+ adapter.selectEngine(engine);++ const [innerCode] = adapter.transformIn("");+ expect(adapter.engine).toBe(engine);++ const [outCode] = adapter.transformOut(innerCode);+ expect(outCode).toContain(`engine=${engine}`);+ });++ it("should restore previous engine when selecting default", () => {+ const engine = "postgres_engine" as ConnectionName;+ adapter.selectEngine(engine);+ adapter.selectEngine(DEFAULT_ENGINE);++ expect(adapter.engine).toBe(DEFAULT_ENGINE);+ expect(store.get(latestEngineSelected)).toBe(DEFAULT_ENGINE);+ });+ });++ describe("getDefaultCode", () => {+ it("should include engine in getDefaultCode when selected", () => {+ const engine = "postgres_engine" as ConnectionName;+ adapter.selectEngine(engine);+ expect(adapter.getDefaultCode()).toBe(+ `_df = mo.sql(f"""SELECT * FROM """, engine=${engine})`,+ );+ });++ it("should not include engine in getDefaultCode when using default engine", () => {+ adapter.selectEngine(DEFAULT_ENGINE);+ expect(adapter.getDefaultCode()).toBe(+ `_df = mo.sql(f"""SELECT * FROM """)`,+ );+ });+ });});diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsxindex 01859def1b..d72f52fbf1 100644--- a/frontend/src/core/codemirror/language/panel.tsx+++ b/frontend/src/core/codemirror/language/panel.tsx@@ -4,60 +4,73 @@ import { languageAdapterState } from "./extension";import { SQLLanguageAdapter } from "./sql";import { normalizeName } from "@/core/cells/names";import { useAutoGrowInputProps } from "@/hooks/useAutoGrowInputProps";+import { getFeatureFlag } from "@/core/config/feature-flag";+import {+ type ConnectionName,+ dataConnectionsMapAtom,+} from "@/core/cells/data-source-connections";+import { useAtomValue } from "jotai";+import { CircleHelpIcon } from "lucide-react";+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";+import { useState } from "react";export const LanguagePanelComponent: React.FC<{view: EditorView;}> = ({ view }) => {const languageAdapter = view.state.field(languageAdapterState);const { spanProps, inputProps } = useAutoGrowInputProps({ minWidth: 50 });+let actions: React.ReactNode = <div />;let showDivider = false;+ // Send noop update code event, which will trigger an update to the new output variable name+ const triggerUpdate = () => {+ view.dispatch({+ changes: {+ from: 0,+ to: view.state.doc.length,+ insert: view.state.doc.toString(),+ },+ });+ };+if (languageAdapter instanceof SQLLanguageAdapter) {showDivider = true;actions = (- <div className="flex flex-1 gap-2 relative items-center justify-between">+ <div className="flex flex-1 gap-2 relative items-center"><label className="flex gap-2 items-center"><span className="select-none">Output variable: </span><input{...inputProps}defaultValue={languageAdapter.dataframeName}onChange={(e) => {- languageAdapter.dataframeName = e.target.value;+ languageAdapter.setDataframeName(e.target.value);inputProps.onChange?.(e);}}onBlur={(e) => {// Normalize the name to a valid variable nameconst name = normalizeName(e.target.value, false);- languageAdapter.dataframeName = name;+ languageAdapter.setDataframeName(name);e.target.value = name;- // Send noop update code event, which will trigger an update to the new output variable name- view.dispatch({- changes: {- from: 0,- to: view.state.doc.length,- insert: view.state.doc.toString(),- },- });+ triggerUpdate();}}className="min-w-14 w-auto border border-border rounded px-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"/><span {...spanProps} /></label>- <label className="flex items-center gap-2">+ {getFeatureFlag("sql_engines") && (+ <SQLEngineSelect+ languageAdapter={languageAdapter}+ onChange={triggerUpdate}+ />+ )}+ <label className="flex items-center gap-2 ml-auto"><inputtype="checkbox"onChange={(e) => {- languageAdapter.showOutput = !e.target.checked;- // Trigger an update to reflect the change- view.dispatch({- changes: {- from: 0,- to: view.state.doc.length,- insert: view.state.doc.toString(),- },- });+ languageAdapter.setShowOutput(!e.target.checked);+ triggerUpdate();}}checked={!languageAdapter.showOutput}/>@@ -75,3 +88,55 @@ export const LanguagePanelComponent: React.FC<{</div>);};++const SQLEngineSelect: React.FC<{+ languageAdapter: SQLLanguageAdapter;+ onChange: (engine: ConnectionName) => void;+}> = ({ languageAdapter, onChange }) => {+ // use local state as languageAdapter may not trigger an update+ const [selectedEngine, setSelectedEngine] = useState(languageAdapter.engine);+ const connectionsMap = useAtomValue(dataConnectionsMapAtom);++ return (+ <div className="flex flex-row gap-1 items-center">+ <select+ id="sql-engine"+ name="sql-engine"+ className="border border-border rounded px-0.5 focus-visible:outline-none focus-visible:ring-1"+ value={selectedEngine}+ onChange={(e) => {+ const nextEngine = e.target.value as ConnectionName;+ languageAdapter.selectEngine(nextEngine);+ setSelectedEngine(nextEngine);+ onChange(nextEngine);+ }}+ >+ {/* Fallback option if an existing option is deleted,+ let's users intentionally switch to default if needed */}+ <option value="None">Choose an option</option>+ {[...connectionsMap.entries()].map(([key, value]) => (+ <option key={key} value={value.name}>+ {value.display_name}+ </option>+ ))}+ </select>+ <TooltipProvider>+ <Tooltip+ content="Find out how to add an SQL engine"+ delayDuration={200}+ >+ <a+ href="http://docs.marimo.io/guides/working_with_data/sql/#connecting-to-a-custom-database"+ target="_blank"+ rel="noreferrer"+ >+ <CircleHelpIcon+ size={13}+ className="text-[var(--sky-11)] opacity-60 hover:opacity-100"+ />+ </a>+ </Tooltip>+ </TooltipProvider>+ </div>+ );+};diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsindex a00b4d624e..270fef733a 100644--- a/frontend/src/core/codemirror/language/sql.ts+++ b/frontend/src/core/codemirror/language/sql.ts@@ -12,39 +12,21 @@ import {} from "@codemirror/autocomplete";import { store } from "@/core/state/jotai";import { datasetsAtom } from "@/core/datasets/state";-import {- QUOTE_PREFIX_KINDS,- type QuotePrefixKind,- splitQuotePrefix,- upgradePrefixKind,-} from "./utils/quotes";+import { type QuotePrefixKind, upgradePrefixKind } from "./utils/quotes";import { capabilitiesAtom } from "@/core/config/capabilities";import { MarkdownLanguageAdapter } from "./markdown";+import type { ConnectionName } from "@/core/cells/data-source-connections";+import { atom } from "jotai";+import { parser } from "@lezer/python";+import type { SyntaxNode, TreeCursor } from "@lezer/common";+import { parseArgsKwargs } from "./utils/ast";+import { Logger } from "@/utils/Logger";++// Default engine to use when not specified, shouldn't conflict with user_defined engines+export const DEFAULT_ENGINE: ConnectionName =+ "_marimo_duckdb" as ConnectionName;-const quoteKinds = [- ['"""', '"""'],- ["'''", "'''"],- ["'", "'"],- ['"', '"'],-];--// explode into all combinations-// only f is supported-const pairs = QUOTE_PREFIX_KINDS.flatMap((prefix) =>- quoteKinds.map(([start, end]) => [prefix + start, end]),-);--const regexes = pairs.map(- ([start, end]) =>- // df = mo.sql( space + start + capture + space + end, optional output flag)- [- start,- new RegExp(- `^(?<dataframe>\\w*)\\s*=\\s*mo\\.sql\\(\\s*${start}(?<sql>.*)${end}\\s*(?:,\\s*output\\s*=\\s*(?<output>True|False),?)?\\s*\\)$`,- "s",- ),- ] as const,-);+export const latestEngineSelected = atom<ConnectionName>(DEFAULT_ENGINE);/*** Language adapter for SQL.@@ -57,8 +39,18 @@ export class SQLLanguageAdapter implements LanguageAdapter {dataframeName = "_df";lastQuotePrefix: QuotePrefixKind = "f";showOutput = true;+ engine: ConnectionName = store.get(latestEngineSelected);++ getDefaultCode(): string {+ if (this.engine === DEFAULT_ENGINE) {+ return this.defaultCode;+ }+ return `_df = mo.sql(f"""SELECT * FROM """, engine=${this.engine})`;+ }- transformIn(pythonCode: string): [string, number] {+ transformIn(+ pythonCode: string,+ ): [sqlQuery: string, queryStartOffset: number] {if (!this.isSupported(pythonCode)) {// Attempt to remove any markdown wrappersconst [transformedCode, offset] =@@ -76,24 +68,22 @@ export class SQLLanguageAdapter implements LanguageAdapter {return ["", 0];}- for (const [start, regex] of regexes) {- const match = pythonCode.match(regex);- if (match) {- const dataframe = match.groups?.dataframe || this.dataframeName;- const innerCode = match.groups?.sql || "";- const output = match.groups?.output;+ const sqlStatement = parseSQLStatement(pythonCode);+ if (sqlStatement) {+ this.dataframeName = sqlStatement.dfName;+ this.showOutput = sqlStatement.output ?? true;+ this.engine = (sqlStatement.engine as ConnectionName) ?? DEFAULT_ENGINE;- const [quotePrefix, quoteType] = splitQuotePrefix(start);- // store the quote prefix for later when we transform out- this.lastQuotePrefix = quotePrefix;- this.dataframeName = dataframe;- this.showOutput = output === undefined ? true : output === "True";- const unescapedCode = innerCode.replaceAll(`\\${quoteType}`, quoteType);-- const offset = pythonCode.indexOf(innerCode);- // string-dedent expects the first and last line to be empty / contain only whitespace, so we pad with \n- return [dedent(`\n${unescapedCode}\n`).trim(), offset];+ if (this.engine !== DEFAULT_ENGINE) {+ // User selected a new engine, set it as latest.+ // This makes new SQL statements use the new engine by default.+ store.set(latestEngineSelected, this.engine);}++ return [+ dedent(`\n${sqlStatement.sqlString}\n`).trim(),+ sqlStatement.startPosition,+ ];}return [pythonCode, 0];@@ -106,7 +96,12 @@ export class SQLLanguageAdapter implements LanguageAdapter {// Multiline codeconst start = `${this.dataframeName} = mo.sql(\n ${prefix}"""\n`;const escapedCode = code.replaceAll('"""', String.raw`\"""`);- const end = `\n """${this.showOutput ? "" : ",\n output=False,"}\n)`;++ const showOutputParam = this.showOutput ? "" : ",\n output=False";+ const engineParam =+ this.engine === DEFAULT_ENGINE ? "" : `,\n engine=${this.engine}`;+ const end = `\n """${showOutputParam}${engineParam}\n)`;+return [start + indentOneTab(escapedCode) + end, start.length + 1];}@@ -120,12 +115,30 @@ export class SQLLanguageAdapter implements LanguageAdapter {return true;}- // not 2 mo.sql calls+ // Does not have 2 `mo.sql` callsif (pythonCode.split("mo.sql").length > 2) {return false;}- return regexes.some(([, regex]) => regex.test(pythonCode));+ // Has at least one `mo.sql` call+ if (!pythonCode.includes("mo.sql")) {+ return false;+ }++ return parseSQLStatement(pythonCode) !== null;+ }++ selectEngine(connectionName: ConnectionName): void {+ this.engine = connectionName;+ store.set(latestEngineSelected, connectionName);+ }++ setShowOutput(showOutput: boolean): void {+ this.showOutput = showOutput;+ }++ setDataframeName(dataframeName: string): void {+ this.dataframeName = dataframeName;}getExtension(@@ -159,3 +172,178 @@ function tablesCompletionSource(): CompletionSource {})(ctx);};}++interface SQLConfig {+ dfName: string;+ sqlString: string;+ engine: string | undefined;+ output: boolean | undefined;+ startPosition: number;+}++function findAssignment(cursor: TreeCursor): SyntaxNode | null {+ do {+ if (cursor.name === "AssignStatement") {+ return cursor.node;+ }+ } while (cursor.next());+ return null;+}++function getStringContent(node: SyntaxNode, code: string): string | null {+ // Handle triple quoted strings+ if (node.name === "String") {+ const content = code.slice(node.from, node.to);+ // Remove quotes and trim+ if (content.startsWith('"""') || content.startsWith("'''")) {+ return safeDedent(content.slice(3, -3));+ }+ // Handle single quoted strings+ return safeDedent(content.slice(1, -1));+ }+ // Handle f-strings+ if (node.name === "FormatString") {+ const content = code.slice(node.from, node.to);+ if (content.startsWith('f"""') || content.startsWith("f'''")) {+ return safeDedent(content.slice(4, -3));+ }+ return safeDedent(content.slice(2, -1));+ }+ return null;+}++/**+ * Parses a SQL statement from a Python code string.+ *+ * @param code - The Python code string to parse.+ * @returns The parsed SQL statement or null if parsing fails.+ */+export function parseSQLStatement(code: string): SQLConfig | null {+ try {+ const tree = parser.parse(code);+ const cursor = tree.cursor();++ // Find assignment statement+ const assignStmt = findAssignment(cursor);+ if (!assignStmt) {+ return null;+ }++ let dfName: string | null = null;+ let sqlString: string | null = null;+ let engine: string | undefined;+ let output: boolean | undefined;+ let startPosition = 0;++ // Parse the assignment+ const assignCursor = assignStmt.cursor();+ assignCursor.firstChild(); // Move to first child of assignment++ // First child should be the variable name+ if (assignCursor.name === "VariableName") {+ dfName = code.slice(assignCursor.from, assignCursor.to);+ }++ if (!dfName) {+ return null;+ }++ // Move to the expression part (after the =)+ while (assignCursor.next()) {+ if (assignCursor.name === "CallExpression") {+ // Check if it's mo.sql call+ const callCursor = assignCursor.node.cursor();+ let isMoSql = false;++ callCursor.firstChild(); // Move to first child of call+ if (callCursor.name === "MemberExpression") {+ const memberText = code.slice(callCursor.from, callCursor.to);+ isMoSql = memberText === "mo.sql";+ }++ if (!isMoSql) {+ return null;+ }++ // Move to arguments+ while (callCursor.next()) {+ if (callCursor.name === "ArgList") {+ const argListCursor = callCursor.node.cursor();++ const { args, kwargs } = parseArgsKwargs(argListCursor, code);++ // Parse positional args (SQL query)+ if (args.length === 1) {+ sqlString = getStringContent(args[0], code);+ startPosition =+ args[0].from ++ getPrefixLength(code.slice(args[0].from, args[0].to));+ }++ // Parse kwargs (engine and output)+ for (const { key, value } of kwargs) {+ switch (key) {+ case "engine":+ engine = value;+ break;+ case "output":+ output = value === "True";+ break;+ }+ }++ // Check if sql string is empty+ if (sqlString === "") {+ return { dfName, sqlString: "", engine, output, startPosition };+ }++ break;+ }+ }+ }+ }++ if (!dfName || !sqlString) {+ return null;+ }++ return {+ dfName,+ sqlString,+ engine,+ output,+ startPosition,+ };+ } catch (error) {+ Logger.warn("Failed to parse SQL statement", { error: error });+ return null;+ }+}++function getPrefixLength(code: string): number {+ if (code === "") {+ return 0;+ }+ if (code.startsWith('f"""') || code.startsWith("f'''")) {+ return 4;+ }+ if (code.startsWith('"""') || code.startsWith("'''")) {+ return 3;+ }+ if (code.startsWith("f'") || code.startsWith('f"')) {+ return 2;+ }+ if (code.startsWith("'") || code.startsWith('"')) {+ return 1;+ }+ return 0;+}++function safeDedent(code: string): string {+ try {+ // Dedent expects the first and last line to be empty / contain only whitespace, so we pad with \n+ return dedent(`\n${code}\n`).trim();+ } catch {+ return code;+ }+}diff --git a/frontend/src/core/codemirror/language/utils/ast.ts b/frontend/src/core/codemirror/language/utils/ast.tsnew file mode 100644index 0000000000..f8bef41532--- /dev/null+++ b/frontend/src/core/codemirror/language/utils/ast.ts@@ -0,0 +1,83 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Logger } from "@/utils/Logger";+import type { SyntaxNode, TreeCursor } from "@lezer/common";++const SYNTAX_TOKENS = new Set(["(", "[", "{", ",", ")", "]", "}"]);++export function parseArgsKwargs(+ argCursor: TreeCursor,+ code: string,+): {+ args: SyntaxNode[];+ kwargs: Array<{ key: string; value: string }>;+} {+ // Check we are in an ArgList+ const name = argCursor.name;++ if (name !== "ArgList") {+ Logger.warn("Not an ArgList");+ return { args: [], kwargs: [] };+ }++ return { args: parseArgs(argCursor), kwargs: parseKwargs(argCursor, code) };+}++export function parseArgs(argCursor: TreeCursor): SyntaxNode[] {+ // Move to first argument+ argCursor.firstChild();++ const args: SyntaxNode[] = [];+ let name = argCursor.name;++ do {+ name = argCursor.name;+ if (SYNTAX_TOKENS.has(name)) {+ continue;+ }++ if (name === "VariableName") {+ // Stop if we hit a kwarg (next token is AssignOp)+ const peek = argCursor.node.nextSibling;+ if (peek?.name === "AssignOp") {+ argCursor.prev();+ break;+ }+ }++ args.push(argCursor.node);+ } while (argCursor.nextSibling());++ return args;+}++export function parseKwargs(+ argCursor: TreeCursor,+ code: string,+): Array<{ key: string; value: string }> {+ const kwargs: Array<{ key: string; value: string }> = [];+ let name = argCursor.name;++ do {+ name = argCursor.name;+ if (name === "VariableName") {+ const key = code.slice(argCursor.from, argCursor.to);++ // Check for AssignOp+ const assignNode = argCursor.node.nextSibling;+ if (!assignNode || assignNode.name !== "AssignOp") {+ continue;+ }++ // Get the value node+ const valueNode = assignNode.nextSibling;+ if (!valueNode) {+ continue;+ }++ const value = code.slice(valueNode.from, valueNode.to).trim();+ kwargs.push({ key, value });+ }+ } while (argCursor.nextSibling());++ return kwargs;+}diff --git a/frontend/src/core/codemirror/react-dom/createPanel.tsx b/frontend/src/core/codemirror/react-dom/createPanel.tsxindex 3e811737a6..53d1ad3bcf 100644--- a/frontend/src/core/codemirror/react-dom/createPanel.tsx+++ b/frontend/src/core/codemirror/react-dom/createPanel.tsx@@ -1,5 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */+import { store } from "@/core/state/jotai";import type { EditorView, Panel } from "@codemirror/view";+import { Provider } from "jotai";import { type Root, createRoot } from "react-dom/client";export function createPanel(@@ -13,10 +15,18 @@ export function createPanel(dom,mount() {root = createRoot(dom);- root.render(<Component view={view} />);+ root.render(+ <Provider store={store}>+ <Component view={view} />+ </Provider>,+ );},update() {- root?.render(<Component view={view} />);+ root?.render(+ <Provider store={store}>+ <Component view={view} />+ </Provider>,+ );},destroy() {root?.unmount();diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex c58f0a8015..8ee2bc2295 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -12,6 +12,7 @@ export interface ExperimentalFeatures {scratchpad: boolean;chat_sidebar: boolean;rtc: boolean;+ sql_engines: boolean;// Add new feature flags here}@@ -21,6 +22,7 @@ const defaultValues: ExperimentalFeatures = {scratchpad: true,chat_sidebar: import.meta.env.DEV,rtc: false,+ sql_engines: import.meta.env.DEV,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex eca08cd1a4..67a7007fe3 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -103,6 +103,7 @@ export async function initialize() {case "variable-values":case "data-column-preview":case "datasets":+ case "data-source-connections":// Unsupportedreturn;case "kernel-ready":diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 22ce11e452..09f502f4f9 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -41,6 +41,7 @@ import { capabilitiesAtom } from "../config/capabilities";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { reloadSafe } from "@/utils/reload-safe";import { useRunsActions } from "../cells/runs";+import { useDataSourceActions } from "../cells/data-source-connections";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -61,6 +62,8 @@ export function useMarimoWebSocket(opts: {const { setVariables, setMetadata } = useVariablesActions();const { addColumnPreview } = useDatasetsActions();const { addDatasets, filterDatasetsFromVariables } = useDatasetsActions();+ const { addDataSourceConnection, filterDataSourcesFromVariables } =+ useDataSourceActions();const { setLayoutData } = useLayoutActions();const [connection, setConnection] = useAtom(connectionAtom);const { addBanner } = useBannersActions();@@ -133,6 +136,9 @@ export function useMarimoWebSocket(opts: {filterDatasetsFromVariables(msg.data.variables.map((v) => v.name as VariableName),);+ filterDataSourcesFromVariables(+ msg.data.variables.map((v) => v.name as VariableName),+ );return;case "variable-values":setMetadata(@@ -189,6 +195,9 @@ export function useMarimoWebSocket(opts: {case "data-column-preview":addColumnPreview(msg.data);return;+ case "data-source-connections":+ addDataSourceConnection(msg.data);+ return;case "reconnected":return;diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex a681d75774..67f173fb65 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -73,6 +73,7 @@ def _generate_schema() -> dict[str, Any]:data.DataTableColumn,data.DataTable,data.ColumnSummary,+ data.DataSourceConnection,# Operationsops.CellOp,ops.HumanReadableStatus,@@ -103,6 +104,7 @@ def _generate_schema() -> dict[str, Any]:ops.UpdateCellIdsRequest,ops.FocusCell,ops.MessageOperation,+ ops.DataSourceConnections,]# dataclass components used in requests/responsesdiff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex aedb75300f..40f40afe4c 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -37,7 +37,7 @@ class DataTableColumn:sample_values: List[Any]-DataTableSource = Literal["local", "duckdb"]+DataTableSource = Literal["local", "duckdb", "connection"]@dataclass@@ -91,3 +91,21 @@ class ColumnSummary:# p50 is the medianp75: Optional[NonNestedLiteral] = Nonep95: Optional[NonNestedLiteral] = None+++@dataclass+class DataSourceConnection:+ """+ Represents a data source connection.++ Attributes:+ source (str): The source of the data source connection. E.g 'postgres'.+ dialect (str): The dialect of the data source connection. E.g 'postgresql'.+ name (str): The name of the data source connection. E.g 'engine'.+ display_name (str): The display name of the data source connection. E.g 'PostgresQL (engine)'.+ """++ source: str+ dialect: str+ name: str+ display_name: strdiff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.pyindex 2d7828bed6..801cbdbb55 100644--- a/marimo/_data/sql_summaries.py+++ b/marimo/_data/sql_summaries.py@@ -5,7 +5,7 @@ from typing import List, Tuplefrom marimo._data.get_datasets import _db_type_to_data_typefrom marimo._data.models import ColumnSummary, DataType-from marimo._sql.sql import _wrapped_sql+from marimo._sql.sql import wrapped_sqldef get_sql_summary(@@ -66,7 +66,7 @@ def get_sql_summary(FROM {table_name}""" # noqa: E501- stats_result: Tuple[int, ...] | None = _wrapped_sql(stats_query).fetchone()+ stats_result: Tuple[int, ...] | None = wrapped_sql(stats_query).fetchone()if stats_result is None:raise ValueError(f"Column {column_name} not found in table {table_name}"@@ -141,7 +141,7 @@ def get_column_type(table_name: str, column_name: str) -> DataType:AND column_name = '{column_name}'"""- column_info_result: Tuple[str] | None = _wrapped_sql(+ column_info_result: Tuple[str] | None = wrapped_sql(column_info_query).fetchone()if column_info_result is None:diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 6afe5229e4..0b8da2cb6d 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -169,6 +169,7 @@ class DependencyManager:google_ai = Dependency("google.generativeai")groq = Dependency("groq")panel = Dependency("panel")+ sqlalchemy = Dependency("sqlalchemy")@staticmethoddef has(pkg: str) -> bool:diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 278066e48c..d3c4dc2b07 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -28,7 +28,12 @@ from uuid import uuid4from marimo import _loggers as loggersfrom marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, CellId_t, RuntimeStateType-from marimo._data.models import ColumnSummary, DataTable, DataTableSource+from marimo._data.models import (+ ColumnSummary,+ DataSourceConnection,+ DataTable,+ DataTableSource,+)from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOption@@ -598,6 +603,12 @@ class DataColumnPreview(Op):summary: Optional[ColumnSummary] = None+@dataclass+class DataSourceConnections(Op):+ name: ClassVar[str] = "data-source-connections"+ connections: List[DataSourceConnection]++@dataclassclass QueryParamsSet(Op):"""Set query parameters."""@@ -688,6 +699,7 @@ MessageOperation = Union[# DatasetsDatasets,DataColumnPreview,+ DataSourceConnections,# Kiosk specificFocusCell,UpdateCellCodes,diff --git a/marimo/_messaging/print_override.py b/marimo/_messaging/print_override.pyindex 6a26e0d13e..03032549df 100644--- a/marimo/_messaging/print_override.py+++ b/marimo/_messaging/print_override.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsimport functoolsdiff --git a/marimo/_messaging/variables.py b/marimo/_messaging/variables.pyindex e1c5eeaccc..f0373ea55a 100644--- a/marimo/_messaging/variables.py+++ b/marimo/_messaging/variables.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsfrom typing import Any, Mapping, Sequence, Uniondiff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex d374376ba2..83c126b7f9 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -20,6 +20,7 @@ from marimo._messaging.errors import (from marimo._messaging.ops import (CellOp,Datasets,+ DataSourceConnections,VariableValue,VariableValues,)@@ -31,6 +32,10 @@ from marimo._runtime.context.types import get_context, get_global_contextfrom marimo._runtime.control_flow import MarimoInterrupt, MarimoStopErrorfrom marimo._runtime.runner import cell_runnerfrom marimo._server.model import SessionMode+from marimo._sql.get_engines import (+ engine_to_data_source_connection,+ get_engines_from_variables,+)from marimo._tracer import kernel_tracerfrom marimo._utils.flatten import contains_instance@@ -131,6 +136,35 @@ def _broadcast_datasets(Datasets(tables=tables).broadcast()+@kernel_tracer.start_as_current_span("broadcast_data_source_connection")+def _broadcast_data_source_connection(+ cell: CellImpl,+ runner: cell_runner.Runner,+ run_result: cell_runner.RunResult,+) -> None:+ # Skip if not in edit mode+ if not _is_edit_mode():+ return++ del run_result+ engines = get_engines_from_variables(+ [+ (variable, runner.glbls[variable])+ for variable in cell.defs+ if variable in runner.glbls+ ]+ )++ if engines:+ LOGGER.debug("Broadcasting data source connections")+ DataSourceConnections(+ connections=[+ engine_to_data_source_connection(variable, engine)+ for variable, engine in engines+ ]+ ).broadcast()++@kernel_tracer.start_as_current_span("broadcast_duckdb_tables")def _broadcast_duckdb_tables(cell: CellImpl,@@ -330,6 +364,7 @@ POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [_store_state_reference,_broadcast_variables,_broadcast_datasets,+ _broadcast_data_source_connection,_broadcast_duckdb_tables,_broadcast_outputs,_reset_matplotlib_context,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 94f0e82547..0226eb01b8 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2022,6 +2022,9 @@ class Kernel:elif source_type == "local":dataset = self.globals[table_name]column_preview = get_column_preview_dataframe(dataset, request)+ elif source_type == "connection":+ # TODO: Handle data-source-connection / engine display+ passelse:assert_never(source_type)diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pyindex c586854f0d..1ad871be22 100644--- a/marimo/_server/session/session_view.py+++ b/marimo/_server/session/session_view.py@@ -6,11 +6,12 @@ from dataclasses import dataclassfrom typing import Any, Literal, Optional, Unionfrom marimo._ast.cell import CellId_t-from marimo._data.models import DataTable+from marimo._data.models import DataSourceConnection, DataTablefrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.ops import (CellOp,Datasets,+ DataSourceConnections,Interrupted,MessageOperation,UpdateCellCodes,@@ -42,7 +43,9 @@ class SessionView:# List of operations we care about keeping track of.self.cell_operations: dict[CellId_t, CellOp] = {}# The most recent datasets operation.- self.datasets: Datasets = Datasets(tables=[])+ self.datasets = Datasets(tables=[])+ # The most recent data-connectors operation+ self.data_connectors = DataSourceConnections(connections=[])# The most recent Variables operation.self.variable_operations: Variables = Variables(variables=[])# Map of variable name to value.@@ -149,6 +152,15 @@ class SessionView:next_tables[table.name] = tableself.datasets = Datasets(tables=list(next_tables.values()))+ # Remove any data source connections that are no longer in scope.+ next_connections: dict[str, DataSourceConnection] = {}+ for connection in self.data_connectors.connections:+ if connection.name in variable_names:+ next_connections[connection.name] = connection+ self.data_connectors = DataSourceConnections(+ connections=list(next_connections.values())+ )+elif isinstance(operation, VariableValues):for value in operation.variables:self.variable_values[value.name] = value@@ -172,6 +184,18 @@ class SessionView:tables[table.name] = tableself.datasets = Datasets(tables=list(tables.values()))+ elif isinstance(operation, DataSourceConnections):+ # Update data source connections, dedupe by name and keep the latest+ prev_connections = self.data_connectors.connections+ connections = {c.name: c for c in prev_connections}++ for c in operation.connections:+ connections[c.name] = c++ self.data_connectors = DataSourceConnections(+ connections=list(connections.values())+ )+elif isinstance(operation, UpdateCellIdsRequest):self.cell_ids = operation@@ -233,6 +257,8 @@ class SessionView:)if self.datasets.tables:all_ops.append(self.datasets)+ if self.data_connectors.connections:+ all_ops.append(self.data_connectors)all_ops.extend(self.cell_operations.values())if self.stale_code:all_ops.append(self.stale_code)diff --git a/marimo/_smoke_tests/sql/duckdb_engine.py b/marimo/_smoke_tests/sql/duckdb_engine.pynew file mode 100644index 0000000000..9a170734d7--- /dev/null+++ b/marimo/_smoke_tests/sql/duckdb_engine.py@@ -0,0 +1,69 @@+import marimo++__generated_with = "0.10.17"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)+++def _():+ import duckdb++ connection_one = duckdb.connect("one.db")+ connection_two = duckdb.connect("two.db")+ return connection_one, connection_two, duckdb+++def _(connection_one, mo):+ _df = mo.sql(+ f"""+ CREATE OR REPLACE TABLE numbers AS+ SELECT * FROM range(1, 101) AS n;+ """,+ engine=connection_one+ )+ return (numbers,)+++def _(connection_two, mo):+ _df = mo.sql(+ f"""+ CREATE OR REPLACE TABLE other_numbers AS+ SELECT * FROM range(1, 101) AS n;+ """,+ engine=connection_two+ )+ return (other_numbers,)+++def _(connection_one, mo):+ _df = mo.sql(+ f"""+ SELECT * FROM duckdb_tables();+ """,+ engine=connection_one+ )+ return+++def _(connection_two, mo):+ _df = mo.sql(+ f"""+ SELECT * FROM duckdb_tables();+ """,+ engine=connection_two+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/sql/polars_sql.py b/marimo/_smoke_tests/sql/polars_sql.pynew file mode 100644index 0000000000..ca32c7a5e5--- /dev/null+++ b/marimo/_smoke_tests/sql/polars_sql.py@@ -0,0 +1,45 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "connectorx==0.4.1",+# "marimo",+# "polars==1.20.0",+# "pyarrow==19.0.0",+# ]+# ///++import marimo++__generated_with = "0.10.16"+app = marimo.App(width="medium")+++def _():+ import polars as pl+ import os+ import pyarrow+ import connectorx++ uri = os.environ.get("DATABASE_URL")+ return connectorx, os, pl, pyarrow, uri+++def _(mo, pl, uri):+ mo.stop(not uri)+ query = "SELECT * FROM pg_catalog.pg_tables;"++ df = pl.read_database_uri(query=query, uri=uri)+ df+ return df, query+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/sql/sql_alchemy.py b/marimo/_smoke_tests/sql/sql_alchemy.pynew file mode 100644index 0000000000..1eba51eaf0--- /dev/null+++ b/marimo/_smoke_tests/sql/sql_alchemy.py@@ -0,0 +1,146 @@+import marimo++__generated_with = "0.10.16"+app = marimo.App()++[email protected](hide_code=True)+def _(mo):+ mo.md("""# SQLAlchemy Demo""")+ return+++def _():+ import marimo as mo+ return (mo,)+++def _():+ import sqlalchemy as sa+ from sqlalchemy.orm import declarative_base, Session+ from sqlalchemy.orm import Mapped, mapped_column+ import polars as pl+ return Mapped, Session, declarative_base, mapped_column, pl, sa+++def _(Mapped, declarative_base, mapped_column, sa):+ # Create an in-memory SQLite database+ engine = sa.create_engine("sqlite:///:memory:")++ # Define our models+ Base = declarative_base()+++ class User(Base):+ __tablename__ = "users"++ id: Mapped[int] = mapped_column(primary_key=True)+ name: Mapped[str] = mapped_column(sa.String(50))+ age: Mapped[int] = mapped_column(sa.Integer)+++ # Create tables+ Base.metadata.create_all(engine)+ return Base, User, engine+++def _(Session, User, engine):+ # Insert sample data+ with Session(engine) as _session:+ users = [+ User(name="Alice", age=25),+ User(name="Bob", age=30),+ User(name="Charlie", age=35),+ User(name="Diana", age=28),+ ]+ _session.add_all(users)+ _session.commit()+ return (users,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### All Users""")+ return+++def _(Session, User, engine, mo, pl):+ # Query examples+ with Session(engine) as _session:+ # Basic query+ all_users = _session.query(User).all()+ df = pl.DataFrame(+ [(u.name, u.age) for u in all_users],+ schema=["Name", "Age"],+ orient="row",+ )++ mo.hstack(+ [+ df,+ mo.vstack(+ [+ mo.md("### Stats"),+ f"Average age: {df['Age'].mean():.1f}",+ f"Total users: {len(df)}",+ ]+ ),+ ]+ )+ return all_users, df++[email protected](hide_code=True)+def _(mo):+ mo.md("""### Users under 30 (ordered by name)""")+ return+++def _(Session, User, engine, mo):+ # Advanced queries+ with Session(engine) as _session:+ # Filter and order+ young_users = (+ _session.query(User).filter(User.age < 30).order_by(User.name).all()+ )++ mo.ui.table(+ [{"Name": u.name, "Age": u.age} for u in young_users], selection=None+ )+ return (young_users,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### Age Statistics""")+ return+++def _(Session, User, engine, sa):+ # Aggregation example+ with Session(engine) as _session:+ age_stats = _session.query(+ sa.func.count(User.id).label("count"),+ sa.func.avg(User.age).label("avg_age"),+ sa.func.min(User.age).label("min_age"),+ sa.func.max(User.age).label("max_age"),+ ).one()++ [+ ("Total Users", age_stats.count),+ ("Average Age", f"{age_stats.avg_age:.1f}"),+ ("Youngest", age_stats.min_age),+ ("Oldest", age_stats.max_age),+ ]+ return (age_stats,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/sql/sql_alchemy_engine.py b/marimo/_smoke_tests/sql/sql_alchemy_engine.pynew file mode 100644index 0000000000..0f329d4050--- /dev/null+++ b/marimo/_smoke_tests/sql/sql_alchemy_engine.py@@ -0,0 +1,196 @@+import marimo++__generated_with = "0.10.17"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""# SQL Alchemy with `mo.sql()`""")+ return+++def _():+ from sqlalchemy import text, create_engine+ return create_engine, text++[email protected](hide_code=True)+def _(mo):+ mo.md("""## sqlite""")+ return+++def _(create_engine, mo, products):+ # Create an in-memory SQLite database+ sqlite = create_engine("sqlite:///:memory:")++ mo.sql("DROP TABLE IF EXISTS products;", engine=sqlite)++ mo.sql(+ """+ CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ name TEXT NOT NULL,+ price DECIMAL(10,2) NOT NULL,+ category TEXT NOT NULL+ );+ """,+ engine=sqlite,+ )++ mo.sql(+ """+ INSERT INTO products (name, price, category) VALUES+ ('Laptop', 999.99, 'Electronics'),+ ('Coffee Maker', 49.99, 'Appliances'),+ ('Headphones', 79.99, 'Electronics'),+ ('Toaster', 29.99, 'Appliances'),+ ('Smartphone', 599.99, 'Electronics'),+ ('Blender', 39.99, 'Appliances');+ """,+ engine=sqlite,+ )+ return products, sqlite+++def _(mo, products, sqlite):+ products_df = mo.sql(+ f"""+ SELECT name, price, category+ FROM products+ ORDER BY price DESC+ """,+ engine=sqlite+ )+ return (products_df,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### All Products (sorted by price)""")+ return++[email protected](hide_code=True)+def _(mo, products_df):+ mo.hstack(+ [+ products_df,+ mo.vstack(+ [+ mo.md("### Summary"),+ f"Total products: {len(products_df)}",+ f"Average price: ${products_df['price'].mean():.2f}",+ ]+ ),+ ]+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""### Category Summary""")+ return+++def _(mo, products, sqlite):+ _df = mo.sql(+ f"""+ -- Category summary+ SELECT+ category,+ COUNT(*) as count,+ ROUND(AVG(price), 2) as avg_price,+ ROUND(MIN(price), 2) as min_price,+ ROUND(MAX(price), 2) as max_price+ FROM products+ GROUP BY category+ ORDER BY avg_price DESC+ """,+ engine=sqlite+ )+ return++[email protected](hide_code=True)+def _(mo):+ # Interactive price filter+ price_threshold = mo.ui.slider(+ start=0, stop=1000, value=100, label="Max Price $"+ )+ mo.md(f"### Products under {price_threshold}")+ return (price_threshold,)+++def _(mo, price_threshold, products, sqlite):+ mo.sql(+ f"""+ SELECT name, price, category+ FROM products+ WHERE price < {price_threshold.value}+ ORDER BY price DESC+ """,+ engine=sqlite,+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""## postgresql""")+ return+++def _(mo):+ import os++ psql_url = mo.ui.text(+ kind="password",+ label="PostgreSQL URL",+ placeholder="postgresql://",+ value=os.getenv("POSTGRES_URL") or "",+ )+ psql_url+ return os, psql_url+++def _(create_engine, mo, psql_url):+ mo.stop(not psql_url.value)++ # Create a PostgreSQL database+ my_postgres = create_engine(+ psql_url.value.replace("postgresql", "postgresql+psycopg")+ )+ return (my_postgres,)+++def _(information_schema, mo, my_postgres, tables):+ _df = mo.sql(+ f"""+ SELECT table_name+ FROM information_schema.tables+ WHERE table_schema = 'public';+ """,+ engine=my_postgres+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/sql/sqlmodel_engine.py b/marimo/_smoke_tests/sql/sqlmodel_engine.pynew file mode 100644index 0000000000..333d502df0--- /dev/null+++ b/marimo/_smoke_tests/sql/sqlmodel_engine.py@@ -0,0 +1,207 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "polars==1.21.0",+# "psycopg==3.2.4",+# "sqlglot==26.3.9",+# "sqlmodel==0.0.22",+# ]+# ///++import marimo++__generated_with = "0.10.17"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""# SQLModel with `mo.sql()`""")+ return+++def _():+ from sqlmodel import text, create_engine+ return create_engine, text++[email protected](hide_code=True)+def _(mo):+ mo.md("""## sqlite""")+ return+++def _(create_engine, mo, products):+ # Create an in-memory SQLite database+ sqlite = create_engine("sqlite:///:memory:")++ mo.sql("DROP TABLE IF EXISTS products;", engine=sqlite)++ mo.sql(+ """+ CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ name TEXT NOT NULL,+ price DECIMAL(10,2) NOT NULL,+ category TEXT NOT NULL+ );+ """,+ engine=sqlite,+ )++ mo.sql(+ """+ INSERT INTO products (name, price, category) VALUES+ ('Laptop', 999.99, 'Electronics'),+ ('Coffee Maker', 49.99, 'Appliances'),+ ('Headphones', 79.99, 'Electronics'),+ ('Toaster', 29.99, 'Appliances'),+ ('Smartphone', 599.99, 'Electronics'),+ ('Blender', 39.99, 'Appliances');+ """,+ engine=sqlite,+ )+ return products, sqlite+++def _(mo, products, sqlite):+ products_df = mo.sql(+ f"""+ SELECT name, price, category+ FROM products+ ORDER BY price DESC+ """,+ engine=sqlite+ )+ return (products_df,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""### All Products (sorted by price)""")+ return++[email protected](hide_code=True)+def _(mo, products_df):+ mo.hstack(+ [+ products_df,+ mo.vstack(+ [+ mo.md("### Summary"),+ f"Total products: {len(products_df)}",+ f"Average price: ${products_df['price'].mean():.2f}",+ ]+ ),+ ]+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""### Category Summary""")+ return+++def _(mo, products, sqlite):+ _df = mo.sql(+ f"""+ -- Category summary+ SELECT+ category,+ COUNT(*) as count,+ ROUND(AVG(price), 2) as avg_price,+ ROUND(MIN(price), 2) as min_price,+ ROUND(MAX(price), 2) as max_price+ FROM products+ GROUP BY category+ ORDER BY avg_price DESC+ """,+ engine=sqlite+ )+ return++[email protected](hide_code=True)+def _(mo):+ # Interactive price filter+ price_threshold = mo.ui.slider(+ start=0, stop=1000, value=100, label="Max Price $"+ )+ mo.md(f"### Products under {price_threshold}")+ return (price_threshold,)+++def _(mo, price_threshold, products, sqlite):+ mo.sql(+ f"""+ SELECT name, price, category+ FROM products+ WHERE price < {price_threshold.value}+ ORDER BY price DESC+ """,+ engine=sqlite,+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""## postgresql""")+ return+++def _(mo):+ import os++ psql_url = mo.ui.text(+ kind="password",+ label="PostgreSQL URL",+ placeholder="postgresql://",+ value=os.getenv("POSTGRES_URL") or "",+ )+ psql_url+ return os, psql_url+++def _(create_engine, mo, psql_url):+ mo.stop(not psql_url.value)++ # Create a PostgreSQL database+ my_postgres = create_engine(+ psql_url.value.replace("postgresql", "postgresql+psycopg2")+ )+ return (my_postgres,)+++def _(information_schema, mo, my_postgres, tables):+ _df = mo.sql(+ f"""+ SELECT table_name+ FROM information_schema.tables+ WHERE table_schema = 'public';+ """,+ engine=my_postgres+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_sql/engines.py b/marimo/_sql/engines.pynew file mode 100644index 0000000000..ba977d7d52--- /dev/null+++ b/marimo/_sql/engines.py@@ -0,0 +1,114 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional++from marimo._dependencies.dependencies import DependencyManager+from marimo._sql.types import SQLEngine++if TYPE_CHECKING:+ import duckdb+ from sqlalchemy import Engine+++def raise_df_import_error(pkg: str) -> None:+ raise ModuleNotFoundError(+ "pandas or polars is required to execute sql. "+ + "You can install them with 'pip install pandas polars'",+ name=pkg,+ )+++class DuckDBEngine(SQLEngine):+ """DuckDB SQL engine."""++ def __init__(+ self, connection: Optional[duckdb.DuckDBPyConnection]+ ) -> None:+ self._connection = connection++ @property+ def source(self) -> str:+ return "duckdb"++ @property+ def dialect(self) -> str:+ return "duckdb"++ def execute(self, query: str) -> Any:+ import duckdb++ if self._connection is None:+ relation = duckdb.sql(query)+ else:+ relation = self._connection.sql(query)++ # Invalid / empty query+ if relation is None:+ return None++ if DependencyManager.polars.has():+ return relation.pl()+ elif DependencyManager.pandas.has():+ return relation.df()+ else:+ raise_df_import_error("polars")++ @staticmethod+ def is_compatible(var: Any) -> bool:+ if not DependencyManager.duckdb.imported():+ return False++ import duckdb++ return isinstance(var, duckdb.DuckDBPyConnection)+++class SQLAlchemyEngine(SQLEngine):+ """SQLAlchemy engine."""++ def __init__(self, engine: Engine) -> None:+ self._engine = engine++ @property+ def source(self) -> str:+ return "sqlalchemy"++ @property+ def dialect(self) -> str:+ return str(self._engine.dialect.name)++ def execute(self, query: str) -> Any:+ # Can't use polars.imported() because this is the first time we+ # might come across polars.+ if not (+ DependencyManager.polars.has() or DependencyManager.pandas.has()+ ):+ raise_df_import_error("polars")++ from sqlalchemy import text++ with self._engine.connect() as connection:+ result = connection.execute(text(query))+ connection.commit()++ if not result.returns_rows:+ return None++ if DependencyManager.polars.has():+ import polars as pl++ return pl.DataFrame(result) # type: ignore+ else:+ import pandas as pd++ return pd.DataFrame(result)++ @staticmethod+ def is_compatible(var: Any) -> bool:+ if not DependencyManager.sqlalchemy.imported():+ return False++ from sqlalchemy.engine import Engine++ return isinstance(var, Engine)diff --git a/marimo/_sql/get_engines.py b/marimo/_sql/get_engines.pynew file mode 100644index 0000000000..ead48a3d7f--- /dev/null+++ b/marimo/_sql/get_engines.py@@ -0,0 +1,33 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, cast++from marimo._data.models import DataSourceConnection+from marimo._sql.engines import DuckDBEngine, SQLAlchemyEngine+from marimo._sql.types import SQLEngine+++def get_engines_from_variables(+ variables: list[tuple[str, object]],+) -> list[tuple[str, SQLEngine]]:+ engines: list[tuple[str, SQLEngine]] = []+ for variable_name, value in variables:+ if SQLAlchemyEngine.is_compatible(value):+ engines.append((variable_name, SQLAlchemyEngine(cast(Any, value))))+ elif DuckDBEngine.is_compatible(value):+ engines.append((variable_name, DuckDBEngine(cast(Any, value))))++ return engines+++def engine_to_data_source_connection(+ variable_name: str,+ engine: SQLEngine,+) -> DataSourceConnection:+ return DataSourceConnection(+ source=engine.source,+ dialect=engine.dialect,+ name=variable_name,+ display_name=f"{engine.dialect} ({variable_name})",+ )diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex 5fb82369c6..dfb06dba80 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -11,9 +11,12 @@ from marimo._runtime.context.types import (get_context,)from marimo._runtime.output import replace--if TYPE_CHECKING:- import duckdb+from marimo._sql.engines import (+ DuckDBEngine,+ SQLAlchemyEngine,+ raise_df_import_error,+)+from marimo._sql.types import SQLEnginedef get_default_result_limit() -> Optional[int]:@@ -21,31 +24,54 @@ def get_default_result_limit() -> Optional[int]:return int(limit) if limit is not None else None+if TYPE_CHECKING:+ import duckdb+ import sqlalchemy++@mddocdef sql(query: str,+ *,output: bool = True,+ engine: Optional[sqlalchemy.Engine | duckdb.DuckDBPyConnection] = None,) -> Any:"""Execute a SQL query.- This uses duckdb to execute the query. Any dataframes in the global+ By default, this uses duckdb to execute the query. Any dataframes in the globalnamespace can be used inside the query.+ You can also pass a SQLAlchemy engine to execute queries against other databases.+The result of the query is displayed in the UI if output is True.Args:query: The SQL query to execute.output: Whether to display the result in the UI. Defaults to True.+ engine: Optional SQL engine to use. Can be a SQLAlchemy engine or DuckDB connection.+ If None, uses DuckDB.Returns:The result of the query."""- DependencyManager.duckdb.require("to execute sql")+ if query is None or query.strip() == "":+ return None- relation = _wrapped_sql(query)+ if engine is None:+ DependencyManager.duckdb.require("to execute sql")+ sql_engine = DuckDBEngine(connection=None)+ elif SQLAlchemyEngine.is_compatible(engine):+ sql_engine = SQLAlchemyEngine(engine) # type: ignore+ elif DuckDBEngine.is_compatible(engine):+ sql_engine = DuckDBEngine(engine) # type: ignore+ else:+ raise ValueError(+ "Unsupported engine. Must be a SQLAlchemy engine or DuckDB connection."+ )- if not relation:+ df = _execute_query(query, sql_engine)+ if df is None:return Nonehas_limit = _query_includes_limit(query)@@ -56,38 +82,24 @@ def sql(enforce_own_limit = not has_limit and default_result_limit is not None- if enforce_own_limit:- relation = relation.limit(- cast(int, default_result_limit) + 1- ) # request 1 more-custom_total_count: Optional[Literal["too_many"]] = None-- df: Any- if DependencyManager.polars.has():- df = relation.pl()- if enforce_own_limit:+ if enforce_own_limit:+ if DependencyManager.polars.has():custom_total_count = ("too_many"if len(df) > cast(int, default_result_limit)else None)df = df.limit(default_result_limit)- elif DependencyManager.pandas.has():- df = relation.df()- if enforce_own_limit:+ elif DependencyManager.pandas.has():custom_total_count = ("too_many"if len(df) > cast(int, default_result_limit)else None)df = df.head(default_result_limit)- else:- raise ModuleNotFoundError(- "pandas or polars is required to execute sql. "- + "You can install them with 'pip install pandas polars'",- name="polars",- )+ else:+ raise_df_import_error("polars")if output:from marimo._plugins.ui._impl import table@@ -104,34 +116,51 @@ def sql(def _query_includes_limit(query: str) -> bool:- import duckdb+ """Check if a SQL query includes a LIMIT clause."""+ import sqlglot+ from sqlglot.expressions import Limit, Selecttry:- statements = duckdb.extract_statements(query.strip())+ expressions = sqlglot.parse(query.strip())except Exception:# May not be valid SQLreturn False- if not statements:+ if not expressions:return False- last_statement = statements[-1]-- return last_statement.type == duckdb.StatementType.SELECT and (- "LIMIT " in last_statement.query.upper()- or "LIMIT\n" in last_statement.query.upper()- )+ # Only check the last statement in case of multiple statements+ last_expr = expressions[-1]+ if not isinstance(last_expr, Select):+ return False+ # Look for any LIMIT clause in the SELECT statement+ return last_expr.find(Limit) is not None-def _wrapped_sql(query: str) -> "duckdb.DuckDBPyRelation":- import duckdb+def _execute_query(query: str, engine: SQLEngine) -> Any:# In Python globals() are scoped to modules; since this function# is in a different module than user code, globals() doesn't return# the kernel globals, it just returns this module's global namespace.## However, duckdb needs access to the kernel's globals. For this reason,# we manually exec duckdb and provide it with the kernel's globals.+ try:+ ctx = get_context()+ except ContextNotInitializedError:+ return engine.execute(query)+ else:+ return eval(+ "engine.execute(query)",+ ctx.globals,+ {"query": query, "engine": engine},+ )+++def wrapped_sql(query: str) -> "duckdb.DuckDBPyRelation":+ import duckdb++ # Same as above, but for plain duckdbtry:ctx = get_context()except ContextNotInitializedError:diff --git a/marimo/_sql/types.py b/marimo/_sql/types.pynew file mode 100644index 0000000000..259c7cb1aa--- /dev/null+++ b/marimo/_sql/types.py@@ -0,0 +1,32 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from abc import ABC, abstractmethod+from typing import Any+++class SQLEngine(ABC):+ """Protocol for SQL engines that can execute queries."""++ @property+ @abstractmethod+ def source(self) -> str:+ """Return the source of the engine."""+ pass++ @property+ @abstractmethod+ def dialect(self) -> str:+ """Return the sqlglot dialect for this engine."""+ pass++ @abstractmethod+ def execute(self, query: str) -> Any:+ """Execute a SQL query and return a dataframe."""+ pass++ @staticmethod+ @abstractmethod+ def is_compatible(var: Any) -> bool:+ """Check if a variable is a compatible engine."""+ passdiff --git a/marimo/_utils/lists.py b/marimo/_utils/lists.pyindex ed538b4f89..e620c840fd 100644--- a/marimo/_utils/lists.py+++ b/marimo/_utils/lists.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsfrom typing import Iterable, TypeVar, Uniondiff --git a/marimo/_utils/versions.py b/marimo/_utils/versions.pyindex f1cfb11015..906b83bb1c 100644--- a/marimo/_utils/versions.py+++ b/marimo/_utils/versions.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsimport jsondiff --git a/openapi/api.yaml b/openapi/api.yamlindex 5cd02225c4..2747723e60 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -380,6 +380,36 @@ components:- chart_max_rows_errors- nametype: object+ DataSourceConnection:+ properties:+ dialect:+ type: string+ display_name:+ type: string+ name:+ type: string+ source:+ type: string+ required:+ - source+ - dialect+ - name+ - display_name+ type: object+ DataSourceConnections:+ properties:+ connections:+ items:+ $ref: '#/components/schemas/DataSourceConnection'+ type: array+ name:+ enum:+ - data-source-connections+ type: string+ required:+ - connections+ - name+ type: objectDataTable:properties:columns:@@ -400,6 +430,7 @@ components:enum:- local- duckdb+ - connectiontype: stringvariable_name:nullable: true@@ -444,6 +475,7 @@ components:enum:- local- duckdb+ - connectionnullable: truetype: stringname:@@ -1356,6 +1388,19 @@ components:- $ref: '#/components/schemas/QueryParamsClear'- $ref: '#/components/schemas/Datasets'- $ref: '#/components/schemas/DataColumnPreview'+ - properties:+ connections:+ items:+ $ref: '#/components/schemas/DataSourceConnection'+ type: array+ name:+ enum:+ - data-source-connections+ type: string+ required:+ - connections+ - name+ type: object- $ref: '#/components/schemas/FocusCell'- $ref: '#/components/schemas/UpdateCellCodes'- $ref: '#/components/schemas/UpdateCellIdsRequest'@@ -1490,6 +1535,7 @@ components:enum:- local- duckdb+ - connectiontype: stringtableName:type: stringdiff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 1a04c9099d..0d2a79ed4e 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2230,6 +2230,17 @@ export interface components {summary?: components["schemas"]["ColumnSummary"];table_name: string;};+ DataSourceConnection: {+ dialect: string;+ display_name: string;+ name: string;+ source: string;+ };+ DataSourceConnections: {+ connections: components["schemas"]["DataSourceConnection"][];+ /** @enum {string} */+ name: "data-source-connections";+ };DataTable: {columns: components["schemas"]["DataTableColumn"][];name: string;@@ -2237,7 +2248,7 @@ export interface components {num_rows?: number | null;source: string;/** @enum {string} */- source_type: "local" | "duckdb";+ source_type: "local" | "duckdb" | "connection";variable_name?: string | null;};DataTableColumn: {@@ -2258,7 +2269,7 @@ export interface components {| "unknown";Datasets: {/** @enum {string|null} */- clear_channel?: "local" | "duckdb" | null;+ clear_channel?: "local" | "duckdb" | "connection" | null;/** @enum {string} */name: "datasets";tables: components["schemas"]["DataTable"][];@@ -2642,6 +2653,11 @@ export interface components {| components["schemas"]["QueryParamsClear"]| components["schemas"]["Datasets"]| components["schemas"]["DataColumnPreview"]+ | {+ connections: components["schemas"]["DataSourceConnection"][];+ /** @enum {string} */+ name: "data-source-connections";+ }| components["schemas"]["FocusCell"]| components["schemas"]["UpdateCellCodes"]| components["schemas"]["UpdateCellIdsRequest"];@@ -2710,7 +2726,7 @@ export interface components {columnName: string;source: string;/** @enum {string} */- sourceType: "local" | "duckdb";+ sourceType: "local" | "duckdb" | "connection";tableName: string;};QueryParamsAppend: {diff --git a/pyproject.toml b/pyproject.tomlindex bcde20fc09..11cff4b93d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -175,6 +175,8 @@ dependencies = ["narwhals>=1.12.0","matplotlib>=3.8.0","pyarrow-stubs>=17.0",+ "sqlglot>=23.4",+ "sqlalchemy>=2.0.0","pandas-stubs>=1.5.3.230321","types-Pillow~=10.2.0.20240520","types-Pygments~=2.18.0.20240506",@@ -230,6 +232,8 @@ extra-dependencies = ["pyarrow_hotfix","altair>=5.4.0","polars~=1.9.0",+ "sqlglot>=23.4",+ "sqlalchemy>=2.0.0","pandas>=1.5.3","hvplot~=0.11.2",# Causes issues installing `shapely` (v2.0.7)@@ -396,6 +400,9 @@ banned-module-level-imports = ["pandas","tomlkit","polars",+ "sqlglot",+ "duckdb",+ "sqlalchemy","altair","ipython","anywidget",diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pyindex 0cb990b9c1..802812d34e 100644--- a/tests/_server/session/test_session_view.py+++ b/tests/_server/session/test_session_view.py@@ -10,6 +10,8 @@ from marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.ops import (CellOp,Datasets,+ DataSourceConnection,+ DataSourceConnections,UpdateCellCodes,UpdateCellIdsRequest,VariableDeclaration,@@ -423,6 +425,90 @@ def test_add_datasets_clear_channel() -> None:assert "db.table2" in names+def test_add_data_source_connections() -> None:+ session_view = SessionView()++ # Add initial connections+ session_view.add_raw_operation(+ serialize(+ DataSourceConnections(+ connections=[+ DataSourceConnection(+ source="duckdb",+ dialect="duckdb",+ name="db1",+ display_name="duckdb (db1)",+ ),+ DataSourceConnection(+ source="sqlalchemy",+ dialect="postgresql",+ name="pg1",+ display_name="postgresql (pg1)",+ ),+ ]+ )+ )+ )++ assert len(session_view.data_connectors.connections) == 2+ names = [c.name for c in session_view.data_connectors.connections]+ assert "db1" in names+ assert "pg1" in names++ # Add new connection and update existing+ session_view.add_raw_operation(+ serialize(+ DataSourceConnections(+ connections=[+ DataSourceConnection(+ source="duckdb",+ dialect="duckdb",+ name="db1",+ display_name="duckdb (db1_updated)",+ ),+ DataSourceConnection(+ source="sqlalchemy",+ dialect="mysql",+ name="mysql1",+ display_name="mysql (mysql1)",+ ),+ ]+ )+ )+ )++ assert len(session_view.data_connectors.connections) == 3+ conns = {c.name: c for c in session_view.data_connectors.connections}++ # Check updated connection+ assert "db1" in conns+ assert conns["db1"].display_name == "duckdb (db1_updated)"++ # Check new connection replaced old one+ assert "mysql1" in conns+ assert conns["mysql1"].dialect == "mysql"+ # Check existing connection+ assert "pg1" in conns++ # Check connectors in operations+ assert session_view.data_connectors in session_view.operations++ # Filter out connections from variables+ session_view.add_raw_operation(+ serialize(+ Variables(+ variables=[+ VariableDeclaration(+ name="mysql1", declared_by=[cell_id], used_by=[]+ ),+ ]+ )+ )+ )+ assert len(session_view.data_connectors.connections) == 1+ assert session_view.data_connectors.connections[0].name == "mysql1"++def test_add_cell_op() -> None:session_view = SessionView()session_view.add_raw_operation(diff --git a/tests/_sql/test_engines.py b/tests/_sql/test_engines.pynew file mode 100644index 0000000000..05c6267d46--- /dev/null+++ b/tests/_sql/test_engines.py@@ -0,0 +1,160 @@+"""Tests for SQL engines."""++from __future__ import annotations++from typing import TYPE_CHECKING, Generator+from unittest.mock import MagicMock++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._sql.engines import (+ DuckDBEngine,+ SQLAlchemyEngine,+ raise_df_import_error,+)+from marimo._sql.sql import _execute_query, sql++HAS_DUCKDB = DependencyManager.duckdb.has()+HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()+HAS_POLARS = DependencyManager.polars.has()+HAS_PANDAS = DependencyManager.pandas.has()++if TYPE_CHECKING:+ import duckdb+ import sqlalchemy as sa+++def sqlite_engine() -> sa.Engine:+ """Create a temporary SQLite database for testing."""++ import sqlalchemy as sa+ from sqlalchemy import text++ engine = sa.create_engine("sqlite:///:memory:")++ # Test if standard syntax works+ with engine.begin() as conn:+ conn.execute(+ text(+ """+ CREATE TABLE test (+ id INTEGER PRIMARY KEY,+ name TEXT+ )+ """+ )+ )+ conn.execute(+ text(+ """+ INSERT INTO test (id, name) VALUES+ (1, 'Alice'),+ (2, 'Bob'),+ (3, 'Charlie')+ """+ )+ )++ # Test if mo.sql works+ sql("INSERT INTO test (id, name) VALUES (4, 'Rose')", engine=engine)+ return engine+++def duckdb_connection() -> Generator[duckdb.DuckDBPyConnection, None, None]:+ """Create a DuckDB connection for testing."""++ import duckdb++ conn = duckdb.connect(":memory:")+ conn.execute(+ """+ CREATE TABLE test (+ id INTEGER PRIMARY KEY,+ name TEXT+ );+ """+ )+ conn.execute(+ """+ INSERT INTO test VALUES+ (1, 'Alice'),+ (2, 'Bob'),+ (3, 'Charlie');+ """+ )+ sql("INSERT INTO test (id, name) VALUES (4, 'Rose')", engine=conn)+ yield conn+ conn.close()++[email protected](not HAS_DUCKDB, reason="DuckDB not installed")+def test_duckdb_engine_dialect() -> None:+ """Test DuckDBEngine dialect property."""+ engine = DuckDBEngine(None)+ assert engine.dialect == "duckdb"++[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_sqlalchemy_engine_dialect(sqlite_engine: sa.Engine) -> None:+ """Test SQLAlchemyEngine dialect property."""+ engine = SQLAlchemyEngine(sqlite_engine)+ assert engine.dialect == "sqlite"+++ not HAS_DUCKDB or not HAS_PANDAS, reason="DuckDB and Pandas not installed"+)+def test_duckdb_engine_execute(+ duckdb_connection: duckdb.DuckDBPyConnection,+) -> None:+ """Test DuckDBEngine execute with both connection and no connection."""+ import pandas as pd+ import polars as pl++ # Test with explicit connection+ engine = DuckDBEngine(duckdb_connection)+ result = _execute_query("SELECT * FROM test ORDER BY id", engine)+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ assert len(result) == 4+++ not HAS_SQLALCHEMY or not HAS_PANDAS,+ reason="SQLAlchemy and Pandas not installed",+)+def test_sqlalchemy_engine_execute(sqlite_engine: sa.Engine) -> None:+ """Test SQLAlchemyEngine execute."""+ import pandas as pd+ import polars as pl++ engine = SQLAlchemyEngine(sqlite_engine)+ result = _execute_query("SELECT * FROM test ORDER BY id", engine)+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ assert len(result) == 4+++ not HAS_DUCKDB or not HAS_SQLALCHEMY or not HAS_PANDAS,+ reason="Duckdb, sqlalchemy and pandas not installed",+)+def test_engine_compatibility() -> None:+ """Test engine compatibility checks."""+ import duckdb+ import sqlalchemy as sa++ mock_duckdb = MagicMock(spec=duckdb.DuckDBPyConnection)+ mock_sqlalchemy = MagicMock(spec=sa.Engine)++ assert DuckDBEngine.is_compatible(mock_duckdb)+ assert not DuckDBEngine.is_compatible(mock_sqlalchemy)+ assert SQLAlchemyEngine.is_compatible(mock_sqlalchemy)+ assert not SQLAlchemyEngine.is_compatible(mock_duckdb)+++def test_raise_df_import_error() -> None:+ """Test raise_df_import_error function."""+ with pytest.raises(ImportError):+ raise_df_import_error("test_pkg")diff --git a/tests/_sql/test_get_engines.py b/tests/_sql/test_get_engines.pynew file mode 100644index 0000000000..ffac683ab2--- /dev/null+++ b/tests/_sql/test_get_engines.py@@ -0,0 +1,115 @@+from __future__ import annotations++from unittest.mock import MagicMock++import pytest++from marimo._data.models import DataSourceConnection+from marimo._dependencies.dependencies import DependencyManager+from marimo._sql.engines import DuckDBEngine, SQLAlchemyEngine+from marimo._sql.get_engines import (+ engine_to_data_source_connection,+ get_engines_from_variables,+)++HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()+HAS_DUCKDB = DependencyManager.duckdb.has()+++def test_engine_to_data_source_connection():+ # Test with DuckDB engine+ duckdb_engine = DuckDBEngine(None)+ connection = engine_to_data_source_connection("my_duckdb", duckdb_engine)+ assert isinstance(connection, DataSourceConnection)+ assert connection.source == "duckdb"+ assert connection.dialect == "duckdb"+ assert connection.name == "my_duckdb"+ assert connection.display_name == "duckdb (my_duckdb)"++ # Test with SQLAlchemy engine+ mock_sqlalchemy_engine = MagicMock()+ mock_sqlalchemy_engine.dialect.name = "postgresql"+ sqlalchemy_engine = SQLAlchemyEngine(mock_sqlalchemy_engine)+ connection = engine_to_data_source_connection(+ "my_postgres", sqlalchemy_engine+ )+ assert isinstance(connection, DataSourceConnection)+ assert connection.source == "sqlalchemy"+ assert connection.dialect == "postgresql"+ assert connection.name == "my_postgres"+ assert connection.display_name == "postgresql (my_postgres)"++[email protected](not HAS_DUCKDB, reason="DuckDB not installed")+def test_get_engines_from_variables_duckdb():+ import duckdb++ mock_duckdb_conn = MagicMock(spec=duckdb.DuckDBPyConnection)+ variables: list[tuple[str, object]] = [("duckdb_conn", mock_duckdb_conn)]++ engines = get_engines_from_variables(variables)+ assert len(engines) == 1+ var_name, engine = engines[0]+ assert var_name == "duckdb_conn"+ assert isinstance(engine, DuckDBEngine)++[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_get_engines_from_variables_sqlalchemy():+ import sqlalchemy as sa++ mock_sqlalchemy_engine = MagicMock(spec=sa.Engine)+ variables: list[tuple[str, object]] = [+ ("sa_engine", mock_sqlalchemy_engine)+ ]++ engines = get_engines_from_variables(variables)+ assert len(engines) == 1+ var_name, engine = engines[0]+ assert var_name == "sa_engine"+ assert isinstance(engine, SQLAlchemyEngine)+++def test_get_engines_from_variables_mixed():+ variables: list[tuple[str, object]] = [+ ("not_an_engine", "some string"),+ ("another_not_engine", 42),+ ]++ engines = get_engines_from_variables(variables)+ assert len(engines) == 0+++ not (HAS_SQLALCHEMY and HAS_DUCKDB),+ reason="SQLAlchemy or DuckDB not installed",+)+def test_get_engines_from_variables_multiple():+ import duckdb+ import sqlalchemy as sa++ mock_sqlalchemy_engine = MagicMock(spec=sa.Engine)+ mock_duckdb_conn = MagicMock(spec=duckdb.DuckDBPyConnection)++ variables: list[tuple[str, object]] = [+ ("sa_engine", mock_sqlalchemy_engine),+ ("duckdb_conn", mock_duckdb_conn),+ ("not_an_engine", "some string"),+ ]++ engines = get_engines_from_variables(variables)+ assert len(engines) == 2++ # Check SQLAlchemy engine+ sa_var_name, _sa_engine = next(+ (name, eng)+ for name, eng in engines+ if isinstance(eng, SQLAlchemyEngine)+ )+ assert sa_var_name == "sa_engine"++ # Check DuckDB engine+ duckdb_var_name, _duckdb_engine = next(+ (name, eng) for name, eng in engines if isinstance(eng, DuckDBEngine)+ )+ assert duckdb_var_name == "duckdb_conn"diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.pyindex 7840dc9588..f99d9f5d46 100644--- a/tests/_sql/test_sql.py+++ b/tests/_sql/test_sql.py@@ -1,6 +1,9 @@+"""Tests for SQL functionality."""+from __future__ import annotationsimport os+from typing import TYPE_CHECKING, Generatorfrom unittest.mock import MagicMock, patchimport pytest@@ -9,18 +12,218 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins import uifrom marimo._sql.sql import _query_includes_limit, sql-HAS_DEPS = DependencyManager.duckdb.has() and DependencyManager.polars.has()+if TYPE_CHECKING:+ import duckdb+ import sqlalchemy as sa+++HAS_DUCKDB = DependencyManager.duckdb.has()+HAS_SQLALCHEMY = DependencyManager.sqlalchemy.has()+HAS_POLARS = DependencyManager.polars.has()+HAS_PANDAS = DependencyManager.pandas.has()+HAS_SQLGLOT = DependencyManager.sqlglot.has()+++def sqlite_engine() -> sa.Engine:+ """Create a temporary SQLite database for testing."""+ import sqlalchemy as sa++ engine = sa.create_engine("sqlite:///:memory:")+ sql(+ """+ CREATE TABLE test (+ id INTEGER PRIMARY KEY,+ name TEXT+ );+ """,+ engine=engine,+ )+ sql(+ """+ INSERT INTO test VALUES+ (1, 'Alice'),+ (2, 'Bob'),+ (3, 'Charlie');+ """,+ engine=engine,+ )+ return engine+++def duckdb_connection() -> Generator[duckdb.DuckDBPyConnection, None, None]:+ """Create a DuckDB connection for testing."""+ import duckdb++ conn = duckdb.connect(":memory:")+ sql(+ """+ CREATE TABLE test (+ id INTEGER PRIMARY KEY,+ name TEXT+ );+ """,+ engine=conn,+ )+ sql(+ """+ INSERT INTO test VALUES+ (1, 'Alice'),+ (2, 'Bob'),+ (3, 'Charlie');+ """,+ engine=conn,+ )++ yield conn+ conn.close()++[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_sql_with_different_engines(+ sqlite_engine: sa.Engine, duckdb_connection: duckdb.DuckDBPyConnection+) -> None:+ """Test sql function with different engines."""+ import pandas as pd+ import polars as pl++ # Test with SQLAlchemy engine+ result = sql("SELECT * FROM test ORDER BY id", engine=sqlite_engine)+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ assert len(result) == 3++ # Test with DuckDB connection+ result = sql("SELECT * FROM test ORDER BY id", engine=duckdb_connection)+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ assert len(result) == 3++ # Test with default DuckDB+ # df = pd.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})+ # with patch.dict(globals(), {"df": df}):+ # result = sql("SELECT * FROM df")+ # assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ # assert len(result) == 2+++def test_sql_with_invalid_engine() -> None:+ """Test sql function with invalid engine."""+ with pytest.raises(ValueError, match="Unsupported engine"):+ sql("SELECT 1", engine="invalid")++[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_empty_sql(+ sqlite_engine: sa.Engine, duckdb_connection: duckdb.DuckDBPyConnection+) -> None:+ result = sql("", engine=duckdb_connection)+ assert result is None++ result = sql("", engine=sqlite_engine)+ assert result is None++[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_invalid_sql(+ sqlite_engine: sa.Engine, duckdb_connection: duckdb.DuckDBPyConnection+) -> None:+ import duckdb+ import sqlalchemy++ with pytest.raises(duckdb.Error):+ sql("SELECT *", engine=duckdb_connection)+ with pytest.raises(sqlalchemy.exc.StatementError):+ sql("SELECT *", engine=sqlite_engine)[email protected](not HAS_DEPS, reason="polars and duckdb is required")-def test_query_includes_limit():- assert _query_includes_limit("SELECT * FROM t LIMIT 10") is True- assert _query_includes_limit("SELECT * FROM t LIMIT\n10") is True- assert _query_includes_limit("SELECT * FROM t limit 10") is True- assert _query_includes_limit("SELECT * FROM t limit\n10") is True- assert _query_includes_limit("SELECT * FROM t") is False- assert _query_includes_limit("INSERT INTO t VALUES (1, 2, 3)") is False- assert _query_includes_limit("") is False++# TODO[email protected](not HAS_PANDAS, reason="Pandas not installed")+def test_sql_with_limit() -> None:+ """Test sql function respects LIMIT clause and environment variable."""+ import pandas as pd++ _df = pd.DataFrame(+ {"id": range(10), "name": [f"User{i}" for i in range(10)]}+ )++ # Test with explicit LIMIT+ # with patch.dict(globals(), {"df": df}):+ # result = sql("SELECT * FROM df LIMIT 5")+ # assert len(result) == 5++ # Test with environment variable limit+ # with patch.dict(os.environ, {"MARIMO_SQL_DEFAULT_LIMIT": "3"}):+ # with patch.dict(globals(), {"df": df}):+ # result = sql("SELECT * FROM df")+ # assert len(result) == 3++[email protected](not HAS_PANDAS, reason="Pandas not installed")+def test_sql_output_formatting() -> None:+ """Test sql function output formatting."""+ import pandas as pd++ # import polars as pl++ _df = pd.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})++ # Test with output=False+ # with patch.dict(globals(), {"df": df}):+ # result = sql("SELECT * FROM df", output=False)+ # assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ # assert len(result) == 2++ # Test with output=True (mock replace function)+ # with patch("marimo._runtime.output.replace") as mock_replace:+ # with patch.dict(globals(), {"df": df}):+ # sql("SELECT * FROM df", output=True)+ # mock_replace.assert_called_once()+++ reason="Multiple select statements are not supported for sqlite"+)[email protected](not HAS_SQLALCHEMY, reason="SQLAlchemy not installed")+def test_sql_multiple_statements(sqlite_engine: sa.Engine) -> None:+ import pandas as pd+ import polars as pl++ multi_statement = """+ SELECT 1, 2;+ SELECT 3, 4;+ """+ result = sql(multi_statement, engine=sqlite_engine)+ assert isinstance(result, (pd.DataFrame, pl.DataFrame))+ assert len(result) == 2++[email protected](not HAS_SQLGLOT, reason="sqlglot not installed")+def test_query_includes_limit() -> None:+ """Test _query_includes_limit function."""+ # Test queries with LIMIT+ assert _query_includes_limit("SELECT * FROM table LIMIT 5")+ assert _query_includes_limit("SELECT * FROM table LIMIT\n5")+ assert _query_includes_limit("SELECT * FROM table limit\n5")+ assert _query_includes_limit(+ """+ SELECT *+ FROM table+ LIMIT 5+ """+ )++ # Test queries without LIMIT+ assert not _query_includes_limit("SELECT * FROM table")+ assert not _query_includes_limit("SELECT LIMIT_COL FROM table")+ assert not _query_includes_limit("-- LIMIT 5\nSELECT * FROM table")++ # Test invalid SQL+ assert not _query_includes_limit("NOT A VALID SQL QUERY")+ assert not _query_includes_limit("")+ assert not _query_includes_limit("INSERT INTO t VALUES (1, 2, 3)")++ # Multiple queriesassert (_query_includes_limit("SELECT * FROM t; SELECT * FROM t2 LIMIT 5")is True@@ -32,12 +235,11 @@ def test_query_includes_limit():@patch("marimo._sql.sql.replace")[email protected](not HAS_DEPS, reason="polars and duckdb is required")[email protected](not HAS_POLARS and HAS_DUCKDB, reason="polars is required")def test_applies_limit(mock_replace: MagicMock) -> None:import duckdb- try:- os.environ["MARIMO_SQL_DEFAULT_LIMIT"] = "300"+ with patch.dict(os.environ, {"MARIMO_SQL_DEFAULT_LIMIT": "300"}):duckdb.sql("CREATE OR REPLACE TABLE t AS SELECT * FROM range(1000)")mock_replace.assert_not_called()@@ -72,20 +274,18 @@ def test_applies_limit(mock_replace: MagicMock) -> None:assert len(table._data) == 400assert table._searched_manager.get_num_rows() == 400- # Limit above 20_0000 (which is the mo.ui.table cutoff)- mock_replace.reset_mock()- duckdb.sql(- "CREATE OR REPLACE TABLE big_table AS SELECT * FROM range(30_000)"- )- assert len(sql("SELECT * FROM big_table LIMIT 25_000")) == 25_000- mock_replace.assert_called_once()- table = mock_replace.call_args[0][0]- assert table._component_args["total-rows"] == 25_000- assert table._component_args["pagination"] is True- assert len(table._data) == 25_000- assert table._searched_manager.get_num_rows() == 25_000- finally:- del os.environ["MARIMO_SQL_DEFAULT_LIMIT"]+ # Limit above 20_0000 (which is the mo.ui.table cutoff)+ mock_replace.reset_mock()+ duckdb.sql(+ "CREATE OR REPLACE TABLE big_table AS SELECT * FROM range(30_000)"+ )+ assert len(sql("SELECT * FROM big_table LIMIT 25_000")) == 25_000+ mock_replace.assert_called_once()+ table = mock_replace.call_args[0][0]+ assert table._component_args["total-rows"] == 25_000+ assert table._component_args["pagination"] is True+ assert len(table._data) == 25_000+ assert table._searched_manager.get_num_rows() == 25_000@pytest.mark.skipif(@@ -97,7 +297,7 @@ def test_sql_raises_error_without_duckdb():@patch("marimo._sql.sql.replace")[email protected](not HAS_DEPS, reason="polars and duckdb is required")[email protected](not HAS_POLARS and HAS_DUCKDB, reason="polars is required")def test_sql_output_flag(mock_replace: MagicMock) -> None:import duckdbimport polars as pl