pg_sql (equery v0.22.0)

View Source

SQL expression builders.

Operators, scalar functions, aggregates, CASE, type casts. These produce qast:ast_node() values that go inside q:where/q:select/etc. closures.

Inside DSL closures, native Erlang operators (=:=, >, andalso, +, …) are rewritten by equery_pt to corresponding pg_sql: functions, so you rarely call these directly for primitive operations.

Use the explicit pg_sql: form for:

JSON/JSONB live in qjson.

Summary

Aggregates

array_agg(A) — collect values into an array. NULLs are included.

array_agg(A ORDER BY ...) — collect into array with explicit ordering.

avg(A) — arithmetic mean. Returns numeric or double precision.

bool_and(A) — true iff every non-NULL input is true.

bool_or(A) — true iff any non-NULL input is true.

count(A) — non-NULL row count. Returns bigint.

DISTINCT A qualifier — typically used inside another aggregate, e.g. count(distinct(x)).

every(A) — SQL standard alias for bool_and/1.

Wrap any aggregate with FILTER (WHERE Cond) — limits which rows the aggregate sees, without affecting the rest of the query. Essential for dashboard-style queries with multiple conditional metrics.

json_agg(A) — aggregate into a JSON array. See JSON Functions.

json_agg(A ORDER BY ...).

json_object_agg(K, V) — aggregate into a JSON object.

jsonb_agg(A) — aggregate into a JSONB array.

jsonb_agg(A ORDER BY ...).

jsonb_object_agg(K, V) — aggregate into a JSONB object.

max(A) — aggregate maximum.

min(A) — aggregate minimum.

mode() WITHIN GROUP (ORDER BY x) — most frequent value (statistical mode).

percentile_cont(Frac) WITHIN GROUP (ORDER BY x) — interpolated continuous percentile. Frac ∈ [0, 1].

percentile_disc(Frac) WITHIN GROUP (ORDER BY x) — discrete percentile (picks one of the input values).

string_agg(expr, sep) — concatenate string values with a separator. NULL inputs are ignored.

string_agg(expr, sep ORDER BY ...) — concatenate with explicit ordering.

Arithmetic

A * B.

A - B.

A / B — division. For integers, truncates toward zero.

abs(A) — absolute value. See Math Functions.

div(A, B) — integer quotient, truncated toward zero.

Alias for mod/2. Erlang's rem operator inside DSL closures rewrites to this.

Arrays

A && B — arrays overlap (have any common element).

A <@ B — is contained by.

A @> B — contains. See Array Functions and Operators.

ARRAY[v1, v2, ...] constructor. Element type is inferred from the first element's opts.

array_append(arr, elem) — append element.

array_cat(a, b) — concatenate two arrays. Equivalent to a || b.

array_length(arr, 1) — length of the first dimension.

array_length(arr, dim) — length of dimension dim.

array_position(arr, elem) — 1-based index of elem in arr, or NULL.

array_prepend(elem, arr) — prepend element.

array_remove(arr, elem) — remove all occurrences of elem.

array_replace(arr, from, to) — replace all from elements with to.

unnest(arr) — set-returning function that produces one row per array element.

Comparison

A < B.

A <= B.

A >= B.

A IS B. Low-level building block for IS NULL, IS TRUE, etc. See Comparison Predicates.

A IS DISTINCT FROM B — NULL-safe inequality (treats NULL = NULL as equal). See Comparison Predicates.

A IS NOT DISTINCT FROM B — NULL-safe equality.

A IS NOT NULL.

Conditional

Searched CASE WHEN cond THEN val ... END without ELSENULL if no branch matches.

CASE WHEN cond THEN val ... ELSE default END.

COALESCE(a, b, c, ...) — returns the first non-NULL argument.

GREATEST(A, B, C, ...) — N-ary form. Returns max of all non-NULL inputs.

LEAST(A, B, C, ...) — N-ary form. Returns min of all non-NULL inputs.

GREATEST(A, B) — maximum of two values, ignoring NULLs.

LEAST(A, B) — minimum of two values, ignoring NULLs. See Conditional Expressions.

Date/time

age(t) — interval since current_date to t (or vice-versa).

