Skip to main content

Crate rqb

Crate rqb 

Source
Expand description

SQL-first Postgres query builder for Rust services.

rqb is not an ORM. Application code owns SQL shape, rqb validates the typed AST before rendering, and values are passed to Postgres as sqlx bind arguments. It is not a complete compile-time SQL type system: typed fields and bind values make common service queries hard to mix up, but operator legality, statement shape, and raw bind counts are runtime validation checks that fail at .build()?.

§Basic shape

Start with schema metadata. In applications this usually comes from rqb-cli and the schema! macro; small examples can write the macro directly.

ⓘ
rqb::schema! {
    table public.users {
        id: uuid = uuid::Uuid,
        email: text = String,
        active: bool = bool,
    }
}

let u = users::alias("u");
let query = rqb::select(&u)
    .column(u.id())
    .column(u.email())
    .filter(u.active().eq(true))
    .build()?;

select(table()) projects known metadata fields, not SELECT *. Joined fields and computed expressions stay explicit.

§Imports

prelude contains the builders, core AST types, schema support, execution traits, and structured errors that normal service modules use. Broad SQL helper names such as lower, left, array, row, and replace are available at the crate root for qualified calls, but are intentionally kept out of prelude. The Result alias is also kept qualified as rqb::Result so application entry points can keep using their normal error type. Import SQL helpers from dsl when a module wants short names.

ⓘ
use rqb::prelude::*;
use rqb::dsl::{count_all, date_trunc, sum};

§Execution

Statements build parameterized Postgres SQL and execute through sqlx executors:

ⓘ
#[derive(sqlx::FromRow)]
struct UserRow {
    id: uuid::Uuid,
    email: String,
}

let users = rqb::select(users::table())
    .columns((users::ID, users::EMAIL))
    .filter(users::ACTIVE.eq(true))
    .fetch_all_as::<UserRow>(&pool)
    .await?;

Service functions can accept &PgPool by default. Reuse query-shape helper functions when the same statement should run inside a transaction. Use impl PgExecutor<'_> for small helpers that should execute directly from both pool-backed code and transaction code. Pool-owned streaming helpers are available for HTTP response streams where the returned stream must own the built query.

§JSON search boundary

SearchRequest lets client JSON control filters, sort, limit, and offset only over fields exposed with Meta::json. It cannot define tables, joins, raw SQL, CTEs, writes, subqueries, or projections. Use Select::apply_search to preserve tenant, permission, and other server-owned filters. When a request should own the whole search clause, start from a fresh select(...) and call Select::apply_search there. LIKE and regex-style search operators require text-pattern field capability and reject very long client patterns before SQL is rendered; still set statement timeouts at HTTP or job boundaries for public search endpoints.

§Writes and raw SQL

Writes use field assignments or #[derive(Insertable)] / #[derive(Changeset)]; there is no serde JSON write bridge. Raw SQL is still server-owned and stays parameterized through raw, raw_expr, raw_predicate, and raw_source. Raw placeholders are SQL-aware, but any raw fragment disables persistent prepared-statement caching for the whole built query.

Modules§

dsl
SQL expression and source helpers that are useful on demand but too broad for the prelude.
prelude
Common imports for application query code.

Macros§

field
Creates a metadata-backed computed field for CTEs, subqueries, and projections.
jsonb_agg_object
Builds jsonb_agg(jsonb_build_object(...)) from metadata-backed fields.
schema
Generates compact rqb schema modules.
tx
Runs an async expression or block in a sqlx transaction.

Structs§

