Skip to content

write_statements

UPDATE, DELETE and locking SELECT statements of a model: filtered by a queryset (QuerySet.build_write_template) or by primary key (row_template, bulk_update).

Every statement is built in the same steps, each class overriding only the steps it changes::

Text Only
1
2
3
4
5
6
7
target    UPDATE / DELETE / SELECT
joins     the tables the updated values read
restrict  WHERE: the filters, the matched rows or the primary key(s)
finish    RETURNING or FOR UPDATE

DeleteWrite(model=Author, queryset=qs, binder=binder).build()
DeleteWrite.make(model=Author)  # DELETE ... WHERE authors.id = :ormar_pk

BulkUpdateWrite

Bases: UpdateWrite

UPDATE ... SET <col>=:new_<col> WHERE <pk> = :<prefix><pk>: the per-row update of bulk_update, run once per row by executemany::

Text Only
1
2
UPDATE authors SET name=:new_name WHERE authors.id = :new_id
# rows: [{"new_id": 1, "new_name": "a"}, {"new_id": 2, "new_name": "b"}]
Source code in ormar/queryset/write_statements.py
Python
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
271
class BulkUpdateWrite(UpdateWrite):
    """
    ``UPDATE ... SET <col>=:new_<col> WHERE <pk> = :<prefix><pk>``: the per-row
    update of ``bulk_update``, run once per row by ``executemany``::

        UPDATE authors SET name=:new_name WHERE authors.id = :new_id
        # rows: [{"new_id": 1, "new_name": "a"}, {"new_id": 2, "new_name": "b"}]
    """

    def __init__(
        self, model: type["Model"], columns: tuple[str, ...], where_prefix: str
    ):
        """
        :param model: updated model
        :type model: type[Model]
        :param columns: updated column names
        :type columns: tuple[str, ...]
        :param where_prefix: prefix of the key parameters matching each row:
            ``new_`` for the current key, ``old_`` for the persisted key when a
            key in the batch was changed (the key columns are then also updated)
        :type where_prefix: str
        """
        super().__init__(model=model)
        self.where_prefix = where_prefix
        self.assignments = {
            name: sqlalchemy.bindparam(key="new_" + name) for name in columns
        }

    def restrict(self, expr: Any) -> Any:
        """
        :param expr: update to restrict
        :type expr: Any
        :return: update of the row with the prefixed untyped key parameters
        :rtype: Any
        """
        aliases = self.primary_key.column_aliases()
        slots = tuple(self.where_prefix + alias for alias in aliases)
        return expr.where(self.primary_key.where_clause(slots=slots, typed=False))

__init__(model, columns, where_prefix)

Parameters:

Name Type Description Default
model type[Model]

updated model

required
columns tuple[str, ...]

updated column names

required
where_prefix str

prefix of the key parameters matching each row: new_ for the current key, old_ for the persisted key when a key in the batch was changed (the key columns are then also updated)

required
Source code in ormar/queryset/write_statements.py
Python
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def __init__(
    self, model: type["Model"], columns: tuple[str, ...], where_prefix: str
):
    """
    :param model: updated model
    :type model: type[Model]
    :param columns: updated column names
    :type columns: tuple[str, ...]
    :param where_prefix: prefix of the key parameters matching each row:
        ``new_`` for the current key, ``old_`` for the persisted key when a
        key in the batch was changed (the key columns are then also updated)
    :type where_prefix: str
    """
    super().__init__(model=model)
    self.where_prefix = where_prefix
    self.assignments = {
        name: sqlalchemy.bindparam(key="new_" + name) for name in columns
    }

restrict(expr)

Parameters:

Name Type Description Default
expr Any

update to restrict

required

Returns:

Type Description
Any

update of the row with the prefixed untyped key parameters

Source code in ormar/queryset/write_statements.py
Python
262
263
264
265
266
267
268
269
270
271
def restrict(self, expr: Any) -> Any:
    """
    :param expr: update to restrict
    :type expr: Any
    :return: update of the row with the prefixed untyped key parameters
    :rtype: Any
    """
    aliases = self.primary_key.column_aliases()
    slots = tuple(self.where_prefix + alias for alias in aliases)
    return expr.where(self.primary_key.where_clause(slots=slots, typed=False))

