Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/_orm_constructors.py: 60%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

128 statements  

1# orm/_orm_constructors.py 

2# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors 

3# <see AUTHORS file> 

4# 

5# This module is part of SQLAlchemy and is released under 

6# the MIT License: https://www.opensource.org/licenses/mit-license.php 

7 

8from __future__ import annotations 

9 

10import typing 

11from typing import Any 

12from typing import Callable 

13from typing import Collection 

14from typing import Iterable 

15from typing import Mapping 

16from typing import NoReturn 

17from typing import Optional 

18from typing import overload 

19from typing import Type 

20from typing import TYPE_CHECKING 

21from typing import Union 

22 

23from . import mapperlib as mapperlib 

24from ._typing import _O 

25from .descriptor_props import Composite 

26from .descriptor_props import Synonym 

27from .interfaces import _AttributeOptions 

28from .properties import MappedColumn 

29from .properties import MappedSQLExpression 

30from .query import AliasOption 

31from .relationships import _RelationshipArgumentType 

32from .relationships import _RelationshipDeclared 

33from .relationships import _RelationshipSecondaryArgument 

34from .relationships import RelationshipProperty 

35from .session import Session 

36from .util import _ORMJoin 

37from .util import AliasedClass 

38from .util import AliasedInsp 

39from .util import LoaderCriteriaOption 

40from .. import sql 

41from .. import util 

42from ..exc import InvalidRequestError 

43from ..sql._typing import _no_kw 

44from ..sql.base import _NoArg 

45from ..sql.base import SchemaEventTarget 

46from ..sql.schema import _InsertSentinelColumnDefault 

47from ..sql.schema import SchemaConst 

48from ..sql.selectable import FromClause 

49from ..util.typing import Annotated 

50from ..util.typing import Literal 

51 

52if TYPE_CHECKING: 

53 from ._typing import _EntityType 

54 from ._typing import _ORMColumnExprArgument 

55 from .descriptor_props import _CC 

56 from .descriptor_props import _CompositeAttrType 

57 from .interfaces import PropComparator 

58 from .mapper import Mapper 

59 from .query import Query 

60 from .relationships import _LazyLoadArgumentType 

61 from .relationships import _ORMColCollectionArgument 

62 from .relationships import _ORMOrderByArgument 

63 from .relationships import _RelationshipJoinConditionArgument 

64 from .relationships import ORMBackrefArgument 

65 from .session import _SessionBind 

66 from ..sql._typing import _AutoIncrementType 

67 from ..sql._typing import _ColumnExpressionArgument 

68 from ..sql._typing import _FromClauseArgument 

69 from ..sql._typing import _InfoType 

70 from ..sql._typing import _OnClauseArgument 

71 from ..sql._typing import _TypeEngineArgument 

72 from ..sql.elements import ColumnElement 

73 from ..sql.schema import _ServerDefaultArgument 

74 from ..sql.schema import _ServerOnUpdateArgument 

75 from ..sql.selectable import Alias 

76 from ..sql.selectable import Subquery 

77 

78 

79_T = typing.TypeVar("_T") 

80 

81 

82@util.deprecated( 

83 "1.4", 

84 "The :class:`.AliasOption` object is not necessary " 

85 "for entities to be matched up to a query that is established " 

86 "via :meth:`.Query.from_statement` and now does nothing.", 

87 enable_warnings=False, # AliasOption itself warns 

88) 

89def contains_alias(alias: Union[Alias, Subquery]) -> AliasOption: 

90 r"""Return a :class:`.MapperOption` that will indicate to the 

91 :class:`_query.Query` 

92 that the main table has been aliased. 

93 

94 """ 

95 return AliasOption(alias) 

96 

97 

98def mapped_column( 

99 __name_pos: Optional[ 

100 Union[str, _TypeEngineArgument[Any], SchemaEventTarget] 

101 ] = None, 

102 __type_pos: Optional[ 

103 Union[_TypeEngineArgument[Any], SchemaEventTarget] 

104 ] = None, 

105 *args: SchemaEventTarget, 

106 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

107 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

108 default: Optional[Any] = _NoArg.NO_ARG, 

109 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

110 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

111 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

112 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

113 nullable: Optional[ 

114 Union[bool, Literal[SchemaConst.NULL_UNSPECIFIED]] 

115 ] = SchemaConst.NULL_UNSPECIFIED, 

116 primary_key: Optional[bool] = False, 

117 deferred: Union[_NoArg, bool] = _NoArg.NO_ARG, 

118 deferred_group: Optional[str] = None, 

119 deferred_raiseload: Optional[bool] = None, 

120 use_existing_column: bool = False, 

121 name: Optional[str] = None, 

122 type_: Optional[_TypeEngineArgument[Any]] = None, 

123 autoincrement: _AutoIncrementType = "auto", 

124 doc: Optional[str] = None, 

125 key: Optional[str] = None, 

126 index: Optional[bool] = None, 

127 unique: Optional[bool] = None, 

128 info: Optional[_InfoType] = None, 

129 onupdate: Optional[Any] = None, 

130 insert_default: Optional[Any] = _NoArg.NO_ARG, 

131 server_default: Optional[_ServerDefaultArgument] = None, 

132 server_onupdate: Optional[_ServerOnUpdateArgument] = None, 

133 active_history: bool = False, 

134 quote: Optional[bool] = None, 

135 system: bool = False, 

136 comment: Optional[str] = None, 

137 sort_order: Union[_NoArg, int] = _NoArg.NO_ARG, 

138 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

139 **kw: Any, 

140) -> MappedColumn[Any]: 

141 r"""declare a new ORM-mapped :class:`_schema.Column` construct 

142 for use within :ref:`Declarative Table <orm_declarative_table>` 

143 configuration. 

144 

145 The :func:`_orm.mapped_column` function provides an ORM-aware and 

146 Python-typing-compatible construct which is used with 

147 :ref:`declarative <orm_declarative_mapping>` mappings to indicate an 

148 attribute that's mapped to a Core :class:`_schema.Column` object. It 

149 provides the equivalent feature as mapping an attribute to a 

150 :class:`_schema.Column` object directly when using Declarative, 

151 specifically when using :ref:`Declarative Table <orm_declarative_table>` 

152 configuration. 

153 

154 .. versionadded:: 2.0 

155 

156 :func:`_orm.mapped_column` is normally used with explicit typing along with 

157 the :class:`_orm.Mapped` annotation type, where it can derive the SQL 

158 type and nullability for the column based on what's present within the 

159 :class:`_orm.Mapped` annotation. It also may be used without annotations 

160 as a drop-in replacement for how :class:`_schema.Column` is used in 

161 Declarative mappings in SQLAlchemy 1.x style. 

162 

163 For usage examples of :func:`_orm.mapped_column`, see the documentation 

164 at :ref:`orm_declarative_table`. 

165 

166 .. seealso:: 

167 

168 :ref:`orm_declarative_table` - complete documentation 

169 

170 :ref:`whatsnew_20_orm_declarative_typing` - migration notes for 

171 Declarative mappings using 1.x style mappings 

172 

173 :param __name: String name to give to the :class:`_schema.Column`. This 

174 is an optional, positional only argument that if present must be the 

175 first positional argument passed. If omitted, the attribute name to 

176 which the :func:`_orm.mapped_column` is mapped will be used as the SQL 

177 column name. 

178 :param __type: :class:`_types.TypeEngine` type or instance which will 

179 indicate the datatype to be associated with the :class:`_schema.Column`. 

180 This is an optional, positional-only argument that if present must 

181 immediately follow the ``__name`` parameter if present also, or otherwise 

182 be the first positional parameter. If omitted, the ultimate type for 

183 the column may be derived either from the annotated type, or if a 

184 :class:`_schema.ForeignKey` is present, from the datatype of the 

185 referenced column. 

186 :param \*args: Additional positional arguments include constructs such 

187 as :class:`_schema.ForeignKey`, :class:`_schema.CheckConstraint`, 

188 and :class:`_schema.Identity`, which are passed through to the constructed 

189 :class:`_schema.Column`. 

190 :param nullable: Optional bool, whether the column should be "NULL" or 

191 "NOT NULL". If omitted, the nullability is derived from the type 

192 annotation based on whether or not ``typing.Optional`` (or its equivalent) 

193 is present. ``nullable`` defaults to ``True`` otherwise for non-primary 

194 key columns, and ``False`` for primary key columns. 

195 :param primary_key: optional bool, indicates the :class:`_schema.Column` 

196 would be part of the table's primary key or not. 

197 :param deferred: Optional bool - this keyword argument is consumed by the 

198 ORM declarative process, and is not part of the :class:`_schema.Column` 

199 itself; instead, it indicates that this column should be "deferred" for 

200 loading as though mapped by :func:`_orm.deferred`. 

201 

202 .. seealso:: 

203 

204 :ref:`orm_queryguide_deferred_declarative` 

205 

206 :param deferred_group: Implies :paramref:`_orm.mapped_column.deferred` 

207 to ``True``, and set the :paramref:`_orm.deferred.group` parameter. 

208 

209 .. seealso:: 

210 

211 :ref:`orm_queryguide_deferred_group` 

212 

213 :param deferred_raiseload: Implies :paramref:`_orm.mapped_column.deferred` 

214 to ``True``, and set the :paramref:`_orm.deferred.raiseload` parameter. 

215 

216 .. seealso:: 

217 

218 :ref:`orm_queryguide_deferred_raiseload` 

219 

220 :param use_existing_column: if True, will attempt to locate the given 

221 column name on an inherited superclass (typically single inheriting 

222 superclass), and if present, will not produce a new column, mapping 

223 to the superclass column as though it were omitted from this class. 

224 This is used for mixins that add new columns to an inherited superclass. 

225 

226 .. seealso:: 

227 

228 :ref:`orm_inheritance_column_conflicts` 

229 

230 .. versionadded:: 2.0.0b4 

231 

232 :param default: Passed directly to the 

233 :paramref:`_schema.Column.default` parameter if the 

234 :paramref:`_orm.mapped_column.insert_default` parameter is not present. 

235 Additionally, when used with :ref:`orm_declarative_native_dataclasses`, 

236 indicates a default Python value that should be applied to the keyword 

237 constructor within the generated ``__init__()`` method. 

238 

239 Note that in the case of dataclass generation when 

240 :paramref:`_orm.mapped_column.insert_default` is not present, this means 

241 the :paramref:`_orm.mapped_column.default` value is used in **two** 

242 places, both the ``__init__()`` method as well as the 

243 :paramref:`_schema.Column.default` parameter. While this behavior may 

244 change in a future release, for the moment this tends to "work out"; a 

245 default of ``None`` will mean that the :class:`_schema.Column` gets no 

246 default generator, whereas a default that refers to a non-``None`` Python 

247 or SQL expression value will be assigned up front on the object when 

248 ``__init__()`` is called, which is the same value that the Core 

249 :class:`_sql.Insert` construct would use in any case, leading to the same 

250 end result. 

251 

252 .. note:: When using Core level column defaults that are callables to 

253 be interpreted by the underlying :class:`_schema.Column` in conjunction 

254 with :ref:`ORM-mapped dataclasses 

255 <orm_declarative_native_dataclasses>`, especially those that are 

256 :ref:`context-aware default functions <context_default_functions>`, 

257 **the** :paramref:`_orm.mapped_column.insert_default` **parameter must 

258 be used instead**. This is necessary to disambiguate the callable from 

259 being interpreted as a dataclass level default. 

260 

261 .. seealso:: 

262 

263 :ref:`defaults_default_factory_insert_default` 

264 

265 :paramref:`_orm.mapped_column.insert_default` 

266 

267 :paramref:`_orm.mapped_column.default_factory` 

268 

269 :param insert_default: Passed directly to the 

270 :paramref:`_schema.Column.default` parameter; will supersede the value 

271 of :paramref:`_orm.mapped_column.default` when present, however 

272 :paramref:`_orm.mapped_column.default` will always apply to the 

273 constructor default for a dataclasses mapping. 

274 

275 .. seealso:: 

276 

277 :ref:`defaults_default_factory_insert_default` 

278 

279 :paramref:`_orm.mapped_column.default` 

280 

281 :paramref:`_orm.mapped_column.default_factory` 

282 

283 :param sort_order: An integer that indicates how this mapped column 

284 should be sorted compared to the others when the ORM is creating a 

285 :class:`_schema.Table`. Among mapped columns that have the same 

286 value the default ordering is used, placing first the mapped columns 

287 defined in the main class, then the ones in the super classes. 

288 Defaults to 0. The sort is ascending. 

289 

290 .. versionadded:: 2.0.4 

291 

292 :param active_history=False: 

293 

294 When ``True``, indicates that the "previous" value for a 

295 scalar attribute should be loaded when replaced, if not 

296 already loaded. Normally, history tracking logic for 

297 simple non-primary-key scalar values only needs to be 

298 aware of the "new" value in order to perform a flush. This 

299 flag is available for applications that make use of 

300 :func:`.attributes.get_history` or :meth:`.Session.is_modified` 

301 which also need to know the "previous" value of the attribute. 

302 

303 .. versionadded:: 2.0.10 

304 

305 

306 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

307 specifies if the mapped attribute should be part of the ``__init__()`` 

308 method as generated by the dataclass process. 

309 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

310 specifies if the mapped attribute should be part of the ``__repr__()`` 

311 method as generated by the dataclass process. 

312 :param default_factory: Specific to 

313 :ref:`orm_declarative_native_dataclasses`, 

314 specifies a default-value generation function that will take place 

315 as part of the ``__init__()`` 

316 method as generated by the dataclass process. 

317 

318 .. seealso:: 

319 

320 :ref:`defaults_default_factory_insert_default` 

321 

322 :paramref:`_orm.mapped_column.default` 

323 

324 :paramref:`_orm.mapped_column.insert_default` 

325 

326 :param compare: Specific to 

327 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

328 should be included in comparison operations when generating the 

329 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

330 

331 .. versionadded:: 2.0.0b4 

332 

333 :param kw_only: Specific to 

334 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

335 should be marked as keyword-only when generating the ``__init__()``. 

336 

337 :param hash: Specific to 

338 :ref:`orm_declarative_native_dataclasses`, controls if this field 

339 is included when generating the ``__hash__()`` method for the mapped 

340 class. 

341 

342 .. versionadded:: 2.0.36 

343 

344 :param dataclass_metadata: Specific to 

345 :ref:`orm_declarative_native_dataclasses`, supplies metadata 

346 to be attached to the generated dataclass field. 

347 

348 .. versionadded:: 2.0.42 

349 

350 :param \**kw: All remaining keyword arguments are passed through to the 

351 constructor for the :class:`_schema.Column`. 

352 

353 """ 

