Skip to content

templates

Statement templates: a statement built once per cache key and reused with new values on every later call.

Most of the cost of a simple read is building the statement: ormar walks the filters, joins, selected fields and ordering, and SQLAlchemy assembles the expression tree. Two calls that differ only in their values build the same tree, so QuerySet builds it once with named bind parameters ("slots") in place of the values and keeps it in a cache of the model::

Text Only
1
2
3
4
5
6
await Author.objects.filter(name="a").limit(5).all()
# built and cached: SELECT ... WHERE authors.name = :ormar_p0 LIMIT :ormar_limit
# bound this call:  {"ormar_p0": "a", "ormar_limit": 5}

await Author.objects.filter(name="b").limit(10).all()
# same cache key, statement reused: {"ormar_p0": "b", "ormar_limit": 10}

The cache key (see QuerySet.select_cache_key) holds everything that changes the SQL text and none of the bound values: filtered columns, operators, and/or/not nesting, select_related, selected fields, ordering and whether a limit or offset is present. Values SQLAlchemy writes into the SQL text instead of binding (None as IS NULL, booleans, isnull) are part of the key as well.

Writes are cached the same way. Model.save(), update(), delete(), load() and upsert() run one statement per model and set of written columns, binding the values as ormar_v{i} (in sorted column order) and the primary key as ormar_pk::

Text Only
1
2
3
await Author(name="a", score=1).save()
# INSERT INTO authors (name, score) VALUES (:ormar_v0, :ormar_v1)
# {"ormar_v0": "a", "ormar_v1": 1}

QuerySet.update() and delete() bind both filter and value slots, and bulk_create and bulk_update reuse one statement per set of columns for all their rows.

Running the same statement object every time also lets the native compiler reuse its plan for it instead of compiling the statement again.

The package is split by role:

  • cache - the per-model template cache
  • cache_keys - what makes two querysets share a statement
  • slots - named bind parameters and the values collected per call
  • reads - statements wrapped around a select, clean-up of templates
  • writes - insert and upsert templates (updates, deletes and selects by primary key: ormar.queryset.write_statements)

SlotBinder

Turns per-call values of a read statement into named bind parameters while the statement is built. A filter action's value is named ormar_p{n} after its position among the canonical actions, limit and offset get fixed names::

Text Only
1
2
3
binder = SlotBinder(actions=[name_action, score_action])
binder.bind(action=score_action, value=5)  # -> :ormar_p1
binder.limit(value=10)  # -> :ormar_limit

Slots are looked up by action object, not by order of use, because one action can be emitted twice: with select_related and a limit, the filters go into the pagination subquery and the outer query, and both copies bind the same ormar_p{n}, so one value fills both.

Passed down through Query, FilterQuery, LimitQuery and OffsetQuery; without a binder they bind the plain values as before.

Source code in ormar/queryset/templates/slots.py
Python
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
class SlotBinder:
    """
    Turns per-call values of a read statement into named bind parameters while
    the statement is built. A filter action's value is named ``ormar_p{n}``
    after its position among the canonical actions, limit and offset get fixed
    names::

        binder = SlotBinder(actions=[name_action, score_action])
        binder.bind(action=score_action, value=5)  # -> :ormar_p1
        binder.limit(value=10)  # -> :ormar_limit

    Slots are looked up by action object, not by order of use, because one
    action can be emitted twice: with ``select_related`` and a limit, the
    filters go into the pagination subquery and the outer query, and both
    copies bind the same ``ormar_p{n}``, so one value fills both.

    Passed down through ``Query``, ``FilterQuery``, ``LimitQuery`` and
    ``OffsetQuery``; without a binder they bind the plain values as before.
    """

    def __init__(self, actions: List["FilterAction"]) -> None:
        """
        :param actions: filter actions of the queryset in canonical order
        :type actions: List[FilterAction]
        """
        self.slots = {
            id(action): f"ormar_p{index}" for index, action in enumerate(actions)
        }

    def bind(self, action: "FilterAction", value: Any) -> BindParameter:
        """
        Return the named bind parameter for a filter action's value.

        The parameter is built the way SQLAlchemy builds the bind of
        ``column <op> value``: it is compared to the column's type, so the value
        gets the column's bind processing (dates, JSON, enums and so on), and
        an ``in`` filter is expanding, so it renders one placeholder per item of
        the list it is given on each call.

        :param action: filter action the value belongs to
        :type action: FilterAction
        :param value: value to bind
        :type value: Any
        :return: named bind parameter
        :rtype: BindParameter
        """
        operator = COMPARISON_OPERATORS[FILTER_OPERATORS[action.operator]]
        return BindParameter(
            key=self.slots[id(action)],
            value=value,
            expanding=action.operator == "in",
            _compared_to_operator=operator,
            _compared_to_type=action.column.type,
        )

    def bind_key_in(
        self, action: "FilterAction", value: Any, column_types: List[Any]
    ) -> BindParameter:
        """
        Return the expanding bind parameter of a row-value ``IN`` over several
        key columns, typed as a tuple of the column types so each part gets its
        column's bind processing::

            (orders.tenant_id, orders.number) IN (:ormar_p0)
            # rendered per call as IN ((?, ?), (?, ?))

        :param action: the key ``IN`` filter action
        :type action: FilterAction
        :param value: key values, one tuple of parts per key
        :type value: Any
        :param column_types: types of the key columns, in key order
        :type column_types: List[Any]
        :return: named expanding bind parameter
        :rtype: BindParameter
        """
        return BindParameter(
            key=self.slots[id(action)],
            value=value,
            expanding=True,
            type_=TupleType(*column_types),
        )

    def limit(self, value: int) -> BindParameter:
        """
        Return the named bind parameter for a limit, typed as an integer like
        the one SQLAlchemy creates for ``select.limit(10)``.

        :param value: limit value
        :type value: int
        :return: named bind parameter
        :rtype: BindParameter
        """
        return sqlalchemy.bindparam(
            key=LIMIT_SLOT, value=value, type_=sqlalchemy.Integer()
        )

    def offset(self, value: int) -> BindParameter:
        """
        Return the named bind parameter for an offset, typed as an integer like
        the one SQLAlchemy creates for ``select.offset(10)``.

        :param value: offset value
        :type value: int
        :return: named bind parameter
        :rtype: BindParameter
        """
        return sqlalchemy.bindparam(
            key=OFFSET_SLOT, value=value, type_=sqlalchemy.Integer()
        )

