Skip to content

QuerySet class

edgy.QuerySet

QuerySet(model_class=None, *, database=None, filter_clauses=_empty_set, select_related=_empty_set, prefetch_related=_empty_set, limit_count=None, limit=None, limit_offset=None, offset=None, batch_size=None, order_by=_empty_set, group_by=_empty_set, distinct_on=None, distinct=None, only_fields=None, only=_empty_set, defer_fields=None, defer=_empty_set, embed_parent=None, using_schema=Undefined, table=None, exclude_secrets=False, extra_select=None, reference_select=None)

Bases: BaseQuerySet

QuerySet object used for query retrieving. Public interface

Source code in edgy/core/db/querysets/base.py
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
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
def __init__(
    self,
    model_class: type[BaseModelType] | None = None,
    *,
    database: Database | None = None,
    filter_clauses: Iterable[Any] = _empty_set,
    select_related: Iterable[str] = _empty_set,
    prefetch_related: Iterable[Prefetch] = _empty_set,
    limit_count: int | None = None,
    limit: int | None = None,
    limit_offset: int | None = None,
    offset: int | None = None,
    batch_size: int | None = None,
    order_by: Iterable[str] = _empty_set,
    group_by: Iterable[str] = _empty_set,
    distinct_on: None | Literal[True] | Iterable[str] = None,
    distinct: None | Literal[True] | Iterable[str] = None,
    only_fields: Iterable[str] | None = None,
    only: Iterable[str] = _empty_set,
    defer_fields: Sequence[str] | None = None,
    defer: Iterable[str] = _empty_set,
    embed_parent: tuple[str, str | str] | None = None,
    using_schema: str | None | Any = Undefined,
    table: sqlalchemy.Table | None = None,
    exclude_secrets: bool = False,
    extra_select: Iterable[sqlalchemy.ClauseElement] | None = None,
    reference_select: reference_select_type | None = None,
) -> None:
    # Making sure for queries we use the main class and not the proxy
    # And enable the parent
    if model_class.__is_proxy_model__:
        model_class = model_class.__parent__

    super().__init__(model_class=model_class)
    self.filter_clauses: list[Any] = list(filter_clauses)
    self.or_clauses: list[Any] = []
    self._aliases: dict[str, sqlalchemy.Alias] = {}
    if limit_count is not None:
        warnings.warn(
            "`limit_count` is deprecated use `limit`", DeprecationWarning, stacklevel=2
        )
        limit = limit_count
    self.limit_count = limit
    if limit_offset is not None:
        warnings.warn(
            "`limit_offset` is deprecated use `limit`", DeprecationWarning, stacklevel=2
        )
        offset = limit_offset
    self._offset = offset
    # Have the user passed select related values copied
    select_related = set(select_related)
    # Have the **real** path values
    self._select_related: set[str] = set()
    # computed only, replacable. Have the **real** path values
    self._select_related_weak: set[str] = set()
    if select_related:
        self._update_select_related(select_related)
    self._prefetch_related = list(prefetch_related)
    self._batch_size = batch_size
    self._order_by: tuple[str, ...] = tuple(order_by)
    self._group_by: tuple[str, ...] = tuple(group_by)
    if distinct_on is not None:
        warnings.warn(
            "`distinct_on` is deprecated use `distinct`", DeprecationWarning, stacklevel=2
        )
        distinct = distinct_on

    if distinct is True:
        distinct = _empty_set
    self.distinct_on = list(distinct) if distinct is not None else None
    if only_fields is not None:
        warnings.warn(
            "`only_fields` is deprecated use `only`", DeprecationWarning, stacklevel=2
        )
        only = only_fields
    self._only = set(only)
    if defer_fields is not None:
        warnings.warn(
            "`defer_fields` is deprecated use `defer`", DeprecationWarning, stacklevel=2
        )
        defer = defer_fields
    self._defer = set(defer)
    self.embed_parent = embed_parent
    # private attribute which manipulates the prefix of filters, order_by, select_related
    # set by relations
    self.embed_parent_filters: tuple[str, str | str] | None = None
    self.using_schema = using_schema
    self._extra_select = list(extra_select) if extra_select is not None else []
    self._reference_select = (
        reference_select.copy() if isinstance(reference_select, dict) else {}
    )
    self._exclude_secrets = exclude_secrets
    # cache should not be cloned
    self._cache = QueryModelResultCache(attrs=self.model_class.pkcolumns)
    # is empty
    self._clear_cache(keep_result_cache=False)
    # this is not cleared, because the expression is immutable
    self._cached_select_related_expression: (
        tuple[Any, dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]]] | None
    ) = None
    # initialize
    self.active_schema = self.get_schema()

    # Making sure the queryset always starts without any schema associated unless specified

    if table is not None:
        self.table = table
    if database is not None:
        self.database = database

model_class instance-attribute

model_class = model_class

The model class associated with this QuerySet.

_table class-attribute instance-attribute

_table = None

_database class-attribute instance-attribute

_database = None

database instance-attribute

database = database

table instance-attribute

table = table

pkcolumns property

pkcolumns

Returns a sequence of primary key column names for the model class associated with this queryset.

This property directly delegates to the pkcolumns property of the model_class, providing access to the underlying database column names that constitute the primary key.

RETURNS DESCRIPTION
Sequence[str]

Sequence[str]: A sequence (e.g., list or tuple) of strings, where each string is the name of a primary key column in the database.

filter_clauses instance-attribute

filter_clauses = list(filter_clauses)

or_clauses instance-attribute

or_clauses = []

_aliases instance-attribute

_aliases = {}

limit_count instance-attribute

limit_count = limit

_offset instance-attribute

_offset = offset
_select_related = set()
_select_related_weak = set()
_prefetch_related = list(prefetch_related)

_batch_size instance-attribute

_batch_size = batch_size

_order_by instance-attribute

_order_by = tuple(order_by)

_group_by instance-attribute

_group_by = tuple(group_by)

distinct_on instance-attribute

distinct_on = list(distinct) if distinct is not None else None

_only instance-attribute

_only = set(only)

_defer instance-attribute

_defer = set(defer)

embed_parent instance-attribute

embed_parent = embed_parent

embed_parent_filters instance-attribute

embed_parent_filters = None

using_schema instance-attribute

using_schema = using_schema

_extra_select instance-attribute

_extra_select = list(extra_select) if extra_select is not None else []

_reference_select instance-attribute

_reference_select = copy() if isinstance(reference_select, dict) else {}

_exclude_secrets instance-attribute

_exclude_secrets = exclude_secrets

_cache instance-attribute

_cache = QueryModelResultCache(attrs=pkcolumns)
_cached_select_related_expression = None

active_schema instance-attribute

active_schema = get_schema()

_has_dynamic_clauses cached property

_has_dynamic_clauses

Indicates if the queryset has any dynamic (callable) filter or OR clauses.

_current_row property

_current_row

Get async safe the current row when in _execute_iterate

sql cached property

sql

Get SQL select query as string with inserted blanks. For debugging only!

build_where_clause async

build_where_clause(_=None, tables_and_models=None)

Builds a SQLAlchemy WHERE clause from the queryset's filter and OR clauses.

PARAMETER DESCRIPTION
_

Ignored. Used for compatibility with clauses_mod.parse_clause_arg signature.

TYPE: Any DEFAULT: None

tables_and_models

A dictionary mapping table aliases to (table, model) tuples. If None, it's built internally. Defaults to None.

TYPE: tables_and_models_type | None DEFAULT: None

RETURNS DESCRIPTION
Any

The combined SQLAlchemy WHERE clause.

TYPE: Any

Source code in edgy/core/db/querysets/base.py
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
360
async def build_where_clause(
    self, _: Any = None, tables_and_models: tables_and_models_type | None = None
) -> Any:
    """
    Builds a SQLAlchemy WHERE clause from the queryset's filter and OR clauses.

    Args:
        _ (Any): Ignored. Used for compatibility with `clauses_mod.parse_clause_arg` signature.
        tables_and_models (tables_and_models_type | None): A dictionary mapping table aliases to
                                                           (table, model) tuples. If None, it's
                                                           built internally. Defaults to None.

    Returns:
        Any: The combined SQLAlchemy WHERE clause.
    """
    joins: Any | None = None
    if tables_and_models is None:
        joins, tables_and_models = self._build_tables_join_from_relationship()
    # ignored args for passing build_where_clause in filter_clauses
    where_clauses: list[Any] = []
    if self.or_clauses:
        where_clauses.append(
            await clauses_mod.parse_clause_arg(
                clauses_mod.or_(*self.or_clauses, no_select_related=True),
                self,
                tables_and_models,
            )
        )

    if self.filter_clauses:
        # we AND by default
        where_clauses.extend(
            await clauses_mod.parse_clause_args(self.filter_clauses, self, tables_and_models)
        )
    # for nicer unpacking
    if joins is None or len(tables_and_models) == 1:
        return clauses_mod.and_sqlalchemy(*where_clauses)
    expression = sqlalchemy.sql.select(
        *(
            getattr(tables_and_models[""][0].c, col)
            for col in tables_and_models[""][1].pkcolumns
        ),
    ).set_label_style(sqlalchemy.LABEL_STYLE_NONE)
    idtuple = sqlalchemy.tuple_(
        *(
            getattr(tables_and_models[""][0].c, col)
            for col in tables_and_models[""][1].pkcolumns
        )
    )
    expression = expression.select_from(joins)
    return idtuple.in_(
        expression.where(
            *where_clauses,
        )
    )

using

using(_positional=_sentinel, *, database=Undefined, schema=Undefined)

Enables and switches the database schema and/or database connection for the queryset.

This method creates a new QuerySet instance that operates within the specified database and/or schema context. It's designed to support multi-tenancy by allowing dynamic selection of the database or schema without modifying the original QuerySet.

PARAMETER DESCRIPTION
_positional

Deprecated positional argument for schema. This argument is maintained for backward compatibility but its use is discouraged. It will be treated as the schema argument.

TYPE: Any DEFAULT: _sentinel

database

Specifies the database to use. - str: Name of an extra database connection registered in the model's registry. - Database: A Database instance to use directly. - None: Uses the default database from the model's registry. - Undefined (default): Retains the current database of the queryset.

TYPE: str | Database | None DEFAULT: Undefined

schema

Specifies the database schema to use. - str: The schema name to activate. - False: Unsets the schema, reverting to the active default schema for the model. - None: Uses no specific schema. - Undefined (default): Retains the current schema of the queryset.

TYPE: str | None | Literal[False] DEFAULT: Undefined

RETURNS DESCRIPTION
QuerySet

A new QuerySet instance configured with the specified database and/or schema settings. This new instance allows chaining operations within the new context.

TYPE: QuerySet

WARNS DESCRIPTION
DeprecationWarning

If positional arguments are passed to this method for _positional. Users should explicitly use schema= keyword argument instead.