354 

355 return MappedColumn( 

356 __name_pos, 

357 __type_pos, 

358 *args, 

359 name=name, 

360 type_=type_, 

361 autoincrement=autoincrement, 

362 insert_default=insert_default, 

363 attribute_options=_AttributeOptions( 

364 init, 

365 repr, 

366 default, 

367 default_factory, 

368 compare, 

369 kw_only, 

370 hash, 

371 dataclass_metadata, 

372 ), 

373 doc=doc, 

374 key=key, 

375 index=index, 

376 unique=unique, 

377 info=info, 

378 active_history=active_history, 

379 nullable=nullable, 

380 onupdate=onupdate, 

381 primary_key=primary_key, 

382 server_default=server_default, 

383 server_onupdate=server_onupdate, 

384 use_existing_column=use_existing_column, 

385 quote=quote, 

386 comment=comment, 

387 system=system, 

388 deferred=deferred, 

389 deferred_group=deferred_group, 

390 deferred_raiseload=deferred_raiseload, 

391 sort_order=sort_order, 

392 **kw, 

393 ) 

394 

395 

396def orm_insert_sentinel( 

397 name: Optional[str] = None, 

398 type_: Optional[_TypeEngineArgument[Any]] = None, 

399 *, 

400 default: Optional[Any] = None, 

401 omit_from_statements: bool = True, 

402) -> MappedColumn[Any]: 

403 """Provides a surrogate :func:`_orm.mapped_column` that generates 

404 a so-called :term:`sentinel` column, allowing efficient bulk 

405 inserts with deterministic RETURNING sorting for tables that don't 

406 otherwise have qualifying primary key configurations. 

407 

408 Use of :func:`_orm.orm_insert_sentinel` is analogous to the use of the 

409 :func:`_schema.insert_sentinel` construct within a Core 

410 :class:`_schema.Table` construct. 

411 

412 Guidelines for adding this construct to a Declarative mapped class 

413 are the same as that of the :func:`_schema.insert_sentinel` construct; 

414 the database table itself also needs to have a column with this name 

415 present. 

416 

417 For background on how this object is used, see the section 

418 :ref:`engine_insertmanyvalues_sentinel_columns` as part of the 

419 section :ref:`engine_insertmanyvalues`. 

420 

421 .. seealso:: 

422 

423 :func:`_schema.insert_sentinel` 

424 

425 :ref:`engine_insertmanyvalues` 

426 

427 :ref:`engine_insertmanyvalues_sentinel_columns` 

428 

429 

430 .. versionadded:: 2.0.10 

431 

432 """ 

433 

434 return mapped_column( 

435 name=name, 

436 default=( 

437 default if default is not None else _InsertSentinelColumnDefault() 

438 ), 

439 _omit_from_statements=omit_from_statements, 

440 insert_sentinel=True, 

441 use_existing_column=True, 

442 nullable=True, 

443 ) 

444 

445 

446@util.deprecated_params( 

447 **{ 

448 arg: ( 

449 "2.0", 

450 f"The :paramref:`_orm.column_property.{arg}` parameter is " 

451 "deprecated for :func:`_orm.column_property`. This parameter " 

452 "applies to a writeable-attribute in a Declarative Dataclasses " 

453 "configuration only, and :func:`_orm.column_property` is treated " 

454 "as a read-only attribute in this context.", 

455 ) 

456 for arg in ("init", "kw_only", "default", "default_factory") 

457 } 

458) 

459def column_property( 

460 column: _ORMColumnExprArgument[_T], 

461 *additional_columns: _ORMColumnExprArgument[Any], 

462 group: Optional[str] = None, 

463 deferred: bool = False, 

464 raiseload: bool = False, 

465 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

466 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

467 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

468 default: Optional[Any] = _NoArg.NO_ARG, 

469 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

470 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

471 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

472 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

473 active_history: bool = False, 

474 expire_on_flush: bool = True, 

475 info: Optional[_InfoType] = None, 

476 doc: Optional[str] = None, 

477 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

478) -> MappedSQLExpression[_T]: 

479 r"""Provide a column-level property for use with a mapping. 

480 

481 With Declarative mappings, :func:`_orm.column_property` is used to 

482 map read-only SQL expressions to a mapped class. 

483 

484 When using Imperative mappings, :func:`_orm.column_property` also 

485 takes on the role of mapping table columns with additional features. 

486 When using fully Declarative mappings, the :func:`_orm.mapped_column` 

487 construct should be used for this purpose. 

488 

489 With Declarative Dataclass mappings, :func:`_orm.column_property` 

490 is considered to be **read only**, and will not be included in the 

491 Dataclass ``__init__()`` constructor. 

492 

493 The :func:`_orm.column_property` function returns an instance of 

494 :class:`.ColumnProperty`. 

495 

496 .. seealso:: 

497 

498 :ref:`mapper_column_property_sql_expressions` - general use of 

499 :func:`_orm.column_property` to map SQL expressions 

500 

501 :ref:`orm_imperative_table_column_options` - usage of 

502 :func:`_orm.column_property` with Imperative Table mappings to apply 

503 additional options to a plain :class:`_schema.Column` object 

504 

505 :param \*cols: 

506 list of Column objects to be mapped. 

507 

508 :param active_history=False: 

509 

510 Used only for Imperative Table mappings, or legacy-style Declarative 

511 mappings (i.e. which have not been upgraded to 

512 :func:`_orm.mapped_column`), for column-based attributes that are 

513 expected to be writeable; use :func:`_orm.mapped_column` with 

514 :paramref:`_orm.mapped_column.active_history` for Declarative mappings. 

515 See that parameter for functional details. 

516 

517 :param comparator_factory: a class which extends 

518 :class:`.ColumnProperty.Comparator` which provides custom SQL 

519 clause generation for comparison operations. 

520 

521 :param group: 

522 a group name for this property when marked as deferred. 

523 

524 :param deferred: 

525 when True, the column property is "deferred", meaning that 

526 it does not load immediately, and is instead loaded when the 

527 attribute is first accessed on an instance. See also 

528 :func:`~sqlalchemy.orm.deferred`. 

529 

530 :param doc: 

531 optional string that will be applied as the doc on the 

532 class-bound descriptor. 

533 

534 :param expire_on_flush=True: 

535 Disable expiry on flush. A column_property() which refers 

536 to a SQL expression (and not a single table-bound column) 

537 is considered to be a "read only" property; populating it 

538 has no effect on the state of data, and it can only return 

539 database state. For this reason a column_property()'s value 

540 is expired whenever the parent object is involved in a 

541 flush, that is, has any kind of "dirty" state within a flush. 

542 Setting this parameter to ``False`` will have the effect of 

543 leaving any existing value present after the flush proceeds. 

544 Note that the :class:`.Session` with default expiration 

545 settings still expires 

546 all attributes after a :meth:`.Session.commit` call, however. 

547 

548 :param info: Optional data dictionary which will be populated into the 

549 :attr:`.MapperProperty.info` attribute of this object. 

550 

551 :param raiseload: if True, indicates the column should raise an error 

552 when undeferred, rather than loading the value. This can be 

553 altered at query time by using the :func:`.deferred` option with 

554 raiseload=False. 

555 

556 .. versionadded:: 1.4 

557 

558 .. seealso:: 

559 

560 :ref:`orm_queryguide_deferred_raiseload` 

561 

562 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

563 specifies if the mapped attribute should be part of the ``__init__()`` 

564 method as generated by the dataclass process. 

565 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

566 specifies if the mapped attribute should be part of the ``__repr__()`` 

567 method as generated by the dataclass process. 

568 :param default_factory: Specific to 

569 :ref:`orm_declarative_native_dataclasses`, 

570 specifies a default-value generation function that will take place 

571 as part of the ``__init__()`` 

572 method as generated by the dataclass process. 

573 

574 .. seealso:: 

575 

576 :ref:`defaults_default_factory_insert_default` 

577 

578 :paramref:`_orm.mapped_column.default` 

579 

580 :paramref:`_orm.mapped_column.insert_default` 

581 

582 :param compare: Specific to 

583 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

584 should be included in comparison operations when generating the 

585 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

586 

587 .. versionadded:: 2.0.0b4 

588 

589 :param kw_only: Specific to 

590 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

591 should be marked as keyword-only when generating the ``__init__()``. 

592 

593 :param hash: Specific to 

594 :ref:`orm_declarative_native_dataclasses`, controls if this field 

595 is included when generating the ``__hash__()`` method for the mapped 

596 class. 

597 

598 .. versionadded:: 2.0.36 

599 

600 :param dataclass_metadata: Specific to 

601 :ref:`orm_declarative_native_dataclasses`, supplies metadata 

602 to be attached to the generated dataclass field. 

603 

604 .. versionadded:: 2.0.42 

605 

606 """ 

607 return MappedSQLExpression( 

608 column, 

609 *additional_columns, 

610 attribute_options=_AttributeOptions( 

611 False if init is _NoArg.NO_ARG else init, 

612 repr, 

613 default, 

614 default_factory, 

615 compare, 

616 kw_only, 

617 hash, 

618 dataclass_metadata, 

619 ), 

620 group=group, 

621 deferred=deferred, 

622 raiseload=raiseload, 

623 comparator_factory=comparator_factory, 

624 active_history=active_history, 

625 expire_on_flush=expire_on_flush, 

626 info=info, 

627 doc=doc, 

628 _assume_readonly_dc_attributes=True, 

629 ) 

630 

631 

632@overload 

633def composite( 

634 _class_or_attr: _CompositeAttrType[Any], 

635 *attrs: _CompositeAttrType[Any], 

636 group: Optional[str] = None, 

637 deferred: bool = False, 

638 raiseload: bool = False, 

639 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

640 active_history: bool = False, 

641 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

642 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

643 default: Optional[Any] = _NoArg.NO_ARG, 

644 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

645 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

646 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

647 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

648 info: Optional[_InfoType] = None, 

649 doc: Optional[str] = None, 

650 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

651 **__kw: Any, 

652) -> Composite[Any]: ... 

653 

654 

655@overload 

656def composite( 

657 _class_or_attr: Type[_CC], 

658 *attrs: _CompositeAttrType[Any], 

659 group: Optional[str] = None, 

660 deferred: bool = False, 

661 raiseload: bool = False, 

662 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

663 active_history: bool = False, 

664 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

665 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

666 default: Optional[Any] = _NoArg.NO_ARG, 

667 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

668 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

669 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

670 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

671 info: Optional[_InfoType] = None, 

672 doc: Optional[str] = None, 

673 **__kw: Any, 

674) -> Composite[_CC]: ... 

675 

676 

677@overload 

678def composite( 

679 _class_or_attr: Callable[..., _CC], 

680 *attrs: _CompositeAttrType[Any], 

681 group: Optional[str] = None, 

682 deferred: bool = False, 

683 raiseload: bool = False, 

684 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

685 active_history: bool = False, 

686 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

687 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

688 default: Optional[Any] = _NoArg.NO_ARG, 

689 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

690 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

691 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

692 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

693 info: Optional[_InfoType] = None, 

694 doc: Optional[str] = None, 

695 **__kw: Any, 

696) -> Composite[_CC]: ... 

697 

698 

699def composite( 

700 _class_or_attr: Union[ 

701 None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any] 

702 ] = None, 

703 *attrs: _CompositeAttrType[Any], 

704 group: Optional[str] = None, 

