Xpersona
S

Sqlx Code Review

CLAWHUB · Unverified

Reviews sqlx database code for compile-time query checking, connection pool management, migration patterns, and PostgreSQL-specific usage. Use when reviewing... Skill: Sqlx Code Review Owner: anderskev Summary: Reviews sqlx database code for compile-time query checking, connection pool management, migration patterns, and PostgreSQL-specific usage. Use when reviewing... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-06-01T02:26:36.001Z | auto - Updated review-verification protocol instructions to link to an external skill file instead of a local one. - Removed the sample f

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:sqlx-code-review
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-sqlx-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

79,861 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: sqlx-code-review
description: Reviews sqlx database code for compile-time query checking, connection pool management, migration patterns, and PostgreSQL-specific usage. Use when reviewing Rust code that uses sqlx, database queries, connection pools, or migrations. Covers offline mode, type mapping, and transaction patterns.
---

# sqlx Code Review

## Review Workflow

1. **Check Cargo.toml** — Note sqlx features (`runtime-tokio`, `tls-rustls`/`tls-native-tls`, `postgres`/`mysql`/`sqlite`, `uuid`, `chrono`, `json`, `migrate`) and Rust edition (2024 changes RPIT lifetime capture and removes need for `async-trait`)
2. **Check query patterns** — Compile-time checked (`query!`, `query_as!`) vs runtime (`query`, `query_as`)
3. **Check pool configuration** — Connection limits, timeouts, idle settings
4. **Check migrations** — File naming, reversibility, data migration safety
5. **Check type mappings** — Rust types align with SQL column types

## Gates (evidence before severity)

Complete in order; do not assign **Critical** / **Major** until the gate for that claim is passed.

1. **Scope** — Identify the crate under review (`Cargo.toml` path) and the `.rs` files (or directory) you opened. **Pass:** At least one concrete path you inspected is named.
2. **sqlx / compile claims** — Before asserting issues about `query!` / `query_as!`, offline mode, `sqlx.toml`, `DATABASE_URL`, or Cargo features: open the relevant `Cargo.toml` and, if applicable, `sqlx.toml` or documented env. **Pass:** The finding cites a line or you state that those files were absent / out of scope.
3. **Finding anchors** — Each reported issue includes `[FILE:LINE]` per **Output Format**. **Pass:** No Critical or Major without a line reference.
4. **Protocol** — Load and complete the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill **after** gates 1–3 and **before** final severity labels. **Pass:** Protocol steps satisfied for each retained finding.

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| Query macros, bind parameters, result mapping | [references/queries.md](references/queries.md) |
| Migrations, pool config, transaction patterns | [references/migrations.md](references/migrations.md) |

## Review Checklist

### Query Patterns
- [ ] Compile-time checked queries (`query!`, `query_as!`) used where possible
- [ ] `sqlx.toml` or `DATABASE_URL` configured for offline compile-time checking
- [ ] No string interpolation in queries (SQL injection risk) — use bind parameters (`$1`, `$2`)
- [ ] `query_as!` maps to named structs, not anonymous records, for public APIs
- [ ] `.fetch_one()`, `.fetch_optional()`, `.fetch_all()` chosen appropriately
- [ ] `.fetch()` (streaming) used for large result sets

### Connection Pool
- [ ] `PgPool` shared via `Arc` or

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "sqlx-code-review",
  "version": "1.0.3",
  "publishedAt": 1780280796001
}

references/migrations.md

# Migrations and Pool Management

## Connection Pool Configuration

### Creating the Pool

```rust
use sqlx::postgres::PgPoolOptions;

let pool = PgPoolOptions::new()
    .max_connections(20)
    .min_connections(5)
    .acquire_timeout(Duration::from_secs(5))
    .idle_timeout(Duration::from_secs(600))
    .max_lifetime(Duration::from_secs(1800))
    .connect(&database_url)
    .await?;
```

### Edition 2024: Static Pool with `LazyLock`

For applications that initialize a global pool once, use `std::sync::LazyLock` instead of `once_cell::sync::Lazy` or `lazy_static!`. `LazyLock` is in std since Rust 1.80.

```rust
// BAD — third-party crate, unnecessary dependency
use once_cell::sync::Lazy;

static POOL: Lazy<PgPool> = Lazy::new(|| {
    tokio::runtime::Handle::current().block_on(async {
        PgPoolOptions::new()
            .max_connections(20)
            .connect(&std::env::var("DATABASE_URL").unwrap())
            .await
            .unwrap()
    })
});

// GOOD — std library, no extra dependency
use std::sync::LazyLock;

static POOL: LazyLock<PgPool> = LazyLock::new(|| {
    tokio::runtime::Handle::current().block_on(async {
        PgPoolOptions::new()
            .max_connections(20)
            .connect(&std::env::var("DATABASE_URL").unwrap())
            .await
            .unwrap()
    })
});
```

Note: Framework-managed state (e.g., axum `State<PgPool>`) is still preferred over global statics. Use `LazyLock` only when a static singleton is genuinely needed.

### Pool Sizing Guidelines

- **Web servers:** 2-4× the number of async worker threads
- **Background workers:** Match to the number of concurrent jobs
- **Default (5):** Too low for most production workloads
- **Maximum:** Don't exceed the database's `max_connections` minus connections reserved for admin/monitoring

### Common Mistake: Pool Per Request