__init__(actions)

Parameters:

Name Type Description Default
actions List[FilterAction]

filter actions of the queryset in canonical order

required
Source code in ormar/queryset/templates/slots.py
Python
182
183
184
185
186
187
188
189
def __init__(self, actions: List["FilterAction"]) -> None:
    """
    :param actions: filter actions of the queryset in canonical order
    :type actions: List[FilterAction]
    """
    self.slots = {
        id(action): f"ormar_p{index}" for index, action in enumerate(actions)
    }

bind(action, value)

Return the named bind parameter for a filter action's value.

The parameter is built the way SQLAlchemy builds the bind of column <op> value: it is compared to the column's type, so the value gets the column's bind processing (dates, JSON, enums and so on), and an in filter is expanding, so it renders one placeholder per item of the list it is given on each call.

Parameters:

Name Type Description Default
action FilterAction

filter action the value belongs to

required
value Any

value to bind

required

Returns:

Type Description
BindParameter

named bind parameter

Source code in ormar/queryset/templates/slots.py
Python
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def bind(self, action: "FilterAction", value: Any) -> BindParameter:
    """
    Return the named bind parameter for a filter action's value.

    The parameter is built the way SQLAlchemy builds the bind of
    ``column <op> value``: it is compared to the column's type, so the value
    gets the column's bind processing (dates, JSON, enums and so on), and
    an ``in`` filter is expanding, so it renders one placeholder per item of
    the list it is given on each call.

    :param action: filter action the value belongs to
    :type action: FilterAction
    :param value: value to bind
    :type value: Any
    :return: named bind parameter
    :rtype: BindParameter
    """
    operator = COMPARISON_OPERATORS[FILTER_OPERATORS[action.operator]]
    return BindParameter(
        key=self.slots[id(action)],
        value=value,
        expanding=action.operator == "in",
        _compared_to_operator=operator,
        _compared_to_type=action.column.type,
    )

bind_key_in(action, value, column_types)

Return the expanding bind parameter of a row-value IN over several key columns, typed as a tuple of the column types so each part gets its column's bind processing::

Text Only
1
2
(orders.tenant_id, orders.number) IN (:ormar_p0)
# rendered per call as IN ((?, ?), (?, ?))

Parameters:

Name Type Description Default
action FilterAction

the key IN filter action

required
value Any

key values, one tuple of parts per key

required
column_types List[Any]

types of the key columns, in key order

required

Returns:

Type Description
BindParameter

named expanding bind parameter

Source code in ormar/queryset/templates/slots.py
Python
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def bind_key_in(
    self, action: "FilterAction", value: Any, column_types: List[Any]
) -> BindParameter:
    """
    Return the expanding bind parameter of a row-value ``IN`` over several
    key columns, typed as a tuple of the column types so each part gets its
    column's bind processing::

        (orders.tenant_id, orders.number) IN (:ormar_p0)
        # rendered per call as IN ((?, ?), (?, ?))

    :param action: the key ``IN`` filter action
    :type action: FilterAction
    :param value: key values, one tuple of parts per key
    :type value: Any
    :param column_types: types of the key columns, in key order
    :type column_types: List[Any]
    :return: named expanding bind parameter
    :rtype: BindParameter
    """
    return BindParameter(
        key=self.slots[id(action)],
        value=value,
        expanding=True,
        type_=TupleType(*column_types),
    )

limit(value)

Return the named bind parameter for a limit, typed as an integer like the one SQLAlchemy creates for select.limit(10).

Parameters:

Name Type Description Default
value int

limit value

required

Returns:

Type Description
BindParameter

named bind parameter

Source code in ormar/queryset/templates/slots.py
Python
244
245
246
247
248
249
250
251
252
253
254
255
256
def limit(self, value: int) -> BindParameter:
    """
    Return the named bind parameter for a limit, typed as an integer like
    the one SQLAlchemy creates for ``select.limit(10)``.

    :param value: limit value
    :type value: int
    :return: named bind parameter
    :rtype: BindParameter
    """
    return sqlalchemy.bindparam(
        key=LIMIT_SLOT, value=value, type_=sqlalchemy.Integer()
    )

offset(value)

Return the named bind parameter for an offset, typed as an integer like the one SQLAlchemy creates for select.offset(10).

Parameters:

Name Type Description Default
value int

offset value

required

Returns:

Type Description
BindParameter

named bind parameter

Source code in ormar/queryset/templates/slots.py
Python
258
259
260
261
262
263
264
265
266
267
268
269
270
def offset(self, value: int) -> BindParameter:
    """
    Return the named bind parameter for an offset, typed as an integer like
    the one SQLAlchemy creates for ``select.offset(10)``.

    :param value: offset value
    :type value: int
    :return: named bind parameter
    :rtype: BindParameter
    """
    return sqlalchemy.bindparam(
        key=OFFSET_SLOT, value=value, type_=sqlalchemy.Integer()
    )

StatementTemplate

Bases: NamedTuple

A statement from the template cache and the values to run it with for one call::

Text Only
1
2
3
template = queryset.filter(name="a").limit(5).build_select_template()
template.params  # -> {"ormar_p0": "a", "ormar_limit": 5}
await executor.fetch_all(template.statement, template.params)
Source code in ormar/queryset/templates/cache.py
Python
31
32
33
34
35
36
37
38
39
40
41
42
class StatementTemplate(NamedTuple):
    """
    A statement from the template cache and the values to run it with for one
    call::

        template = queryset.filter(name="a").limit(5).build_select_template()
        template.params  # -> {"ormar_p0": "a", "ormar_limit": 5}
        await executor.fetch_all(template.statement, template.params)
    """

    statement: Executable
    params: Dict[str, Any]

TemplateCache

Least-recently-used cache of one model's statements, keyed by cache key.

The size is bounded so an application that builds queries from many different filter combinations cannot grow memory without limit: once max_size keys are cached, adding one drops the key used longest ago.

