Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.5 — Tables and Databases
RAG and Vector Search · Example 1 of 1

Validate a model-written SQL string (never run it)

The queries are plain strings and nothing here talks to a database. A word-based check is a teaching version of Layer 2. In production a SQL parser and a read-only role do this job.

Questions such as "how many rentals did each shop have?" are answered by a query, not by a passage. A model can write the SQL, but its output is untrusted: run it only through a read-only role, an allow-list of tables and a validator.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write add_limit(sql, max_rows) that appends LIMIT <max_rows> when the statement has no LIMIT word (any letter case) and returns it unchanged otherwise. Print the result for two statements.

02

Write tables_in(sql) that returns the sorted list of table names that follow FROM or JOIN (any letter case). Print it for a query with a join and for a query with a sub-select.

Explain it without notes

01

Why are aggregation questions a poor fit for embedded text?

02

Why is a model's SQL treated as untrusted, and what are the layers of defence?

03

What does your validator check and what can it miss?

04

How do you combine a SQL result with retrieved passages in one answer?

Validate a model-written SQL string (never run it)
Sign in to run this example in your browser.

Expected output

SELECT shop, COUNT(*) FROM rentals GROUP BY shop
    ok: SELECT shop, COUNT(*) FROM rentals GROUP BY shop LIMIT 100
SELECT name FROM shops LIMIT 5
    ok: SELECT name FROM shops LIMIT 5
DELETE FROM rentals
    rejected: only SELECT is allowed
SELECT * FROM users
    rejected: table not allowed: users
SELECT id FROM rentals; DROP TABLE rentals
    rejected: more than one statement
SELECT id FROM rentals -- and more
    rejected: comments are not allowed
SELECT shop FROM shops WHERE id IN (SELECT id FROM secrets)
    rejected: table not allowed: secrets