Notebook cells that know what they depend on
Named cells, {{references}} folded into one query as CTEs, fingerprints that mark results out of date, and run modes that work out the order for you.
The first version of SQLly's notebook ran your cells top to bottom and stopped at the first error. That's how a script works, and it's fine until the notebook gets long. Then you change the base query in cell three, forget that cell nine reads it, and stare at a chart that's quietly showing the old numbers.
The new notebook knows which cells read which. This post is about how it knows, what it does with that, and the places where it still doesn't know enough. It's the second in a series about SQLly notebooks.
The revenue notebook from this post: the Lineage rail, an edit to orders, three cells going Out of date while prod_totals doesn't, then Run Stale Cells. Recorded in the app. Watch the whole recording, with chapters.
A name turns a cell into something you can query
Select a cell, type a name like orders in the inspector, and any other SQL cell can read its result by writing the name in double curly braces:
-- cell "orders"
SELECT o.OrderID, o.CustomerID, o.ShipCountry, o.Freight
FROM dbo.Orders AS o
WHERE YEAR(o.OrderDate) >= 1997
-- another cell
SELECT ShipCountry, SUM(Freight) AS Freight
FROM {{orders}}
GROUP BY ShipCountry
Names follow identifier rules: a letter or underscore first, then letters, digits and underscores, unique in the notebook and not case-sensitive. SQL reserved words are refused, and so is param, because parameters use {{param.region}}. Every cell also has an id like c_qm4tz7a2kd, and {{c_qm4tz7a2kd}} works too. Rename a cell and SQLly rewrites every {{old_name}} in the other SQL and Markdown cells, and the formulas that name it. References by id never need rewriting.
Most references become one query
When both cells are on the same connection and the referenced cell is a single read-only query, SQLly folds it into the reading cell as a common table expression and sends one query. Nothing is copied out of the database, and the optimizer sees the whole thing.
That sounds simple. It mostly is on PostgreSQL, MySQL, MariaDB, SQLite and Oracle, which allow a WITH nested inside a CTE, so the referenced query goes in whole. SQL Server doesn't allow that. So SQLly lifts the referenced query's own CTEs up into the outer WITH list. If two of them would end up with the same name, or one would hide a table the query uses, it refuses with a message and asks you to rename one. I'd rather it refuse than guess. A trailing ORDER BY without TOP or OFFSET gets dropped because it means nothing inside a CTE, and a query ending in FOR XML, FOR JSON or FOR BROWSE can't be folded at all.
References inside strings, comments, quoted identifiers and dollar-quoted bodies are ignored, so '{{orders}}' stays text. The first version used a hand-rolled WITH parser for all this. The new one is tested with randomized CTE chains on four engines, which made me less nervous about it. It still has rough spots, which are in the last section.
One gotcha bit my own test suite. An end-to-end test of the command-line runner named a cell orders, and that cell read FROM orders. Fold it into another cell and you get a CTE called orders that reads from orders, which is itself. SQLite refused it as a circular reference. Nothing warns you about this yet, so for now: name cells differently from tables. Call it recent_orders.
To see the folded SQL, Export ▸ Convert to SQL Script writes the notebook out as one script with references expanded where they can be.
Out of date means something specific
Each cell's result is tied to a fingerprint of everything that produced it. When any part changes, the cell and every cell that reads it are marked Out of date. The result stays on screen, but it's never presented as current. The parts are:
- The SQL, compared token by token. Whitespace, keyword case and ordinary comments don't count. Changing a value, an optimizer hint or a
-- sqllydirective does. - The parameters the cell uses, by their typed values. Change one parameter and only the cells that use it go stale, plus whatever reads them.
- The connection: which one, the database, the engine, the login it signs in with, and its safety settings like read-only and masking. A result fetched by one login is never current for another.
- The cell's own policy: read-only, row and download limits, cache mode and session group.
- The fingerprints of the cells it reads.
A side effect: undo an edit and the result is current again, because the fingerprint matches once more. You don't have to re-run a query because you typed a character and deleted it.
Run modes say how much, SQLly works out the order
Once the notebook knows the graph, running is less about order and more about scope. The Run menu has Run Cell, Run Cell and Stale Inputs, Run All, Run Stale Cells, Run Cell and Dependents, Run Cells Above, Run Cell and Below, Run Selected Cells, and Check Without Running, which checks references, cycles, parameters and safety and runs nothing.
Two details I care about. When a run pulls in a cell you didn't ask for, an input of the one you did, SQLly reuses its result if it's still current and says "Kept the current result" in the activity panel. A cell you ask for by name always runs. And the top bar's Mode switch can make ⌘Return mean "this cell and its out-of-date inputs", so you don't have to remember which inputs you touched.
One broken query doesn't stop the rest
This is the biggest change from the first version. A failed cell now blocks only the cells that depend on it. Independent cells in the same run keep going, and each blocked cell names the cell it was waiting for. Fix the broken one, press Run Stale Cells, and everything that was blocked runs.
Cells that don't depend on each other also run at the same time: up to two at once per connection by default, which you can set from 1 to 4, and two at once on the notebook's local data. Each cell has its own query, so one cell's error never cancels another. A cell that changes data runs alone on its connection, cells sharing a session_group run one at a time on one database session so temp tables carry over, and nothing new starts while a change review is waiting for you.
If you manage to make two cells read each other, SQLly reports the whole loop and suggests which reference to drop: "These cells depend on each other in a loop: by_country → orders → by_country". Cells on or behind the loop are blocked. Everything else still runs.
Where it falls short
A reading cell can start with setup statements like SET NOCOUNT ON, DECLARE or a GO batch, and the referenced queries go in front of the statement that uses them. But all of a cell's references have to sit in that one statement. Spread them over two and SQLly refuses with a message. A reference between cells on different connections can't be folded into one query, so the reading cell has to run on the notebook's local DuckDB data instead, which is the fourth post. And a cell's download size limit isn't counted once a result has started spilling to disk. Its row limit still holds there.
Next up is parameters, which is where the fingerprint pays off: change one input and only the cells that use it go stale. The full reference is on Named cells and references and Running notebooks. If a fold turns your SQL into something your database rejects, send me the two cells.