705 deferred: bool = False, 

706 raiseload: bool = False, 

707 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

708 active_history: bool = False, 

709 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

710 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

711 default: Optional[Any] = _NoArg.NO_ARG, 

712 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

713 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

714 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

715 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

716 info: Optional[_InfoType] = None, 

717 doc: Optional[str] = None, 

718 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

719 **__kw: Any, 

720) -> Composite[Any]: 

721 r"""Return a composite column-based property for use with a Mapper. 

722 

723 See the mapping documentation section :ref:`mapper_composite` for a 

724 full usage example. 

725 

726 The :class:`.MapperProperty` returned by :func:`.composite` 

727 is the :class:`.Composite`. 

728 

729 :param class\_: 

730 The "composite type" class, or any classmethod or callable which 

731 will produce a new instance of the composite object given the 

732 column values in order. 

733 

734 :param \*attrs: 

735 List of elements to be mapped, which may include: 

736 

737 * :class:`_schema.Column` objects 

738 * :func:`_orm.mapped_column` constructs 

739 * string names of other attributes on the mapped class, which may be 

740 any other SQL or object-mapped attribute. This can for 

741 example allow a composite that refers to a many-to-one relationship 

742 

743 :param active_history=False: 

744 When ``True``, indicates that the "previous" value for a 

745 scalar attribute should be loaded when replaced, if not 

746 already loaded. See the same flag on :func:`.column_property`. 

747 

748 :param group: 

749 A group name for this property when marked as deferred. 

750 

751 :param deferred: 

752 When True, the column property is "deferred", meaning that it does 

753 not load immediately, and is instead loaded when the attribute is 

754 first accessed on an instance. See also 

755 :func:`~sqlalchemy.orm.deferred`. 

756 

757 :param comparator_factory: a class which extends 

758 :class:`.Composite.Comparator` which provides custom SQL 

759 clause generation for comparison operations. 

760 

761 :param doc: 

762 optional string that will be applied as the doc on the 

763 class-bound descriptor. 

764 

765 :param info: Optional data dictionary which will be populated into the 

766 :attr:`.MapperProperty.info` attribute of this object. 

767 

768 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

769 specifies if the mapped attribute should be part of the ``__init__()`` 

770 method as generated by the dataclass process. 

771 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

772 specifies if the mapped attribute should be part of the ``__repr__()`` 

773 method as generated by the dataclass process. 

774 :param default_factory: Specific to 

775 :ref:`orm_declarative_native_dataclasses`, 

776 specifies a default-value generation function that will take place 

777 as part of the ``__init__()`` 

778 method as generated by the dataclass process. 

779 

780 :param compare: Specific to 

781 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

782 should be included in comparison operations when generating the 

783 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

784 

785 .. versionadded:: 2.0.0b4 

786 

787 :param kw_only: Specific to 

788 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

789 should be marked as keyword-only when generating the ``__init__()``. 

790 

791 :param hash: Specific to 

792 :ref:`orm_declarative_native_dataclasses`, controls if this field 

793 is included when generating the ``__hash__()`` method for the mapped 

794 class. 

795 

796 .. versionadded:: 2.0.36 

797 

798 :param dataclass_metadata: Specific to 

799 :ref:`orm_declarative_native_dataclasses`, supplies metadata 

800 to be attached to the generated dataclass field. 

801 

802 .. versionadded:: 2.0.42 

803 

804 """ 

805 if __kw: 

806 raise _no_kw() 

807 

808 return Composite( 

809 _class_or_attr, 

810 *attrs, 

811 attribute_options=_AttributeOptions( 

812 init, 

813 repr, 

814 default, 

815 default_factory, 

816 compare, 

817 kw_only, 

818 hash, 

819 dataclass_metadata, 

820 ), 

821 group=group, 

822 deferred=deferred, 

823 raiseload=raiseload, 

824 comparator_factory=comparator_factory, 

825 active_history=active_history, 

826 info=info, 

827 doc=doc, 

828 ) 

829 

830 

831def with_loader_criteria( 

832 entity_or_base: _EntityType[Any], 

833 where_criteria: Union[ 

834 _ColumnExpressionArgument[bool], 

835 Callable[[Any], _ColumnExpressionArgument[bool]], 

836 ], 

837 loader_only: bool = False, 

838 include_aliases: bool = False, 

839 propagate_to_loaders: bool = True, 

840 track_closure_variables: bool = True, 

841) -> LoaderCriteriaOption: 

842 """Add additional WHERE criteria to the load for all occurrences of 

843 a particular entity. 

844 

845 .. versionadded:: 1.4 

846 

847 The :func:`_orm.with_loader_criteria` option is intended to add 

848 limiting criteria to a particular kind of entity in a query, 

849 **globally**, meaning it will apply to the entity as it appears 

850 in the SELECT query as well as within any subqueries, join 

851 conditions, and relationship loads, including both eager and lazy 

852 loaders, without the need for it to be specified in any particular 

853 part of the query. The rendering logic uses the same system used by 

854 single table inheritance to ensure a certain discriminator is applied 

855 to a table. 

856 

857 E.g., using :term:`2.0-style` queries, we can limit the way the 

858 ``User.addresses`` collection is loaded, regardless of the kind 

859 of loading used:: 

860 

861 from sqlalchemy.orm import with_loader_criteria 

862 

863 stmt = select(User).options( 

864 selectinload(User.addresses), 

865 with_loader_criteria(Address, Address.email_address != "foo"), 

866 ) 

867 

868 Above, the "selectinload" for ``User.addresses`` will apply the 

869 given filtering criteria to the WHERE clause. 

870 

871 Another example, where the filtering will be applied to the 

872 ON clause of the join, in this example using :term:`1.x style` 

873 queries:: 

874 

875 q = ( 

876 session.query(User) 

877 .outerjoin(User.addresses) 

878 .options(with_loader_criteria(Address, Address.email_address != "foo")) 

879 ) 

880 

881 The primary purpose of :func:`_orm.with_loader_criteria` is to use 

882 it in the :meth:`_orm.SessionEvents.do_orm_execute` event handler 

883 to ensure that all occurrences of a particular entity are filtered 

884 in a certain way, such as filtering for access control roles. It 

885 also can be used to apply criteria to relationship loads. In the 

886 example below, we can apply a certain set of rules to all queries 

887 emitted by a particular :class:`_orm.Session`:: 

888 

889 session = Session(bind=engine) 

890 

891 

892 @event.listens_for("do_orm_execute", session) 

893 def _add_filtering_criteria(execute_state): 

894 

895 if ( 

896 execute_state.is_select 

897 and not execute_state.is_column_load 

898 and not execute_state.is_relationship_load 

899 ): 

900 execute_state.statement = execute_state.statement.options( 

901 with_loader_criteria( 

902 SecurityRole, 

903 lambda cls: cls.role.in_(["some_role"]), 

904 include_aliases=True, 

905 ) 

906 ) 

907 

908 In the above example, the :meth:`_orm.SessionEvents.do_orm_execute` 

909 event will intercept all queries emitted using the 

910 :class:`_orm.Session`. For those queries which are SELECT statements 

911 and are not attribute or relationship loads a custom 

912 :func:`_orm.with_loader_criteria` option is added to the query. The 

913 :func:`_orm.with_loader_criteria` option will be used in the given 

914 statement and will also be automatically propagated to all relationship 

915 loads that descend from this query. 

916 

917 The criteria argument given is a ``lambda`` that accepts a ``cls`` 

918 argument. The given class will expand to include all mapped subclass 

919 and need not itself be a mapped class. 

920 

921 .. tip:: 

922 

923 When using :func:`_orm.with_loader_criteria` option in 

924 conjunction with the :func:`_orm.contains_eager` loader option, 

925 it's important to note that :func:`_orm.with_loader_criteria` only 

926 affects the part of the query that determines what SQL is rendered 

927 in terms of the WHERE and FROM clauses. The 

928 :func:`_orm.contains_eager` option does not affect the rendering of 

929 the SELECT statement outside of the columns clause, so does not have 

930 any interaction with the :func:`_orm.with_loader_criteria` option. 

931 However, the way things "work" is that :func:`_orm.contains_eager` 

932 is meant to be used with a query that is already selecting from the 

933 additional entities in some way, where 

934 :func:`_orm.with_loader_criteria` can apply it's additional 

935 criteria. 

936 

937 In the example below, assuming a mapping relationship as 

938 ``A -> A.bs -> B``, the given :func:`_orm.with_loader_criteria` 

939 option will affect the way in which the JOIN is rendered:: 

940 

941 stmt = ( 

942 select(A) 

943 .join(A.bs) 

944 .options(contains_eager(A.bs), with_loader_criteria(B, B.flag == 1)) 

945 ) 

946 

947 Above, the given :func:`_orm.with_loader_criteria` option will 

948 affect the ON clause of the JOIN that is specified by 

949 ``.join(A.bs)``, so is applied as expected. The 

950 :func:`_orm.contains_eager` option has the effect that columns from 

951 ``B`` are added to the columns clause: 

952 

953 .. sourcecode:: sql 

954 

955 SELECT 

956 b.id, b.a_id, b.data, b.flag, 

957 a.id AS id_1, 

958 a.data AS data_1 

959 FROM a JOIN b ON a.id = b.a_id AND b.flag = :flag_1 

960 

961 

962 The use of the :func:`_orm.contains_eager` option within the above 

963 statement has no effect on the behavior of the 

964 :func:`_orm.with_loader_criteria` option. If the 

965 :func:`_orm.contains_eager` option were omitted, the SQL would be 

966 the same as regards the FROM and WHERE clauses, where 

967 :func:`_orm.with_loader_criteria` continues to add its criteria to 

968 the ON clause of the JOIN. The addition of 

969 :func:`_orm.contains_eager` only affects the columns clause, in that 

970 additional columns against ``b`` are added which are then consumed 

971 by the ORM to produce ``B`` instances. 

972 

973 .. warning:: The use of a lambda inside of the call to 

974 :func:`_orm.with_loader_criteria` is only invoked **once per unique 

975 class**. Custom functions should not be invoked within this lambda. 

976 See :ref:`engine_lambda_caching` for an overview of the "lambda SQL" 

977 feature, which is for advanced use only. 

978 

979 :param entity_or_base: a mapped class, or a class that is a super 

980 class of a particular set of mapped classes, to which the rule 

981 will apply. 

982 

983 :param where_criteria: a Core SQL expression that applies limiting 

984 criteria. This may also be a "lambda:" or Python function that 

985 accepts a target class as an argument, when the given class is 

986 a base with many different mapped subclasses. 

987 

988 .. note:: To support pickling, use a module-level Python function to 

989 produce the SQL expression instead of a lambda or a fixed SQL 

990 expression, which tend to not be picklable. 

991 

992 :param include_aliases: if True, apply the rule to :func:`_orm.aliased` 

993 constructs as well. 

994 

995 :param propagate_to_loaders: defaults to True, apply to relationship 

996 loaders such as lazy loaders. This indicates that the 

997 option object itself including SQL expression is carried along with 

998 each loaded instance. Set to ``False`` to prevent the object from 

999 being assigned to individual instances. 

1000 

1001 

1002 .. seealso:: 

1003 

1004 :ref:`examples_session_orm_events` - includes examples of using 

1005 :func:`_orm.with_loader_criteria`. 

1006 

1007 :ref:`do_orm_execute_global_criteria` - basic example on how to 

1008 combine :func:`_orm.with_loader_criteria` with the 

1009 :meth:`_orm.SessionEvents.do_orm_execute` event. 

1010 

1011 :param track_closure_variables: when False, closure variables inside 

1012 of a lambda expression will not be used as part of 

1013 any cache key. This allows more complex expressions to be used 

1014 inside of a lambda expression but requires that the lambda ensures 

1015 it returns the identical SQL every time given a particular class. 

1016 

1017 .. versionadded:: 1.4.0b2 

1018 

1019 """ # noqa: E501 

1020 return LoaderCriteriaOption( 

1021 entity_or_base, 

1022 where_criteria, 

1023 loader_only, 

1024 include_aliases, 

1025 propagate_to_loaders, 

1026 track_closure_variables, 

1027 ) 

1028 

1029 