Source code in ormar/queryset/templates/cache.py
Python
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class TemplateCache:
    """
    Least-recently-used cache of one model's statements, keyed by cache key.

    The size is bounded so an application that builds queries from many
    different filter combinations cannot grow memory without limit: once
    ``max_size`` keys are cached, adding one drops the key used longest ago.
    """

    def __init__(self, max_size: int = TEMPLATE_CACHE_SIZE) -> None:
        """
        :param max_size: number of cache keys kept
        :type max_size: int
        """
        self.max_size = max_size
        self.entries: "OrderedDict[Any, Any]" = OrderedDict()

    def get(self, key: Any) -> Any:
        """
        Return the statement cached for a key, or None, and mark it as the
        most recently used.

        Another thread using the same model may evict the entry between reading
        it and marking it, so that case is ignored: the statement is still
        valid for this call.

        :param key: cache key of the statement
        :type key: Any
        :return: cached statement or None
        :rtype: Any
        """
        statement = self.entries.get(key)
        if statement is not None:
            try:
                self.entries.move_to_end(key)
            except KeyError:  # pragma: no cover - evicted concurrently
                pass
        return statement

    def put(self, key: Any, statement: Any) -> None:
        """
        Cache the statement of a key. When the cache is full, the key used
        longest ago is dropped.

        :param key: cache key of the statement
        :type key: Any
        :param statement: statement to cache
        :type statement: Any
        """
        self.entries[key] = statement
        if len(self.entries) > self.max_size:
            self.entries.popitem(last=False)

    def clear(self) -> None:
        """Remove every cached statement."""
        self.entries.clear()

__init__(max_size=TEMPLATE_CACHE_SIZE)

Parameters:

Name Type Description Default
max_size int

number of cache keys kept

TEMPLATE_CACHE_SIZE
Source code in ormar/queryset/templates/cache.py
Python
54
55
56
57
58
59
60
def __init__(self, max_size: int = TEMPLATE_CACHE_SIZE) -> None:
    """
    :param max_size: number of cache keys kept
    :type max_size: int
    """
    self.max_size = max_size
    self.entries: "OrderedDict[Any, Any]" = OrderedDict()

clear()

Remove every cached statement.

Source code in ormar/queryset/templates/cache.py
Python
 98
 99
100
def clear(self) -> None:
    """Remove every cached statement."""
    self.entries.clear()

get(key)

Return the statement cached for a key, or None, and mark it as the most recently used.

Another thread using the same model may evict the entry between reading it and marking it, so that case is ignored: the statement is still valid for this call.

Parameters:

Name Type Description Default
key Any

cache key of the statement

required

Returns:

Type Description
Any

cached statement or None

Source code in ormar/queryset/templates/cache.py
Python
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def get(self, key: Any) -> Any:
    """
    Return the statement cached for a key, or None, and mark it as the
    most recently used.

    Another thread using the same model may evict the entry between reading
    it and marking it, so that case is ignored: the statement is still
    valid for this call.

    :param key: cache key of the statement
    :type key: Any
    :return: cached statement or None
    :rtype: Any
    """
    statement = self.entries.get(key)
    if statement is not None:
        try:
            self.entries.move_to_end(key)
        except KeyError:  # pragma: no cover - evicted concurrently
            pass
    return statement

put(key, statement)

Cache the statement of a key. When the cache is full, the key used longest ago is dropped.

Parameters:

Name Type Description Default
key Any

cache key of the statement

required
statement Any

statement to cache

required
Source code in ormar/queryset/templates/cache.py
Python
84
85
86
87
88
89
90
91
92
93
94
95
96
def put(self, key: Any, statement: Any) -> None:
    """
    Cache the statement of a key. When the cache is full, the key used
    longest ago is dropped.

    :param key: cache key of the statement
    :type key: Any
    :param statement: statement to cache
    :type statement: Any
    """
    self.entries[key] = statement
    if len(self.entries) > self.max_size:
        self.entries.popitem(last=False)

action_cache_key(action)

Return everything about a filter action that changes the SQL text: the field path, the table alias of the joined relation, the operator, the kind of value (see value_cache_key) and whether LIKE needs an ESCAPE clause for % or _ in the value.

Parameters:

Name Type Description Default
action FilterAction

filter action

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the action

Source code in ormar/queryset/templates/cache_keys.py
Python
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def action_cache_key(action: "FilterAction") -> Tuple[Any, ...]:
    """
    Return everything about a filter action that changes the SQL text: the
    field path, the table alias of the joined relation, the operator, the
    kind of value (see ``value_cache_key``) and whether LIKE needs an ``ESCAPE``
    clause for ``%`` or ``_`` in the value.

    :param action: filter action
    :type action: FilterAction
    :return: hashable cache key of the action
    :rtype: Tuple[Any, ...]
    """
    return (
        action.query_str,
        action.table_prefix,
        action.operator,
        value_cache_key(action=action),
        action.has_escaped_character,
    )

aggregate_statement(select, func_name, select_columns)

Wrap a read select into aggregate function columns, the statement run by QuerySet.max(), min(), sum() and avg()::

Text Only
1
2
SELECT max(subquery_for_max.score) AS score
FROM (<select>) AS subquery_for_max

Parameters:

Name Type Description Default
select Select

read select of the queryset

required
func_name str

aggregate function name

required
select_columns List[Any]

aggregate column expressions

required

Returns:

Type Description
Executable

aggregate statement

Source code in ormar/queryset/templates/reads.py
Python
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def aggregate_statement(
    select: sqlalchemy.sql.Select, func_name: str, select_columns: List[Any]
) -> Executable:
    """
    Wrap a read select into aggregate function columns, the statement run by
    ``QuerySet.max()``, ``min()``, ``sum()`` and ``avg()``::

        SELECT max(subquery_for_max.score) AS score
        FROM (<select>) AS subquery_for_max

    :param select: read select of the queryset
    :type select: sqlalchemy.sql.Select
    :param func_name: aggregate function name
    :type func_name: str
    :param select_columns: aggregate column expressions
    :type select_columns: List[Any]
    :return: aggregate statement
    :rtype: Executable
    """
    subquery = select.alias(name=f"subquery_for_{func_name}")
    return sqlalchemy.select(*select_columns).select_from(subquery)

build_insert(table, names)

Build an insert of the given columns with named value binds::

Text Only
1
INSERT INTO authors (name, score) VALUES (:ormar_v0, :ormar_v1)