DeleteWrite

Bases: WriteStatement

DELETE ... WHERE <filters or pk>

Source code in ormar/queryset/write_statements.py
Python
274
275
276
277
278
279
280
281
282
283
284
class DeleteWrite(WriteStatement):
    """``DELETE ... WHERE <filters or pk>``"""

    row_key = "delete"

    def target(self) -> Any:
        """
        :return: delete of the table
        :rtype: Any
        """
        return self.table.delete()

target()

Returns:

Type Description
Any

delete of the table

Source code in ormar/queryset/write_statements.py
Python
279
280
281
282
283
284
def target(self) -> Any:
    """
    :return: delete of the table
    :rtype: Any
    """
    return self.table.delete()

LockWrite

Bases: WriteStatement

SELECT <pk> ... WHERE <filters> FOR UPDATE: the rows the update would touch, locked (update_returning() without RETURNING). It joins the tables the values read too, so it selects the same rows as the update.

Source code in ormar/queryset/write_statements.py
Python
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class LockWrite(WriteStatement):
    """
    ``SELECT <pk> ... WHERE <filters> FOR UPDATE``: the rows the update would
    touch, locked (``update_returning()`` without ``RETURNING``). It joins the
    tables the values read too, so it selects the same rows as the update.
    """

    def target(self) -> Any:
        """
        :return: select of the primary key locking the rows
        :rtype: Any
        """
        primary_key = self.primary_key.columns()
        return sqlalchemy.select(*primary_key).with_for_update(of=self.table)

target()

Returns:

Type Description
Any

select of the primary key locking the rows

Source code in ormar/queryset/write_statements.py
Python
294
295
296
297
298
299
300
def target(self) -> Any:
    """
    :return: select of the primary key locking the rows
    :rtype: Any
    """
    primary_key = self.primary_key.columns()
    return sqlalchemy.select(*primary_key).with_for_update(of=self.table)

RowSelectWrite

Bases: WriteStatement

SELECT <all columns> ... WHERE <pk> = :ormar_pk: the row of Model.load() and of the existence check of upsert(force_save=True).

Source code in ormar/queryset/write_statements.py
Python
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class RowSelectWrite(WriteStatement):
    """
    ``SELECT <all columns> ... WHERE <pk> = :ormar_pk``: the row of
    ``Model.load()`` and of the existence check of ``upsert(force_save=True)``.
    """

    row_key = "select_pk"

    def target(self) -> Any:
        """
        :return: select of all columns of the table
        :rtype: Any
        """
        return self.table.select()

target()

Returns:

Type Description
Any

select of all columns of the table

Source code in ormar/queryset/write_statements.py
Python
311
312
313
314
315
316
def target(self) -> Any:
    """
    :return: select of all columns of the table
    :rtype: Any
    """
    return self.table.select()

RowsLockWrite

Bases: RowSelectWrite

SELECT <all columns> ... WHERE <pk> IN (:ormar_pks) FOR UPDATE: the rows update_returning() reads back where the database has no UPDATE ... RETURNING. A locking read sees the latest committed row versions, a plain read in a MySQL REPEATABLE READ transaction would see its snapshot. The update already locked the rows, so the lock costs nothing.

Source code in ormar/queryset/write_statements.py
Python
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
class RowsLockWrite(RowSelectWrite):
    """
    ``SELECT <all columns> ... WHERE <pk> IN (:ormar_pks) FOR UPDATE``: the
    rows ``update_returning()`` reads back where the database has no
    ``UPDATE ... RETURNING``. A locking read sees the latest committed row
    versions, a plain read in a MySQL REPEATABLE READ transaction would see its
    snapshot. The update already locked the rows, so the lock costs nothing.
    """

    row_key = "select_pks"
    restrict = UpdateLockedWrite.restrict

    def finish(self, expr: Any) -> Any:
        """
        :param expr: restricted select
        :type expr: Any
        :return: select locking the rows
        :rtype: Any
        """
        return expr.with_for_update()

    @staticmethod
    def key_params(primary_key: "PrimaryKey", key: Any) -> dict:
        """
        :param primary_key: primary key of the model
        :type primary_key: PrimaryKey
        :param key: primary key values, tuples of column values for a
            composite key
        :type key: Any
        :return: parameters binding the keys to ``PKS_SLOT``
        :rtype: dict
        """
        return {PKS_SLOT: key}