1030def relationship( 

1031 argument: Optional[_RelationshipArgumentType[Any]] = None, 

1032 secondary: Optional[_RelationshipSecondaryArgument] = None, 

1033 *, 

1034 uselist: Optional[bool] = None, 

1035 collection_class: Optional[ 

1036 Union[Type[Collection[Any]], Callable[[], Collection[Any]]] 

1037 ] = None, 

1038 primaryjoin: Optional[_RelationshipJoinConditionArgument] = None, 

1039 secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None, 

1040 back_populates: Optional[str] = None, 

1041 order_by: _ORMOrderByArgument = False, 

1042 backref: Optional[ORMBackrefArgument] = None, 

1043 overlaps: Optional[str] = None, 

1044 post_update: bool = False, 

1045 cascade: str = "save-update, merge", 

1046 viewonly: bool = False, 

1047 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1048 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

1049 default: Union[_NoArg, _T] = _NoArg.NO_ARG, 

1050 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

1051 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1052 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1053 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

1054 lazy: _LazyLoadArgumentType = "select", 

1055 passive_deletes: Union[Literal["all"], bool] = False, 

1056 passive_updates: bool = True, 

1057 active_history: bool = False, 

1058 enable_typechecks: bool = True, 

1059 foreign_keys: Optional[_ORMColCollectionArgument] = None, 

1060 remote_side: Optional[_ORMColCollectionArgument] = None, 

1061 join_depth: Optional[int] = None, 

1062 comparator_factory: Optional[ 

1063 Type[RelationshipProperty.Comparator[Any]] 

1064 ] = None, 

1065 single_parent: bool = False, 

1066 innerjoin: bool = False, 

1067 distinct_target_key: Optional[bool] = None, 

1068 load_on_pending: bool = False, 

1069 query_class: Optional[Type[Query[Any]]] = None, 

1070 info: Optional[_InfoType] = None, 

1071 omit_join: Literal[None, False] = None, 

1072 sync_backref: Optional[bool] = None, 

1073 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

1074 **kw: Any, 

1075) -> _RelationshipDeclared[Any]: 

