DBQC for Rust

Schema discovery generates table modules with typed column constructors. The types prevent invalid comparisons and let ordinary values become SQL literals without repeating names or SQL types.

use dbqc::*;
use dbqc_schema::{Orders, Restaurants};

The ordinary case

let restaurants = Restaurants::source();

let ids = restaurants
    .where_eq(Restaurants::city(), "New York")
    .select([Restaurants::id()]);

where_eq is DBQC null-safe equality (IS NOT DISTINCT FROM). The compiler may emit = where nullability proves the two equivalent.

Predicates and joins

Rust does not support overloading == or >. Generated columns therefore provide typed SQL methods:

let high_value = Restaurants::source()
    .inner_join(
        &Orders::source(),
        Restaurants::id().eq(Orders::restaurant_id()),
    )
    .where_(Orders::total().gt("100.00".parse::<rust_decimal::Decimal>()?))
    .select((Restaurants::name(), Orders::total()))
    .order([desc(Orders::total())]);

.eq() compares two generated columns. .eq_value() compares a column with a Rust value; where_eq() is the concise equality-filter shorthand. Ordered literal comparisons use .lt(), .lte(), .gt(), and .gte().

Runtime parameters

let input = parameter::<uuid::Uuid>("restaurant_id", "uuid");

let by_id = Restaurants::source()
    .inner_join(
        &input.source,
        Restaurants::id().eq(input.column),
    )
    .select((Restaurants::id(), Restaurants::name()));

let compiled = by_id.compile("psql")?;
println!("{}", compiled.sql);
println!("{:?}", compiled.param_order); // ["restaurant_id"]

Bind runtime values in param_order; DBQC never interpolates them into SQL.

Aggregates and HAVING

let revenue = Orders::source()
    .group_by((Orders::restaurant_id(),))
    .having(sum(&Orders::total().expr()).gt_value("0.00"))
    .select((
        Orders::restaurant_id(),
        sum(&Orders::total().expr()).as_("revenue"),
    ));

The generated grouping field retains its name. Only computed output needs .as_(...).

Reusable queries and CTE ordering

let revenue = Orders::source()
    .group_by((Orders::restaurant_id(),))
    .select((
        Orders::restaurant_id(),
        sum(&Orders::total().expr()).as_("revenue"),
    ));

let revenue_restaurant_id =
    column::<uuid::Uuid>(revenue.clone(), "restaurant_id", "uuid", false);
let revenue_amount =
    column::<rust_decimal::Decimal>(revenue.clone(), "revenue", "numeric(12,2)", false);

let ranked = Restaurants::source()
    .inner_join(
        &revenue,
        Restaurants::id().eq(revenue_restaurant_id),
    )
    .where_(revenue_amount.gt("1000.00".parse::<rust_decimal::Decimal>()?))
    .select((Restaurants::name(), revenue_amount));

A newly computed heading is typed once; generated base-table columns remain zero-ceremony. DBQC derives the dependency DAG and emits CTEs in valid order.

Windows, JSON, and pagination

let feed = Orders::source()
    .select((
        Orders::id(),
        window(
            row_number(),
            (Orders::restaurant_id(),),
            [desc(Orders::created_at())],
        )
        .as_("number"),
    ))
    .page(25, 0, [desc(Orders::created_at())]);
let contacts = Restaurants::source().select((
    Restaurants::id(),
    Restaurants::metadata()
        .expr()
        .json_path_text("$.contact.email")
        .as_("email"),
));

Writes

let created = Restaurants::source().insert([
    Restaurants::id().set(uuid::Uuid::new_v4()),
    Restaurants::name().set("Saffron"),
    Restaurants::city().set("New York"),
]);

let moved = Restaurants::source().update(
    Restaurants::id().eq_value(restaurant_id),
    [Restaurants::city().set("Brooklyn")],
);

let removed = Restaurants::source().delete(
    Restaurants::status().eq_value("closed"),
);

The explicit insert_values, insert_from, conflict-policy, update-from, returning, transaction, and procedure methods remain available for their less-common shapes.

Recursive queries

Recursive output is dynamic, so its heading is declared once:

let tree = Dsl::cte_ref(
    "tree",
    &[("id", "uuid"), ("parent_id", "uuid")],
);
let seed = Roots::source().select((Roots::id(), Roots::parent_id()));
let step = Nodes::source()
    .inner_join(
        &tree,
        Nodes::parent_id().expr().eq(&tree.column("id", "uuid")),
    )
    .select((Nodes::id(), Nodes::parent_id()));
let query = Dsl::with_recursive("tree", &seed, &step, &tree);

Use with_recursive_distinct when recursive UNION semantics are required for deduplication or cycle termination.

Compile and execute

let compiled = ranked.compile("psql")?;
let rows = sqlx::query(&compiled.sql)
    // bind values in compiled.param_order
    .fetch_all(&pool)
    .await?;

DBQC compiles and describes results; the normal Rust database driver executes them. Set DBQC_ENDPOINT and DBQC_KEY, or use the explicit compile overload.

Escape hatch

raw_expr() and raw_source() support vendor features DBQC does not model. Keep them isolated so normal queries retain type checks, dependency ordering, and dialect portability.