finish(expr)

Parameters:

Name Type Description Default
expr Any

restricted select

required

Returns:

Type Description
Any

select locking the rows

Source code in ormar/queryset/write_statements.py
Python
331
332
333
334
335
336
337
338
def finish(self, expr: Any) -> Any:
    """
    :param expr: restricted select
    :type expr: Any
    :return: select locking the rows
    :rtype: Any
    """
    return expr.with_for_update()

key_params(primary_key, key) staticmethod

Parameters:

Name Type Description Default
primary_key PrimaryKey

primary key of the model

required
key Any

primary key values, tuples of column values for a composite key

required

Returns:

Type Description
dict

parameters binding the keys to PKS_SLOT

Source code in ormar/queryset/write_statements.py
Python
340
341
342
343
344
345
346
347
348
349
350
351
@staticmethod
def key_params(primary_key: "PrimaryKey", key: Any) -> dict:
    """
    :param primary_key: primary key of the model
    :type primary_key: PrimaryKey
    :param key: primary key values, tuples of column values for a
        composite key
    :type key: Any
    :return: parameters binding the keys to ``PKS_SLOT``
    :rtype: dict
    """
    return {PKS_SLOT: key}

UpdateLockedWrite

Bases: UpdateWrite

UPDATE ... WHERE <pk> IN (<locked keys>): the update of the rows LockWrite locked, the filters already chose them.

Source code in ormar/queryset/write_statements.py
Python
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class UpdateLockedWrite(UpdateWrite):
    """
    ``UPDATE ... WHERE <pk> IN (<locked keys>)``: the update of the rows
    ``LockWrite`` locked, the filters already chose them.
    """

    def restrict(self, expr: Any) -> Any:
        """
        :param expr: statement to restrict
        :type expr: Any
        :return: statement of the primary keys bound to ``PKS_SLOT``
        :rtype: Any
        """
        return expr.where(self.primary_key.in_clause(slot=PKS_SLOT))

restrict(expr)

Parameters:

Name Type Description Default
expr Any

statement to restrict

required

Returns:

Type Description
Any

statement of the primary keys bound to PKS_SLOT

Source code in ormar/queryset/write_statements.py
Python
224
225
226
227
228
229
230
231
def restrict(self, expr: Any) -> Any:
    """
    :param expr: statement to restrict
    :type expr: Any
    :return: statement of the primary keys bound to ``PKS_SLOT``
    :rtype: Any
    """
    return expr.where(self.primary_key.in_clause(slot=PKS_SLOT))

UpdateReturningWrite

Bases: UpdateWrite

UPDATE ... WHERE <filters> RETURNING <all columns>

Source code in ormar/queryset/write_statements.py
Python
205
206
207
208
209
210
211
212
213
214
215
class UpdateReturningWrite(UpdateWrite):
    """``UPDATE ... WHERE <filters> RETURNING <all columns>``"""

    def finish(self, expr: Any) -> Any:
        """
        :param expr: restricted update
        :type expr: Any
        :return: update returning all columns of the table
        :rtype: Any
        """
        return expr.returning(*self.table.c)

finish(expr)

Parameters:

Name Type Description Default
expr Any

restricted update

required

Returns:

Type Description
Any

update returning all columns of the table

Source code in ormar/queryset/write_statements.py
Python
208
209
210
211
212
213
214
215
def finish(self, expr: Any) -> Any:
    """
    :param expr: restricted update
    :type expr: Any
    :return: update returning all columns of the table
    :rtype: Any
    """
    return expr.returning(*self.table.c)

UpdateWrite

Bases: WriteStatement

UPDATE ... SET <values> WHERE <filters or pk>

Source code in ormar/queryset/write_statements.py
Python
192
193
194
195
196
197
198
199
200
201
202
class UpdateWrite(WriteStatement):
    """``UPDATE ... SET <values> WHERE <filters or pk>``"""

    row_key = "update"

    def target(self) -> Any:
        """
        :return: update setting the values
        :rtype: Any
        """
        return self.table.update().values(self.assignments)