Source code in edgy/core/db/querysets/mixins.py
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
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
def using(
    self,
    _positional: Any = _sentinel,
    *,
    database: str | Any | None | Database = Undefined,
    schema: str | Any | None | Literal[False] = Undefined,
) -> QuerySet:
    """
    Enables and switches the database schema and/or database connection for
    the queryset.

    This method creates a new QuerySet instance that operates within the
    specified database and/or schema context. It's designed to support
    multi-tenancy by allowing dynamic selection of the database or schema
    without modifying the original QuerySet.

    Args:
        _positional (Any): Deprecated positional argument for `schema`. This
                           argument is maintained for backward compatibility but
                           its use is discouraged. It will be treated as the
                           `schema` argument.
        database (str | Database | None): Specifies the database to use.
          - `str`: Name of an extra database connection registered in the model's registry.
          - `Database`: A Database instance to use directly.
          - `None`: Uses the default database from the model's registry.
          - `Undefined` (default): Retains the current database of the queryset.
        schema (str | None | Literal[False]): Specifies the database schema to use.
          - `str`: The schema name to activate.
          - `False`: Unsets the schema, reverting to the active default schema for the model.
          - `None`: Uses no specific schema.
          - `Undefined` (default): Retains the current schema of the queryset.

    Returns:
        QuerySet: A new QuerySet instance configured with the specified database
                  and/or schema settings. This new instance allows chaining
                  operations within the new context.

    Warnings:
        DeprecationWarning: If positional arguments are passed to this method for
                            `_positional`. Users should explicitly use `schema=`
                            keyword argument instead.
    """
    # Check for deprecated positional argument usage.
    if _positional is not _sentinel:
        warnings.warn(
            "Passing positional arguments to using is deprecated. Use schema= instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        schema = _positional
        # If schema was not explicitly set as Undefined (meaning it was passed
        # positionally) and is still Undefined, set it to False to unset the schema.
        if schema is Undefined:
            schema = False

    # Create a clone of the current queryset to avoid modifying the original.
    queryset = cast("QuerySet", self._clone())

    # Process the 'database' argument.
    if database is not Undefined:
        if isinstance(database, Database):
            connection: Database = database
        elif database is None:
            # Use the default database from the model's registry.
            connection = self.model_class.meta.registry.database
        else:
            # Assert that the database name exists in the extra connections.
            assert database is None or database in self.model_class.meta.registry.extra, (
                f"`{database}` is not in the connections extra of the model"
                f"`{self.model_class.__name__}` registry"
            )
            # Retrieve the database from extra connections.
            connection = self.model_class.meta.registry.extra[database]
        # Assign the determined connection to the new queryset's database.
        queryset.database = connection

    # Process the 'schema' argument.
    if schema is not Undefined:
        # If schema is False, set using_schema to Undefined to unset it;
        # otherwise, use the provided schema.
        queryset.using_schema = schema if schema is not False else Undefined
        # Get the new schema based on the current queryset's configuration.
        new_schema = queryset.get_schema()
        # If the new schema is different from the active schema, update and
        # invalidate table cache.
        if new_schema != queryset.active_schema:
            queryset.active_schema = new_schema
            queryset.table = None  # Force regeneration of the table with the new schema.

    return queryset
prefetch_related(*prefetch)

Performs a reverse lookup for foreign keys and other relationships, populating results onto the main model instances.

This method is distinct from select_related in that select_related performs a SQL JOIN to fetch related data in the same query, whereas prefetch_related executes separate queries for each relationship and then joins the results in Python. This is particularly useful for many-to-many relationships or reverse foreign key lookups, or when preloading related objects for a large set of parent objects.

PARAMETER DESCRIPTION
*prefetch

One or more Prefetch objects, each defining a relationship to prefetch, including the related_name and the to_attr where results will be stored. An optional custom QuerySet can also be provided within the Prefetch object.

TYPE: Prefetch DEFAULT: ()

RETURNS DESCRIPTION
QuerySet

A new QuerySet instance with the specified prefetch relationships configured. This new QuerySet can then be further filtered, ordered, or executed.

TYPE: QuerySet

RAISES DESCRIPTION
QuerySetError

If any argument passed to prefetch is not an instance of the Prefetch class.

Source code in edgy/core/db/querysets/prefetch.py
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
def prefetch_related(self, *prefetch: Prefetch) -> QuerySet:
    """
    Performs a reverse lookup for foreign keys and other relationships,
    populating results onto the main model instances.

    This method is distinct from `select_related` in that `select_related`
    performs a SQL JOIN to fetch related data in the same query, whereas
    `prefetch_related` executes separate queries for each relationship
    and then joins the results in Python. This is particularly useful for
    many-to-many relationships or reverse foreign key lookups, or when
    preloading related objects for a large set of parent objects.

    Args:
        *prefetch (Prefetch): One or more `Prefetch` objects, each defining
                               a relationship to prefetch, including the
                               `related_name` and the `to_attr` where results
                               will be stored. An optional custom `QuerySet`
                               can also be provided within the `Prefetch` object.

    Returns:
        QuerySet: A new `QuerySet` instance with the specified prefetch
                  relationships configured. This new QuerySet can then be
                  further filtered, ordered, or executed.

    Raises:
        QuerySetError: If any argument passed to `prefetch` is not an
                       instance of the `Prefetch` class.
    """
    queryset: QuerySet = self._clone()

    # Validate that all provided arguments are instances of Prefetch.
    if any(not isinstance(value, Prefetch) for value in prefetch):
        raise QuerySetError("The prefetch_related must have Prefetch type objects only.")

    # Append the new prefetch objects to the queryset's internal list.
    queryset._prefetch_related = [*self._prefetch_related, *prefetch]
    return queryset

using_with_db

using_with_db(connection_name, schema=Undefined)

Switches the database connection and optionally the schema for the queryset.

This method is deprecated in favor of the more flexible using method, which accepts both database and schema as keyword arguments.

PARAMETER DESCRIPTION
connection_name

The name of the database connection (registered in the model's registry's extra connections) to switch to.

TYPE: str

schema

The schema name to use. - str: The schema name to activate. - False: Unsets the schema, reverting to the active default schema. - None: Uses no specific schema. - Undefined (default): Retains the current schema.

TYPE: str | None | Literal[False] DEFAULT: Undefined

RETURNS DESCRIPTION
QuerySet

A new QuerySet instance configured with the specified database connection and schema.

TYPE: QuerySet

WARNS DESCRIPTION
DeprecationWarning

This method is deprecated. Users should migrate to using(database=..., schema=...) for future compatibility.

Source code in edgy/core/db/querysets/mixins.py
249
250
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
def using_with_db(
    self, connection_name: str, schema: str | Any | None | Literal[False] = Undefined
) -> QuerySet:
    """
    Switches the database connection and optionally the schema for the queryset.

    This method is deprecated in favor of the more flexible `using` method, which
    accepts both `database` and `schema` as keyword arguments.

    Args:
        connection_name (str): The name of the database connection (registered
                               in the model's registry's `extra` connections)
                               to switch to.
        schema (str | None | Literal[False]): The schema name to use.
          - `str`: The schema name to activate.
          - `False`: Unsets the schema, reverting to the active default schema.
          - `None`: Uses no specific schema.
          - `Undefined` (default): Retains the current schema.

    Returns:
        QuerySet: A new QuerySet instance configured with the specified database
                  connection and schema.

    Warnings:
        DeprecationWarning: This method is deprecated. Users should migrate to
                            `using(database=..., schema=...)` for future
                            compatibility.
    """
    warnings.warn(
        "'using_with_db' is deprecated in favor of 'using' with schema, database arguments.",
        DeprecationWarning,
        stacklevel=2,
    )
    # Delegate to the `using` method with the appropriate keyword arguments.
    return self.using(database=connection_name, schema=schema)

_clone

_clone()

Return a copy of the current QuerySet that's ready for another operation.

Source code in edgy/core/db/querysets/base.py
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
def _clone(self) -> QuerySet:
    """
    Return a copy of the current QuerySet that's ready for another
    operation.
    """
    queryset = self.__class__(
        self.model_class,
        database=getattr(self, "_database", None),
        filter_clauses=self.filter_clauses,
        prefetch_related=self._prefetch_related,
        limit=self.limit_count,
        offset=self._offset,
        batch_size=self._batch_size,
        order_by=self._order_by,
        group_by=self._group_by,
        distinct=self.distinct_on,
        only=self._only,
        defer=self._defer,
        embed_parent=self.embed_parent,
        using_schema=self.using_schema,
        table=getattr(self, "_table", None),
        exclude_secrets=self._exclude_secrets,
        reference_select=self._reference_select,
        extra_select=self._extra_select,
    )
    queryset.or_clauses.extend(self.or_clauses)
    queryset.embed_parent_filters = self.embed_parent_filters
    # copy but don't trigger update select related
    queryset._select_related.update(self._select_related)
    queryset._select_related_weak.update(self._select_related_weak)
    queryset._cached_select_related_expression = self._cached_select_related_expression
    return cast("QuerySet", queryset)

_clear_cache

_clear_cache(*, keep_result_cache=False, keep_cached_selected=False)

Clears the internal cache of the queryset.

PARAMETER DESCRIPTION
keep_result_cache

If True, the result cache (for fetched models) is preserved. Defaults to False.

TYPE: bool DEFAULT: False

keep_cached_selected

If True, the cached select expression and tables are preserved. Defaults to False.

TYPE: bool DEFAULT: False

Source code in edgy/core/db/querysets/base.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def _clear_cache(
    self, *, keep_result_cache: bool = False, keep_cached_selected: bool = False
) -> None:
    """
    Clears the internal cache of the queryset.

    Args:
        keep_result_cache (bool): If True, the result cache (for fetched models) is preserved.
                                  Defaults to False.
        keep_cached_selected (bool): If True, the cached select expression and tables are preserved.
                                     Defaults to False.
    """
    if not keep_result_cache:
        self._cache.clear()
    if not keep_cached_selected:
        self._cached_select_with_tables: (
            tuple[Any, dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]]] | None
        ) = None
    self._cache_count: int | None = None
    self._cache_first: tuple[BaseModelType, Any] | None = None
    self._cache_last: tuple[BaseModelType, Any] | None = None
    # fetch all is in cache
    self._cache_fetch_all: bool = False

_build_order_by_iterable

_build_order_by_iterable(order_by, tables_and_models)

Builds the iterator for a order by like expression.

Source code in edgy/core/db/querysets/base.py
300
301
302
303
304
def _build_order_by_iterable(
    self, order_by: Iterable[str], tables_and_models: tables_and_models_type
) -> Iterable:
    """Builds the iterator for a order by like expression."""
    return (self._prepare_order_by(entry, tables_and_models) for entry in order_by)

_build_select_distinct

_build_select_distinct(distinct_on, expression, tables_and_models)

Filters selects only specific fields. Leave empty to use simple distinct

Source code in edgy/core/db/querysets/base.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def _build_select_distinct(
    self,
    distinct_on: Sequence[str] | None,
    expression: Any,
    tables_and_models: tables_and_models_type,
) -> Any:
    """Filters selects only specific fields. Leave empty to use simple distinct"""
    # using with columns is not supported by all databases
    if distinct_on:
        return expression.distinct(
            *(
                self._prepare_distinct(distinct_el, tables_and_models)
                for distinct_el in distinct_on
            )
        )
    else:
        return expression.distinct()

_join_table_helper classmethod

_join_table_helper(join_clause, current_transition, *, transitions, tables_and_models)

Recursively builds SQLAlchemy join clauses based on a transition map.

PARAMETER DESCRIPTION
join_clause

The current join clause to which new joins are added.

TYPE: Any

current_transition

The key for the current transition.

TYPE: tuple[str, str, str]

transitions

A dictionary mapping transition keys to (join_condition, parent_transition_key, table_alias) tuples.

TYPE: dict[tuple[str, str, str], tuple[Any, tuple[str, str, str] | None, str]]

tables_and_models

A dictionary mapping table aliases to (table, model) tuples.

TYPE: dict[str, tuple[Table, type[BaseModelType]]]

RETURNS DESCRIPTION
Any

The updated join clause.

TYPE: Any

Source code in edgy/core/db/querysets/base.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
@classmethod
def _join_table_helper(
    cls,
    join_clause: Any,
    current_transition: tuple[str, str, str],
    *,
    transitions: dict[tuple[str, str, str], tuple[Any, tuple[str, str, str] | None, str]],
    tables_and_models: dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]],
) -> Any:
    """
    Recursively builds SQLAlchemy join clauses based on a transition map.

    Args:
        join_clause (Any): The current join clause to which new joins are added.
        current_transition (tuple[str, str, str]): The key for the current transition.
        transitions (dict[tuple[str, str, str], tuple[Any, tuple[str, str, str] | None, str]]):
            A dictionary mapping transition keys to (join_condition, parent_transition_key, table_alias) tuples.
        tables_and_models (dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]]):
            A dictionary mapping table aliases to (table, model) tuples.

    Returns:
        Any: The updated join clause.
    """
    if current_transition not in transitions:
        return join_clause
    transition_value = transitions.pop(current_transition)

    if transition_value[1] is not None:
        join_clause = cls._join_table_helper(
            join_clause,
            transition_value[1],
            transitions=transitions,
            tables_and_models=tables_and_models,
        )

    return sqlalchemy.sql.join(
        join_clause,
        tables_and_models[transition_value[2]][0],
        transition_value[0],
        isouter=True,
    )

_build_tables_join_from_relationship

_build_tables_join_from_relationship()

Builds the table relationships and joins for select_related operations.

This method constructs a graph of table joins based on the _select_related paths. It handles many-to-many relationships and aliasing of tables to ensure uniqueness. The result is cached for performance.

RETURNS DESCRIPTION
tuple[Any, tables_and_models_type]

tuple[Any, tables_and_models_type]: A tuple containing: - The SQLAlchemy join expression. - A dictionary mapping table aliases (prefixes) to (table, model) tuples.

RAISES DESCRIPTION
QuerySetError

If a selected field does not exist or is not a RelationshipField, or if a selected model is on another database.