age(t1, t2) — symbolic interval t1 - t2.

current_date — current date (date only).

current_time — current time of day with timezone.

current_timestamp — start-of-transaction timestamp with timezone. Standard SQL.

date_part('field', source) — same as extract, returns double precision.

date_trunc('field', source) — truncate a timestamp to the specified precision. Field is a closed enum (validated at build time).

EXTRACT(field FROM source) — get a sub-field as numeric.

now() — current transaction timestamp (with timezone). PostgreSQL extension; equivalent to current_timestamp/0.

to_char(val, fmt) — format a date/timestamp/number as text. See Data Type Formatting Functions.

to_date(text, fmt) — parse a string into date.

to_timestamp(epoch) — Unix-epoch seconds to timestamptz.

to_timestamp(text, fmt) — parse a formatted string into timestamptz.

Logical

Logical AND. Short-circuits on boolean literals. See Logical Operators.

Logical NOT. See Logical Operators.

Logical OR. Short-circuits on boolean literals. See Logical Operators.

Misc

Build a function call AST: FunName(Args...).

EXISTS (subquery). See EXISTS.

A IN (...) — membership test.

ROW(...) constructor with anonymous record type. See Row Constructors.

ROW(...) constructor tagged with a model module (for type inference in row-typed projections).

Numeric

ceil(A) — ceiling (smallest integer not less than A).

exp(A) — exponential (e^A).

floor(A) — floor (largest integer not greater than A).

ln(A) — natural logarithm.

log(A) — base-10 logarithm.

log(B, A) — logarithm of A to base B.

mod(A, B) — remainder of A / B. See Math Functions.

power(A, B)A raised to the power of B.

random() — pseudo-random double precision in [0.0, 1.0).

round(A) — round to nearest integer (banker's rounding for numeric).

round(A, N) — round to N decimal places.

sign(A)-1, 0, or 1 according to sign.

sqrt(A) — square root.

trunc(V, N) — truncate to N decimal places.

Pattern matching

A ILIKE B — case-insensitive LIKE (PostgreSQL extension).

A LIKE B. See LIKE.

POSIX regex match (case-insensitive) A ~* B.

POSIX regex match A ~ B. See POSIX Regular Expressions.

Strings

char_length(s) — SQL-standard alias for length.

concat(a, b, c, ...) — concatenate. NULLs are skipped (unlike ||). See String Functions.

concat(a, b) — 2-arg form for convenience.

length(s) — string length in characters.

lower(s) — lowercase.

ltrim(s) — strip whitespace from the left.

ltrim(s, chars) — strip listed characters from the left.

regexp_match(s, pat) — returns a text[] of capture groups, or NULL if no match.

regexp_match(s, pat, flags) — with regex flags.

regexp_replace(s, pat, repl) — replace first match. See POSIX Regex Match.

regexp_replace(s, pat, repl, flags)'g' for global replace, 'i' case-insensitive, etc.

replace(s, from, to) — replace all occurrences of from with to.

rtrim(s) — strip whitespace from the right.

rtrim(s, chars) — strip listed characters from the right.

split_part(s, sep, n)n-th field after splitting s by sep (1-indexed).

starts_with(s, prefix) — boolean prefix test. Faster than LIKE 'prefix%' for indexed lookup.

strpos(haystack, needle) — 1-based position of needle in haystack, or 0.

substring(s, from) — from the given 1-based start position to end.

substring(s, from, len)len characters starting at from.

trim(s) — strip whitespace from both ends.

trim(s, chars) — strip any character listed in chars from both ends.

upper(s) — uppercase.

A || B — concatenation operator.

Type casts

(Ast)::Type — SQL type cast.

Annotate an AST node with a type, without emitting an SQL cast.

Types

agg_order_spec()

-type agg_order_spec() :: expr() | {expr(), asc | desc} | {expr(), asc | desc, nulls_first | nulls_last}.

agg_order_specs()

-type agg_order_specs() :: [agg_order_spec(), ...].

datetime_field()

-type datetime_field() ::
          century | day | decade | dow | doy | epoch | hour | isodow | isoyear | julian | microseconds |
          millennium | milliseconds | minute | month | quarter | second | timezone | timezone_hour |
          timezone_minute | week | year.

expr()

-type expr() :: qast:ast_node() | term().

Aggregates

array_agg(Ast)

-spec array_agg(expr()) -> qast:ast_node().

array_agg(A) — collect values into an array. NULLs are included.

array_agg(Ast, OrderSpecs)

-spec array_agg(expr(), agg_order_specs()) -> qast:ast_node().

array_agg(A ORDER BY ...) — collect into array with explicit ordering.

avg(A)

-spec avg(expr()) -> qast:ast_node().

avg(A) — arithmetic mean. Returns numeric or double precision.

bool_and(A)

-spec bool_and(expr()) -> qast:ast_node().

bool_and(A) — true iff every non-NULL input is true.

bool_or(A)

-spec bool_or(expr()) -> qast:ast_node().

bool_or(A) — true iff any non-NULL input is true.

count(Ast)

-spec count(qast:ast_node()) -> qast:ast_node().

count(A) — non-NULL row count. Returns bigint.

distinct(Ast)

-spec distinct(expr()) -> qast:ast_node().

DISTINCT A qualifier — typically used inside another aggregate, e.g. count(distinct(x)).

every(A)

-spec every(expr()) -> qast:ast_node().

every(A) — SQL standard alias for bool_and/1.

filter(AggAst, Cond)

-spec filter(qast:ast_node(), expr()) -> qast:ast_node().

Wrap any aggregate with FILTER (WHERE Cond) — limits which rows the aggregate sees, without affecting the rest of the query. Essential for dashboard-style queries with multiple conditional metrics.

#{
    total => pg_sql:count(Id),
    paid  => pg_sql:filter(pg_sql:count(Id), Status =:= <<"paid">>)
}.