The names are sorted by the caller, so the same columns given in any order share one statement.

Parameters:

Name Type Description Default
table Table

written table

required
names Tuple[str, ...]

written column names, sorted

required

Returns:

Type Description
Executable

insert statement

Source code in ormar/queryset/templates/writes.py
Python
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def build_insert(table: sqlalchemy.Table, names: Tuple[str, ...]) -> Executable:
    """
    Build an insert of the given columns with named value binds::

        INSERT INTO authors (name, score) VALUES (:ormar_v0, :ormar_v1)

    The names are sorted by the caller, so the same columns given in any
    order share one statement.

    :param table: written table
    :type table: sqlalchemy.Table
    :param names: written column names, sorted
    :type names: Tuple[str, ...]
    :return: insert statement
    :rtype: Executable
    """
    return table.insert().values(value_binds(table=table, names=names))

build_update_assignment(model, on_update, update_values)

Build the MySQL SET of the user variables a multi-row upsert reads its on_update values and the bound update_values from (see update_assignment).

Parameters:

Name Type Description Default
model Type[Any]

written model

required
on_update Tuple[str, ...]

columns updated with their on_update value

required
update_values Mapping[str, Any]

value or expression node by column name

required

Returns:

Type Description
Executable

assignment statement

Source code in ormar/queryset/templates/writes.py
Python
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def build_update_assignment(
    model: Type[Any],
    on_update: Tuple[str, ...],
    update_values: Mapping[str, Any],
) -> Executable:
    """
    Build the MySQL ``SET`` of the user variables a multi-row upsert reads its
    ``on_update`` values and the bound ``update_values`` from (see
    ``update_assignment``).

    :param model: written model
    :type model: Type[Any]
    :param on_update: columns updated with their ``on_update`` value
    :type on_update: Tuple[str, ...]
    :param update_values: value or expression node by column name
    :type update_values: Mapping[str, Any]
    :return: assignment statement
    :rtype: Executable
    """
    table = model.ormar_config.table
    clauses = update_value_clauses(
        inserted=table.c, model_cls=model, update_values=update_values
    )
    return update_assignment(
        table=table,
        on_update=on_update,
        value_binds=tuple(
            element
            for clause in clauses.values()
            for element in visitors.iterate(clause)
            if isinstance(element, BindParameter)
        ),
    )

cached_statement(model_cls, key, builder, **builder_kwargs)

Return the statement cached for a write cache key, building it on a miss. The statement is marked as a template (TEMPLATE_OPTION), so the native compiler keeps its plan even when SQLAlchemy cannot cache it.

A write's cache key is small (the kind of statement and the written column names), so callers pass the key directly. The statement is only built on a miss, from builder(**builder_kwargs)::

Text Only
1
2
3
4
5
6
7
cached_statement(
    model_cls=Author,
    key=("insert", ("name", "score")),
    builder=build_insert,
    table=Author.ormar_config.table,
    names=("name", "score"),
)

Parameters:

Name Type Description Default
model_cls Type[Any]

model the statement writes

required
key Tuple[Any, ...]

cache key of the write

required
builder Callable[..., Executable]

builds the statement from builder_kwargs

required
builder_kwargs Any

keyword arguments of the builder

{}

Returns:

Type Description
Executable

statement for the key

Source code in ormar/queryset/templates/cache.py
Python
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def cached_statement(
    model_cls: Type[Any],
    key: Tuple[Any, ...],
    builder: Callable[..., Executable],
    **builder_kwargs: Any,
) -> Executable:
    """
    Return the statement cached for a write cache key, building it on a miss.
    The statement is marked as a template (``TEMPLATE_OPTION``), so the native
    compiler keeps its plan even when SQLAlchemy cannot cache it.

    A write's cache key is small (the kind of statement and the written column
    names), so callers pass the key directly. The statement is only built on
    a miss, from ``builder(**builder_kwargs)``::

        cached_statement(
            model_cls=Author,
            key=("insert", ("name", "score")),
            builder=build_insert,
            table=Author.ormar_config.table,
            names=("name", "score"),
        )

    :param model_cls: model the statement writes
    :type model_cls: Type[Any]
    :param key: cache key of the write
    :type key: Tuple[Any, ...]
    :param builder: builds the statement from ``builder_kwargs``
    :type builder: Callable[..., Executable]
    :param builder_kwargs: keyword arguments of the builder
    :type builder_kwargs: Any
    :return: statement for the key
    :rtype: Executable
    """
    cache = template_cache_for(model_cls=model_cls)
    statement = cache.get(key)
    if statement is None:
        statement = builder(**builder_kwargs).execution_options(
            **{TEMPLATE_OPTION: True}
        )
        cache.put(key=key, statement=statement)
    return statement

canonical_actions(filter_clauses, exclude_clauses)

Return every filter action of a queryset in canonical order: filter clauses first, then exclude clauses, each in build order::

Text Only
1
2
Author.objects.exclude(score=0).filter(name="a")
# -> name="a" (ormar_p0), score=0 (ormar_p1)

SlotBinder (naming the slots while building) and template_params (collecting values on every call) both use this list, so a value always ends up in the slot built for it.

Parameters:

Name Type Description Default
filter_clauses List[Any]

queryset filter clauses

required
exclude_clauses List[Any]

queryset exclude clauses

required

Returns:

Type Description
List[FilterAction]

filter actions in canonical order

Source code in ormar/queryset/templates/slots.py
Python
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def canonical_actions(
    filter_clauses: List[Any], exclude_clauses: List[Any]
) -> List["FilterAction"]:
    """
    Return every filter action of a queryset in canonical order: filter clauses
    first, then exclude clauses, each in build order::

        Author.objects.exclude(score=0).filter(name="a")
        # -> name="a" (ormar_p0), score=0 (ormar_p1)

    ``SlotBinder`` (naming the slots while building) and ``template_params``
    (collecting values on every call) both use this list, so a value always
    ends up in the slot built for it.

    :param filter_clauses: queryset filter clauses
    :type filter_clauses: List[Any]
    :param exclude_clauses: queryset exclude clauses
    :type exclude_clauses: List[Any]
    :return: filter actions in canonical order
    :rtype: List[FilterAction]
    """
    return [
        *iter_actions(clauses=filter_clauses),
        *iter_actions(clauses=exclude_clauses),
    ]