Assignment
Field assignment used by insert, update, merge, and changesets.
BuiltQuery
Rendered SQL plus its bind parameters.
CaseBuilder
Builder for SQL CASE WHEN ... THEN ... ELSE ... END expressions.
ColumnConflictBuilder
Pending column-target conflict clause on an InsertRow or Insert. Completing the clause returns the same host type I.
ConstraintConflictBuilder
Pending named-constraint conflict clause on an InsertRow or Insert. Completing the clause returns the same host type I.
ConstraintError
Payload for Postgres constraint-class errors.
Cte
Common table expression definition.
CteShapeError
Payload for CTE shape validation failures.
DatabaseFailure
Payload for mapped or unmapped Postgres database failures.
DbErrorInfo
Structured metadata extracted from a Postgres database error.
Delete
Typed delete statement.
Field
Typed database field generated from schema metadata.
FieldRef
Qualified typed database field, usually created through an alias handle.
FunctionSource
Table-valued function source before it enters the general Source enum.
Insert
INSERT with a selected body, without additive single-row setters.
InsertRow
Editable single-row INSERT returned by insert().
MatchedMergeBuilder
Builder returned by Merge::when_matched().
Merge
Typed PostgreSQL MERGE statement.
Meta
Field metadata used for validation, rendering, and JSON search exposure.
NotMatchedBySourceMergeBuilder
Builder returned by Merge::when_not_matched_by_source().
NotMatchedMergeBuilder
Builder returned by Merge::when_not_matched().
OffsetWindowFunctionBuilder
Builder for lag / lead window functions.
OpSet
Operator capability flags for a field.
OperatorError
Payload for field/operator validation failures.
OrderItem
One ORDER BY expression.
Param
Type-erased value that can be bound to Postgres through sqlx.
Params
Ordered bind parameters for a built query.
PgConnection
A connection to a PostgreSQL database.
PgFailure
Payload for Postgres failures without a dedicated constraint or column shape.
RawStmt
Server-owned raw SQL statement.
SearchPredicate
A single JSON search predicate.
SearchRequest
Client-supplied filtering, sorting, and pagination for a server-owned query.
SearchSort
A client-supplied sort key.
SearchValueError
Payload for JSON search value validation failures.
Select
Typed select statement.
SetQuery
SQL set query with optional ordering and row limits.
Update
Typed update statement.
WindowFrame
Window frame specification.
WindowFunctionBuilder
Builder for window functions without offset/default arguments.
WindowSpec
Window specification used by OVER (...).
WriteTargetError
Payload for write-target validation failures.

Enums§

AdvisoryLockKey
PostgreSQL advisory lock key.
BoolExpr
Boolean expression AST.
BoolOp
Binary comparison operator.
DatePart
Stable date/time part names accepted by helpers such as date_trunc.
DbErrorPosition
Position metadata reported by Postgres for a database error.
Error
Error type returned by rqb builders and sqlx execution helpers.
FrameBound
Window frame boundary.
FrameExclude
Window frame exclusion clause.
JsonKind
JSON value kind accepted by a field in SearchRequest.
LockMode
PostgreSQL row lock mode.
SearchFilter
Boolean filter tree accepted by SearchRequest.
SearchOperator
Operators supported by the JSON search API.
SortDirection
Sort direction for SearchSort.
Source
Relation-like object that can appear in a FROM, JOIN, UPDATE, or write target.
Stmt
Any top-level query statement rqb can render.
ValueExpr
SQL value expression AST.
ValueOp
Arithmetic or custom value operator.
WindowFrameKind
Window frame unit.
WindowFunction
Supported SQL window function names.

Traits§

BindValue
Rust value that can be stored as a Postgres bind parameter.
Changeset
Trait implemented by DTOs that can provide update assignments.
ConflictFields
Column set accepted by Insert::on_conflict(...).
Insertable
Trait implemented by DTOs that can provide insert assignments.
PgExecutor
An alias for Executor<'_, Database = Postgres>.
ScalarValue
Rust value that can be decoded from a single Postgres result column.

Functions§