See Aggregate Expressions.

json_agg(A)

-spec json_agg(expr()) -> qast:ast_node().

json_agg(A) — aggregate into a JSON array. See JSON Functions.

json_agg(A, OrderSpecs)

-spec json_agg(expr(), agg_order_specs()) -> qast:ast_node().

json_agg(A ORDER BY ...).

json_object_agg(K, V)

-spec json_object_agg(expr(), expr()) -> qast:ast_node().

json_object_agg(K, V) — aggregate into a JSON object.

jsonb_agg(A)

-spec jsonb_agg(expr()) -> qast:ast_node().

jsonb_agg(A) — aggregate into a JSONB array.

jsonb_agg(A, OrderSpecs)

-spec jsonb_agg(expr(), agg_order_specs()) -> qast:ast_node().

jsonb_agg(A ORDER BY ...).

jsonb_object_agg(K, V)

-spec jsonb_object_agg(expr(), expr()) -> qast:ast_node().

jsonb_object_agg(K, V) — aggregate into a JSONB object.

max(Ast)

-spec max(expr()) -> qast:ast_node().

max(A) — aggregate maximum.

min(Ast)

-spec min(expr()) -> qast:ast_node().

min(A) — aggregate minimum.

mode(OrderExpr)

-spec mode(expr()) -> qast:ast_node().

mode() WITHIN GROUP (ORDER BY x) — most frequent value (statistical mode).

percentile_cont(Frac, OrderExpr)

-spec percentile_cont(expr(), expr()) -> qast:ast_node().

percentile_cont(Frac) WITHIN GROUP (ORDER BY x) — interpolated continuous percentile. Frac ∈ [0, 1].

See Ordered-Set Aggregate Functions.

percentile_disc(Frac, OrderExpr)

-spec percentile_disc(expr(), expr()) -> qast:ast_node().

percentile_disc(Frac) WITHIN GROUP (ORDER BY x) — discrete percentile (picks one of the input values).

string_agg(Expr, Sep)

-spec string_agg(expr(), expr()) -> qast:ast_node().

string_agg(expr, sep) — concatenate string values with a separator. NULL inputs are ignored.

string_agg(Expr, Sep, OrderSpecs)

-spec string_agg(expr(), expr(), agg_order_specs()) -> qast:ast_node().

string_agg(expr, sep ORDER BY ...) — concatenate with explicit ordering.