clauses_cache_key(clauses)

Return the cache key of a list of filter actions and filter groups, keeping the and/or/not nesting, since or_(a, b) and and_(a, b) build different SQL from the same actions::

Text Only
1
2
filter(ormar.or_(name="a", score=1))
# -> (("group", FilterType.OR, False, (), (<name key>, <score key>)),)

Parameters:

Name Type Description Default
clauses Iterable[Any]

filter actions and filter groups

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the clauses

Source code in ormar/queryset/templates/cache_keys.py
Python
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def clauses_cache_key(clauses: Iterable[Any]) -> Tuple[Any, ...]:
    """
    Return the cache key of a list of filter actions and filter groups, keeping
    the and/or/not nesting, since ``or_(a, b)`` and ``and_(a, b)`` build
    different SQL from the same actions::

        filter(ormar.or_(name="a", score=1))
        # -> (("group", FilterType.OR, False, (), (<name key>, <score key>)),)

    :param clauses: filter actions and filter groups
    :type clauses: Iterable[Any]
    :return: hashable cache key of the clauses
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (
            "group",
            clause.filter_type,
            clause.exclude,
            clauses_cache_key(clauses=clause._nested_groups),
            tuple(action_cache_key(action=action) for action in clause.actions),
        )
        if hasattr(clause, "_nested_groups")
        else action_cache_key(action=clause)
        for clause in clauses
    )

count_statement(select, distinct, pk_column_names)

Wrap a read select into a row count, the statement run by QuerySet.count(). With distinct the rows are grouped by primary key first, so a model joined to several related rows is counted once::

Text Only
1
2
3
SELECT count(*) FROM (
    SELECT count(*) FROM (<select>) AS subquery_for_count GROUP BY <pk>
) AS subquery_for_group

Parameters:

Name Type Description Default
select Select

read select of the queryset

required
distinct bool

count distinct primary keys only

required
pk_column_names Tuple[str, ...]

primary key column aliases of the model

required

Returns:

Type Description
Executable

count statement

Source code in ormar/queryset/templates/reads.py
Python
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def count_statement(
    select: sqlalchemy.sql.Select, distinct: bool, pk_column_names: Tuple[str, ...]
) -> Executable:
    """
    Wrap a read select into a row count, the statement run by
    ``QuerySet.count()``. With ``distinct`` the rows are grouped by primary key
    first, so a model joined to several related rows is counted once::

        SELECT count(*) FROM (
            SELECT count(*) FROM (<select>) AS subquery_for_count GROUP BY <pk>
        ) AS subquery_for_group

    :param select: read select of the queryset
    :type select: sqlalchemy.sql.Select
    :param distinct: count distinct primary keys only
    :type distinct: bool
    :param pk_column_names: primary key column aliases of the model
    :type pk_column_names: Tuple[str, ...]
    :return: count statement
    :rtype: Executable
    """
    subquery = select.alias(name="subquery_for_count")
    expr = sqlalchemy.func.count().select().select_from(subquery)
    if distinct:
        grouped = expr.group_by(*pk_column_names).alias(  # type: ignore[arg-type]
            name="subquery_for_group"
        )
        expr = sqlalchemy.func.count().select().select_from(grouped)
    return expr

excludable_cache_key(excludable)

Return the fields included and excluded per model and relation, which decide the selected columns (fields(), exclude_fields(), values()). Field sets are sorted so the same selection always gives the same key.

Parameters:

Name Type Description Default
excludable ExcludableItems

queryset's fields to include and exclude

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the projection

Source code in ormar/queryset/templates/cache_keys.py
Python
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def excludable_cache_key(excludable: "ExcludableItems") -> Tuple[Any, ...]:
    """
    Return the fields included and excluded per model and relation, which
    decide the selected columns (``fields()``, ``exclude_fields()``,
    ``values()``). Field sets are sorted so the same selection always gives
    the same key.

    :param excludable: queryset's fields to include and exclude
    :type excludable: ExcludableItems
    :return: hashable cache key of the projection
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (
            key,
            tuple(sorted(item.include, key=repr)),
            tuple(sorted(item.exclude, key=repr)),
            tuple(sorted(item.flatten, key=repr)),
            item.pk_only,
        )
        for key, item in sorted(excludable.items.items())
    )

exists_statement(select)

Wrap a read select into SELECT EXISTS (...), the statement run by QuerySet.exists().

This and the other *_statement helpers are the wrap callables of QuerySet.build_select_template: they run on the select once, when a cache key is first seen, and the wrapped statement is what gets cached.

Parameters:

Name Type Description Default
select Select

read select of the queryset

required

Returns:

Type Description
Executable

exists statement

Source code in ormar/queryset/templates/reads.py
Python
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def exists_statement(select: sqlalchemy.sql.Select) -> Executable:
    """
    Wrap a read select into ``SELECT EXISTS (...)``, the statement run by
    ``QuerySet.exists()``.

    This and the other ``*_statement`` helpers are the ``wrap`` callables of
    ``QuerySet.build_select_template``: they run on the select once, when a
    cache key is first seen, and the wrapped statement is what gets cached.

    :param select: read select of the queryset
    :type select: sqlalchemy.sql.Select
    :return: exists statement
    :rtype: Executable
    """
    return sqlalchemy.exists(select).select()

insert_statement(model_cls, names, on_conflict=None, conflict_target=None, update_fields=None, on_update=(), returning=(), update_values=None, update_variables=False)

Return the insert of a model for the given sorted column names, from the model's template cache. save() binds one row to it and bulk_create runs it with executemany for every row with the same columns.

With on_conflict the insert skips or updates conflicting rows (see build_conflict_insert): the target defaults to the primary key and the updated columns to the inserted ones but the target, the key and on_update, or to none with update_values. One statement is cached per shape of update_values (see update_values_key).

Parameters:

Name Type Description Default
model_cls Type[Any]

inserted model

required
names Tuple[str, ...]

inserted column names, sorted

required
on_conflict Optional[str]

ignore or update conflicting rows

None
conflict_target Optional[Sequence[str]]

names of the fields of the conflicting unique key

None
update_fields Optional[Sequence[str]]

names of the fields updated from the inserted row

None
on_update Tuple[str, ...]

columns updated with their on_update value