Source code in edgy/core/db/querysets/base.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def _build_tables_join_from_relationship(
    self,
) -> tuple[Any, tables_and_models_type]:
    """
    Builds the table relationships and joins for `select_related` operations.

    This method constructs a graph of table joins based on the `_select_related` paths.
    It handles many-to-many relationships and aliasing of tables to ensure uniqueness.
    The result is cached for performance.

    Returns:
        tuple[Any, tables_and_models_type]: A tuple containing:
            - The SQLAlchemy join expression.
            - A dictionary mapping table aliases (prefixes) to (table, model) tuples.

    Raises:
        QuerySetError: If a selected field does not exist or is not a RelationshipField,
                       or if a selected model is on another database.
    """

    # How does this work?
    # First we build a transitions tree (maintable is root) by providing optionally a dependency.
    # Resolving a dependency automatically let's us resolve the tree.
    # At last we iter through the transisitions and build their dependencies first
    # We pop out the transitions so a path is not taken 2 times

    # Why left outer join? It is possible and legal for a relation to not exist we check that already in filtering.

    if self._cached_select_related_expression is None:
        maintable = self.table
        select_from = maintable
        tables_and_models: tables_and_models_type = {"": (select_from, self.model_class)}
        _select_tables_and_models: tables_and_models_type = {
            "": (select_from, self.model_class)
        }
        transitions: dict[
            tuple[str, str, str], tuple[Any, tuple[str, str, str] | None, str]
        ] = {}

        # Select related
        for select_path in self._select_related.union(self._select_related_weak):
            # For m2m relationships
            model_class = self.model_class
            former_table = maintable
            former_transition = None
            prefix: str = ""
            # prefix which expands m2m fields
            _select_prefix: str = ""
            # False (default): add prefix regularly.
            # True: skip adding existing prefix to tables_and_models and skip adding the next field to the
            #       public prefix.
            # string: add a custom prefix instead of the calculated one and skip adding the next field to the
            #         public prefix.

            injected_prefix: bool | str = False
            model_database: Database | None = self.database
            while select_path:
                field_name = select_path.split("__", 1)[0]
                try:
                    field = model_class.meta.fields[field_name]
                except KeyError:
                    raise QuerySetError(
                        detail=f'Selected field "{field_name}" does not exist on {model_class}.'
                    ) from None
                field = model_class.meta.fields[field_name]
                if isinstance(field, RelationshipField):
                    model_class, reverse_part, select_path = field.traverse_field(select_path)
                else:
                    raise QuerySetError(
                        detail=f'Selected field "{field_name}" is not a RelationshipField on {model_class}.'
                    )
                if isinstance(field, BaseForeignKey):
                    foreign_key: BaseForeignKey = field
                    reverse = False
                else:
                    foreign_key = model_class.meta.fields[reverse_part]
                    reverse = True
                if foreign_key.is_cross_db(model_database):
                    raise QuerySetError(
                        detail=f'Selected model "{field_name}" is on another database.'
                    )
                # now use the one of the model_class itself
                model_database = None
                if injected_prefix:
                    injected_prefix = False
                else:
                    prefix = f"{prefix}__{field_name}" if prefix else f"{field_name}"
                _select_prefix = (
                    f"{_select_prefix}__{field_name}" if _select_prefix else f"{field_name}"
                )
                if foreign_key.is_m2m and foreign_key.embed_through != "":
                    # we need to inject the through model for the select
                    model_class = foreign_key.through
                    if foreign_key.embed_through is False:
                        injected_prefix = True
                    else:
                        injected_prefix = f"{prefix}__{foreign_key.embed_through}"
                    if reverse:
                        select_path = f"{foreign_key.from_foreign_key}__{select_path}"
                    else:
                        select_path = f"{foreign_key.to_foreign_key}__{select_path}"
                    # if select_path is empty
                    select_path = select_path.removesuffix("__")
                    if reverse:
                        foreign_key = model_class.meta.fields[foreign_key.to_foreign_key]
                    else:
                        foreign_key = model_class.meta.fields[foreign_key.from_foreign_key]
                        reverse = True
                if _select_prefix in _select_tables_and_models:
                    # use prexisting prefix
                    table: Any = _select_tables_and_models[_select_prefix][0]
                else:
                    table = model_class.table_schema(self.active_schema)
                    table = table.alias(hash_tablekey(tablekey=table.key, prefix=prefix))

                # it is guranteed that former_table is either root and has a key or is an unique join node
                # except there would be a hash collision which is very unlikely
                transition_key = (get_table_key_or_name(former_table), table.name, field_name)
                if transition_key in transitions:
                    # can not provide new informations
                    former_table = table
                    former_transition = transition_key
                    continue
                and_clause = clauses_mod.and_sqlalchemy(
                    *self._select_from_relationship_clause_generator(
                        foreign_key, table, reverse, former_table
                    )
                )
                transitions[transition_key] = (
                    and_clause,
                    former_transition,
                    _select_prefix,
                )
                if injected_prefix is False:
                    tables_and_models[prefix] = table, model_class
                elif injected_prefix is not True:
                    # we inject a string
                    tables_and_models[injected_prefix] = table, model_class

                # prefix used for select_related
                _select_tables_and_models[_select_prefix] = table, model_class
                former_table = table
                former_transition = transition_key

        while transitions:
            select_from = self._join_table_helper(
                select_from,
                next(iter(transitions.keys())),
                transitions=transitions,
                tables_and_models=_select_tables_and_models,
            )
        self._cached_select_related_expression = (
            select_from,
            tables_and_models,
        )
    return self._cached_select_related_expression

_select_from_relationship_clause_generator staticmethod

_select_from_relationship_clause_generator(foreign_key, table, reverse, former_table)

Generates SQLAlchemy WHERE clauses for joining tables based on a foreign key relationship.

PARAMETER DESCRIPTION
foreign_key

The foreign key field defining the relationship.

TYPE: BaseForeignKey

table

The SQLAlchemy table for the related model.

TYPE: Any

reverse

True if the relationship is being traversed in reverse (from related to source model).

TYPE: bool

former_table

The SQLAlchemy table for the source model.

TYPE: Any

YIELDS DESCRIPTION
Any

SQLAlchemy binary expressions for the join condition.

TYPE:: Any

Source code in edgy/core/db/querysets/base.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
@staticmethod
def _select_from_relationship_clause_generator(
    foreign_key: BaseForeignKey,
    table: Any,
    reverse: bool,
    former_table: Any,
) -> Any:
    """
    Generates SQLAlchemy WHERE clauses for joining tables based on a foreign key relationship.

    Args:
        foreign_key (BaseForeignKey): The foreign key field defining the relationship.
        table (Any): The SQLAlchemy table for the related model.
        reverse (bool): True if the relationship is being traversed in reverse (from related to source model).
        former_table (Any): The SQLAlchemy table for the source model.

    Yields:
        Any: SQLAlchemy binary expressions for the join condition.
    """
    column_names = foreign_key.get_column_names(foreign_key.name)
    assert column_names, f"foreign key without column names detected: {foreign_key.name}"
    for col in column_names:
        colname = foreign_key.from_fk_field_name(foreign_key.name, col) if reverse else col
        if reverse:
            yield getattr(former_table.c, colname) == getattr(table.c, col)
        else:
            yield getattr(former_table.c, colname) == getattr(
                table.c, foreign_key.from_fk_field_name(foreign_key.name, col)
            )

_validate_only_and_defer

_validate_only_and_defer()

Validates that .only() and .defer() are not used simultaneously.

RAISES DESCRIPTION
QuerySetError

If both .only() and .defer() are applied to the queryset.

Source code in edgy/core/db/querysets/base.py
609
610
611
612
613
614
615
616
617
def _validate_only_and_defer(self) -> None:
    """
    Validates that .only() and .defer() are not used simultaneously.

    Raises:
        QuerySetError: If both .only() and .defer() are applied to the queryset.
    """
    if self._only and self._defer:
        raise QuerySetError("You cannot use .only() and .defer() at the same time.")

_as_select_with_tables async

_as_select_with_tables()

Builds the SQLAlchemy SELECT expression along with the mapping of tables and models, based on the queryset's parameters and filters.

This method handles only, defer, exclude_secrets, extra_select, and reference_select clauses, and incorporates select_related joins.

RETURNS DESCRIPTION
tuple[Any, tables_and_models_type]

tuple[Any, tables_and_models_type]: A tuple containing: - The constructed SQLAlchemy SELECT expression. - A dictionary mapping table aliases to (table, model) tuples.

RAISES DESCRIPTION
AssertionError

If no columns or extra_select elements are specified for the query.

Source code in edgy/core/db/querysets/base.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
async def _as_select_with_tables(
    self,
) -> tuple[Any, tables_and_models_type]:
    """
    Builds the SQLAlchemy SELECT expression along with the mapping of tables and models,
    based on the queryset's parameters and filters.

    This method handles `only`, `defer`, `exclude_secrets`, `extra_select`, and
    `reference_select` clauses, and incorporates `select_related` joins.

    Returns:
        tuple[Any, tables_and_models_type]: A tuple containing:
            - The constructed SQLAlchemy SELECT expression.
            - A dictionary mapping table aliases to (table, model) tuples.

    Raises:
        AssertionError: If no columns or extra_select elements are specified for the query.
    """
    self._validate_only_and_defer()
    joins, tables_and_models = self._build_tables_join_from_relationship()
    columns_and_extra: list[Any] = [*self._extra_select]
    for prefix, (table, model_class) in tables_and_models.items():
        if not prefix:
            for column_key, column in table.columns.items():
                # e.g. reflection has not always a field
                field_name = model_class.meta.columns_to_field.get(column_key, column_key)
                if self._only and field_name not in self._only:
                    continue
                if self._defer and field_name in self._defer:
                    continue
                if (
                    self._exclude_secrets
                    and field_name in model_class.meta.fields
                    and model_class.meta.fields[field_name].secret
                ):
                    continue
                # add without alias
                columns_and_extra.append(column)

        else:
            for column_key, column in table.columns.items():
                # e.g. reflection has not always a field
                field_name = model_class.meta.columns_to_field.get(column_key, column_key)
                if (
                    self._only
                    and prefix not in self._only
                    and f"{prefix}__{field_name}" not in self._only
                ):
                    continue
                if self._defer and (
                    prefix in self._defer or f"{prefix}__{field_name}" in self._defer
                ):
                    continue
                if (
                    self._exclude_secrets
                    and field_name in model_class.meta.fields
                    and model_class.meta.fields[field_name].secret
                ):
                    continue
                # alias has name not a key. The name is fully descriptive
                columns_and_extra.append(column.label(f"{table.name}_{column_key}"))
    assert columns_and_extra, "no columns or extra_select specified"
    # all columns are aliased already
    expression = sqlalchemy.sql.select(*columns_and_extra).set_label_style(
        sqlalchemy.LABEL_STYLE_NONE
    )
    expression = expression.select_from(joins)
    expression = expression.where(await self.build_where_clause(self, tables_and_models))

    if self._order_by:
        expression = expression.order_by(
            *self._build_order_by_iterable(self._order_by, tables_and_models)
        )

    if self._group_by:
        expression = expression.group_by(
            *self._build_order_by_iterable(self._group_by, tables_and_models)
        )

    if self.limit_count:
        expression = expression.limit(self.limit_count)

    if self._offset:
        expression = expression.offset(self._offset)

    if self.distinct_on is not None:
        expression = self._build_select_distinct(
            self.distinct_on, expression=expression, tables_and_models=tables_and_models
        )
    return expression, tables_and_models

as_select_with_tables async

as_select_with_tables()

Builds the query select based on the given parameters and filters, including the mapping of tables and models involved in the query. The result is cached.

RETURNS DESCRIPTION
tuple[Any, tables_and_models_type]

tuple[Any, tables_and_models_type]: A tuple containing the SQLAlchemy select expression and the tables and models dictionary.

Source code in edgy/core/db/querysets/base.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
async def as_select_with_tables(
    self,
) -> tuple[Any, tables_and_models_type]:
    """
    Builds the query select based on the given parameters and filters, including
    the mapping of tables and models involved in the query. The result is cached.

    Returns:
        tuple[Any, tables_and_models_type]: A tuple containing the SQLAlchemy select
                                             expression and the tables and models dictionary.
    """
    if self._cached_select_with_tables is None:
        self._cached_select_with_tables = await self._as_select_with_tables()
    return self._cached_select_with_tables

as_select async

as_select()

Builds and returns only the SQLAlchemy select expression for the current queryset.

RETURNS DESCRIPTION
Any

The SQLAlchemy select expression.

TYPE: Any

Source code in edgy/core/db/querysets/base.py
725
726
727
728
729
730
731
732
733
734
async def as_select(
    self,
) -> Any:
    """
    Builds and returns only the SQLAlchemy select expression for the current queryset.

    Returns:
        Any: The SQLAlchemy select expression.
    """
    return (await self.as_select_with_tables())[0]

_kwargs_to_clauses

_kwargs_to_clauses(kwargs)

Converts keyword arguments into a list of callable filter clauses and a set of select_related paths.

This function handles relationship traversal and cross-database foreign keys, generating appropriate SQLAlchemy expressions or wrapped async functions.

PARAMETER DESCRIPTION
kwargs

The keyword arguments representing the filter conditions.

TYPE: Any

RETURNS DESCRIPTION
tuple[list[Any], set[str]]

tuple[list[Any], set[str]]: A tuple containing: - A list of SQLAlchemy binary expressions or async callable wrappers. - A set of relationship paths for select_related.

