AI Writes SQL Fluent Enough to Ship a Bug
A syntax error is a gift. It fails at build, points at a line, and costs five minutes.
The generated data-access bug I worry about looks different. The query compiles. It returns rows. It updates the wrong records, or overwrites a field another request just changed, or works fine against the local SQLite file and misbehaves against Postgres. Nobody sees it until a customer does.
rust-ef is an ORM I maintain with rust-dix and rust-webx. This piece is about the specific data-layer decisions that make that failure mode harder to reach — not because the model writes better SQL, but because part of the query never exists as a string in the first place.
Columns stop being strings
Ask a model to write a filtered, sorted query and it will happily produce a column name as text. A typo passes review, compiles, and fails at runtime. A rename in the database makes it worse: the query still succeeds, against the wrong meaning.
rust-ef emits typed column handles from #[derive(EntityType)]. You sort by a field constant, not by a string:
query.order_by(Order::created_at)
.then_by_desc(Order::id);
A renamed or nonexistent field fails at compile time. order_by* accepts only types implementing Sortable — integers, floats, bool, char, String, Option<T: Sortable> and feature-gated chrono/uuid/decimal types. Blobs and JSON are rejected at compile time, with a compile_fail doc test covering it.
The older string-based entry points were renamed to order_by_raw / order_by_desc_raw. The name tells you what you are opting into.
Filters go through linq!, which checks column identity against the entity at expansion time. You can compose predicates and reuse them:
let predicate = Predicate::<Order>::always()
.and(linq!(|o: Order| o.tenant_id == tenant))
.and_opt(keyword.map(|k| linq!(|o: Order| o.no.contains(k))));
let page = ctx.set::<Order>().query()
.filter(predicate)
.order_by_desc(Order::created_at)
.to_page(&paging)
.await?;
The to_page terminal runs COUNT(*) on a clone with ORDER BY, skip and take removed. The total and the page share the same FROM / JOIN / WHERE, so pagination totals do not quietly disagree with the list. It returns a flat PagedResult<T> with items and total alongside the outcome fields.
One caveat worth spelling out: the count and the page are not one snapshot. Under concurrent writes they can disagree. Wrap the call in a transaction when the two must agree.
Writes are tracked, not blanket
Here is a failure that unit tests almost never catch. Two people edit the same order. One changes the shipping address, the other changes the status. A generated full-row UPDATE from the second request overwrites the address with the value it read a moment earlier.
rust-ef takes the EF Core route: load the entity, edit the tracked copy, detect changes, save.
ctx.edit(order, |o| o.patch(req))?;
ctx.detect_changes();
ctx.save_changes().await?;
detect_changes() writes only the dirty columns. edit attaches the entity and captures the original snapshot before applying the closure, which avoids the attach-ordering footgun. If a row with the same key is already tracked, the closure runs on that instance and no second tracker entry appears.
The cost is real. You have to load the entity first. For a bulk status change across a hundred thousand rows, this is the wrong tool — execute_update exists for that case and deliberately bypasses the change tracker and interceptors. After a unique violation with DML, you need clear_tracking() before retrying.
Generated code will reach for the convenient tool. Knowing which tool is wrong for a bulk operation is still a human decision.
Schema drift becomes a diff, not a surprise
The other silent failure is environmental. The entity says one thing, the database says another, and staging finds out.
Entities carry their own schema through #[derive(EntityType)] and IEntityTypeConfiguration. The migration engine can inspect a live database and compare it to the model:
let live = provider.introspect().await?;
let diff = engine.diff(&model, &live)?;
engine.apply_diff(&provider, &diff).await?;
On SQLite and PostgreSQL, apply_diff runs in a single transaction. SQLite constraint changes use a shadow-table rebuild, with PRAGMA foreign_keys=OFF outside the transaction. MySQL executes statements one by one, because its DDL implicitly commits — not atomic, and worth knowing before you rely on it.
There are guard rails inside the guard rail. If a rebuild would add a NOT NULL column without a default to a non-empty table, apply_diff returns a typed error before touching the database. CHECK constraints that cannot be introspected produce constraint_not_introspected rather than a silent drop. Runtime diff never drops a CHECK constraint.
This matters more with AI-assisted changes, where an entity edit and a schema edit can land in different files, different commits, or only one of the two.
Error identity crosses the boundary once
Data-layer failures used to arrive at the web boundary wearing three different coats. Each service wrote its own map_*_error, and each one decided separately whether to show a constraint name to the client.
rust-ef 2.9.1 classifies driver failures at the source: closed connections, I/O, TLS, pool timeouts and SQLite busy/locked become EFError::Connection; decoding failures become EFError::TypeConversion; Query is reserved for statement generation and projection shape. Before this, a lost connection reached the web boundary as a non-retryable 400. Now it is a retryable 503.
EFError implements From<EFError> for AppError. AppError lives in rust-core, shared by all three frameworks. The handler uses ? and the framework owns the mapping: unique violations become conflicts without echoing the constraint name, internal detail stays in the operator log, and the client sees an empty public_detail() on 5xx.
There is no rust-webx feature in rust-ef and no bridge crate. That was removed in 2.6, deliberately, so the ORM stays usable in a worker or a CLI.
Where this stops
Type checks do not validate your domain. A query can be perfectly typed and still filter on the wrong field. detect_changes() will faithfully write the wrong value if you edited the wrong object. The migration diff compares structure, not intent.
rust-ef is not EF Core parity. Complex reporting still wants typed projections or the raw SQL escape hatch. SQLite's limited ALTER TABLE still needs a plan. The persistence adapters for auth, outbox and idempotency live under examples/adapters/*/ef with publish = false — they are meant to be copied into your service, not depended on. Adding rust-webx-pay-ef to Cargo.toml will not resolve.
These are documented boundaries, not surprises.
Start with one aggregate
Pick one entity with a real state transition. Write its configuration. Replace one list query with Predicate plus to_page. Replace one write with edit plus detect_changes. Run the migration diff against a copy of the database.
If the diff is empty on the first run, the model and the schema agree. If it is not, you found the drift before production did — which is the entire point of putting the check in the tooling instead of in a review checklist.
Repositories:
rust-webx · rust-ef · rust-dix
Which data-layer bug in your codebase would a compiler never see? That is the boundary I am interested in next.
Top comments (0)