1076 """Provide a relationship between two mapped classes. 

1077 

1078 This corresponds to a parent-child or associative table relationship. 

1079 The constructed class is an instance of :class:`.Relationship`. 

1080 

1081 .. seealso:: 

1082 

1083 :ref:`tutorial_orm_related_objects` - tutorial introduction 

1084 to :func:`_orm.relationship` in the :ref:`unified_tutorial` 

1085 

1086 :ref:`relationship_config_toplevel` - narrative documentation 

1087 

1088 :param argument: 

1089 This parameter refers to the class that is to be related. It 

1090 accepts several forms, including a direct reference to the target 

1091 class itself, the :class:`_orm.Mapper` instance for the target class, 

1092 a Python callable / lambda that will return a reference to the 

1093 class or :class:`_orm.Mapper` when called, and finally a string 

1094 name for the class, which will be resolved from the 

1095 :class:`_orm.registry` in use in order to locate the class, e.g.:: 

1096 

1097 class SomeClass(Base): 

1098 # ... 

1099 

1100 related = relationship("RelatedClass") 

1101 

1102 The :paramref:`_orm.relationship.argument` may also be omitted from the 

1103 :func:`_orm.relationship` construct entirely, and instead placed inside 

1104 a :class:`_orm.Mapped` annotation on the left side, which should 

1105 include a Python collection type if the relationship is expected 

1106 to be a collection, such as:: 

1107 

1108 class SomeClass(Base): 

1109 # ... 

1110 

1111 related_items: Mapped[List["RelatedItem"]] = relationship() 

1112 

1113 Or for a many-to-one or one-to-one relationship:: 

1114 

1115 class SomeClass(Base): 

1116 # ... 

1117 

1118 related_item: Mapped["RelatedItem"] = relationship() 

1119 

1120 .. seealso:: 

1121 

1122 :ref:`orm_declarative_properties` - further detail 

1123 on relationship configuration when using Declarative. 

1124 

1125 :param secondary: 

1126 For a many-to-many relationship, specifies the intermediary 

1127 table, and is typically an instance of :class:`_schema.Table`. 

1128 In less common circumstances, the argument may also be specified 

1129 as an :class:`_expression.Alias` construct, or even a 

1130 :class:`_expression.Join` construct. 

1131 

1132 :paramref:`_orm.relationship.secondary` may 

1133 also be passed as a callable function which is evaluated at 

1134 mapper initialization time. When using Declarative, it may also 

1135 be a string argument noting the name of a :class:`_schema.Table` 

1136 that is 

1137 present in the :class:`_schema.MetaData` 

1138 collection associated with the 

1139 parent-mapped :class:`_schema.Table`. 

1140 

1141 .. warning:: When passed as a Python-evaluable string, the 

1142 argument is interpreted using Python's ``eval()`` function. 

1143 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1144 See :ref:`declarative_relationship_eval` for details on 

1145 declarative evaluation of :func:`_orm.relationship` arguments. 

1146 

1147 The :paramref:`_orm.relationship.secondary` keyword argument is 

1148 typically applied in the case where the intermediary 

1149 :class:`_schema.Table` 

1150 is not otherwise expressed in any direct class mapping. If the 

1151 "secondary" table is also explicitly mapped elsewhere (e.g. as in 

1152 :ref:`association_pattern`), one should consider applying the 

1153 :paramref:`_orm.relationship.viewonly` flag so that this 

1154 :func:`_orm.relationship` 

1155 is not used for persistence operations which 

1156 may conflict with those of the association object pattern. 

1157 

1158 .. seealso:: 

1159 

1160 :ref:`relationships_many_to_many` - Reference example of "many 

1161 to many". 

1162 

1163 :ref:`self_referential_many_to_many` - Specifics on using 

1164 many-to-many in a self-referential case. 

1165 

1166 :ref:`declarative_many_to_many` - Additional options when using 

1167 Declarative. 

1168 

1169 :ref:`association_pattern` - an alternative to 

1170 :paramref:`_orm.relationship.secondary` 

1171 when composing association 

1172 table relationships, allowing additional attributes to be 

1173 specified on the association table. 

1174 

1175 :ref:`composite_secondary_join` - a lesser-used pattern which 

1176 in some cases can enable complex :func:`_orm.relationship` SQL 

1177 conditions to be used. 

1178 

1179 :param active_history=False: 

1180 When ``True``, indicates that the "previous" value for a 

1181 many-to-one reference should be loaded when replaced, if 

1182 not already loaded. Normally, history tracking logic for 

1183 simple many-to-ones only needs to be aware of the "new" 

1184 value in order to perform a flush. This flag is available 

1185 for applications that make use of 

1186 :func:`.attributes.get_history` which also need to know 

1187 the "previous" value of the attribute. 

1188 

1189 :param backref: 

1190 A reference to a string relationship name, or a :func:`_orm.backref` 

1191 construct, which will be used to automatically generate a new 

1192 :func:`_orm.relationship` on the related class, which then refers to this 

1193 one using a bi-directional :paramref:`_orm.relationship.back_populates` 

1194 configuration. 

1195 

1196 In modern Python, explicit use of :func:`_orm.relationship` 

1197 with :paramref:`_orm.relationship.back_populates` should be preferred, 

1198 as it is more robust in terms of mapper configuration as well as 

1199 more conceptually straightforward. It also integrates with 

1200 new :pep:`484` typing features introduced in SQLAlchemy 2.0 which 

1201 is not possible with dynamically generated attributes. 

1202 

1203 .. seealso:: 

1204 

1205 :ref:`relationships_backref` - notes on using 

1206 :paramref:`_orm.relationship.backref` 

1207 

1208 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`, 

1209 presents an overview of bi-directional relationship configuration 

1210 and behaviors using :paramref:`_orm.relationship.back_populates` 

1211 

1212 :func:`.backref` - allows control over :func:`_orm.relationship` 

1213 configuration when using :paramref:`_orm.relationship.backref`. 

1214 

1215 

1216 :param back_populates: 

1217 Indicates the name of a :func:`_orm.relationship` on the related 

1218 class that will be synchronized with this one. It is usually 

1219 expected that the :func:`_orm.relationship` on the related class 

1220 also refer to this one. This allows objects on both sides of 

1221 each :func:`_orm.relationship` to synchronize in-Python state 

1222 changes and also provides directives to the :term:`unit of work` 

1223 flush process how changes along these relationships should 

1224 be persisted. 

1225 

1226 .. seealso:: 

1227 

1228 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`, 

1229 presents an overview of bi-directional relationship configuration 

1230 and behaviors. 

1231 

1232 :ref:`relationship_patterns` - includes many examples of 

1233 :paramref:`_orm.relationship.back_populates`. 

1234 

1235 :paramref:`_orm.relationship.backref` - legacy form which allows 

1236 more succinct configuration, but does not support explicit typing 

1237 

1238 :param overlaps: 

1239 A string name or comma-delimited set of names of other relationships 

1240 on either this mapper, a descendant mapper, or a target mapper with 

1241 which this relationship may write to the same foreign keys upon 

1242 persistence. The only effect this has is to eliminate the 

1243 warning that this relationship will conflict with another upon 

1244 persistence. This is used for such relationships that are truly 

1245 capable of conflicting with each other on write, but the application 

1246 will ensure that no such conflicts occur. 

1247 

1248 .. versionadded:: 1.4 

1249 

1250 .. seealso:: 

1251 

1252 :ref:`error_qzyx` - usage example 

1253 

1254 :param cascade: 

1255 A comma-separated list of cascade rules which determines how 

1256 Session operations should be "cascaded" from parent to child. 

1257 This defaults to ``False``, which means the default cascade 

1258 should be used - this default cascade is ``"save-update, merge"``. 

1259 

1260 The available cascades are ``save-update``, ``merge``, 

1261 ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``. 

1262 An additional option, ``all`` indicates shorthand for 

1263 ``"save-update, merge, refresh-expire, 

1264 expunge, delete"``, and is often used as in ``"all, delete-orphan"`` 

1265 to indicate that related objects should follow along with the 

1266 parent object in all cases, and be deleted when de-associated. 

1267 

1268 .. seealso:: 

1269 

1270 :ref:`unitofwork_cascades` - Full detail on each of the available 

1271 cascade options. 

1272 

1273 :param cascade_backrefs=False: 

1274 Legacy; this flag is always False. 

1275 

1276 .. versionchanged:: 2.0 "cascade_backrefs" functionality has been 

1277 removed. 

1278 

1279 :param collection_class: 

1280 A class or callable that returns a new list-holding object. will 

1281 be used in place of a plain list for storing elements. 

1282 

1283 .. seealso:: 

1284 

1285 :ref:`custom_collections` - Introductory documentation and 

1286 examples. 

1287 

1288 :param comparator_factory: 

1289 A class which extends :class:`.Relationship.Comparator` 

1290 which provides custom SQL clause generation for comparison 

1291 operations. 

1292 

1293 .. seealso:: 

1294 

1295 :class:`.PropComparator` - some detail on redefining comparators 

1296 at this level. 

1297 

1298 :ref:`custom_comparators` - Brief intro to this feature. 

1299 

1300 

1301 :param distinct_target_key=None: 

1302 Indicate if a "subquery" eager load should apply the DISTINCT 

1303 keyword to the innermost SELECT statement. When left as ``None``, 

1304 the DISTINCT keyword will be applied in those cases when the target 

1305 columns do not comprise the full primary key of the target table. 

1306 When set to ``True``, the DISTINCT keyword is applied to the 

1307 innermost SELECT unconditionally. 

1308 

1309 It may be desirable to set this flag to False when the DISTINCT is 

1310 reducing performance of the innermost subquery beyond that of what 

1311 duplicate innermost rows may be causing. 

1312 

1313 .. seealso:: 

1314 

1315 :ref:`loading_toplevel` - includes an introduction to subquery 

1316 eager loading. 

1317 

1318 :param doc: 

1319 Docstring which will be applied to the resulting descriptor. 

1320 

1321 :param foreign_keys: 

1322 

1323 A list of columns which are to be used as "foreign key" 

1324 columns, or columns which refer to the value in a remote 

1325 column, within the context of this :func:`_orm.relationship` 

1326 object's :paramref:`_orm.relationship.primaryjoin` condition. 

1327 That is, if the :paramref:`_orm.relationship.primaryjoin` 

1328 condition of this :func:`_orm.relationship` is ``a.id == 

1329 b.a_id``, and the values in ``b.a_id`` are required to be 

1330 present in ``a.id``, then the "foreign key" column of this 

1331 :func:`_orm.relationship` is ``b.a_id``. 

1332 

1333 In normal cases, the :paramref:`_orm.relationship.foreign_keys` 

1334 parameter is **not required.** :func:`_orm.relationship` will 

1335 automatically determine which columns in the 

1336 :paramref:`_orm.relationship.primaryjoin` condition are to be 

1337 considered "foreign key" columns based on those 

1338 :class:`_schema.Column` objects that specify 

1339 :class:`_schema.ForeignKey`, 

1340 or are otherwise listed as referencing columns in a 

1341 :class:`_schema.ForeignKeyConstraint` construct. 

1342 :paramref:`_orm.relationship.foreign_keys` is only needed when: 

1343 

1344 1. There is more than one way to construct a join from the local 

1345 table to the remote table, as there are multiple foreign key 

1346 references present. Setting ``foreign_keys`` will limit the 

1347 :func:`_orm.relationship` 

1348 to consider just those columns specified 

1349 here as "foreign". 

1350 

1351 2. The :class:`_schema.Table` being mapped does not actually have 

1352 :class:`_schema.ForeignKey` or 

1353 :class:`_schema.ForeignKeyConstraint` 

1354 constructs present, often because the table 

1355 was reflected from a database that does not support foreign key 

1356 reflection (MySQL MyISAM). 

1357 

1358 3. The :paramref:`_orm.relationship.primaryjoin` 

1359 argument is used to 

1360 construct a non-standard join condition, which makes use of 

1361 columns or expressions that do not normally refer to their 

1362 "parent" column, such as a join condition expressed by a 

1363 complex comparison using a SQL function. 

1364 

1365 The :func:`_orm.relationship` construct will raise informative 

1366 error messages that suggest the use of the 

1367 :paramref:`_orm.relationship.foreign_keys` parameter when 

1368 presented with an ambiguous condition. In typical cases, 

1369 if :func:`_orm.relationship` doesn't raise any exceptions, the 

1370 :paramref:`_orm.relationship.foreign_keys` parameter is usually 

1371 not needed. 

1372 

1373 :paramref:`_orm.relationship.foreign_keys` may also be passed as a 

1374 callable function which is evaluated at mapper initialization time, 

1375 and may be passed as a Python-evaluable string when using 

1376 Declarative. 

1377 

1378 .. warning:: When passed as a Python-evaluable string, the 

1379 argument is interpreted using Python's ``eval()`` function. 

1380 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1381 See :ref:`declarative_relationship_eval` for details on 

1382 declarative evaluation of :func:`_orm.relationship` arguments. 

1383 

1384 .. seealso:: 

1385 

1386 :ref:`relationship_foreign_keys` 

1387 

1388 :ref:`relationship_custom_foreign` 

1389 

1390 :func:`.foreign` - allows direct annotation of the "foreign" 

1391 columns within a :paramref:`_orm.relationship.primaryjoin` 

1392 condition. 

1393 

1394 :param info: Optional data dictionary which will be populated into the 

1395 :attr:`.MapperProperty.info` attribute of this object. 

1396 

1397 :param innerjoin=False: 

1398 When ``True``, joined eager loads will use an inner join to join 

1399 against related tables instead of an outer join. The purpose 

1400 of this option is generally one of performance, as inner joins 

1401 generally perform better than outer joins. 

1402 

1403 This flag can be set to ``True`` when the relationship references an 

1404 object via many-to-one using local foreign keys that are not 

1405 nullable, or when the reference is one-to-one or a collection that 

1406 is guaranteed to have one or at least one entry. 

1407 

1408 The option supports the same "nested" and "unnested" options as 

1409 that of :paramref:`_orm.joinedload.innerjoin`. See that flag 

1410 for details on nested / unnested behaviors. 

1411 

1412 .. seealso:: 

1413 

1414 :paramref:`_orm.joinedload.innerjoin` - the option as specified by 

1415 loader option, including detail on nesting behavior. 

1416 

1417 :ref:`what_kind_of_loading` - Discussion of some details of 

1418 various loader options. 

1419 

1420 

1421 :param join_depth: 

1422 When non-``None``, an integer value indicating how many levels 

1423 deep "eager" loaders should join on a self-referring or cyclical 

1424 relationship. The number counts how many times the same Mapper 

1425 shall be present in the loading condition along a particular join 

1426 branch. When left at its default of ``None``, eager loaders 

1427 will stop chaining when they encounter a the same target mapper 

1428 which is already higher up in the chain. This option applies 

1429 both to joined- and subquery- eager loaders. 

1430 

1431 .. seealso:: 

1432 

1433 :ref:`self_referential_eager_loading` - Introductory documentation 

1434 and examples. 

1435 

1436 :param lazy='select': specifies 

1437 How the related items should be loaded. Default value is 

1438 ``select``. Values include: 

1439 

1440 * ``select`` - items should be loaded lazily when the property is 

1441 first accessed, using a separate SELECT statement, or identity map 

1442 fetch for simple many-to-one references. 

1443 

1444 * ``immediate`` - items should be loaded as the parents are loaded, 

1445 using a separate SELECT statement, or identity map fetch for 

1446 simple many-to-one references. 

1447 

1448 * ``joined`` - items should be loaded "eagerly" in the same query as 

1449 that of the parent, using a JOIN or LEFT OUTER JOIN. Whether 

1450 the join is "outer" or not is determined by the 

1451 :paramref:`_orm.relationship.innerjoin` parameter. 

1452 

1453 * ``subquery`` - items should be loaded "eagerly" as the parents are 

1454 loaded, using one additional SQL statement, which issues a JOIN to 

1455 a subquery of the original statement, for each collection 

1456 requested. 

1457 

1458 * ``selectin`` - items should be loaded "eagerly" as the parents 

1459 are loaded, using one or more additional SQL statements, which 

1460 issues a JOIN to the immediate parent object, specifying primary 

1461 key identifiers using an IN clause. 

1462 

1463 * ``noload`` - no loading should occur at any time. The related 

1464 collection will remain empty. The ``noload`` strategy is not 

1465 recommended for general use. For a general use "never load" 

1466 approach, see :ref:`write_only_relationship` 

1467 

1468 * ``raise`` - lazy loading is disallowed; accessing 

1469 the attribute, if its value were not already loaded via eager 

1470 loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`. 

1471 This strategy can be used when objects are to be detached from 

1472 their attached :class:`.Session` after they are loaded. 

1473 

1474 * ``raise_on_sql`` - lazy loading that emits SQL is disallowed; 

1475 accessing the attribute, if its value were not already loaded via 

1476 eager loading, will raise an 

1477 :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load 

1478 needs to emit SQL**. If the lazy load can pull the related value 

1479 from the identity map or determine that it should be None, the 

1480 value is loaded. This strategy can be used when objects will 

1481 remain associated with the attached :class:`.Session`, however 

1482 additional SELECT statements should be blocked. 

1483 

1484 * ``write_only`` - the attribute will be configured with a special 

1485 "virtual collection" that may receive 

1486 :meth:`_orm.WriteOnlyCollection.add` and 

1487 :meth:`_orm.WriteOnlyCollection.remove` commands to add or remove 

1488 individual objects, but will not under any circumstances load or 

1489 iterate the full set of objects from the database directly. Instead, 

1490 methods such as :meth:`_orm.WriteOnlyCollection.select`, 

1491 :meth:`_orm.WriteOnlyCollection.insert`, 

1492 :meth:`_orm.WriteOnlyCollection.update` and 

1493 :meth:`_orm.WriteOnlyCollection.delete` are provided which generate SQL 

1494 constructs that may be used to load and modify rows in bulk. Used for 

1495 large collections that are never appropriate to load at once into 

1496 memory. 

1497 

1498 The ``write_only`` loader style is configured automatically when 

1499 the :class:`_orm.WriteOnlyMapped` annotation is provided on the 

1500 left hand side within a Declarative mapping. See the section 

1501 :ref:`write_only_relationship` for examples. 

1502 

1503 .. versionadded:: 2.0 

1504 

1505 .. seealso:: 

1506 

1507 :ref:`write_only_relationship` - in the :ref:`queryguide_toplevel` 

1508 

1509 * ``dynamic`` - the attribute will return a pre-configured 

1510 :class:`_query.Query` object for all read 

1511 operations, onto which further filtering operations can be 

1512 applied before iterating the results. 

1513 

1514 The ``dynamic`` loader style is configured automatically when 

1515 the :class:`_orm.DynamicMapped` annotation is provided on the 

1516 left hand side within a Declarative mapping. See the section 

1517 :ref:`dynamic_relationship` for examples. 

1518 

1519 .. legacy:: The "dynamic" lazy loader strategy is the legacy form of 

1520 what is now the "write_only" strategy described in the section 

1521 :ref:`write_only_relationship`. 

1522 

1523 .. seealso:: 

1524 

1525 :ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel` 

1526 

1527 :ref:`write_only_relationship` - more generally useful approach 

1528 for large collections that should not fully load into memory 

1529 

1530 * True - a synonym for 'select' 

1531 

1532 * False - a synonym for 'joined' 

1533 

1534 * None - a synonym for 'noload' 

1535 

1536 .. seealso:: 

1537 

1538 :ref:`orm_queryguide_relationship_loaders` - Full documentation on 

1539 relationship loader configuration in the :ref:`queryguide_toplevel`. 

1540 

1541 

1542 :param load_on_pending=False: 

1543 Indicates loading behavior for transient or pending parent objects. 

1544 

1545 When set to ``True``, causes the lazy-loader to 

1546 issue a query for a parent object that is not persistent, meaning it 

1547 has never been flushed. This may take effect for a pending object 

1548 when autoflush is disabled, or for a transient object that has been 

1549 "attached" to a :class:`.Session` but is not part of its pending 

1550 collection. 

1551 

1552 The :paramref:`_orm.relationship.load_on_pending` 

1553 flag does not improve 

1554 behavior when the ORM is used normally - object references should be 

1555 constructed at the object level, not at the foreign key level, so 

1556 that they are present in an ordinary way before a flush proceeds. 

1557 This flag is not not intended for general use. 

1558 

1559 .. seealso:: 

1560 

1561 :meth:`.Session.enable_relationship_loading` - this method 

1562 establishes "load on pending" behavior for the whole object, and 

1563 also allows loading on objects that remain transient or 

1564 detached. 

1565 

1566 :param order_by: 

1567 Indicates the ordering that should be applied when loading these 

1568 items. :paramref:`_orm.relationship.order_by` 

1569 is expected to refer to 

1570 one of the :class:`_schema.Column` 

1571 objects to which the target class is 

1572 mapped, or the attribute itself bound to the target class which 

1573 refers to the column. 

1574 

1575 :paramref:`_orm.relationship.order_by` 

1576 may also be passed as a callable 

1577 function which is evaluated at mapper initialization time, and may 

1578 be passed as a Python-evaluable string when using Declarative. 

1579 

1580 .. warning:: When passed as a Python-evaluable string, the 

1581 argument is interpreted using Python's ``eval()`` function. 

1582 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1583 See :ref:`declarative_relationship_eval` for details on 

1584 declarative evaluation of :func:`_orm.relationship` arguments. 

1585 

1586 :param passive_deletes=False: 

1587 Indicates loading behavior during delete operations. 

1588 

1589 A value of True indicates that unloaded child items should not 

1590 be loaded during a delete operation on the parent. Normally, 

1591 when a parent item is deleted, all child items are loaded so 

1592 that they can either be marked as deleted, or have their 

1593 foreign key to the parent set to NULL. Marking this flag as 

1594 True usually implies an ON DELETE <CASCADE|SET NULL> rule is in 

1595 place which will handle updating/deleting child rows on the 

1596 database side. 

1597 

1598 Additionally, setting the flag to the string value 'all' will 

1599 disable the "nulling out" of the child foreign keys, when the parent 

1600 object is deleted and there is no delete or delete-orphan cascade 

1601 enabled. This is typically used when a triggering or error raise 

1602 scenario is in place on the database side. Note that the foreign 

1603 key attributes on in-session child objects will not be changed after 

1604 a flush occurs so this is a very special use-case setting. 

1605 Additionally, the "nulling out" will still occur if the child 

1606 object is de-associated with the parent. 

1607 

1608 .. seealso:: 

1609 

1610 :ref:`passive_deletes` - Introductory documentation 

1611 and examples. 

1612 

1613 :param passive_updates=True: 

1614 Indicates the persistence behavior to take when a referenced 

1615 primary key value changes in place, indicating that the referencing 

1616 foreign key columns will also need their value changed. 

1617 

1618 When True, it is assumed that ``ON UPDATE CASCADE`` is configured on 

1619 the foreign key in the database, and that the database will 

1620 handle propagation of an UPDATE from a source column to 

1621 dependent rows. When False, the SQLAlchemy 

1622 :func:`_orm.relationship` 

1623 construct will attempt to emit its own UPDATE statements to 

1624 modify related targets. However note that SQLAlchemy **cannot** 

1625 emit an UPDATE for more than one level of cascade. Also, 

1626 setting this flag to False is not compatible in the case where 

1627 the database is in fact enforcing referential integrity, unless 

1628 those constraints are explicitly "deferred", if the target backend 

1629 supports it. 

1630 

1631 It is highly advised that an application which is employing 

1632 mutable primary keys keeps ``passive_updates`` set to True, 

1633 and instead uses the referential integrity features of the database 

1634 itself in order to handle the change efficiently and fully. 

1635 

1636 .. seealso:: 

1637 

1638 :ref:`passive_updates` - Introductory documentation and 

1639 examples. 

1640 

1641 :paramref:`.mapper.passive_updates` - a similar flag which 

1642 takes effect for joined-table inheritance mappings. 

1643 

1644 :param post_update: 

1645 This indicates that the relationship should be handled by a 

1646 second UPDATE statement after an INSERT or before a 

1647 DELETE. This flag is used to handle saving bi-directional 

1648 dependencies between two individual rows (i.e. each row 

1649 references the other), where it would otherwise be impossible to 

1650 INSERT or DELETE both rows fully since one row exists before the 

1651 other. Use this flag when a particular mapping arrangement will 

1652 incur two rows that are dependent on each other, such as a table 

1653 that has a one-to-many relationship to a set of child rows, and 

1654 also has a column that references a single child row within that 

1655 list (i.e. both tables contain a foreign key to each other). If 

1656 a flush operation returns an error that a "cyclical 

1657 dependency" was detected, this is a cue that you might want to 

1658 use :paramref:`_orm.relationship.post_update` to "break" the cycle. 

1659 

1660 .. seealso:: 

1661 

1662 :ref:`post_update` - Introductory documentation and examples. 

1663 

1664 :param primaryjoin: 

1665 A SQL expression that will be used as the primary 

1666 join of the child object against the parent object, or in a 

1667 many-to-many relationship the join of the parent object to the 

1668 association table. By default, this value is computed based on the 

1669 foreign key relationships of the parent and child tables (or 

1670 association table). 

1671 

1672 :paramref:`_orm.relationship.primaryjoin` may also be passed as a 

1673 callable function which is evaluated at mapper initialization time, 

1674 and may be passed as a Python-evaluable string when using 

1675 Declarative. 

1676 

1677 .. warning:: When passed as a Python-evaluable string, the 

1678 argument is interpreted using Python's ``eval()`` function. 

1679 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1680 See :ref:`declarative_relationship_eval` for details on 

1681 declarative evaluation of :func:`_orm.relationship` arguments. 

1682 

1683 .. seealso:: 

1684 

1685 :ref:`relationship_primaryjoin` 

1686 

1687 :param remote_side: 

1688 Used for self-referential relationships, indicates the column or 

1689 list of columns that form the "remote side" of the relationship. 

1690 

1691 :paramref:`_orm.relationship.remote_side` may also be passed as a 

1692 callable function which is evaluated at mapper initialization time, 

1693 and may be passed as a Python-evaluable string when using 

1694 Declarative. 

1695 

1696 .. warning:: When passed as a Python-evaluable string, the 

1697 argument is interpreted using Python's ``eval()`` function. 

1698 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1699 See :ref:`declarative_relationship_eval` for details on 

1700 declarative evaluation of :func:`_orm.relationship` arguments. 

1701 

1702 .. seealso:: 

1703 

1704 :ref:`self_referential` - in-depth explanation of how 

1705 :paramref:`_orm.relationship.remote_side` 

1706 is used to configure self-referential relationships. 

1707 

1708 :func:`.remote` - an annotation function that accomplishes the 

1709 same purpose as :paramref:`_orm.relationship.remote_side`, 

1710 typically 

1711 when a custom :paramref:`_orm.relationship.primaryjoin` condition 

1712 is used. 

1713 

1714 :param query_class: 

1715 A :class:`_query.Query` 

1716 subclass that will be used internally by the 

1717 ``AppenderQuery`` returned by a "dynamic" relationship, that 

1718 is, a relationship that specifies ``lazy="dynamic"`` or was 

1719 otherwise constructed using the :func:`_orm.dynamic_loader` 

1720 function. 

1721 

1722 .. seealso:: 

1723 

1724 :ref:`dynamic_relationship` - Introduction to "dynamic" 

1725 relationship loaders. 

1726 

1727 :param secondaryjoin: 

1728 A SQL expression that will be used as the join of 

1729 an association table to the child object. By default, this value is 

1730 computed based on the foreign key relationships of the association 

1731 and child tables. 

1732 

1733 :paramref:`_orm.relationship.secondaryjoin` may also be passed as a 

1734 callable function which is evaluated at mapper initialization time, 

1735 and may be passed as a Python-evaluable string when using 

1736 Declarative. 

1737 

1738 .. warning:: When passed as a Python-evaluable string, the 

1739 argument is interpreted using Python's ``eval()`` function. 

1740 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1741 See :ref:`declarative_relationship_eval` for details on 

1742 declarative evaluation of :func:`_orm.relationship` arguments. 

1743 

1744 .. seealso:: 

1745 

1746 :ref:`relationship_primaryjoin` 

1747 

1748 :param single_parent: 

1749 When True, installs a validator which will prevent objects 

1750 from being associated with more than one parent at a time. 

1751 This is used for many-to-one or many-to-many relationships that 

1752 should be treated either as one-to-one or one-to-many. Its usage 

1753 is optional, except for :func:`_orm.relationship` constructs which 

1754 are many-to-one or many-to-many and also 

1755 specify the ``delete-orphan`` cascade option. The 

1756 :func:`_orm.relationship` construct itself will raise an error 

1757 instructing when this option is required. 

1758 

1759 .. seealso:: 

1760 

1761 :ref:`unitofwork_cascades` - includes detail on when the 

1762 :paramref:`_orm.relationship.single_parent` 

1763 flag may be appropriate. 

1764 

1765 :param uselist: 

1766 A boolean that indicates if this property should be loaded as a 

1767 list or a scalar. In most cases, this value is determined 

1768 automatically by :func:`_orm.relationship` at mapper configuration 

1769 time. When using explicit :class:`_orm.Mapped` annotations, 

1770 :paramref:`_orm.relationship.uselist` may be derived from the 

1771 whether or not the annotation within :class:`_orm.Mapped` contains 

1772 a collection class. 

1773 Otherwise, :paramref:`_orm.relationship.uselist` may be derived from 

1774 the type and direction 

1775 of the relationship - one to many forms a list, many to one 

1776 forms a scalar, many to many is a list. If a scalar is desired 

1777 where normally a list would be present, such as a bi-directional 

1778 one-to-one relationship, use an appropriate :class:`_orm.Mapped` 

1779 annotation or set :paramref:`_orm.relationship.uselist` to False. 

1780 

1781 The :paramref:`_orm.relationship.uselist` 

1782 flag is also available on an 

1783 existing :func:`_orm.relationship` 

1784 construct as a read-only attribute, 

1785 which can be used to determine if this :func:`_orm.relationship` 

1786 deals 

1787 with collections or scalar attributes:: 

1788 

1789 >>> User.addresses.property.uselist 

1790 True 

1791 

1792 .. seealso:: 

1793 

1794 :ref:`relationships_one_to_one` - Introduction to the "one to 

1795 one" relationship pattern, which is typically when an alternate 

1796 setting for :paramref:`_orm.relationship.uselist` is involved. 

1797 

1798 :param viewonly=False: 

1799 When set to ``True``, the relationship is used only for loading 

1800 objects, and not for any persistence operation. A 

1801 :func:`_orm.relationship` which specifies 

1802 :paramref:`_orm.relationship.viewonly` can work 

1803 with a wider range of SQL operations within the 

1804 :paramref:`_orm.relationship.primaryjoin` condition, including 

1805 operations that feature the use of a variety of comparison operators 

1806 as well as SQL functions such as :func:`_expression.cast`. The 

1807 :paramref:`_orm.relationship.viewonly` 

1808 flag is also of general use when defining any kind of 

1809 :func:`_orm.relationship` that doesn't represent 

1810 the full set of related objects, to prevent modifications of the 

1811 collection from resulting in persistence operations. 

1812 

1813 .. seealso:: 

1814 

1815 :ref:`relationship_viewonly_notes` - more details on best practices 

1816 when using :paramref:`_orm.relationship.viewonly`. 

1817 

1818 :param sync_backref: 

1819 A boolean that enables the events used to synchronize the in-Python 

1820 attributes when this relationship is target of either 

1821 :paramref:`_orm.relationship.backref` or 

1822 :paramref:`_orm.relationship.back_populates`. 

1823 

1824 Defaults to ``None``, which indicates that an automatic value should 

1825 be selected based on the value of the 

1826 :paramref:`_orm.relationship.viewonly` flag. When left at its 

1827 default, changes in state will be back-populated only if neither 

1828 sides of a relationship is viewonly. 

1829 

1830 .. versionadded:: 1.3.17 

1831 

1832 .. versionchanged:: 1.4 - A relationship that specifies 

1833 :paramref:`_orm.relationship.viewonly` automatically implies 

1834 that :paramref:`_orm.relationship.sync_backref` is ``False``. 

1835 

1836 .. seealso:: 

1837 

1838 :paramref:`_orm.relationship.viewonly` 

1839 

1840 :param omit_join: 

1841 Allows manual control over the "selectin" automatic join 

1842 optimization. Set to ``False`` to disable the "omit join" feature 

1843 added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic 

1844 optimization in place. 

1845 

1846 .. note:: This flag may only be set to ``False``. It is not 

1847 necessary to set it to ``True`` as the "omit_join" optimization is 

1848 automatically detected; if it is not detected, then the 

1849 optimization is not supported. 

1850 

1851 .. versionchanged:: 1.3.11 setting ``omit_join`` to True will now 

1852 emit a warning as this was not the intended use of this flag. 

1853 

1854 .. versionadded:: 1.3 

1855 

1856 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

1857 specifies if the mapped attribute should be part of the ``__init__()`` 

1858 method as generated by the dataclass process. 

1859 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

1860 specifies if the mapped attribute should be part of the ``__repr__()`` 

1861 method as generated by the dataclass process. 

1862 :param default_factory: Specific to 

1863 :ref:`orm_declarative_native_dataclasses`, 

1864 specifies a default-value generation function that will take place 

1865 as part of the ``__init__()`` 

1866 method as generated by the dataclass process. 

1867 :param compare: Specific to 

1868 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

1869 should be included in comparison operations when generating the 

1870 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

1871 

1872 .. versionadded:: 2.0.0b4 

1873 

1874 :param kw_only: Specific to 

1875 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

1876 should be marked as keyword-only when generating the ``__init__()``. 

1877 

1878 :param hash: Specific to 

1879 :ref:`orm_declarative_native_dataclasses`, controls if this field 

1880 is included when generating the ``__hash__()`` method for the mapped 

1881 class. 

1882 

1883 .. versionadded:: 2.0.36 

1884 

1885 :param dataclass_metadata: Specific to 

1886 :ref:`orm_declarative_native_dataclasses`, supplies metadata 

1887 to be attached to the generated dataclass field. 

1888 

1889 .. versionadded:: 2.0.42 

1890 

1891 """ 