()
returning Tuple[str, ...]

columns of the written row to return, if any

()
update_values Optional[Mapping[str, Any]]

value or expression node set by column name

None
update_variables bool

read the bound update values from MySQL user variables set by update_assignment instead of binds

False

Returns:

Type Description
Executable

insert statement with ormar_v{i} binds

Source code in ormar/queryset/templates/writes.py
Python
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def insert_statement(
    model_cls: Type[Any],
    names: Tuple[str, ...],
    on_conflict: Optional[str] = None,
    conflict_target: Optional[Sequence[str]] = None,
    update_fields: Optional[Sequence[str]] = None,
    on_update: Tuple[str, ...] = (),
    returning: Tuple[str, ...] = (),
    update_values: Optional[Mapping[str, Any]] = None,
    update_variables: bool = False,
) -> Executable:
    """
    Return the insert of a model for the given sorted column names, from the
    model's template cache. ``save()`` binds one row to it and
    ``bulk_create`` runs it with ``executemany`` for every row with the same
    columns.

    With ``on_conflict`` the insert skips or updates conflicting rows (see
    ``build_conflict_insert``): the target defaults to the primary key and the
    updated columns to the inserted ones but the target, the key and
    ``on_update``, or to none with ``update_values``. One statement is cached
    per shape of ``update_values`` (see ``update_values_key``).

    :param model_cls: inserted model
    :type model_cls: Type[Any]
    :param names: inserted column names, sorted
    :type names: Tuple[str, ...]
    :param on_conflict: ``ignore`` or ``update`` conflicting rows
    :type on_conflict: Optional[str]
    :param conflict_target: names of the fields of the conflicting unique key
    :type conflict_target: Optional[Sequence[str]]
    :param update_fields: names of the fields updated from the inserted row
    :type update_fields: Optional[Sequence[str]]
    :param on_update: columns updated with their ``on_update`` value
    :type on_update: Tuple[str, ...]
    :param returning: columns of the written row to return, if any
    :type returning: Tuple[str, ...]
    :param update_values: value or expression node set by column name
    :type update_values: Optional[Mapping[str, Any]]
    :param update_variables: read the bound update values from MySQL user
        variables set by ``update_assignment`` instead of binds
    :type update_variables: bool
    :return: insert statement with ``ormar_v{i}`` binds
    :rtype: Executable
    """
    config = model_cls.ormar_config
    if not on_conflict:
        return cached_statement(
            model_cls=model_cls,
            key=("insert", names),
            builder=build_insert,
            table=config.table,
            names=names,
        )
    pk = config.pk.column_aliases()
    target = (
        tuple(
            column
            for field_name in conflict_target or ()
            for column in model_cls.get_column_aliases(field_name=field_name)
        )
        or pk
    )
    update_names = tuple(
        sorted(
            column
            for field_name in update_fields or ()
            for column in model_cls.get_column_aliases(field_name=field_name)
        )
    )
    if not update_names and not update_values:
        update_names = tuple(
            column for column in names if column not in {*target, *pk, *on_update}
        )
    if (
        on_conflict == "update"
        and not update_names
        and not on_update
        and not update_values
    ):
        # nothing left to update: set a target column to itself, so the
        # conflicting row is still returned (DO NOTHING would return no row)
        update_names = target[:1]
    rules = config.database.rules
    conflict = dict(
        on_conflict=on_conflict,
        target=target,
        update_names=update_names,
        on_update=on_update,
        returning=returning,
        update_variables=update_variables,
    )
    return cached_statement(
        model_cls=model_cls,
        key=(
            "insert",
            names,
            rules.backend_name,
            *conflict.values(),
            update_values_key(update_values=update_values or {}),
        ),
        builder=build_conflict_insert,
        table=config.table,
        names=names,
        rules=rules,
        model=model_cls,
        update_values=update_values,
        **conflict,
    )

insert_template(model_cls, values, **statement_kwargs)

Return the insert of a model for the given column values, used by save() and one-row bulk_create::

Text Only
1
2
3
insert_template(model_cls=Author, values={"name": "a", "score": 1})
# -> INSERT INTO authors (name, score) VALUES (:ormar_v0, :ormar_v1)
#    {"ormar_v0": "a", "ormar_v1": 1}

Rows that leave out the primary key or a column with a server default write a different set of columns, so each set gets its own statement.

Parameters:

Name Type Description Default
model_cls Type[Any]

inserted model

required
values Mapping[str, Any]

values by column name

required
statement_kwargs Any

conflict handling (see insert_statement)

{}

Returns:

Type Description
StatementTemplate

statement and values to bind

Source code in ormar/queryset/templates/writes.py
Python
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def insert_template(
    model_cls: Type[Any], values: Mapping[str, Any], **statement_kwargs: Any
) -> StatementTemplate:
    """
    Return the insert of a model for the given column values, used by
    ``save()`` and one-row ``bulk_create``::

        insert_template(model_cls=Author, values={"name": "a", "score": 1})
        # -> INSERT INTO authors (name, score) VALUES (:ormar_v0, :ormar_v1)
        #    {"ormar_v0": "a", "ormar_v1": 1}

    Rows that leave out the primary key or a column with a server default
    write a different set of columns, so each set gets its own statement.

    :param model_cls: inserted model
    :type model_cls: Type[Any]
    :param values: values by column name
    :type values: Mapping[str, Any]
    :param statement_kwargs: conflict handling (see ``insert_statement``)
    :type statement_kwargs: Any
    :return: statement and values to bind
    :rtype: StatementTemplate
    """
    names = tuple(sorted(values))
    statement = insert_statement(model_cls=model_cls, names=names, **statement_kwargs)
    params = value_params(names=names, values=values)
    return StatementTemplate(statement=statement, params=params)

iter_actions(clauses)

Yield the filter actions of a clause list in the order their SQL is built: a group's nested groups first, then its own actions (the order FilterGroup.get_text_clause emits them in)::

Text Only
1
2
filter(ormar.or_(ormar.and_(score=1, id=2), name="a"))
# -> score=1, id=2, name="a"

The order is the same for every queryset of one cache key, so an action's index here can name its slot.

Parameters:

Name Type Description Default
clauses List[Union[FilterAction, FilterGroup]]

filter actions and filter groups

required

Returns:

Type Description
Iterator[FilterAction]

filter actions in build order

Source code in ormar/queryset/templates/slots.py
Python
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def iter_actions(
    clauses: List[Union["FilterAction", "FilterGroup"]],
) -> Iterator["FilterAction"]:
    """
    Yield the filter actions of a clause list in the order their SQL is built:
    a group's nested groups first, then its own actions (the order
    ``FilterGroup.get_text_clause`` emits them in)::

        filter(ormar.or_(ormar.and_(score=1, id=2), name="a"))
        # -> score=1, id=2, name="a"

    The order is the same for every queryset of one cache key, so an action's
    index here can name its slot.

    :param clauses: filter actions and filter groups
    :type clauses: List[Union[FilterAction, FilterGroup]]
    :return: filter actions in build order
    :rtype: Iterator[FilterAction]
    """
    for clause in clauses:
        if hasattr(clause, "_nested_groups"):
            yield from iter_actions(clauses=clause._nested_groups)  # type: ignore
            yield from clause.actions  # type: ignore
        else:
            yield clause  # type: ignore

order_cache_key(order_bys)

Return the cache key of the requested orderings: field path, direction, table alias and nulls placement of each, in order::

Text Only
1
order_by("-name")  # -> (("-name", "desc", "", None),)

Parameters:

Name Type Description Default
order_bys Iterable[OrderAction]

order actions of the query

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the ordering

Source code in ormar/queryset/templates/cache_keys.py
Python
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def order_cache_key(order_bys: Iterable["OrderAction"]) -> Tuple[Any, ...]:
    """
    Return the cache key of the requested orderings: field path, direction, table
    alias and nulls placement of each, in order::

        order_by("-name")  # -> (("-name", "desc", "", None),)

    :param order_bys: order actions of the query
    :type order_bys: Iterable[OrderAction]
    :return: hashable cache key of the ordering
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (order.query_str, order.direction, order.table_prefix, order.nulls_ordering)
        for order in order_bys
    )

release_values(statement)

Drop the values of a template's named slots, so a cached statement does not keep the first call's values (possibly large lists or documents) alive for as long as it stays cached. Every call binds its own values anyway.

SQLAlchemy may have cloned the bind parameters while wrapping the select (for example into a subquery), so the whole statement is walked instead of clearing only the parameters SlotBinder created.

Parameters:

Name Type Description Default
statement Executable

built template statement

required
Source code in ormar/queryset/templates/reads.py
Python
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def release_values(statement: Executable) -> None:
    """
    Drop the values of a template's named slots, so a cached statement does
    not keep the first call's values (possibly large lists or documents) alive
    for as long as it stays cached. Every call binds its own values anyway.

    SQLAlchemy may have cloned the bind parameters while wrapping the select
    (for example into a subquery), so the whole statement is walked instead of
    clearing only the parameters ``SlotBinder`` created.

    :param statement: built template statement
    :type statement: Executable
    """
    for element in visitors.iterate(statement):  # type: ignore[arg-type]
        if isinstance(element, BindParameter) and str(element.key).startswith("ormar_"):
            element.value = None

template_cache_for(model_cls)

Return the statement template cache of a model class, creating it on the model's first read. setdefault keeps a single cache when two threads create it at the same time.

Parameters:

Name Type Description Default
model_cls Type[Any]

model class

required

Returns:

Type Description
TemplateCache

the model's template cache

Source code in ormar/queryset/templates/cache.py
Python
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def template_cache_for(model_cls: Type[Any]) -> TemplateCache:
    """
    Return the statement template cache of a model class, creating it on the
    model's first read. ``setdefault`` keeps a single cache when two threads
    create it at the same time.

    :param model_cls: model class
    :type model_cls: Type[Any]
    :return: the model's template cache
    :rtype: TemplateCache
    """
    cache = TEMPLATE_CACHES.get(model_cls)
    if cache is None:
        cache = TEMPLATE_CACHES.setdefault(model_cls, TemplateCache())
    return cache

template_params(actions, limit, offset)

Collect the values a template binds for one call, keyed like the slots SlotBinder names::

Text Only
1
2
Author.objects.filter(name="a", score__gt=5).limit(10)
# -> {"ormar_p0": "a", "ormar_p1": 5, "ormar_limit": 10}

Actions whose value is written into the SQL text (see FilterAction.binds_slot) get no entry, but still use up their index, so the names of the other slots do not depend on those values. The offset is only bound when non-zero, matching OffsetQuery, which leaves out OFFSET 0.

Parameters:

Name Type Description Default
actions List[FilterAction]

filter actions in canonical order

required
limit Optional[int]

effective limit (applied when not None)

required
offset Optional[int]

effective offset (applied when truthy)

required

Returns:

Type Description
Dict[str, Any]

values per slot name

Source code in ormar/queryset/templates/slots.py
Python
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def template_params(
    actions: List["FilterAction"], limit: Optional[int], offset: Optional[int]
) -> Dict[str, Any]:
    """
    Collect the values a template binds for one call, keyed like the slots
    ``SlotBinder`` names::

        Author.objects.filter(name="a", score__gt=5).limit(10)
        # -> {"ormar_p0": "a", "ormar_p1": 5, "ormar_limit": 10}

    Actions whose value is written into the SQL text (see
    ``FilterAction.binds_slot``) get no entry, but still use up their index,
    so the names of the other slots do not depend on those values. The offset
    is only bound when non-zero, matching ``OffsetQuery``, which leaves out
    ``OFFSET 0``.

    :param actions: filter actions in canonical order
    :type actions: List[FilterAction]
    :param limit: effective limit (applied when not None)
    :type limit: Optional[int]
    :param offset: effective offset (applied when truthy)
    :type offset: Optional[int]
    :return: values per slot name
    :rtype: Dict[str, Any]
    """
    params = {}
    for index, action in enumerate(actions):
        if action.binds_slot():
            params.update(
                expression_params(value=action.bound_value(), slot=f"ormar_p{index}")
            )
    if limit is not None:
        params[LIMIT_SLOT] = limit
    if offset:
        params[OFFSET_SLOT] = offset
    return params

update_values_key(update_values)

Return the shape of the update_values of an upsert for cache keys: the column of a value, the column and expression_key of an expression, so the literals do not split the cache.

Parameters:

Name Type Description Default
update_values Mapping[str, Any]

value or expression node by column name

required

Returns:

Type Description
Tuple[Any, ...]

hashable shape

Source code in ormar/queryset/templates/writes.py
Python
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def update_values_key(update_values: Mapping[str, Any]) -> Tuple[Any, ...]:
    """
    Return the shape of the ``update_values`` of an upsert for cache keys: the
    column of a value, the column and ``expression_key`` of an expression, so
    the literals do not split the cache.

    :param update_values: value or expression node by column name
    :type update_values: Mapping[str, Any]
    :return: hashable shape
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (name, expression_key(node=update_values[name]))
        if isinstance(update_values[name], Expression)
        else name
        for name in sorted(update_values)
    )

