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.
- Built
Query - Rendered SQL plus its bind parameters.
- Case
Builder - Builder for SQL
CASE WHEN ... THEN ... ELSE ... ENDexpressions. - Column
Conflict Builder - Pending column-target conflict clause on an
InsertRoworInsert. Completing the clause returns the same host typeI. - Constraint
Conflict Builder - Pending named-constraint conflict clause on an
InsertRoworInsert. Completing the clause returns the same host typeI. - Constraint
Error - Payload for Postgres constraint-class errors.
- Cte
- Common table expression definition.
- CteShape
Error - Payload for CTE shape validation failures.
- Database
Failure - Payload for mapped or unmapped Postgres database failures.
- DbError
Info - Structured metadata extracted from a Postgres database error.
- Delete
- Typed delete statement.
- Field
- Typed database field generated from schema metadata.
- Field
Ref - Qualified typed database field, usually created through an alias handle.
- Function
Source - Table-valued function source before it enters the general
Sourceenum. - Insert
- INSERT with a selected body, without additive single-row setters.
- Insert
Row - Editable single-row INSERT returned by
insert(). - Matched
Merge Builder - Builder returned by
Merge::when_matched(). - Merge
- Typed PostgreSQL
MERGEstatement. - Meta
- Field metadata used for validation, rendering, and JSON search exposure.
- NotMatched
BySource Merge Builder - Builder returned by
Merge::when_not_matched_by_source(). - NotMatched
Merge Builder - Builder returned by
Merge::when_not_matched(). - Offset
Window Function Builder - Builder for
lag/leadwindow functions. - OpSet
- Operator capability flags for a field.
- Operator
Error - Payload for field/operator validation failures.
- Order
Item - One
ORDER BYexpression. - 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.
- Search
Predicate - A single JSON search predicate.
- Search
Request - Client-supplied filtering, sorting, and pagination for a server-owned query.
- Search
Sort - A client-supplied sort key.
- Search
Value Error - 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.
- Window
Frame - Window frame specification.
- Window
Function Builder - Builder for window functions without offset/default arguments.
- Window
Spec - Window specification used by
OVER (...). - Write
Target Error - Payload for write-target validation failures.
Enums§
- Advisory
Lock Key - PostgreSQL advisory lock key.
- Bool
Expr - Boolean expression AST.
- BoolOp
- Binary comparison operator.
- Date
Part - Stable date/time part names accepted by helpers such as
date_trunc. - DbError
Position - Position metadata reported by Postgres for a database error.
- Error
- Error type returned by rqb builders and sqlx execution helpers.
- Frame
Bound - Window frame boundary.
- Frame
Exclude - Window frame exclusion clause.
- Json
Kind - JSON value kind accepted by a field in
SearchRequest. - Lock
Mode - PostgreSQL row lock mode.
- Search
Filter - Boolean filter tree accepted by
SearchRequest. - Search
Operator - Operators supported by the JSON search API.
- Sort
Direction - 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.
- Value
Expr - SQL value expression AST.
- ValueOp
- Arithmetic or custom value operator.
- Window
Frame Kind - Window frame unit.
- Window
Function - Supported SQL window function names.
Traits§
- Bind
Value - Rust value that can be stored as a Postgres bind parameter.
- Changeset
- Trait implemented by DTOs that can provide update assignments.
- Conflict
Fields - Column set accepted by
Insert::on_conflict(...). - Insertable
- Trait implemented by DTOs that can provide insert assignments.
- PgExecutor
- An alias for
Executor<'_, Database = Postgres>. - Scalar
Value - 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
ANDgroup. - 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
CASEexpression 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_DATESQL keyword. - current_
row - Returns
CURRENT ROW. - current_
schema - Builds the
CURRENT_SCHEMASQL keyword. - current_
timestamp - Builds the
CURRENT_TIMESTAMPSQL keyword. - current_
user - Builds the
CURRENT_USERSQL 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 FROMstatement. - dense_
rank - Builds
dense_rank(). - div
- Builds
div(left, right). - encode
- Builds
encode(bytea, format). - every
- Builds
every(expr). - except
- Builds an
EXCEPTset query. - except_
all - Builds an
EXCEPT ALLset 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
FALSEpredicate. - 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
GROUPSframe. - initcap
- Builds
initcap(expr). - insert
- Starts a typed
INSERTstatement. - intersect
- Builds an
INTERSECTset query. - intersect_
all - Builds an
INTERSECT ALLset 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 -> keyJSON access expression. - json_
get_ text - Builds the Postgres
target ->> keyJSON 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 #> pathJSON path expression. - json_
path_ text - Builds the Postgres
target #>> pathJSON 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 - keydelete 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
MERGEstatement. - 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 TOpredicate. - now
- Builds
now(). - nth_
value - Builds
nth_value(expr, nth). - ntile
- Builds
ntile(buckets). - null
- Builds the SQL
NULLliteral. - nullif
- Builds
nullif(left, right). - octet_
length - Builds
octet_length(expr). - or
- Builds a logical
ORgroup. - ordered_
set_ aggregate - Builds an ordered-set aggregate with a
WITHIN GROUPordering. - 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
RANGEframe. - 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, usefunction("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
ROWSframe. - rpad
- Builds
rpad(expr, length, fill). - rtrim
- Builds
rtrim(expr). - scalar_
subquery - Builds a scalar subquery value expression.
- select
- Starts a typed
SELECTstatement. - session_
user - Builds the
SESSION_USERSQL keyword. - sign
- Builds
sign(expr). - similar_
to - Builds a
SIMILAR TOpredicate. - 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
TRUEpredicate. - 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
UNIONset query. - union_
all - Builds a
UNION ALLset query. - unnest
- Builds
unnest(expr). - unnest_
source - Creates an
unnest(array)table-valued function source. - update
- Starts a typed
UPDATEstatement. - 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§
Derive Macros§
- Changeset
- Derives
rqb::Changesetfor patch DTOs. - Insertable
- Derives
rqb::Insertablefor a DTO.