Without ORDER BY, string_agg is non-deterministic. Use the 3-arg form when result order matters.

sum(Ast)

-spec sum(qast:ast_node()) -> qast:ast_node().

sum(A). See Aggregate Functions.

Arithmetic

'*'(A, B)

-spec '*'(expr(), expr()) -> qast:ast_node().

A * B.

'+'(A, B)

-spec '+'(expr(), expr()) -> qast:ast_node().

A + B. See Mathematical Operators.

'-'(A, B)

-spec '-'(expr(), expr()) -> qast:ast_node().

A - B.

'/'(A, B)

-spec '/'(expr(), expr()) -> qast:ast_node().

A / B — division. For integers, truncates toward zero.

abs(A)

-spec abs(expr()) -> qast:ast_node().

abs(A) — absolute value. See Math Functions.

'div'(A, B)

-spec 'div'(expr(), expr()) -> qast:ast_node().

div(A, B) — integer quotient, truncated toward zero.

'rem'(A, B)

-spec 'rem'(expr(), expr()) -> qast:ast_node().

Alias for mod/2. Erlang's rem operator inside DSL closures rewrites to this.

Arrays

'&&'(A, B)

-spec '&&'(expr(), expr()) -> qast:ast_node().

A && B — arrays overlap (have any common element).

'<@'(A, B)

-spec '<@'(expr(), expr()) -> qast:ast_node().

A <@ B — is contained by.

'@>'(A, B)

A @> B — contains. See Array Functions and Operators.

array(Items)

-spec array([expr()]) -> qast:ast_node().

ARRAY[v1, v2, ...] constructor. Element type is inferred from the first element's opts.

Empty array (ARRAY[]) needs an explicit cast in PG; use as/2: pg_sql:as(pg_sql:array([]), {array, int}).

array_append(Arr, Elem)

-spec array_append(expr(), expr()) -> qast:ast_node().

array_append(arr, elem) — append element.

array_cat(A, B)

-spec array_cat(expr(), expr()) -> qast:ast_node().

array_cat(a, b) — concatenate two arrays. Equivalent to a || b.

array_length(Arr)

-spec array_length(expr()) -> qast:ast_node().

array_length(arr, 1) — length of the first dimension.

array_length(Arr, Dim)

-spec array_length(expr(), expr()) -> qast:ast_node().

array_length(arr, dim) — length of dimension dim.

array_position(Arr, Elem)

-spec array_position(expr(), expr()) -> qast:ast_node().

array_position(arr, elem) — 1-based index of elem in arr, or NULL.

array_prepend(Elem, Arr)

-spec array_prepend(expr(), expr()) -> qast:ast_node().

array_prepend(elem, arr) — prepend element.

array_remove(Arr, Elem)

-spec array_remove(expr(), expr()) -> qast:ast_node().

array_remove(arr, elem) — remove all occurrences of elem.

array_replace(Arr, From, To)

-spec array_replace(expr(), expr(), expr()) -> qast:ast_node().

array_replace(arr, from, to) — replace all from elements with to.

unnest(Arr)

-spec unnest(expr()) -> qast:ast_node().

unnest(arr) — set-returning function that produces one row per array element.

Integrates with q:from/1 and q:lateral_join/2,3,4: the resulting table has a single column named unnest (PostgreSQL default).

