SQL composition¶
Dynamic SQL in Gres separates SQL structure from bound data. Ordinary strings are always bound as data, never interpolated into SQL; only Query, Identifier, and Literal contribute SQL structure.
import asyncio
from gres import Connection, Query, and_, insert, scalar
def search(city: str | None = None, active: bool | None = None) -> Query:
where = and_(
{'city': city} if city is not None else None,
{'active': active} if active is not None else None,
)
return Query(
'SELECT name FROM station WHERE $where ORDER BY id', {'where': where}
)
async def main() -> None:
async with Connection() as db:
await db.execute(
'CREATE TEMP TABLE station('
'id int PRIMARY KEY, name text, city text, active bool)'
)
await db.execute(
insert(
'station',
[
{'id': 1, 'name': 'Harbour', 'city': 'Oslo', 'active': True},
{'id': 2, 'name': 'Airport', 'city': 'Oslo', 'active': False},
{'id': 3, 'name': 'Central', 'city': 'Bergen', 'active': True},
],
)
)
print(await db.fetch_all(search(city='Oslo', active=True), row=scalar(str))) # ['Harbour']
print(await db.fetch_all(search(active=True), row=scalar(str))) # ['Harbour', 'Central']
asyncio.run(main())
Fragments and bindings¶
Query(sql, params) holds SQL with its own named ($name) or positional ($1) bindings, so composed fragments never collide on parameter names. query.bind(params) returns a new Query with overridden bindings. Every execution method accepts a Query anywhere it accepts SQL text.
raw_sql(text, params) wraps runtime SQL from trusted code (such as a migration file); it does not sanitize untrusted input.
Names¶
Use Identifier for dynamic table, column, schema, or type names. Each argument is one quoted component:
Identifier('app', 'notes')renders"app"."notes".Identifier('left.value')renders"left.value"(a single column whose name contains a dot).
Predicates and statements¶
| Helper | Builds |
|---|---|
and_(*parts), or_(*parts) |
A parenthesized conjunction or disjunction. |
join(items, sep) |
Items separated by trusted SQL, such as a projection of Identifier values. |
assignments(changes) |
A SET list from column names to bound values or fragments. |
insert(table, records, columns=) |
A multi-row INSERT from mappings. Without columns, every record must have the first record's keys. |
values(records, columns=, alias=) |
An aliased VALUES relation with explicit SQL types, for UPDATE ... FROM and joins. Empty input yields a typed relation with no rows. |
cast(value, type) |
CAST(value AS type) with a bound value; type can be an Identifier. |
and_() and or_() rules:
- A mapping compares each column to its bound value; a
Nonevalue becomesIS NULL. Noneoperands are omitted; emptyand_()isTRUEand emptyor_()isFALSE.- Plain strings raise
TypeError; wrap trusted SQL fragments inQuery.
Using assignments() and values() in updates:
# Partial: db is an open connection with the station table above.
from gres import Query, assignments, values
changes = assignments({'city': 'Trondheim', 'active': False})
await db.execute(
Query('UPDATE station SET $changes WHERE id = $id', {'changes': changes, 'id': 3})
)
renamed = values(
[(1, 'Harbour East'), (2, 'Airport Express')],
columns={'id': 'int', 'name': 'text'},
alias='renamed',
)
await db.execute(
Query(
'UPDATE station AS s SET name = renamed.name'
' FROM $renamed WHERE s.id = renamed.id',
{'renamed': renamed},
)
)
insert() and values() send all rows in one statement; for larger loads, use binary COPY.
Types and constants¶
Where SQL leaves a parameter's type ambiguous, cast it: $1::app.phase in SQL or cast(value, Identifier('app', 'phase')) in composed queries. Registering an adapter changes conversion for that SQL type, not which type PostgreSQL selects.
Use Literal(value) only where PostgreSQL requires an inline constant rather than a bound parameter (such as SET statement_timeout or WAIT FOR LSN). Because it becomes part of the SQL text, its value can appear in query logs.
- Without
type=,LiteralacceptsNone, booleans, integers, floats,Decimal, strings, byte buffers (bytea), anduuid.UUID. Literal(value, type=...)encodes the value for that SQL type (e.g.Literal({'enabled': True}, type='jsonb')); PostgreSQL resolves the type name and enforces domain constraints and type modifiers.- Statements whose literal types the database must resolve execute standalone rather than in a multi-statement script.
- A text
PgValueworks as a literal of its qualified type; bind a binaryPgValueas a parameter.
Template strings¶
On CPython 3.14+, template strings (t'...') compose queries directly from locals: values bind as parameters while Identifier, Query, and Literal insert SQL structure.
# Partial: CPython 3.14 or later; db is an open connection with the
# station table above.
from gres import Identifier, scalar
column, city = Identifier('name'), 'Oslo'
names = await db.fetch_all(
t'SELECT {column} FROM station WHERE city = {city}', row=scalar(str)
)