1892 

1893 return _RelationshipDeclared( 

1894 argument, 

1895 secondary=secondary, 

1896 uselist=uselist, 

1897 collection_class=collection_class, 

1898 primaryjoin=primaryjoin, 

1899 secondaryjoin=secondaryjoin, 

1900 back_populates=back_populates, 

1901 order_by=order_by, 

1902 backref=backref, 

1903 overlaps=overlaps, 

1904 post_update=post_update, 

1905 cascade=cascade, 

1906 viewonly=viewonly, 

1907 attribute_options=_AttributeOptions( 

1908 init, 

1909 repr, 

1910 default, 

1911 default_factory, 

1912 compare, 

1913 kw_only, 

1914 hash, 

1915 dataclass_metadata, 

1916 ), 

1917 lazy=lazy, 

1918 passive_deletes=passive_deletes, 

1919 passive_updates=passive_updates, 

1920 active_history=active_history, 

1921 enable_typechecks=enable_typechecks, 

1922 foreign_keys=foreign_keys, 

1923 remote_side=remote_side, 

1924 join_depth=join_depth, 

1925 comparator_factory=comparator_factory, 

1926 single_parent=single_parent, 

1927 innerjoin=innerjoin, 

1928 distinct_target_key=distinct_target_key, 

1929 load_on_pending=load_on_pending, 

1930 query_class=query_class, 

1931 info=info, 

1932 omit_join=omit_join, 

1933 sync_backref=sync_backref, 

1934 **kw, 

1935 ) 

1936 

1937 

1938def synonym( 

1939 name: str, 

1940 *, 

1941 map_column: Optional[bool] = None, 

1942 descriptor: Optional[Any] = None, 

1943 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

1944 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1945 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

1946 default: Union[_NoArg, _T] = _NoArg.NO_ARG, 

1947 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

1948 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1949 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1950 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

1951 info: Optional[_InfoType] = None, 

1952 doc: Optional[str] = None, 

1953 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

1954) -> Synonym[Any]: 