target()

Returns:

Type Description
Any

update setting the values

Source code in ormar/queryset/write_statements.py
Python
197
198
199
200
201
202
def target(self) -> Any:
    """
    :return: update setting the values
    :rtype: Any
    """
    return self.table.update().values(self.assignments)

WriteStatement

Bases: ABC

Write of a model with named slots for the updated values and the filter values: of the rows of a queryset when one is given, of one row by primary key (ormar_pk slots) otherwise. Subclasses give the target and override the other steps they change.

Attributes:

Name Type Description
row_key

cache key of the statement by primary key (row_template)

Source code in ormar/queryset/write_statements.py
Python
 43
 44
 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
101
102
103
104
105
106
107
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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class WriteStatement(abc.ABC):
    """
    Write of a model with named slots for the updated values and the filter
    values: of the rows of a queryset when one is given, of one row by
    primary key (``ormar_pk`` slots) otherwise. Subclasses give the
    ``target`` and override the other steps they change.

    :cvar row_key: cache key of the statement by primary key (``row_template``)
    """

    row_key = ""

    def __init__(
        self,
        model: type["Model"],
        queryset: Optional["QuerySet"] = None,
        values: Optional[Mapping[str, Any]] = None,
        binder: Optional[SlotBinder] = None,
    ):
        """
        :param model: written model
        :type model: type[Model]
        :param queryset: queryset selecting the written rows, if not by key
        :type queryset: Optional[QuerySet]
        :param values: updated values by column name (none for delete)
        :type values: Optional[Mapping[str, Any]]
        :param binder: names filter values for templates
        :type binder: Optional[SlotBinder]
        """
        self.model = model
        self.queryset = queryset
        self.table = model.ormar_config.table
        self.primary_key = model.ormar_config.pk
        self.values = values or {}
        self.binder = binder
        self.join_conditions: dict[str, list] = {}
        self.assignments = self.read_values()

    @classmethod
    def make(cls, **kwargs: Any) -> Any:
        """
        :param kwargs: arguments of the statement
        :type kwargs: Any
        :return: built statement, a builder of ``cached_statement``
        :rtype: Any
        """
        return cls(**kwargs).build()

    def read_values(self) -> dict:
        """
        Return the column assignments of the updated values, with expressions
        in place of the binds of the expression values, and collect the join
        conditions of the related tables those expressions read.

        :return: bind or expression per column
        :rtype: dict
        """
        names = tuple(sorted(self.values))
        assignments = value_binds(table=self.table, names=names)
        for index, name in enumerate(names):
            if isinstance(self.values[name], Expression):
                columns = expression_columns(node=self.values[name], model=self.model)
                assignments[self.table.c[name]] = expression_clause(
                    node=self.values[name], columns=columns, slot=f"ormar_v{index}"
                )
                for column in columns.values():
                    self.join_conditions.update(
                        forward_join_conditions(
                            model=self.model, path=column.related_parts
                        )
                    )
        return assignments

    def build(self) -> Any:
        """
        :return: statement to execute
        :rtype: Any
        """
        expr = self.join_read_tables(expr=self.target())
        return self.finish(expr=self.restrict(expr=expr))

    @abc.abstractmethod
    def target(self) -> Any:
        """
        :return: statement before its rows are restricted
        :rtype: Any
        """

    def join_read_tables(self, expr: Any) -> Any:
        """
        Join the tables the updated values read (``UPDATE ... FROM`` or a
        multi-table ``UPDATE`` on MySQL, as SQLAlchemy renders it).

        :param expr: statement to join
        :type expr: Any
        :return: joined statement
        :rtype: Any
        """
        for conditions in self.join_conditions.values():
            expr = expr.where(*conditions)
        return expr

    def restrict(self, expr: Any) -> Any:
        """
        Restrict the statement to one row by primary key without a queryset,
        else to the rows the queryset selects in ``all()``: by the primary
        keys it selects (see ``QuerySet.matched_rows_clause``) when a filter
        reads a related model, by the filter and exclude clauses otherwise.

        :param expr: statement to restrict
        :type expr: Any
        :return: restricted statement
        :rtype: Any
        """
        queryset = self.queryset
        if queryset is None:
            slots = self.primary_key.bind_slots()
            return expr.where(self.primary_key.where_clause(slots=slots))
        if queryset._filters_read_related():
            return expr.where(queryset.matched_rows_clause(binder=self.binder))
        expr = FilterQuery(
            filter_clauses=queryset.filter_clauses, binder=self.binder
        ).apply(expr=expr)
        return FilterQuery(
            filter_clauses=queryset.exclude_clauses, exclude=True, binder=self.binder
        ).apply(expr=expr)

    def finish(self, expr: Any) -> Any:
        """
        :param expr: restricted statement
        :type expr: Any
        :return: statement to execute
        :rtype: Any
        """
        return expr

    @staticmethod
    def key_params(primary_key: "PrimaryKey", key: Any) -> dict:
        """
        :param primary_key: primary key of the model
        :type primary_key: PrimaryKey
        :param key: primary key value of the row
        :type key: Any
        :return: parameters binding the key (see ``row_template``)
        :rtype: dict
        """
        return primary_key.bind_params(value=key)

