SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

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