1955 """Denote an attribute name as a synonym to a mapped property, 

1956 in that the attribute will mirror the value and expression behavior 

1957 of another attribute. 

1958 

1959 e.g.:: 

1960 

1961 class MyClass(Base): 

1962 __tablename__ = "my_table" 

1963 

1964 id = Column(Integer, primary_key=True) 

1965 job_status = Column(String(50)) 

1966 

1967 status = synonym("job_status") 

1968 

1969 :param name: the name of the existing mapped property. This 

1970 can refer to the string name ORM-mapped attribute 

1971 configured on the class, including column-bound attributes 

1972 and relationships. 

1973 

1974 :param descriptor: a Python :term:`descriptor` that will be used 

1975 as a getter (and potentially a setter) when this attribute is 

1976 accessed at the instance level. 

1977 

1978 :param map_column: **For classical mappings and mappings against 

1979 an existing Table object only**. if ``True``, the :func:`.synonym` 

1980 construct will locate the :class:`_schema.Column` 

1981 object upon the mapped 

1982 table that would normally be associated with the attribute name of 

1983 this synonym, and produce a new :class:`.ColumnProperty` that instead 

1984 maps this :class:`_schema.Column` 

1985 to the alternate name given as the "name" 

1986 argument of the synonym; in this way, the usual step of redefining 

1987 the mapping of the :class:`_schema.Column` 

1988 to be under a different name is 

1989 unnecessary. This is usually intended to be used when a 

1990 :class:`_schema.Column` 

1991 is to be replaced with an attribute that also uses a 

1992 descriptor, that is, in conjunction with the 

1993 :paramref:`.synonym.descriptor` parameter:: 

1994 

1995 my_table = Table( 

1996 "my_table", 

1997 metadata, 

1998 Column("id", Integer, primary_key=True), 

1999 Column("job_status", String(50)), 

2000 ) 

2001 

2002 

2003 class MyClass: 

2004 @property 

2005 def _job_status_descriptor(self): 

2006 return "Status: %s" % self._job_status 

2007 

2008 

2009 mapper( 

2010 MyClass, 

2011 my_table, 

2012 properties={ 

2013 "job_status": synonym( 

2014 "_job_status", 

2015 map_column=True, 

2016 descriptor=MyClass._job_status_descriptor, 

2017 ) 

2018 }, 

2019 ) 

2020 

2021 Above, the attribute named ``_job_status`` is automatically 

2022 mapped to the ``job_status`` column:: 

2023 

2024 >>> j1 = MyClass() 

2025 >>> j1._job_status = "employed" 

2026 >>> j1.job_status 

2027 Status: employed 

2028 

2029 When using Declarative, in order to provide a descriptor in 

2030 conjunction with a synonym, use the 

2031 :func:`sqlalchemy.ext.declarative.synonym_for` helper. However, 

2032 note that the :ref:`hybrid properties <mapper_hybrids>` feature 

2033 should usually be preferred, particularly when redefining attribute 

2034 behavior. 

2035 

2036 :param info: Optional data dictionary which will be populated into the 

2037 :attr:`.InspectionAttr.info` attribute of this object. 

2038 

2039 :param comparator_factory: A subclass of :class:`.PropComparator` 

2040 that will provide custom comparison behavior at the SQL expression 

2041 level. 

2042 

2043 .. note:: 

2044 

2045 For the use case of providing an attribute which redefines both 

2046 Python-level and SQL-expression level behavior of an attribute, 

2047 please refer to the Hybrid attribute introduced at 

2048 :ref:`mapper_hybrids` for a more effective technique. 

2049 

2050 .. seealso:: 

2051 

2052 :ref:`synonyms` - Overview of synonyms 

2053 

2054 :func:`.synonym_for` - a helper oriented towards Declarative 

2055 

2056 :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an 

2057 updated approach to augmenting attribute behavior more flexibly 

2058 than can be achieved with synonyms. 

2059 

2060 """ 

2061 return Synonym( 

2062 name, 

2063 map_column=map_column, 

2064 descriptor=descriptor, 

2065 comparator_factory=comparator_factory, 

2066 attribute_options=_AttributeOptions( 

2067 init, 

2068 repr, 

2069 default, 

2070 default_factory, 

2071 compare, 

2072 kw_only, 

2073 hash, 

2074 dataclass_metadata, 

2075 ), 

2076 doc=doc, 

2077 info=info, 

2078 ) 

2079 

2080 

2081def create_session( 

2082 bind: Optional[_SessionBind] = None, **kwargs: Any 

2083) -> Session: 

2084 r"""Create a new :class:`.Session` 

2085 with no automation enabled by default. 

2086 

2087 This function is used primarily for testing. The usual 

2088 route to :class:`.Session` creation is via its constructor 

2089 or the :func:`.sessionmaker` function. 

2090 

2091 :param bind: optional, a single Connectable to use for all 

2092 database access in the created 

2093 :class:`~sqlalchemy.orm.session.Session`. 

2094 

2095 :param \*\*kwargs: optional, passed through to the 

2096 :class:`.Session` constructor. 

2097 

2098 :returns: an :class:`~sqlalchemy.orm.session.Session` instance 

2099 

2100 The defaults of create_session() are the opposite of that of 

2101 :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are 

2102 False. 

2103 

2104 Usage:: 

2105 

2106 >>> from sqlalchemy.orm import create_session 

2107 >>> session = create_session() 

2108 

2109 It is recommended to use :func:`sessionmaker` instead of 

2110 create_session(). 

2111 

2112 """ 

2113 

2114 kwargs.setdefault("autoflush", False) 

2115 kwargs.setdefault("expire_on_commit", False) 

2116 return Session(bind=bind, **kwargs) 

2117 

2118 

2119def _mapper_fn(*arg: Any, **kw: Any) -> NoReturn: 

2120 """Placeholder for the now-removed ``mapper()`` function. 

2121 

2122 Classical mappings should be performed using the 

2123 :meth:`_orm.registry.map_imperatively` method. 

2124 

2125 This symbol remains in SQLAlchemy 2.0 to suit the deprecated use case 

2126 of using the ``mapper()`` function as a target for ORM event listeners, 

2127 which failed to be marked as deprecated in the 1.4 series. 

2128 

2129 Global ORM mapper listeners should instead use the :class:`_orm.Mapper` 

2130 class as the target. 

2131 

2132 .. versionchanged:: 2.0 The ``mapper()`` function was removed; the 

2133 symbol remains temporarily as a placeholder for the event listening 

2134 use case. 

2135 

2136 """ 

2137 raise InvalidRequestError( 

2138 "The 'sqlalchemy.orm.mapper()' function is removed as of " 

2139 "SQLAlchemy 2.0. Use the " 

2140 "'sqlalchemy.orm.registry.map_imperatively()` " 

2141 "method of the ``sqlalchemy.orm.registry`` class to perform " 

2142 "classical mapping." 

2143 ) 

2144 

2145 

2146def dynamic_loader( 

2147 argument: Optional[_RelationshipArgumentType[Any]] = None, **kw: Any 

2148) -> RelationshipProperty[Any]: 

2149 """Construct a dynamically-loading mapper property. 

2150 

2151 This is essentially the same as 

2152 using the ``lazy='dynamic'`` argument with :func:`relationship`:: 

2153 

2154 dynamic_loader(SomeClass) 

2155 

2156 # is the same as 

2157 

2158 relationship(SomeClass, lazy="dynamic") 

2159 

2160 See the section :ref:`dynamic_relationship` for more details 

2161 on dynamic loading. 

2162 

2163 """ 

2164 kw["lazy"] = "dynamic" 

2165 return relationship(argument, **kw) 

2166 

2167 

2168def backref(name: str, **kwargs: Any) -> ORMBackrefArgument: 

2169 """When using the :paramref:`_orm.relationship.backref` parameter, 

2170 provides specific parameters to be used when the new 

2171 :func:`_orm.relationship` is generated. 

2172 

2173 E.g.:: 

2174 

2175 "items": relationship(SomeItem, backref=backref("parent", lazy="subquery")) 

2176 

2177 The :paramref:`_orm.relationship.backref` parameter is generally 

2178 considered to be legacy; for modern applications, using 

2179 explicit :func:`_orm.relationship` constructs linked together using 

2180 the :paramref:`_orm.relationship.back_populates` parameter should be 

2181 preferred. 

2182 

2183 .. seealso:: 

2184 

2185 :ref:`relationships_backref` - background on backrefs 

2186 

2187 """ # noqa: E501 

2188 

2189 return (name, kwargs) 

2190 

2191 

2192def deferred( 

2193 column: _ORMColumnExprArgument[_T], 

2194 *additional_columns: _ORMColumnExprArgument[Any], 

2195 group: Optional[str] = None, 

2196 raiseload: bool = False, 

2197 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

2198 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2199 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2200 default: Optional[Any] = _NoArg.NO_ARG, 

2201 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

2202 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2203 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2204 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

2205 active_history: bool = False, 

2206 expire_on_flush: bool = True, 

2207 info: Optional[_InfoType] = None, 

2208 doc: Optional[str] = None, 

2209 dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, 

2210) -> MappedSQLExpression[_T]: 

2211 r"""Indicate a column-based mapped attribute that by default will 

2212 not load unless accessed. 

2213 

2214 When using :func:`_orm.mapped_column`, the same functionality as 

2215 that of :func:`_orm.deferred` construct is provided by using the 

2216 :paramref:`_orm.mapped_column.deferred` parameter. 

2217 

2218 :param \*columns: columns to be mapped. This is typically a single 

2219 :class:`_schema.Column` object, 

2220 however a collection is supported in order 

2221 to support multiple columns mapped under the same attribute. 

2222 

2223 :param raiseload: boolean, if True, indicates an exception should be raised 

2224 if the load operation is to take place. 

2225 

2226 .. versionadded:: 1.4 

2227 

2228 

2229 Additional arguments are the same as that of :func:`_orm.column_property`. 

2230 

2231 .. seealso:: 

2232 

2233 :ref:`orm_queryguide_deferred_imperative` 

2234 

2235 """ 

2236 return MappedSQLExpression( 

2237 column, 

2238 *additional_columns, 

2239 attribute_options=_AttributeOptions( 

2240 init, 

2241 repr, 

2242 default, 

2243 default_factory, 

2244 compare, 

2245 kw_only, 

2246 hash, 

2247 dataclass_metadata, 

2248 ), 

2249 group=group, 

2250 deferred=True, 

2251 raiseload=raiseload, 

2252 comparator_factory=comparator_factory, 

2253 active_history=active_history, 

2254 expire_on_flush=expire_on_flush, 

2255 info=info, 

2256 doc=doc, 

2257 ) 

2258 

2259 

2260def query_expression( 

2261 default_expr: _ORMColumnExprArgument[_T] = sql.null(), 

2262 *, 

2263 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2264 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2265 expire_on_flush: bool = True, 

2266 info: Optional[_InfoType] = None, 

2267 doc: Optional[str] = None, 

2268) -> MappedSQLExpression[_T]: 

2269 """Indicate an attribute that populates from a query-time SQL expression. 

2270 

2271 :param default_expr: Optional SQL expression object that will be used in 

2272 all cases if not assigned later with :func:`_orm.with_expression`. 

2273 

2274 .. versionadded:: 1.2 

2275 

2276 .. seealso:: 

2277 

2278 :ref:`orm_queryguide_with_expression` - background and usage examples 

2279 

2280 """ 

2281 prop = MappedSQLExpression( 

2282 default_expr, 

2283 attribute_options=_AttributeOptions( 

2284 False, 

2285 repr, 

2286 _NoArg.NO_ARG, 

2287 _NoArg.NO_ARG, 

2288 compare, 

2289 _NoArg.NO_ARG, 

2290 _NoArg.NO_ARG, 

2291 _NoArg.NO_ARG, 

2292 ), 

2293 expire_on_flush=expire_on_flush, 

2294 info=info, 

2295 doc=doc, 

2296 _assume_readonly_dc_attributes=True, 

2297 ) 

2298 

2299 prop.strategy_key = (("query_expression", True),) 

2300 return prop 

2301 

2302 

2303def clear_mappers() -> None: 

2304 """Remove all mappers from all classes. 

2305 

2306 .. versionchanged:: 1.4 This function now locates all 

2307 :class:`_orm.registry` objects and calls upon the 

2308 :meth:`_orm.registry.dispose` method of each. 

2309 

2310 This function removes all instrumentation from classes and disposes 

2311 of their associated mappers. Once called, the classes are unmapped 

2312 and can be later re-mapped with new mappers. 

2313 

2314 :func:`.clear_mappers` is *not* for normal use, as there is literally no 

2315 valid usage for it outside of very specific testing scenarios. Normally, 

2316 mappers are permanent structural components of user-defined classes, and 

2317 are never discarded independently of their class. If a mapped class 

2318 itself is garbage collected, its mapper is automatically disposed of as 

2319 well. As such, :func:`.clear_mappers` is only for usage in test suites 

2320 that re-use the same classes with different mappings, which is itself an 

2321 extremely rare use case - the only such use case is in fact SQLAlchemy's 

2322 own test suite, and possibly the test suites of other ORM extension 

2323 libraries which intend to test various combinations of mapper construction 

2324 upon a fixed set of classes. 

2325 

2326 """ 

2327 

2328 mapperlib._dispose_registries(mapperlib._all_registries(), False) 

2329 

2330 

2331# I would really like a way to get the Type[] here that shows up 

2332# in a different way in typing tools, however there is no current method 

2333# that is accepted by mypy (subclass of Type[_O] works in pylance, rejected 

2334# by mypy). 

2335AliasedType = Annotated[Type[_O], "aliased"] 

2336 

2337 

2338@overload 

2339def aliased( 

2340 element: Type[_O], 

2341 alias: Optional[FromClause] = None, 

2342 name: Optional[str] = None, 

2343 flat: bool = False, 

2344 adapt_on_names: bool = False, 

2345) -> AliasedType[_O]: ... 

2346 

2347 

2348@overload 

2349def aliased( 

2350 element: Union[AliasedClass[_O], Mapper[_O], AliasedInsp[_O]], 

2351 alias: Optional[FromClause] = None, 

2352 name: Optional[str] = None, 

2353 flat: bool = False, 

2354 adapt_on_names: bool = False, 

2355) -> AliasedClass[_O]: ... 

2356 

2357 

2358@overload 