update_values_params(update_values)

Return the values bound by the update_values of an upsert, named like update_value_clauses names them::

Text Only
1
2
update_values_params(update_values={"completed": F("completed") + 1})
# -> {"ormar_u0_0": 1}

Parameters:

Name Type Description Default
update_values Mapping[str, Any]

value or expression node by column name

required

Returns:

Type Description
Dict[str, Any]

values by bind parameter name

Source code in ormar/queryset/templates/writes.py
Python
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def update_values_params(update_values: Mapping[str, Any]) -> Dict[str, Any]:
    """
    Return the values bound by the ``update_values`` of an upsert, named like
    ``update_value_clauses`` names them::

        update_values_params(update_values={"completed": F("completed") + 1})
        # -> {"ormar_u0_0": 1}

    :param update_values: value or expression node by column name
    :type update_values: Mapping[str, Any]
    :return: values by bind parameter name
    :rtype: Dict[str, Any]
    """
    params: Dict[str, Any] = {}
    for index, name in enumerate(sorted(update_values)):
        params.update(
            expression_params(value=update_values[name], slot=f"ormar_u{index}")
        )
    return params

value_binds(table, names)

Return named bind parameters for the written columns, ormar_v{i} in the given column order, typed like their columns::

Text Only
1
2
value_binds(table=authors, names=("name", "score"))
# -> {authors.c.name: :ormar_v0, authors.c.score: :ormar_v1}

Parameters:

Name Type Description Default
table Table

written table

required
names Tuple[str, ...]

written column names, sorted

required

Returns:

Type Description
Dict[Any, Any]

bind parameter per column

Source code in ormar/queryset/templates/slots.py
Python
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def value_binds(table: sqlalchemy.Table, names: Tuple[str, ...]) -> Dict[Any, Any]:
    """
    Return named bind parameters for the written columns, ``ormar_v{i}`` in
    the given column order, typed like their columns::

        value_binds(table=authors, names=("name", "score"))
        # -> {authors.c.name: :ormar_v0, authors.c.score: :ormar_v1}

    :param table: written table
    :type table: sqlalchemy.Table
    :param names: written column names, sorted
    :type names: Tuple[str, ...]
    :return: bind parameter per column
    :rtype: Dict[Any, Any]
    """
    return {
        table.c[name]: sqlalchemy.bindparam(
            key=f"ormar_v{index}", type_=table.c[name].type
        )
        for index, name in enumerate(names)
    }

value_cache_key(action)

Return the part of a filter value that changes the SQL text::

Text Only
1
2
3
4
5
6
filter(name__isnull=True)  # -> ("isnull", True)   IS NULL
filter(name=None)  # -> ("literal", None)  IS NULL
filter(active=True)  # -> ("literal", True)  literal true
filter(id__in=[1, 2])  # -> "in"               IN (expanding)
filter(name="a")  # -> ("value", str)     = :ormar_p0
filter(a__lt=F("b") + 1)  # -> ("expr", <shape>)  < b + :ormar_p0_0

Values written into the SQL text are part of the key as they are. For a bound value only its type is kept, so values of different types never share a statement.

Parameters:

Name Type Description Default
action FilterAction

filter action

required

Returns:

Type Description
Any

hashable value kind

Source code in ormar/queryset/templates/cache_keys.py
Python
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def value_cache_key(action: "FilterAction") -> Any:
    """
    Return the part of a filter value that changes the SQL text::

        filter(name__isnull=True)  # -> ("isnull", True)   IS NULL
        filter(name=None)  # -> ("literal", None)  IS NULL
        filter(active=True)  # -> ("literal", True)  literal true
        filter(id__in=[1, 2])  # -> "in"               IN (expanding)
        filter(name="a")  # -> ("value", str)     = :ormar_p0
        filter(a__lt=F("b") + 1)  # -> ("expr", <shape>)  < b + :ormar_p0_0

    Values written into the SQL text are part of the key as they are. For a
    bound value only its type is kept, so values of different types never
    share a statement.

    :param action: filter action
    :type action: FilterAction
    :return: hashable value kind
    :rtype: Any
    """
    value = action.bound_value()
    if isinstance(value, Expression):
        return ("expr", expression_key(node=value))
    if action.operator == "isnull":
        return ("isnull", bool(value))
    if action.operator == "in":
        return "in"
    if not action.binds_slot():
        return ("literal", value)
    return ("value", type(value))

value_params(names, values)

Return the written values keyed by their bind parameter names, matching value_binds for the same names::

Text Only
1
2
value_params(names=("name", "score"), values={"score": 1, "name": "a"})
# -> {"ormar_v0": "a", "ormar_v1": 1}

Parameters:

Name Type Description Default
names Tuple[str, ...]

written column names, sorted

required
values Mapping[str, Any]

written values by column name

required

Returns:

Type Description
Dict[str, Any]

values by bind parameter name

Source code in ormar/queryset/templates/slots.py
Python
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def value_params(names: Tuple[str, ...], values: Mapping[str, Any]) -> Dict[str, Any]:
    """
    Return the written values keyed by their bind parameter names, matching
    ``value_binds`` for the same ``names``::

        value_params(names=("name", "score"), values={"score": 1, "name": "a"})
        # -> {"ormar_v0": "a", "ormar_v1": 1}

    :param names: written column names, sorted
    :type names: Tuple[str, ...]
    :param values: written values by column name
    :type values: Mapping[str, Any]
    :return: values by bind parameter name
    :rtype: Dict[str, Any]
    """
    return {f"ormar_v{index}": values[name] for index, name in enumerate(names)}