sqlx-best-practices
Installation
SKILL.md
SQLx best practices
Use when writing or reviewing Rust code with SQLx against Postgres (or other supported drivers): pools, query! / query_as, migrations, QueryBuilder, and CI/Docker builds.
Mental model
- SQLx checks SQL + types at compile time when using macros (
query!,query_as!) against a live DB or offline metadata (.sqlx); runtimequery/query_aswith string SQL skips that check—use deliberately. - Treat the database schema as the source of truth macros validate against; keep migrations and
.sqlxcache in sync with schema changes.
Compile-time checked queries
- Prefer
query!/query_as!(orquery_aswith aFromRowtype) for fixed SQL so renames and type drift fail the build, not production. - Run
cargo sqlx prepare(or the project’s documented prepare step) after migration or query changes and commit updated.sqlxdata so offline / Docker builds match CI. - For dynamic fragments (optional filters,
INlists), useQueryBuilderor carefully validated runtime SQL; don’t build raw strings from untrusted input.
Mapping rows
- Use
FromRow(derive or manual) forquery_asshapes that map 1:1 to tables or stable select lists; keep field order and types aligned with theSELECTlist. - Use
query_scalarwhen a single column is enough; avoid fetching full rows just to read one value.