```rust
// BAD - creates a new pool (and connections) per request
async fn handle(req: Request) -> Response {
    let pool = PgPool::connect(&url).await.unwrap();
    let user = query_as!(User, "...", id).fetch_one(&pool).await?;
    // pool dropped, connections closed
}

// GOOD - share pool via application state
async fn handle(State(pool): State<PgPool>, req: Request) -> Response {
    let user = query_as!(User, "...", id).fetch_one(&pool).await?;
}
```

## Transactions

### Basic Pattern

```rust
let mut tx = pool.begin().await?;

sqlx::query!("INSERT INTO orders (user_id, total) VALUES ($1, $2)", user_id, total)
    .execute(&mut *tx)
    .await?;

sqlx::query!("UPDATE inventory SET count = count - $1 WHERE item_id = $2", qty, item_id)
    .execute(&mut *tx)
    .await?;

tx.commit().await?;
```

If `tx` is dropped without calling `.commit()`, the transaction rolls back automatically. This is a safety net — explicit commit is clearer.

### Error Handling in Transactions

```rust
async fn create_order(pool: &PgPool, order: NewOrder) -> Result<Order, Error> {
    let mut tx = pool.begin().await?;

    let order = sqlx::query

references/queries.md

# Queries

## Compile-Time Checked Queries

sqlx verifies queries against the database schema at compile time. This catches column name typos, type mismatches, and invalid SQL before runtime.

### query! Macro

Returns an anonymous struct with fields matching the query columns.

```rust
// Compile-time checked — column names and types verified
let row = sqlx::query!(
    "SELECT id, name, email FROM users WHERE id = $1",
    user_id
)
.fetch_one(&pool)
.await?;

let name: String = row.name;
let email: Option<String> = row.email; // nullable column → Option
```

### query_as! Macro

Maps results directly to a named struct. Preferred for reusable result types.

```rust
#[derive(Debug)]
struct User {
    id: Uuid,
    name: String,
    email: Option<String>,
    created_at: DateTime<Utc>,
}

let user = sqlx::query_as!(
    User,
    "SELECT id, name, email, created_at FROM users WHERE id = $1",
    user_id
)
.fetch_optional(&pool)
.await?;
```

### Offline Mode

For CI/CD where the database isn't available, sqlx caches query metadata. In sqlx 0.8+, configuration lives in `sqlx.toml` and cached metadata is stored in the `.sqlx/` directory. Older versions used `sqlx-data.json`.

```bash
# Generate cache from live database
cargo sqlx prepare

# Build uses cached metadata when DATABASE_URL is absent
cargo build
```

In sqlx 0.8+, you can configure offline mode and other settings via `sqlx.toml`:

```toml
# sqlx.toml
[common]
offline = true
column-override = {}
```

## Fetch Methods

| Method | Returns | Use When |
|--------|---------|----------|
| `.fetch_one()` | `T` (error if 0 or 2+ rows) | Exactly one row expected (by PK) |
| `.fetch_optional()` | `Option<T>` | Zero or one row expected |
| `.fetch_all()` | `Vec<T>` | Small, bounded result set |
| `.fetch()` | `Stream<Item = Result<T>>` | Large or unbounded results |

### Common Mistake: fetch_one for Lookups

```rust
// BAD - returns Err(RowNotFound) on "not found" which is an expected case
let user = sqlx::query_as!(User, "SELECT ... WHERE id = $1", id)
    .fetch_one(&pool)
    .await?; // RowNotFound error for missing users

// GOOD - "not found" is a normal case, not an error
let user = sqlx::query_as!(User, "SELECT ... WHERE id = $1", id)
    .fetch_optional(&pool)
    .await?;
match user {
    Some(user) => Ok(user),
    None => Err(Error::NotFound(id)),
}
```

### Streaming Large Results

```rust
use futures::TryStreamExt;

let mut stream = sqlx::query_as!(Event, "SELECT * FROM events WHERE workflow_id = $1", wf_id)
    .fetch(&pool);

while let Some(event) = stream.try_next().await? {
    process(event).await;
}
```

### Edition 2024: RPIT Lifetime Capture in Query Helpers

In edition 2024, `-> impl Trait` captures all in-scope lifetimes by default. This affects functions that return streams or futures from sqlx queries.

```rust
// Edition 2021 — worked because `-> impl Stream` didn't capture 'a
fn get_events<'a>(pool: &'a PgPool, wf_id: Uuid) -> impl Stream<Item = Result<Event, sqlx::Error

skill-card.md

## Description:

Reviews Rust sqlx database code for compile-time query checking, connection pool management, migration safety, type mapping, and PostgreSQL-specific usage.

This skill is ready for commercial/non-commercial use.

## Publisher:

[anderskev](https://clawhub.ai/user/anderskev)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and code reviewers use this skill to review Rust projects that use sqlx for query safety, connection pooling, migrations, transaction handling, and PostgreSQL type mapping.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: The skill depends on a separate unbundled review-verification-protocol skill that was not included in the reviewed package.

Mitigation: Review and vendor the referenced protocol, or otherwise control its content and integrity, before installation.

## Reference(s):

- [Migrations and Pool Management](references/migrations.md)
- [Queries](references/queries.md)

## Skill Output:

**Output Type(s):** [Text, Markdown, Guidance]

**Output Format:** [Markdown review findings with file-line anchors and severity labels]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [Findings are gated by inspected evidence and reported with Critical, Major, Minor, or Informational severity when issues are present.]

## Skill Version(s):

1.0.3 (source: server release evidence)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to Sqlx Code Review and adjacent AI workflows.