Source code in edgy/core/db/querysets/base.py
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def _kwargs_to_clauses(
    self,
    kwargs: Any,
) -> tuple[list[Any], set[str]]:
    """
    Converts keyword arguments into a list of callable filter clauses and a set of
    `select_related` paths.

    This function handles relationship traversal and cross-database foreign keys,
    generating appropriate SQLAlchemy expressions or wrapped async functions.

    Args:
        kwargs (Any): The keyword arguments representing the filter conditions.

    Returns:
        tuple[list[Any], set[str]]: A tuple containing:
            - A list of SQLAlchemy binary expressions or async callable wrappers.
            - A set of relationship paths for `select_related`.
    """
    clauses = []
    select_related: set[str] = set()
    cleaned_kwargs = clauses_mod.clean_query_kwargs(
        self.model_class, kwargs, self.embed_parent_filters, model_database=self.database
    )

    for key, value in cleaned_kwargs.items():
        model_class, field_name, op, related_str, _, cross_db_remainder = crawl_relationship(
            self.model_class, key
        )
        if related_str:
            select_related.add(related_str)
        field = model_class.meta.fields.get(field_name, clauses_mod.generic_field)
        if cross_db_remainder:
            assert field is not clauses_mod.generic_field
            fk_field = cast(BaseForeignKey, field)
            sub_query = (
                fk_field.target.query.filter(**{cross_db_remainder: value})
                .only(*fk_field.related_columns.keys())
                .values_list(fields=fk_field.related_columns.keys())
            )

            # bind local vars
            async def wrapper(
                queryset: QuerySet,
                tables_and_models: tables_and_models_type,
                *,
                _field: BaseFieldType = field,
                _sub_query: QuerySet = sub_query,
                _prefix: str = related_str,
            ) -> Any:
                table = tables_and_models[_prefix][0]
                fk_tuple = sqlalchemy.tuple_(
                    *(getattr(table.columns, colname) for colname in _field.get_column_names())
                )
                return fk_tuple.in_(await _sub_query)

            clauses.append(wrapper)
        else:
            assert not isinstance(value, BaseModelType), (
                f"should be parsed in clean: {key}: {value}"
            )

            async def wrapper(
                queryset: QuerySet,
                tables_and_models: tables_and_models_type,
                *,
                _field: BaseFieldType = field,
                _value: Any = value,
                _op: str | None = op,
                _prefix: str = related_str,
                # generic field has no field name
                _field_name: str = field_name,
            ) -> Any:
                _value = await clauses_mod.parse_clause_arg(
                    _value, queryset, tables_and_models
                )
                table = tables_and_models[_prefix][0]
                return _field.operator_to_clause(_field_name, _op, table, _value)

            wrapper._edgy_force_callable_queryset_filter = True
            clauses.append(wrapper)

    return clauses, select_related

_prepare_order_by

_prepare_order_by(order_by, tables_and_models)

Prepares an order_by or group_by clause from a string.

PARAMETER DESCRIPTION
order_by

The field name for ordering, optionally prefixed with '-' for descending.

TYPE: str

RETURNS DESCRIPTION
Any

The SQLAlchemy column expression for ordering and the select_path.

TYPE: Any

Source code in edgy/core/db/querysets/base.py
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def _prepare_order_by(self, order_by: str, tables_and_models: tables_and_models_type) -> Any:
    """
    Prepares an order_by or group_by clause from a string.

    Args:
        order_by (str): The field name for ordering, optionally prefixed with '-' for descending.

    Returns:
        Any: The SQLAlchemy column expression for ordering and the select_path.
    """
    reverse = order_by.startswith("-")
    order_by = order_by.lstrip("-")
    crawl_result = clauses_mod.clean_path_to_crawl_result(
        self.model_class,
        path=order_by,
        embed_parent=self.embed_parent_filters,
        model_database=self.database,
    )
    order_col = tables_and_models[crawl_result.forward_path][0].columns[
        crawl_result.field_name
    ]
    return order_col.desc() if reverse else order_col
_update_select_related_weak(fields, *, clear)

Update _select_related_weak

PARAMETER DESCRIPTION
fields

The field names of order_by, group_by, ...

TYPE: Iterable[str]

Source code in edgy/core/db/querysets/base.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def _update_select_related_weak(self, fields: Iterable[str], *, clear: bool) -> bool:
    """
    Update _select_related_weak

    Args:
        fields (Iterable[str]): The field names of order_by, group_by, ...

    """
    related: set[str] = set()
    for field_name in fields:
        # handle order by values by stripping -
        field_name = field_name.lstrip("-")
        related_element = clauses_mod.clean_path_to_crawl_result(
            self.model_class,
            path=field_name,
            embed_parent=self.embed_parent_filters,
            model_database=self.database,
        ).forward_path
        if related_element:
            related.add(related_element)
    if related and not self._select_related.union(self._select_related_weak).issuperset(
        related
    ):
        self._cached_select_related_expression = None
        if clear:
            self._select_related_weak.clear()
        self._select_related_weak.update(related)
        return True
    return False
_update_select_related(pathes)

Update _select_related

PARAMETER DESCRIPTION
pathes

The related pathes.

TYPE: Iterable[str]

Source code in edgy/core/db/querysets/base.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def _update_select_related(self, pathes: Iterable[str]) -> None:
    """
    Update _select_related

    Args:
        pathes (Iterable[str]): The related pathes.

    """
    related: set[str] = set()
    for path in pathes:
        # handle order by values by stripping -
        path = path.lstrip("-")
        crawl_result = clauses_mod.clean_path_to_crawl_result(
            self.model_class,
            # actually not a field_path
            path=path,
            embed_parent=self.embed_parent_filters,
            model_database=self.database,
        )
        # actually not a field name
        related_element = (
            crawl_result.field_name
            if not crawl_result.forward_path
            else f"{crawl_result.forward_path}__{crawl_result.field_name}"
        )
        if crawl_result.cross_db_remainder:
            raise QuerySetError(
                detail=f'Selected path "{related_element}" is on another database.'
            )
        if related_element:
            related.add(related_element)
    if related and not self._select_related.issuperset(related):
        self._cached_select_related_expression = None
        self._select_related.update(related)

_prepare_distinct

_prepare_distinct(distinct_on, tables_and_models)

Prepares a field for use in a distinct-on clause.

PARAMETER DESCRIPTION
distinct_on

The field name for distinctness.

TYPE: str

RETURNS DESCRIPTION
Column

sqlalchemy.Column: The SQLAlchemy column object.

Source code in edgy/core/db/querysets/base.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def _prepare_distinct(
    self, distinct_on: str, tables_and_models: tables_and_models_type
) -> sqlalchemy.Column:
    """
    Prepares a field for use in a distinct-on clause.

    Args:
        distinct_on (str): The field name for distinctness.

    Returns:
        sqlalchemy.Column: The SQLAlchemy column object.
    """
    crawl_result = clauses_mod.clean_path_to_crawl_result(
        self.model_class,
        path=distinct_on,
        embed_parent=self.embed_parent_filters,
        model_database=self.database,
    )
    return tables_and_models[crawl_result.forward_path][0].columns[crawl_result.field_name]

_embed_parent_in_result async

_embed_parent_in_result(result)

Embeds a parent model into the result if embed_parent is configured.

This allows accessing related models directly from the main model instance as defined by the embed_parent setting.

PARAMETER DESCRIPTION
result

The model instance or an awaitable that resolves to a model instance.

TYPE: EdgyModel | Awaitable[EdgyModel]

RETURNS DESCRIPTION
tuple[EdgyModel, Any]

tuple[EdgyModel, Any]: A tuple where the first element is the original result and the second is the potentially embedded result.

Source code in edgy/core/db/querysets/base.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
async def _embed_parent_in_result(
    self, result: EdgyModel | Awaitable[EdgyModel]
) -> tuple[EdgyModel, Any]:
    """
    Embeds a parent model into the result if `embed_parent` is configured.

    This allows accessing related models directly from the main model instance
    as defined by the `embed_parent` setting.

    Args:
        result (EdgyModel | Awaitable[EdgyModel]): The model instance or an awaitable
                                                    that resolves to a model instance.

    Returns:
        tuple[EdgyModel, Any]: A tuple where the first element is the original result
                               and the second is the potentially embedded result.
    """
    if isawaitable(result):
        result = await result
    if not self.embed_parent:
        return result, result
    token = MODEL_GETATTR_BEHAVIOR.set("coro")
    try:
        new_result: Any = result
        for part in self.embed_parent[0].split("__"):
            new_result = getattr(new_result, part)
            if isawaitable(new_result):
                new_result = await new_result
    finally:
        MODEL_GETATTR_BEHAVIOR.reset(token)
    if self.embed_parent[1]:
        setattr(new_result, self.embed_parent[1], result)
    return result, new_result

_get_or_cache_row async

_get_or_cache_row(row, tables_and_models, extra_attr='', raw=False)

Retrieves or caches a single model instance from a SQLAlchemy row.

This method converts a SQLAlchemy row into a model instance, handles only_fields, defer_fields, prefetch_related, and embed_parent configurations, and optionally sets extra attributes on the queryset for caching.

PARAMETER DESCRIPTION
row

The SQLAlchemy row object.

TYPE: Any

tables_and_models

A dictionary mapping table aliases to (table, model) tuples.

TYPE: dict[str, tuple[Table, type[BaseModelType]]]

extra_attr

Comma-separated string of attributes to set on the queryset with the result. Defaults to "".

TYPE: str DEFAULT: ''

raw

If True, returns the raw model instance without embed_parent transformation. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple[EdgyModel, EdgyEmbedTarget]

tuple[EdgyModel, EdgyEmbedTarget]: A tuple containing the raw model instance and the potentially embedded target instance.

Source code in edgy/core/db/querysets/base.py
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
async def _get_or_cache_row(
    self,
    row: Any,
    tables_and_models: dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]],
    extra_attr: str = "",
    raw: bool = False,
) -> tuple[EdgyModel, EdgyEmbedTarget]:
    """
    Retrieves or caches a single model instance from a SQLAlchemy row.

    This method converts a SQLAlchemy row into a model instance, handles
    `only_fields`, `defer_fields`, `prefetch_related`, and `embed_parent` configurations,
    and optionally sets extra attributes on the queryset for caching.

    Args:
        row (Any): The SQLAlchemy row object.
        tables_and_models (dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]]):
            A dictionary mapping table aliases to (table, model) tuples.
        extra_attr (str): Comma-separated string of attributes to set on the queryset with the result.
                          Defaults to "".
        raw (bool): If True, returns the raw model instance without `embed_parent` transformation.
                    Defaults to False.

    Returns:
        tuple[EdgyModel, EdgyEmbedTarget]: A tuple containing the raw model instance
                                           and the potentially embedded target instance.
    """
    is_defer_fields = bool(self._defer)
    result_tuple: tuple[EdgyModel, EdgyEmbedTarget] = (
        await self._cache.aget_or_cache_many(
            self.model_class,
            [row],
            cache_fn=lambda _row: self.model_class.from_sqla_row(
                _row,
                tables_and_models=tables_and_models,
                select_related=self._select_related,
                only_fields=self._only,
                is_defer_fields=is_defer_fields,
                prefetch_related=self._prefetch_related,
                exclude_secrets=self._exclude_secrets,
                using_schema=self.active_schema,
                database=self.database,
                reference_select=self._reference_select,
            ),
            transform_fn=self._embed_parent_in_result,
        )
    )[0]
    if extra_attr:
        for attr in extra_attr.split(","):
            setattr(self, attr, result_tuple)
    return result_tuple

get_schema

get_schema()

Retrieves the active database schema for the queryset.

The schema can be explicitly set via using_schema, obtained from the current context variable, or derived from the model's metadata.

RETURNS DESCRIPTION
str | None

str | None: The active schema name, or None if not applicable.

Source code in edgy/core/db/querysets/base.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def get_schema(self) -> str | None:
    """
    Retrieves the active database schema for the queryset.

    The schema can be explicitly set via `using_schema`, obtained from the
    current context variable, or derived from the model's metadata.

    Returns:
        str | None: The active schema name, or None if not applicable.
    """
    # Differs from get_schema global
    schema = self.using_schema
    if schema is Undefined:
        schema = get_schema()
    if schema is None:
        schema = self.model_class.get_db_schema()
    return schema

_handle_batch async

_handle_batch(batch, tables_and_models, queryset, new_cache)

Handles a batch of SQLAlchemy rows, converting them to model instances and performing prefetching operations.

PARAMETER DESCRIPTION
batch

A sequence of SQLAlchemy row objects.

TYPE: Sequence[Row]

tables_and_models

A dictionary mapping table aliases to (table, model) tuples.

TYPE: dict[str, tuple[Table, type[BaseModelType]]]

queryset

The current queryset (used for its configuration).

TYPE: BaseQuerySet

new_cache

The cache to store the new batch results.

TYPE: QueryModelResultCache

RETURNS DESCRIPTION
Sequence[tuple[BaseModelType, BaseModelType]]

Sequence[tuple[BaseModelType, BaseModelType]]: A sequence of tuples, each containing the raw model instance and the embedded target.

RAISES DESCRIPTION
NotImplementedError

If prefetching from another database is attempted.

QuerySetError

If creating a reverse path for prefetching is not possible.