q:pipe(q:from(?USER), [
    q:lateral_join(inner, fun([#{tags := T}]) ->
        q:from(pg_sql:unnest(T))
    end),
    q:select(fun([#{name := N}, #{unnest := Tag}]) ->
        #{name => N, tag => Tag}
    end)
]).

Comparison

'<'(A, B)

-spec '<'(expr(), expr()) -> qast:ast_node().

A < B.

'=/='(A, B)

-spec '=/='(expr(), expr()) -> qast:ast_node().

A <> B. See Comparison Operators.

'=:='(A, B)

-spec '=:='(expr(), expr()) -> qast:ast_node().

A = B. See Comparison Operators.

'=<'(A, B)

-spec '=<'(expr(), expr()) -> qast:ast_node().

A <= B.

'>'(A, B)

-spec '>'(expr(), expr()) -> qast:ast_node().

A > B. See Comparison Operators.

'>='(A, B)

-spec '>='(expr(), expr()) -> qast:ast_node().

A >= B.

is(A, B)

-spec is(expr(), expr()) -> qast:ast_node().

A IS B. Low-level building block for IS NULL, IS TRUE, etc. See Comparison Predicates.

is_distinct_from(A, B)

-spec is_distinct_from(expr(), expr()) -> qast:ast_node().

A IS DISTINCT FROM B — NULL-safe inequality (treats NULL = NULL as equal). See Comparison Predicates.

is_not_distinct_from(A, B)

-spec is_not_distinct_from(expr(), expr()) -> qast:ast_node().

A IS NOT DISTINCT FROM B — NULL-safe equality.

is_not_null(A)

-spec is_not_null(expr()) -> qast:ast_node().

A IS NOT NULL.

is_null(A)

-spec is_null(expr()) -> qast:ast_node().

A IS NULL. See Comparison Predicates.

Conditional

case_when(Whens)

-spec case_when([{expr(), expr()}, ...]) -> qast:ast_node().

Searched CASE WHEN cond THEN val ... END without ELSENULL if no branch matches.

case_when/2

-spec case_when([{expr(), expr()}, ...], expr() | undefined) -> qast:ast_node().

CASE WHEN cond THEN val ... ELSE default END.

pg_sql:case_when([
    {Id > 100, <<"big">>},
    {Id > 10,  <<"medium">>}
], <<"small">>).

See Conditional Expressions.

coalesce/1

COALESCE(a, b, c, ...) — returns the first non-NULL argument.

See Conditional Expressions.

greatest/1

-spec greatest([expr(), ...]) -> qast:ast_node().

GREATEST(A, B, C, ...) — N-ary form. Returns max of all non-NULL inputs.

least/1

-spec least([expr(), ...]) -> qast:ast_node().

LEAST(A, B, C, ...) — N-ary form. Returns min of all non-NULL inputs.

max(A, B)

-spec max(expr(), expr()) -> qast:ast_node().

GREATEST(A, B) — maximum of two values, ignoring NULLs.

min(A, B)

-spec min(expr(), expr()) -> qast:ast_node().

LEAST(A, B) — minimum of two values, ignoring NULLs. See Conditional Expressions.

Date/time

age(A)

-spec age(expr()) -> qast:ast_node().

age(t) — interval since current_date to t (or vice-versa).

age(A, B)

-spec age(expr(), expr()) -> qast:ast_node().

age(t1, t2) — symbolic interval t1 - t2.

current_date()

-spec current_date() -> qast:ast_node().

current_date — current date (date only).

current_time()

-spec current_time() -> qast:ast_node().

current_time — current time of day with timezone.

current_timestamp()

-spec current_timestamp() -> qast:ast_node().

current_timestamp — start-of-transaction timestamp with timezone. Standard SQL.

date_part(Field, Source)

-spec date_part(datetime_field(), expr()) -> qast:ast_node().

date_part('field', source) — same as extract, returns double precision.

date_trunc(Field, Source)

-spec date_trunc(datetime_field(), expr()) -> qast:ast_node().

date_trunc('field', source) — truncate a timestamp to the specified precision. Field is a closed enum (validated at build time).

See Date/Time Functions.

extract(Field, Source)

-spec extract(datetime_field(), expr()) -> qast:ast_node().

EXTRACT(field FROM source) — get a sub-field as numeric.

See EXTRACT.

now()

-spec now() -> qast:ast_node().

now() — current transaction timestamp (with timezone). PostgreSQL extension; equivalent to current_timestamp/0.

to_char(A, Fmt)

-spec to_char(expr(), expr()) -> qast:ast_node().

to_char(val, fmt) — format a date/timestamp/number as text. See Data Type Formatting Functions.

to_date(A, Fmt)

-spec to_date(expr(), expr()) -> qast:ast_node().

to_date(text, fmt) — parse a string into date.

to_timestamp(A)

-spec to_timestamp(expr()) -> qast:ast_node().

to_timestamp(epoch) — Unix-epoch seconds to timestamptz.

to_timestamp(A, Fmt)

-spec to_timestamp(expr(), expr()) -> qast:ast_node().

to_timestamp(text, fmt) — parse a formatted string into timestamptz.

Logical

'andalso'(V, V)

-spec 'andalso'(V, V) -> V when V :: boolean() | qast:ast_node().

Logical AND. Short-circuits on boolean literals. See Logical Operators.

'not'(V)

-spec 'not'(V) -> V when V :: boolean() | qast:ast_node().

Logical NOT. See Logical Operators.

'orelse'(V, V)

-spec 'orelse'(V, V) -> V when V :: boolean() | qast:ast_node().

Logical OR. Short-circuits on boolean literals. See Logical Operators.

Misc

call(FunName, Args, Opts)

-spec call(iodata(), [expr()], qast:opts()) -> qast:ast_node().

Build a function call AST: FunName(Args...).

Used internally by all pg_sql: function builders. Public for custom PG functions not yet wrapped by the library:

pg_sql:call("my_extension_fn", [Arg1, Arg2], #{type => text}).

Warning

FunName is inlined raw. Never pass user-controlled input here; use a literal string.

exists/1

EXISTS (subquery). See EXISTS.

in/2

A IN (...) — membership test.

  • With a query() argument, emits A IN (subquery). See Subquery Expressions.
  • With a list, emits A = ANY($1) (parameterized).
  • With a single-element list, optimized to A = item.

row(Fields)

-spec row(#{atom() => qast:ast_node()}) -> qast:ast_node().

ROW(...) constructor with anonymous record type. See Row Constructors.

row(Model, Fields)

-spec row(Model :: module(), #{atom() => qast:ast_node()}) -> qast:ast_node().

ROW(...) constructor tagged with a model module (for type inference in row-typed projections).

Numeric

ceil(A)

-spec ceil(expr()) -> qast:ast_node().

ceil(A) — ceiling (smallest integer not less than A).

exp(A)

-spec exp(expr()) -> qast:ast_node().

exp(A) — exponential (e^A).

floor(A)

-spec floor(expr()) -> qast:ast_node().

floor(A) — floor (largest integer not greater than A).

ln(A)

-spec ln(expr()) -> qast:ast_node().

ln(A) — natural logarithm.

log(A)

-spec log(expr()) -> qast:ast_node().

log(A) — base-10 logarithm.

log(B, A)

-spec log(expr(), expr()) -> qast:ast_node().

log(B, A) — logarithm of A to base B.

mod(A, B)

-spec mod(expr(), expr()) -> qast:ast_node().

mod(A, B) — remainder of A / B. See Math Functions.

power(A, B)

-spec power(expr(), expr()) -> qast:ast_node().

power(A, B)A raised to the power of B.

random()

-spec random() -> qast:ast_node().

random() — pseudo-random double precision in [0.0, 1.0).

round(A)

-spec round(expr()) -> qast:ast_node().

round(A) — round to nearest integer (banker's rounding for numeric).

round(A, N)

-spec round(expr(), expr()) -> qast:ast_node().

round(A, N) — round to N decimal places.

sign(A)

-spec sign(expr()) -> qast:ast_node().

sign(A)-1, 0, or 1 according to sign.

sqrt(A)

-spec sqrt(expr()) -> qast:ast_node().

sqrt(A) — square root.

trunc(V, N)

-spec trunc(expr(), qast:ast_node() | non_neg_integer()) -> qast:ast_node().

trunc(V, N) — truncate to N decimal places.

Pattern matching

ilike(A, B)

A ILIKE B — case-insensitive LIKE (PostgreSQL extension).

like(A, B)

A LIKE B. See LIKE.

'~*'(A, B)

-spec '~*'(expr(), expr()) -> qast:ast_node().

POSIX regex match (case-insensitive) A ~* B.

'~'(A, B)

-spec '~'(expr(), expr()) -> qast:ast_node().

POSIX regex match A ~ B. See POSIX Regular Expressions.

Strings

char_length(A)

-spec char_length(expr()) -> qast:ast_node().

char_length(s) — SQL-standard alias for length.

concat(List)

-spec concat([expr(), ...]) -> qast:ast_node().

concat(a, b, c, ...) — concatenate. NULLs are skipped (unlike ||). See String Functions.

concat(A, B)

-spec concat(expr(), expr()) -> qast:ast_node().

concat(a, b) — 2-arg form for convenience.

length(A)

-spec length(expr()) -> qast:ast_node().

length(s) — string length in characters.

lower(A)

-spec lower(expr()) -> qast:ast_node().

lower(s) — lowercase.

ltrim(A)

-spec ltrim(expr()) -> qast:ast_node().

ltrim(s) — strip whitespace from the left.

ltrim(A, Chars)

-spec ltrim(expr(), expr()) -> qast:ast_node().

ltrim(s, chars) — strip listed characters from the left.

regexp_match(A, Pattern)

-spec regexp_match(expr(), expr()) -> qast:ast_node().

regexp_match(s, pat) — returns a text[] of capture groups, or NULL if no match.

regexp_match(A, Pattern, Flags)

-spec regexp_match(expr(), expr(), expr()) -> qast:ast_node().

regexp_match(s, pat, flags) — with regex flags.

regexp_replace(A, Pattern, Repl)

-spec regexp_replace(expr(), expr(), expr()) -> qast:ast_node().

regexp_replace(s, pat, repl) — replace first match. See POSIX Regex Match.

regexp_replace(A, Pattern, Repl, Flags)

-spec regexp_replace(expr(), expr(), expr(), expr()) -> qast:ast_node().

regexp_replace(s, pat, repl, flags)'g' for global replace, 'i' case-insensitive, etc.

replace(A, From, To)

-spec replace(expr(), expr(), expr()) -> qast:ast_node().

replace(s, from, to) — replace all occurrences of from with to.

rtrim(A)

-spec rtrim(expr()) -> qast:ast_node().

rtrim(s) — strip whitespace from the right.

rtrim(A, Chars)

-spec rtrim(expr(), expr()) -> qast:ast_node().

rtrim(s, chars) — strip listed characters from the right.

split_part(A, Delim, N)

-spec split_part(expr(), expr(), expr()) -> qast:ast_node().

split_part(s, sep, n)n-th field after splitting s by sep (1-indexed).

starts_with(A, Prefix)

-spec starts_with(expr(), expr()) -> qast:ast_node().

starts_with(s, prefix) — boolean prefix test. Faster than LIKE 'prefix%' for indexed lookup.

strpos(Haystack, Needle)

-spec strpos(expr(), expr()) -> qast:ast_node().

strpos(haystack, needle) — 1-based position of needle in haystack, or 0.

substring(A, From)

-spec substring(expr(), expr()) -> qast:ast_node().

substring(s, from) — from the given 1-based start position to end.

substring(A, From, Len)

-spec substring(expr(), expr(), expr()) -> qast:ast_node().

substring(s, from, len)len characters starting at from.

trim(A)

-spec trim(expr()) -> qast:ast_node().

trim(s) — strip whitespace from both ends.

trim(A, Chars)

-spec trim(expr(), expr()) -> qast:ast_node().

trim(s, chars) — strip any character listed in chars from both ends.

upper(A)

-spec upper(expr()) -> qast:ast_node().

upper(s) — uppercase.

'||'(A, B)

-spec '||'(expr(), expr()) -> qast:ast_node().

A || B — concatenation operator.

NULL-propagating: 'foo' || NULLNULL. For NULL-skipping behavior use concat/2. Same operator works for arrays.

See String Functions.

Type casts

as(Ast, Type)

(Ast)::Type — SQL type cast.

pg_sql:as(Id, text)              %% (id)::text
pg_sql:as(V, {varchar, 60})      %% (v)::varchar(60)
pg_sql:as(V, {array, integer})   %% (v)::integer[]

See Type Casts.

Warning

Type is rendered raw. Use only with literal atoms / tuples; never with user-controlled values.

set_type(Ast, Type)

Annotate an AST node with a type, without emitting an SQL cast.

Useful when you know the inferred type is wrong (e.g. when wrapping a call/3 to a function whose return type isn't auto-inferred) and want correct downstream type propagation without paying for a runtime cast.