← All posts

LLMs over SQL need boundaries, not better prompts

A new Datasette agent release highlights a larger pattern in AI system design: once an LLM gets query access to structured data, the hard problems shift to boundaries, controls, and traceability. Here is what to inspect before you put a model in front of your database.

Simon Willison recently noted the release of datasette-agent 0.7a1, an experiment in giving an LLM structured access to a Datasette instance. The useful part for you is not the release itself. It is the design pattern. Once an LLM gains query access to live data, your risk shifts from prompt quality to system boundaries, query control, and output verification.

This matters in AI systems built for internal analytics, customer support, fraud review, and operational search. Many teams wire a model to SQL and stop there. The first demo works. The second week brings slow queries, hidden data exposure, and answers no one can reproduce. If you build LLM features on top of relational data, you need a narrower interface and stronger audit trails than a raw chat layer suggests.

A Datasette-style architecture helps because it starts from a read-oriented data surface. But read-only is not the same as low-risk. You still need to control what the model sees, what it asks for, how much it pulls back, and how a human checks the result.

Start with the data boundary, not the prompt

The common mistake is treating the database as the tool and the model as the operator. In practice, your real control point is the contract between them. A model should never infer table meaning from a full schema dump if you care about reliability or least privilege.

Inspect these points first:

  • Which tables are exposed at all
  • Which columns are visible in each table
  • Whether row-level filters apply by tenant, region, or case owner
  • Whether derived views hide sensitive joins
  • Whether primary keys, foreign keys, and timestamps are preserved in the exposed surface

A good pattern is to publish purpose-built views for model access. Keep names plain. Keep semantics stable. Expose fewer joins. Put policy in SQL views or service middleware, not in the system prompt.

For example, an internal support assistant rarely needs direct access to users, payments, and sessions as raw tables. It needs a small set of stable read models such as:

create view support_case_summary as
select
  c.case_id,
  c.account_id,
  c.status,
  c.priority,
  c.created_at,
  c.updated_at,
  count(m.message_id) as message_count
from cases c
left join messages m on m.case_id = c.case_id
group by 1,2,3,4,5,6;

This does two things. It limits exposure. It gives the model cleaner primitives, which improves answer quality.

Constrain query generation before you optimize it

Teams often focus on prompt phrasing to reduce bad SQL. The larger win comes from reducing the SQL space the model is allowed to produce.

There are several workable approaches:

  • Template-backed queries with parameter filling
  • A DSL translated to SQL by trusted code
  • Whitelisted views plus parser-level SQL validation
  • Prebuilt endpoints for high-value questions

If you allow free-form SQL, validate the abstract syntax tree before execution. Block writes, DDL, attachment features, unsafe functions, and unbounded scans. Set strict limits on rows, execution time, nesting depth, and returned bytes.

Useful controls include:

  • LIMIT injection when absent
  • Statement type allowlists, usually SELECT only
  • Query timeout at the driver or proxy layer
  • Cancellation on token budget or latency budget breach
  • Prevention of cross-database references
  • Logging of normalized query shapes

The key signal to read is whether your system can explain why a query was permitted. If approval logic lives only in prompt text, you do not have a real control.

This matters even for read-only systems. Read-only access still exposes personal data, internal pricing logic, fraud rules, and security-sensitive metadata. It also creates availability risk if the model issues expensive joins or repeated retries.

Make every answer reproducible

A useful AI data assistant should produce answers you can trace back to rows, filters, and query time. Without this, you are left with plausible text and weak accountability.

At minimum, store these artifacts for each model-assisted response:

  • The user question
  • The exact tool call or SQL sent
  • Query parameters
  • Database or snapshot version
  • Execution time and row count
  • The result sample or full result hash
  • The final model answer

You should also return citations or record handles in the UI. If the answer says an account had three failed payouts last week, the operator should be able to open the underlying rows.

A practical pattern is to separate retrieval from synthesis:

  1. Generate a candidate query.
  2. Execute it in a restricted environment.
  3. Show rows or aggregates to the model.
  4. Ask the model to summarize only from returned data.
  5. Render links or IDs for user verification.

This split reduces a common failure mode where the model mixes prior knowledge with fresh data. It also improves incident review. When an answer is wrong, you can inspect whether the failure came from query generation, stale data, bad joins, or summarization.

Watch for hidden prompt injection in data itself

Once models read database content, the data becomes part of the instruction surface. This is easy to miss. Free-text fields such as tickets, comments, notes, and imported web content can contain text that steers the model away from your intended task.

Typical examples include:

  • Customer messages with phrases like “ignore previous instructions”
  • HTML or markdown imported from external sources
  • OCR text from uploaded documents
  • CRM notes copied from email threads
  • Synthetic test data with misleading labels

Your mitigations should live outside the model where possible:

  • Treat retrieved text as data, never as instructions
  • Put clear delimiters around tool results
  • Strip or transform markup before passing text onward
  • Truncate long free-text fields by policy
  • Classify sources by trust level and expose less from low-trust inputs

If you run adversarial tests against your toolchain, use a dedicated harness. Prompt-Injection & System-Prompt-Leak Tester fits this stage because it tests whether your system prompt and tool flow hold up under hostile inputs.

The main verification step is simple. Seed your staging data with adversarial records and confirm the model still follows task rules, still cites returned rows, and still refuses data it should not see.

Design for performance failure, not average success

An LLM-to-data system often looks fine with ten rows and one user. It fails under broad date ranges, skewed joins, or repeated retry loops from the orchestration layer.

Read these signals early:

  • Slow queries concentrated on one or two views
  • Large token use caused by wide result sets
  • Repeated near-duplicate questions from users
  • Timeouts followed by larger fallback queries
  • Summaries built from partial result sets without disclosure

Good countermeasures are mostly standard data engineering:

  • Pre-aggregate common metrics
  • Add covering indexes for model-facing views
  • Enforce default date windows
  • Cache result sets by normalized query shape and parameters
  • Return compact table summaries before full rows
  • Use async jobs for expensive analyses

You should also set explicit response modes. A system answering “top causes of payment failure in the last 90 days” does not need raw records on first pass. It needs grouped counts, then drill-down paths.

This is where many teams go wrong. They ask the model to figure out both the analytical plan and the final explanation in one shot. Split those steps. First choose the data access pattern. Then run it. Then summarize.

What to watch next

The important trend is not one package release. It is the steady move toward LLMs operating over structured business data through narrow tool interfaces. If you build these systems, watch three areas closely: schema exposure, query governance, and reproducibility. Those determine whether your assistant behaves like a controlled analytics layer or an expensive text box wired to production data.

Expect better tooling around SQL validation, row-level policy enforcement, and answer citations. Until then, your safest path is simple. Expose less. Log more. Make each answer traceable to data you can inspect.