2359def aliased( 

2360 element: FromClause, 

2361 alias: None = None, 

2362 name: Optional[str] = None, 

2363 flat: bool = False, 

2364 adapt_on_names: bool = False, 

2365) -> FromClause: ... 

2366 

2367 

2368def aliased( 

2369 element: Union[_EntityType[_O], FromClause], 

2370 alias: Optional[FromClause] = None, 

2371 name: Optional[str] = None, 

2372 flat: bool = False, 

2373 adapt_on_names: bool = False, 

2374) -> Union[AliasedClass[_O], FromClause, AliasedType[_O]]: 

2375 """Produce an alias of the given element, usually an :class:`.AliasedClass` 

2376 instance. 

2377 

2378 E.g.:: 

2379 

2380 my_alias = aliased(MyClass) 

2381 

2382 stmt = select(MyClass, my_alias).filter(MyClass.id > my_alias.id) 

2383 result = session.execute(stmt) 

2384 

2385 The :func:`.aliased` function is used to create an ad-hoc mapping of a 

2386 mapped class to a new selectable. By default, a selectable is generated 

2387 from the normally mapped selectable (typically a :class:`_schema.Table` 

2388 ) using the 

2389 :meth:`_expression.FromClause.alias` method. However, :func:`.aliased` 

2390 can also be 

2391 used to link the class to a new :func:`_expression.select` statement. 

2392 Also, the :func:`.with_polymorphic` function is a variant of 

2393 :func:`.aliased` that is intended to specify a so-called "polymorphic 

2394 selectable", that corresponds to the union of several joined-inheritance 

2395 subclasses at once. 

2396 

2397 For convenience, the :func:`.aliased` function also accepts plain 

2398 :class:`_expression.FromClause` constructs, such as a 

2399 :class:`_schema.Table` or 

2400 :func:`_expression.select` construct. In those cases, the 

2401 :meth:`_expression.FromClause.alias` 

2402 method is called on the object and the new 

2403 :class:`_expression.Alias` object returned. The returned 

2404 :class:`_expression.Alias` is not 

2405 ORM-mapped in this case. 

2406 

2407 .. seealso:: 

2408 

2409 :ref:`tutorial_orm_entity_aliases` - in the :ref:`unified_tutorial` 

2410 

2411 :ref:`orm_queryguide_orm_aliases` - in the :ref:`queryguide_toplevel` 

2412 

2413 :param element: element to be aliased. Is normally a mapped class, 

2414 but for convenience can also be a :class:`_expression.FromClause` 

2415 element. 

2416 

2417 :param alias: Optional selectable unit to map the element to. This is 

2418 usually used to link the object to a subquery, and should be an aliased 

2419 select construct as one would produce from the 

2420 :meth:`_query.Query.subquery` method or 

2421 the :meth:`_expression.Select.subquery` or 

2422 :meth:`_expression.Select.alias` methods of the :func:`_expression.select` 

2423 construct. 

2424 

2425 :param name: optional string name to use for the alias, if not specified 

2426 by the ``alias`` parameter. The name, among other things, forms the 

2427 attribute name that will be accessible via tuples returned by a 

2428 :class:`_query.Query` object. Not supported when creating aliases 

2429 of :class:`_sql.Join` objects. 

2430 

2431 :param flat: Boolean, will be passed through to the 

2432 :meth:`_expression.FromClause.alias` call so that aliases of 

2433 :class:`_expression.Join` objects will alias the individual tables 

2434 inside the join, rather than creating a subquery. This is generally 

2435 supported by all modern databases with regards to right-nested joins 

2436 and generally produces more efficient queries. 

2437 

2438 When :paramref:`_orm.aliased.flat` is combined with 

2439 :paramref:`_orm.aliased.name`, the resulting joins will alias individual 

2440 tables using a naming scheme similar to ``<prefix>_<tablename>``. This 

2441 naming scheme is for visibility / debugging purposes only and the 

2442 specific scheme is subject to change without notice. 

2443 

2444 .. versionadded:: 2.0.32 added support for combining 

2445 :paramref:`_orm.aliased.name` with :paramref:`_orm.aliased.flat`. 

2446 Previously, this would raise ``NotImplementedError``. 

2447 

2448 :param adapt_on_names: if True, more liberal "matching" will be used when 

2449 mapping the mapped columns of the ORM entity to those of the 

2450 given selectable - a name-based match will be performed if the 

2451 given selectable doesn't otherwise have a column that corresponds 

2452 to one on the entity. The use case for this is when associating 

2453 an entity with some derived selectable such as one that uses 

2454 aggregate functions:: 

2455 

2456 class UnitPrice(Base): 

2457 __tablename__ = "unit_price" 

2458 ... 

2459 unit_id = Column(Integer) 

2460 price = Column(Numeric) 

2461 

2462 

2463 aggregated_unit_price = ( 

2464 Session.query(func.sum(UnitPrice.price).label("price")) 

2465 .group_by(UnitPrice.unit_id) 

2466 .subquery() 

2467 ) 

2468 

2469 aggregated_unit_price = aliased( 

2470 UnitPrice, alias=aggregated_unit_price, adapt_on_names=True 

2471 ) 

2472 

2473 Above, functions on ``aggregated_unit_price`` which refer to 

2474 ``.price`` will return the 

2475 ``func.sum(UnitPrice.price).label('price')`` column, as it is 

2476 matched on the name "price". Ordinarily, the "price" function 

2477 wouldn't have any "column correspondence" to the actual 

2478 ``UnitPrice.price`` column as it is not a proxy of the original. 

2479 

2480 """ 

2481 return AliasedInsp._alias_factory( 

2482 element, 

2483 alias=alias, 

2484 name=name, 

2485 flat=flat, 

2486 adapt_on_names=adapt_on_names, 

2487 ) 

2488 

2489 

2490def with_polymorphic( 

2491 base: Union[Type[_O], Mapper[_O]], 

2492 classes: Union[Literal["*"], Iterable[Type[Any]]], 

2493 selectable: Union[Literal[False, None], FromClause] = False, 

2494 flat: bool = False, 

2495 polymorphic_on: Optional[ColumnElement[Any]] = None, 

2496 aliased: bool = False, 

2497 innerjoin: bool = False, 

2498 adapt_on_names: bool = False, 

2499 name: Optional[str] = None, 

2500 _use_mapper_path: bool = False, 

2501) -> AliasedClass[_O]: 

2502 """Produce an :class:`.AliasedClass` construct which specifies 

2503 columns for descendant mappers of the given base. 

2504 

2505 Using this method will ensure that each descendant mapper's 

2506 tables are included in the FROM clause, and will allow filter() 

2507 criterion to be used against those tables. The resulting 

2508 instances will also have those columns already loaded so that 

2509 no "post fetch" of those columns will be required. 

2510 

2511 .. seealso:: 

2512 

2513 :ref:`with_polymorphic` - full discussion of 

2514 :func:`_orm.with_polymorphic`. 

2515 

2516 :param base: Base class to be aliased. 

2517 

2518 :param classes: a single class or mapper, or list of 

2519 class/mappers, which inherit from the base class. 

2520 Alternatively, it may also be the string ``'*'``, in which case 

2521 all descending mapped classes will be added to the FROM clause. 

2522 

2523 :param aliased: when True, the selectable will be aliased. For a 

2524 JOIN, this means the JOIN will be SELECTed from inside of a subquery 

2525 unless the :paramref:`_orm.with_polymorphic.flat` flag is set to 

2526 True, which is recommended for simpler use cases. 

2527 

2528 :param flat: Boolean, will be passed through to the 

2529 :meth:`_expression.FromClause.alias` call so that aliases of 

2530 :class:`_expression.Join` objects will alias the individual tables 

2531 inside the join, rather than creating a subquery. This is generally 

2532 supported by all modern databases with regards to right-nested joins 

2533 and generally produces more efficient queries. Setting this flag is 

2534 recommended as long as the resulting SQL is functional. 

2535 

2536 :param selectable: a table or subquery that will 

2537 be used in place of the generated FROM clause. This argument is 

2538 required if any of the desired classes use concrete table 

2539 inheritance, since SQLAlchemy currently cannot generate UNIONs 

2540 among tables automatically. If used, the ``selectable`` argument 

2541 must represent the full set of tables and columns mapped by every 

2542 mapped class. Otherwise, the unaccounted mapped columns will 

2543 result in their table being appended directly to the FROM clause 

2544 which will usually lead to incorrect results. 

2545 

2546 When left at its default value of ``False``, the polymorphic 

2547 selectable assigned to the base mapper is used for selecting rows. 

2548 However, it may also be passed as ``None``, which will bypass the 

2549 configured polymorphic selectable and instead construct an ad-hoc 

2550 selectable for the target classes given; for joined table inheritance 

2551 this will be a join that includes all target mappers and their 

2552 subclasses. 

2553 

2554 :param polymorphic_on: a column to be used as the "discriminator" 

2555 column for the given selectable. If not given, the polymorphic_on 

2556 attribute of the base classes' mapper will be used, if any. This 

2557 is useful for mappings that don't have polymorphic loading 

2558 behavior by default. 

2559 

2560 :param innerjoin: if True, an INNER JOIN will be used. This should 

2561 only be specified if querying for one specific subtype only 

2562 

2563 :param adapt_on_names: Passes through the 

2564 :paramref:`_orm.aliased.adapt_on_names` 

2565 parameter to the aliased object. This may be useful in situations where 

2566 the given selectable is not directly related to the existing mapped 

2567 selectable. 

2568 

2569 .. versionadded:: 1.4.33 

2570 

2571 :param name: Name given to the generated :class:`.AliasedClass`. 

2572 

2573 .. versionadded:: 2.0.31 

2574 

2575 """ 

2576 return AliasedInsp._with_polymorphic_factory( 

2577 base, 

2578 classes, 

2579 selectable=selectable, 

2580 flat=flat, 

2581 polymorphic_on=polymorphic_on, 

2582 adapt_on_names=adapt_on_names, 

2583 aliased=aliased, 

2584 innerjoin=innerjoin, 

2585 name=name, 

2586 _use_mapper_path=_use_mapper_path, 

2587 ) 

2588 

2589 

2590def join( 

2591 left: _FromClauseArgument, 

2592 right: _FromClauseArgument, 

2593 onclause: Optional[_OnClauseArgument] = None, 

2594 isouter: bool = False, 

2595 full: bool = False, 

2596) -> _ORMJoin: 

2597 r"""Produce an inner join between left and right clauses. 

2598 

2599 :func:`_orm.join` is an extension to the core join interface 

2600 provided by :func:`_expression.join()`, where the 

2601 left and right selectable may be not only core selectable 

2602 objects such as :class:`_schema.Table`, but also mapped classes or 

2603 :class:`.AliasedClass` instances. The "on" clause can 

2604 be a SQL expression or an ORM mapped attribute 

2605 referencing a configured :func:`_orm.relationship`. 

2606 

2607 :func:`_orm.join` is not commonly needed in modern usage, 

2608 as its functionality is encapsulated within that of the 

2609 :meth:`_sql.Select.join` and :meth:`_query.Query.join` 

2610 methods. which feature a 

2611 significant amount of automation beyond :func:`_orm.join` 

2612 by itself. Explicit use of :func:`_orm.join` 

2613 with ORM-enabled SELECT statements involves use of the 

2614 :meth:`_sql.Select.select_from` method, as in:: 

2615 

2616 from sqlalchemy.orm import join 

2617 

2618 stmt = ( 

2619 select(User) 

2620 .select_from(join(User, Address, User.addresses)) 

2621 .filter(Address.email_address == "foo@bar.com") 

2622 ) 

2623 

2624 In modern SQLAlchemy the above join can be written more 

2625 succinctly as:: 

2626 

2627 stmt = ( 

2628 select(User) 

2629 .join(User.addresses) 

2630 .filter(Address.email_address == "foo@bar.com") 

2631 ) 

2632 

2633 .. warning:: using :func:`_orm.join` directly may not work properly 

2634 with modern ORM options such as :func:`_orm.with_loader_criteria`. 

2635 It is strongly recommended to use the idiomatic join patterns 

2636 provided by methods such as :meth:`.Select.join` and 

2637 :meth:`.Select.join_from` when creating ORM joins. 

2638 

2639 .. seealso:: 

2640 

2641 :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` for 

2642 background on idiomatic ORM join patterns 

2643 

2644 """ 

2645 return _ORMJoin(left, right, onclause, isouter, full) 

2646 

2647 

2648def outerjoin( 

2649 left: _FromClauseArgument, 

2650 right: _FromClauseArgument, 

2651 onclause: Optional[_OnClauseArgument] = None, 

2652 full: bool = False, 

2653) -> _ORMJoin: 

2654 """Produce a left outer join between left and right clauses. 

2655 

2656 This is the "outer join" version of the :func:`_orm.join` function, 

2657 featuring the same behavior except that an OUTER JOIN is generated. 

2658 See that function's documentation for other usage details. 

2659 

2660 """ 

2661 return _ORMJoin(left, right, onclause, True, full)