Source code in edgy/core/db/querysets/base.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
async def _handle_batch(
    self,
    batch: Sequence[sqlalchemy.Row],
    tables_and_models: dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]],
    queryset: BaseQuerySet,
    new_cache: QueryModelResultCache,
) -> Sequence[tuple[BaseModelType, BaseModelType]]:
    """
    Handles a batch of SQLAlchemy rows, converting them to model instances and
    performing prefetching operations.

    Args:
        batch (Sequence[sqlalchemy.Row]): A sequence of SQLAlchemy row objects.
        tables_and_models (dict[str, tuple[sqlalchemy.Table, type[BaseModelType]]]):
            A dictionary mapping table aliases to (table, model) tuples.
        queryset (BaseQuerySet): The current queryset (used for its configuration).
        new_cache (QueryModelResultCache): The cache to store the new batch results.

    Returns:
        Sequence[tuple[BaseModelType, BaseModelType]]: A sequence of tuples, each containing
                                                        the raw model instance and the embedded target.

    Raises:
        NotImplementedError: If prefetching from another database is attempted.
        QuerySetError: If creating a reverse path for prefetching is not possible.
    """
    is_defer_fields = bool(queryset._defer)
    del queryset
    _prefetch_related: list[Prefetch] = []

    for prefetch in self._prefetch_related:
        check_prefetch_collision(self.model_class, prefetch)  # type: ignore

        crawl_result = crawl_relationship(
            self.model_class, prefetch.related_name, traverse_last=True
        )
        if crawl_result.cross_db_remainder:
            raise NotImplementedError(
                "Cannot prefetch from other db yet. Maybe in future this feature will be added."
            )
        if crawl_result.reverse_path is False:
            QuerySetError(
                detail=("Creating a reverse path is not possible, unidirectional fields used.")
            )
        prefetch_queryset: QuerySet | None = prefetch.queryset

        clauses = [
            {
                f"{crawl_result.reverse_path}__{pkcol}": row._mapping[pkcol]
                for pkcol in self.model_class.pkcolumns
            }
            for row in batch
        ]
        if prefetch_queryset is None:
            prefetch_queryset = crawl_result.model_class.query.local_or(*clauses)
        else:
            # ensure local or
            prefetch_queryset = prefetch_queryset.local_or(*clauses)

        if prefetch_queryset.model_class is self.model_class:
            # queryset is of this model
            prefetch_queryset = prefetch_queryset.select_related(prefetch.related_name)
            prefetch_queryset.embed_parent = (prefetch.related_name, "")
        else:
            # queryset is of the target model
            prefetch_queryset = prefetch_queryset.select_related(
                cast(str, crawl_result.reverse_path)
            )
        new_prefetch = Prefetch(
            related_name=prefetch.related_name,
            to_attr=prefetch.to_attr,
            queryset=prefetch_queryset,
        )
        new_prefetch._bake_prefix = f"{hash_tablekey(tablekey=tables_and_models[''][0].key, prefix=cast(str, crawl_result.reverse_path))}_"
        new_prefetch._is_finished = True
        _prefetch_related.append(new_prefetch)

    return cast(
        Sequence[tuple[BaseModelType, BaseModelType]],
        await new_cache.aget_or_cache_many(
            self.model_class,
            batch,
            cache_fn=lambda row: self.model_class.from_sqla_row(
                row,
                tables_and_models=tables_and_models,
                select_related=self._select_related,
                only_fields=self._only,
                is_defer_fields=is_defer_fields,
                prefetch_related=_prefetch_related,
                exclude_secrets=self._exclude_secrets,
                using_schema=self.active_schema,
                database=self.database,
                reference_select=self._reference_select,
            ),
            transform_fn=self._embed_parent_in_result,
            old_cache=self._cache,
        ),
    )

_execute_iterate async

_execute_iterate(fetch_all_at_once=False)

Executes the query and yields model instances during iteration.

This method supports fetching all results at once or in batches, and handles prefetching and embedding parent models. It also includes warnings for force_rollback usage with iterations due to potential deadlocks.

PARAMETER DESCRIPTION
fetch_all_at_once

If True, all results are fetched before yielding. Defaults to False.

TYPE: bool DEFAULT: False

YIELDS DESCRIPTION
BaseModelType

A model instance for each row.

TYPE:: AsyncIterator[BaseModelType]

WARNS DESCRIPTION
UserWarning

If using queryset iterations with Database-level force_rollback enabled.

Source code in edgy/core/db/querysets/base.py
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
async def _execute_iterate(
    self, fetch_all_at_once: bool = False
) -> AsyncIterator[BaseModelType]:
    """
    Executes the query and yields model instances during iteration.

    This method supports fetching all results at once or in batches, and handles
    prefetching and embedding parent models. It also includes warnings for
    `force_rollback` usage with iterations due to potential deadlocks.

    Args:
        fetch_all_at_once (bool): If True, all results are fetched before yielding.
                                  Defaults to False.

    Yields:
        BaseModelType: A model instance for each row.

    Warns:
        UserWarning: If using queryset iterations with `Database`-level `force_rollback` enabled.
    """
    if self._cache_fetch_all:
        for result in cast(
            Sequence[tuple[BaseModelType, BaseModelType]],
            self._cache.get_category(self.model_class).values(),
        ):
            yield result[1]
        return
    queryset = self
    if queryset.embed_parent:
        # activates distinct, not distinct on
        queryset = queryset.distinct()  # type: ignore

    expression, tables_and_models = await queryset.as_select_with_tables()

    if not fetch_all_at_once and bool(queryset.database.force_rollback):
        # force_rollback on db = we have only one connection
        # so every operation must be atomic
        # Note: force_rollback is a bit magic, it evaluates its truthiness to the actual value
        warnings.warn(
            'Using queryset iterations with "Database"-level force_rollback set is risky. '
            "Deadlocks can occur because only one connection is used.",
            UserWarning,
            stacklevel=3,
        )
        if queryset._prefetch_related:
            # prefetching will certainly deadlock, let's mitigate
            fetch_all_at_once = True

    counter = 0
    last_element: tuple[BaseModelType, BaseModelType] | None = None
    check_db_connection(queryset.database, stacklevel=4)
    current_row: list[sqlalchemy.Row | None] = [None]
    token = _current_row_holder.set(current_row)
    try:
        if fetch_all_at_once:
            # we need a new cache to have the right order
            new_cache = QueryModelResultCache(self._cache.attrs)
            async with queryset.database as database:
                batch = cast(Sequence[sqlalchemy.Row], await database.fetch_all(expression))
            for row_num, result in enumerate(
                await self._handle_batch(
                    batch, tables_and_models, queryset, new_cache=new_cache
                )
            ):
                if counter == 0:
                    self._cache_first = result
                last_element = result
                counter += 1
                current_row[0] = batch[row_num]
                yield result[1]
            self._cache_fetch_all = True
            self._cache = new_cache
        else:
            batch_num: int = 0
            new_cache = QueryModelResultCache(self._cache.attrs)
            async with queryset.database as database:
                async for batch in cast(
                    AsyncGenerator[Sequence[sqlalchemy.Row], None],
                    database.batched_iterate(expression, batch_size=self._batch_size),
                ):
                    # clear only result cache
                    new_cache.clear()
                    self._cache_fetch_all = False
                    for row_num, result in enumerate(
                        await self._handle_batch(batch, tables_and_models, queryset, new_cache)
                    ):
                        if counter == 0:
                            self._cache_first = result
                        last_element = result
                        counter += 1
                        current_row[0] = batch[row_num]
                        yield result[1]
                    batch_num += 1
            if batch_num <= 1:
                self._cache = new_cache
                self._cache_fetch_all = True

    finally:
        _current_row_holder.reset(token)
    # better update them once
    self._cache_count = counter
    self._cache_last = last_element

_execute_all async

_execute_all()

Executes the query and returns all results as a list of model instances.

Source code in edgy/core/db/querysets/base.py
1242
1243
1244
1245
1246
async def _execute_all(self) -> list[EdgyModel]:
    """
    Executes the query and returns all results as a list of model instances.
    """
    return [result async for result in self._execute_iterate(fetch_all_at_once=True)]

_filter_or_exclude

_filter_or_exclude(kwargs, clauses, exclude=False, or_=False, allow_global_or=True)

Filters or excludes a given clause for a specific QuerySet.

This is an internal method used by filter, exclude, or_, and and_ to construct the query's WHERE clauses. It handles various clause types including dictionaries (kwargs), callable filters, and other QuerySet objects.

PARAMETER DESCRIPTION
kwargs

Additional keyword arguments to filter by.

TYPE: Any

clauses

A sequence of filter clauses.

TYPE: Sequence[...]

exclude

If True, the clauses are inverted for exclusion. Defaults to False.

TYPE: bool DEFAULT: False

or_

If True, the clauses are combined with OR. Defaults to False.

TYPE: bool DEFAULT: False

allow_global_or

If True, and only one OR clause is provided, it can be added to the queryset's global OR clauses. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
QuerySet

A new QuerySet with the applied filters/exclusions.

TYPE: QuerySet

RAISES DESCRIPTION
AssertionError

If exclude is True and or_ is also True when adding to global OR.

AssertionError

If a QuerySet object is used as a clause with a different model class.

Source code in edgy/core/db/querysets/base.py
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
def _filter_or_exclude(
    self,
    kwargs: Any,
    clauses: Sequence[
        sqlalchemy.sql.expression.BinaryExpression
        | Callable[
            [QuerySetType],
            sqlalchemy.sql.expression.BinaryExpression
            | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
        ]
        | dict[str, Any]
        | QuerySet
    ],
    exclude: bool = False,
    or_: bool = False,
    allow_global_or: bool = True,
) -> QuerySet:
    """
    Filters or excludes a given clause for a specific QuerySet.

    This is an internal method used by `filter`, `exclude`, `or_`, and `and_` to
    construct the query's WHERE clauses. It handles various clause types including
    dictionaries (kwargs), callable filters, and other QuerySet objects.

    Args:
        kwargs (Any): Additional keyword arguments to filter by.
        clauses (Sequence[...]): A sequence of filter clauses.
        exclude (bool): If True, the clauses are inverted for exclusion. Defaults to False.
        or_ (bool): If True, the clauses are combined with OR. Defaults to False.
        allow_global_or (bool): If True, and only one OR clause is provided, it can be
                                added to the queryset's global OR clauses. Defaults to True.

    Returns:
        QuerySet: A new QuerySet with the applied filters/exclusions.

    Raises:
        AssertionError: If `exclude` is True and `or_` is also True when adding to global OR.
        AssertionError: If a `QuerySet` object is used as a clause with a different model class.
    """
    queryset: QuerySet = self._clone()
    if kwargs:
        clauses = [*clauses, kwargs]
    converted_clauses: Sequence[
        sqlalchemy.sql.expression.BinaryExpression
        | Callable[
            [QuerySetType],
            sqlalchemy.sql.expression.BinaryExpression
            | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
        ]
    ] = []
    for raw_clause in clauses:
        if isinstance(raw_clause, dict):
            extracted_clauses, related = queryset._kwargs_to_clauses(kwargs=raw_clause)
            if not queryset._select_related.issuperset(related):
                queryset._select_related.update(related)
                queryset._cached_select_related_expression = None
            if or_ and extracted_clauses:
                wrapper_and = clauses_mod.and_(*extracted_clauses, no_select_related=True)
                if allow_global_or and len(clauses) == 1:
                    # add to global or
                    assert not exclude
                    queryset.or_clauses.append(wrapper_and)
                    return queryset
                converted_clauses.append(wrapper_and)
            else:
                converted_clauses.extend(extracted_clauses)
        elif isinstance(raw_clause, QuerySet):
            assert raw_clause.model_class is queryset.model_class, (
                f"QuerySet arg has wrong model_class {raw_clause.model_class}"
            )
            converted_clauses.append(raw_clause.build_where_clause)
            if not queryset._select_related.issuperset(raw_clause._select_related):
                queryset._select_related.update(raw_clause._select_related)
                queryset._cached_select_related_expression = None
        else:
            converted_clauses.append(raw_clause)
            if hasattr(raw_clause, "_edgy_calculate_select_related"):
                select_related_calculated = raw_clause._edgy_calculate_select_related(queryset)
                if not queryset._select_related.issuperset(select_related_calculated):
                    queryset._select_related.update(select_related_calculated)
                    queryset._cached_select_related_expression = None
    if not converted_clauses:
        return queryset

    if exclude:
        op = clauses_mod.and_ if not or_ else clauses_mod.or_

        queryset.filter_clauses.append(
            clauses_mod.not_(
                op(*converted_clauses, no_select_related=True), no_select_related=True
            )
        )
    elif or_:
        queryset.filter_clauses.append(
            clauses_mod.or_(*converted_clauses, no_select_related=True)
        )
    else:
        # default to and
        queryset.filter_clauses.extend(converted_clauses)
    return queryset

_model_based_delete async

_model_based_delete(remove_referenced_call)

Performs a model-based deletion, iterating through models and calling their raw_delete method.

This method is used when __require_model_based_deletion__ or post_delete_fields are set on the model, ensuring hooks and related object handling are executed.

PARAMETER DESCRIPTION
remove_referenced_call

Specifies how to handle referenced objects during deletion.

TYPE: str | bool

RETURNS DESCRIPTION
int

The total number of records deleted.

TYPE: int

