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