decl_api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. # orm/decl_api.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Public API functions and helpers for declarative."""
  8. from __future__ import absolute_import
  9. import itertools
  10. import re
  11. import weakref
  12. from . import attributes
  13. from . import clsregistry
  14. from . import exc as orm_exc
  15. from . import instrumentation
  16. from . import interfaces
  17. from . import mapper as mapperlib
  18. from .base import _inspect_mapped_class
  19. from .decl_base import _add_attribute
  20. from .decl_base import _as_declarative
  21. from .decl_base import _declarative_constructor
  22. from .decl_base import _DeferredMapperConfig
  23. from .decl_base import _del_attribute
  24. from .decl_base import _mapper
  25. from .descriptor_props import SynonymProperty as _orm_synonym
  26. from .. import exc
  27. from .. import inspection
  28. from .. import util
  29. from ..sql.schema import MetaData
  30. from ..util import hybridmethod
  31. from ..util import hybridproperty
  32. def has_inherited_table(cls):
  33. """Given a class, return True if any of the classes it inherits from has a
  34. mapped table, otherwise return False.
  35. This is used in declarative mixins to build attributes that behave
  36. differently for the base class vs. a subclass in an inheritance
  37. hierarchy.
  38. .. seealso::
  39. :ref:`decl_mixin_inheritance`
  40. """
  41. for class_ in cls.__mro__[1:]:
  42. if getattr(class_, "__table__", None) is not None:
  43. return True
  44. return False
  45. class DeclarativeMeta(type):
  46. def __init__(cls, classname, bases, dict_, **kw):
  47. # use cls.__dict__, which can be modified by an
  48. # __init_subclass__() method (#7900)
  49. dict_ = cls.__dict__
  50. # early-consume registry from the initial declarative base,
  51. # assign privately to not conflict with subclass attributes named
  52. # "registry"
  53. reg = getattr(cls, "_sa_registry", None)
  54. if reg is None:
  55. reg = dict_.get("registry", None)
  56. if not isinstance(reg, registry):
  57. raise exc.InvalidRequestError(
  58. "Declarative base class has no 'registry' attribute, "
  59. "or registry is not a sqlalchemy.orm.registry() object"
  60. )
  61. else:
  62. cls._sa_registry = reg
  63. if not cls.__dict__.get("__abstract__", False):
  64. _as_declarative(reg, cls, dict_)
  65. type.__init__(cls, classname, bases, dict_)
  66. def __setattr__(cls, key, value):
  67. _add_attribute(cls, key, value)
  68. def __delattr__(cls, key):
  69. _del_attribute(cls, key)
  70. def synonym_for(name, map_column=False):
  71. """Decorator that produces an :func:`_orm.synonym`
  72. attribute in conjunction with a Python descriptor.
  73. The function being decorated is passed to :func:`_orm.synonym` as the
  74. :paramref:`.orm.synonym.descriptor` parameter::
  75. class MyClass(Base):
  76. __tablename__ = 'my_table'
  77. id = Column(Integer, primary_key=True)
  78. _job_status = Column("job_status", String(50))
  79. @synonym_for("job_status")
  80. @property
  81. def job_status(self):
  82. return "Status: %s" % self._job_status
  83. The :ref:`hybrid properties <mapper_hybrids>` feature of SQLAlchemy
  84. is typically preferred instead of synonyms, which is a more legacy
  85. feature.
  86. .. seealso::
  87. :ref:`synonyms` - Overview of synonyms
  88. :func:`_orm.synonym` - the mapper-level function
  89. :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an
  90. updated approach to augmenting attribute behavior more flexibly than
  91. can be achieved with synonyms.
  92. """
  93. def decorate(fn):
  94. return _orm_synonym(name, map_column=map_column, descriptor=fn)
  95. return decorate
  96. class declared_attr(interfaces._MappedAttribute, property):
  97. """Mark a class-level method as representing the definition of
  98. a mapped property or special declarative member name.
  99. :class:`_orm.declared_attr` is typically applied as a decorator to a class
  100. level method, turning the attribute into a scalar-like property that can be
  101. invoked from the uninstantiated class. The Declarative mapping process
  102. looks for these :class:`_orm.declared_attr` callables as it scans classes,
  103. and assumes any attribute marked with :class:`_orm.declared_attr` will be a
  104. callable that will produce an object specific to the Declarative mapping or
  105. table configuration.
  106. :class:`_orm.declared_attr` is usually applicable to mixins, to define
  107. relationships that are to be applied to different implementors of the
  108. class. It is also used to define :class:`_schema.Column` objects that
  109. include the :class:`_schema.ForeignKey` construct, as these cannot be
  110. easily reused across different mappings. The example below illustrates
  111. both::
  112. class ProvidesUser(object):
  113. "A mixin that adds a 'user' relationship to classes."
  114. @declared_attr
  115. def user_id(self):
  116. return Column(ForeignKey("user_account.id"))
  117. @declared_attr
  118. def user(self):
  119. return relationship("User")
  120. :class:`_orm.declared_attr` can also be applied to mapped classes, such as
  121. to provide a "polymorphic" scheme for inheritance::
  122. class Employee(Base):
  123. id = Column(Integer, primary_key=True)
  124. type = Column(String(50), nullable=False)
  125. @declared_attr
  126. def __tablename__(cls):
  127. return cls.__name__.lower()
  128. @declared_attr
  129. def __mapper_args__(cls):
  130. if cls.__name__ == 'Employee':
  131. return {
  132. "polymorphic_on":cls.type,
  133. "polymorphic_identity":"Employee"
  134. }
  135. else:
  136. return {"polymorphic_identity":cls.__name__}
  137. To use :class:`_orm.declared_attr` inside of a Python dataclass
  138. as discussed at :ref:`orm_declarative_dataclasses_declarative_table`,
  139. it may be placed directly inside the field metadata using a lambda::
  140. @dataclass
  141. class AddressMixin:
  142. __sa_dataclass_metadata_key__ = "sa"
  143. user_id: int = field(
  144. init=False, metadata={"sa": declared_attr(lambda: Column(ForeignKey("user.id")))}
  145. )
  146. user: User = field(
  147. init=False, metadata={"sa": declared_attr(lambda: relationship(User))}
  148. )
  149. :class:`_orm.declared_attr` also may be omitted from this form using a
  150. lambda directly, as in::
  151. user: User = field(
  152. init=False, metadata={"sa": lambda: relationship(User)}
  153. )
  154. .. seealso::
  155. :ref:`orm_mixins_toplevel` - illustrates how to use Declarative Mixins
  156. which is the primary use case for :class:`_orm.declared_attr`
  157. :ref:`orm_declarative_dataclasses_mixin` - illustrates special forms
  158. for use with Python dataclasses
  159. """ # noqa: E501
  160. def __init__(self, fget, cascading=False):
  161. super(declared_attr, self).__init__(fget)
  162. self.__doc__ = fget.__doc__
  163. self._cascading = cascading
  164. def __get__(desc, self, cls):
  165. # the declared_attr needs to make use of a cache that exists
  166. # for the span of the declarative scan_attributes() phase.
  167. # to achieve this we look at the class manager that's configured.
  168. manager = attributes.manager_of_class(cls)
  169. if manager is None:
  170. if not re.match(r"^__.+__$", desc.fget.__name__):
  171. # if there is no manager at all, then this class hasn't been
  172. # run through declarative or mapper() at all, emit a warning.
  173. util.warn(
  174. "Unmanaged access of declarative attribute %s from "
  175. "non-mapped class %s" % (desc.fget.__name__, cls.__name__)
  176. )
  177. return desc.fget(cls)
  178. elif manager.is_mapped:
  179. # the class is mapped, which means we're outside of the declarative
  180. # scan setup, just run the function.
  181. return desc.fget(cls)
  182. # here, we are inside of the declarative scan. use the registry
  183. # that is tracking the values of these attributes.
  184. declarative_scan = manager.declarative_scan()
  185. assert declarative_scan is not None
  186. reg = declarative_scan.declared_attr_reg
  187. if desc in reg:
  188. return reg[desc]
  189. else:
  190. reg[desc] = obj = desc.fget(cls)
  191. return obj
  192. @hybridmethod
  193. def _stateful(cls, **kw):
  194. return _stateful_declared_attr(**kw)
  195. @hybridproperty
  196. def cascading(cls):
  197. """Mark a :class:`.declared_attr` as cascading.
  198. This is a special-use modifier which indicates that a column
  199. or MapperProperty-based declared attribute should be configured
  200. distinctly per mapped subclass, within a mapped-inheritance scenario.
  201. .. warning::
  202. The :attr:`.declared_attr.cascading` modifier has several
  203. limitations:
  204. * The flag **only** applies to the use of :class:`.declared_attr`
  205. on declarative mixin classes and ``__abstract__`` classes; it
  206. currently has no effect when used on a mapped class directly.
  207. * The flag **only** applies to normally-named attributes, e.g.
  208. not any special underscore attributes such as ``__tablename__``.
  209. On these attributes it has **no** effect.
  210. * The flag currently **does not allow further overrides** down
  211. the class hierarchy; if a subclass tries to override the
  212. attribute, a warning is emitted and the overridden attribute
  213. is skipped. This is a limitation that it is hoped will be
  214. resolved at some point.
  215. Below, both MyClass as well as MySubClass will have a distinct
  216. ``id`` Column object established::
  217. class HasIdMixin(object):
  218. @declared_attr.cascading
  219. def id(cls):
  220. if has_inherited_table(cls):
  221. return Column(
  222. ForeignKey('myclass.id'), primary_key=True
  223. )
  224. else:
  225. return Column(Integer, primary_key=True)
  226. class MyClass(HasIdMixin, Base):
  227. __tablename__ = 'myclass'
  228. # ...
  229. class MySubClass(MyClass):
  230. ""
  231. # ...
  232. The behavior of the above configuration is that ``MySubClass``
  233. will refer to both its own ``id`` column as well as that of
  234. ``MyClass`` underneath the attribute named ``some_id``.
  235. .. seealso::
  236. :ref:`declarative_inheritance`
  237. :ref:`mixin_inheritance_columns`
  238. """
  239. return cls._stateful(cascading=True)
  240. class _stateful_declared_attr(declared_attr):
  241. def __init__(self, **kw):
  242. self.kw = kw
  243. def _stateful(self, **kw):
  244. new_kw = self.kw.copy()
  245. new_kw.update(kw)
  246. return _stateful_declared_attr(**new_kw)
  247. def __call__(self, fn):
  248. return declared_attr(fn, **self.kw)
  249. def declarative_mixin(cls):
  250. """Mark a class as providing the feature of "declarative mixin".
  251. E.g.::
  252. from sqlalchemy.orm import declared_attr
  253. from sqlalchemy.orm import declarative_mixin
  254. @declarative_mixin
  255. class MyMixin:
  256. @declared_attr
  257. def __tablename__(cls):
  258. return cls.__name__.lower()
  259. __table_args__ = {'mysql_engine': 'InnoDB'}
  260. __mapper_args__= {'always_refresh': True}
  261. id = Column(Integer, primary_key=True)
  262. class MyModel(MyMixin, Base):
  263. name = Column(String(1000))
  264. The :func:`_orm.declarative_mixin` decorator currently does not modify
  265. the given class in any way; it's current purpose is strictly to assist
  266. the :ref:`Mypy plugin <mypy_toplevel>` in being able to identify
  267. SQLAlchemy declarative mixin classes when no other context is present.
  268. .. versionadded:: 1.4.6
  269. .. seealso::
  270. :ref:`orm_mixins_toplevel`
  271. :ref:`mypy_declarative_mixins` - in the
  272. :ref:`Mypy plugin documentation <mypy_toplevel>`
  273. """ # noqa: E501
  274. return cls
  275. def declarative_base(
  276. bind=None,
  277. metadata=None,
  278. mapper=None,
  279. cls=object,
  280. name="Base",
  281. constructor=_declarative_constructor,
  282. class_registry=None,
  283. metaclass=DeclarativeMeta,
  284. ):
  285. r"""Construct a base class for declarative class definitions.
  286. The new base class will be given a metaclass that produces
  287. appropriate :class:`~sqlalchemy.schema.Table` objects and makes
  288. the appropriate :func:`~sqlalchemy.orm.mapper` calls based on the
  289. information provided declaratively in the class and any subclasses
  290. of the class.
  291. The :func:`_orm.declarative_base` function is a shorthand version
  292. of using the :meth:`_orm.registry.generate_base`
  293. method. That is, the following::
  294. from sqlalchemy.orm import declarative_base
  295. Base = declarative_base()
  296. Is equivalent to::
  297. from sqlalchemy.orm import registry
  298. mapper_registry = registry()
  299. Base = mapper_registry.generate_base()
  300. See the docstring for :class:`_orm.registry`
  301. and :meth:`_orm.registry.generate_base`
  302. for more details.
  303. .. versionchanged:: 1.4 The :func:`_orm.declarative_base`
  304. function is now a specialization of the more generic
  305. :class:`_orm.registry` class. The function also moves to the
  306. ``sqlalchemy.orm`` package from the ``declarative.ext`` package.
  307. :param bind: An optional
  308. :class:`~sqlalchemy.engine.Connectable`, will be assigned
  309. the ``bind`` attribute on the :class:`~sqlalchemy.schema.MetaData`
  310. instance.
  311. .. deprecated:: 1.4 The "bind" argument to declarative_base is
  312. deprecated and will be removed in SQLAlchemy 2.0.
  313. :param metadata:
  314. An optional :class:`~sqlalchemy.schema.MetaData` instance. All
  315. :class:`~sqlalchemy.schema.Table` objects implicitly declared by
  316. subclasses of the base will share this MetaData. A MetaData instance
  317. will be created if none is provided. The
  318. :class:`~sqlalchemy.schema.MetaData` instance will be available via the
  319. ``metadata`` attribute of the generated declarative base class.
  320. :param mapper:
  321. An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`. Will
  322. be used to map subclasses to their Tables.
  323. :param cls:
  324. Defaults to :class:`object`. A type to use as the base for the generated
  325. declarative base class. May be a class or tuple of classes.
  326. :param name:
  327. Defaults to ``Base``. The display name for the generated
  328. class. Customizing this is not required, but can improve clarity in
  329. tracebacks and debugging.
  330. :param constructor:
  331. Specify the implementation for the ``__init__`` function on a mapped
  332. class that has no ``__init__`` of its own. Defaults to an
  333. implementation that assigns \**kwargs for declared
  334. fields and relationships to an instance. If ``None`` is supplied,
  335. no __init__ will be provided and construction will fall back to
  336. cls.__init__ by way of the normal Python semantics.
  337. :param class_registry: optional dictionary that will serve as the
  338. registry of class names-> mapped classes when string names
  339. are used to identify classes inside of :func:`_orm.relationship`
  340. and others. Allows two or more declarative base classes
  341. to share the same registry of class names for simplified
  342. inter-base relationships.
  343. :param metaclass:
  344. Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__
  345. compatible callable to use as the meta type of the generated
  346. declarative base class.
  347. .. seealso::
  348. :class:`_orm.registry`
  349. """
  350. if bind is not None:
  351. # util.deprecated_params does not work
  352. util.warn_deprecated_20(
  353. "The ``bind`` argument to declarative_base is "
  354. "deprecated and will be removed in SQLAlchemy 2.0.",
  355. )
  356. return registry(
  357. _bind=bind,
  358. metadata=metadata,
  359. class_registry=class_registry,
  360. constructor=constructor,
  361. ).generate_base(
  362. mapper=mapper,
  363. cls=cls,
  364. name=name,
  365. metaclass=metaclass,
  366. )
  367. class registry(object):
  368. """Generalized registry for mapping classes.
  369. The :class:`_orm.registry` serves as the basis for maintaining a collection
  370. of mappings, and provides configurational hooks used to map classes.
  371. The three general kinds of mappings supported are Declarative Base,
  372. Declarative Decorator, and Imperative Mapping. All of these mapping
  373. styles may be used interchangeably:
  374. * :meth:`_orm.registry.generate_base` returns a new declarative base
  375. class, and is the underlying implementation of the
  376. :func:`_orm.declarative_base` function.
  377. * :meth:`_orm.registry.mapped` provides a class decorator that will
  378. apply declarative mapping to a class without the use of a declarative
  379. base class.
  380. * :meth:`_orm.registry.map_imperatively` will produce a
  381. :class:`_orm.Mapper` for a class without scanning the class for
  382. declarative class attributes. This method suits the use case historically
  383. provided by the
  384. :func:`_orm.mapper` classical mapping function.
  385. .. versionadded:: 1.4
  386. .. seealso::
  387. :ref:`orm_mapping_classes_toplevel` - overview of class mapping
  388. styles.
  389. """
  390. def __init__(
  391. self,
  392. metadata=None,
  393. class_registry=None,
  394. constructor=_declarative_constructor,
  395. _bind=None,
  396. ):
  397. r"""Construct a new :class:`_orm.registry`
  398. :param metadata:
  399. An optional :class:`_schema.MetaData` instance. All
  400. :class:`_schema.Table` objects generated using declarative
  401. table mapping will make use of this :class:`_schema.MetaData`
  402. collection. If this argument is left at its default of ``None``,
  403. a blank :class:`_schema.MetaData` collection is created.
  404. :param constructor:
  405. Specify the implementation for the ``__init__`` function on a mapped
  406. class that has no ``__init__`` of its own. Defaults to an
  407. implementation that assigns \**kwargs for declared
  408. fields and relationships to an instance. If ``None`` is supplied,
  409. no __init__ will be provided and construction will fall back to
  410. cls.__init__ by way of the normal Python semantics.
  411. :param class_registry: optional dictionary that will serve as the
  412. registry of class names-> mapped classes when string names
  413. are used to identify classes inside of :func:`_orm.relationship`
  414. and others. Allows two or more declarative base classes
  415. to share the same registry of class names for simplified
  416. inter-base relationships.
  417. """
  418. lcl_metadata = metadata or MetaData()
  419. if _bind:
  420. lcl_metadata.bind = _bind
  421. if class_registry is None:
  422. class_registry = weakref.WeakValueDictionary()
  423. self._class_registry = class_registry
  424. self._managers = weakref.WeakKeyDictionary()
  425. self._non_primary_mappers = weakref.WeakKeyDictionary()
  426. self.metadata = lcl_metadata
  427. self.constructor = constructor
  428. self._dependents = set()
  429. self._dependencies = set()
  430. self._new_mappers = False
  431. with mapperlib._CONFIGURE_MUTEX:
  432. mapperlib._mapper_registries[self] = True
  433. @property
  434. def mappers(self):
  435. """read only collection of all :class:`_orm.Mapper` objects."""
  436. return frozenset(manager.mapper for manager in self._managers).union(
  437. self._non_primary_mappers
  438. )
  439. def _set_depends_on(self, registry):
  440. if registry is self:
  441. return
  442. registry._dependents.add(self)
  443. self._dependencies.add(registry)
  444. def _flag_new_mapper(self, mapper):
  445. mapper._ready_for_configure = True
  446. if self._new_mappers:
  447. return
  448. for reg in self._recurse_with_dependents({self}):
  449. reg._new_mappers = True
  450. @classmethod
  451. def _recurse_with_dependents(cls, registries):
  452. todo = registries
  453. done = set()
  454. while todo:
  455. reg = todo.pop()
  456. done.add(reg)
  457. # if yielding would remove dependents, make sure we have
  458. # them before
  459. todo.update(reg._dependents.difference(done))
  460. yield reg
  461. # if yielding would add dependents, make sure we have them
  462. # after
  463. todo.update(reg._dependents.difference(done))
  464. @classmethod
  465. def _recurse_with_dependencies(cls, registries):
  466. todo = registries
  467. done = set()
  468. while todo:
  469. reg = todo.pop()
  470. done.add(reg)
  471. # if yielding would remove dependencies, make sure we have
  472. # them before
  473. todo.update(reg._dependencies.difference(done))
  474. yield reg
  475. # if yielding would remove dependencies, make sure we have
  476. # them before
  477. todo.update(reg._dependencies.difference(done))
  478. def _mappers_to_configure(self):
  479. return itertools.chain(
  480. (
  481. manager.mapper
  482. for manager in list(self._managers)
  483. if manager.is_mapped
  484. and not manager.mapper.configured
  485. and manager.mapper._ready_for_configure
  486. ),
  487. (
  488. npm
  489. for npm in list(self._non_primary_mappers)
  490. if not npm.configured and npm._ready_for_configure
  491. ),
  492. )
  493. def _add_non_primary_mapper(self, np_mapper):
  494. self._non_primary_mappers[np_mapper] = True
  495. def _dispose_cls(self, cls):
  496. clsregistry.remove_class(cls.__name__, cls, self._class_registry)
  497. def _add_manager(self, manager):
  498. self._managers[manager] = True
  499. if manager.registry is not None and manager.is_mapped:
  500. raise exc.ArgumentError(
  501. "Class '%s' already has a primary mapper defined. "
  502. % manager.class_
  503. )
  504. manager.registry = self
  505. def configure(self, cascade=False):
  506. """Configure all as-yet unconfigured mappers in this
  507. :class:`_orm.registry`.
  508. The configure step is used to reconcile and initialize the
  509. :func:`_orm.relationship` linkages between mapped classes, as well as
  510. to invoke configuration events such as the
  511. :meth:`_orm.MapperEvents.before_configured` and
  512. :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM
  513. extensions or user-defined extension hooks.
  514. If one or more mappers in this registry contain
  515. :func:`_orm.relationship` constructs that refer to mapped classes in
  516. other registries, this registry is said to be *dependent* on those
  517. registries. In order to configure those dependent registries
  518. automatically, the :paramref:`_orm.registry.configure.cascade` flag
  519. should be set to ``True``. Otherwise, if they are not configured, an
  520. exception will be raised. The rationale behind this behavior is to
  521. allow an application to programmatically invoke configuration of
  522. registries while controlling whether or not the process implicitly
  523. reaches other registries.
  524. As an alternative to invoking :meth:`_orm.registry.configure`, the ORM
  525. function :func:`_orm.configure_mappers` function may be used to ensure
  526. configuration is complete for all :class:`_orm.registry` objects in
  527. memory. This is generally simpler to use and also predates the usage of
  528. :class:`_orm.registry` objects overall. However, this function will
  529. impact all mappings throughout the running Python process and may be
  530. more memory/time consuming for an application that has many registries
  531. in use for different purposes that may not be needed immediately.
  532. .. seealso::
  533. :func:`_orm.configure_mappers`
  534. .. versionadded:: 1.4.0b2
  535. """
  536. mapperlib._configure_registries({self}, cascade=cascade)
  537. def dispose(self, cascade=False):
  538. """Dispose of all mappers in this :class:`_orm.registry`.
  539. After invocation, all the classes that were mapped within this registry
  540. will no longer have class instrumentation associated with them. This
  541. method is the per-:class:`_orm.registry` analogue to the
  542. application-wide :func:`_orm.clear_mappers` function.
  543. If this registry contains mappers that are dependencies of other
  544. registries, typically via :func:`_orm.relationship` links, then those
  545. registries must be disposed as well. When such registries exist in
  546. relation to this one, their :meth:`_orm.registry.dispose` method will
  547. also be called, if the :paramref:`_orm.registry.dispose.cascade` flag
  548. is set to ``True``; otherwise, an error is raised if those registries
  549. were not already disposed.
  550. .. versionadded:: 1.4.0b2
  551. .. seealso::
  552. :func:`_orm.clear_mappers`
  553. """
  554. mapperlib._dispose_registries({self}, cascade=cascade)
  555. def _dispose_manager_and_mapper(self, manager):
  556. if "mapper" in manager.__dict__:
  557. mapper = manager.mapper
  558. mapper._set_dispose_flags()
  559. class_ = manager.class_
  560. self._dispose_cls(class_)
  561. instrumentation._instrumentation_factory.unregister(class_)
  562. def generate_base(
  563. self,
  564. mapper=None,
  565. cls=object,
  566. name="Base",
  567. metaclass=DeclarativeMeta,
  568. ):
  569. """Generate a declarative base class.
  570. Classes that inherit from the returned class object will be
  571. automatically mapped using declarative mapping.
  572. E.g.::
  573. from sqlalchemy.orm import registry
  574. mapper_registry = registry()
  575. Base = mapper_registry.generate_base()
  576. class MyClass(Base):
  577. __tablename__ = "my_table"
  578. id = Column(Integer, primary_key=True)
  579. The above dynamically generated class is equivalent to the
  580. non-dynamic example below::
  581. from sqlalchemy.orm import registry
  582. from sqlalchemy.orm.decl_api import DeclarativeMeta
  583. mapper_registry = registry()
  584. class Base(metaclass=DeclarativeMeta):
  585. __abstract__ = True
  586. registry = mapper_registry
  587. metadata = mapper_registry.metadata
  588. __init__ = mapper_registry.constructor
  589. The :meth:`_orm.registry.generate_base` method provides the
  590. implementation for the :func:`_orm.declarative_base` function, which
  591. creates the :class:`_orm.registry` and base class all at once.
  592. See the section :ref:`orm_declarative_mapping` for background and
  593. examples.
  594. :param mapper:
  595. An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`.
  596. This function is used to generate new :class:`_orm.Mapper` objects.
  597. :param cls:
  598. Defaults to :class:`object`. A type to use as the base for the
  599. generated declarative base class. May be a class or tuple of classes.
  600. :param name:
  601. Defaults to ``Base``. The display name for the generated
  602. class. Customizing this is not required, but can improve clarity in
  603. tracebacks and debugging.
  604. :param metaclass:
  605. Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__
  606. compatible callable to use as the meta type of the generated
  607. declarative base class.
  608. .. seealso::
  609. :ref:`orm_declarative_mapping`
  610. :func:`_orm.declarative_base`
  611. """
  612. metadata = self.metadata
  613. bases = not isinstance(cls, tuple) and (cls,) or cls
  614. class_dict = dict(registry=self, metadata=metadata)
  615. if isinstance(cls, type):
  616. class_dict["__doc__"] = cls.__doc__
  617. if self.constructor:
  618. class_dict["__init__"] = self.constructor
  619. class_dict["__abstract__"] = True
  620. if mapper:
  621. class_dict["__mapper_cls__"] = mapper
  622. if hasattr(cls, "__class_getitem__"):
  623. def __class_getitem__(cls, key):
  624. # allow generic classes in py3.9+
  625. return cls
  626. class_dict["__class_getitem__"] = __class_getitem__
  627. return metaclass(name, bases, class_dict)
  628. def mapped(self, cls):
  629. """Class decorator that will apply the Declarative mapping process
  630. to a given class.
  631. E.g.::
  632. from sqlalchemy.orm import registry
  633. mapper_registry = registry()
  634. @mapper_registry.mapped
  635. class Foo:
  636. __tablename__ = 'some_table'
  637. id = Column(Integer, primary_key=True)
  638. name = Column(String)
  639. See the section :ref:`orm_declarative_mapping` for complete
  640. details and examples.
  641. :param cls: class to be mapped.
  642. :return: the class that was passed.
  643. .. seealso::
  644. :ref:`orm_declarative_mapping`
  645. :meth:`_orm.registry.generate_base` - generates a base class
  646. that will apply Declarative mapping to subclasses automatically
  647. using a Python metaclass.
  648. """
  649. _as_declarative(self, cls, cls.__dict__)
  650. return cls
  651. def as_declarative_base(self, **kw):
  652. """
  653. Class decorator which will invoke
  654. :meth:`_orm.registry.generate_base`
  655. for a given base class.
  656. E.g.::
  657. from sqlalchemy.orm import registry
  658. mapper_registry = registry()
  659. @mapper_registry.as_declarative_base()
  660. class Base(object):
  661. @declared_attr
  662. def __tablename__(cls):
  663. return cls.__name__.lower()
  664. id = Column(Integer, primary_key=True)
  665. class MyMappedClass(Base):
  666. # ...
  667. All keyword arguments passed to
  668. :meth:`_orm.registry.as_declarative_base` are passed
  669. along to :meth:`_orm.registry.generate_base`.
  670. """
  671. def decorate(cls):
  672. kw["cls"] = cls
  673. kw["name"] = cls.__name__
  674. return self.generate_base(**kw)
  675. return decorate
  676. def map_declaratively(self, cls):
  677. """Map a class declaratively.
  678. In this form of mapping, the class is scanned for mapping information,
  679. including for columns to be associated with a table, and/or an
  680. actual table object.
  681. Returns the :class:`_orm.Mapper` object.
  682. E.g.::
  683. from sqlalchemy.orm import registry
  684. mapper_registry = registry()
  685. class Foo:
  686. __tablename__ = 'some_table'
  687. id = Column(Integer, primary_key=True)
  688. name = Column(String)
  689. mapper = mapper_registry.map_declaratively(Foo)
  690. This function is more conveniently invoked indirectly via either the
  691. :meth:`_orm.registry.mapped` class decorator or by subclassing a
  692. declarative metaclass generated from
  693. :meth:`_orm.registry.generate_base`.
  694. See the section :ref:`orm_declarative_mapping` for complete
  695. details and examples.
  696. :param cls: class to be mapped.
  697. :return: a :class:`_orm.Mapper` object.
  698. .. seealso::
  699. :ref:`orm_declarative_mapping`
  700. :meth:`_orm.registry.mapped` - more common decorator interface
  701. to this function.
  702. :meth:`_orm.registry.map_imperatively`
  703. """
  704. return _as_declarative(self, cls, cls.__dict__)
  705. def map_imperatively(self, class_, local_table=None, **kw):
  706. r"""Map a class imperatively.
  707. In this form of mapping, the class is not scanned for any mapping
  708. information. Instead, all mapping constructs are passed as
  709. arguments.
  710. This method is intended to be fully equivalent to the classic
  711. SQLAlchemy :func:`_orm.mapper` function, except that it's in terms of
  712. a particular registry.
  713. E.g.::
  714. from sqlalchemy.orm import registry
  715. mapper_registry = registry()
  716. my_table = Table(
  717. "my_table",
  718. mapper_registry.metadata,
  719. Column('id', Integer, primary_key=True)
  720. )
  721. class MyClass:
  722. pass
  723. mapper_registry.map_imperatively(MyClass, my_table)
  724. See the section :ref:`orm_imperative_mapping` for complete background
  725. and usage examples.
  726. :param class\_: The class to be mapped. Corresponds to the
  727. :paramref:`_orm.mapper.class_` parameter.
  728. :param local_table: the :class:`_schema.Table` or other
  729. :class:`_sql.FromClause` object that is the subject of the mapping.
  730. Corresponds to the
  731. :paramref:`_orm.mapper.local_table` parameter.
  732. :param \**kw: all other keyword arguments are passed to the
  733. :func:`_orm.mapper` function directly.
  734. .. seealso::
  735. :ref:`orm_imperative_mapping`
  736. :ref:`orm_declarative_mapping`
  737. """
  738. return _mapper(self, class_, local_table, kw)
  739. mapperlib._legacy_registry = registry()
  740. @util.deprecated_params(
  741. bind=(
  742. "2.0",
  743. "The ``bind`` argument to as_declarative is "
  744. "deprecated and will be removed in SQLAlchemy 2.0.",
  745. )
  746. )
  747. def as_declarative(**kw):
  748. """
  749. Class decorator which will adapt a given class into a
  750. :func:`_orm.declarative_base`.
  751. This function makes use of the :meth:`_orm.registry.as_declarative_base`
  752. method, by first creating a :class:`_orm.registry` automatically
  753. and then invoking the decorator.
  754. E.g.::
  755. from sqlalchemy.orm import as_declarative
  756. @as_declarative()
  757. class Base(object):
  758. @declared_attr
  759. def __tablename__(cls):
  760. return cls.__name__.lower()
  761. id = Column(Integer, primary_key=True)
  762. class MyMappedClass(Base):
  763. # ...
  764. .. seealso::
  765. :meth:`_orm.registry.as_declarative_base`
  766. """
  767. bind, metadata, class_registry = (
  768. kw.pop("bind", None),
  769. kw.pop("metadata", None),
  770. kw.pop("class_registry", None),
  771. )
  772. return registry(
  773. _bind=bind, metadata=metadata, class_registry=class_registry
  774. ).as_declarative_base(**kw)
  775. @inspection._inspects(DeclarativeMeta)
  776. def _inspect_decl_meta(cls):
  777. mp = _inspect_mapped_class(cls)
  778. if mp is None:
  779. if _DeferredMapperConfig.has_cls(cls):
  780. _DeferredMapperConfig.raise_unmapped_for_cls(cls)
  781. raise orm_exc.UnmappedClassError(
  782. cls,
  783. msg="Class %s has a deferred mapping on it. It is not yet "
  784. "usable as a mapped class." % orm_exc._safe_cls_name(cls),
  785. )
  786. return mp