Source code in edgy/core/db/querysets/base.py
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
async def _model_based_delete(self, remove_referenced_call: str | bool) -> int:
    """
    Performs a model-based deletion, iterating through models and calling their `raw_delete` method.

    This method is used when `__require_model_based_deletion__` or `post_delete_fields` are set
    on the model, ensuring hooks and related object handling are executed.

    Args:
        remove_referenced_call (str | bool): Specifies how to handle referenced objects during deletion.

    Returns:
        int: The total number of records deleted.
    """
    queryset = self.limit(self._batch_size) if not self._cache_fetch_all else self
    # we set embed_parent on the copy to None to get raw instances
    # embed_parent_filters is not affected
    queryset.embed_parent = None
    row_count = 0
    models = await queryset
    token = CURRENT_INSTANCE.set(cast("QuerySet", self))
    try:
        while models:
            for model in models:
                await model.raw_delete(
                    skip_post_delete_hooks=False, remove_referenced_call=remove_referenced_call
                )
                row_count += 1
            # clear cache and fetch new batch
            models = await queryset.all(True)
    finally:
        CURRENT_INSTANCE.reset(token)
    return row_count

raw_delete async

raw_delete(use_models=False, remove_referenced_call=False)

Executes a raw delete operation on the database.

This method can either perform a direct SQL DELETE statement or iterate through models and call their individual raw_delete methods based on use_models and model configurations.

PARAMETER DESCRIPTION
use_models

If True, deletion is performed by iterating and deleting individual model instances. Defaults to False.

TYPE: bool DEFAULT: False

remove_referenced_call

Specifies how to handle referenced objects during deletion.

TYPE: str | bool DEFAULT: False

RETURNS DESCRIPTION
int

The number of rows deleted.

TYPE: int

Source code in edgy/core/db/querysets/base.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
async def raw_delete(
    self, use_models: bool = False, remove_referenced_call: str | bool = False
) -> int:
    """
    Executes a raw delete operation on the database.

    This method can either perform a direct SQL DELETE statement or iterate
    through models and call their individual `raw_delete` methods based on
    `use_models` and model configurations.

    Args:
        use_models (bool): If True, deletion is performed by iterating and
                           deleting individual model instances. Defaults to False.
        remove_referenced_call (str | bool): Specifies how to handle referenced objects during deletion.

    Returns:
        int: The number of rows deleted.
    """
    if (
        self.model_class.__require_model_based_deletion__
        or self.model_class.meta.post_delete_fields
    ):
        use_models = True
    if use_models:
        row_count = await self._model_based_delete(
            remove_referenced_call=remove_referenced_call
        )
    else:
        expression = self.table.delete()
        expression = expression.where(await self.build_where_clause())

        check_db_connection(self.database)
        async with self.database as database:
            row_count = cast(int, await database.execute(expression))

    # clear cache before executing post_delete. Fresh results can be retrieved in signals
    self._clear_cache()

    return row_count

_get_raw async

_get_raw(**kwargs)

Returns a single record based on the given kwargs.

This is an internal method that fetches a single row from the database, handling caching and raising exceptions for no results or multiple results.

PARAMETER DESCRIPTION
**kwargs

Keyword arguments to filter the query.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
tuple[BaseModelType, Any]

tuple[BaseModelType, Any]: A tuple containing the raw model instance and the potentially embedded target instance.

RAISES DESCRIPTION
ObjectNotFound

If no object matches the given criteria.

MultipleObjectsReturned

If more than one object matches the criteria.

Source code in edgy/core/db/querysets/base.py
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
async def _get_raw(self, **kwargs: Any) -> tuple[BaseModelType, Any]:
    """
    Returns a single record based on the given kwargs.

    This is an internal method that fetches a single row from the database,
    handling caching and raising exceptions for no results or multiple results.

    Args:
        **kwargs (Any): Keyword arguments to filter the query.

    Returns:
        tuple[BaseModelType, Any]: A tuple containing the raw model instance and
                                   the potentially embedded target instance.

    Raises:
        ObjectNotFound: If no object matches the given criteria.
        MultipleObjectsReturned: If more than one object matches the criteria.
    """

    if kwargs:
        cached = cast(
            tuple[BaseModelType, Any] | None, self._cache.get(self.model_class, kwargs)
        )
        if cached is not None:
            return cached
        filter_query = cast("BaseQuerySet", self.filter(**kwargs))
        # connect parent query cache
        filter_query._cache = self._cache
        return await filter_query._get_raw()
    elif self._cache_count == 1:
        if self._cache_first is not None:
            return self._cache_first
        elif self._cache_last is not None:
            return self._cache_last

    expression, tables_and_models = await self.as_select_with_tables()
    check_db_connection(self.database, stacklevel=4)
    async with self.database as database:
        # we want no queryset copy, so use sqlalchemy limit(2)
        rows = await database.fetch_all(expression.limit(2))

    if not rows:
        self._cache_count = 0
        raise ObjectNotFound()
    if len(rows) > 1:
        raise MultipleObjectsReturned()
    self._cache_count = 1

    return await self._get_or_cache_row(rows[0], tables_and_models, "_cache_first,_cache_last")

__repr__

__repr__()
Source code in edgy/core/db/querysets/base.py
1472
1473
def __repr__(self) -> str:
    return f"QuerySet<{self.sql}>"

_sql_helper async

_sql_helper()

Helper method to compile the SQL query into a string.

Source code in edgy/core/db/querysets/base.py
1481
1482
1483
1484
1485
1486
1487
1488
async def _sql_helper(self) -> Any:
    """
    Helper method to compile the SQL query into a string.
    """
    async with self.database:
        return (await self.as_select()).compile(
            self.database.engine, compile_kwargs={"literal_binds": True}
        )

filter

filter(*clauses, **kwargs)

Filters the QuerySet by the given kwargs and clauses.

Source code in edgy/core/db/querysets/base.py
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
def filter(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any]
    | QuerySet,
    **kwargs: Any,
) -> QuerySet:
    """
    Filters the QuerySet by the given kwargs and clauses.
    """
    return self._filter_or_exclude(clauses=clauses, kwargs=kwargs)

all

all(clear_cache=False)

Returns a cloned query with empty cache. Optionally just clear the cache and return the same query.

Source code in edgy/core/db/querysets/base.py
1512
1513
1514
1515
1516
1517
1518
1519
def all(self, clear_cache: bool = False) -> QuerySet:
    """
    Returns a cloned query with empty cache. Optionally just clear the cache and return the same query.
    """
    if clear_cache:
        self._clear_cache(keep_cached_selected=not self._has_dynamic_clauses)
        return self
    return self._clone()

or_

or_(*clauses, **kwargs)

Filters the QuerySet by the OR operand.

Source code in edgy/core/db/querysets/base.py
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
def or_(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any]
    | QuerySet,
    **kwargs: Any,
) -> QuerySet:
    """
    Filters the QuerySet by the OR operand.
    """
    return self._filter_or_exclude(clauses=clauses, or_=True, kwargs=kwargs)

local_or

local_or(*clauses, **kwargs)

Filters the QuerySet by the OR operand.

Source code in edgy/core/db/querysets/base.py
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
def local_or(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any]
    | QuerySet,
    **kwargs: Any,
) -> QuerySet:
    """
    Filters the QuerySet by the OR operand.
    """
    return self._filter_or_exclude(
        clauses=clauses, or_=True, kwargs=kwargs, allow_global_or=False
    )

and_

and_(*clauses, **kwargs)

Filters the QuerySet by the AND operand. Alias of filter.

Source code in edgy/core/db/querysets/base.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def and_(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any],
    **kwargs: Any,
) -> QuerySet:
    """
    Filters the QuerySet by the AND operand. Alias of filter.
    """
    return self._filter_or_exclude(clauses=clauses, kwargs=kwargs)

not_

not_(*clauses, **kwargs)

Filters the QuerySet by the NOT operand. Alias of exclude.

Source code in edgy/core/db/querysets/base.py
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
def not_(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any]
    | QuerySet,
    **kwargs: Any,
) -> QuerySet:
    """
    Filters the QuerySet by the NOT operand. Alias of exclude.
    """
    return self.exclude(*clauses, **kwargs)

exclude

exclude(*clauses, **kwargs)

Exactly the same as the filter but for the exclude.

Source code in edgy/core/db/querysets/base.py
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
def exclude(
    self,
    *clauses: sqlalchemy.sql.expression.BinaryExpression
    | Callable[
        [QuerySetType],
        sqlalchemy.sql.expression.BinaryExpression
        | Awaitable[sqlalchemy.sql.expression.BinaryExpression],
    ]
    | dict[str, Any]
    | QuerySet,
    **kwargs: Any,
) -> QuerySet:
    """
    Exactly the same as the filter but for the exclude.
    """
    return self._filter_or_exclude(clauses=clauses, exclude=True, kwargs=kwargs)

exclude_secrets

exclude_secrets(exclude_secrets=True)

Excludes any field that contains the secret=True declared from being leaked.

Source code in edgy/core/db/querysets/base.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
def exclude_secrets(
    self,
    exclude_secrets: bool = True,
) -> QuerySet:
    """
    Excludes any field that contains the `secret=True` declared from being leaked.
    """
    queryset = self._clone()
    queryset._exclude_secrets = exclude_secrets
    return queryset

extra_select

extra_select(*extra)

Adds extra columns or expressions to the SELECT statement.

PARAMETER DESCRIPTION
*extra

Additional SQLAlchemy column clauses or expressions.

TYPE: ColumnClause DEFAULT: ()

RETURNS DESCRIPTION
QuerySetType

A new QuerySet with the extra select clauses.

TYPE: QuerySetType

Source code in edgy/core/db/querysets/base.py
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
def extra_select(
    self,
    *extra: sqlalchemy.ColumnClause,
) -> QuerySetType:
    """
    Adds extra columns or expressions to the SELECT statement.

    Args:
        *extra (sqlalchemy.ColumnClause): Additional SQLAlchemy column clauses or expressions.

    Returns:
        QuerySetType: A new QuerySet with the extra select clauses.
    """
    queryset = self._clone()
    queryset._extra_select.extend(extra)
    return queryset

reference_select

reference_select(references)

Adds references to the SELECT statement, used for specific model field handling.

PARAMETER DESCRIPTION
references

A dictionary defining reference selections.

TYPE: reference_select_type

RETURNS DESCRIPTION
QuerySetType

A new QuerySet with the added reference selections.

TYPE: QuerySetType

Source code in edgy/core/db/querysets/base.py
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
def reference_select(self, references: reference_select_type) -> QuerySetType:
    """
    Adds references to the SELECT statement, used for specific model field handling.

    Args:
        references (reference_select_type): A dictionary defining reference selections.

    Returns:
        QuerySetType: A new QuerySet with the added reference selections.
    """
    queryset = self._clone()
    queryset._reference_select.update(references)
    return queryset

batch_size

batch_size(batch_size=None)

Set batch/chunk size. Used for iterate

Source code in edgy/core/db/querysets/base.py
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
def batch_size(
    self,
    batch_size: int | None = None,
) -> QuerySet:
    """
    Set batch/chunk size. Used for iterate
    """
    queryset = self._clone()
    queryset._batch_size = batch_size
    return queryset

lookup

lookup(term)

Broader way of searching for a given term on CharField and TextField instances.

Source code in edgy/core/db/querysets/base.py
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
def lookup(self, term: Any) -> QuerySet:
    """
    Broader way of searching for a given term on CharField and TextField instances.
    """
    queryset: QuerySet = self._clone()
    if not term:
        return queryset

    filter_clauses = list(queryset.filter_clauses)
    value = f"%{term}%"

    search_fields = [
        name
        for name, field in queryset.model_class.meta.fields.items()
        if isinstance(field, CharField | TextField)
    ]
    search_clauses = [queryset.table.columns[name].ilike(value) for name in search_fields]

    if len(search_clauses) > 1:
        filter_clauses.append(sqlalchemy.sql.or_(*search_clauses))
    else:
        filter_clauses.extend(search_clauses)

    return queryset

order_by

order_by(*order_by)

Returns a QuerySet ordered by the given fields.

Source code in edgy/core/db/querysets/base.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
def order_by(self, *order_by: str) -> QuerySet:
    """
    Returns a QuerySet ordered by the given fields.
    """
    queryset: QuerySet = self._clone()
    queryset._order_by = order_by
    if queryset._update_select_related_weak(order_by, clear=True):
        queryset._update_select_related_weak(queryset._group_by, clear=False)
    return queryset

reverse

reverse()

Reverses the order of the QuerySet.

If no order_by is set, it defaults to ordering by primary key columns. It also attempts to reverse the cached results for immediate consistency.

Source code in edgy/core/db/querysets/base.py
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
def reverse(self) -> QuerySet:
    """
    Reverses the order of the QuerySet.

    If no `order_by` is set, it defaults to ordering by primary key columns.
    It also attempts to reverse the cached results for immediate consistency.
    """
    if not self._order_by:
        queryset = self.order_by(*self.model_class.pkcolumns)
    else:
        queryset = self._clone()
    queryset._order_by = tuple(
        el[1:] if el.startswith("-") else f"-{el}" for el in queryset._order_by
    )
    queryset._cache_last = self._cache_first
    queryset._cache_first = self._cache_last
    queryset._cache_count = self._cache_count
    if self._cache_fetch_all:
        # we may have embedded active
        cache_keys = []
        values = []
        for k, v in reversed(self._cache.get_category(self.model_class).items()):
            cache_keys.append(k)
            values.append(v)
        queryset._cache.update(self.model_class, values, cache_keys=cache_keys)
        queryset._cache_fetch_all = True
    return queryset

