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