abs
Builds abs(expr).
age
Builds age(...) with one or two arguments.
aggregate
Builds a generic aggregate function call.
and
Builds a logical AND group.
any_value
Builds any_value(expr).
array
Builds an SQL array expression from value expressions.
array_agg
Builds array_agg(expr).
array_agg_distinct
Builds array_agg(DISTINCT expr).
array_append
Builds array_append(expr, value).
array_cat
Builds array_cat(left, right).
array_dims
Builds array_dims(expr).
array_fill
Builds array_fill(value, dimensions).
array_fill_with_lower_bounds
Builds array_fill(value, dimensions, lower_bounds).
array_length
Builds array_length(expr, dimension).
array_lower
Builds array_lower(expr, dimension).
array_ndims
Builds array_ndims(expr).
array_position
Builds array_position(expr, value).
array_positions
Builds array_positions(expr, value).
array_prepend
Builds array_prepend(value, expr).
array_remove
Builds array_remove(expr, value).
array_replace
Builds array_replace(expr, from, to).
array_reverse
Builds array_reverse(expr).
array_sample
Builds array_sample(expr, count).
array_shuffle
Builds array_shuffle(expr).
array_sort
Builds array_sort(expr).
array_sort_desc
Builds array_sort(expr, true, false).
array_sort_with
Builds array_sort(expr, descending, nulls_first).
array_to_json
Builds array_to_json(array).
array_to_string
Builds array_to_string(expr, delimiter).
array_upper
Builds array_upper(expr, dimension).
ascii
Builds ascii(expr).
avg
Builds avg(expr).
avg_distinct
Builds avg(DISTINCT expr).
bit_and
Builds bit_and(expr).
bit_or
Builds bit_or(expr).
bit_xor
Builds bit_xor(expr).
bool_and
Builds bool_and(expr).
bool_or
Builds bool_or(expr).
btrim
Builds btrim(expr).
cardinality
Builds cardinality(expr).
case
Starts a SQL CASE expression builder.
casefold
Builds casefold(expr).
cbrt
Builds cbrt(expr).
ceil
Builds ceil(expr).
char_length
Builds char_length(expr).
chr
Builds chr(code).
coalesce
Builds coalesce(...).
concat
Builds concat(...).
concat_op
Builds a Postgres || concatenation expression.
concat_ws
Builds concat_ws(separator, ...).
count
Builds count(expr).
count_all
Builds count(*).
count_distinct
Builds count(DISTINCT expr).
crc32
Builds crc32(expr).
crc32c
Builds crc32c(expr).
cte
Creates a CTE with explicit exposed field metadata.
cte_ref
Creates a source reference to a CTE defined elsewhere in the same query.
cume_dist
Builds cume_dist().
current_database
Builds current_database().
current_date
Builds the CURRENT_DATE SQL keyword.
current_row
Returns CURRENT ROW.
current_schema
Builds the CURRENT_SCHEMA SQL keyword.
current_timestamp
Builds the CURRENT_TIMESTAMP SQL keyword.
current_user
Builds the CURRENT_USER SQL keyword.
date_bin
Builds date_bin(stride, source, origin).
date_trunc
Builds date_trunc(part, expr).
date_trunc_part
Builds date_trunc('part', expr) with a typed static date part.
decode
Builds decode(text, format).
degrees
Builds degrees(expr).
delete_from
Starts a typed DELETE FROM statement.
dense_rank
Builds dense_rank().
div
Builds div(left, right).
encode
Builds encode(bytea, format).
every
Builds every(expr).
except
Builds an EXCEPT set query.
except_all
Builds an EXCEPT ALL set query.
exists
Builds an EXISTS (...) predicate from a server-owned subquery.
exp
Builds exp(expr).
extract
Builds EXTRACT(field FROM expr).
factorial
Builds factorial(expr).
false_
Builds a SQL FALSE predicate.
first_value
Builds first_value(expr).
floor
Builds floor(expr).
following
Returns expr FOLLOWING.
format
Builds format(format, ...).
function
Builds a generic SQL function call.
function_source
Creates a table-valued function source with explicit exposed fields.
gamma
Builds gamma(expr).
gcd
Builds gcd(left, right).
gen_random_uuid
Builds gen_random_uuid().
generate_series_source
Creates a generate_series(start, stop) table-valued function source.
generate_series_step_source
Creates a generate_series(start, stop, step) table-valued function source.
generate_subscripts_source
Creates a generate_subscripts(array, dim) table-valued function source.
greatest
Builds greatest(...).
grouping
Builds GROUPING(...) for grouped reports using rollups, cubes, or grouping sets.
groups
Starts a GROUPS frame.
initcap
Builds initcap(expr).
insert
Starts a typed INSERT statement.
intersect
Builds an INTERSECT set query.
intersect_all
Builds an INTERSECT ALL set query.
isempty
Builds isempty(range).
isfinite
Builds isfinite(value).
json
Builds the SQL/JSON json(expr) constructor.
json_agg
Builds json_agg(expr).
json_agg_strict
Builds json_agg_strict(expr).
json_array_elements_source
Creates a json_array_elements(json) source.
json_array_length
Builds json_array_length(expr).
json_build_array
Builds json_build_array(...).
json_build_object
Builds json_build_object(...).
json_each_source
Creates a json_each(json) source.
json_exists
Builds json_exists(target, path) as a boolean predicate.
json_get
Builds the Postgres target -> key JSON access expression.
json_get_text
Builds the Postgres target ->> key JSON text access expression.
json_object
Builds json_object(expr).
json_object_agg
Builds json_object_agg(key, value).
json_object_agg_strict
Builds json_object_agg_strict(key, value).
json_object_agg_unique
Builds json_object_agg_unique(key, value).
json_object_agg_unique_strict
Builds json_object_agg_unique_strict(key, value).
json_object_keys_source
Creates a json_object_keys(json) source.
json_path
Builds the Postgres target #> path JSON path expression.
json_path_text
Builds the Postgres target #>> path JSON path text expression.
json_query
Builds json_query(target, path).
json_scalar
Builds the SQL/JSON json_scalar(expr) constructor.
json_serialize
Builds json_serialize(expr).
json_typeof
Builds json_typeof(expr).
json_value
Builds json_value(target, path).
jsonb_agg
Builds jsonb_agg(expr).
jsonb_agg_object
Builds jsonb_agg(jsonb_build_object(...)) from fields or explicit key/value pairs.
jsonb_agg_strict
Builds jsonb_agg_strict(expr).
jsonb_array_elements
Builds jsonb_array_elements(expr).
jsonb_array_elements_source
Creates a jsonb_array_elements(jsonb) source.
jsonb_array_length
Builds jsonb_array_length(expr).
jsonb_build_array
Builds jsonb_build_array(...).
jsonb_build_object
Builds jsonb_build_object(...).
jsonb_delete
Builds the Postgres jsonb - key delete expression.
jsonb_each
Builds jsonb_each(expr).
jsonb_each_source
Creates a jsonb_each(jsonb) source.
jsonb_insert
Builds jsonb_insert(target, path, new_value).
jsonb_object
Builds jsonb_object(expr).
jsonb_object_agg
Builds jsonb_object_agg(key, value).
jsonb_object_agg_strict
Builds jsonb_object_agg_strict(key, value).
jsonb_object_agg_unique
Builds jsonb_object_agg_unique(key, value).
jsonb_object_agg_unique_strict
Builds jsonb_object_agg_unique_strict(key, value).
jsonb_object_keys_source
Creates a jsonb_object_keys(jsonb) source.
jsonb_path_exists
Builds jsonb_path_exists(target, path::jsonpath) as a boolean predicate.
jsonb_path_query
Builds jsonb_path_query(target, path::jsonpath). String paths stay bound parameters.
jsonb_pretty
Builds jsonb_pretty(expr).
jsonb_set
Builds jsonb_set(target, path, new_value).
jsonb_strip_nulls
Builds jsonb_strip_nulls(expr).
jsonb_typeof
Builds jsonb_typeof(expr).
lag
Builds lag(expr).
last_value
Builds last_value(expr).
lcm
Builds lcm(left, right).
lead
Builds lead(expr).
least
Builds least(...).
left
Builds left(expr, count).
length
Builds length(expr).
lgamma
Builds lgamma(expr).
literal
Builds a server-owned static SQL string literal.
ln
Builds ln(expr).
log
Builds log(...).
lower
Builds lower(expr).
lower_inc
Builds lower_inc(range).
lower_inf
Builds lower_inf(range).
lpad
Builds lpad(expr, length, fill).
ltrim
Builds ltrim(expr).
make_date
Builds make_date(year, month, day).
make_time
Builds make_time(hour, min, sec).
make_timestamp
Builds make_timestamp(...).
make_timestamptz
Builds make_timestamptz(...).
max
Builds max(expr).
md5
Builds md5(expr).
merge_action
Builds the Postgres merge_action() helper expression.
merge_into
Starts a typed PostgreSQL MERGE statement.
min
Builds min(expr).
mod_
Builds mod(left, right).
mode
Builds mode() WITHIN GROUP (ORDER BY order_by ASC).
normalize
Builds normalize(expr).
normalize_form
Builds normalize(expr, form) where form is a PostgreSQL normalization keyword.
not
Negates a predicate.
not_similar_to
Builds a negated SIMILAR TO predicate.
now
Builds now().
nth_value
Builds nth_value(expr, nth).
ntile
Builds ntile(buckets).
null
Builds the SQL NULL literal.
nullif
Builds nullif(left, right).
octet_length
Builds octet_length(expr).
or
Builds a logical OR group.
ordered_set_aggregate
Builds an ordered-set aggregate with a WITHIN GROUP ordering.
param
Wraps an owned Rust value as a typed bind parameter expression.
percent_rank
Builds percent_rank().
percentile_cont
Builds percentile_cont(fraction) WITHIN GROUP (ORDER BY order_by ASC).
percentile_disc
Builds percentile_disc(fraction) WITHIN GROUP (ORDER BY order_by ASC).
phraseto_tsquery
Builds phraseto_tsquery(query).
phraseto_tsquery_config
Builds phraseto_tsquery(config::regconfig, query).
pi
Builds pi().
plainto_tsquery
Builds plainto_tsquery(query).
pow
Alias for power(left, right).
power
Builds power(left, right).
preceding
Returns expr PRECEDING.
radians
Builds radians(expr).
random
Builds random().
random_between
Builds random(min, max) for Postgres versions that support bounds.
range
Starts a RANGE frame.
range_agg
Builds range_agg(expr).
range_intersect_agg
Builds range_intersect_agg(expr).
range_lower
Builds lower(range).
range_merge
Returns the smallest range containing a multirange via range_merge(multirange). For the two-range overload, use function("range_merge", [left, right]).
range_upper
Builds upper(range).
rank
Builds rank().
raw
Starts a server-owned raw SQL statement.
raw_expr
Builds a server-owned raw value expression with rqb ? placeholders.
raw_predicate
Builds a server-owned raw predicate with rqb ? placeholders.
raw_source
Creates a raw SQL source with explicit exposed field metadata.
regexp_matches
Builds regexp_matches(...).
regexp_replace
Builds regexp_replace(...).
regexp_split_to_array
Builds regexp_split_to_array(text, pattern).
regexp_split_to_table_source
Creates a regexp_split_to_table(text, pattern) source.
repeat
Builds repeat(text, count).
replace
Builds replace(text, from, to).
reverse
Builds reverse(expr).
right
Builds right(expr, count).
round
Builds round(...).
row
Builds an SQL row expression from value expressions.
row_number
Builds row_number().
row_to_json
Builds row_to_json(row).
rows
Starts a ROWS frame.
rpad
Builds rpad(expr, length, fill).
rtrim
Builds rtrim(expr).
scalar_subquery
Builds a scalar subquery value expression.
select
Starts a typed SELECT statement.
session_user
Builds the SESSION_USER SQL keyword.
sign
Builds sign(expr).
similar_to
Builds a SIMILAR TO predicate.
slice
Builds an array or JSON slice expression.
split_part
Builds split_part(text, delimiter, field).
sqrt
Builds sqrt(expr).
starts_with
Builds starts_with(text, prefix).
stddev
Builds stddev(expr).
stddev_pop
Builds stddev_pop(expr).
stddev_samp
Builds stddev_samp(expr).
string_agg
Builds string_agg(expr, delimiter).
string_to_array
Builds string_to_array(expr, delimiter).
strpos
Builds strpos(text, substring).
subquery
Creates a subquery source with explicit exposed field metadata.
subscript
Builds an array or JSON subscript expression.
substring
Builds substring(...).
sum
Builds sum(expr).
sum_distinct
Builds sum(DISTINCT expr).
table
Creates a table source from static metadata.
timezone
Builds timezone(zone, expr).
to_char
Builds to_char(value, format).
to_date
Builds to_date(text, format).
to_json
Builds to_json(expr).
to_jsonb
Builds to_jsonb(expr).
to_number
Builds to_number(text, format).
to_timestamp
Builds to_timestamp(text, format).
to_tsquery
Builds to_tsquery(query).
to_tsvector
Builds to_tsvector(document).
to_tsvector_config
Builds to_tsvector(config::regconfig, document).
translate
Builds translate(text, from, to).
trim
Builds trim(expr).
trim_array
Builds trim_array(expr, n).
true_
Builds a SQL TRUE predicate.
trunc
Builds trunc(...).
ts_headline
Builds ts_headline(...).
ts_match
Builds a full-text @@ match predicate.
ts_rank
Builds ts_rank(vector, query).
ts_rank_cd
Builds ts_rank_cd(vector, query).
unbounded_following
Returns UNBOUNDED FOLLOWING.
unbounded_preceding
Returns UNBOUNDED PRECEDING.
unicode_assigned
Builds unicode_assigned(expr).
union
Builds a UNION set query.
union_all
Builds a UNION ALL set query.
unnest
Builds unnest(expr).
unnest_source
Creates an unnest(array) table-valued function source.
update
Starts a typed UPDATE statement.
upper
Builds upper(expr).
upper_inc
Builds upper_inc(range).
upper_inf
Builds upper_inf(range).
uuid_extract_timestamp
Builds uuid_extract_timestamp(uuid).
uuid_extract_version
Builds uuid_extract_version(uuid).
uuidv4
Builds uuidv4().
uuidv7
Builds uuidv7().
uuidv7_shift
Builds uuidv7(shift).
values_source
Creates a FROM (VALUES ...) AS alias(columns...) source.
var_pop
Builds var_pop(expr).
var_samp
Builds var_samp(expr).
variance
Builds variance(expr).
version
Builds version().
view
Creates a view source from static metadata.
websearch_to_tsquery
Builds websearch_to_tsquery(query).
width_bucket
Builds width_bucket(operand, low, high, count).
window
Starts a window specification.

Type Aliases§

PgPool
An alias for Pool, specialized for Postgres.
Result
rqb result type.

Derive Macros§

Changeset
Derives rqb::Changeset for patch DTOs.
Insertable
Derives rqb::Insertable for a DTO.