1# orm/_orm_constructors.py
2# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: https://www.opensource.org/licenses/mit-license.php
7
8from __future__ import annotations
9
10import typing
11from typing import Any
12from typing import Callable
13from typing import Collection
14from typing import Iterable
15from typing import Mapping
16from typing import NoReturn
17from typing import Optional
18from typing import overload
19from typing import Type
20from typing import TYPE_CHECKING
21from typing import Union
22
23from . import mapperlib as mapperlib
24from ._typing import _O
25from .descriptor_props import Composite
26from .descriptor_props import Synonym
27from .interfaces import _AttributeOptions
28from .properties import MappedColumn
29from .properties import MappedSQLExpression
30from .query import AliasOption
31from .relationships import _RelationshipArgumentType
32from .relationships import _RelationshipBackPopulatesArgument
33from .relationships import _RelationshipDeclared
34from .relationships import _RelationshipSecondaryArgument
35from .relationships import RelationshipProperty
36from .session import Session
37from .util import _ORMJoin
38from .util import AliasedClass
39from .util import AliasedInsp
40from .util import LoaderCriteriaOption
41from .. import sql
42from .. import util
43from ..exc import InvalidRequestError
44from ..sql._typing import _no_kw
45from ..sql.base import _NoArg
46from ..sql.base import SchemaEventTarget
47from ..sql.schema import _InsertSentinelColumnDefault
48from ..sql.schema import SchemaConst
49from ..sql.selectable import FromClause
50from ..util.typing import Annotated
51from ..util.typing import Literal
52
53if TYPE_CHECKING:
54 from ._typing import _EntityType
55 from ._typing import _ORMColumnExprArgument
56 from .descriptor_props import _CC
57 from .descriptor_props import _CompositeAttrType
58 from .interfaces import PropComparator
59 from .mapper import Mapper
60 from .query import Query
61 from .relationships import _LazyLoadArgumentType
62 from .relationships import _ORMColCollectionArgument
63 from .relationships import _ORMOrderByArgument
64 from .relationships import _RelationshipJoinConditionArgument
65 from .relationships import ORMBackrefArgument
66 from .session import _SessionBind
67 from ..sql._typing import _AutoIncrementType
68 from ..sql._typing import _ColumnExpressionArgument
69 from ..sql._typing import _FromClauseArgument
70 from ..sql._typing import _InfoType
71 from ..sql._typing import _OnClauseArgument
72 from ..sql._typing import _TypeEngineArgument
73 from ..sql.elements import ColumnElement
74 from ..sql.schema import _ServerDefaultArgument
75 from ..sql.schema import _ServerOnUpdateArgument
76 from ..sql.selectable import Alias
77 from ..sql.selectable import Subquery
78
79
80_T = typing.TypeVar("_T")
81
82
83@util.deprecated(
84 "1.4",
85 "The :class:`.AliasOption` object is not necessary "
86 "for entities to be matched up to a query that is established "
87 "via :meth:`.Query.from_statement` and now does nothing.",
88 enable_warnings=False, # AliasOption itself warns
89)
90def contains_alias(alias: Union[Alias, Subquery]) -> AliasOption:
91 r"""Return a :class:`.MapperOption` that will indicate to the
92 :class:`_query.Query`
93 that the main table has been aliased.
94
95 """
96 return AliasOption(alias)
97
98
99def mapped_column(
100 __name_pos: Optional[
101 Union[str, _TypeEngineArgument[Any], SchemaEventTarget]
102 ] = None,
103 __type_pos: Optional[
104 Union[_TypeEngineArgument[Any], SchemaEventTarget]
105 ] = None,
106 /,
107 *args: SchemaEventTarget,
108 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
109 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
110 default: Optional[Any] = _NoArg.NO_ARG,
111 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
112 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
113 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
114 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
115 nullable: Optional[
116 Union[bool, Literal[SchemaConst.NULL_UNSPECIFIED]]
117 ] = SchemaConst.NULL_UNSPECIFIED,
118 primary_key: Optional[bool] = False,
119 deferred: Union[_NoArg, bool] = _NoArg.NO_ARG,
120 deferred_group: Optional[str] = None,
121 deferred_raiseload: Optional[bool] = None,
122 use_existing_column: bool = False,
123 name: Optional[str] = None,
124 type_: Optional[_TypeEngineArgument[Any]] = None,
125 autoincrement: _AutoIncrementType = "auto",
126 doc: Optional[str] = None,
127 key: Optional[str] = None,
128 index: Optional[bool] = None,
129 unique: Optional[bool] = None,
130 info: Optional[_InfoType] = None,
131 onupdate: Optional[Any] = None,
132 insert_default: Optional[Any] = _NoArg.NO_ARG,
133 server_default: Optional[_ServerDefaultArgument] = None,
134 server_onupdate: Optional[_ServerOnUpdateArgument] = None,
135 active_history: bool = False,
136 quote: Optional[bool] = None,
137 system: bool = False,
138 comment: Optional[str] = None,
139 sort_order: Union[_NoArg, int] = _NoArg.NO_ARG,
140 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
141 **kw: Any,
142) -> MappedColumn[Any]:
143 r"""declare a new ORM-mapped :class:`_schema.Column` construct
144 for use within :ref:`Declarative Table <orm_declarative_table>`
145 configuration.
146
147 The :func:`_orm.mapped_column` function provides an ORM-aware and
148 Python-typing-compatible construct which is used with
149 :ref:`declarative <orm_declarative_mapping>` mappings to indicate an
150 attribute that's mapped to a Core :class:`_schema.Column` object. It
151 provides the equivalent feature as mapping an attribute to a
152 :class:`_schema.Column` object directly when using Declarative,
153 specifically when using :ref:`Declarative Table <orm_declarative_table>`
154 configuration.
155
156 .. versionadded:: 2.0
157
158 :func:`_orm.mapped_column` is normally used with explicit typing along with
159 the :class:`_orm.Mapped` annotation type, where it can derive the SQL
160 type and nullability for the column based on what's present within the
161 :class:`_orm.Mapped` annotation. It also may be used without annotations
162 as a drop-in replacement for how :class:`_schema.Column` is used in
163 Declarative mappings in SQLAlchemy 1.x style.
164
165 For usage examples of :func:`_orm.mapped_column`, see the documentation
166 at :ref:`orm_declarative_table`.
167
168 .. seealso::
169
170 :ref:`orm_declarative_table` - complete documentation
171
172 :ref:`whatsnew_20_orm_declarative_typing` - migration notes for
173 Declarative mappings using 1.x style mappings
174
175 :param __name: String name to give to the :class:`_schema.Column`. This
176 is an optional, positional only argument that if present must be the
177 first positional argument passed. If omitted, the attribute name to
178 which the :func:`_orm.mapped_column` is mapped will be used as the SQL
179 column name.
180 :param __type: :class:`_types.TypeEngine` type or instance which will
181 indicate the datatype to be associated with the :class:`_schema.Column`.
182 This is an optional, positional-only argument that if present must
183 immediately follow the ``__name`` parameter if present also, or otherwise
184 be the first positional parameter. If omitted, the ultimate type for
185 the column may be derived either from the annotated type, or if a
186 :class:`_schema.ForeignKey` is present, from the datatype of the
187 referenced column.
188 :param \*args: Additional positional arguments include constructs such
189 as :class:`_schema.ForeignKey`, :class:`_schema.CheckConstraint`,
190 and :class:`_schema.Identity`, which are passed through to the constructed
191 :class:`_schema.Column`.
192 :param nullable: Optional bool, whether the column should be "NULL" or
193 "NOT NULL". If omitted, the nullability is derived from the type
194 annotation based on whether or not ``typing.Optional`` (or its equivalent)
195 is present. ``nullable`` defaults to ``True`` otherwise for non-primary
196 key columns, and ``False`` for primary key columns.
197 :param primary_key: optional bool, indicates the :class:`_schema.Column`
198 would be part of the table's primary key or not.
199 :param deferred: Optional bool - this keyword argument is consumed by the
200 ORM declarative process, and is not part of the :class:`_schema.Column`
201 itself; instead, it indicates that this column should be "deferred" for
202 loading as though mapped by :func:`_orm.deferred`.
203
204 .. seealso::
205
206 :ref:`orm_queryguide_deferred_declarative`
207
208 :param deferred_group: Implies :paramref:`_orm.mapped_column.deferred`
209 to ``True``, and set the :paramref:`_orm.deferred.group` parameter.
210
211 .. seealso::
212
213 :ref:`orm_queryguide_deferred_group`
214
215 :param deferred_raiseload: Implies :paramref:`_orm.mapped_column.deferred`
216 to ``True``, and set the :paramref:`_orm.deferred.raiseload` parameter.
217
218 .. seealso::
219
220 :ref:`orm_queryguide_deferred_raiseload`
221
222 :param use_existing_column: if True, will attempt to locate the given
223 column name on an inherited superclass (typically single inheriting
224 superclass), and if present, will not produce a new column, mapping
225 to the superclass column as though it were omitted from this class.
226 This is used for mixins that add new columns to an inherited superclass.
227
228 .. seealso::
229
230 :ref:`orm_inheritance_column_conflicts`
231
232 .. versionadded:: 2.0.0b4
233
234 :param default: Passed directly to the
235 :paramref:`_schema.Column.default` parameter if the
236 :paramref:`_orm.mapped_column.insert_default` parameter is not present.
237 Additionally, when used with :ref:`orm_declarative_native_dataclasses`,
238 indicates a default Python value that should be applied to the keyword
239 constructor within the generated ``__init__()`` method.
240
241 Note that in the case of dataclass generation when
242 :paramref:`_orm.mapped_column.insert_default` is not present, this means
243 the :paramref:`_orm.mapped_column.default` value is used in **two**
244 places, both the ``__init__()`` method as well as the
245 :paramref:`_schema.Column.default` parameter. While this behavior may
246 change in a future release, for the moment this tends to "work out"; a
247 default of ``None`` will mean that the :class:`_schema.Column` gets no
248 default generator, whereas a default that refers to a non-``None`` Python
249 or SQL expression value will be assigned up front on the object when
250 ``__init__()`` is called, which is the same value that the Core
251 :class:`_sql.Insert` construct would use in any case, leading to the same
252 end result.
253
254 .. note:: When using Core level column defaults that are callables to
255 be interpreted by the underlying :class:`_schema.Column` in conjunction
256 with :ref:`ORM-mapped dataclasses
257 <orm_declarative_native_dataclasses>`, especially those that are
258 :ref:`context-aware default functions <context_default_functions>`,
259 **the** :paramref:`_orm.mapped_column.insert_default` **parameter must
260 be used instead**. This is necessary to disambiguate the callable from
261 being interpreted as a dataclass level default.
262
263 .. seealso::
264
265 :ref:`defaults_default_factory_insert_default`
266
267 :paramref:`_orm.mapped_column.insert_default`
268
269 :paramref:`_orm.mapped_column.default_factory`
270
271 :param insert_default: Passed directly to the
272 :paramref:`_schema.Column.default` parameter; will supersede the value
273 of :paramref:`_orm.mapped_column.default` when present, however
274 :paramref:`_orm.mapped_column.default` will always apply to the
275 constructor default for a dataclasses mapping.
276
277 .. seealso::
278
279 :ref:`defaults_default_factory_insert_default`
280
281 :paramref:`_orm.mapped_column.default`
282
283 :paramref:`_orm.mapped_column.default_factory`
284
285 :param sort_order: An integer that indicates how this mapped column
286 should be sorted compared to the others when the ORM is creating a
287 :class:`_schema.Table`. Among mapped columns that have the same
288 value the default ordering is used, placing first the mapped columns
289 defined in the main class, then the ones in the super classes.
290 Defaults to 0. The sort is ascending.
291
292 .. versionadded:: 2.0.4
293
294 :param active_history=False:
295
296 When ``True``, indicates that the "previous" value for a
297 scalar attribute should be loaded when replaced, if not
298 already loaded. Normally, history tracking logic for
299 simple non-primary-key scalar values only needs to be
300 aware of the "new" value in order to perform a flush. This
301 flag is available for applications that make use of
302 :func:`.attributes.get_history` or :meth:`.Session.is_modified`
303 which also need to know the "previous" value of the attribute.
304
305 .. versionadded:: 2.0.10
306
307
308 :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
309 specifies if the mapped attribute should be part of the ``__init__()``
310 method as generated by the dataclass process.
311 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
312 specifies if the mapped attribute should be part of the ``__repr__()``
313 method as generated by the dataclass process.
314 :param default_factory: Specific to
315 :ref:`orm_declarative_native_dataclasses`,
316 specifies a default-value generation function that will take place
317 as part of the ``__init__()``
318 method as generated by the dataclass process.
319
320 .. seealso::
321
322 :ref:`defaults_default_factory_insert_default`
323
324 :paramref:`_orm.mapped_column.default`
325
326 :paramref:`_orm.mapped_column.insert_default`
327
328 :param compare: Specific to
329 :ref:`orm_declarative_native_dataclasses`, indicates if this field
330 should be included in comparison operations when generating the
331 ``__eq__()`` and ``__ne__()`` methods for the mapped class.
332
333 .. versionadded:: 2.0.0b4
334
335 :param kw_only: Specific to
336 :ref:`orm_declarative_native_dataclasses`, indicates if this field
337 should be marked as keyword-only when generating the ``__init__()``.
338
339 :param hash: Specific to
340 :ref:`orm_declarative_native_dataclasses`, controls if this field
341 is included when generating the ``__hash__()`` method for the mapped
342 class.
343
344 .. versionadded:: 2.0.36
345
346 :param dataclass_metadata: Specific to
347 :ref:`orm_declarative_native_dataclasses`, supplies metadata
348 to be attached to the generated dataclass field.
349
350 .. versionadded:: 2.0.42
351
352 :param \**kw: All remaining keyword arguments are passed through to the
353 constructor for the :class:`_schema.Column`.
354
355 """
356
357 return MappedColumn(
358 __name_pos,
359 __type_pos,
360 *args,
361 name=name,
362 type_=type_,
363 autoincrement=autoincrement,
364 insert_default=insert_default,
365 attribute_options=_AttributeOptions(
366 init,
367 repr,
368 default,
369 default_factory,
370 compare,
371 kw_only,
372 hash,
373 dataclass_metadata,
374 ),
375 doc=doc,
376 key=key,
377 index=index,
378 unique=unique,
379 info=info,
380 active_history=active_history,
381 nullable=nullable,
382 onupdate=onupdate,
383 primary_key=primary_key,
384 server_default=server_default,
385 server_onupdate=server_onupdate,
386 use_existing_column=use_existing_column,
387 quote=quote,
388 comment=comment,
389 system=system,
390 deferred=deferred,
391 deferred_group=deferred_group,
392 deferred_raiseload=deferred_raiseload,
393 sort_order=sort_order,
394 **kw,
395 )
396
397
398def orm_insert_sentinel(
399 name: Optional[str] = None,
400 type_: Optional[_TypeEngineArgument[Any]] = None,
401 *,
402 default: Optional[Any] = None,
403 omit_from_statements: bool = True,
404) -> MappedColumn[Any]:
405 """Provides a surrogate :func:`_orm.mapped_column` that generates
406 a so-called :term:`sentinel` column, allowing efficient bulk
407 inserts with deterministic RETURNING sorting for tables that don't
408 otherwise have qualifying primary key configurations.
409
410 Use of :func:`_orm.orm_insert_sentinel` is analogous to the use of the
411 :func:`_schema.insert_sentinel` construct within a Core
412 :class:`_schema.Table` construct.
413
414 Guidelines for adding this construct to a Declarative mapped class
415 are the same as that of the :func:`_schema.insert_sentinel` construct;
416 the database table itself also needs to have a column with this name
417 present.
418
419 For background on how this object is used, see the section
420 :ref:`engine_insertmanyvalues_sentinel_columns` as part of the
421 section :ref:`engine_insertmanyvalues`.
422
423 .. seealso::
424
425 :func:`_schema.insert_sentinel`
426
427 :ref:`engine_insertmanyvalues`
428
429 :ref:`engine_insertmanyvalues_sentinel_columns`
430
431
432 .. versionadded:: 2.0.10
433
434 """
435
436 return mapped_column(
437 name=name,
438 default=(
439 default if default is not None else _InsertSentinelColumnDefault()
440 ),
441 _omit_from_statements=omit_from_statements,
442 insert_sentinel=True,
443 use_existing_column=True,
444 nullable=True,
445 )
446
447
448@util.deprecated_params(
449 **{
450 arg: (
451 "2.0",
452 f"The :paramref:`_orm.column_property.{arg}` parameter is "
453 "deprecated for :func:`_orm.column_property`. This parameter "
454 "applies to a writeable-attribute in a Declarative Dataclasses "
455 "configuration only, and :func:`_orm.column_property` is treated "
456 "as a read-only attribute in this context.",
457 )
458 for arg in ("init", "kw_only", "default", "default_factory")
459 }
460)
461def column_property(
462 column: _ORMColumnExprArgument[_T],
463 *additional_columns: _ORMColumnExprArgument[Any],
464 group: Optional[str] = None,
465 deferred: bool = False,
466 raiseload: bool = False,
467 comparator_factory: Optional[Type[PropComparator[_T]]] = None,
468 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
469 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
470 default: Optional[Any] = _NoArg.NO_ARG,
471 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
472 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
473 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
474 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
475 active_history: bool = False,
476 expire_on_flush: bool = True,
477 info: Optional[_InfoType] = None,
478 doc: Optional[str] = None,
479 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
480) -> MappedSQLExpression[_T]:
481 r"""Provide a column-level property for use with a mapping.
482
483 With Declarative mappings, :func:`_orm.column_property` is used to
484 map read-only SQL expressions to a mapped class.
485
486 When using Imperative mappings, :func:`_orm.column_property` also
487 takes on the role of mapping table columns with additional features.
488 When using fully Declarative mappings, the :func:`_orm.mapped_column`
489 construct should be used for this purpose.
490
491 With Declarative Dataclass mappings, :func:`_orm.column_property`
492 is considered to be **read only**, and will not be included in the
493 Dataclass ``__init__()`` constructor.
494
495 The :func:`_orm.column_property` function returns an instance of
496 :class:`.ColumnProperty`.
497
498 .. seealso::
499
500 :ref:`mapper_column_property_sql_expressions` - general use of
501 :func:`_orm.column_property` to map SQL expressions
502
503 :ref:`orm_imperative_table_column_options` - usage of
504 :func:`_orm.column_property` with Imperative Table mappings to apply
505 additional options to a plain :class:`_schema.Column` object
506
507 :param \*cols:
508 list of Column objects to be mapped.
509
510 :param active_history=False:
511
512 Used only for Imperative Table mappings, or legacy-style Declarative
513 mappings (i.e. which have not been upgraded to
514 :func:`_orm.mapped_column`), for column-based attributes that are
515 expected to be writeable; use :func:`_orm.mapped_column` with
516 :paramref:`_orm.mapped_column.active_history` for Declarative mappings.
517 See that parameter for functional details.
518
519 :param comparator_factory: a class which extends
520 :class:`.ColumnProperty.Comparator` which provides custom SQL
521 clause generation for comparison operations.
522
523 :param group:
524 a group name for this property when marked as deferred.
525
526 :param deferred:
527 when True, the column property is "deferred", meaning that
528 it does not load immediately, and is instead loaded when the
529 attribute is first accessed on an instance. See also
530 :func:`~sqlalchemy.orm.deferred`.
531
532 :param doc:
533 optional string that will be applied as the doc on the
534 class-bound descriptor.
535
536 :param expire_on_flush=True:
537 Disable expiry on flush. A column_property() which refers
538 to a SQL expression (and not a single table-bound column)
539 is considered to be a "read only" property; populating it
540 has no effect on the state of data, and it can only return
541 database state. For this reason a column_property()'s value
542 is expired whenever the parent object is involved in a
543 flush, that is, has any kind of "dirty" state within a flush.
544 Setting this parameter to ``False`` will have the effect of
545 leaving any existing value present after the flush proceeds.
546 Note that the :class:`.Session` with default expiration
547 settings still expires
548 all attributes after a :meth:`.Session.commit` call, however.
549
550 :param info: Optional data dictionary which will be populated into the
551 :attr:`.MapperProperty.info` attribute of this object.
552
553 :param raiseload: if True, indicates the column should raise an error
554 when undeferred, rather than loading the value. This can be
555 altered at query time by using the :func:`.deferred` option with
556 raiseload=False.
557
558 .. versionadded:: 1.4
559
560 .. seealso::
561
562 :ref:`orm_queryguide_deferred_raiseload`
563
564 :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
565 specifies if the mapped attribute should be part of the ``__init__()``
566 method as generated by the dataclass process.
567 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
568 specifies if the mapped attribute should be part of the ``__repr__()``
569 method as generated by the dataclass process.
570 :param default_factory: Specific to
571 :ref:`orm_declarative_native_dataclasses`,
572 specifies a default-value generation function that will take place
573 as part of the ``__init__()``
574 method as generated by the dataclass process.
575
576 .. seealso::
577
578 :ref:`defaults_default_factory_insert_default`
579
580 :paramref:`_orm.mapped_column.default`
581
582 :paramref:`_orm.mapped_column.insert_default`
583
584 :param compare: Specific to
585 :ref:`orm_declarative_native_dataclasses`, indicates if this field
586 should be included in comparison operations when generating the
587 ``__eq__()`` and ``__ne__()`` methods for the mapped class.
588
589 .. versionadded:: 2.0.0b4
590
591 :param kw_only: Specific to
592 :ref:`orm_declarative_native_dataclasses`, indicates if this field
593 should be marked as keyword-only when generating the ``__init__()``.
594
595 :param hash: Specific to
596 :ref:`orm_declarative_native_dataclasses`, controls if this field
597 is included when generating the ``__hash__()`` method for the mapped
598 class.
599
600 .. versionadded:: 2.0.36
601
602 :param dataclass_metadata: Specific to
603 :ref:`orm_declarative_native_dataclasses`, supplies metadata
604 to be attached to the generated dataclass field.
605
606 .. versionadded:: 2.0.42
607
608 """
609 return MappedSQLExpression(
610 column,
611 *additional_columns,
612 attribute_options=_AttributeOptions(
613 False if init is _NoArg.NO_ARG else init,
614 repr,
615 default,
616 default_factory,
617 compare,
618 kw_only,
619 hash,
620 dataclass_metadata,
621 ),
622 group=group,
623 deferred=deferred,
624 raiseload=raiseload,
625 comparator_factory=comparator_factory,
626 active_history=active_history,
627 expire_on_flush=expire_on_flush,
628 info=info,
629 doc=doc,
630 _assume_readonly_dc_attributes=True,
631 )
632
633
634@overload
635def composite(
636 _class_or_attr: _CompositeAttrType[Any],
637 /,
638 *attrs: _CompositeAttrType[Any],
639 group: Optional[str] = None,
640 deferred: bool = False,
641 raiseload: bool = False,
642 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None,
643 active_history: bool = False,
644 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
645 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
646 default: Optional[Any] = _NoArg.NO_ARG,
647 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
648 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
649 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
650 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
651 info: Optional[_InfoType] = None,
652 doc: Optional[str] = None,
653 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
654 **__kw: Any,
655) -> Composite[Any]: ...
656
657
658@overload
659def composite(
660 _class_or_attr: Type[_CC],
661 /,
662 *attrs: _CompositeAttrType[Any],
663 group: Optional[str] = None,
664 deferred: bool = False,
665 raiseload: bool = False,
666 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None,
667 active_history: bool = False,
668 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
669 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
670 default: Optional[Any] = _NoArg.NO_ARG,
671 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
672 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
673 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
674 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
675 info: Optional[_InfoType] = None,
676 doc: Optional[str] = None,
677 **__kw: Any,
678) -> Composite[_CC]: ...
679
680
681@overload
682def composite(
683 _class_or_attr: Callable[..., _CC],
684 /,
685 *attrs: _CompositeAttrType[Any],
686 group: Optional[str] = None,
687 deferred: bool = False,
688 raiseload: bool = False,
689 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None,
690 active_history: bool = False,
691 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
692 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
693 default: Optional[Any] = _NoArg.NO_ARG,
694 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
695 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
696 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
697 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
698 info: Optional[_InfoType] = None,
699 doc: Optional[str] = None,
700 **__kw: Any,
701) -> Composite[_CC]: ...
702
703
704def composite(
705 _class_or_attr: Union[
706 None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any]
707 ] = None,
708 /,
709 *attrs: _CompositeAttrType[Any],
710 group: Optional[str] = None,
711 deferred: bool = False,
712 raiseload: bool = False,
713 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None,
714 active_history: bool = False,
715 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
716 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
717 default: Optional[Any] = _NoArg.NO_ARG,
718 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
719 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
720 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
721 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
722 info: Optional[_InfoType] = None,
723 doc: Optional[str] = None,
724 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
725 **__kw: Any,
726) -> Composite[Any]:
727 r"""Return a composite column-based property for use with a Mapper.
728
729 See the mapping documentation section :ref:`mapper_composite` for a
730 full usage example.
731
732 The :class:`.MapperProperty` returned by :func:`.composite`
733 is the :class:`.Composite`.
734
735 :param class\_:
736 The "composite type" class, or any classmethod or callable which
737 will produce a new instance of the composite object given the
738 column values in order.
739
740 :param \*attrs:
741 List of elements to be mapped, which may include:
742
743 * :class:`_schema.Column` objects
744 * :func:`_orm.mapped_column` constructs
745 * string names of other attributes on the mapped class, which may be
746 any other SQL or object-mapped attribute. This can for
747 example allow a composite that refers to a many-to-one relationship
748
749 :param active_history=False:
750 When ``True``, indicates that the "previous" value for a
751 scalar attribute should be loaded when replaced, if not
752 already loaded. See the same flag on :func:`.column_property`.
753
754 :param group:
755 A group name for this property when marked as deferred.
756
757 :param deferred:
758 When True, the column property is "deferred", meaning that it does
759 not load immediately, and is instead loaded when the attribute is
760 first accessed on an instance. See also
761 :func:`~sqlalchemy.orm.deferred`.
762
763 :param comparator_factory: a class which extends
764 :class:`.Composite.Comparator` which provides custom SQL
765 clause generation for comparison operations.
766
767 :param doc:
768 optional string that will be applied as the doc on the
769 class-bound descriptor.
770
771 :param info: Optional data dictionary which will be populated into the
772 :attr:`.MapperProperty.info` attribute of this object.
773
774 :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
775 specifies if the mapped attribute should be part of the ``__init__()``
776 method as generated by the dataclass process.
777 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
778 specifies if the mapped attribute should be part of the ``__repr__()``
779 method as generated by the dataclass process.
780 :param default_factory: Specific to
781 :ref:`orm_declarative_native_dataclasses`,
782 specifies a default-value generation function that will take place
783 as part of the ``__init__()``
784 method as generated by the dataclass process.
785
786 :param compare: Specific to
787 :ref:`orm_declarative_native_dataclasses`, indicates if this field
788 should be included in comparison operations when generating the
789 ``__eq__()`` and ``__ne__()`` methods for the mapped class.
790
791 .. versionadded:: 2.0.0b4
792
793 :param kw_only: Specific to
794 :ref:`orm_declarative_native_dataclasses`, indicates if this field
795 should be marked as keyword-only when generating the ``__init__()``.
796
797 :param hash: Specific to
798 :ref:`orm_declarative_native_dataclasses`, controls if this field
799 is included when generating the ``__hash__()`` method for the mapped
800 class.
801
802 .. versionadded:: 2.0.36
803
804 :param dataclass_metadata: Specific to
805 :ref:`orm_declarative_native_dataclasses`, supplies metadata
806 to be attached to the generated dataclass field.
807
808 .. versionadded:: 2.0.42
809
810 """
811 if __kw:
812 raise _no_kw()
813
814 return Composite(
815 _class_or_attr,
816 *attrs,
817 attribute_options=_AttributeOptions(
818 init,
819 repr,
820 default,
821 default_factory,
822 compare,
823 kw_only,
824 hash,
825 dataclass_metadata,
826 ),
827 group=group,
828 deferred=deferred,
829 raiseload=raiseload,
830 comparator_factory=comparator_factory,
831 active_history=active_history,
832 info=info,
833 doc=doc,
834 )
835
836
837def with_loader_criteria(
838 entity_or_base: _EntityType[Any],
839 where_criteria: Union[
840 _ColumnExpressionArgument[bool],
841 Callable[[Any], _ColumnExpressionArgument[bool]],
842 ],
843 loader_only: bool = False,
844 include_aliases: bool = False,
845 propagate_to_loaders: bool = True,
846 track_closure_variables: bool = True,
847) -> LoaderCriteriaOption:
848 """Add additional WHERE criteria to the load for all occurrences of
849 a particular entity.
850
851 .. versionadded:: 1.4
852
853 The :func:`_orm.with_loader_criteria` option is intended to add
854 limiting criteria to a particular kind of entity in a query,
855 **globally**, meaning it will apply to the entity as it appears
856 in the SELECT query as well as within any subqueries, join
857 conditions, and relationship loads, including both eager and lazy
858 loaders, without the need for it to be specified in any particular
859 part of the query. The rendering logic uses the same system used by
860 single table inheritance to ensure a certain discriminator is applied
861 to a table.
862
863 E.g., using :term:`2.0-style` queries, we can limit the way the
864 ``User.addresses`` collection is loaded, regardless of the kind
865 of loading used::
866
867 from sqlalchemy.orm import with_loader_criteria
868
869 stmt = select(User).options(
870 selectinload(User.addresses),
871 with_loader_criteria(Address, Address.email_address != "foo"),
872 )
873
874 Above, the "selectinload" for ``User.addresses`` will apply the
875 given filtering criteria to the WHERE clause.
876
877 Another example, where the filtering will be applied to the
878 ON clause of the join, in this example using :term:`1.x style`
879 queries::
880
881 q = (
882 session.query(User)
883 .outerjoin(User.addresses)
884 .options(with_loader_criteria(Address, Address.email_address != "foo"))
885 )
886
887 The primary purpose of :func:`_orm.with_loader_criteria` is to use
888 it in the :meth:`_orm.SessionEvents.do_orm_execute` event handler
889 to ensure that all occurrences of a particular entity are filtered
890 in a certain way, such as filtering for access control roles. It
891 also can be used to apply criteria to relationship loads. In the
892 example below, we can apply a certain set of rules to all queries
893 emitted by a particular :class:`_orm.Session`::
894
895 session = Session(bind=engine)
896
897
898 @event.listens_for("do_orm_execute", session)
899 def _add_filtering_criteria(execute_state):
900
901 if (
902 execute_state.is_select
903 and not execute_state.is_column_load
904 and not execute_state.is_relationship_load
905 ):
906 execute_state.statement = execute_state.statement.options(
907 with_loader_criteria(
908 SecurityRole,
909 lambda cls: cls.role.in_(["some_role"]),
910 include_aliases=True,
911 )
912 )
913
914 In the above example, the :meth:`_orm.SessionEvents.do_orm_execute`
915 event will intercept all queries emitted using the
916 :class:`_orm.Session`. For those queries which are SELECT statements
917 and are not attribute or relationship loads a custom
918 :func:`_orm.with_loader_criteria` option is added to the query. The
919 :func:`_orm.with_loader_criteria` option will be used in the given
920 statement and will also be automatically propagated to all relationship
921 loads that descend from this query.
922
923 The criteria argument given is a ``lambda`` that accepts a ``cls``
924 argument. The given class will expand to include all mapped subclass
925 and need not itself be a mapped class.
926
927 .. tip::
928
929 When using :func:`_orm.with_loader_criteria` option in
930 conjunction with the :func:`_orm.contains_eager` loader option,
931 it's important to note that :func:`_orm.with_loader_criteria` only
932 affects the part of the query that determines what SQL is rendered
933 in terms of the WHERE and FROM clauses. The
934 :func:`_orm.contains_eager` option does not affect the rendering of
935 the SELECT statement outside of the columns clause, so does not have
936 any interaction with the :func:`_orm.with_loader_criteria` option.
937 However, the way things "work" is that :func:`_orm.contains_eager`
938 is meant to be used with a query that is already selecting from the
939 additional entities in some way, where
940 :func:`_orm.with_loader_criteria` can apply it's additional
941 criteria.
942
943 In the example below, assuming a mapping relationship as
944 ``A -> A.bs -> B``, the given :func:`_orm.with_loader_criteria`
945 option will affect the way in which the JOIN is rendered::
946
947 stmt = (
948 select(A)
949 .join(A.bs)
950 .options(contains_eager(A.bs), with_loader_criteria(B, B.flag == 1))
951 )
952
953 Above, the given :func:`_orm.with_loader_criteria` option will
954 affect the ON clause of the JOIN that is specified by
955 ``.join(A.bs)``, so is applied as expected. The
956 :func:`_orm.contains_eager` option has the effect that columns from
957 ``B`` are added to the columns clause:
958
959 .. sourcecode:: sql
960
961 SELECT
962 b.id, b.a_id, b.data, b.flag,
963 a.id AS id_1,
964 a.data AS data_1
965 FROM a JOIN b ON a.id = b.a_id AND b.flag = :flag_1
966
967
968 The use of the :func:`_orm.contains_eager` option within the above
969 statement has no effect on the behavior of the
970 :func:`_orm.with_loader_criteria` option. If the
971 :func:`_orm.contains_eager` option were omitted, the SQL would be
972 the same as regards the FROM and WHERE clauses, where
973 :func:`_orm.with_loader_criteria` continues to add its criteria to
974 the ON clause of the JOIN. The addition of
975 :func:`_orm.contains_eager` only affects the columns clause, in that
976 additional columns against ``b`` are added which are then consumed
977 by the ORM to produce ``B`` instances.
978
979 .. warning:: The use of a lambda inside of the call to
980 :func:`_orm.with_loader_criteria` is only invoked **once per unique
981 class**. Custom functions should not be invoked within this lambda.
982 See :ref:`engine_lambda_caching` for an overview of the "lambda SQL"
983 feature, which is for advanced use only.
984
985 :param entity_or_base: a mapped class, or a class that is a super
986 class of a particular set of mapped classes, to which the rule
987 will apply.
988
989 :param where_criteria: a Core SQL expression that applies limiting
990 criteria. This may also be a "lambda:" or Python function that
991 accepts a target class as an argument, when the given class is
992 a base with many different mapped subclasses.
993
994 .. note:: To support pickling, use a module-level Python function to
995 produce the SQL expression instead of a lambda or a fixed SQL
996 expression, which tend to not be picklable.
997
998 :param include_aliases: if True, apply the rule to :func:`_orm.aliased`
999 constructs as well.
1000
1001 :param propagate_to_loaders: defaults to True, apply to relationship
1002 loaders such as lazy loaders. This indicates that the
1003 option object itself including SQL expression is carried along with
1004 each loaded instance. Set to ``False`` to prevent the object from
1005 being assigned to individual instances.
1006
1007
1008 .. seealso::
1009
1010 :ref:`examples_session_orm_events` - includes examples of using
1011 :func:`_orm.with_loader_criteria`.
1012
1013 :ref:`do_orm_execute_global_criteria` - basic example on how to
1014 combine :func:`_orm.with_loader_criteria` with the
1015 :meth:`_orm.SessionEvents.do_orm_execute` event.
1016
1017 :param track_closure_variables: when False, closure variables inside
1018 of a lambda expression will not be used as part of
1019 any cache key. This allows more complex expressions to be used
1020 inside of a lambda expression but requires that the lambda ensures
1021 it returns the identical SQL every time given a particular class.
1022
1023 .. versionadded:: 1.4.0b2
1024
1025 """ # noqa: E501
1026 return LoaderCriteriaOption(
1027 entity_or_base,
1028 where_criteria,
1029 loader_only,
1030 include_aliases,
1031 propagate_to_loaders,
1032 track_closure_variables,
1033 )
1034
1035
1036def relationship(
1037 argument: Optional[_RelationshipArgumentType[Any]] = None,
1038 secondary: Optional[_RelationshipSecondaryArgument] = None,
1039 *,
1040 uselist: Optional[bool] = None,
1041 collection_class: Optional[
1042 Union[Type[Collection[Any]], Callable[[], Collection[Any]]]
1043 ] = None,
1044 primaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
1045 secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
1046 back_populates: Optional[_RelationshipBackPopulatesArgument] = None,
1047 order_by: _ORMOrderByArgument = False,
1048 backref: Optional[ORMBackrefArgument] = None,
1049 overlaps: Optional[str] = None,
1050 post_update: bool = False,
1051 cascade: str = "save-update, merge",
1052 viewonly: bool = False,
1053 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
1054 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
1055 default: Union[_NoArg, _T] = _NoArg.NO_ARG,
1056 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
1057 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
1058 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
1059 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
1060 lazy: _LazyLoadArgumentType = "select",
1061 passive_deletes: Union[Literal["all"], bool] = False,
1062 passive_updates: bool = True,
1063 active_history: bool = False,
1064 enable_typechecks: bool = True,
1065 foreign_keys: Optional[_ORMColCollectionArgument] = None,
1066 remote_side: Optional[_ORMColCollectionArgument] = None,
1067 join_depth: Optional[int] = None,
1068 comparator_factory: Optional[
1069 Type[RelationshipProperty.Comparator[Any]]
1070 ] = None,
1071 single_parent: bool = False,
1072 innerjoin: bool = False,
1073 distinct_target_key: Optional[bool] = None,
1074 load_on_pending: bool = False,
1075 query_class: Optional[Type[Query[Any]]] = None,
1076 info: Optional[_InfoType] = None,
1077 omit_join: Literal[None, False] = None,
1078 sync_backref: Optional[bool] = None,
1079 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
1080 **kw: Any,
1081) -> _RelationshipDeclared[Any]:
1082 """Provide a relationship between two mapped classes.
1083
1084 This corresponds to a parent-child or associative table relationship.
1085 The constructed class is an instance of :class:`.Relationship`.
1086
1087 .. seealso::
1088
1089 :ref:`tutorial_orm_related_objects` - tutorial introduction
1090 to :func:`_orm.relationship` in the :ref:`unified_tutorial`
1091
1092 :ref:`relationship_config_toplevel` - narrative documentation
1093
1094 :param argument:
1095 This parameter refers to the class that is to be related. It
1096 accepts several forms, including a direct reference to the target
1097 class itself, the :class:`_orm.Mapper` instance for the target class,
1098 a Python callable / lambda that will return a reference to the
1099 class or :class:`_orm.Mapper` when called, and finally a string
1100 name for the class, which will be resolved from the
1101 :class:`_orm.registry` in use in order to locate the class, e.g.::
1102
1103 class SomeClass(Base):
1104 # ...
1105
1106 related = relationship("RelatedClass")
1107
1108 The :paramref:`_orm.relationship.argument` may also be omitted from the
1109 :func:`_orm.relationship` construct entirely, and instead placed inside
1110 a :class:`_orm.Mapped` annotation on the left side, which should
1111 include a Python collection type if the relationship is expected
1112 to be a collection, such as::
1113
1114 class SomeClass(Base):
1115 # ...
1116
1117 related_items: Mapped[List["RelatedItem"]] = relationship()
1118
1119 Or for a many-to-one or one-to-one relationship::
1120
1121 class SomeClass(Base):
1122 # ...
1123
1124 related_item: Mapped["RelatedItem"] = relationship()
1125
1126 .. seealso::
1127
1128 :ref:`orm_declarative_properties` - further detail
1129 on relationship configuration when using Declarative.
1130
1131 :param secondary:
1132 For a many-to-many relationship, specifies the intermediary
1133 table, and is typically an instance of :class:`_schema.Table`.
1134 In less common circumstances, the argument may also be specified
1135 as an :class:`_expression.Alias` construct, or even a
1136 :class:`_expression.Join` construct.
1137
1138 :paramref:`_orm.relationship.secondary` may
1139 also be passed as a callable function which is evaluated at
1140 mapper initialization time. When using Declarative, it may also
1141 be a string argument noting the name of a :class:`_schema.Table`
1142 that is
1143 present in the :class:`_schema.MetaData`
1144 collection associated with the
1145 parent-mapped :class:`_schema.Table`.
1146
1147 .. versionchanged:: 2.1 When passed as a string, the argument is
1148 interpreted as a string name that should exist directly in the
1149 registry of tables. The Python ``eval()`` function is no longer
1150 used for the :paramref:`_orm.relationship.secondary` argument when
1151 passed as a string.
1152
1153 The :paramref:`_orm.relationship.secondary` keyword argument is
1154 typically applied in the case where the intermediary
1155 :class:`_schema.Table`
1156 is not otherwise expressed in any direct class mapping. If the
1157 "secondary" table is also explicitly mapped elsewhere (e.g. as in
1158 :ref:`association_pattern`), one should consider applying the
1159 :paramref:`_orm.relationship.viewonly` flag so that this
1160 :func:`_orm.relationship`
1161 is not used for persistence operations which
1162 may conflict with those of the association object pattern.
1163
1164 .. seealso::
1165
1166 :ref:`relationships_many_to_many` - Reference example of "many
1167 to many".
1168
1169 :ref:`self_referential_many_to_many` - Specifics on using
1170 many-to-many in a self-referential case.
1171
1172 :ref:`declarative_many_to_many` - Additional options when using
1173 Declarative.
1174
1175 :ref:`association_pattern` - an alternative to
1176 :paramref:`_orm.relationship.secondary`
1177 when composing association
1178 table relationships, allowing additional attributes to be
1179 specified on the association table.
1180
1181 :ref:`composite_secondary_join` - a lesser-used pattern which
1182 in some cases can enable complex :func:`_orm.relationship` SQL
1183 conditions to be used.
1184
1185 :param active_history=False:
1186 When ``True``, indicates that the "previous" value for a
1187 many-to-one reference should be loaded when replaced, if
1188 not already loaded. Normally, history tracking logic for
1189 simple many-to-ones only needs to be aware of the "new"
1190 value in order to perform a flush. This flag is available
1191 for applications that make use of
1192 :func:`.attributes.get_history` which also need to know
1193 the "previous" value of the attribute.
1194
1195 :param backref:
1196 A reference to a string relationship name, or a :func:`_orm.backref`
1197 construct, which will be used to automatically generate a new
1198 :func:`_orm.relationship` on the related class, which then refers to this
1199 one using a bi-directional :paramref:`_orm.relationship.back_populates`
1200 configuration.
1201
1202 In modern Python, explicit use of :func:`_orm.relationship`
1203 with :paramref:`_orm.relationship.back_populates` should be preferred,
1204 as it is more robust in terms of mapper configuration as well as
1205 more conceptually straightforward. It also integrates with
1206 new :pep:`484` typing features introduced in SQLAlchemy 2.0 which
1207 is not possible with dynamically generated attributes.
1208
1209 .. seealso::
1210
1211 :ref:`relationships_backref` - notes on using
1212 :paramref:`_orm.relationship.backref`
1213
1214 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
1215 presents an overview of bi-directional relationship configuration
1216 and behaviors using :paramref:`_orm.relationship.back_populates`
1217
1218 :func:`.backref` - allows control over :func:`_orm.relationship`
1219 configuration when using :paramref:`_orm.relationship.backref`.
1220
1221
1222 :param back_populates:
1223 Indicates the name of a :func:`_orm.relationship` on the related
1224 class that will be synchronized with this one. It is usually
1225 expected that the :func:`_orm.relationship` on the related class
1226 also refer to this one. This allows objects on both sides of
1227 each :func:`_orm.relationship` to synchronize in-Python state
1228 changes and also provides directives to the :term:`unit of work`
1229 flush process how changes along these relationships should
1230 be persisted.
1231
1232 .. seealso::
1233
1234 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
1235 presents an overview of bi-directional relationship configuration
1236 and behaviors.
1237
1238 :ref:`relationship_patterns` - includes many examples of
1239 :paramref:`_orm.relationship.back_populates`.
1240
1241 :paramref:`_orm.relationship.backref` - legacy form which allows
1242 more succinct configuration, but does not support explicit typing
1243
1244 :param overlaps:
1245 A string name or comma-delimited set of names of other relationships
1246 on either this mapper, a descendant mapper, or a target mapper with
1247 which this relationship may write to the same foreign keys upon
1248 persistence. The only effect this has is to eliminate the
1249 warning that this relationship will conflict with another upon
1250 persistence. This is used for such relationships that are truly
1251 capable of conflicting with each other on write, but the application
1252 will ensure that no such conflicts occur.
1253
1254 .. versionadded:: 1.4
1255
1256 .. seealso::
1257
1258 :ref:`error_qzyx` - usage example
1259
1260 :param cascade:
1261 A comma-separated list of cascade rules which determines how
1262 Session operations should be "cascaded" from parent to child.
1263 This defaults to ``False``, which means the default cascade
1264 should be used - this default cascade is ``"save-update, merge"``.
1265
1266 The available cascades are ``save-update``, ``merge``,
1267 ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``.
1268 An additional option, ``all`` indicates shorthand for
1269 ``"save-update, merge, refresh-expire,
1270 expunge, delete"``, and is often used as in ``"all, delete-orphan"``
1271 to indicate that related objects should follow along with the
1272 parent object in all cases, and be deleted when de-associated.
1273
1274 .. seealso::
1275
1276 :ref:`unitofwork_cascades` - Full detail on each of the available
1277 cascade options.
1278
1279 :param cascade_backrefs=False:
1280 Legacy; this flag is always False.
1281
1282 .. versionchanged:: 2.0 "cascade_backrefs" functionality has been
1283 removed.
1284
1285 :param collection_class:
1286 A class or callable that returns a new list-holding object. will
1287 be used in place of a plain list for storing elements.
1288
1289 .. seealso::
1290
1291 :ref:`custom_collections` - Introductory documentation and
1292 examples.
1293
1294 :param comparator_factory:
1295 A class which extends :class:`.Relationship.Comparator`
1296 which provides custom SQL clause generation for comparison
1297 operations.
1298
1299 .. seealso::
1300
1301 :class:`.PropComparator` - some detail on redefining comparators
1302 at this level.
1303
1304 :ref:`custom_comparators` - Brief intro to this feature.
1305
1306
1307 :param distinct_target_key=None:
1308 Indicate if a "subquery" eager load should apply the DISTINCT
1309 keyword to the innermost SELECT statement. When left as ``None``,
1310 the DISTINCT keyword will be applied in those cases when the target
1311 columns do not comprise the full primary key of the target table.
1312 When set to ``True``, the DISTINCT keyword is applied to the
1313 innermost SELECT unconditionally.
1314
1315 It may be desirable to set this flag to False when the DISTINCT is
1316 reducing performance of the innermost subquery beyond that of what
1317 duplicate innermost rows may be causing.
1318
1319 .. seealso::
1320
1321 :ref:`loading_toplevel` - includes an introduction to subquery
1322 eager loading.
1323
1324 :param doc:
1325 Docstring which will be applied to the resulting descriptor.
1326
1327 :param foreign_keys:
1328
1329 A list of columns which are to be used as "foreign key"
1330 columns, or columns which refer to the value in a remote
1331 column, within the context of this :func:`_orm.relationship`
1332 object's :paramref:`_orm.relationship.primaryjoin` condition.
1333 That is, if the :paramref:`_orm.relationship.primaryjoin`
1334 condition of this :func:`_orm.relationship` is ``a.id ==
1335 b.a_id``, and the values in ``b.a_id`` are required to be
1336 present in ``a.id``, then the "foreign key" column of this
1337 :func:`_orm.relationship` is ``b.a_id``.
1338
1339 In normal cases, the :paramref:`_orm.relationship.foreign_keys`
1340 parameter is **not required.** :func:`_orm.relationship` will
1341 automatically determine which columns in the
1342 :paramref:`_orm.relationship.primaryjoin` condition are to be
1343 considered "foreign key" columns based on those
1344 :class:`_schema.Column` objects that specify
1345 :class:`_schema.ForeignKey`,
1346 or are otherwise listed as referencing columns in a
1347 :class:`_schema.ForeignKeyConstraint` construct.
1348 :paramref:`_orm.relationship.foreign_keys` is only needed when:
1349
1350 1. There is more than one way to construct a join from the local
1351 table to the remote table, as there are multiple foreign key
1352 references present. Setting ``foreign_keys`` will limit the
1353 :func:`_orm.relationship`
1354 to consider just those columns specified
1355 here as "foreign".
1356
1357 2. The :class:`_schema.Table` being mapped does not actually have
1358 :class:`_schema.ForeignKey` or
1359 :class:`_schema.ForeignKeyConstraint`
1360 constructs present, often because the table
1361 was reflected from a database that does not support foreign key
1362 reflection (MySQL MyISAM).
1363
1364 3. The :paramref:`_orm.relationship.primaryjoin`
1365 argument is used to
1366 construct a non-standard join condition, which makes use of
1367 columns or expressions that do not normally refer to their
1368 "parent" column, such as a join condition expressed by a
1369 complex comparison using a SQL function.
1370
1371 The :func:`_orm.relationship` construct will raise informative
1372 error messages that suggest the use of the
1373 :paramref:`_orm.relationship.foreign_keys` parameter when
1374 presented with an ambiguous condition. In typical cases,
1375 if :func:`_orm.relationship` doesn't raise any exceptions, the
1376 :paramref:`_orm.relationship.foreign_keys` parameter is usually
1377 not needed.
1378
1379 :paramref:`_orm.relationship.foreign_keys` may also be passed as a
1380 callable function which is evaluated at mapper initialization time,
1381 and may be passed as a Python-evaluable string when using
1382 Declarative.
1383
1384 .. warning:: When passed as a Python-evaluable string, the
1385 argument is interpreted using Python's ``eval()`` function.
1386 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1387 See :ref:`declarative_relationship_eval` for details on
1388 declarative evaluation of :func:`_orm.relationship` arguments.
1389
1390 .. seealso::
1391
1392 :ref:`relationship_foreign_keys`
1393
1394 :ref:`relationship_custom_foreign`
1395
1396 :func:`.foreign` - allows direct annotation of the "foreign"
1397 columns within a :paramref:`_orm.relationship.primaryjoin`
1398 condition.
1399
1400 :param info: Optional data dictionary which will be populated into the
1401 :attr:`.MapperProperty.info` attribute of this object.
1402
1403 :param innerjoin=False:
1404 When ``True``, joined eager loads will use an inner join to join
1405 against related tables instead of an outer join. The purpose
1406 of this option is generally one of performance, as inner joins
1407 generally perform better than outer joins.
1408
1409 This flag can be set to ``True`` when the relationship references an
1410 object via many-to-one using local foreign keys that are not
1411 nullable, or when the reference is one-to-one or a collection that
1412 is guaranteed to have one or at least one entry.
1413
1414 The option supports the same "nested" and "unnested" options as
1415 that of :paramref:`_orm.joinedload.innerjoin`. See that flag
1416 for details on nested / unnested behaviors.
1417
1418 .. seealso::
1419
1420 :paramref:`_orm.joinedload.innerjoin` - the option as specified by
1421 loader option, including detail on nesting behavior.
1422
1423 :ref:`what_kind_of_loading` - Discussion of some details of
1424 various loader options.
1425
1426
1427 :param join_depth:
1428 When non-``None``, an integer value indicating how many levels
1429 deep "eager" loaders should join on a self-referring or cyclical
1430 relationship. The number counts how many times the same Mapper
1431 shall be present in the loading condition along a particular join
1432 branch. When left at its default of ``None``, eager loaders
1433 will stop chaining when they encounter a the same target mapper
1434 which is already higher up in the chain. This option applies
1435 both to joined- and subquery- eager loaders.
1436
1437 .. seealso::
1438
1439 :ref:`self_referential_eager_loading` - Introductory documentation
1440 and examples.
1441
1442 :param lazy='select': specifies
1443 How the related items should be loaded. Default value is
1444 ``select``. Values include:
1445
1446 * ``select`` - items should be loaded lazily when the property is
1447 first accessed, using a separate SELECT statement, or identity map
1448 fetch for simple many-to-one references.
1449
1450 * ``immediate`` - items should be loaded as the parents are loaded,
1451 using a separate SELECT statement, or identity map fetch for
1452 simple many-to-one references.
1453
1454 * ``joined`` - items should be loaded "eagerly" in the same query as
1455 that of the parent, using a JOIN or LEFT OUTER JOIN. Whether
1456 the join is "outer" or not is determined by the
1457 :paramref:`_orm.relationship.innerjoin` parameter.
1458
1459 * ``subquery`` - items should be loaded "eagerly" as the parents are
1460 loaded, using one additional SQL statement, which issues a JOIN to
1461 a subquery of the original statement, for each collection
1462 requested.
1463
1464 * ``selectin`` - items should be loaded "eagerly" as the parents
1465 are loaded, using one or more additional SQL statements, which
1466 issues a JOIN to the immediate parent object, specifying primary
1467 key identifiers using an IN clause.
1468
1469 * ``raise`` - lazy loading is disallowed; accessing
1470 the attribute, if its value were not already loaded via eager
1471 loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`.
1472 This strategy can be used when objects are to be detached from
1473 their attached :class:`.Session` after they are loaded.
1474
1475 * ``raise_on_sql`` - lazy loading that emits SQL is disallowed;
1476 accessing the attribute, if its value were not already loaded via
1477 eager loading, will raise an
1478 :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load
1479 needs to emit SQL**. If the lazy load can pull the related value
1480 from the identity map or determine that it should be None, the
1481 value is loaded. This strategy can be used when objects will
1482 remain associated with the attached :class:`.Session`, however
1483 additional SELECT statements should be blocked.
1484
1485 * ``write_only`` - the attribute will be configured with a special
1486 "virtual collection" that may receive
1487 :meth:`_orm.WriteOnlyCollection.add` and
1488 :meth:`_orm.WriteOnlyCollection.remove` commands to add or remove
1489 individual objects, but will not under any circumstances load or
1490 iterate the full set of objects from the database directly. Instead,
1491 methods such as :meth:`_orm.WriteOnlyCollection.select`,
1492 :meth:`_orm.WriteOnlyCollection.insert`,
1493 :meth:`_orm.WriteOnlyCollection.update` and
1494 :meth:`_orm.WriteOnlyCollection.delete` are provided which generate SQL
1495 constructs that may be used to load and modify rows in bulk. Used for
1496 large collections that are never appropriate to load at once into
1497 memory.
1498
1499 The ``write_only`` loader style is configured automatically when
1500 the :class:`_orm.WriteOnlyMapped` annotation is provided on the
1501 left hand side within a Declarative mapping. See the section
1502 :ref:`write_only_relationship` for examples.
1503
1504 .. versionadded:: 2.0
1505
1506 .. seealso::
1507
1508 :ref:`write_only_relationship` - in the :ref:`queryguide_toplevel`
1509
1510 * ``dynamic`` - the attribute will return a pre-configured
1511 :class:`_query.Query` object for all read
1512 operations, onto which further filtering operations can be
1513 applied before iterating the results.
1514
1515 The ``dynamic`` loader style is configured automatically when
1516 the :class:`_orm.DynamicMapped` annotation is provided on the
1517 left hand side within a Declarative mapping. See the section
1518 :ref:`dynamic_relationship` for examples.
1519
1520 .. legacy:: The "dynamic" lazy loader strategy is the legacy form of
1521 what is now the "write_only" strategy described in the section
1522 :ref:`write_only_relationship`.
1523
1524 .. seealso::
1525
1526 :ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel`
1527
1528 :ref:`write_only_relationship` - more generally useful approach
1529 for large collections that should not fully load into memory
1530
1531 * ``noload`` - no loading should occur at any time. The related
1532 collection will remain empty.
1533
1534 .. deprecated:: 2.1 The ``noload`` loader strategy is deprecated and
1535 will be removed in a future release. This option produces incorrect
1536 results by returning ``None`` for related items.
1537
1538 * True - a synonym for 'select'
1539
1540 * False - a synonym for 'joined'
1541
1542 * None - a synonym for 'noload'
1543
1544 .. seealso::
1545
1546 :ref:`orm_queryguide_relationship_loaders` - Full documentation on
1547 relationship loader configuration in the :ref:`queryguide_toplevel`.
1548
1549
1550 :param load_on_pending=False:
1551 Indicates loading behavior for transient or pending parent objects.
1552
1553 When set to ``True``, causes the lazy-loader to
1554 issue a query for a parent object that is not persistent, meaning it
1555 has never been flushed. This may take effect for a pending object
1556 when autoflush is disabled, or for a transient object that has been
1557 "attached" to a :class:`.Session` but is not part of its pending
1558 collection.
1559
1560 The :paramref:`_orm.relationship.load_on_pending`
1561 flag does not improve
1562 behavior when the ORM is used normally - object references should be
1563 constructed at the object level, not at the foreign key level, so
1564 that they are present in an ordinary way before a flush proceeds.
1565 This flag is not not intended for general use.
1566
1567 .. seealso::
1568
1569 :meth:`.Session.enable_relationship_loading` - this method
1570 establishes "load on pending" behavior for the whole object, and
1571 also allows loading on objects that remain transient or
1572 detached.
1573
1574 :param order_by:
1575 Indicates the ordering that should be applied when loading these
1576 items. :paramref:`_orm.relationship.order_by`
1577 is expected to refer to
1578 one of the :class:`_schema.Column`
1579 objects to which the target class is
1580 mapped, or the attribute itself bound to the target class which
1581 refers to the column.
1582
1583 :paramref:`_orm.relationship.order_by`
1584 may also be passed as a callable
1585 function which is evaluated at mapper initialization time, and may
1586 be passed as a Python-evaluable string when using Declarative.
1587
1588 .. warning:: When passed as a Python-evaluable string, the
1589 argument is interpreted using Python's ``eval()`` function.
1590 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1591 See :ref:`declarative_relationship_eval` for details on
1592 declarative evaluation of :func:`_orm.relationship` arguments.
1593
1594 :param passive_deletes=False:
1595 Indicates loading behavior during delete operations.
1596
1597 A value of True indicates that unloaded child items should not
1598 be loaded during a delete operation on the parent. Normally,
1599 when a parent item is deleted, all child items are loaded so
1600 that they can either be marked as deleted, or have their
1601 foreign key to the parent set to NULL. Marking this flag as
1602 True usually implies an ON DELETE <CASCADE|SET NULL> rule is in
1603 place which will handle updating/deleting child rows on the
1604 database side.
1605
1606 Additionally, setting the flag to the string value 'all' will
1607 disable the "nulling out" of the child foreign keys, when the parent
1608 object is deleted and there is no delete or delete-orphan cascade
1609 enabled. This is typically used when a triggering or error raise
1610 scenario is in place on the database side. Note that the foreign
1611 key attributes on in-session child objects will not be changed after
1612 a flush occurs so this is a very special use-case setting.
1613 Additionally, the "nulling out" will still occur if the child
1614 object is de-associated with the parent.
1615
1616 .. seealso::
1617
1618 :ref:`passive_deletes` - Introductory documentation
1619 and examples.
1620
1621 :param passive_updates=True:
1622 Indicates the persistence behavior to take when a referenced
1623 primary key value changes in place, indicating that the referencing
1624 foreign key columns will also need their value changed.
1625
1626 When True, it is assumed that ``ON UPDATE CASCADE`` is configured on
1627 the foreign key in the database, and that the database will
1628 handle propagation of an UPDATE from a source column to
1629 dependent rows. When False, the SQLAlchemy
1630 :func:`_orm.relationship`
1631 construct will attempt to emit its own UPDATE statements to
1632 modify related targets. However note that SQLAlchemy **cannot**
1633 emit an UPDATE for more than one level of cascade. Also,
1634 setting this flag to False is not compatible in the case where
1635 the database is in fact enforcing referential integrity, unless
1636 those constraints are explicitly "deferred", if the target backend
1637 supports it.
1638
1639 It is highly advised that an application which is employing
1640 mutable primary keys keeps ``passive_updates`` set to True,
1641 and instead uses the referential integrity features of the database
1642 itself in order to handle the change efficiently and fully.
1643
1644 .. seealso::
1645
1646 :ref:`passive_updates` - Introductory documentation and
1647 examples.
1648
1649 :paramref:`.mapper.passive_updates` - a similar flag which
1650 takes effect for joined-table inheritance mappings.
1651
1652 :param post_update:
1653 This indicates that the relationship should be handled by a
1654 second UPDATE statement after an INSERT or before a
1655 DELETE. This flag is used to handle saving bi-directional
1656 dependencies between two individual rows (i.e. each row
1657 references the other), where it would otherwise be impossible to
1658 INSERT or DELETE both rows fully since one row exists before the
1659 other. Use this flag when a particular mapping arrangement will
1660 incur two rows that are dependent on each other, such as a table
1661 that has a one-to-many relationship to a set of child rows, and
1662 also has a column that references a single child row within that
1663 list (i.e. both tables contain a foreign key to each other). If
1664 a flush operation returns an error that a "cyclical
1665 dependency" was detected, this is a cue that you might want to
1666 use :paramref:`_orm.relationship.post_update` to "break" the cycle.
1667
1668 .. seealso::
1669
1670 :ref:`post_update` - Introductory documentation and examples.
1671
1672 :param primaryjoin:
1673 A SQL expression that will be used as the primary
1674 join of the child object against the parent object, or in a
1675 many-to-many relationship the join of the parent object to the
1676 association table. By default, this value is computed based on the
1677 foreign key relationships of the parent and child tables (or
1678 association table).
1679
1680 :paramref:`_orm.relationship.primaryjoin` may also be passed as a
1681 callable function which is evaluated at mapper initialization time,
1682 and may be passed as a Python-evaluable string when using
1683 Declarative.
1684
1685 .. warning:: When passed as a Python-evaluable string, the
1686 argument is interpreted using Python's ``eval()`` function.
1687 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1688 See :ref:`declarative_relationship_eval` for details on
1689 declarative evaluation of :func:`_orm.relationship` arguments.
1690
1691 .. seealso::
1692
1693 :ref:`relationship_primaryjoin`
1694
1695 :param remote_side:
1696 Used for self-referential relationships, indicates the column or
1697 list of columns that form the "remote side" of the relationship.
1698
1699 :paramref:`_orm.relationship.remote_side` may also be passed as a
1700 callable function which is evaluated at mapper initialization time,
1701 and may be passed as a Python-evaluable string when using
1702 Declarative.
1703
1704 .. warning:: When passed as a Python-evaluable string, the
1705 argument is interpreted using Python's ``eval()`` function.
1706 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1707 See :ref:`declarative_relationship_eval` for details on
1708 declarative evaluation of :func:`_orm.relationship` arguments.
1709
1710 .. seealso::
1711
1712 :ref:`self_referential` - in-depth explanation of how
1713 :paramref:`_orm.relationship.remote_side`
1714 is used to configure self-referential relationships.
1715
1716 :func:`.remote` - an annotation function that accomplishes the
1717 same purpose as :paramref:`_orm.relationship.remote_side`,
1718 typically
1719 when a custom :paramref:`_orm.relationship.primaryjoin` condition
1720 is used.
1721
1722 :param query_class:
1723 A :class:`_query.Query`
1724 subclass that will be used internally by the
1725 ``AppenderQuery`` returned by a "dynamic" relationship, that
1726 is, a relationship that specifies ``lazy="dynamic"`` or was
1727 otherwise constructed using the :func:`_orm.dynamic_loader`
1728 function.
1729
1730 .. seealso::
1731
1732 :ref:`dynamic_relationship` - Introduction to "dynamic"
1733 relationship loaders.
1734
1735 :param secondaryjoin:
1736 A SQL expression that will be used as the join of
1737 an association table to the child object. By default, this value is
1738 computed based on the foreign key relationships of the association
1739 and child tables.
1740
1741 :paramref:`_orm.relationship.secondaryjoin` may also be passed as a
1742 callable function which is evaluated at mapper initialization time,
1743 and may be passed as a Python-evaluable string when using
1744 Declarative.
1745
1746 .. warning:: When passed as a Python-evaluable string, the
1747 argument is interpreted using Python's ``eval()`` function.
1748 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1749 See :ref:`declarative_relationship_eval` for details on
1750 declarative evaluation of :func:`_orm.relationship` arguments.
1751
1752 .. seealso::
1753
1754 :ref:`relationship_primaryjoin`
1755
1756 :param single_parent:
1757 When True, installs a validator which will prevent objects
1758 from being associated with more than one parent at a time.
1759 This is used for many-to-one or many-to-many relationships that
1760 should be treated either as one-to-one or one-to-many. Its usage
1761 is optional, except for :func:`_orm.relationship` constructs which
1762 are many-to-one or many-to-many and also
1763 specify the ``delete-orphan`` cascade option. The
1764 :func:`_orm.relationship` construct itself will raise an error
1765 instructing when this option is required.
1766
1767 .. seealso::
1768
1769 :ref:`unitofwork_cascades` - includes detail on when the
1770 :paramref:`_orm.relationship.single_parent`
1771 flag may be appropriate.
1772
1773 :param uselist:
1774 A boolean that indicates if this property should be loaded as a
1775 list or a scalar. In most cases, this value is determined
1776 automatically by :func:`_orm.relationship` at mapper configuration
1777 time. When using explicit :class:`_orm.Mapped` annotations,
1778 :paramref:`_orm.relationship.uselist` may be derived from the
1779 whether or not the annotation within :class:`_orm.Mapped` contains
1780 a collection class.
1781 Otherwise, :paramref:`_orm.relationship.uselist` may be derived from
1782 the type and direction
1783 of the relationship - one to many forms a list, many to one
1784 forms a scalar, many to many is a list. If a scalar is desired
1785 where normally a list would be present, such as a bi-directional
1786 one-to-one relationship, use an appropriate :class:`_orm.Mapped`
1787 annotation or set :paramref:`_orm.relationship.uselist` to False.
1788
1789 The :paramref:`_orm.relationship.uselist`
1790 flag is also available on an
1791 existing :func:`_orm.relationship`
1792 construct as a read-only attribute,
1793 which can be used to determine if this :func:`_orm.relationship`
1794 deals
1795 with collections or scalar attributes::
1796
1797 >>> User.addresses.property.uselist
1798 True
1799
1800 .. seealso::
1801
1802 :ref:`relationships_one_to_one` - Introduction to the "one to
1803 one" relationship pattern, which is typically when an alternate
1804 setting for :paramref:`_orm.relationship.uselist` is involved.
1805
1806 :param viewonly=False:
1807 When set to ``True``, the relationship is used only for loading
1808 objects, and not for any persistence operation. A
1809 :func:`_orm.relationship` which specifies
1810 :paramref:`_orm.relationship.viewonly` can work
1811 with a wider range of SQL operations within the
1812 :paramref:`_orm.relationship.primaryjoin` condition, including
1813 operations that feature the use of a variety of comparison operators
1814 as well as SQL functions such as :func:`_expression.cast`. The
1815 :paramref:`_orm.relationship.viewonly`
1816 flag is also of general use when defining any kind of
1817 :func:`_orm.relationship` that doesn't represent
1818 the full set of related objects, to prevent modifications of the
1819 collection from resulting in persistence operations.
1820
1821 .. seealso::
1822
1823 :ref:`relationship_viewonly_notes` - more details on best practices
1824 when using :paramref:`_orm.relationship.viewonly`.
1825
1826 :param sync_backref:
1827 A boolean that enables the events used to synchronize the in-Python
1828 attributes when this relationship is target of either
1829 :paramref:`_orm.relationship.backref` or
1830 :paramref:`_orm.relationship.back_populates`.
1831
1832 Defaults to ``None``, which indicates that an automatic value should
1833 be selected based on the value of the
1834 :paramref:`_orm.relationship.viewonly` flag. When left at its
1835 default, changes in state will be back-populated only if neither
1836 sides of a relationship is viewonly.
1837
1838 .. versionchanged:: 1.4 - A relationship that specifies
1839 :paramref:`_orm.relationship.viewonly` automatically implies
1840 that :paramref:`_orm.relationship.sync_backref` is ``False``.
1841
1842 .. seealso::
1843
1844 :paramref:`_orm.relationship.viewonly`
1845
1846 :param omit_join:
1847 Allows manual control over the "selectin" automatic join
1848 optimization. Set to ``False`` to disable the "omit join" feature
1849 added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic
1850 optimization in place.
1851
1852 .. note:: This flag may only be set to ``False``. It is not
1853 necessary to set it to ``True`` as the "omit_join" optimization is
1854 automatically detected; if it is not detected, then the
1855 optimization is not supported.
1856
1857 :param default: Specific to :ref:`orm_declarative_native_dataclasses`,
1858 specifies an immutable scalar default value for the relationship that
1859 will behave as though it is the default value for the parameter in the
1860 ``__init__()`` method. This is only supported for a ``uselist=False``
1861 relationship, that is many-to-one or one-to-one, and only supports the
1862 scalar value ``None``, since no other immutable value is valid for such a
1863 relationship.
1864
1865 .. versionchanged:: 2.1 the :paramref:`_orm.relationship.default`
1866 parameter only supports a value of ``None``.
1867
1868 :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
1869 specifies if the mapped attribute should be part of the ``__init__()``
1870 method as generated by the dataclass process.
1871 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
1872 specifies if the mapped attribute should be part of the ``__repr__()``
1873 method as generated by the dataclass process.
1874 :param default_factory: Specific to
1875 :ref:`orm_declarative_native_dataclasses`,
1876 specifies a default-value generation function that will take place
1877 as part of the ``__init__()``
1878 method as generated by the dataclass process.
1879 :param compare: Specific to
1880 :ref:`orm_declarative_native_dataclasses`, indicates if this field
1881 should be included in comparison operations when generating the
1882 ``__eq__()`` and ``__ne__()`` methods for the mapped class.
1883
1884 .. versionadded:: 2.0.0b4
1885
1886 :param kw_only: Specific to
1887 :ref:`orm_declarative_native_dataclasses`, indicates if this field
1888 should be marked as keyword-only when generating the ``__init__()``.
1889
1890 :param hash: Specific to
1891 :ref:`orm_declarative_native_dataclasses`, controls if this field
1892 is included when generating the ``__hash__()`` method for the mapped
1893 class.
1894
1895 .. versionadded:: 2.0.36
1896
1897 :param dataclass_metadata: Specific to
1898 :ref:`orm_declarative_native_dataclasses`, supplies metadata
1899 to be attached to the generated dataclass field.
1900
1901 .. versionadded:: 2.0.42
1902
1903 """
1904
1905 return _RelationshipDeclared(
1906 argument,
1907 secondary=secondary,
1908 uselist=uselist,
1909 collection_class=collection_class,
1910 primaryjoin=primaryjoin,
1911 secondaryjoin=secondaryjoin,
1912 back_populates=back_populates,
1913 order_by=order_by,
1914 backref=backref,
1915 overlaps=overlaps,
1916 post_update=post_update,
1917 cascade=cascade,
1918 viewonly=viewonly,
1919 attribute_options=_AttributeOptions(
1920 init,
1921 repr,
1922 default,
1923 default_factory,
1924 compare,
1925 kw_only,
1926 hash,
1927 dataclass_metadata,
1928 ),
1929 lazy=lazy,
1930 passive_deletes=passive_deletes,
1931 passive_updates=passive_updates,
1932 active_history=active_history,
1933 enable_typechecks=enable_typechecks,
1934 foreign_keys=foreign_keys,
1935 remote_side=remote_side,
1936 join_depth=join_depth,
1937 comparator_factory=comparator_factory,
1938 single_parent=single_parent,
1939 innerjoin=innerjoin,
1940 distinct_target_key=distinct_target_key,
1941 load_on_pending=load_on_pending,
1942 query_class=query_class,
1943 info=info,
1944 omit_join=omit_join,
1945 sync_backref=sync_backref,
1946 **kw,
1947 )
1948
1949
1950def synonym(
1951 name: str,
1952 *,
1953 map_column: Optional[bool] = None,
1954 descriptor: Optional[Any] = None,
1955 comparator_factory: Optional[Type[PropComparator[_T]]] = None,
1956 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
1957 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
1958 default: Union[_NoArg, _T] = _NoArg.NO_ARG,
1959 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
1960 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
1961 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
1962 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
1963 info: Optional[_InfoType] = None,
1964 doc: Optional[str] = None,
1965 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
1966) -> Synonym[Any]:
1967 """Denote an attribute name as a synonym to a mapped property,
1968 in that the attribute will mirror the value and expression behavior
1969 of another attribute.
1970
1971 e.g.::
1972
1973 class MyClass(Base):
1974 __tablename__ = "my_table"
1975
1976 id = Column(Integer, primary_key=True)
1977 job_status = Column(String(50))
1978
1979 status = synonym("job_status")
1980
1981 :param name: the name of the existing mapped property. This
1982 can refer to the string name ORM-mapped attribute
1983 configured on the class, including column-bound attributes
1984 and relationships.
1985
1986 :param descriptor: a Python :term:`descriptor` that will be used
1987 as a getter (and potentially a setter) when this attribute is
1988 accessed at the instance level.
1989
1990 :param map_column: **For classical mappings and mappings against
1991 an existing Table object only**. if ``True``, the :func:`.synonym`
1992 construct will locate the :class:`_schema.Column`
1993 object upon the mapped
1994 table that would normally be associated with the attribute name of
1995 this synonym, and produce a new :class:`.ColumnProperty` that instead
1996 maps this :class:`_schema.Column`
1997 to the alternate name given as the "name"
1998 argument of the synonym; in this way, the usual step of redefining
1999 the mapping of the :class:`_schema.Column`
2000 to be under a different name is
2001 unnecessary. This is usually intended to be used when a
2002 :class:`_schema.Column`
2003 is to be replaced with an attribute that also uses a
2004 descriptor, that is, in conjunction with the
2005 :paramref:`.synonym.descriptor` parameter::
2006
2007 my_table = Table(
2008 "my_table",
2009 metadata,
2010 Column("id", Integer, primary_key=True),
2011 Column("job_status", String(50)),
2012 )
2013
2014
2015 class MyClass:
2016 @property
2017 def _job_status_descriptor(self):
2018 return "Status: %s" % self._job_status
2019
2020
2021 mapper(
2022 MyClass,
2023 my_table,
2024 properties={
2025 "job_status": synonym(
2026 "_job_status",
2027 map_column=True,
2028 descriptor=MyClass._job_status_descriptor,
2029 )
2030 },
2031 )
2032
2033 Above, the attribute named ``_job_status`` is automatically
2034 mapped to the ``job_status`` column::
2035
2036 >>> j1 = MyClass()
2037 >>> j1._job_status = "employed"
2038 >>> j1.job_status
2039 Status: employed
2040
2041 When using Declarative, in order to provide a descriptor in
2042 conjunction with a synonym, use the
2043 :func:`sqlalchemy.ext.declarative.synonym_for` helper. However,
2044 note that the :ref:`hybrid properties <mapper_hybrids>` feature
2045 should usually be preferred, particularly when redefining attribute
2046 behavior.
2047
2048 :param info: Optional data dictionary which will be populated into the
2049 :attr:`.InspectionAttr.info` attribute of this object.
2050
2051 :param comparator_factory: A subclass of :class:`.PropComparator`
2052 that will provide custom comparison behavior at the SQL expression
2053 level.
2054
2055 .. note::
2056
2057 For the use case of providing an attribute which redefines both
2058 Python-level and SQL-expression level behavior of an attribute,
2059 please refer to the Hybrid attribute introduced at
2060 :ref:`mapper_hybrids` for a more effective technique.
2061
2062 .. seealso::
2063
2064 :ref:`synonyms` - Overview of synonyms
2065
2066 :func:`.synonym_for` - a helper oriented towards Declarative
2067
2068 :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an
2069 updated approach to augmenting attribute behavior more flexibly
2070 than can be achieved with synonyms.
2071
2072 """
2073 return Synonym(
2074 name,
2075 map_column=map_column,
2076 descriptor=descriptor,
2077 comparator_factory=comparator_factory,
2078 attribute_options=_AttributeOptions(
2079 init,
2080 repr,
2081 default,
2082 default_factory,
2083 compare,
2084 kw_only,
2085 hash,
2086 dataclass_metadata,
2087 ),
2088 doc=doc,
2089 info=info,
2090 )
2091
2092
2093def create_session(
2094 bind: Optional[_SessionBind] = None, **kwargs: Any
2095) -> Session:
2096 r"""Create a new :class:`.Session`
2097 with no automation enabled by default.
2098
2099 This function is used primarily for testing. The usual
2100 route to :class:`.Session` creation is via its constructor
2101 or the :func:`.sessionmaker` function.
2102
2103 :param bind: optional, a single Connectable to use for all
2104 database access in the created
2105 :class:`~sqlalchemy.orm.session.Session`.
2106
2107 :param \*\*kwargs: optional, passed through to the
2108 :class:`.Session` constructor.
2109
2110 :returns: an :class:`~sqlalchemy.orm.session.Session` instance
2111
2112 The defaults of create_session() are the opposite of that of
2113 :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
2114 False.
2115
2116 Usage::
2117
2118 >>> from sqlalchemy.orm import create_session
2119 >>> session = create_session()
2120
2121 It is recommended to use :func:`sessionmaker` instead of
2122 create_session().
2123
2124 """
2125
2126 kwargs.setdefault("autoflush", False)
2127 kwargs.setdefault("expire_on_commit", False)
2128 return Session(bind=bind, **kwargs)
2129
2130
2131def _mapper_fn(*arg: Any, **kw: Any) -> NoReturn:
2132 """Placeholder for the now-removed ``mapper()`` function.
2133
2134 Classical mappings should be performed using the
2135 :meth:`_orm.registry.map_imperatively` method.
2136
2137 This symbol remains in SQLAlchemy 2.0 to suit the deprecated use case
2138 of using the ``mapper()`` function as a target for ORM event listeners,
2139 which failed to be marked as deprecated in the 1.4 series.
2140
2141 Global ORM mapper listeners should instead use the :class:`_orm.Mapper`
2142 class as the target.
2143
2144 .. versionchanged:: 2.0 The ``mapper()`` function was removed; the
2145 symbol remains temporarily as a placeholder for the event listening
2146 use case.
2147
2148 """
2149 raise InvalidRequestError(
2150 "The 'sqlalchemy.orm.mapper()' function is removed as of "
2151 "SQLAlchemy 2.0. Use the "
2152 "'sqlalchemy.orm.registry.map_imperatively()` "
2153 "method of the ``sqlalchemy.orm.registry`` class to perform "
2154 "classical mapping."
2155 )
2156
2157
2158def dynamic_loader(
2159 argument: Optional[_RelationshipArgumentType[Any]] = None, **kw: Any
2160) -> RelationshipProperty[Any]:
2161 """Construct a dynamically-loading mapper property.
2162
2163 This is essentially the same as
2164 using the ``lazy='dynamic'`` argument with :func:`relationship`::
2165
2166 dynamic_loader(SomeClass)
2167
2168 # is the same as
2169
2170 relationship(SomeClass, lazy="dynamic")
2171
2172 See the section :ref:`dynamic_relationship` for more details
2173 on dynamic loading.
2174
2175 """
2176 kw["lazy"] = "dynamic"
2177 return relationship(argument, **kw)
2178
2179
2180def backref(name: str, **kwargs: Any) -> ORMBackrefArgument:
2181 """When using the :paramref:`_orm.relationship.backref` parameter,
2182 provides specific parameters to be used when the new
2183 :func:`_orm.relationship` is generated.
2184
2185 E.g.::
2186
2187 "items": relationship(SomeItem, backref=backref("parent", lazy="subquery"))
2188
2189 The :paramref:`_orm.relationship.backref` parameter is generally
2190 considered to be legacy; for modern applications, using
2191 explicit :func:`_orm.relationship` constructs linked together using
2192 the :paramref:`_orm.relationship.back_populates` parameter should be
2193 preferred.
2194
2195 .. seealso::
2196
2197 :ref:`relationships_backref` - background on backrefs
2198
2199 """ # noqa: E501
2200
2201 return (name, kwargs)
2202
2203
2204def deferred(
2205 column: _ORMColumnExprArgument[_T],
2206 *additional_columns: _ORMColumnExprArgument[Any],
2207 group: Optional[str] = None,
2208 raiseload: bool = False,
2209 comparator_factory: Optional[Type[PropComparator[_T]]] = None,
2210 init: Union[_NoArg, bool] = _NoArg.NO_ARG,
2211 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
2212 default: Optional[Any] = _NoArg.NO_ARG,
2213 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
2214 compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
2215 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
2216 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
2217 active_history: bool = False,
2218 expire_on_flush: bool = True,
2219 info: Optional[_InfoType] = None,
2220 doc: Optional[str] = None,
2221 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG,
2222) -> MappedSQLExpression[_T]:
2223 r"""Indicate a column-based mapped attribute that by default will
2224 not load unless accessed.
2225
2226 When using :func:`_orm.mapped_column`, the same functionality as
2227 that of :func:`_orm.deferred` construct is provided by using the
2228 :paramref:`_orm.mapped_column.deferred` parameter.
2229
2230 :param \*columns: columns to be mapped. This is typically a single
2231 :class:`_schema.Column` object,
2232 however a collection is supported in order
2233 to support multiple columns mapped under the same attribute.
2234
2235 :param raiseload: boolean, if True, indicates an exception should be raised
2236 if the load operation is to take place.
2237
2238 .. versionadded:: 1.4
2239
2240
2241 Additional arguments are the same as that of :func:`_orm.column_property`.
2242
2243 .. seealso::
2244
2245 :ref:`orm_queryguide_deferred_imperative`
2246
2247 """
2248 return MappedSQLExpression(
2249 column,
2250 *additional_columns,
2251 attribute_options=_AttributeOptions(
2252 init,
2253 repr,
2254 default,
2255 default_factory,
2256 compare,
2257 kw_only,
2258 hash,
2259 dataclass_metadata,
2260 ),
2261 group=group,
2262 deferred=True,
2263 raiseload=raiseload,
2264 comparator_factory=comparator_factory,
2265 active_history=active_history,
2266 expire_on_flush=expire_on_flush,
2267 info=info,
2268 doc=doc,
2269 )
2270
2271
2272def query_expression(
2273 default_expr: _ORMColumnExprArgument[_T] = sql.null(),
2274 *,
2275 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
2276 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
2277 expire_on_flush: bool = True,
2278 info: Optional[_InfoType] = None,
2279 doc: Optional[str] = None,
2280) -> MappedSQLExpression[_T]:
2281 """Indicate an attribute that populates from a query-time SQL expression.
2282
2283 :param default_expr: Optional SQL expression object that will be used in
2284 all cases if not assigned later with :func:`_orm.with_expression`.
2285
2286 .. seealso::
2287
2288 :ref:`orm_queryguide_with_expression` - background and usage examples
2289
2290 """
2291 prop = MappedSQLExpression(
2292 default_expr,
2293 attribute_options=_AttributeOptions(
2294 False,
2295 repr,
2296 _NoArg.NO_ARG,
2297 _NoArg.NO_ARG,
2298 compare,
2299 _NoArg.NO_ARG,
2300 _NoArg.NO_ARG,
2301 _NoArg.NO_ARG,
2302 ),
2303 expire_on_flush=expire_on_flush,
2304 info=info,
2305 doc=doc,
2306 _assume_readonly_dc_attributes=True,
2307 )
2308
2309 prop.strategy_key = (("query_expression", True),)
2310 return prop
2311
2312
2313def clear_mappers() -> None:
2314 """Remove all mappers from all classes.
2315
2316 .. versionchanged:: 1.4 This function now locates all
2317 :class:`_orm.registry` objects and calls upon the
2318 :meth:`_orm.registry.dispose` method of each.
2319
2320 This function removes all instrumentation from classes and disposes
2321 of their associated mappers. Once called, the classes are unmapped
2322 and can be later re-mapped with new mappers.
2323
2324 :func:`.clear_mappers` is *not* for normal use, as there is literally no
2325 valid usage for it outside of very specific testing scenarios. Normally,
2326 mappers are permanent structural components of user-defined classes, and
2327 are never discarded independently of their class. If a mapped class
2328 itself is garbage collected, its mapper is automatically disposed of as
2329 well. As such, :func:`.clear_mappers` is only for usage in test suites
2330 that re-use the same classes with different mappings, which is itself an
2331 extremely rare use case - the only such use case is in fact SQLAlchemy's
2332 own test suite, and possibly the test suites of other ORM extension
2333 libraries which intend to test various combinations of mapper construction
2334 upon a fixed set of classes.
2335
2336 """
2337
2338 mapperlib._dispose_registries(mapperlib._all_registries(), False)
2339
2340
2341# I would really like a way to get the Type[] here that shows up
2342# in a different way in typing tools, however there is no current method
2343# that is accepted by mypy (subclass of Type[_O] works in pylance, rejected
2344# by mypy).
2345AliasedType = Annotated[Type[_O], "aliased"]
2346
2347
2348@overload
2349def aliased(
2350 element: Type[_O],
2351 alias: Optional[FromClause] = None,
2352 name: Optional[str] = None,
2353 flat: bool = False,
2354 adapt_on_names: bool = False,
2355) -> AliasedType[_O]: ...
2356
2357
2358@overload
2359def aliased(
2360 element: Union[AliasedClass[_O], Mapper[_O], AliasedInsp[_O]],
2361 alias: Optional[FromClause] = None,
2362 name: Optional[str] = None,
2363 flat: bool = False,
2364 adapt_on_names: bool = False,
2365) -> AliasedClass[_O]: ...
2366
2367
2368@overload
2369def aliased(
2370 element: FromClause,
2371 alias: None = None,
2372 name: Optional[str] = None,
2373 flat: bool = False,
2374 adapt_on_names: bool = False,
2375) -> FromClause: ...
2376
2377
2378def aliased(
2379 element: Union[_EntityType[_O], FromClause],
2380 alias: Optional[FromClause] = None,
2381 name: Optional[str] = None,
2382 flat: bool = False,
2383 adapt_on_names: bool = False,
2384) -> Union[AliasedClass[_O], FromClause, AliasedType[_O]]:
2385 """Produce an alias of the given element, usually an :class:`.AliasedClass`
2386 instance.
2387
2388 E.g.::
2389
2390 my_alias = aliased(MyClass)
2391
2392 stmt = select(MyClass, my_alias).filter(MyClass.id > my_alias.id)
2393 result = session.execute(stmt)
2394
2395 The :func:`.aliased` function is used to create an ad-hoc mapping of a
2396 mapped class to a new selectable. By default, a selectable is generated
2397 from the normally mapped selectable (typically a :class:`_schema.Table`
2398 ) using the
2399 :meth:`_expression.FromClause.alias` method. However, :func:`.aliased`
2400 can also be
2401 used to link the class to a new :func:`_expression.select` statement.
2402 Also, the :func:`.with_polymorphic` function is a variant of
2403 :func:`.aliased` that is intended to specify a so-called "polymorphic
2404 selectable", that corresponds to the union of several joined-inheritance
2405 subclasses at once.
2406
2407 For convenience, the :func:`.aliased` function also accepts plain
2408 :class:`_expression.FromClause` constructs, such as a
2409 :class:`_schema.Table` or
2410 :func:`_expression.select` construct. In those cases, the
2411 :meth:`_expression.FromClause.alias`
2412 method is called on the object and the new
2413 :class:`_expression.Alias` object returned. The returned
2414 :class:`_expression.Alias` is not
2415 ORM-mapped in this case.
2416
2417 .. seealso::
2418
2419 :ref:`tutorial_orm_entity_aliases` - in the :ref:`unified_tutorial`
2420
2421 :ref:`orm_queryguide_orm_aliases` - in the :ref:`queryguide_toplevel`
2422
2423 :param element: element to be aliased. Is normally a mapped class,
2424 but for convenience can also be a :class:`_expression.FromClause`
2425 element.
2426
2427 :param alias: Optional selectable unit to map the element to. This is
2428 usually used to link the object to a subquery, and should be an aliased
2429 select construct as one would produce from the
2430 :meth:`_query.Query.subquery` method or
2431 the :meth:`_expression.Select.subquery` or
2432 :meth:`_expression.Select.alias` methods of the :func:`_expression.select`
2433 construct.
2434
2435 :param name: optional string name to use for the alias, if not specified
2436 by the ``alias`` parameter. The name, among other things, forms the
2437 attribute name that will be accessible via tuples returned by a
2438 :class:`_query.Query` object. Not supported when creating aliases
2439 of :class:`_sql.Join` objects.
2440
2441 :param flat: Boolean, will be passed through to the
2442 :meth:`_expression.FromClause.alias` call so that aliases of
2443 :class:`_expression.Join` objects will alias the individual tables
2444 inside the join, rather than creating a subquery. This is generally
2445 supported by all modern databases with regards to right-nested joins
2446 and generally produces more efficient queries.
2447
2448 When :paramref:`_orm.aliased.flat` is combined with
2449 :paramref:`_orm.aliased.name`, the resulting joins will alias individual
2450 tables using a naming scheme similar to ``<prefix>_<tablename>``. This
2451 naming scheme is for visibility / debugging purposes only and the
2452 specific scheme is subject to change without notice.
2453
2454 .. versionadded:: 2.0.32 added support for combining
2455 :paramref:`_orm.aliased.name` with :paramref:`_orm.aliased.flat`.
2456 Previously, this would raise ``NotImplementedError``.
2457
2458 :param adapt_on_names: if True, more liberal "matching" will be used when
2459 mapping the mapped columns of the ORM entity to those of the
2460 given selectable - a name-based match will be performed if the
2461 given selectable doesn't otherwise have a column that corresponds
2462 to one on the entity. The use case for this is when associating
2463 an entity with some derived selectable such as one that uses
2464 aggregate functions::
2465
2466 class UnitPrice(Base):
2467 __tablename__ = "unit_price"
2468 ...
2469 unit_id = Column(Integer)
2470 price = Column(Numeric)
2471
2472
2473 aggregated_unit_price = (
2474 Session.query(func.sum(UnitPrice.price).label("price"))
2475 .group_by(UnitPrice.unit_id)
2476 .subquery()
2477 )
2478
2479 aggregated_unit_price = aliased(
2480 UnitPrice, alias=aggregated_unit_price, adapt_on_names=True
2481 )
2482
2483 Above, functions on ``aggregated_unit_price`` which refer to
2484 ``.price`` will return the
2485 ``func.sum(UnitPrice.price).label('price')`` column, as it is
2486 matched on the name "price". Ordinarily, the "price" function
2487 wouldn't have any "column correspondence" to the actual
2488 ``UnitPrice.price`` column as it is not a proxy of the original.
2489
2490 """
2491 return AliasedInsp._alias_factory(
2492 element,
2493 alias=alias,
2494 name=name,
2495 flat=flat,
2496 adapt_on_names=adapt_on_names,
2497 )
2498
2499
2500def with_polymorphic(
2501 base: Union[Type[_O], Mapper[_O]],
2502 classes: Union[Literal["*"], Iterable[Type[Any]]],
2503 selectable: Union[Literal[False, None], FromClause] = False,
2504 flat: bool = False,
2505 polymorphic_on: Optional[ColumnElement[Any]] = None,
2506 aliased: bool = False,
2507 innerjoin: bool = False,
2508 adapt_on_names: bool = False,
2509 name: Optional[str] = None,
2510 _use_mapper_path: bool = False,
2511) -> AliasedClass[_O]:
2512 """Produce an :class:`.AliasedClass` construct which specifies
2513 columns for descendant mappers of the given base.
2514
2515 Using this method will ensure that each descendant mapper's
2516 tables are included in the FROM clause, and will allow filter()
2517 criterion to be used against those tables. The resulting
2518 instances will also have those columns already loaded so that
2519 no "post fetch" of those columns will be required.
2520
2521 .. seealso::
2522
2523 :ref:`with_polymorphic` - full discussion of
2524 :func:`_orm.with_polymorphic`.
2525
2526 :param base: Base class to be aliased.
2527
2528 :param classes: a single class or mapper, or list of
2529 class/mappers, which inherit from the base class.
2530 Alternatively, it may also be the string ``'*'``, in which case
2531 all descending mapped classes will be added to the FROM clause.
2532
2533 :param aliased: when True, the selectable will be aliased. For a
2534 JOIN, this means the JOIN will be SELECTed from inside of a subquery
2535 unless the :paramref:`_orm.with_polymorphic.flat` flag is set to
2536 True, which is recommended for simpler use cases.
2537
2538 :param flat: Boolean, will be passed through to the
2539 :meth:`_expression.FromClause.alias` call so that aliases of
2540 :class:`_expression.Join` objects will alias the individual tables
2541 inside the join, rather than creating a subquery. This is generally
2542 supported by all modern databases with regards to right-nested joins
2543 and generally produces more efficient queries. Setting this flag is
2544 recommended as long as the resulting SQL is functional.
2545
2546 :param selectable: a table or subquery that will
2547 be used in place of the generated FROM clause. This argument is
2548 required if any of the desired classes use concrete table
2549 inheritance, since SQLAlchemy currently cannot generate UNIONs
2550 among tables automatically. If used, the ``selectable`` argument
2551 must represent the full set of tables and columns mapped by every
2552 mapped class. Otherwise, the unaccounted mapped columns will
2553 result in their table being appended directly to the FROM clause
2554 which will usually lead to incorrect results.
2555
2556 When left at its default value of ``False``, the polymorphic
2557 selectable assigned to the base mapper is used for selecting rows.
2558 However, it may also be passed as ``None``, which will bypass the
2559 configured polymorphic selectable and instead construct an ad-hoc
2560 selectable for the target classes given; for joined table inheritance
2561 this will be a join that includes all target mappers and their
2562 subclasses.
2563
2564 :param polymorphic_on: a column to be used as the "discriminator"
2565 column for the given selectable. If not given, the polymorphic_on
2566 attribute of the base classes' mapper will be used, if any. This
2567 is useful for mappings that don't have polymorphic loading
2568 behavior by default.
2569
2570 :param innerjoin: if True, an INNER JOIN will be used. This should
2571 only be specified if querying for one specific subtype only
2572
2573 :param adapt_on_names: Passes through the
2574 :paramref:`_orm.aliased.adapt_on_names`
2575 parameter to the aliased object. This may be useful in situations where
2576 the given selectable is not directly related to the existing mapped
2577 selectable.
2578
2579 .. versionadded:: 1.4.33
2580
2581 :param name: Name given to the generated :class:`.AliasedClass`.
2582
2583 .. versionadded:: 2.0.31
2584
2585 """
2586 return AliasedInsp._with_polymorphic_factory(
2587 base,
2588 classes,
2589 selectable=selectable,
2590 flat=flat,
2591 polymorphic_on=polymorphic_on,
2592 adapt_on_names=adapt_on_names,
2593 aliased=aliased,
2594 innerjoin=innerjoin,
2595 name=name,
2596 _use_mapper_path=_use_mapper_path,
2597 )
2598
2599
2600def join(
2601 left: _FromClauseArgument,
2602 right: _FromClauseArgument,
2603 onclause: Optional[_OnClauseArgument] = None,
2604 isouter: bool = False,
2605 full: bool = False,
2606) -> _ORMJoin:
2607 r"""Produce an inner join between left and right clauses.
2608
2609 :func:`_orm.join` is an extension to the core join interface
2610 provided by :func:`_expression.join()`, where the
2611 left and right selectable may be not only core selectable
2612 objects such as :class:`_schema.Table`, but also mapped classes or
2613 :class:`.AliasedClass` instances. The "on" clause can
2614 be a SQL expression or an ORM mapped attribute
2615 referencing a configured :func:`_orm.relationship`.
2616
2617 :func:`_orm.join` is not commonly needed in modern usage,
2618 as its functionality is encapsulated within that of the
2619 :meth:`_sql.Select.join` and :meth:`_query.Query.join`
2620 methods. which feature a
2621 significant amount of automation beyond :func:`_orm.join`
2622 by itself. Explicit use of :func:`_orm.join`
2623 with ORM-enabled SELECT statements involves use of the
2624 :meth:`_sql.Select.select_from` method, as in::
2625
2626 from sqlalchemy.orm import join
2627
2628 stmt = (
2629 select(User)
2630 .select_from(join(User, Address, User.addresses))
2631 .filter(Address.email_address == "foo@bar.com")
2632 )
2633
2634 In modern SQLAlchemy the above join can be written more
2635 succinctly as::
2636
2637 stmt = (
2638 select(User)
2639 .join(User.addresses)
2640 .filter(Address.email_address == "foo@bar.com")
2641 )
2642
2643 .. warning:: using :func:`_orm.join` directly may not work properly
2644 with modern ORM options such as :func:`_orm.with_loader_criteria`.
2645 It is strongly recommended to use the idiomatic join patterns
2646 provided by methods such as :meth:`.Select.join` and
2647 :meth:`.Select.join_from` when creating ORM joins.
2648
2649 .. seealso::
2650
2651 :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` for
2652 background on idiomatic ORM join patterns
2653
2654 """
2655 return _ORMJoin(left, right, onclause, isouter, full)
2656
2657
2658def outerjoin(
2659 left: _FromClauseArgument,
2660 right: _FromClauseArgument,
2661 onclause: Optional[_OnClauseArgument] = None,
2662 full: bool = False,
2663) -> _ORMJoin:
2664 """Produce a left outer join between left and right clauses.
2665
2666 This is the "outer join" version of the :func:`_orm.join` function,
2667 featuring the same behavior except that an OUTER JOIN is generated.
2668 See that function's documentation for other usage details.
2669
2670 """
2671 return _ORMJoin(left, right, onclause, True, full)