Expand description
Type-safe SQL expressions: comparisons, logic, aggregates and functions.
Every expression carries three facts in its type:
- its SQL type, such as the dialect’s integer or text type;
- whether it can be NULL (
NonNullorNull); - whether it is a plain value or an aggregate (
ScalarorAgg).
The functions in this module read those facts from their arguments and
compute them for their result. Comparing a number with text, summing a text
column, or calling a PostgreSQL-only function on SQLite fails to compile.
Expressions also record which tables they read (ExprSources); a query
checks that against its FROM/JOIN scope.
Rust values (i32, &str, bool, …) can be used wherever an expression
is expected. They are sent as bound parameters (? on SQLite and MySQL,
$1, $2, … on PostgreSQL).
The examples in this module use a users table with the columns id,
age (integer), name (text), email (nullable text), score (nullable
real), active (boolean) and created_at (timestamp).
§Examples
let adults = and(gt(users.age, 18), like(users.name, "A%"));
assert_eq!(adults.sql(), r#"("users"."age" > ? AND "users"."name" LIKE ?)"#);
// Arithmetic uses the Rust operators.
let next_year = users.age.clone() + 1;
assert_eq!(next_year.sql(), r#""users"."age" + ?"#);Comparing an integer column with text does not compile:
let wrong = eq(users.age, "hello");Structs§
- Agg
- Aggregate marker: an aggregate expression such as
COUNT(...)orSUM(...). - Aliased
Expr - An expression renamed with
AS "name"; created byaliasorAliasExt::alias. - AllAgg
- SELECT-list status: every selected expression is an aggregate.
- AllScalar
- SELECT-list status: every selected expression is scalar.
- Case
Builder - A
CASEbuilder with at least one branch. - Case
Init - A
CASEbuilder before its first branch; created bycase. - Excluded
- A column of the row that failed to insert (
EXCLUDED."column"); created byexcluded. - Mixed
Agg - SELECT-list status: the list mixes scalar and aggregate expressions.
- Named
Expr - An expression whose output name is a type-level
Tag; created byAliasExt::named. - NonNull
- Nullability marker: the expression is never NULL.
- Null
- Nullability marker: the expression can be NULL.
- SQLExpr
- A SQL fragment together with its type information.
- Scalar
- Aggregate marker: a plain per-row expression (not an aggregate).
- Window
FnExpr - A window function that still needs its
OVER (...)clause. - Window
Spec - The contents of an
OVER (...)clause; start one withwindow.
Enums§
- Frame
Bound - One end of a window frame, for
WindowSpec::rows_betweenandWindowSpec::range_between.
Traits§
- Aggregate
Kind - Type-level marker saying whether an expression is an aggregate.
- Aggregate
Policy - Result types of
sumandavgfor a numeric SQL type on dialectD. - Alias
Ext - Method syntax for naming a selected expression.
- Boolean
Aggregate Policy - SQL types that
BOOL_AND,BOOL_ORandEVERYaccept on dialectD. - Cast
Target - The target argument of
cast: a SQL type name such as"VARCHAR(255)", or a type marker value whoseDefaultCastTypeNameis used. - Cast
Type Policy - Casts from
SourcetoTargetthat dialectDallows. - Combine
AggStatus - Combines the SELECT-list statuses of two expressions.
- Comparison
Operand - A value that can be the right-hand side of a comparison with
L. - Condition
List - A tuple of conditions that
allandanycan combine. - Date
Trunc Policy - Temporal types that
date_truncaccepts on dialectD, and its result type. On PostgreSQL,timestampandtimestamptzare accepted and keep their type. - Default
Cast Type Name - The SQL type name
castwrites when given a type marker, such as"INTEGER"for SQLite’sInteger. - Expr
- A typed SQL expression.
- ExprExt
- Method syntax for comparisons:
users.age.gt(18)instead ofgt(users.age, 18). - Expr
Sources - The tables an expression reads, as a type-level tree.
- Greatest
Least Policy - How
GREATESTandLEASTtreat NULL on a dialect. - HasAgg
Status - The SELECT-list status of a type that can appear in a SELECT list.
- InSubquery
Lhs - Left side of
in_subqueryandnot_in_subquery. - Instr
Policy - Dialects that provide
instr(SQLite and MySQL), and its result type. - Length
Policy - Result type of
length,char_lengthandoctet_lengthfor a text SQL type on dialectD:INTEGERon SQLite,int4on PostgreSQL,BIGINTon MySQL. - Log2
Policy - Dialects that provide
LOG2, and the nullability of its result. - MathExt
- Dialects that provide the optional math functions.
- Nullability
- Type-level marker saying whether an expression can be NULL.
- Rounding
Policy - Result type of
round,round_to,ceil,floorandtruncfor a numeric SQL type on dialectD. - Select
Query - A complete
SELECTstatement, accepted byexistsandnot_exists. - Statistical
Aggregate Policy - Result types of the standard deviation and variance aggregates for a
numeric SQL type on dialect
D. - Subquery
Type - Maps a select marker (the type-level record of what a query selects) to the SQL type the query produces as a subquery.
Functions§
- abs
- Absolute value (
ABS). - age
- The interval between two timestamps (
AGE(a, b), that isa - b), on PostgreSQL. - alias
- Renames an expression:
expr AS "name". - all
- Logical AND of every condition in a tuple.
- and
- Logical AND of two conditions.
- any
- Logical OR of every condition in a tuple.
- array_
agg - Collects values into a SQL array (
ARRAY_AGG), on PostgreSQL. - avg
- Average of numeric values (
AVG). - avg_
distinct - Average of distinct numeric values (
AVG(DISTINCT expr)). - between
- Range check (
BETWEEN), inclusive on both ends. - bool_
and - True when every non-NULL input is true (
BOOL_AND), on PostgreSQL. - bool_or
- True when any non-NULL input is true (
BOOL_OR), on PostgreSQL. - case
- Starts a searched
CASEexpression. - cast
- Converts an expression to another SQL type (
CAST(expr AS type)). - ceil
- Rounds up to the nearest integer (
CEIL). - char_
length - Number of characters in a text value.
- clock_
timestamp - The actual wall-clock time (
CLOCK_TIMESTAMP()), on PostgreSQL. - coalesce
- The first non-NULL of two values (
COALESCE(expr, default)). - coalesce_
many - The first non-NULL of several values (
COALESCE(first, rest...)). - collate
- Applies a collation to a text expression (
expr COLLATE "name"). - concat
- Joins two text values.
- concat_
ws - Joins values with a separator, skipping NULLs (
CONCAT_WS). - count
- Row or value count (
COUNT). - count_
distinct - Count of distinct non-NULL values (
COUNT(DISTINCT expr)). - cume_
dist - Fraction of rows ordered at or before this row (
CUME_DIST()). - current_
date - The current date (
CURRENT_DATE), on every dialect. - current_
time - The current time (
CURRENT_TIME), on every dialect. - current_
timestamp - The current date and time (
CURRENT_TIMESTAMP), on every dialect. - currval
- The value most recently returned by
NEXTVALfor a sequence in this session (CURRVAL), on PostgreSQL. - date
- The date part of a time value (
DATE), on SQLite. - date_
bin - Rounds a timestamp down into fixed-size buckets (
DATE_BIN), on PostgreSQL 14+. - date_
trunc - Truncates a timestamp to a unit (
DATE_TRUNC(unit, expr)), on PostgreSQL. - datetime
- A time value as
YYYY-MM-DD HH:MM:SS(DATETIME), on SQLite. - dense_
rank - Rank of the row, without gaps after ties (
DENSE_RANK()). - distinct
- Prefixes an expression with
DISTINCT. - eq
- Equality comparison (
=). - every
- True when every non-NULL input is true (
EVERY), on PostgreSQL. - excluded
- Refers to the value a conflicting insert tried to write (
EXCLUDED."column"). - exists
- Whether a subquery returns any row (
EXISTS (SELECT ...)). - exp
- e raised to the argument (
EXP). - extract
- One field of a time value (
EXTRACT(field FROM expr)), on PostgreSQL. - first_
value - The value of
exprin the first row of the frame (FIRST_VALUE(expr)). - floor
- Rounds down to the nearest integer (
FLOOR). - greatest
- The larger of two values (
GREATEST(left, right)), on PostgreSQL and MySQL. - group_
concat - Joins text values with commas (
GROUP_CONCAT), on SQLite and MySQL. - gt
- Greater-than comparison (
>). - gte
- Greater-than-or-equal comparison (
>=). - ifnull
- The first value, or
defaultwhen it is NULL (IFNULL(expr, default)). - in_
array - Membership in a list of values (
expr IN (v1, v2, ...)). - in_
subquery - Membership in a subquery’s rows (
lhs IN (SELECT ...)). - initcap
- Capitalizes the first letter of each word (
INITCAP), on PostgreSQL. - instr
- Position of
searchwithin a text value (INSTR), on SQLite and MySQL. - is_
distinct_ from - NULL-safe inequality (
IS DISTINCT FROM). - is_
false - Falsity test (
IS FALSE) that never returns NULL. - is_
not_ distinct_ from - NULL-safe equality (
IS NOT DISTINCT FROM). - is_
not_ null - Non-NULL check (
IS NOT NULL). - is_null
- NULL check (
IS NULL). - is_true
- Truth test (
IS TRUE) that never returns NULL. - json_
agg - Collects values into a JSON array (
JSON_AGG), on PostgreSQL. - json_
object_ agg - Collects key/value pairs into a JSON object (
JSON_OBJECT_AGG), on PostgreSQL. - jsonb_
agg - Collects values into a JSONB array (
JSONB_AGG), on PostgreSQL. - jsonb_
object_ agg - Collects key/value pairs into a JSONB object (
JSONB_OBJECT_AGG), on PostgreSQL. - julianday
- A time value as a Julian day number (
JULIANDAY), on SQLite. - lag
- The value of
exprin the previous row (LAG(expr)). - lag_
with_ default - The value of
exproffsetrows back, ordefault(LAG(expr, offset, default)). - last_
value - The value of
exprin the last row of the frame (LAST_VALUE(expr)). - lead
- The value of
exprin the next row (LEAD(expr)). - lead_
with_ default - The value of
exproffsetrows ahead, ordefault(LEAD(expr, offset, default)). - least
- The smaller of two values (
LEAST(left, right)), on PostgreSQL and MySQL. - left
- The first
ncharacters of a text value (LEFT), on PostgreSQL and MySQL. - length
- Length of a text value (
LENGTH). - like
- Pattern match (
LIKE). - ln
- Natural logarithm (
LN). - localtime
- The current time without time zone (
LOCALTIME), on PostgreSQL. - localtimestamp
- The current date and time without time zone (
LOCALTIMESTAMP), on PostgreSQL. - log
- Logarithm of
valuein basebase(LOG(base, value)). - log2
- Base-2 logarithm (
LOG2), on SQLite and MySQL. - log10
- Base-10 logarithm (
LOG10). - lower
- Converts text to lower case (
LOWER). - lpad
- Pads a text value on the left to
lengthcharacters (LPAD), on PostgreSQL and MySQL. - lt
- Less-than comparison (
<). - lte
- Less-than-or-equal comparison (
<=). - ltrim
- Removes leading spaces (
LTRIM). - make_
date - Builds a date from year, month and day (
MAKE_DATE), on PostgreSQL. - make_
timestamp - Builds a timestamp from its parts (
MAKE_TIMESTAMP), on PostgreSQL. - max
- Largest value (
MAX). - min
- Smallest value (
MIN). - mod_
- Remainder of a division, rendered with the
%operator. - ne
- Inequality comparison (
<>). - neq
- Inequality comparison (
<>); same asne. - nextval
- Advances a sequence and returns the new value (
NEXTVAL), on PostgreSQL. - not
- Logical negation (
NOT). - not_
between - Negated range check (
NOT BETWEEN). - not_
exists - Whether a subquery returns no rows (
NOT EXISTS (SELECT ...)). - not_
in_ array - Non-membership in a list of values (
expr NOT IN (v1, v2, ...)). - not_
in_ subquery - Non-membership in a subquery’s rows (
lhs NOT IN (SELECT ...)). - not_
like - Negated pattern match (
NOT LIKE). - now
- The current date and time (
NOW()), on PostgreSQL. - nth_
value - The value of
exprin then-th row of the frame, from 1 (NTH_VALUE(expr, n)). - ntile
- Splits the partition into
ngroups of nearly equal size (NTILE(n)). - nullif
- NULL when two values are equal, otherwise the first (
NULLIF(a, b)). - octet_
length - Number of bytes in a text value (
OCTET_LENGTH). - or
- Logical OR of two conditions.
- percent_
rank - Relative rank:
(rank - 1) / (rows - 1)(PERCENT_RANK()). - pi
- The constant pi (
PI()). - power
baseraised toexponent(POWER).- random
- A random value.
- rank
- Rank of the row, with gaps after ties (
RANK()). - raw
- A raw SQL fragment with a declared SQL type, typed as nullable.
- raw_
non_ null - A raw SQL fragment with a declared SQL type, typed as non-null.
- raw_
nullable - A raw SQL fragment with a declared SQL type, typed as nullable; same as
raw. - regexp_
match - Capture groups of the first POSIX regular expression match (
REGEXP_MATCH), on PostgreSQL. - regexp_
match_ flags - Capture groups of the first POSIX regular expression match, with flags, on PostgreSQL.
- regexp_
replace - Replaces the first POSIX regular expression match (
REGEXP_REPLACE), on PostgreSQL. - regexp_
replace_ flags - Replaces POSIX regular expression matches, with flags, on PostgreSQL.
- repeat
- Repeats a text value
ntimes (REPEAT), on PostgreSQL and MySQL. - replace
- Replaces every occurrence of
fromwithto(REPLACE). - reverse
- Reverses a text value (
REVERSE), on PostgreSQL and MySQL. - right
- The last
ncharacters of a text value (RIGHT), on PostgreSQL and MySQL. - round
- Rounds to the nearest integer (
ROUND(expr)). - round_
to - Rounds to
precisiondecimal places (ROUND(expr, precision)). - row_
number - Number of the row within its partition, from 1 (
ROW_NUMBER()). - rpad
- Pads a text value on the right to
lengthcharacters (RPAD), on PostgreSQL and MySQL. - rtrim
- Removes trailing spaces (
RTRIM). - setval
- Sets a sequence’s current value (
SETVAL), on PostgreSQL. - sign
- Sign of a number: -1, 0 or 1 (
SIGN). - split_
part - The
n-th field of a text value split ondelimiter(SPLIT_PART), on PostgreSQL. - sqrt
- Square root (
SQRT). - starts_
with - Whether a text value starts with
prefix(STARTS_WITH), on PostgreSQL. - stddev_
pop - Population standard deviation (
STDDEV_POP), on PostgreSQL and MySQL. - stddev_
samp - Sample standard deviation (
STDDEV_SAMP), on PostgreSQL and MySQL. - strftime
- Formats a time value as text (
STRFTIME(format, expr)), on SQLite. - string_
agg - Joins text values with a delimiter (
STRING_AGG), on PostgreSQL. - string_
concat - Joins two text values; same as
concat. - strpos
- Position of
searchwithin a text value (STRPOS), on PostgreSQL. - substr
- Part of a text value (
SUBSTR(expr, start, len)). - sum
- Sum of numeric values (
SUM). - sum_
distinct - Sum of distinct numeric values (
SUM(DISTINCT expr)). - time
- The time part of a time value (
TIME), on SQLite. - timediff
- The difference between two time values as text (
TIMEDIFF), on SQLite 3.43+. - to_char
- Formats a time value as text (
TO_CHAR(expr, format)), on PostgreSQL. - to_date
- Parses text into a date using a format (
TO_DATE(text, format)), on PostgreSQL. - to_
number - Parses text into a number using a format (
TO_NUMBER(text, format)), on PostgreSQL. - to_
timestamp - Converts Unix time in seconds to a timestamp (
TO_TIMESTAMP), on PostgreSQL. - total
- Floating-point sum that is never NULL (
TOTAL), on SQLite. - translate
- Replaces characters one for one (
TRANSLATE), on PostgreSQL. - trim
- Removes leading and trailing spaces (
TRIM). - trunc
- Truncates toward zero.
- typeof
- Same as
typeof_, spelled with a raw identifier. - typeof_
- The storage class of a value as text (
TYPEOF), on SQLite. - unixepoch
- A time value as seconds since 1970-01-01 (
UNIXEPOCH), on SQLite 3.38+. - upper
- Converts text to upper case (
UPPER). - var_pop
- Population variance (
VAR_POP), on PostgreSQL and MySQL. - var_
samp - Sample variance (
VAR_SAMP), on PostgreSQL and MySQL. - variance
- Sample variance:
VARIANCEon PostgreSQL,VAR_SAMPon MySQL. - window
- Starts an empty window specification (
OVER ()).
Type Aliases§
- AggExpr
- A non-null, aggregate
SQLExpr. - Nullable
AggExpr - A nullable, aggregate
SQLExpr. - Nullable
Expr - A nullable, scalar
SQLExpr. - Scalar
Expr - A non-null, scalar
SQLExpr.