extensions.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. # ext/declarative/extensions.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 ... import inspection
  9. from ... import util
  10. from ...orm import exc as orm_exc
  11. from ...orm import registry
  12. from ...orm import relationships
  13. from ...orm.base import _mapper_or_none
  14. from ...orm.clsregistry import _resolver
  15. from ...orm.decl_base import _DeferredMapperConfig
  16. from ...orm.util import polymorphic_union
  17. from ...schema import Table
  18. from ...util import OrderedDict
  19. @util.deprecated(
  20. "2.0",
  21. "the instrument_declarative function is deprecated "
  22. "and will be removed in SQLAlhcemy 2.0. Please use "
  23. ":meth:`_orm.registry.map_declaratively",
  24. )
  25. def instrument_declarative(cls, cls_registry, metadata):
  26. """Given a class, configure the class declaratively,
  27. using the given registry, which can be any dictionary, and
  28. MetaData object.
  29. """
  30. registry(metadata=metadata, class_registry=cls_registry).map_declaratively(
  31. cls
  32. )
  33. class ConcreteBase(object):
  34. """A helper class for 'concrete' declarative mappings.
  35. :class:`.ConcreteBase` will use the :func:`.polymorphic_union`
  36. function automatically, against all tables mapped as a subclass
  37. to this class. The function is called via the
  38. ``__declare_last__()`` function, which is essentially
  39. a hook for the :meth:`.after_configured` event.
  40. :class:`.ConcreteBase` produces a mapped
  41. table for the class itself. Compare to :class:`.AbstractConcreteBase`,
  42. which does not.
  43. Example::
  44. from sqlalchemy.ext.declarative import ConcreteBase
  45. class Employee(ConcreteBase, Base):
  46. __tablename__ = 'employee'
  47. employee_id = Column(Integer, primary_key=True)
  48. name = Column(String(50))
  49. __mapper_args__ = {
  50. 'polymorphic_identity':'employee',
  51. 'concrete':True}
  52. class Manager(Employee):
  53. __tablename__ = 'manager'
  54. employee_id = Column(Integer, primary_key=True)
  55. name = Column(String(50))
  56. manager_data = Column(String(40))
  57. __mapper_args__ = {
  58. 'polymorphic_identity':'manager',
  59. 'concrete':True}
  60. The name of the discriminator column used by :func:`.polymorphic_union`
  61. defaults to the name ``type``. To suit the use case of a mapping where an
  62. actual column in a mapped table is already named ``type``, the
  63. discriminator name can be configured by setting the
  64. ``_concrete_discriminator_name`` attribute::
  65. class Employee(ConcreteBase, Base):
  66. _concrete_discriminator_name = '_concrete_discriminator'
  67. .. versionadded:: 1.3.19 Added the ``_concrete_discriminator_name``
  68. attribute to :class:`_declarative.ConcreteBase` so that the
  69. virtual discriminator column name can be customized.
  70. .. versionchanged:: 1.4.2 The ``_concrete_discriminator_name`` attribute
  71. need only be placed on the basemost class to take correct effect for
  72. all subclasses. An explicit error message is now raised if the
  73. mapped column names conflict with the discriminator name, whereas
  74. in the 1.3.x series there would be some warnings and then a non-useful
  75. query would be generated.
  76. .. seealso::
  77. :class:`.AbstractConcreteBase`
  78. :ref:`concrete_inheritance`
  79. """
  80. @classmethod
  81. def _create_polymorphic_union(cls, mappers, discriminator_name):
  82. return polymorphic_union(
  83. OrderedDict(
  84. (mp.polymorphic_identity, mp.local_table) for mp in mappers
  85. ),
  86. discriminator_name,
  87. "pjoin",
  88. )
  89. @classmethod
  90. def __declare_first__(cls):
  91. m = cls.__mapper__
  92. if m.with_polymorphic:
  93. return
  94. discriminator_name = (
  95. getattr(cls, "_concrete_discriminator_name", None) or "type"
  96. )
  97. mappers = list(m.self_and_descendants)
  98. pjoin = cls._create_polymorphic_union(mappers, discriminator_name)
  99. m._set_with_polymorphic(("*", pjoin))
  100. m._set_polymorphic_on(pjoin.c[discriminator_name])
  101. class AbstractConcreteBase(ConcreteBase):
  102. """A helper class for 'concrete' declarative mappings.
  103. :class:`.AbstractConcreteBase` will use the :func:`.polymorphic_union`
  104. function automatically, against all tables mapped as a subclass
  105. to this class. The function is called via the
  106. ``__declare_last__()`` function, which is essentially
  107. a hook for the :meth:`.after_configured` event.
  108. :class:`.AbstractConcreteBase` does produce a mapped class
  109. for the base class, however it is not persisted to any table; it
  110. is instead mapped directly to the "polymorphic" selectable directly
  111. and is only used for selecting. Compare to :class:`.ConcreteBase`,
  112. which does create a persisted table for the base class.
  113. .. note::
  114. The :class:`.AbstractConcreteBase` class does not intend to set up the
  115. mapping for the base class until all the subclasses have been defined,
  116. as it needs to create a mapping against a selectable that will include
  117. all subclass tables. In order to achieve this, it waits for the
  118. **mapper configuration event** to occur, at which point it scans
  119. through all the configured subclasses and sets up a mapping that will
  120. query against all subclasses at once.
  121. While this event is normally invoked automatically, in the case of
  122. :class:`.AbstractConcreteBase`, it may be necessary to invoke it
  123. explicitly after **all** subclass mappings are defined, if the first
  124. operation is to be a query against this base class. To do so, invoke
  125. :func:`.configure_mappers` once all the desired classes have been
  126. configured::
  127. from sqlalchemy.orm import configure_mappers
  128. configure_mappers()
  129. .. seealso::
  130. :func:`_orm.configure_mappers`
  131. Example::
  132. from sqlalchemy.ext.declarative import AbstractConcreteBase
  133. class Employee(AbstractConcreteBase, Base):
  134. pass
  135. class Manager(Employee):
  136. __tablename__ = 'manager'
  137. employee_id = Column(Integer, primary_key=True)
  138. name = Column(String(50))
  139. manager_data = Column(String(40))
  140. __mapper_args__ = {
  141. 'polymorphic_identity':'manager',
  142. 'concrete':True}
  143. configure_mappers()
  144. The abstract base class is handled by declarative in a special way;
  145. at class configuration time, it behaves like a declarative mixin
  146. or an ``__abstract__`` base class. Once classes are configured
  147. and mappings are produced, it then gets mapped itself, but
  148. after all of its descendants. This is a very unique system of mapping
  149. not found in any other SQLAlchemy system.
  150. Using this approach, we can specify columns and properties
  151. that will take place on mapped subclasses, in the way that
  152. we normally do as in :ref:`declarative_mixins`::
  153. class Company(Base):
  154. __tablename__ = 'company'
  155. id = Column(Integer, primary_key=True)
  156. class Employee(AbstractConcreteBase, Base):
  157. employee_id = Column(Integer, primary_key=True)
  158. @declared_attr
  159. def company_id(cls):
  160. return Column(ForeignKey('company.id'))
  161. @declared_attr
  162. def company(cls):
  163. return relationship("Company")
  164. class Manager(Employee):
  165. __tablename__ = 'manager'
  166. name = Column(String(50))
  167. manager_data = Column(String(40))
  168. __mapper_args__ = {
  169. 'polymorphic_identity':'manager',
  170. 'concrete':True}
  171. configure_mappers()
  172. When we make use of our mappings however, both ``Manager`` and
  173. ``Employee`` will have an independently usable ``.company`` attribute::
  174. session.query(Employee).filter(Employee.company.has(id=5))
  175. .. versionchanged:: 1.0.0 - The mechanics of :class:`.AbstractConcreteBase`
  176. have been reworked to support relationships established directly
  177. on the abstract base, without any special configurational steps.
  178. .. seealso::
  179. :class:`.ConcreteBase`
  180. :ref:`concrete_inheritance`
  181. """
  182. __no_table__ = True
  183. @classmethod
  184. def __declare_first__(cls):
  185. cls._sa_decl_prepare_nocascade()
  186. @classmethod
  187. def _sa_decl_prepare_nocascade(cls):
  188. if getattr(cls, "__mapper__", None):
  189. return
  190. to_map = _DeferredMapperConfig.config_for_cls(cls)
  191. # can't rely on 'self_and_descendants' here
  192. # since technically an immediate subclass
  193. # might not be mapped, but a subclass
  194. # may be.
  195. mappers = []
  196. stack = list(cls.__subclasses__())
  197. while stack:
  198. klass = stack.pop()
  199. stack.extend(klass.__subclasses__())
  200. mn = _mapper_or_none(klass)
  201. if mn is not None:
  202. mappers.append(mn)
  203. discriminator_name = (
  204. getattr(cls, "_concrete_discriminator_name", None) or "type"
  205. )
  206. pjoin = cls._create_polymorphic_union(mappers, discriminator_name)
  207. # For columns that were declared on the class, these
  208. # are normally ignored with the "__no_table__" mapping,
  209. # unless they have a different attribute key vs. col name
  210. # and are in the properties argument.
  211. # In that case, ensure we update the properties entry
  212. # to the correct column from the pjoin target table.
  213. declared_cols = set(to_map.declared_columns)
  214. for k, v in list(to_map.properties.items()):
  215. if v in declared_cols:
  216. to_map.properties[k] = pjoin.c[v.key]
  217. to_map.local_table = pjoin
  218. m_args = to_map.mapper_args_fn or dict
  219. def mapper_args():
  220. args = m_args()
  221. args["polymorphic_on"] = pjoin.c[discriminator_name]
  222. return args
  223. to_map.mapper_args_fn = mapper_args
  224. m = to_map.map()
  225. for scls in cls.__subclasses__():
  226. sm = _mapper_or_none(scls)
  227. if sm and sm.concrete and cls in scls.__bases__:
  228. sm._set_concrete_base(m)
  229. @classmethod
  230. def _sa_raise_deferred_config(cls):
  231. raise orm_exc.UnmappedClassError(
  232. cls,
  233. msg="Class %s is a subclass of AbstractConcreteBase and "
  234. "has a mapping pending until all subclasses are defined. "
  235. "Call the sqlalchemy.orm.configure_mappers() function after "
  236. "all subclasses have been defined to "
  237. "complete the mapping of this class."
  238. % orm_exc._safe_cls_name(cls),
  239. )
  240. class DeferredReflection(object):
  241. """A helper class for construction of mappings based on
  242. a deferred reflection step.
  243. Normally, declarative can be used with reflection by
  244. setting a :class:`_schema.Table` object using autoload_with=engine
  245. as the ``__table__`` attribute on a declarative class.
  246. The caveat is that the :class:`_schema.Table` must be fully
  247. reflected, or at the very least have a primary key column,
  248. at the point at which a normal declarative mapping is
  249. constructed, meaning the :class:`_engine.Engine` must be available
  250. at class declaration time.
  251. The :class:`.DeferredReflection` mixin moves the construction
  252. of mappers to be at a later point, after a specific
  253. method is called which first reflects all :class:`_schema.Table`
  254. objects created so far. Classes can define it as such::
  255. from sqlalchemy.ext.declarative import declarative_base
  256. from sqlalchemy.ext.declarative import DeferredReflection
  257. Base = declarative_base()
  258. class MyClass(DeferredReflection, Base):
  259. __tablename__ = 'mytable'
  260. Above, ``MyClass`` is not yet mapped. After a series of
  261. classes have been defined in the above fashion, all tables
  262. can be reflected and mappings created using
  263. :meth:`.prepare`::
  264. engine = create_engine("someengine://...")
  265. DeferredReflection.prepare(engine)
  266. The :class:`.DeferredReflection` mixin can be applied to individual
  267. classes, used as the base for the declarative base itself,
  268. or used in a custom abstract class. Using an abstract base
  269. allows that only a subset of classes to be prepared for a
  270. particular prepare step, which is necessary for applications
  271. that use more than one engine. For example, if an application
  272. has two engines, you might use two bases, and prepare each
  273. separately, e.g.::
  274. class ReflectedOne(DeferredReflection, Base):
  275. __abstract__ = True
  276. class ReflectedTwo(DeferredReflection, Base):
  277. __abstract__ = True
  278. class MyClass(ReflectedOne):
  279. __tablename__ = 'mytable'
  280. class MyOtherClass(ReflectedOne):
  281. __tablename__ = 'myothertable'
  282. class YetAnotherClass(ReflectedTwo):
  283. __tablename__ = 'yetanothertable'
  284. # ... etc.
  285. Above, the class hierarchies for ``ReflectedOne`` and
  286. ``ReflectedTwo`` can be configured separately::
  287. ReflectedOne.prepare(engine_one)
  288. ReflectedTwo.prepare(engine_two)
  289. """
  290. @classmethod
  291. def prepare(cls, engine):
  292. """Reflect all :class:`_schema.Table` objects for all current
  293. :class:`.DeferredReflection` subclasses"""
  294. to_map = _DeferredMapperConfig.classes_for_base(cls)
  295. with inspection.inspect(engine)._inspection_context() as insp:
  296. for thingy in to_map:
  297. cls._sa_decl_prepare(thingy.local_table, insp)
  298. thingy.map()
  299. mapper = thingy.cls.__mapper__
  300. metadata = mapper.class_.metadata
  301. for rel in mapper._props.values():
  302. if (
  303. isinstance(rel, relationships.RelationshipProperty)
  304. and rel.secondary is not None
  305. ):
  306. if isinstance(rel.secondary, Table):
  307. cls._reflect_table(rel.secondary, insp)
  308. elif isinstance(rel.secondary, str):
  309. _, resolve_arg = _resolver(rel.parent.class_, rel)
  310. rel.secondary = resolve_arg(rel.secondary)
  311. rel.secondary._resolvers += (
  312. cls._sa_deferred_table_resolver(
  313. insp, metadata
  314. ),
  315. )
  316. # controversy! do we resolve it here? or leave
  317. # it deferred? I think doing it here is necessary
  318. # so the connection does not leak.
  319. rel.secondary = rel.secondary()
  320. @classmethod
  321. def _sa_deferred_table_resolver(cls, inspector, metadata):
  322. def _resolve(key):
  323. t1 = Table(key, metadata)
  324. cls._reflect_table(t1, inspector)
  325. return t1
  326. return _resolve
  327. @classmethod
  328. def _sa_decl_prepare(cls, local_table, inspector):
  329. # autoload Table, which is already
  330. # present in the metadata. This
  331. # will fill in db-loaded columns
  332. # into the existing Table object.
  333. if local_table is not None:
  334. cls._reflect_table(local_table, inspector)
  335. @classmethod
  336. def _sa_raise_deferred_config(cls):
  337. raise orm_exc.UnmappedClassError(
  338. cls,
  339. msg="Class %s is a subclass of DeferredReflection. "
  340. "Mappings are not produced until the .prepare() "
  341. "method is called on the class hierarchy."
  342. % orm_exc._safe_cls_name(cls),
  343. )
  344. @classmethod
  345. def _reflect_table(cls, table, inspector):
  346. Table(
  347. table.name,
  348. table.metadata,
  349. extend_existing=True,
  350. autoload_replace=False,
  351. autoload_with=inspector,
  352. schema=table.schema,
  353. )