← LeaderboardThe Skill Leaderboard

rust-sqlx-nullable-scalar-lookups

Preserve missing rows, SQL NULL, and concrete values in Rust SQLx scalar lookups. Trace nested Option through SQLite queries and test the caller's decisions.

Published by sickn33 ↗sickn33/agentic-awesome-skills

Try your first task

A source-grounded starter task has not been verified for this skill yet.

SKILL.md

name: rust-sqlx-nullable-scalar-lookupsdescription: Preserve missing rows, SQL NULL, and concrete values in Rust SQLx scalar lookups. Trace nested Option through SQLite queries and test the caller's decisions.category: databaserisk: criticalsource: selfsource_type: selfdate_added: "2026-12-03"author: ShianMiketags: [rust, sqlx, sqlite, null, option, row-cardinality]

Rust SQLx nullable scalar lookups

When to Use

  • A Rust SQLx lookup returns the same response for a missing record and an existing record with a null setting.
  • A repository's query_scalar, fetch_optional, or .flatten() appears in a code path where row existence changes behavior.
  • A nullable lookup must distinguish an unset value from a concrete zero or empty value.

Prerequisites

  • Identify the database backend, SQLx version, query, and public caller. The example uses SQLx 0.9.1 on SQLite.
  • Find the schema constraint or join that determines result cardinality, along with the expression that can produce a null scalar.
  • Use fixtures where each outcome has a clear meaning. In the example, a missing schedule has no policy, an existing schedule with a null override inherits a policy, and a zero override explicitly selects zero minutes.

1. Check how the SQL produces rows and values

  1. Read the actual selected expression. query_scalar decodes only the first column of each row.
  2. Identify the lookup key and prove the query returns at most one row. A predicate on a primary key makes that explicit. fetch_optional takes the first row and cannot detect an unexpected extra match.
  3. Check how joins, predicates, and expressions affect the result. A left join can yield a row with a null joined value. A filter can drop that row entirely, and COALESCE can change its null into a concrete value.
  4. Confirm which representation the caller needs. Trace any .flatten(), .ok(), unwrap_or_default(), or mapping at the repository and response boundaries. Identify where a state first disappears.

2. Decode nullability and cardinality independently

  • Choose query_scalar::<_, Option<T>>(...).fetch_optional(...) when a lookup can return zero rows and the selected value can be null.
  • Preserve the resulting Option<Option<T>> through the await. Propagate sqlx::Error with ? or the caller's existing error mapping.
  • Match the three cases where the lookup becomes an application decision.
Decoded resultSQL conditionExample meaning
NoneZero matching rowsSchedule missing
Some(None)A row whose selected value is SQL NULLInherit a policy
Some(Some(value))A row whose selected value is concreteApply the stored override

Use a named enum when it makes those meanings clear to downstream code. If the public API already distinguishes them by status or response shape, preserve that contract too. Collapse states only when the caller explicitly treats them alike.

3. Test the caller's decision with real rows

  1. Run the same lookup against a missing key, a present null, and a concrete value. Include zero or an empty value when the domain permits it.
  2. Reproduce the bug with a failing assertion on the application outcome. Avoid a string equality assertion against SQL logs.
  3. Repeat the same cases after fixing the mapping. If the query accepts a key that should be unique, verify the relevant constraint while reviewing the query.
  4. For a production change, run the repository test and the focused consumer test that observes the distinct outcomes. Report the backend, SQLx version, and observed values.

Example

Preserve missing rows and null values runs a synthetic schedule lookup on a single SQLite connection. The same assertions catch a flattened result and confirm a three-way mapping.

Limitations

  • An ungrouped aggregate such as MAX usually returns one row containing SQL NULL for an empty input. When the query contract guarantees one row, fetch_one with a nullable scalar expresses that contract. Check grouping and filters before choosing it.
  • Multiple matching rows, migration history, and SQLx macro inference require separate validation. The fixture uses the runtime function and SQLite's driver.
  • A SQL null value may represent several application situations, such as a null stored value and a missing left-joined record. Select extra columns or query a clearer shape if those situations need to be distinct.

Safety and Side Effects

The worked example creates and seeds an in-memory database on one connection. Run it in a scratch crate. Confirm result semantics before editing a shared repository method because callers may depend on the existing error and missing-row behavior.

Related Skills and Documentation