__init__(model, queryset=None, values=None, binder=None)

Parameters:

Name Type Description Default
model type[Model]

written model

required
queryset Optional[QuerySet]

queryset selecting the written rows, if not by key

None
values Optional[Mapping[str, Any]]

updated values by column name (none for delete)

None
binder Optional[SlotBinder]

names filter values for templates

None
Source code in ormar/queryset/write_statements.py
Python
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
def __init__(
    self,
    model: type["Model"],
    queryset: Optional["QuerySet"] = None,
    values: Optional[Mapping[str, Any]] = None,
    binder: Optional[SlotBinder] = None,
):
    """
    :param model: written model
    :type model: type[Model]
    :param queryset: queryset selecting the written rows, if not by key
    :type queryset: Optional[QuerySet]
    :param values: updated values by column name (none for delete)
    :type values: Optional[Mapping[str, Any]]
    :param binder: names filter values for templates
    :type binder: Optional[SlotBinder]
    """
    self.model = model
    self.queryset = queryset
    self.table = model.ormar_config.table
    self.primary_key = model.ormar_config.pk
    self.values = values or {}
    self.binder = binder
    self.join_conditions: dict[str, list] = {}
    self.assignments = self.read_values()

build()

Returns:

Type Description
Any

statement to execute

Source code in ormar/queryset/write_statements.py
Python
116
117
118
119
120
121
122
def build(self) -> Any:
    """
    :return: statement to execute
    :rtype: Any
    """
    expr = self.join_read_tables(expr=self.target())
    return self.finish(expr=self.restrict(expr=expr))

finish(expr)

Parameters:

Name Type Description Default
expr Any

restricted statement

required

Returns:

Type Description
Any

statement to execute

Source code in ormar/queryset/write_statements.py
Python
170
171
172
173
174
175
176
177
def finish(self, expr: Any) -> Any:
    """
    :param expr: restricted statement
    :type expr: Any
    :return: statement to execute
    :rtype: Any
    """
    return expr

join_read_tables(expr)

Join the tables the updated values read (UPDATE ... FROM or a multi-table UPDATE on MySQL, as SQLAlchemy renders it).

Parameters:

Name Type Description Default
expr Any

statement to join

required

Returns:

Type Description
Any

joined statement

Source code in ormar/queryset/write_statements.py
Python
131
132
133
134
135
136
137
138
139
140
141
142
143
def join_read_tables(self, expr: Any) -> Any:
    """
    Join the tables the updated values read (``UPDATE ... FROM`` or a
    multi-table ``UPDATE`` on MySQL, as SQLAlchemy renders it).

    :param expr: statement to join
    :type expr: Any
    :return: joined statement
    :rtype: Any
    """
    for conditions in self.join_conditions.values():
        expr = expr.where(*conditions)
    return expr

key_params(primary_key, key) staticmethod

Parameters:

Name Type Description Default
primary_key PrimaryKey

primary key of the model

required
key Any

primary key value of the row

required

Returns:

Type Description
dict

parameters binding the key (see row_template)