limit

limit(limit_count)

Returns a QuerySet limited by.

Source code in edgy/core/db/querysets/base.py
1723
1724
1725
1726
1727
1728
1729
def limit(self, limit_count: int) -> QuerySet:
    """
    Returns a QuerySet limited by.
    """
    queryset: QuerySet = self._clone()
    queryset.limit_count = limit_count
    return queryset

offset

offset(offset)

Returns a Queryset limited by the offset.

Source code in edgy/core/db/querysets/base.py
1731
1732
1733
1734
1735
1736
1737
def offset(self, offset: int) -> QuerySet:
    """
    Returns a Queryset limited by the offset.
    """
    queryset: QuerySet = self._clone()
    queryset._offset = offset
    return queryset

group_by

group_by(*group_by)

Returns the values grouped by the given fields.

Source code in edgy/core/db/querysets/base.py
1739
1740
1741
1742
1743
1744
1745
1746
1747
def group_by(self, *group_by: str) -> QuerySet:
    """
    Returns the values grouped by the given fields.
    """
    queryset: QuerySet = self._clone()
    queryset._group_by = group_by
    if queryset._update_select_related_weak(group_by, clear=True):
        queryset._update_select_related_weak(queryset._order_by, clear=False)
    return queryset

distinct

distinct(first=True, *distinct_on)

Returns a queryset with distinct results.

PARAMETER DESCRIPTION
first

If True, applies DISTINCT. If False, removes any distinct clause. If a string, applies DISTINCT ON to that field.

TYPE: bool | str DEFAULT: True

*distinct_on

Additional fields for DISTINCT ON.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
QuerySet

A new QuerySet with the distinct clause applied.

TYPE: QuerySet

Source code in edgy/core/db/querysets/base.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
def distinct(self, first: bool | str = True, *distinct_on: str) -> QuerySet:
    """
    Returns a queryset with distinct results.

    Args:
        first (bool | str): If True, applies `DISTINCT`. If False, removes any distinct clause.
                            If a string, applies `DISTINCT ON` to that field.
        *distinct_on (str): Additional fields for `DISTINCT ON`.

    Returns:
        QuerySet: A new QuerySet with the distinct clause applied.
    """
    queryset: QuerySet = self._clone()
    if first is False:
        queryset.distinct_on = None
    elif first is True:
        queryset.distinct_on = []
    else:
        queryset.distinct_on = [first, *distinct_on]
    return queryset

only

only(*fields)

Returns a list of models with the selected only fields and always the primary key.

Source code in edgy/core/db/querysets/base.py
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
def only(self, *fields: str) -> QuerySet:
    """
    Returns a list of models with the selected only fields and always the primary
    key.
    """
    queryset: QuerySet = self._clone()
    only_fields = set(fields)
    if self.model_class.pknames:
        for pkname in self.model_class.pknames:
            if pkname not in fields:
                for pkcolumn in self.model_class.meta.get_columns_for_name(pkname):
                    only_fields.add(pkcolumn.key)
    else:
        for pkcolumn in self.model_class.pkcolumns:
            only_fields.add(pkcolumn.key)
    queryset._only = only_fields
    return queryset

defer

defer(*fields)

Returns a list of models with the selected only fields and always the primary key.

Source code in edgy/core/db/querysets/base.py
1788
1789
1790
1791
1792
1793
1794
1795
1796
def defer(self, *fields: str) -> QuerySet:
    """
    Returns a list of models with the selected only fields and always the primary
    key.
    """
    queryset: QuerySet = self._clone()

    queryset._defer = set(fields)
    return queryset
select_related(*related)

Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.

This is a performance booster which results in a single more complex query but means

later use of foreign-key relationships won't require database queries.

Source code in edgy/core/db/querysets/base.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
def select_related(self, *related: str) -> QuerySet:
    """
    Returns a QuerySet that will “follow” foreign-key relationships, selecting additional
    related-object data when it executes its query.

    This is a performance booster which results in a single more complex query but means

    later use of foreign-key relationships won't require database queries.
    """
    queryset: QuerySet = self._clone()
    if len(related) >= 1 and not isinstance(cast(Any, related[0]), str):
        warnings.warn(
            "use `select_related` with variadic str arguments instead of a Sequence",
            DeprecationWarning,
            stacklevel=2,
        )
        related = cast(tuple[str, ...], related[0])
    queryset._update_select_related(related)
    return queryset

values async

values(fields=None, exclude=None, exclude_none=False)

Returns the results in a python dictionary format.

Source code in edgy/core/db/querysets/base.py
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
async def values(
    self,
    fields: Sequence[str] | str | None = None,
    exclude: Sequence[str] | set[str] = None,
    exclude_none: bool = False,
) -> list[dict]:
    """
    Returns the results in a python dictionary format.
    """

    if isinstance(fields, str):
        fields = [fields]

    if fields is not None and not isinstance(fields, Iterable):
        raise QuerySetError(detail="Fields must be a suitable sequence of strings or unset.")

    rows: list[BaseModelType] = await self
    if fields:
        return [
            row.model_dump(exclude=exclude, exclude_none=exclude_none, include=fields)
            for row in rows
        ]
    else:
        return [row.model_dump(exclude=exclude, exclude_none=exclude_none) for row in rows]

values_list async

values_list(fields=None, exclude=None, exclude_none=False, flat=False)

Returns the results in a python dictionary format.

Source code in edgy/core/db/querysets/base.py
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
async def values_list(
    self,
    fields: Sequence[str] | str | None = None,
    exclude: Sequence[str] | set[str] = None,
    exclude_none: bool = False,
    flat: bool = False,
) -> list[Any]:
    """
    Returns the results in a python dictionary format.
    """
    if isinstance(fields, str):
        fields = [fields]
    rows = await self.values(
        fields=fields,
        exclude=exclude,
        exclude_none=exclude_none,
    )
    if not flat:
        return [tuple(row.values()) for row in rows]
    else:
        try:
            return [row[fields[0]] for row in rows]
        except KeyError:
            raise QuerySetError(detail=f"{fields[0]} does not exist in the results.") from None

exists async

exists(**kwargs)

Returns a boolean indicating if a record exists or not.

Source code in edgy/core/db/querysets/base.py
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
async def exists(self, **kwargs: Any) -> bool:
    """
    Returns a boolean indicating if a record exists or not.
    """
    if kwargs:
        # check cache for existance
        cached = self._cache.get(self.model_class, kwargs)
        if cached is not None:
            return True
        filter_query = self.filter(**kwargs)
        filter_query._cache = self._cache
        return await filter_query.exists()
    queryset: QuerySet = self
    expression = (await queryset.as_select()).exists().select()
    check_db_connection(queryset.database)
    async with queryset.database as database:
        _exists = await database.fetch_val(expression)
    return cast(bool, _exists)

count async

count()

Returns an indicating the total records.

Source code in edgy/core/db/querysets/base.py
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
async def count(self) -> int:
    """
    Returns an indicating the total records.
    """
    if self._cache_count is not None:
        return self._cache_count
    queryset: QuerySet = self
    expression = (await queryset.as_select()).alias("subquery_for_count")
    expression = sqlalchemy.func.count().select().select_from(expression)
    check_db_connection(queryset.database)
    async with queryset.database as database:
        self._cache_count = count = cast("int", await database.fetch_val(expression))
    return count

get_or_none async

get_or_none(**kwargs)

Fetch one object matching the parameters or returns None.

Source code in edgy/core/db/querysets/base.py
1901
1902
1903
1904
1905
1906
1907
1908
async def get_or_none(self, **kwargs: Any) -> EdgyEmbedTarget | None:
    """
    Fetch one object matching the parameters or returns None.
    """
    try:
        return await self.get(**kwargs)
    except ObjectNotFound:
        return None

get async

get(**kwargs)

Returns a single record based on the given kwargs.

Source code in edgy/core/db/querysets/base.py
1910
1911
1912
1913
1914
async def get(self, **kwargs: Any) -> EdgyEmbedTarget:
    """
    Returns a single record based on the given kwargs.
    """
    return cast(EdgyEmbedTarget, (await self._get_raw(**kwargs))[1])

first async

first()

Returns the first record of a given queryset.

Source code in edgy/core/db/querysets/base.py
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
async def first(self) -> EdgyEmbedTarget | None:
    """
    Returns the first record of a given queryset.
    """
    if self._cache_count is not None and self._cache_count == 0:
        return None
    if self._cache_first is not None:
        return cast(EdgyEmbedTarget, self._cache_first[1])
    queryset = self
    if not queryset._order_by:
        queryset = queryset.order_by(*self.model_class.pkcolumns)
    expression, tables_and_models = await queryset.as_select_with_tables()
    self._cached_select_related_expression = queryset._cached_select_related_expression
    check_db_connection(queryset.database)
    async with queryset.database as database:
        row = await database.fetch_one(expression, pos=0)
    if row:
        return (
            await self._get_or_cache_row(row, tables_and_models, extra_attr="_cache_first")
        )[1]
    return None

last async

last()

Returns the last record of a given queryset.

Source code in edgy/core/db/querysets/base.py
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
async def last(self) -> EdgyEmbedTarget | None:
    """
    Returns the last record of a given queryset.
    """
    if self._cache_count is not None and self._cache_count == 0:
        return None
    if self._cache_last is not None:
        return cast(EdgyEmbedTarget, self._cache_last[1])
    queryset = self
    if not queryset._order_by:
        queryset = queryset.order_by(*self.model_class.pkcolumns)
    queryset = queryset.reverse()
    expression, tables_and_models = await queryset.as_select_with_tables()
    self._cached_select_related_expression = queryset._cached_select_related_expression
    check_db_connection(queryset.database)
    async with queryset.database as database:
        row = await database.fetch_one(expression, pos=0)
    if row:
        return (
            await self._get_or_cache_row(row, tables_and_models, extra_attr="_cache_last")
        )[1]
    return None

create async

create(*args, **kwargs)

Creates a record in a specific table.

Source code in edgy/core/db/querysets/base.py
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
async def create(self, *args: Any, **kwargs: Any) -> EdgyEmbedTarget:
    """
    Creates a record in a specific table.
    """
    # for tenancy
    queryset: QuerySet = self._clone()
    check_db_connection(queryset.database)
    token = CHECK_DB_CONNECTION_SILENCED.set(True)
    try:
        instance = queryset.model_class(*args, **kwargs)
        apply_instance_extras(
            instance,
            self.model_class,
            schema=self.using_schema,
            table=queryset.table,
            database=queryset.database,
        )
        # values=set(kwargs.keys()) is required for marking the provided kwargs as explicit provided kwargs
        token2 = CURRENT_INSTANCE.set(self)
        try:
            instance = await instance.real_save(force_insert=True, values=set(kwargs.keys()))
        finally:
            CURRENT_INSTANCE.reset(token2)
        result = await self._embed_parent_in_result(instance)
        self._clear_cache(keep_result_cache=True)
        self._cache.update(
            self.model_class,
            [result],
            cache_keys=[self._cache.create_cache_key(self.model_class, result[0])],
        )
        return cast(EdgyEmbedTarget, result[1])
    finally:
        CHECK_DB_CONNECTION_SILENCED.reset(token)

bulk_create async

bulk_create(objs)

Bulk creates records in a table

Source code in edgy/core/db/querysets/base.py
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
async def bulk_create(self, objs: Iterable[dict[str, Any] | EdgyModel]) -> None:
    """
    Bulk creates records in a table
    """
    queryset: QuerySet = self._clone()

    new_objs: list[EdgyModel] = []

    async def _iterate(obj_or_dict: EdgyModel | dict[str, Any]) -> dict[str, Any]:
        if isinstance(obj_or_dict, dict):
            obj: EdgyModel = queryset.model_class(**obj_or_dict)
            if (
                self.model_class.meta.post_save_fields
                and not self.model_class.meta.post_save_fields.isdisjoint(obj_or_dict.keys())
            ):
                new_objs.append(obj)
        else:
            obj = obj_or_dict
            if self.model_class.meta.post_save_fields:
                new_objs.append(obj)
        original = obj.extract_db_fields()
        col_values: dict[str, Any] = obj.extract_column_values(
            original, phase="prepare_insert", instance=self, model_instance=obj
        )
        col_values.update(
            await obj.execute_pre_save_hooks(col_values, original, is_update=False)
        )
        return col_values

    check_db_connection(queryset.database)
    token = CURRENT_INSTANCE.set(self)
    try:
        async with queryset.database as database, database.transaction():
            expression = queryset.table.insert().values([await _iterate(obj) for obj in objs])
            await database.execute_many(expression)
        self._clear_cache(keep_result_cache=True)
        if new_objs:
            for obj in new_objs:
                await obj.execute_post_save_hooks(
                    self.model_class.meta.fields.keys(), is_update=False
                )
    finally:
        CURRENT_INSTANCE.reset(token)

