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
docs: sql docs and tutorial, loosen variable name lowercase (#1762)
Myles Scolnick23b296f609fe
diff --git a/docs/_static/docs-sql-cell.png b/docs/_static/docs-sql-cell.pngnew file mode 100644index 0000000000..cf9d9a9fa2Binary files /dev/null and b/docs/_static/docs-sql-cell.png differdiff --git a/docs/_static/docs-sql-df.png b/docs/_static/docs-sql-df.pngnew file mode 100644index 0000000000..7197123a4aBinary files /dev/null and b/docs/_static/docs-sql-df.png differdiff --git a/docs/_static/docs-sql-http.png b/docs/_static/docs-sql-http.pngnew file mode 100644index 0000000000..816df34451Binary files /dev/null and b/docs/_static/docs-sql-http.png differdiff --git a/docs/apps/sql.py b/docs/apps/sql.pynew file mode 100644index 0000000000..e39181199d--- /dev/null+++ b/docs/apps/sql.py@@ -0,0 +1,34 @@+import marimo++__generated_with = "0.7.1"+app = marimo.App(width="medium")+++def __(mo):+ cars = mo.sql(+ f"""+ -- Download a CSV and create an in-memory table+ CREATE OR replace TABLE cars as+ FROM 'https://datasets.marimo.app/cars.csv';+ SELECT Make, Model, Cylinders, Weight, MPG_City from cars;+ """+ )+ return cars,+++def __(cars):+ # We can reference the output variable as a dataframe in python+ [len(cars), cars["MPG_City"].mean()]+ return++[email protected](hide_code=True)+def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()diff --git a/docs/guides/index.md b/docs/guides/index.mdindex ea8b3ef121..474ebb4cf2 100644--- a/docs/guides/index.md+++ b/docs/guides/index.md@@ -15,6 +15,7 @@hotkeysdataframesplotting+ sqlstateintegrating_with_marimo/indexappsdiff --git a/docs/guides/sql.md b/docs/guides/sql.mdnew file mode 100644index 0000000000..7ee9b5bbc8--- /dev/null+++ b/docs/guides/sql.md@@ -0,0 +1,65 @@+# SQL++With marimo, you can mix-and-match both **Python and SQL**. To create a SQL cell, you first need to install our SQL query engine of choice: [duckdb](https://duckdb.org/).++```bash+pip install duckdb+```++This will enable SQL cells in your notebook. Once you've installed `duckdb`, you can create a SQL cell by right-clicking an **Add Cell** button and choosing "SQL cell", by converting an empty cell to SQL via the cell context menu, or via the SQL button that appears when you mouse hover at the bottom of your notebook.++<div align="center">+ <figure>+ <img src="/_static/docs-sql-cell.png"/>+ <figcaption>Add SQL Cell</figcaption>+ </figure>+</div>++This creates a "**SQL**" cell for you, while in reality this is actually Python code. Since we store marimo files as pure Python files, the translated code looks like:++```python+output_df = mo.sql(f"SELECT * FROM my_table LIMIT {max_rows.value}")+```++Notice that we have an **`output_df`** variable in the cell. This is a resulting Polars DataFrame (if you have `polars` installed) or a Pandas DataFrame (if you don't). One of them must be installed in order to interact with the SQL result.++The SQL statement itself is an formatted string (f-string), so this means they can contain any valid Python code, such as the values of UI elements. This means your SQL statement and results can be reactive! 🚀++## Reference a local dataframe++You can reference a local dataframe in your SQL cell by using the name of the Python variable that holds the dataframe. If you have a database connection with a table of the same name, the database table will be used instead.++<div align="center">+ <figure>+ <img src="/_static/docs-sql-df.png"/>+ <figcaption>Reference a dataframe</figcaption>+ </figure>+</div>++Since the output dataframe variable (`_df`) has an underscore, making it private, it is not referenceable from other cells.++## Reference the output of a SQL cell++Defining a non-private (non-underscored) output variable in the SQL cell allows you to reference the resulting dataframe in other Python and SQL cells.++<div align="center">+ <figure>+ <img src="/_static/docs-sql-http.png"/>+ <figcaption>Reference the SQL result</figcaption>+ </figure>+</div>++## Querying files, databases, and APIs++In the above example, you may have noticed we queried an HTTP endpoint instead of a local dataframe. We are not only limited to querying local dataframes; we can also query files, databases, and APIs:++```sql+-- or+SELECT * FROM 's3://my-bucket/file.parquet';+-- or+SELECT * FROM read_csv('path/to/example.csv');+-- or+SELECT * FROM read_parquet('path/to/example.parquet');+```++For a full list you can check out the [duckdb extensions](https://duckdb.org/docs/extensions/overview).diff --git a/frontend/public/files/wasm-intro.py b/frontend/public/files/wasm-intro.pyindex 65aa8ada36..10f46022db 100644--- a/frontend/public/files/wasm-intro.py+++ b/frontend/public/files/wasm-intro.py@@ -337,7 +337,11 @@ def __(mo):- `markdown`: how to write markdown, with interpolated values andLaTeX- `plots`: how plotting works in marimo+ - `sql`: how to use SQL+ - `layout`: layout elements in marimo- `fileformat`: how marimo's file format works+ - `markdown-format`: for using `.md` files in marimo+ - `for-jupyter-users`: if you are coming from JupyterStart a tutorial with `marimo tutorial`; for example,diff --git a/frontend/src/core/cells/__tests__/names.test.ts b/frontend/src/core/cells/__tests__/names.test.tsindex 65cbdbea05..c41f2c1dc2 100644--- a/frontend/src/core/cells/__tests__/names.test.ts+++ b/frontend/src/core/cells/__tests__/names.test.ts@@ -22,6 +22,10 @@ describe("normalizeName", () => {expect(normalizeName("Some name 10")).toBe("some_name_10");expect(normalizeName("10 names")).toBe("_10_names");});++ it("should remove special characters and not make lowercase", () => {+ expect(normalizeName("Test Name!", false)).toBe("Test_Name_");+ });});describe("getValidName", () => {diff --git a/frontend/src/core/cells/names.ts b/frontend/src/core/cells/names.tsindex 9b4d63ccbf..f7e079413b 100644--- a/frontend/src/core/cells/names.ts+++ b/frontend/src/core/cells/names.ts@@ -49,7 +49,7 @@ const DISALLOWED_NAMES = new Set([/*** Make's name pythonic - removes spaces, special characters and makes lowercase*/-export function normalizeName(name: string) {+export function normalizeName(name: string, lowercase = true): string {name = name.trim();if (!name) {return DEFAULT_CELL_NAME;@@ -58,7 +58,8 @@ export function normalizeName(name: string) {if (/^\d/.test(name)) {name = `_${name}`;}- return name.replaceAll(/\W/g, "_").toLowerCase();+ name = name.replaceAll(/\W/g, "_");+ return lowercase ? name.toLowerCase() : name;}/**diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsxindex 44d0e1e479..c35e8ea156 100644--- a/frontend/src/core/codemirror/language/panel.tsx+++ b/frontend/src/core/codemirror/language/panel.tsx@@ -19,7 +19,7 @@ export const LanguagePanelComponent: React.FC<{onChange={(e) => (languageAdapter.dataframeName = e.target.value)}onBlur={(e) => {// Normalize the name to a valid variable name- const name = normalizeName(e.target.value);+ const name = normalizeName(e.target.value, false);languageAdapter.dataframeName = name;e.target.value = name;diff --git a/frontend/src/plugins/layout/StatPlugin.tsx b/frontend/src/plugins/layout/StatPlugin.tsxindex 389140ac0a..b1f626fc11 100644--- a/frontend/src/plugins/layout/StatPlugin.tsx+++ b/frontend/src/plugins/layout/StatPlugin.tsx@@ -4,9 +4,10 @@ import { z } from "zod";import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";import { TriangleIcon } from "lucide-react";import { cn } from "@/utils/cn";+import { prettyNumber } from "@/utils/numbers";interface Data {- value: string;+ value?: string | number | boolean | null;label?: string;caption?: string;bordered?: boolean;@@ -17,7 +18,7 @@ export class StatPlugin implements IStatelessPlugin<Data> {tagName = "marimo-stat";validator = z.object({- value: z.string(),+ value: z.union([z.string(), z.number(), z.boolean()]).optional(),label: z.string().optional(),caption: z.string().optional(),bordered: z.boolean().default(false),@@ -36,6 +37,26 @@ export const StatComponent: React.FC<Data> = ({bordered,direction,}) => {+ const renderPrettyValue = () => {+ if (value == null) {+ return <i>No value</i>;+ }++ if (typeof value === "string") {+ return value;+ }++ if (typeof value === "number") {+ return prettyNumber(value);+ }++ if (typeof value === "boolean") {+ return value ? "True" : "False";+ }++ return String(value);+ };+return (<divclassName={cn(@@ -49,7 +70,7 @@ export const StatComponent: React.FC<Data> = ({</div>)}<div className="p-6 pt-0">- <div className="text-2xl font-bold">{value}</div>+ <div className="text-2xl font-bold">{renderPrettyValue()}</div>{caption && (<p className="pt-1 text-xs text-muted-foreground flex align-center">{direction === "increase" && (diff --git a/marimo/_tutorials/__init__.py b/marimo/_tutorials/__init__.pyindex 563b063361..00b34b425f 100644--- a/marimo/_tutorials/__init__.py+++ b/marimo/_tutorials/__init__.py@@ -12,6 +12,7 @@ PythonTutorial = Literal["ui","markdown","plots",+ "sql","layout","fileformat","for-jupyter-users",@@ -25,6 +26,7 @@ tutorial_order: list[Tutorial] = ["ui","markdown","plots",+ "sql","layout","fileformat","markdown-format",diff --git a/marimo/_tutorials/intro.py b/marimo/_tutorials/intro.pyindex cca55353f9..e08909ff5b 100644--- a/marimo/_tutorials/intro.py+++ b/marimo/_tutorials/intro.py@@ -310,7 +310,11 @@ def __(mo):- `markdown`: how to write markdown, with interpolated values andLaTeX- `plots`: how plotting works in marimo+ - `sql`: how to use SQL+ - `layout`: layout elements in marimo- `fileformat`: how marimo's file format works+ - `markdown-format`: for using `.md` files in marimo+ - `for-jupyter-users`: if you are coming from JupyterStart a tutorial with `marimo tutorial`; for example,diff --git a/marimo/_tutorials/sql.py b/marimo/_tutorials/sql.pynew file mode 100644index 0000000000..beb943d068--- /dev/null+++ b/marimo/_tutorials/sql.py@@ -0,0 +1,361 @@+import marimo++__generated_with = "0.7.1"+app = marimo.App()++[email protected](hide_code=True)+def __(mo):+ mo.md(+ r"""+ # Hello, SQL!++ _Let's dive into the world of SQL where we don't just address tables, we also join them!_+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ r"""+ With marimo, you can mix-and-match both **Python and SQL**. To create a SQL cell, you first need to install our SQL query engine of choice: [duckdb](https://duckdb.org/).++ ```bash+ pip install duckdb+ ```++ Or if you `import duckdb` in any SQL cell, marimo will automatically install it for you.+ """+ )+ return++[email protected](hide_code=True)+def __():+ has_duckdb_installed = False+ try:+ import duckdb++ has_duckdb_installed = True+ except ImportError:+ pass++ has_polars_installed = False+ try:+ import polars++ has_polars_installed = True+ except ImportError:+ pass++ has_pandas_installed = False+ try:+ import pandas++ has_pandas_installed = True+ except ImportError:+ pass+ return (+ duckdb,+ has_duckdb_installed,+ has_pandas_installed,+ has_polars_installed,+ pandas,+ polars,+ )++[email protected](hide_code=True)+def __(has_duckdb_installed, mo):+ if has_duckdb_installed:+ mo.output.replace(+ mo.md(+ """+ !!! Tip "Installed"+ If you see this, it means DuckDB is already installed.+ """+ )+ )+ else:+ mo.output.replace(+ mo.md(+ """+ !!! Warning "Not Installed"+ If you see this, it means DuckDB is not installed.+ """+ )+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ r"""+ Once installed, you can either right-click the **Add Cell** buttons on the left, or click the **Add SQL Cell** at the bottom of the page. This creates a '**SQL**' cell for you, while in reality this is actually Python code.++ For example, since we store marimo files as pure Python files, the translated code looks like:++ ```python+ output_df = mo.sql(f"SELECT * FROM my_table LIMIT {max_rows.value}")+ ```++ Notice that we have an **`output_df`** variable in the cell. This is a resulting Polars DataFrame (if you have `polars` installed) or a Pandas DataFrame (if you don't). One of them must be installed in order to interact with the SQL result.++ The SQL statement itself is an formatted string (f-string), so this means they can contain any valid Python code, such as the values of UI elements. This means your SQL statement and results can be reactive! 🚀++ Let's take a look at a SQL cell. First we will create a dataframe+ """+ )+ return++[email protected](hide_code=True)+def __(has_polars_installed, random):+ _SIZE = 20+ # Try polars+ if has_polars_installed:+ import polars as pl++ df = pl.DataFrame(+ {+ "a": [random.randint(0, 1000) for _ in range(_SIZE)],+ "b": [random.randint(0, 1000) for _ in range(_SIZE)],+ }+ )+ # Fallback to pandas (maybe trying to install it)+ else:+ import pandas as pd++ df = pd.DataFrame(+ {+ "a": [random.randint(0, 1000) for _ in range(_SIZE)],+ "b": [random.randint(0, 1000) for _ in range(_SIZE)],+ }+ )+ return df, pd, pl+++def __(df, mo):+ _df = mo.sql(+ f"""+ -- This SQL cell is special since we can reference existing dataframes in the global scope as a table in the SQL query. For example, we can reference the `df` dataframe in the global scope, which was defined in another cell using Python.++ SELECT * FROM df;++ -- Since the output dataframe variable (`_df`) has an underscore, making it private, it is not referenceable from other cells.+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(r"Let's look at another SQL statement, but this time with a UI element")+ return++[email protected](hide_code=True)+def __(df, mo):+ max_b_value = mo.ui.slider(+ start=df["b"].min(),+ stop=df["b"].max(),+ value=df["b"].max(),+ label="Max $b$",+ debounce=True,+ )+ max_b_value+ return max_b_value,+++def __(df, max_b_value, mo):+ result = mo.sql(+ f"""+ -- Move the slider's value down in order to see the SQL query filter itself+ SELECT * FROM df+ WHERE b < {max_b_value.value}+ """+ )+ return result,+++def __(mo):+ mo.md(+ r"""+ Since we named the output dataframe above **`result`**,+ we can reference this back in Python+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ charting_library = mo.ui.radio(["matplotlib", "altair", "plotly"])++ mo.md(+ f"""+ Let's chart the result with a library of your choice:++ {charting_library}+ """+ )+ return charting_library,++[email protected](hide_code=True)+def __(charting_library, max_b_value, mo, render_chart):+ _header = mo.md(+ f"""+ We can re-use the slider from above: {max_b_value}++ Now we have a plot powered by your previous SQL query and your UI elements.+ """+ )++ render_chart(+ charting_library.value, _header+ ) if charting_library.value else None+ return++[email protected](hide_code=True)+def __(mo, result):+ def render_chart(charting_library, header):+ return mo.vstack(+ [header, render_charting_library(charting_library)]+ ).center()+++ def render_charting_library(charting_library):+ if charting_library == "matplotlib":+ return render_matplotlib()+ if charting_library == "altair":+ return render_altair()+ if charting_library == "plotly":+ return render_plotly()+++ def render_matplotlib():+ import matplotlib.pyplot as plt++ plt.scatter(result["a"], result["b"])+ return plt.gcf()+++ def render_altair():+ import altair as alt++ chart = alt.Chart(result).mark_point().encode(x="a", y="b")+ return mo.ui.altair_chart(chart)+++ def render_plotly():+ import plotly.express as px++ fig = px.scatter(result, x="a", y="b")+ return mo.ui.plotly(fig)+ return (+ render_altair,+ render_chart,+ render_charting_library,+ render_matplotlib,+ render_plotly,+ )++[email protected](hide_code=True)+def __(mo):+ mo.md(+ r"""+ We are not only limited to querying dataframes that we have created or pulled in.+ We can additionally query by an **HTTP URL, S3 path, or a file path to a local csv or parquet file**.++ ```sql+ -- or+ SELECT * FROM 's3://my-bucket/file.parquet';+ -- or+ SELECT * FROM read_csv('path/to/example.csv');+ -- or+ SELECT * FROM read_parquet('path/to/example.parquet');+ ```++ For a full list you can check out the [duckdb extensions](https://duckdb.org/docs/extensions/overview).++ For this example, we will query an HTTP endpoint of a csv.+ """+ )+ return+++def __(mo):+ cars = mo.sql(+ f"""+ -- Download a CSV and create an in-memory table+ CREATE OR replace TABLE cars as+ FROM 'https://datasets.marimo.app/cars.csv';+ SELECT * from cars;+ """+ )+ return cars,++[email protected](hide_code=True)+def __(cars, mo):+ cylinders_dropdown = mo.ui.range_slider.from_series(+ cars["Cylinders"], debounce=True, show_value=True+ )+ origin_dropdown = mo.ui.dropdown.from_series(cars["Origin"], value="Asia")+ mo.hstack([cylinders_dropdown, origin_dropdown]).left()+ return cylinders_dropdown, origin_dropdown+++def __(cylinders_dropdown, mo, origin_dropdown):+ filtered_cars = mo.sql(+ f"""+ SELECT * FROM cars+ WHERE+ Cylinders >= {cylinders_dropdown.value[0]}+ AND+ Cylinders <= {cylinders_dropdown.value[1]}+ AND+ ORIGIN = '{origin_dropdown.value}'+ """+ )+ return filtered_cars,++[email protected](hide_code=True)+def __(filtered_cars, mo):+ mo.hstack(+ [+ mo.stat(label="Total cars", value=str(len(filtered_cars))),+ mo.stat(+ label="Average MPG Highway",+ value=f"{filtered_cars['MPG_Highway'].mean() or 0:.1f}",+ ),+ mo.stat(+ label="Average MPG City",+ value=f"{filtered_cars['MPG_City'].mean() or 0:.1f}",+ ),+ ]+ )+ return++[email protected](hide_code=True)+def __():+ import marimo as mo+ import random+ return mo, random+++if __name__ == "__main__":+ app.run()