On this page
The short answerDecide what each SQL block promisesWalk through a page and a small runnerTest the actual dialectWhat the engine seesMake SQL checks repeatableWhere DocsAlive fitsThe sources we checkedFAQThe short answer
Run SQL examples against a deliberately chosen database, in the order a reader follows, and check important results as well as syntax. In engine 0.6.3, DocsAlive skips fences labeled sql as not executable; dialect labels such as postgresql, sqlite, and psql can be reported as passing without a check. Use sql labels with your own SQL runner, or teach with executable Python sqlite3 blocks or Python interactive sessions where that fits.
SQL in documentation is often a sequence rather than a collection of independent statements. A schema creates the objects, sample data gives a query something to find, and a later migration changes the state. Testing only the final query against an unrelated database can miss a broken setup step. Testing only syntax can miss a changed result.
A database also has a dialect and version. A passing SQLite example is useful evidence for SQLite; it is not proof that PostgreSQL or MySQL will accept the same statement or enforce the same types. This guide uses a small SQLite runner to make those boundaries explicit, then describes how to add a PostgreSQL check.
Decide what each SQL block promises
Documentation may contain table definitions, sample inserts, queries with displayed results, migrations, and dialect-specific features. A renamed column can break a query after a schema update. A migration may work only after an earlier step. A result table can become stale after sample data changes. A typo can remain published indefinitely if nothing executes the fence.
Classify the blocks before choosing a test:
| Block | What to check |
|---|---|
| Setup | Run in order against a fresh database and confirm the documented prerequisites. |
| Query with expected rows | Execute after setup and assert the relevant values, order, or count. |
| Dialect-only SQL | Run against the named database and version, or record an explicit coverage gap. |
| Illustrative SQL | Make clear what is omitted and review it in context; do not claim it was executed. |
A row-count assertion is useful but limited. Two result sets can have the same count and different values. For examples where exact values or ordering are part of the lesson, add assertions for them in your own runner. Make an ORDER BY explicit when the displayed order matters.
Walk through a page and a small runner
Imagine that the next five SQL fences appear in order on docs/orders.md. They form one reader journey: create tables, insert data, query it, run another query, and then show a PostgreSQL-only operation. The addresses use a fictional domain.
The first fence creates the schema. A fresh database per page helps reveal dependencies that the page never establishes.
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
total_cents INTEGER NOT NULL
);
The second fence adds sample rows. Later queries rely on this data and therefore need to run after it.
INSERT INTO customers (email) VALUES ('ada@acme-docs-demo.test'), ('lin@acme-docs-demo.test');
INSERT INTO orders (customer_id, total_cents) VALUES (1, 1200), (1, 800), (2, 500);
The third fence asks for each customer's total and declares an expected row count. The comment convention belongs to the runner in this guide only; it is not a standard SQL test instruction or a DocsAlive feature.
-- expect: 2 rows
SELECT c.email, SUM(o.total_cents) AS spend_cents
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.email
ORDER BY spend_cents DESC;
The fourth fence is broken on purpose: the first SQL keyword is misspelled. A runner should surface the failure at this location.
-- expect: 1 row
SELEC id FROM orders WHERE total_cents > 1000;
The fifth fence illustrates a PostgreSQL-only locking form. The SQLite runner below skips it. Its skip comment is another convention belonging to this script only; a separate PostgreSQL check is needed to cover the statement.
-- docs: skip (PostgreSQL only)
SELECT id FROM orders WHERE total_cents > 1000 FOR UPDATE SKIP LOCKED;
The following script extracts sql fences, runs each page against a fresh in-memory SQLite database, and preserves fence order within that page. It checks an expected row count when the first line contains its expectation comment, and skips blocks whose first line uses its skip comment. It reports errors with a page and line number.
"""Run the ```sql fences of each Markdown page, in order, against a fresh SQLite database."""
import pathlib
import re
import sqlite3
import sys
FENCE = re.compile(r"^(`{3,}|~{3,})\s*(\w*)")
EXPECT = re.compile(r"^--\s*expect:\s*(\d+)\s+rows?\s*$", re.I)
def sql_blocks(path):
lines = path.read_text(encoding="utf-8").splitlines()
i = 0
while i < len(lines):
m = FENCE.match(lines[i].strip())
if not m:
i += 1
continue
fence, lang, start, body = m.group(1), m.group(2).lower(), i + 1, []
i += 1
while i < len(lines) and not lines[i].strip().startswith(fence):
body.append(lines[i])
i += 1
i += 1
if lang == "sql":
yield start, "\n".join(body)
def check_page(path):
con = sqlite3.connect(":memory:")
failures = 0
for line, code in sql_blocks(path):
first = code.strip().splitlines()[0] if code.strip() else ""
if first.lower().startswith("-- docs: skip"):
print(f"{path}:{line}: skipped ({first})")
continue
expect = EXPECT.match(first)
try:
if expect:
rows = con.execute(code).fetchall()
if len(rows) != int(expect.group(1)):
raise AssertionError(f"expected {expect.group(1)} rows, got {len(rows)}")
else:
con.executescript(code)
print(f"{path}:{line}: ok")
except (sqlite3.Error, AssertionError) as exc:
failures += 1
print(f"{path}:{line}: FAIL {type(exc).__name__}: {exc}")
con.close()
return failures
pages = [pathlib.Path(p) for p in sys.argv[1:]] or sorted(pathlib.Path("docs").rglob("*.md"))
total = sum(check_page(p) for p in pages)
print(f"{total} failing SQL block(s)")
sys.exit(1 if total else 0)
This is a deliberately small runner. It recognizes a limited fence form, counts rows rather than comparing their contents, and is designed for the examples shown. Extend or replace it for your Markdown dialect, transaction requirements, fixtures, result assertions, and database versions. Do not silently turn a skip into a claim of coverage.
Run it against the example page:
python3 scripts/run_sql_fences.py docs/orders.md
The checked run found the deliberate typo and recorded the PostgreSQL-only block as skipped. The displayed line numbers describe this example page.
docs/orders.md:5: ok
docs/orders.md:16: ok
docs/orders.md:23: ok
docs/orders.md:34: FAIL OperationalError: near "SELEC": syntax error
docs/orders.md:39: skipped (-- docs: skip (PostgreSQL only))
1 failing SQL block(s)
Replace the broken fourth fence with this corrected version, then rerun the page. This fixes the typo; it does not test the separately skipped locking statement.
-- expect: 1 row
SELECT id FROM orders WHERE total_cents > 1000;
Understand SQLite's typing boundary
SQLite uses flexible typing in ordinary tables. A value that cannot be converted to an integer can still be stored in a column declared as integer. STRICT tables apply stronger type rules. The following Python example demonstrates the distinction using an in-memory database.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE loose (qty INTEGER)")
con.execute("INSERT INTO loose VALUES ('three')")
print("loose table accepted:", con.execute("SELECT qty, typeof(qty) FROM loose").fetchone())
con.execute("CREATE TABLE tight (qty INTEGER) STRICT")
try:
con.execute("INSERT INTO tight VALUES ('three')")
except sqlite3.Error as exc:
print("STRICT table rejected:", exc)
The observed output shows the ordinary table storing text and the strict table rejecting it. Treat this as a demonstration of SQLite behavior, not a substitute for a PostgreSQL test.
loose table accepted: ('three', 'text')
STRICT table rejected: cannot store TEXT value in INTEGER column tight.qty
For a short teaching example, a Python interactive session can make both the operations and their expected printed results explicit. The following session passes Python's doctest and the engine's interactive-session check.
>>> import sqlite3
>>> con = sqlite3.connect(":memory:")
>>> con.execute("CREATE TABLE t (n INTEGER)").rowcount
-1
>>> con.executemany("INSERT INTO t VALUES (?)", [(1,), (2,), (3,)]).rowcount
3
>>> con.execute("SELECT SUM(n) FROM t").fetchone()
(6,)
This illustrative GitHub Actions YAML runs the small SQLite fence runner on documentation changes. The runner's skips remain gaps to cover elsewhere, and the workflow should be adapted to the database versions and fixtures your project supports.
name: sql-examples
on:
pull_request:
paths:
- "docs/**"
jobs:
sql:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- name: Run SQL fences against SQLite
run: python3 scripts/run_sql_fences.py
Test the actual dialect
SQLite is convenient for a fast, isolated check, but SQL syntax, locking, data types, and database behavior differ. A SQLite pass does not establish that a PostgreSQL migration works, that a MySQL-specific query is valid, or that a production database has the expected permissions and state. Test dialect-only examples on the database they name.
For PostgreSQL, the psql documentation says that setting ON_ERROR_STOP stops processing on an error; in a script, psql returns exit status 3 when an error occurs and that setting is active. Configure your CI invocation and inspect its exit status so an earlier SQL error does not disappear behind later commands. The GitHub Actions PostgreSQL service-container tutorial shows how to provide a PostgreSQL service to a workflow.
Pin or record the database version and start from a known state. Apply setup, sample data, and migrations in the order documented. Assert the result values that matter, including order where promised. Test destructive migrations on disposable databases, and ensure any credentials used by CI are scoped for that environment.
A database result table is part of the documentation contract if readers are asked to compare their result with it. Decide whether all columns and rows must match exactly or whether the lesson only promises a property such as a count. Make that decision explicit in the test; a successful query alone does not establish that the displayed result is current.
What the engine sees
Engine 0.6.3 recognizes sql but skips it with the reason not executable (sql). Labels such as postgresql, sqlite, and psql are unmapped: the engine reports them as passing without running or parsing them. This is a known engine limitation. Do not use those green results as evidence that the database accepted the code.
| Block form → what the engine does in 0.6.3 | Practical consequence |
|---|---|
Fence labeled sql |
Skips it as not executable (sql); run it with your own SQL runner. |
Fence labeled postgresql, sqlite, or psql |
Reports a pass without checking the contents; use sql plus a separate dialect-aware check. |
Console command invoking sqlite3 |
Runs the prompted command; if the tool is not installed, the result is missing-tool. |
Python fence using sqlite3 |
Executes supported Python blocks in page order. A SQL error raised by Python can be reported as a runtime error needing review. |
Python pycon or python-repl session |
Executes the session and compares its printed output. This is the engine's only printed-output comparison. |
| Separate block identified as output | Skips it; the displayed rows are not validated. |
The runner image should not be assumed to contain a particular database client or server. Console lines after a prompt are run; other console lines are treated as output and not compared. Use a database-specific CI job for actual SQL coverage and inspect its version, setup, and assertions.
Triage results in context
| Finding | Next step |
|---|---|
| SQL syntax error in your runner | Check the dialect and version, correct the statement, and rerun the page sequence. |
| Wrong row count or values | Check sample data, query semantics, expected results, and ordering. |
| Missing table or column | Verify earlier setup and migrations, then check for a renamed object. |
| Dialect-only skip | Run against the named database or document the remaining coverage gap. |
| Missing database tool | Install it in the appropriate test environment or clarify the page prerequisite. |
| Python runtime error wrapping SQL | Inspect the database error and page context; it needs review. |
| Passing unmapped label | Add a real checker; the reported pass did not execute or parse the SQL. |
A missing fixture or database service can be a test-environment issue, a missing reader prerequisite, or both. Preserve enough evidence to distinguish them. See findings for the engine's categories.
Make SQL checks repeatable
Keep each page's setup and query order visible. A fresh database per page prevents a previous page from accidentally supplying a table, but a reader may legitimately need an earlier tutorial page. When that is the intended contract, provide a documented fixture or test the full tutorial sequence separately.
Test migrations in both the state they expect and the state they produce. A migration that runs on an empty database may still fail on existing data. For examples that show results, include representative sample rows and assert the properties the prose promises. Review skipped blocks when the supported database or version changes.
- Identify each example's database dialect and version.
- Classify setup, queries, migrations, dialect-only blocks, and illustrations.
- Start from a known disposable database state.
- Run page setup and examples in the reader's documented order.
- Assert important row values, counts, and ordering.
- Run dialect-only statements against their named database.
- Record every skip and assign an appropriate separate check.
- Check database clients, services, fixtures, and permissions.
- Treat unmapped fence-label passes as unchecked.
- Recheck examples when schemas, sample data, or supported versions change.
Where DocsAlive fits
DocsAlive can run supported Python examples in page order, including Python that uses the standard sqlite3 module. That can be a good fit when Python is already the teaching language. Interactive Python sessions can also express small examples with checked printed results. A direct SQL tutorial, however, should retain clear sql fences and use a SQL-aware runner rather than depend on a misleading label result.
Use the engine's reports alongside database-specific checks and human review. The engine can help with surrounding executable examples and categorize failures, while your database workflow establishes SQL dialect coverage and verifies the result contract. The docs testing overview and CLI reference describe the broader workflow.
SQL can appear inside many site formats. See testing Hugo documentation examples and testing GitBook documentation examples for the source-discovery issues those formats add.
The sources we checked
These sources were read on November 12, 2026. Engine behavior was checked against engine 0.6.3 on the same day.
| Source | What it covers |
|---|---|
| SQLite quirks | Flexible typing and other differences relevant to portable examples. |
| SQLite datatypes | Storage classes, affinity, and typing behavior. |
Python sqlite3 documentation |
Python's SQLite interface. |
PostgreSQL psql documentation |
Script error handling and exit statuses. |
| GitHub Actions PostgreSQL service containers | Supplying PostgreSQL to a CI workflow. |
| Framework coverage | Engine language support and limitations. |
FAQ
Does the engine execute SQL fences?
Engine 0.6.3 skips fences labeled sql as not executable. Run them with your own database-aware runner and review the skip in the report.
Can I use a dialect label to make SQL run?
No. Labels such as postgresql, sqlite, and psql are unmapped in this engine version and can be reported as passing without any check. Use a sql label and a separate runner.
Is a SQLite pass enough for PostgreSQL?
No. SQLite has its own syntax and typing behavior, including flexible typing in ordinary tables. Run PostgreSQL-specific examples against the supported PostgreSQL version.
Why run SQL blocks in page order?
Queries and migrations often depend on tables or data established earlier. A fresh database per page, with blocks run in order, makes those dependencies visible.
Does a row-count check verify the whole result?
No. It can catch a missing or extra row while missing incorrect values or order. Assert the properties the documentation promises.
Can Python examples test SQLite operations?
Yes. Supported Python blocks using sqlite3 execute in page order. Choose that form when it suits the lesson, and use a database-specific runner for direct SQL fences and other dialects.