bulk_update async

bulk_update(objs, fields)

Bulk updates records in a table.

A similar solution was suggested here: https://github.com/encode/orm/pull/148

It is thought to be a clean approach to a simple problem so it was added here and refactored to be compatible with Edgy.

Source code in edgy/core/db/querysets/base.py
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
async def bulk_update(self, objs: list[EdgyModel], fields: list[str]) -> None:
    """
    Bulk updates records in a table.

    A similar solution was suggested here: https://github.com/encode/orm/pull/148

    It is thought to be a clean approach to a simple problem so it was added here and
    refactored to be compatible with Edgy.
    """
    queryset: QuerySet = self._clone()
    fields = list(fields)

    pk_query_placeholder = (
        getattr(queryset.table.c, pkcol)
        == sqlalchemy.bindparam(
            "__id" if pkcol == "id" else pkcol, type_=getattr(queryset.table.c, pkcol).type
        )
        for pkcol in queryset.pkcolumns
    )
    expression = queryset.table.update().where(*pk_query_placeholder)

    update_list = []
    fields_plus_pk = {*fields, *queryset.model_class.pkcolumns}
    check_db_connection(queryset.database)
    token = CURRENT_INSTANCE.set(self)
    try:
        async with queryset.database as database, database.transaction():
            for obj in objs:
                extracted = obj.extract_db_fields(fields_plus_pk)
                update = queryset.model_class.extract_column_values(
                    extracted,
                    is_update=True,
                    is_partial=True,
                    phase="prepare_update",
                    instance=self,
                    model_instance=obj,
                )
                update.update(
                    await obj.execute_pre_save_hooks(update, extracted, is_update=True)
                )
                if "id" in update:
                    update["__id"] = update.pop("id")
                update_list.append(update)

            values_placeholder: Any = {
                pkcol: sqlalchemy.bindparam(pkcol, type_=getattr(queryset.table.c, pkcol).type)
                for field in fields
                for pkcol in queryset.model_class.meta.field_to_column_names[field]
            }
            expression = expression.values(values_placeholder)
            await database.execute_many(expression, update_list)
        self._clear_cache()
        if (
            self.model_class.meta.post_save_fields
            and not self.model_class.meta.post_save_fields.isdisjoint(fields)
        ):
            for obj in objs:
                await obj.execute_post_save_hooks(fields, is_update=True)
    finally:
        CURRENT_INSTANCE.reset(token)

bulk_get_or_create async

bulk_get_or_create(objs, unique_fields=None)

Bulk gets or creates records in a table.

If records exist based on unique fields, they are retrieved. Otherwise, new records are created.

PARAMETER DESCRIPTION
objs

A list of objects or dictionaries.

TYPE: list[Union[dict[str, Any], EdgyModel]]

unique_fields

Fields that determine uniqueness. If None, all records are treated as new.

TYPE: list[str] | None DEFAULT: None

RETURNS DESCRIPTION
list[EdgyModel]

list[EdgyModel]: A list of retrieved or newly created objects.

Source code in edgy/core/db/querysets/base.py
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
async def bulk_get_or_create(
    self,
    objs: list[dict[str, Any] | EdgyModel],
    unique_fields: list[str] | None = None,
) -> list[EdgyModel]:
    """
    Bulk gets or creates records in a table.

    If records exist based on unique fields, they are retrieved.
    Otherwise, new records are created.

    Args:
        objs (list[Union[dict[str, Any], EdgyModel]]): A list of objects or dictionaries.
        unique_fields (list[str] | None): Fields that determine uniqueness. If None, all records are treated as new.

    Returns:
        list[EdgyModel]: A list of retrieved or newly created objects.
    """
    queryset: QuerySet = self._clone()
    new_objs: list[EdgyModel] = []
    retrieved_objs: list[EdgyModel] = []
    check_db_connection(queryset.database)

    if unique_fields:
        existing_records: dict[tuple, EdgyModel] = {}
        for obj in objs:
            filter_kwargs = {}
            dict_fields = {}
            if isinstance(obj, dict):
                for field in unique_fields:
                    if field in obj:
                        value = obj[field]
                        if isinstance(value, dict):
                            dict_fields[field] = value
                        else:
                            filter_kwargs[field] = value
            else:
                for field in unique_fields:
                    value = getattr(obj, field)
                    if isinstance(value, dict):
                        dict_fields[field] = value
                    else:
                        filter_kwargs[field] = value
            lookup_key = _extract_unique_lookup_key(obj, unique_fields)
            if lookup_key is not None and lookup_key in existing_records:
                continue
            found = False
            # This fixes edgy-guardian bug when using databasez.iterate indirectly and
            # is safe in case force_rollback is active
            # Models can also issue loads by accessing attrs for building unique_fields
            # For limiting use something like QuerySet.limit(100).bulk_get_or_create(...)
            for model in await queryset.filter(**filter_kwargs):
                if all(getattr(model, k) == expected for k, expected in dict_fields.items()):
                    lookup_key = _extract_unique_lookup_key(model, unique_fields)
                    assert lookup_key is not None, "invalid fields/attributes in unique_fields"
                    if lookup_key not in existing_records:
                        existing_records[lookup_key] = model
                    found = True
                    break
            if found is False:
                new_objs.append(queryset.model_class(**obj) if isinstance(obj, dict) else obj)

        retrieved_objs.extend(existing_records.values())
    else:
        new_objs.extend(
            [queryset.model_class(**obj) if isinstance(obj, dict) else obj for obj in objs]
        )

    async def _iterate(obj: EdgyModel) -> dict[str, Any]:
        original = obj.extract_db_fields()
        col_values: dict[str, Any] = obj.extract_column_values(
            original, phase="prepare_insert", instance=self
        )
        col_values.update(
            await obj.execute_pre_save_hooks(col_values, original, is_update=False)
        )
        return col_values

    token = CURRENT_INSTANCE.set(self)

    try:
        async with queryset.database as database, database.transaction():
            if new_objs:
                new_obj_values = [await _iterate(obj) for obj in new_objs]
                expression = queryset.table.insert().values(new_obj_values)
                await database.execute_many(expression)
                retrieved_objs.extend(new_objs)

            self._clear_cache()
            for obj in new_objs:
                await obj.execute_post_save_hooks(
                    self.model_class.meta.fields.keys(), is_update=False
                )
    finally:
        CURRENT_INSTANCE.reset(token)

    return retrieved_objs

delete async

delete(use_models=False)

Deletes records from the database.

This method triggers pre_delete and post_delete signals. If use_models is True or the model has specific deletion requirements, it performs a model-based deletion.

PARAMETER DESCRIPTION
use_models

If True, deletion is performed by iterating and deleting individual model instances. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
int

The number of rows deleted.

TYPE: int

Source code in edgy/core/db/querysets/base.py
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
async def delete(self, use_models: bool = False) -> int:
    """
    Deletes records from the database.

    This method triggers `pre_delete` and `post_delete` signals.
    If `use_models` is True or the model has specific deletion requirements,
    it performs a model-based deletion.

    Args:
        use_models (bool): If True, deletion is performed by iterating and
                           deleting individual model instances. Defaults to False.

    Returns:
        int: The number of rows deleted.
    """
    await self.model_class.meta.signals.pre_delete.send_async(
        self.model_class, instance=self, model_instance=None
    )
    row_count = await self.raw_delete(use_models=use_models, remove_referenced_call=False)
    await self.model_class.meta.signals.post_delete.send_async(
        self.model_class, instance=self, model_instance=None, row_count=row_count
    )
    return row_count

update async

update(**kwargs)

Updates records in a specific table with the given kwargs.

Warning: does not execute pre_save_callback/post_save_callback hooks and passes values directly to clean.

Source code in edgy/core/db/querysets/base.py
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
async def update(self, **kwargs: Any) -> None:
    """
    Updates records in a specific table with the given kwargs.

    Warning: does not execute pre_save_callback/post_save_callback hooks and passes values directly to clean.
    """

    column_values = self.model_class.extract_column_values(
        kwargs, is_update=True, is_partial=True, phase="prepare_update", instance=self
    )

    # Broadcast the initial update details
    # add is_update to match save
    await self.model_class.meta.signals.pre_update.send_async(
        self.model_class,
        instance=self,
        model_instance=None,
        values=kwargs,
        column_values=column_values,
        is_update=True,
        is_migration=False,
    )

    expression = self.table.update().values(**column_values)
    expression = expression.where(await self.build_where_clause())
    check_db_connection(self.database)
    async with self.database as database:
        await database.execute(expression)

    # Broadcast the update executed
    # add is_update to match save
    await self.model_class.meta.signals.post_update.send_async(
        self.model_class,
        instance=self,
        model_instance=None,
        values=kwargs,
        column_values=column_values,
        is_update=True,
        is_migration=False,
    )
    self._clear_cache()

get_or_create async

get_or_create(defaults=None, *args, **kwargs)

Creates a record in a specific table or updates if already exists.

Source code in edgy/core/db/querysets/base.py
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
async def get_or_create(
    self, defaults: dict[str, Any] | Any | None = None, *args: Any, **kwargs: Any
) -> tuple[EdgyEmbedTarget, bool]:
    """
    Creates a record in a specific table or updates if already exists.
    """
    if not isinstance(defaults, dict):
        # can be a ModelRef so pass it
        args = (defaults, *args)
        defaults = {}

    try:
        raw_instance, get_instance = await self._get_raw(**kwargs)
    except ObjectNotFound:
        kwargs.update(defaults)
        instance: EdgyEmbedTarget = await self.create(*args, **kwargs)
        return instance, True
    for arg in args:
        if isinstance(arg, ModelRef):
            relation_field = self.model_class.meta.fields[arg.__related_name__]
            extra_params = {}
            try:
                # m2m or foreign key
                target_model_class = relation_field.target
            except AttributeError:
                # reverse m2m or foreign key
                target_model_class = relation_field.related_from
            if not relation_field.is_m2m:
                # sometimes the foreign key is required, so set it already
                extra_params[relation_field.foreign_key.name] = raw_instance
            model = target_model_class(
                **arg.model_dump(exclude={"__related_name__"}),
                **extra_params,
            )
            relation = getattr(raw_instance, arg.__related_name__)
            await relation.add(model)
    return cast(EdgyEmbedTarget, get_instance), False

update_or_create async

update_or_create(defaults=None, *args, **kwargs)

Updates a record in a specific table or creates a new one.

Source code in edgy/core/db/querysets/base.py
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
async def update_or_create(
    self, defaults: dict[str, Any] | Any | None = None, *args: Any, **kwargs: Any
) -> tuple[EdgyEmbedTarget, bool]:
    """
    Updates a record in a specific table or creates a new one.
    """
    if not isinstance(defaults, dict):
        # can be a ModelRef so pass it
        args = (defaults, *args)
        defaults = {}
    try:
        raw_instance, get_instance = await self._get_raw(**kwargs)
    except ObjectNotFound:
        kwargs.update(defaults)
        instance: EdgyEmbedTarget = await self.create(*args, **kwargs)
        return instance, True
    await get_instance.update(**defaults)
    for arg in args:
        if isinstance(arg, ModelRef):
            relation_field = self.model_class.meta.fields[arg.__related_name__]
            extra_params = {}
            try:
                # m2m or foreign key
                target_model_class = relation_field.target
            except AttributeError:
                # reverse m2m or foreign key
                target_model_class = relation_field.related_from
            if not relation_field.is_m2m:
                # sometimes the foreign key is required, so set it already
                extra_params[relation_field.foreign_key.name] = raw_instance
            model = target_model_class(
                **arg.model_dump(exclude={"__related_name__"}),
                **extra_params,
            )
            relation = getattr(raw_instance, arg.__related_name__)
            await relation.add(model)
    self._clear_cache()
    return cast(EdgyEmbedTarget, get_instance), False

contains async

contains(instance)

Returns true if the QuerySet contains the provided object. False if otherwise.

Source code in edgy/core/db/querysets/base.py
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
async def contains(self, instance: BaseModelType) -> bool:
    """Returns true if the QuerySet contains the provided object.
    False if otherwise.
    """
    query: Any = {}
    try:
        pkcolumns = instance.pkcolumns
        for pkcolumn in pkcolumns:
            query[pkcolumn] = getattr(instance, pkcolumn)
            if query[pkcolumn] is None:
                raise ValueError("'obj' has incomplete/missing primary key.") from None
    except AttributeError:
        raise ValueError("'obj' must be a model or reflect model instance.") from None
    return await self.exists(**query)

transaction

transaction(*, force_rollback=False, **kwargs)

Return database transaction for the assigned database.

Source code in edgy/core/db/querysets/base.py
2356
2357
2358
def transaction(self, *, force_rollback: bool = False, **kwargs: Any) -> Transaction:
    """Return database transaction for the assigned database."""
    return self.database.transaction(force_rollback=force_rollback, **kwargs)

__aiter__ async

__aiter__()
Source code in edgy/core/db/querysets/base.py
2365
2366
2367
async def __aiter__(self) -> AsyncIterator[Any]:
    async for value in self._execute_iterate():
        yield value