Source code in ormar/queryset/write_statements.py
Python
179
180
181
182
183
184
185
186
187
188
189
@staticmethod
def key_params(primary_key: "PrimaryKey", key: Any) -> dict:
    """
    :param primary_key: primary key of the model
    :type primary_key: PrimaryKey
    :param key: primary key value of the row
    :type key: Any
    :return: parameters binding the key (see ``row_template``)
    :rtype: dict
    """
    return primary_key.bind_params(value=key)

make(**kwargs) classmethod

Parameters:

Name Type Description Default
kwargs Any

arguments of the statement

{}

Returns:

Type Description
Any

built statement, a builder of cached_statement

Source code in ormar/queryset/write_statements.py
Python
81
82
83
84
85
86
87
88
89
@classmethod
def make(cls, **kwargs: Any) -> Any:
    """
    :param kwargs: arguments of the statement
    :type kwargs: Any
    :return: built statement, a builder of ``cached_statement``
    :rtype: Any
    """
    return cls(**kwargs).build()

read_values()

Return the column assignments of the updated values, with expressions in place of the binds of the expression values, and collect the join conditions of the related tables those expressions read.

Returns:

Type Description
dict

bind or expression per column

Source code in ormar/queryset/write_statements.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def read_values(self) -> dict:
    """
    Return the column assignments of the updated values, with expressions
    in place of the binds of the expression values, and collect the join
    conditions of the related tables those expressions read.

    :return: bind or expression per column
    :rtype: dict
    """
    names = tuple(sorted(self.values))
    assignments = value_binds(table=self.table, names=names)
    for index, name in enumerate(names):
        if isinstance(self.values[name], Expression):
            columns = expression_columns(node=self.values[name], model=self.model)
            assignments[self.table.c[name]] = expression_clause(
                node=self.values[name], columns=columns, slot=f"ormar_v{index}"
            )
            for column in columns.values():
                self.join_conditions.update(
                    forward_join_conditions(
                        model=self.model, path=column.related_parts
                    )
                )
    return assignments

restrict(expr)

Restrict the statement to one row by primary key without a queryset, else to the rows the queryset selects in all(): by the primary keys it selects (see QuerySet.matched_rows_clause) when a filter reads a related model, by the filter and exclude clauses otherwise.

Parameters:

Name Type Description Default
expr Any

statement to restrict

required

Returns:

Type Description
Any

restricted statement

Source code in ormar/queryset/write_statements.py
Python
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 restrict(self, expr: Any) -> Any:
    """
    Restrict the statement to one row by primary key without a queryset,
    else to the rows the queryset selects in ``all()``: by the primary
    keys it selects (see ``QuerySet.matched_rows_clause``) when a filter
    reads a related model, by the filter and exclude clauses otherwise.

    :param expr: statement to restrict
    :type expr: Any
    :return: restricted statement
    :rtype: Any
    """
    queryset = self.queryset
    if queryset is None:
        slots = self.primary_key.bind_slots()
        return expr.where(self.primary_key.where_clause(slots=slots))
    if queryset._filters_read_related():
        return expr.where(queryset.matched_rows_clause(binder=self.binder))
    expr = FilterQuery(
        filter_clauses=queryset.filter_clauses, binder=self.binder
    ).apply(expr=expr)
    return FilterQuery(
        filter_clauses=queryset.exclude_clauses, exclude=True, binder=self.binder
    ).apply(expr=expr)

target() abstractmethod

Returns:

Type Description
Any

statement before its rows are restricted

Source code in ormar/queryset/write_statements.py
Python
124
125
126
127
128
129
@abc.abstractmethod
def target(self) -> Any:
    """
    :return: statement before its rows are restricted
    :rtype: Any
    """

forward_join_conditions(model, path)

Return the join conditions of the tables an update expression reads from, by table alias, following a path of foreign keys from model::

Text Only
1
2
forward_join_conditions(model=Track, path=["album"])
# -> {"t1b26c7": [t1b26c7_albums.id == tracks.album]}

Every table is aliased like in selects, so the conditions join the aliased columns the expression reads.

Parameters:

Name Type Description Default
model type[Model]

updated model

required
path list[str]

relation names leading to the read model

required

Returns:

Type Description
dict[str, list]

join conditions by table alias

Raises:

Type Description
QueryDefinitionError

if the path follows a reverse, many to many or through relation, which can match many rows

