decl_api.py 36 KB

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