You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1044 lines
34KB

  1. # ext/declarative/api.py
  2. # Copyright (C) 2005-2021 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: http://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 classe,
  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 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 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. assert manager.registry is None
  496. manager.registry = self
  497. def configure(self, cascade=False):
  498. """Configure all as-yet unconfigured mappers in this
  499. :class:`_orm.registry`.
  500. The configure step is used to reconcile and initialize the
  501. :func:`_orm.relationship` linkages between mapped classes, as well as
  502. to invoke configuration events such as the
  503. :meth:`_orm.MapperEvents.before_configured` and
  504. :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM
  505. extensions or user-defined extension hooks.
  506. If one or more mappers in this registry contain
  507. :func:`_orm.relationship` constructs that refer to mapped classes in
  508. other registries, this registry is said to be *dependent* on those
  509. registries. In order to configure those dependent registries
  510. automatically, the :paramref:`_orm.registry.configure.cascade` flag
  511. should be set to ``True``. Otherwise, if they are not configured, an
  512. exception will be raised. The rationale behind this behavior is to
  513. allow an application to programmatically invoke configuration of
  514. registries while controlling whether or not the process implicitly
  515. reaches other registries.
  516. As an alternative to invoking :meth:`_orm.registry.configure`, the ORM
  517. function :func:`_orm.configure_mappers` function may be used to ensure
  518. configuration is complete for all :class:`_orm.registry` objects in
  519. memory. This is generally simpler to use and also predates the usage of
  520. :class:`_orm.registry` objects overall. However, this function will
  521. impact all mappings throughout the running Python process and may be
  522. more memory/time consuming for an application that has many registries
  523. in use for different purposes that may not be needed immediately.
  524. .. seealso::
  525. :func:`_orm.configure_mappers`
  526. .. versionadded:: 1.4.0b2
  527. """
  528. mapperlib._configure_registries({self}, cascade=cascade)
  529. def dispose(self, cascade=False):
  530. """Dispose of all mappers in this :class:`_orm.registry`.
  531. After invocation, all the classes that were mapped within this registry
  532. will no longer have class instrumentation associated with them. This
  533. method is the per-:class:`_orm.registry` analogue to the
  534. application-wide :func:`_orm.clear_mappers` function.
  535. If this registry contains mappers that are dependencies of other
  536. registries, typically via :func:`_orm.relationship` links, then those
  537. registries must be disposed as well. When such registries exist in
  538. relation to this one, their :meth:`_orm.registry.dispose` method will
  539. also be called, if the :paramref:`_orm.registry.dispose.cascade` flag
  540. is set to ``True``; otherwise, an error is raised if those registries
  541. were not already disposed.
  542. .. versionadded:: 1.4.0b2
  543. .. seealso::
  544. :func:`_orm.clear_mappers`
  545. """
  546. mapperlib._dispose_registries({self}, cascade=cascade)
  547. def _dispose_manager_and_mapper(self, manager):
  548. if "mapper" in manager.__dict__:
  549. mapper = manager.mapper
  550. mapper._set_dispose_flags()
  551. class_ = manager.class_
  552. self._dispose_cls(class_)
  553. instrumentation._instrumentation_factory.unregister(class_)
  554. def generate_base(
  555. self,
  556. mapper=None,
  557. cls=object,
  558. name="Base",
  559. metaclass=DeclarativeMeta,
  560. ):
  561. """Generate a declarative base class.
  562. Classes that inherit from the returned class object will be
  563. automatically mapped using declarative mapping.
  564. E.g.::
  565. from sqlalchemy.orm import registry
  566. mapper_registry = registry()
  567. Base = mapper_registry.generate_base()
  568. class MyClass(Base):
  569. __tablename__ = "my_table"
  570. id = Column(Integer, primary_key=True)
  571. The above dynamically generated class is equivalent to the
  572. non-dynamic example below::
  573. from sqlalchemy.orm import registry
  574. from sqlalchemy.orm.decl_api import DeclarativeMeta
  575. mapper_registry = registry()
  576. class Base(metaclass=DeclarativeMeta):
  577. __abstract__ = True
  578. registry = mapper_registry
  579. metadata = mapper_registry.metadata
  580. The :meth:`_orm.registry.generate_base` method provides the
  581. implementation for the :func:`_orm.declarative_base` function, which
  582. creates the :class:`_orm.registry` and base class all at once.
  583. See the section :ref:`orm_declarative_mapping` for background and
  584. examples.
  585. :param mapper:
  586. An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`.
  587. This function is used to generate new :class:`_orm.Mapper` objects.
  588. :param cls:
  589. Defaults to :class:`object`. A type to use as the base for the
  590. generated declarative base class. May be a class or tuple of classes.
  591. :param name:
  592. Defaults to ``Base``. The display name for the generated
  593. class. Customizing this is not required, but can improve clarity in
  594. tracebacks and debugging.
  595. :param metaclass:
  596. Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__
  597. compatible callable to use as the meta type of the generated
  598. declarative base class.
  599. .. seealso::
  600. :ref:`orm_declarative_mapping`
  601. :func:`_orm.declarative_base`
  602. """
  603. metadata = self.metadata
  604. bases = not isinstance(cls, tuple) and (cls,) or cls
  605. class_dict = dict(registry=self, metadata=metadata)
  606. if isinstance(cls, type):
  607. class_dict["__doc__"] = cls.__doc__
  608. if self.constructor:
  609. class_dict["__init__"] = self.constructor
  610. class_dict["__abstract__"] = True
  611. if mapper:
  612. class_dict["__mapper_cls__"] = mapper
  613. return metaclass(name, bases, class_dict)
  614. def mapped(self, cls):
  615. """Class decorator that will apply the Declarative mapping process
  616. to a given class.
  617. E.g.::
  618. from sqlalchemy.orm import registry
  619. mapper_registry = registry()
  620. @mapper_registry.mapped
  621. class Foo:
  622. __tablename__ = 'some_table'
  623. id = Column(Integer, primary_key=True)
  624. name = Column(String)
  625. See the section :ref:`orm_declarative_mapping` for complete
  626. details and examples.
  627. :param cls: class to be mapped.
  628. :return: the class that was passed.
  629. .. seealso::
  630. :ref:`orm_declarative_mapping`
  631. :meth:`_orm.registry.generate_base` - generates a base class
  632. that will apply Declarative mapping to subclasses automatically
  633. using a Python metaclass.
  634. """
  635. _as_declarative(self, cls, cls.__dict__)
  636. return cls
  637. def as_declarative_base(self, **kw):
  638. """
  639. Class decorator which will invoke
  640. :meth:`_orm.registry.generate_base`
  641. for a given base class.
  642. E.g.::
  643. from sqlalchemy.orm import registry
  644. mapper_registry = registry()
  645. @mapper_registry.as_declarative_base()
  646. class Base(object):
  647. @declared_attr
  648. def __tablename__(cls):
  649. return cls.__name__.lower()
  650. id = Column(Integer, primary_key=True)
  651. class MyMappedClass(Base):
  652. # ...
  653. All keyword arguments passed to
  654. :meth:`_orm.registry.as_declarative_base` are passed
  655. along to :meth:`_orm.registry.generate_base`.
  656. """
  657. def decorate(cls):
  658. kw["cls"] = cls
  659. kw["name"] = cls.__name__
  660. return self.generate_base(**kw)
  661. return decorate
  662. def map_declaratively(self, cls):
  663. """Map a class declaratively.
  664. In this form of mapping, the class is scanned for mapping information,
  665. including for columns to be associated with a table, and/or an
  666. actual table object.
  667. Returns the :class:`_orm.Mapper` object.
  668. E.g.::
  669. from sqlalchemy.orm import registry
  670. mapper_registry = registry()
  671. class Foo:
  672. __tablename__ = 'some_table'
  673. id = Column(Integer, primary_key=True)
  674. name = Column(String)
  675. mapper = mapper_registry.map_declaratively(Foo)
  676. This function is more conveniently invoked indirectly via either the
  677. :meth:`_orm.registry.mapped` class decorator or by subclassing a
  678. declarative metaclass generated from
  679. :meth:`_orm.registry.generate_base`.
  680. See the section :ref:`orm_declarative_mapping` for complete
  681. details and examples.
  682. :param cls: class to be mapped.
  683. :return: a :class:`_orm.Mapper` object.
  684. .. seealso::
  685. :ref:`orm_declarative_mapping`
  686. :meth:`_orm.registry.mapped` - more common decorator interface
  687. to this function.
  688. :meth:`_orm.registry.map_imperatively`
  689. """
  690. return _as_declarative(self, cls, cls.__dict__)
  691. def map_imperatively(self, class_, local_table=None, **kw):
  692. r"""Map a class imperatively.
  693. In this form of mapping, the class is not scanned for any mapping
  694. information. Instead, all mapping constructs are passed as
  695. arguments.
  696. This method is intended to be fully equivalent to the classic
  697. SQLAlchemy :func:`_orm.mapper` function, except that it's in terms of
  698. a particular registry.
  699. E.g.::
  700. from sqlalchemy.orm import registry
  701. mapper_registry = registry()
  702. my_table = Table(
  703. "my_table",
  704. mapper_registry.metadata,
  705. Column('id', Integer, primary_key=True)
  706. )
  707. class MyClass:
  708. pass
  709. mapper_registry.map_imperatively(MyClass, my_table)
  710. See the section :ref:`orm_imperative_mapping` for complete background
  711. and usage examples.
  712. :param class\_: The class to be mapped. Corresponds to the
  713. :paramref:`_orm.mapper.class_` parameter.
  714. :param local_table: the :class:`_schema.Table` or other
  715. :class:`_sql.FromClause` object that is the subject of the mapping.
  716. Corresponds to the
  717. :paramref:`_orm.mapper.local_table` parameter.
  718. :param \**kw: all other keyword arguments are passed to the
  719. :func:`_orm.mapper` function directly.
  720. .. seealso::
  721. :ref:`orm_imperative_mapping`
  722. :ref:`orm_declarative_mapping`
  723. """
  724. return _mapper(self, class_, local_table, kw)
  725. mapperlib._legacy_registry = registry()
  726. @util.deprecated_params(
  727. bind=(
  728. "2.0",
  729. "The ``bind`` argument to as_declarative is "
  730. "deprecated and will be removed in SQLAlchemy 2.0.",
  731. )
  732. )
  733. def as_declarative(**kw):
  734. """
  735. Class decorator which will adapt a given class into a
  736. :func:`_orm.declarative_base`.
  737. This function makes use of the :meth:`_orm.registry.as_declarative_base`
  738. method, by first creating a :class:`_orm.registry` automatically
  739. and then invoking the decorator.
  740. E.g.::
  741. from sqlalchemy.orm import as_declarative
  742. @as_declarative()
  743. class Base(object):
  744. @declared_attr
  745. def __tablename__(cls):
  746. return cls.__name__.lower()
  747. id = Column(Integer, primary_key=True)
  748. class MyMappedClass(Base):
  749. # ...
  750. .. seealso::
  751. :meth:`_orm.registry.as_declarative_base`
  752. """
  753. bind, metadata, class_registry = (
  754. kw.pop("bind", None),
  755. kw.pop("metadata", None),
  756. kw.pop("class_registry", None),
  757. )
  758. return registry(
  759. _bind=bind, metadata=metadata, class_registry=class_registry
  760. ).as_declarative_base(**kw)
  761. @inspection._inspects(DeclarativeMeta)
  762. def _inspect_decl_meta(cls):
  763. mp = _inspect_mapped_class(cls)
  764. if mp is None:
  765. if _DeferredMapperConfig.has_cls(cls):
  766. _DeferredMapperConfig.raise_unmapped_for_cls(cls)
  767. raise orm_exc.UnmappedClassError(
  768. cls,
  769. msg="Class %s has a deferred mapping on it. It is not yet "
  770. "usable as a mapped class." % orm_exc._safe_cls_name(cls),
  771. )
  772. return mp