Source code in ormar/queryset/write_statements.py
Python
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def forward_join_conditions(model: type["Model"], path: list[str]) -> dict[str, list]:
    """
    Return the join conditions of the tables an update expression reads from,
    by table alias, following a path of foreign keys from ``model``::

        forward_join_conditions(model=Track, path=["album"])
        # -> {"t1b26c7": [t1b26c7_albums.id == tracks.album]}

    Every table is aliased like in selects, so the conditions join the aliased
    columns the expression reads.

    :param model: updated model
    :type model: type[Model]
    :param path: relation names leading to the read model
    :type path: list[str]
    :raises QueryDefinitionError: if the path follows a reverse, many to many or
        through relation, which can match many rows
    :return: join conditions by table alias
    :rtype: dict[str, list]
    """
    conditions: dict[str, list] = {}
    source_table: Any = model.ormar_config.table
    for index, relation in enumerate(path):
        field = cast("ForeignKeyField", model.ormar_config.model_fields[relation])
        if field.is_multi or field.virtual or field.is_through:
            raise QueryDefinitionError(
                f"update() expressions read related models only through foreign "
                f"keys, '{'__'.join(path)}' follows the reverse or many to many "
                f"relation '{relation}', which can match many rows."
            )
        alias = alias_for("__".join(path[: index + 1]))
        target_table = prefixed_table(alias=alias, table=field.to.ormar_config.table)
        conditions[alias] = [
            target_table.c[pair.target_column] == source_table.c[pair.source_column]
            for pair in field.link.pairs
        ]
        model, source_table = field.to, target_table
    return conditions

row_template(statement, model_cls, pk, values=None)

Return a write of the rows of a model by primary key, from the model's template cache, with the values to bind: Model.update(), Model.delete(), Model.load() and the read back of update_returning()::

Text Only
1
2
3
row_template(UpdateWrite, model_cls=Author, pk=1, values={"name": "b"})
# -> UPDATE authors SET name=:ormar_v0 WHERE authors.id = :ormar_pk
#    {"ormar_v0": "b", "ormar_pk": 1}

One statement is cached per class and, for an update, set of columns.

Parameters:

Name Type Description Default
statement type[WriteStatement]

statement class

required
model_cls type[Model]

written model

required
pk Any

primary key of the row (keys of the rows for RowsLockWrite)

required
values Optional[Mapping[str, Any]]

updated values by column name, for an update

None

Returns:

Type Description
StatementTemplate

statement and values to bind

Source code in ormar/queryset/write_statements.py
Python
354
355
356
357
358
359
360
361
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
389
390
391
392
393
394
395
396
397
def row_template(
    statement: type[WriteStatement],
    model_cls: type["Model"],
    pk: Any,
    values: Optional[Mapping[str, Any]] = None,
) -> StatementTemplate:
    """
    Return a write of the rows of a model by primary key, from the model's
    template cache, with the values to bind: ``Model.update()``,
    ``Model.delete()``, ``Model.load()`` and the read back of
    ``update_returning()``::

        row_template(UpdateWrite, model_cls=Author, pk=1, values={"name": "b"})
        # -> UPDATE authors SET name=:ormar_v0 WHERE authors.id = :ormar_pk
        #    {"ormar_v0": "b", "ormar_pk": 1}

    One statement is cached per class and, for an update, set of columns.

    :param statement: statement class
    :type statement: type[WriteStatement]
    :param model_cls: written model
    :type model_cls: type[Model]
    :param pk: primary key of the row (keys of the rows for ``RowsLockWrite``)
    :type pk: Any
    :param values: updated values by column name, for an update
    :type values: Optional[Mapping[str, Any]]
    :return: statement and values to bind
    :rtype: StatementTemplate
    """
    params = statement.key_params(primary_key=model_cls.ormar_config.pk, key=pk)
    if values is None:
        key: tuple = (statement.row_key,)
    else:
        names = tuple(sorted(values))
        key = (statement.row_key, names)
        params.update(value_params(names=names, values=values))
    cached = cached_statement(
        model_cls=model_cls,
        key=key,
        builder=statement.make,
        model=model_cls,
        values=values,
    )
    return StatementTemplate(statement=cached, params=params)