SQLAlchemy 2.1.0rc1__cp315-cp315-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win_arm64.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win_arm64.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win_arm64.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win_arm64.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1702 @@
1
+ # ext/automap.py
2
+ # Copyright (C) 2005-2026 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
+
8
+ r"""Define an extension to the :mod:`sqlalchemy.ext.declarative` system
9
+ which automatically generates mapped classes and relationships from a database
10
+ schema, typically though not necessarily one which is reflected.
11
+
12
+ It is hoped that the :class:`.AutomapBase` system provides a quick
13
+ and modernized solution to the problem that the very famous
14
+ `SQLSoup <https://pypi.org/project/sqlsoup/>`_
15
+ also tries to solve, that of generating a quick and rudimentary object
16
+ model from an existing database on the fly. By addressing the issue strictly
17
+ at the mapper configuration level, and integrating fully with existing
18
+ Declarative class techniques, :class:`.AutomapBase` seeks to provide
19
+ a well-integrated approach to the issue of expediently auto-generating ad-hoc
20
+ mappings.
21
+
22
+ .. tip:: The :ref:`automap_toplevel` extension is geared towards a
23
+ "zero declaration" approach, where a complete ORM model including classes
24
+ and pre-named relationships can be generated on the fly from a database
25
+ schema. For applications that still want to use explicit class declarations
26
+ including explicit relationship definitions in conjunction with reflection
27
+ of tables, the :class:`.DeferredReflection` class, described at
28
+ :ref:`orm_declarative_reflected_deferred_reflection`, is a better choice.
29
+
30
+ .. _automap_basic_use:
31
+
32
+ Basic Use
33
+ =========
34
+
35
+ The simplest usage is to reflect an existing database into a new model.
36
+ We create a new :class:`.AutomapBase` class in a similar manner as to how
37
+ we create a declarative base class, using :func:`.automap_base`.
38
+ We then call :meth:`.AutomapBase.prepare` on the resulting base class,
39
+ asking it to reflect the schema and produce mappings::
40
+
41
+ from sqlalchemy.ext.automap import automap_base
42
+ from sqlalchemy.orm import Session
43
+ from sqlalchemy import create_engine
44
+
45
+ Base = automap_base()
46
+
47
+ # engine, suppose it has two tables 'user' and 'address' set up
48
+ engine = create_engine("sqlite:///mydatabase.db")
49
+
50
+ # reflect the tables
51
+ Base.prepare(autoload_with=engine)
52
+
53
+ # mapped classes are now created with names by default
54
+ # matching that of the table name.
55
+ User = Base.classes.user
56
+ Address = Base.classes.address
57
+
58
+ session = Session(engine)
59
+
60
+ # rudimentary relationships are produced
61
+ session.add(Address(email_address="foo@bar.com", user=User(name="foo")))
62
+ session.commit()
63
+
64
+ # collection-based relationships are by default named
65
+ # "<classname>_collection"
66
+ u1 = session.query(User).first()
67
+ print(u1.address_collection)
68
+
69
+ Above, calling :meth:`.AutomapBase.prepare` while passing along the
70
+ :paramref:`.AutomapBase.prepare.reflect` parameter indicates that the
71
+ :meth:`_schema.MetaData.reflect`
72
+ method will be called on this declarative base
73
+ classes' :class:`_schema.MetaData` collection; then, each **viable**
74
+ :class:`_schema.Table` within the :class:`_schema.MetaData`
75
+ will get a new mapped class
76
+ generated automatically. The :class:`_schema.ForeignKeyConstraint`
77
+ objects which
78
+ link the various tables together will be used to produce new, bidirectional
79
+ :func:`_orm.relationship` objects between classes.
80
+ The classes and relationships
81
+ follow along a default naming scheme that we can customize. At this point,
82
+ our basic mapping consisting of related ``User`` and ``Address`` classes is
83
+ ready to use in the traditional way.
84
+
85
+ .. note:: By **viable**, we mean that for a table to be mapped, it must
86
+ specify a primary key. Additionally, if the table is detected as being
87
+ a pure association table between two other tables, it will not be directly
88
+ mapped and will instead be configured as a many-to-many table between
89
+ the mappings for the two referring tables.
90
+
91
+ Generating Mappings from an Existing MetaData
92
+ =============================================
93
+
94
+ We can pass a pre-declared :class:`_schema.MetaData` object to
95
+ :func:`.automap_base`.
96
+ This object can be constructed in any way, including programmatically, from
97
+ a serialized file, or from itself being reflected using
98
+ :meth:`_schema.MetaData.reflect`.
99
+ Below we illustrate a combination of reflection and
100
+ explicit table declaration::
101
+
102
+ from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey
103
+ from sqlalchemy.ext.automap import automap_base
104
+
105
+ engine = create_engine("sqlite:///mydatabase.db")
106
+
107
+ # produce our own MetaData object
108
+ metadata = MetaData()
109
+
110
+ # we can reflect it ourselves from a database, using options
111
+ # such as 'only' to limit what tables we look at...
112
+ metadata.reflect(engine, only=["user", "address"])
113
+
114
+ # ... or just define our own Table objects with it (or combine both)
115
+ Table(
116
+ "user_order",
117
+ metadata,
118
+ Column("id", Integer, primary_key=True),
119
+ Column("user_id", ForeignKey("user.id")),
120
+ )
121
+
122
+ # we can then produce a set of mappings from this MetaData.
123
+ Base = automap_base(metadata=metadata)
124
+
125
+ # calling prepare() just sets up mapped classes and relationships.
126
+ Base.prepare()
127
+
128
+ # mapped classes are ready
129
+ User = Base.classes.user
130
+ Address = Base.classes.address
131
+ Order = Base.classes.user_order
132
+
133
+ .. _automap_by_module:
134
+
135
+ Generating Mappings from Multiple Schemas
136
+ =========================================
137
+
138
+ The :meth:`.AutomapBase.prepare` method when used with reflection may reflect
139
+ tables from one schema at a time at most, using the
140
+ :paramref:`.AutomapBase.prepare.schema` parameter to indicate the name of a
141
+ schema to be reflected from. In order to populate the :class:`.AutomapBase`
142
+ with tables from multiple schemas, :meth:`.AutomapBase.prepare` may be invoked
143
+ multiple times, each time passing a different name to the
144
+ :paramref:`.AutomapBase.prepare.schema` parameter. The
145
+ :meth:`.AutomapBase.prepare` method keeps an internal list of
146
+ :class:`_schema.Table` objects that have already been mapped, and will add new
147
+ mappings only for those :class:`_schema.Table` objects that are new since the
148
+ last time :meth:`.AutomapBase.prepare` was run::
149
+
150
+ e = create_engine("postgresql://scott:tiger@localhost/test")
151
+
152
+ Base.metadata.create_all(e)
153
+
154
+ Base = automap_base()
155
+
156
+ Base.prepare(e)
157
+ Base.prepare(e, schema="test_schema")
158
+ Base.prepare(e, schema="test_schema_2")
159
+
160
+ .. versionadded:: 2.0 The :meth:`.AutomapBase.prepare` method may be called
161
+ any number of times; only newly added tables will be mapped
162
+ on each run. Previously in version 1.4 and earlier, multiple calls would
163
+ cause errors as it would attempt to re-map an already mapped class.
164
+ The previous workaround approach of invoking
165
+ :meth:`_schema.MetaData.reflect` directly remains available as well.
166
+
167
+ Automapping same-named tables across multiple schemas
168
+ -----------------------------------------------------
169
+
170
+ For the common case where multiple schemas may have same-named tables and
171
+ therefore would generate same-named classes, conflicts can be resolved either
172
+ through use of the :paramref:`.AutomapBase.prepare.classname_for_table` hook to
173
+ apply different classnames on a per-schema basis, or by using the
174
+ :paramref:`.AutomapBase.prepare.modulename_for_table` hook, which allows
175
+ disambiguation of same-named classes by changing their effective ``__module__``
176
+ attribute. In the example below, this hook is used to create a ``__module__``
177
+ attribute for all classes that is of the form ``mymodule.<schemaname>``, where
178
+ the schema name ``default`` is used if no schema is present::
179
+
180
+ e = create_engine("postgresql://scott:tiger@localhost/test")
181
+
182
+ Base.metadata.create_all(e)
183
+
184
+
185
+ def module_name_for_table(cls, tablename, table):
186
+ if table.schema is not None:
187
+ return f"mymodule.{table.schema}"
188
+ else:
189
+ return f"mymodule.default"
190
+
191
+
192
+ Base = automap_base()
193
+
194
+ Base.prepare(e, modulename_for_table=module_name_for_table)
195
+ Base.prepare(
196
+ e, schema="test_schema", modulename_for_table=module_name_for_table
197
+ )
198
+ Base.prepare(
199
+ e, schema="test_schema_2", modulename_for_table=module_name_for_table
200
+ )
201
+
202
+ The same named-classes are organized into a hierarchical collection available
203
+ at :attr:`.AutomapBase.by_module`. This collection is traversed using the
204
+ dot-separated name of a particular package/module down into the desired
205
+ class name.
206
+
207
+ .. note:: When using the :paramref:`.AutomapBase.prepare.modulename_for_table`
208
+ hook to return a new ``__module__`` that is not ``None``, the class is
209
+ **not** placed into the :attr:`.AutomapBase.classes` collection; only
210
+ classes that were not given an explicit modulename are placed here, as the
211
+ collection cannot represent same-named classes individually.
212
+
213
+ In the example above, if the database contained a table named ``accounts`` in
214
+ all three of the default schema, the ``test_schema`` schema, and the
215
+ ``test_schema_2`` schema, three separate classes will be available as::
216
+
217
+ Base.by_module.mymodule.default.accounts
218
+ Base.by_module.mymodule.test_schema.accounts
219
+ Base.by_module.mymodule.test_schema_2.accounts
220
+
221
+ The default module namespace generated for all :class:`.AutomapBase` classes is
222
+ ``sqlalchemy.ext.automap``. If no
223
+ :paramref:`.AutomapBase.prepare.modulename_for_table` hook is used, the
224
+ contents of :attr:`.AutomapBase.by_module` will be entirely within the
225
+ ``sqlalchemy.ext.automap`` namespace (e.g.
226
+ ``MyBase.by_module.sqlalchemy.ext.automap.<classname>``), which would contain
227
+ the same series of classes as what would be seen in
228
+ :attr:`.AutomapBase.classes`. Therefore it's generally only necessary to use
229
+ :attr:`.AutomapBase.by_module` when explicit ``__module__`` conventions are
230
+ present.
231
+
232
+ .. versionadded:: 2.0
233
+
234
+ Added the :attr:`.AutomapBase.by_module` collection, which stores
235
+ classes within a named hierarchy based on dot-separated module names,
236
+ as well as the :paramref:`.Automap.prepare.modulename_for_table` parameter
237
+ which allows for custom ``__module__`` schemes for automapped
238
+ classes.
239
+
240
+
241
+
242
+ Specifying Classes Explicitly
243
+ =============================
244
+
245
+ .. tip:: If explicit classes are expected to be prominent in an application,
246
+ consider using :class:`.DeferredReflection` instead.
247
+
248
+ The :mod:`.sqlalchemy.ext.automap` extension allows classes to be defined
249
+ explicitly, in a way similar to that of the :class:`.DeferredReflection` class.
250
+ Classes that extend from :class:`.AutomapBase` act like regular declarative
251
+ classes, but are not immediately mapped after their construction, and are
252
+ instead mapped when we call :meth:`.AutomapBase.prepare`. The
253
+ :meth:`.AutomapBase.prepare` method will make use of the classes we've
254
+ established based on the table name we use. If our schema contains tables
255
+ ``user`` and ``address``, we can define one or both of the classes to be used::
256
+
257
+ from sqlalchemy.ext.automap import automap_base
258
+ from sqlalchemy import create_engine
259
+
260
+ # automap base
261
+ Base = automap_base()
262
+
263
+
264
+ # pre-declare User for the 'user' table
265
+ class User(Base):
266
+ __tablename__ = "user"
267
+
268
+ # override schema elements like Columns
269
+ user_name = Column("name", String)
270
+
271
+ # override relationships too, if desired.
272
+ # we must use the same name that automap would use for the
273
+ # relationship, and also must refer to the class name that automap will
274
+ # generate for "address"
275
+ address_collection = relationship("address", collection_class=set)
276
+
277
+
278
+ # reflect
279
+ engine = create_engine("sqlite:///mydatabase.db")
280
+ Base.prepare(autoload_with=engine)
281
+
282
+ # we still have Address generated from the tablename "address",
283
+ # but User is the same as Base.classes.User now
284
+
285
+ Address = Base.classes.address
286
+
287
+ u1 = session.query(User).first()
288
+ print(u1.address_collection)
289
+
290
+ # the backref is still there:
291
+ a1 = session.query(Address).first()
292
+ print(a1.user)
293
+
294
+ Above, one of the more intricate details is that we illustrated overriding
295
+ one of the :func:`_orm.relationship` objects that automap would have created.
296
+ To do this, we needed to make sure the names match up with what automap
297
+ would normally generate, in that the relationship name would be
298
+ ``User.address_collection`` and the name of the class referred to, from
299
+ automap's perspective, is called ``address``, even though we are referring to
300
+ it as ``Address`` within our usage of this class.
301
+
302
+ Overriding Naming Schemes
303
+ =========================
304
+
305
+ :mod:`.sqlalchemy.ext.automap` is tasked with producing mapped classes and
306
+ relationship names based on a schema, which means it has decision points in how
307
+ these names are determined. These three decision points are provided using
308
+ functions which can be passed to the :meth:`.AutomapBase.prepare` method, and
309
+ are known as :func:`.classname_for_table`,
310
+ :func:`.name_for_scalar_relationship`,
311
+ and :func:`.name_for_collection_relationship`. Any or all of these
312
+ functions are provided as in the example below, where we use a "camel case"
313
+ scheme for class names and a "pluralizer" for collection names using the
314
+ `Inflect <https://pypi.org/project/inflect>`_ package::
315
+
316
+ import re
317
+ import inflect
318
+
319
+
320
+ def camelize_classname(base, tablename, table):
321
+ "Produce a 'camelized' class name, e.g."
322
+ "'words_and_underscores' -> 'WordsAndUnderscores'"
323
+
324
+ return str(
325
+ tablename[0].upper()
326
+ + re.sub(
327
+ r"_([a-z])",
328
+ lambda m: m.group(1).upper(),
329
+ tablename[1:],
330
+ )
331
+ )
332
+
333
+
334
+ _pluralizer = inflect.engine()
335
+
336
+
337
+ def pluralize_collection(base, local_cls, referred_cls, constraint):
338
+ "Produce an 'uncamelized', 'pluralized' class name, e.g."
339
+ "'SomeTerm' -> 'some_terms'"
340
+
341
+ referred_name = referred_cls.__name__
342
+ uncamelized = re.sub(
343
+ r"[A-Z]",
344
+ lambda m: "_%s" % m.group(0).lower(),
345
+ referred_name,
346
+ )[1:]
347
+ pluralized = _pluralizer.plural(uncamelized)
348
+ return pluralized
349
+
350
+
351
+ from sqlalchemy.ext.automap import automap_base
352
+
353
+ Base = automap_base()
354
+
355
+ engine = create_engine("sqlite:///mydatabase.db")
356
+
357
+ Base.prepare(
358
+ autoload_with=engine,
359
+ classname_for_table=camelize_classname,
360
+ name_for_collection_relationship=pluralize_collection,
361
+ )
362
+
363
+ From the above mapping, we would now have classes ``User`` and ``Address``,
364
+ where the collection from ``User`` to ``Address`` is called
365
+ ``User.addresses``::
366
+
367
+ User, Address = Base.classes.User, Base.classes.Address
368
+
369
+ u1 = User(addresses=[Address(email="foo@bar.com")])
370
+
371
+ Relationship Detection
372
+ ======================
373
+
374
+ The vast majority of what automap accomplishes is the generation of
375
+ :func:`_orm.relationship` structures based on foreign keys. The mechanism
376
+ by which this works for many-to-one and one-to-many relationships is as
377
+ follows:
378
+
379
+ 1. A given :class:`_schema.Table`, known to be mapped to a particular class,
380
+ is examined for :class:`_schema.ForeignKeyConstraint` objects.
381
+
382
+ 2. From each :class:`_schema.ForeignKeyConstraint`, the remote
383
+ :class:`_schema.Table`
384
+ object present is matched up to the class to which it is to be mapped,
385
+ if any, else it is skipped.
386
+
387
+ 3. As the :class:`_schema.ForeignKeyConstraint`
388
+ we are examining corresponds to a
389
+ reference from the immediate mapped class, the relationship will be set up
390
+ as a many-to-one referring to the referred class; a corresponding
391
+ one-to-many backref will be created on the referred class referring
392
+ to this class.
393
+
394
+ 4. If any of the columns that are part of the
395
+ :class:`_schema.ForeignKeyConstraint`
396
+ are not nullable (e.g. ``nullable=False``), a
397
+ :paramref:`_orm.relationship.cascade` keyword argument
398
+ of ``all, delete-orphan`` will be added to the keyword arguments to
399
+ be passed to the relationship or backref. If the
400
+ :class:`_schema.ForeignKeyConstraint` reports that
401
+ :paramref:`_schema.ForeignKeyConstraint.ondelete`
402
+ is set to ``CASCADE`` for a not null or ``SET NULL`` for a nullable
403
+ set of columns, the option :paramref:`_orm.relationship.passive_deletes`
404
+ flag is set to ``True`` in the set of relationship keyword arguments.
405
+ Note that not all backends support reflection of ON DELETE.
406
+
407
+ 5. The names of the relationships are determined using the
408
+ :paramref:`.AutomapBase.prepare.name_for_scalar_relationship` and
409
+ :paramref:`.AutomapBase.prepare.name_for_collection_relationship`
410
+ callable functions. It is important to note that the default relationship
411
+ naming derives the name from the **the actual class name**. If you've
412
+ given a particular class an explicit name by declaring it, or specified an
413
+ alternate class naming scheme, that's the name from which the relationship
414
+ name will be derived.
415
+
416
+ 6. The classes are inspected for an existing mapped property matching these
417
+ names. If one is detected on one side, but none on the other side,
418
+ :class:`.AutomapBase` attempts to create a relationship on the missing side,
419
+ then uses the :paramref:`_orm.relationship.back_populates`
420
+ parameter in order to
421
+ point the new relationship to the other side.
422
+
423
+ 7. In the usual case where no relationship is on either side,
424
+ :meth:`.AutomapBase.prepare` produces a :func:`_orm.relationship` on the
425
+ "many-to-one" side and matches it to the other using the
426
+ :paramref:`_orm.relationship.backref` parameter.
427
+
428
+ 8. Production of the :func:`_orm.relationship` and optionally the
429
+ :func:`.backref`
430
+ is handed off to the :paramref:`.AutomapBase.prepare.generate_relationship`
431
+ function, which can be supplied by the end-user in order to augment
432
+ the arguments passed to :func:`_orm.relationship` or :func:`.backref` or to
433
+ make use of custom implementations of these functions.
434
+
435
+ Custom Relationship Arguments
436
+ -----------------------------
437
+
438
+ The :paramref:`.AutomapBase.prepare.generate_relationship` hook can be used
439
+ to add parameters to relationships. For most cases, we can make use of the
440
+ existing :func:`.automap.generate_relationship` function to return
441
+ the object, after augmenting the given keyword dictionary with our own
442
+ arguments.
443
+
444
+ Below is an illustration of how to send
445
+ :paramref:`_orm.relationship.cascade` and
446
+ :paramref:`_orm.relationship.passive_deletes`
447
+ options along to all one-to-many relationships::
448
+
449
+ from sqlalchemy.ext.automap import generate_relationship
450
+ from sqlalchemy.orm import interfaces
451
+
452
+
453
+ def _gen_relationship(
454
+ base, direction, return_fn, attrname, local_cls, referred_cls, **kw
455
+ ):
456
+ if direction is interfaces.ONETOMANY:
457
+ kw["cascade"] = "all, delete-orphan"
458
+ kw["passive_deletes"] = True
459
+ # make use of the built-in function to actually return
460
+ # the result.
461
+ return generate_relationship(
462
+ base, direction, return_fn, attrname, local_cls, referred_cls, **kw
463
+ )
464
+
465
+
466
+ from sqlalchemy.ext.automap import automap_base
467
+ from sqlalchemy import create_engine
468
+
469
+ # automap base
470
+ Base = automap_base()
471
+
472
+ engine = create_engine("sqlite:///mydatabase.db")
473
+ Base.prepare(autoload_with=engine, generate_relationship=_gen_relationship)
474
+
475
+ Many-to-Many relationships
476
+ --------------------------
477
+
478
+ :mod:`.sqlalchemy.ext.automap` will generate many-to-many relationships, e.g.
479
+ those which contain a ``secondary`` argument. The process for producing these
480
+ is as follows:
481
+
482
+ 1. A given :class:`_schema.Table` is examined for
483
+ :class:`_schema.ForeignKeyConstraint`
484
+ objects, before any mapped class has been assigned to it.
485
+
486
+ 2. If the table contains two and exactly two
487
+ :class:`_schema.ForeignKeyConstraint`
488
+ objects, and all columns within this table are members of these two
489
+ :class:`_schema.ForeignKeyConstraint` objects, the table is assumed to be a
490
+ "secondary" table, and will **not be mapped directly**.
491
+
492
+ 3. The two (or one, for self-referential) external tables to which the
493
+ :class:`_schema.Table`
494
+ refers to are matched to the classes to which they will be
495
+ mapped, if any.
496
+
497
+ 4. If mapped classes for both sides are located, a many-to-many bi-directional
498
+ :func:`_orm.relationship` / :func:`.backref`
499
+ pair is created between the two
500
+ classes.
501
+
502
+ 5. The override logic for many-to-many works the same as that of one-to-many/
503
+ many-to-one; the :func:`.generate_relationship` function is called upon
504
+ to generate the structures and existing attributes will be maintained.
505
+
506
+ Relationships with Inheritance
507
+ ------------------------------
508
+
509
+ :mod:`.sqlalchemy.ext.automap` will not generate any relationships between
510
+ two classes that are in an inheritance relationship. That is, with two
511
+ classes given as follows::
512
+
513
+ class Employee(Base):
514
+ __tablename__ = "employee"
515
+ id = Column(Integer, primary_key=True)
516
+ type = Column(String(50))
517
+ __mapper_args__ = {
518
+ "polymorphic_identity": "employee",
519
+ "polymorphic_on": type,
520
+ }
521
+
522
+
523
+ class Engineer(Employee):
524
+ __tablename__ = "engineer"
525
+ id = Column(Integer, ForeignKey("employee.id"), primary_key=True)
526
+ __mapper_args__ = {
527
+ "polymorphic_identity": "engineer",
528
+ }
529
+
530
+ The foreign key from ``Engineer`` to ``Employee`` is used not for a
531
+ relationship, but to establish joined inheritance between the two classes.
532
+
533
+ Note that this means automap will not generate *any* relationships
534
+ for foreign keys that link from a subclass to a superclass. If a mapping
535
+ has actual relationships from subclass to superclass as well, those
536
+ need to be explicit. Below, as we have two separate foreign keys
537
+ from ``Engineer`` to ``Employee``, we need to set up both the relationship
538
+ we want as well as the ``inherit_condition``, as these are not things
539
+ SQLAlchemy can guess::
540
+
541
+ class Employee(Base):
542
+ __tablename__ = "employee"
543
+ id = Column(Integer, primary_key=True)
544
+ type = Column(String(50))
545
+
546
+ __mapper_args__ = {
547
+ "polymorphic_identity": "employee",
548
+ "polymorphic_on": type,
549
+ }
550
+
551
+
552
+ class Engineer(Employee):
553
+ __tablename__ = "engineer"
554
+ id = Column(Integer, ForeignKey("employee.id"), primary_key=True)
555
+ favorite_employee_id = Column(Integer, ForeignKey("employee.id"))
556
+
557
+ favorite_employee = relationship(
558
+ Employee, foreign_keys=favorite_employee_id
559
+ )
560
+
561
+ __mapper_args__ = {
562
+ "polymorphic_identity": "engineer",
563
+ "inherit_condition": id == Employee.id,
564
+ }
565
+
566
+ Handling Simple Naming Conflicts
567
+ --------------------------------
568
+
569
+ In the case of naming conflicts during mapping, override any of
570
+ :func:`.classname_for_table`, :func:`.name_for_scalar_relationship`,
571
+ and :func:`.name_for_collection_relationship` as needed. For example, if
572
+ automap is attempting to name a many-to-one relationship the same as an
573
+ existing column, an alternate convention can be conditionally selected. Given
574
+ a schema:
575
+
576
+ .. sourcecode:: sql
577
+
578
+ CREATE TABLE table_a (
579
+ id INTEGER PRIMARY KEY
580
+ );
581
+
582
+ CREATE TABLE table_b (
583
+ id INTEGER PRIMARY KEY,
584
+ table_a INTEGER,
585
+ FOREIGN KEY(table_a) REFERENCES table_a(id)
586
+ );
587
+
588
+ The above schema will first automap the ``table_a`` table as a class named
589
+ ``table_a``; it will then automap a relationship onto the class for ``table_b``
590
+ with the same name as this related class, e.g. ``table_a``. This
591
+ relationship name conflicts with the mapping column ``table_b.table_a``,
592
+ and will emit an error on mapping.
593
+
594
+ We can resolve this conflict by using an underscore as follows::
595
+
596
+ def name_for_scalar_relationship(
597
+ base, local_cls, referred_cls, constraint
598
+ ):
599
+ name = referred_cls.__name__.lower()
600
+ local_table = local_cls.__table__
601
+ if name in local_table.columns:
602
+ newname = name + "_"
603
+ warnings.warn(
604
+ "Already detected name %s present. using %s" % (name, newname)
605
+ )
606
+ return newname
607
+ return name
608
+
609
+
610
+ Base.prepare(
611
+ autoload_with=engine,
612
+ name_for_scalar_relationship=name_for_scalar_relationship,
613
+ )
614
+
615
+ Alternatively, we can change the name on the column side. The columns
616
+ that are mapped can be modified using the technique described at
617
+ :ref:`mapper_column_distinct_names`, by assigning the column explicitly
618
+ to a new name::
619
+
620
+ Base = automap_base()
621
+
622
+
623
+ class TableB(Base):
624
+ __tablename__ = "table_b"
625
+ _table_a = Column("table_a", ForeignKey("table_a.id"))
626
+
627
+
628
+ Base.prepare(autoload_with=engine)
629
+
630
+ Using Automap with Explicit Declarations
631
+ ========================================
632
+
633
+ As noted previously, automap has no dependency on reflection, and can make
634
+ use of any collection of :class:`_schema.Table` objects within a
635
+ :class:`_schema.MetaData`
636
+ collection. From this, it follows that automap can also be used
637
+ generate missing relationships given an otherwise complete model that fully
638
+ defines table metadata::
639
+
640
+ from sqlalchemy.ext.automap import automap_base
641
+ from sqlalchemy import Column, Integer, String, ForeignKey
642
+
643
+ Base = automap_base()
644
+
645
+
646
+ class User(Base):
647
+ __tablename__ = "user"
648
+
649
+ id = Column(Integer, primary_key=True)
650
+ name = Column(String)
651
+
652
+
653
+ class Address(Base):
654
+ __tablename__ = "address"
655
+
656
+ id = Column(Integer, primary_key=True)
657
+ email = Column(String)
658
+ user_id = Column(ForeignKey("user.id"))
659
+
660
+
661
+ # produce relationships
662
+ Base.prepare()
663
+
664
+ # mapping is complete, with "address_collection" and
665
+ # "user" relationships
666
+ a1 = Address(email="u1")
667
+ a2 = Address(email="u2")
668
+ u1 = User(address_collection=[a1, a2])
669
+ assert a1.user is u1
670
+
671
+ Above, given mostly complete ``User`` and ``Address`` mappings, the
672
+ :class:`_schema.ForeignKey` which we defined on ``Address.user_id`` allowed a
673
+ bidirectional relationship pair ``Address.user`` and
674
+ ``User.address_collection`` to be generated on the mapped classes.
675
+
676
+ Note that when subclassing :class:`.AutomapBase`,
677
+ the :meth:`.AutomapBase.prepare` method is required; if not called, the classes
678
+ we've declared are in an un-mapped state.
679
+
680
+
681
+ .. _automap_intercepting_columns:
682
+
683
+ Intercepting Column Definitions
684
+ ===============================
685
+
686
+ The :class:`_schema.MetaData` and :class:`_schema.Table` objects support an
687
+ event hook :meth:`_events.DDLEvents.column_reflect` that may be used to intercept
688
+ the information reflected about a database column before the :class:`_schema.Column`
689
+ object is constructed. For example if we wanted to map columns using a
690
+ naming convention such as ``"attr_<columnname>"``, the event could
691
+ be applied as::
692
+
693
+ @event.listens_for(Base.metadata, "column_reflect")
694
+ def column_reflect(inspector, table, column_info):
695
+ # set column.key = "attr_<lower_case_name>"
696
+ column_info["key"] = "attr_%s" % column_info["name"].lower()
697
+
698
+
699
+ # run reflection
700
+ Base.prepare(autoload_with=engine)
701
+
702
+ .. versionadded:: 1.4.0b2 the :meth:`_events.DDLEvents.column_reflect` event
703
+ may be applied to a :class:`_schema.MetaData` object.
704
+
705
+ .. seealso::
706
+
707
+ :meth:`_events.DDLEvents.column_reflect`
708
+
709
+ :ref:`mapper_automated_reflection_schemes` - in the ORM mapping documentation
710
+
711
+
712
+ """ # noqa
713
+
714
+ from __future__ import annotations
715
+
716
+ import dataclasses
717
+ from typing import Any
718
+ from typing import Callable
719
+ from typing import cast
720
+ from typing import ClassVar
721
+ from typing import Dict
722
+ from typing import List
723
+ from typing import NoReturn
724
+ from typing import Optional
725
+ from typing import overload
726
+ from typing import Protocol
727
+ from typing import Set
728
+ from typing import Tuple
729
+ from typing import Type
730
+ from typing import TYPE_CHECKING
731
+ from typing import TypeVar
732
+ from typing import Union
733
+
734
+ from .. import util
735
+ from ..orm import backref
736
+ from ..orm import declarative_base as _declarative_base
737
+ from ..orm import exc as orm_exc
738
+ from ..orm import interfaces
739
+ from ..orm import relationship
740
+ from ..orm.decl_base import _DeferredDeclarativeConfig
741
+ from ..orm.mapper import _CONFIGURE_MUTEX
742
+ from ..schema import ForeignKeyConstraint
743
+ from ..sql import and_
744
+ from ..util import Properties
745
+
746
+ if TYPE_CHECKING:
747
+ from ..engine.base import Engine
748
+ from ..orm.base import RelationshipDirection
749
+ from ..orm.relationships import ORMBackrefArgument
750
+ from ..orm.relationships import Relationship
751
+ from ..sql.schema import Column
752
+ from ..sql.schema import MetaData
753
+ from ..sql.schema import Table
754
+ from ..util import immutabledict
755
+
756
+
757
+ _KT = TypeVar("_KT", bound=Any)
758
+ _VT = TypeVar("_VT", bound=Any)
759
+
760
+
761
+ class PythonNameForTableType(Protocol):
762
+ def __call__(
763
+ self, base: Type[Any], tablename: str, table: Table
764
+ ) -> str: ...
765
+
766
+
767
+ def classname_for_table(
768
+ base: Type[Any],
769
+ tablename: str,
770
+ table: Table,
771
+ ) -> str:
772
+ """Return the class name that should be used, given the name
773
+ of a table.
774
+
775
+ The default implementation is::
776
+
777
+ return str(tablename)
778
+
779
+ Alternate implementations can be specified using the
780
+ :paramref:`.AutomapBase.prepare.classname_for_table`
781
+ parameter.
782
+
783
+ :param base: the :class:`.AutomapBase` class doing the prepare.
784
+
785
+ :param tablename: string name of the :class:`_schema.Table`.
786
+
787
+ :param table: the :class:`_schema.Table` object itself.
788
+
789
+ :return: a string class name.
790
+
791
+ .. note::
792
+
793
+ In Python 2, the string used for the class name **must** be a
794
+ non-Unicode object, e.g. a ``str()`` object. The ``.name`` attribute
795
+ of :class:`_schema.Table` is typically a Python unicode subclass,
796
+ so the
797
+ ``str()`` function should be applied to this name, after accounting for
798
+ any non-ASCII characters.
799
+
800
+ """
801
+ return str(tablename)
802
+
803
+
804
+ class NameForScalarRelationshipType(Protocol):
805
+ def __call__(
806
+ self,
807
+ base: Type[Any],
808
+ local_cls: Type[Any],
809
+ referred_cls: Type[Any],
810
+ constraint: ForeignKeyConstraint,
811
+ ) -> str: ...
812
+
813
+
814
+ def name_for_scalar_relationship(
815
+ base: Type[Any],
816
+ local_cls: Type[Any],
817
+ referred_cls: Type[Any],
818
+ constraint: ForeignKeyConstraint,
819
+ ) -> str:
820
+ """Return the attribute name that should be used to refer from one
821
+ class to another, for a scalar object reference.
822
+
823
+ The default implementation is::
824
+
825
+ return referred_cls.__name__.lower()
826
+
827
+ Alternate implementations can be specified using the
828
+ :paramref:`.AutomapBase.prepare.name_for_scalar_relationship`
829
+ parameter.
830
+
831
+ :param base: the :class:`.AutomapBase` class doing the prepare.
832
+
833
+ :param local_cls: the class to be mapped on the local side.
834
+
835
+ :param referred_cls: the class to be mapped on the referring side.
836
+
837
+ :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being
838
+ inspected to produce this relationship.
839
+
840
+ """
841
+ return referred_cls.__name__.lower()
842
+
843
+
844
+ class NameForCollectionRelationshipType(Protocol):
845
+ def __call__(
846
+ self,
847
+ base: Type[Any],
848
+ local_cls: Type[Any],
849
+ referred_cls: Type[Any],
850
+ constraint: ForeignKeyConstraint,
851
+ ) -> str: ...
852
+
853
+
854
+ def name_for_collection_relationship(
855
+ base: Type[Any],
856
+ local_cls: Type[Any],
857
+ referred_cls: Type[Any],
858
+ constraint: ForeignKeyConstraint,
859
+ ) -> str:
860
+ """Return the attribute name that should be used to refer from one
861
+ class to another, for a collection reference.
862
+
863
+ The default implementation is::
864
+
865
+ return referred_cls.__name__.lower() + "_collection"
866
+
867
+ Alternate implementations
868
+ can be specified using the
869
+ :paramref:`.AutomapBase.prepare.name_for_collection_relationship`
870
+ parameter.
871
+
872
+ :param base: the :class:`.AutomapBase` class doing the prepare.
873
+
874
+ :param local_cls: the class to be mapped on the local side.
875
+
876
+ :param referred_cls: the class to be mapped on the referring side.
877
+
878
+ :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being
879
+ inspected to produce this relationship.
880
+
881
+ """
882
+ return referred_cls.__name__.lower() + "_collection"
883
+
884
+
885
+ class GenerateRelationshipType(Protocol):
886
+ @overload
887
+ def __call__(
888
+ self,
889
+ base: Type[Any],
890
+ direction: RelationshipDirection,
891
+ return_fn: Callable[..., Relationship[Any]],
892
+ attrname: str,
893
+ local_cls: Type[Any],
894
+ referred_cls: Type[Any],
895
+ **kw: Any,
896
+ ) -> Relationship[Any]: ...
897
+
898
+ @overload
899
+ def __call__(
900
+ self,
901
+ base: Type[Any],
902
+ direction: RelationshipDirection,
903
+ return_fn: Callable[..., ORMBackrefArgument],
904
+ attrname: str,
905
+ local_cls: Type[Any],
906
+ referred_cls: Type[Any],
907
+ **kw: Any,
908
+ ) -> ORMBackrefArgument: ...
909
+
910
+ def __call__(
911
+ self,
912
+ base: Type[Any],
913
+ direction: RelationshipDirection,
914
+ return_fn: Union[
915
+ Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument]
916
+ ],
917
+ attrname: str,
918
+ local_cls: Type[Any],
919
+ referred_cls: Type[Any],
920
+ **kw: Any,
921
+ ) -> Union[ORMBackrefArgument, Relationship[Any]]: ...
922
+
923
+
924
+ @overload
925
+ def generate_relationship(
926
+ base: Type[Any],
927
+ direction: RelationshipDirection,
928
+ return_fn: Callable[..., Relationship[Any]],
929
+ attrname: str,
930
+ local_cls: Type[Any],
931
+ referred_cls: Type[Any],
932
+ **kw: Any,
933
+ ) -> Relationship[Any]: ...
934
+
935
+
936
+ @overload
937
+ def generate_relationship(
938
+ base: Type[Any],
939
+ direction: RelationshipDirection,
940
+ return_fn: Callable[..., ORMBackrefArgument],
941
+ attrname: str,
942
+ local_cls: Type[Any],
943
+ referred_cls: Type[Any],
944
+ **kw: Any,
945
+ ) -> ORMBackrefArgument: ...
946
+
947
+
948
+ def generate_relationship(
949
+ base: Type[Any],
950
+ direction: RelationshipDirection,
951
+ return_fn: Union[
952
+ Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument]
953
+ ],
954
+ attrname: str,
955
+ local_cls: Type[Any],
956
+ referred_cls: Type[Any],
957
+ **kw: Any,
958
+ ) -> Union[Relationship[Any], ORMBackrefArgument]:
959
+ r"""Generate a :func:`_orm.relationship` or :func:`.backref`
960
+ on behalf of two
961
+ mapped classes.
962
+
963
+ An alternate implementation of this function can be specified using the
964
+ :paramref:`.AutomapBase.prepare.generate_relationship` parameter.
965
+
966
+ The default implementation of this function is as follows::
967
+
968
+ if return_fn is backref:
969
+ return return_fn(attrname, **kw)
970
+ elif return_fn is relationship:
971
+ return return_fn(referred_cls, **kw)
972
+ else:
973
+ raise TypeError("Unknown relationship function: %s" % return_fn)
974
+
975
+ :param base: the :class:`.AutomapBase` class doing the prepare.
976
+
977
+ :param direction: indicate the "direction" of the relationship; this will
978
+ be one of :data:`.ONETOMANY`, :data:`.MANYTOONE`, :data:`.MANYTOMANY`.
979
+
980
+ :param return_fn: the function that is used by default to create the
981
+ relationship. This will be either :func:`_orm.relationship` or
982
+ :func:`.backref`. The :func:`.backref` function's result will be used to
983
+ produce a new :func:`_orm.relationship` in a second step,
984
+ so it is critical
985
+ that user-defined implementations correctly differentiate between the two
986
+ functions, if a custom relationship function is being used.
987
+
988
+ :param attrname: the attribute name to which this relationship is being
989
+ assigned. If the value of :paramref:`.generate_relationship.return_fn` is
990
+ the :func:`.backref` function, then this name is the name that is being
991
+ assigned to the backref.
992
+
993
+ :param local_cls: the "local" class to which this relationship or backref
994
+ will be locally present.
995
+
996
+ :param referred_cls: the "referred" class to which the relationship or
997
+ backref refers to.
998
+
999
+ :param \**kw: all additional keyword arguments are passed along to the
1000
+ function.
1001
+
1002
+ :return: a :func:`_orm.relationship` or :func:`.backref` construct,
1003
+ as dictated
1004
+ by the :paramref:`.generate_relationship.return_fn` parameter.
1005
+
1006
+ """
1007
+
1008
+ if return_fn is backref:
1009
+ return return_fn(attrname, **kw)
1010
+ elif return_fn is relationship:
1011
+ return return_fn(referred_cls, **kw)
1012
+ else:
1013
+ raise TypeError("Unknown relationship function: %s" % return_fn)
1014
+
1015
+
1016
+ ByModuleProperties = Properties[Union["ByModuleProperties", Type[Any]]]
1017
+
1018
+
1019
+ class AutomapBase:
1020
+ """Base class for an "automap" schema.
1021
+
1022
+ The :class:`.AutomapBase` class can be compared to the "declarative base"
1023
+ class that is produced by the :func:`.declarative.declarative_base`
1024
+ function. In practice, the :class:`.AutomapBase` class is always used
1025
+ as a mixin along with an actual declarative base.
1026
+
1027
+ A new subclassable :class:`.AutomapBase` is typically instantiated
1028
+ using the :func:`.automap_base` function.
1029
+
1030
+ .. seealso::
1031
+
1032
+ :ref:`automap_toplevel`
1033
+
1034
+ """
1035
+
1036
+ __abstract__ = True
1037
+
1038
+ classes: ClassVar[Properties[Type[Any]]]
1039
+ """An instance of :class:`.util.Properties` containing classes.
1040
+
1041
+ This object behaves much like the ``.c`` collection on a table. Classes
1042
+ are present under the name they were given, e.g.::
1043
+
1044
+ Base = automap_base()
1045
+ Base.prepare(autoload_with=some_engine)
1046
+
1047
+ User, Address = Base.classes.User, Base.classes.Address
1048
+
1049
+ For class names that overlap with a method name of
1050
+ :class:`.util.Properties`, such as ``items()``, the getitem form
1051
+ is also supported::
1052
+
1053
+ Item = Base.classes["items"]
1054
+
1055
+ """
1056
+
1057
+ by_module: ClassVar[ByModuleProperties]
1058
+ """An instance of :class:`.util.Properties` containing a hierarchal
1059
+ structure of dot-separated module names linked to classes.
1060
+
1061
+ This collection is an alternative to the :attr:`.AutomapBase.classes`
1062
+ collection that is useful when making use of the
1063
+ :paramref:`.AutomapBase.prepare.modulename_for_table` parameter, which will
1064
+ apply distinct ``__module__`` attributes to generated classes.
1065
+
1066
+ The default ``__module__`` an automap-generated class is
1067
+ ``sqlalchemy.ext.automap``; to access this namespace using
1068
+ :attr:`.AutomapBase.by_module` looks like::
1069
+
1070
+ User = Base.by_module.sqlalchemy.ext.automap.User
1071
+
1072
+ If a class had a ``__module__`` of ``mymodule.account``, accessing
1073
+ this namespace looks like::
1074
+
1075
+ MyClass = Base.by_module.mymodule.account.MyClass
1076
+
1077
+ .. versionadded:: 2.0
1078
+
1079
+ .. seealso::
1080
+
1081
+ :ref:`automap_by_module`
1082
+
1083
+ """
1084
+
1085
+ metadata: ClassVar[MetaData]
1086
+ """Refers to the :class:`_schema.MetaData` collection that will be used
1087
+ for new :class:`_schema.Table` objects.
1088
+
1089
+ .. seealso::
1090
+
1091
+ :ref:`orm_declarative_metadata`
1092
+
1093
+ """
1094
+
1095
+ _sa_automapbase_bookkeeping: ClassVar[_Bookkeeping]
1096
+
1097
+ @classmethod
1098
+ @util.deprecated_params(
1099
+ engine=(
1100
+ "2.0",
1101
+ "The :paramref:`_automap.AutomapBase.prepare.engine` parameter "
1102
+ "is deprecated and will be removed in a future release. "
1103
+ "Please use the "
1104
+ ":paramref:`_automap.AutomapBase.prepare.autoload_with` "
1105
+ "parameter.",
1106
+ ),
1107
+ reflect=(
1108
+ "2.0",
1109
+ "The :paramref:`_automap.AutomapBase.prepare.reflect` "
1110
+ "parameter is deprecated and will be removed in a future "
1111
+ "release. Reflection is enabled when "
1112
+ ":paramref:`_automap.AutomapBase.prepare.autoload_with` "
1113
+ "is passed.",
1114
+ ),
1115
+ )
1116
+ def prepare(
1117
+ cls: Type[AutomapBase],
1118
+ autoload_with: Optional[Engine] = None,
1119
+ engine: Optional[Any] = None,
1120
+ reflect: bool = False,
1121
+ schema: Optional[str] = None,
1122
+ classname_for_table: Optional[PythonNameForTableType] = None,
1123
+ modulename_for_table: Optional[PythonNameForTableType] = None,
1124
+ collection_class: Optional[Any] = None,
1125
+ name_for_scalar_relationship: Optional[
1126
+ NameForScalarRelationshipType
1127
+ ] = None,
1128
+ name_for_collection_relationship: Optional[
1129
+ NameForCollectionRelationshipType
1130
+ ] = None,
1131
+ generate_relationship: Optional[GenerateRelationshipType] = None,
1132
+ reflection_options: Union[
1133
+ Dict[_KT, _VT], immutabledict[_KT, _VT]
1134
+ ] = util.EMPTY_DICT,
1135
+ ) -> None:
1136
+ """Extract mapped classes and relationships from the
1137
+ :class:`_schema.MetaData` and perform mappings.
1138
+
1139
+ For full documentation and examples see
1140
+ :ref:`automap_basic_use`.
1141
+
1142
+ :param autoload_with: an :class:`_engine.Engine` or
1143
+ :class:`_engine.Connection` with which
1144
+ to perform schema reflection; when specified, the
1145
+ :meth:`_schema.MetaData.reflect` method will be invoked within
1146
+ the scope of this method.
1147
+
1148
+ :param engine: legacy; use :paramref:`.AutomapBase.autoload_with`.
1149
+ Used to indicate the :class:`_engine.Engine` or
1150
+ :class:`_engine.Connection` with which to reflect tables with,
1151
+ if :paramref:`.AutomapBase.reflect` is True.
1152
+
1153
+ :param reflect: legacy; use :paramref:`.AutomapBase.autoload_with`.
1154
+ Indicates that :meth:`_schema.MetaData.reflect` should be invoked.
1155
+
1156
+ :param classname_for_table: callable function which will be used to
1157
+ produce new class names, given a table name. Defaults to
1158
+ :func:`.classname_for_table`.
1159
+
1160
+ :param modulename_for_table: callable function which will be used to
1161
+ produce the effective ``__module__`` for an internally generated
1162
+ class, to allow for multiple classes of the same name in a single
1163
+ automap base which would be in different "modules".
1164
+
1165
+ Defaults to ``None``, which will indicate that ``__module__`` will not
1166
+ be set explicitly; the Python runtime will use the value
1167
+ ``sqlalchemy.ext.automap`` for these classes.
1168
+
1169
+ When assigning ``__module__`` to generated classes, they can be
1170
+ accessed based on dot-separated module names using the
1171
+ :attr:`.AutomapBase.by_module` collection. Classes that have
1172
+ an explicit ``__module_`` assigned using this hook do **not** get
1173
+ placed into the :attr:`.AutomapBase.classes` collection, only
1174
+ into :attr:`.AutomapBase.by_module`.
1175
+
1176
+ .. versionadded:: 2.0
1177
+
1178
+ .. seealso::
1179
+
1180
+ :ref:`automap_by_module`
1181
+
1182
+ :param name_for_scalar_relationship: callable function which will be
1183
+ used to produce relationship names for scalar relationships. Defaults
1184
+ to :func:`.name_for_scalar_relationship`.
1185
+
1186
+ :param name_for_collection_relationship: callable function which will
1187
+ be used to produce relationship names for collection-oriented
1188
+ relationships. Defaults to :func:`.name_for_collection_relationship`.
1189
+
1190
+ :param generate_relationship: callable function which will be used to
1191
+ actually generate :func:`_orm.relationship` and :func:`.backref`
1192
+ constructs. Defaults to :func:`.generate_relationship`.
1193
+
1194
+ :param collection_class: the Python collection class that will be used
1195
+ when a new :func:`_orm.relationship`
1196
+ object is created that represents a
1197
+ collection. Defaults to ``list``.
1198
+
1199
+ :param schema: Schema name to reflect when reflecting tables using
1200
+ the :paramref:`.AutomapBase.prepare.autoload_with` parameter. The name
1201
+ is passed to the :paramref:`_schema.MetaData.reflect.schema` parameter
1202
+ of :meth:`_schema.MetaData.reflect`. When omitted, the default schema
1203
+ in use by the database connection is used.
1204
+
1205
+ .. note:: The :paramref:`.AutomapBase.prepare.schema`
1206
+ parameter supports reflection of a single schema at a time.
1207
+ In order to include tables from many schemas, use
1208
+ multiple calls to :meth:`.AutomapBase.prepare`.
1209
+
1210
+ For an overview of multiple-schema automap including the use
1211
+ of additional naming conventions to resolve table name
1212
+ conflicts, see the section :ref:`automap_by_module`.
1213
+
1214
+ .. versionadded:: 2.0 :meth:`.AutomapBase.prepare` supports being
1215
+ directly invoked any number of times, keeping track of tables
1216
+ that have already been processed to avoid processing them
1217
+ a second time.
1218
+
1219
+ :param reflection_options: When present, this dictionary of options
1220
+ will be passed to :meth:`_schema.MetaData.reflect`
1221
+ to supply general reflection-specific options like ``only`` and/or
1222
+ dialect-specific options like ``oracle_resolve_synonyms``.
1223
+
1224
+ .. versionadded:: 1.4
1225
+
1226
+ """
1227
+
1228
+ for mr in cls.__mro__:
1229
+ if "_sa_automapbase_bookkeeping" in mr.__dict__:
1230
+ automap_base = cast("Type[AutomapBase]", mr)
1231
+ break
1232
+ else:
1233
+ assert False, "Can't locate automap base in class hierarchy"
1234
+
1235
+ glbls = globals()
1236
+ if classname_for_table is None:
1237
+ classname_for_table = glbls["classname_for_table"]
1238
+ if name_for_scalar_relationship is None:
1239
+ name_for_scalar_relationship = glbls[
1240
+ "name_for_scalar_relationship"
1241
+ ]
1242
+ if name_for_collection_relationship is None:
1243
+ name_for_collection_relationship = glbls[
1244
+ "name_for_collection_relationship"
1245
+ ]
1246
+ if generate_relationship is None:
1247
+ generate_relationship = glbls["generate_relationship"]
1248
+ if collection_class is None:
1249
+ collection_class = list
1250
+
1251
+ if autoload_with:
1252
+ reflect = True
1253
+
1254
+ if engine:
1255
+ autoload_with = engine
1256
+
1257
+ if reflect:
1258
+ assert autoload_with
1259
+ opts = dict(
1260
+ schema=schema,
1261
+ extend_existing=True,
1262
+ autoload_replace=False,
1263
+ )
1264
+ if reflection_options:
1265
+ opts.update(reflection_options)
1266
+ cls.metadata.reflect(autoload_with, **opts) # type: ignore[arg-type] # noqa: E501
1267
+
1268
+ with _CONFIGURE_MUTEX:
1269
+ table_to_map_config: Union[
1270
+ Dict[Optional[Table], _DeferredDeclarativeConfig],
1271
+ Dict[Table, _DeferredDeclarativeConfig],
1272
+ ] = {
1273
+ cast("Table", m.local_table): m
1274
+ for m in _DeferredDeclarativeConfig.classes_for_base(
1275
+ cls, sort=False
1276
+ )
1277
+ }
1278
+
1279
+ many_to_many: List[
1280
+ Tuple[Table, Table, List[ForeignKeyConstraint], Table]
1281
+ ]
1282
+ many_to_many = []
1283
+
1284
+ bookkeeping = automap_base._sa_automapbase_bookkeeping
1285
+ metadata_tables = cls.metadata.tables
1286
+
1287
+ for table_key in set(metadata_tables).difference(
1288
+ bookkeeping.table_keys
1289
+ ):
1290
+ table = metadata_tables[table_key]
1291
+ bookkeeping.table_keys.add(table_key)
1292
+
1293
+ lcl_m2m, rem_m2m, m2m_const = _is_many_to_many(cls, table)
1294
+ if lcl_m2m is not None:
1295
+ assert rem_m2m is not None
1296
+ assert m2m_const is not None
1297
+ many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table))
1298
+ elif not table.primary_key:
1299
+ continue
1300
+ elif table not in table_to_map_config:
1301
+ clsdict: Dict[str, Any] = {"__table__": table}
1302
+ if modulename_for_table is not None:
1303
+ new_module = modulename_for_table(
1304
+ cls, table.name, table
1305
+ )
1306
+ if new_module is not None:
1307
+ clsdict["__module__"] = new_module
1308
+ else:
1309
+ new_module = None
1310
+
1311
+ newname = classname_for_table(cls, table.name, table)
1312
+ if new_module is None and newname in cls.classes:
1313
+ util.warn(
1314
+ "Ignoring duplicate class name "
1315
+ f"'{newname}' "
1316
+ "received in automap base for table "
1317
+ f"{table.key} without "
1318
+ "``__module__`` being set; consider using the "
1319
+ "``modulename_for_table`` hook"
1320
+ )
1321
+ continue
1322
+
1323
+ mapped_cls = type(
1324
+ newname,
1325
+ (automap_base,),
1326
+ clsdict,
1327
+ )
1328
+ map_config = _DeferredDeclarativeConfig.config_for_cls(
1329
+ mapped_cls
1330
+ )
1331
+ assert map_config.cls.__name__ == newname
1332
+ if new_module is None:
1333
+ cls.classes[newname] = mapped_cls
1334
+
1335
+ by_module_properties: ByModuleProperties = cls.by_module
1336
+ for token in map_config.cls.__module__.split("."):
1337
+ if token not in by_module_properties:
1338
+ by_module_properties[token] = util.Properties({})
1339
+
1340
+ props = by_module_properties[token]
1341
+
1342
+ # we can assert this because the clsregistry
1343
+ # module would have raised if there was a mismatch
1344
+ # between modules/classes already.
1345
+ # see test_cls_schema_name_conflict
1346
+ assert isinstance(props, Properties)
1347
+ by_module_properties = props
1348
+
1349
+ by_module_properties[map_config.cls.__name__] = mapped_cls
1350
+
1351
+ table_to_map_config[table] = map_config
1352
+
1353
+ for map_config in table_to_map_config.values():
1354
+ _relationships_for_fks(
1355
+ automap_base,
1356
+ map_config,
1357
+ table_to_map_config,
1358
+ collection_class,
1359
+ name_for_scalar_relationship,
1360
+ name_for_collection_relationship,
1361
+ generate_relationship,
1362
+ )
1363
+
1364
+ for lcl_m2m, rem_m2m, m2m_const, table in many_to_many:
1365
+ _m2m_relationship(
1366
+ automap_base,
1367
+ lcl_m2m,
1368
+ rem_m2m,
1369
+ m2m_const,
1370
+ table,
1371
+ table_to_map_config,
1372
+ collection_class,
1373
+ name_for_scalar_relationship,
1374
+ name_for_collection_relationship,
1375
+ generate_relationship,
1376
+ )
1377
+
1378
+ for map_config in _DeferredDeclarativeConfig.classes_for_base(
1379
+ automap_base
1380
+ ):
1381
+ map_config.map()
1382
+
1383
+ _sa_decl_prepare = True
1384
+ """Indicate that the mapping of classes should be deferred.
1385
+
1386
+ The presence of this attribute name indicates to declarative
1387
+ that the call to mapper() should not occur immediately; instead,
1388
+ information about the table and attributes to be mapped are gathered
1389
+ into an internal structure called _DeferredMapperConfig. These
1390
+ objects can be collected later using classes_for_base(), additional
1391
+ mapping decisions can be made, and then the map() method will actually
1392
+ apply the mapping.
1393
+
1394
+ The only real reason this deferral of the whole
1395
+ thing is needed is to support primary key columns that aren't reflected
1396
+ yet when the class is declared; everything else can theoretically be
1397
+ added to the mapper later. However, the _DeferredMapperConfig is a
1398
+ nice interface in any case which exists at that not usually exposed point
1399
+ at which declarative has the class and the Table but hasn't called
1400
+ mapper() yet.
1401
+
1402
+ """
1403
+
1404
+ @classmethod
1405
+ def _sa_raise_deferred_config(cls) -> NoReturn:
1406
+ raise orm_exc.UnmappedClassError(
1407
+ cls,
1408
+ msg="Class %s is a subclass of AutomapBase. "
1409
+ "Mappings are not produced until the .prepare() "
1410
+ "method is called on the class hierarchy."
1411
+ % orm_exc._safe_cls_name(cls),
1412
+ )
1413
+
1414
+
1415
+ @dataclasses.dataclass
1416
+ class _Bookkeeping:
1417
+ __slots__ = ("table_keys",)
1418
+
1419
+ table_keys: Set[str]
1420
+
1421
+
1422
+ def automap_base(
1423
+ declarative_base: Optional[Type[Any]] = None, **kw: Any
1424
+ ) -> Any:
1425
+ r"""Produce a declarative automap base.
1426
+
1427
+ This function produces a new base class that is a product of the
1428
+ :class:`.AutomapBase` class as well a declarative base produced by
1429
+ :func:`.declarative.declarative_base`.
1430
+
1431
+ All parameters other than ``declarative_base`` are keyword arguments
1432
+ that are passed directly to the :func:`.declarative.declarative_base`
1433
+ function.
1434
+
1435
+ :param declarative_base: an existing class produced by
1436
+ :func:`.declarative.declarative_base`. When this is passed, the function
1437
+ no longer invokes :func:`.declarative.declarative_base` itself, and all
1438
+ other keyword arguments are ignored.
1439
+
1440
+ :param \**kw: keyword arguments are passed along to
1441
+ :func:`.declarative.declarative_base`.
1442
+
1443
+ """
1444
+ if declarative_base is None:
1445
+ Base = _declarative_base(**kw)
1446
+ else:
1447
+ Base = declarative_base
1448
+
1449
+ return type(
1450
+ Base.__name__,
1451
+ (AutomapBase, Base),
1452
+ {
1453
+ "__abstract__": True,
1454
+ "classes": util.Properties({}),
1455
+ "by_module": util.Properties({}),
1456
+ "_sa_automapbase_bookkeeping": _Bookkeeping(set()),
1457
+ },
1458
+ )
1459
+
1460
+
1461
+ def _is_many_to_many(
1462
+ automap_base: Type[Any], table: Table
1463
+ ) -> Tuple[
1464
+ Optional[Table], Optional[Table], Optional[list[ForeignKeyConstraint]]
1465
+ ]:
1466
+ fk_constraints = [
1467
+ const
1468
+ for const in table.constraints
1469
+ if isinstance(const, ForeignKeyConstraint)
1470
+ ]
1471
+ if len(fk_constraints) != 2:
1472
+ return None, None, None
1473
+
1474
+ cols: List[Column[Any]] = sum(
1475
+ [
1476
+ [fk.parent for fk in fk_constraint.elements]
1477
+ for fk_constraint in fk_constraints
1478
+ ],
1479
+ [],
1480
+ )
1481
+
1482
+ if set(cols) != set(table.c):
1483
+ return None, None, None
1484
+
1485
+ return (
1486
+ fk_constraints[0].elements[0].column.table,
1487
+ fk_constraints[1].elements[0].column.table,
1488
+ fk_constraints,
1489
+ )
1490
+
1491
+
1492
+ def _relationships_for_fks(
1493
+ automap_base: Type[Any],
1494
+ map_config: _DeferredDeclarativeConfig,
1495
+ table_to_map_config: Union[
1496
+ Dict[Optional[Table], _DeferredDeclarativeConfig],
1497
+ Dict[Table, _DeferredDeclarativeConfig],
1498
+ ],
1499
+ collection_class: type,
1500
+ name_for_scalar_relationship: NameForScalarRelationshipType,
1501
+ name_for_collection_relationship: NameForCollectionRelationshipType,
1502
+ generate_relationship: GenerateRelationshipType,
1503
+ ) -> None:
1504
+ local_table = cast("Optional[Table]", map_config.local_table)
1505
+ local_cls = cast(
1506
+ "Optional[Type[Any]]", map_config.cls
1507
+ ) # derived from a weakref, may be None
1508
+
1509
+ if local_table is None or local_cls is None:
1510
+ return
1511
+ for constraint in local_table.constraints:
1512
+ if isinstance(constraint, ForeignKeyConstraint):
1513
+ fks = constraint.elements
1514
+ referred_table = fks[0].column.table
1515
+ referred_cfg = table_to_map_config.get(referred_table, None)
1516
+ if referred_cfg is None:
1517
+ continue
1518
+ referred_cls = referred_cfg.cls
1519
+
1520
+ if local_cls is not referred_cls and issubclass(
1521
+ local_cls, referred_cls
1522
+ ):
1523
+ continue
1524
+
1525
+ relationship_name = name_for_scalar_relationship(
1526
+ automap_base, local_cls, referred_cls, constraint
1527
+ )
1528
+ backref_name = name_for_collection_relationship(
1529
+ automap_base, referred_cls, local_cls, constraint
1530
+ )
1531
+
1532
+ o2m_kws: Dict[str, Union[str, bool]] = {}
1533
+ nullable = False not in {fk.parent.nullable for fk in fks}
1534
+ if not nullable:
1535
+ o2m_kws["cascade"] = "all, delete-orphan"
1536
+
1537
+ if (
1538
+ constraint.ondelete
1539
+ and constraint.ondelete.lower() == "cascade"
1540
+ ):
1541
+ o2m_kws["passive_deletes"] = True
1542
+ else:
1543
+ if (
1544
+ constraint.ondelete
1545
+ and constraint.ondelete.lower() == "set null"
1546
+ ):
1547
+ o2m_kws["passive_deletes"] = True
1548
+
1549
+ create_backref = backref_name not in referred_cfg.properties
1550
+
1551
+ if relationship_name not in map_config.properties:
1552
+ if create_backref:
1553
+ backref_obj = generate_relationship(
1554
+ automap_base,
1555
+ interfaces.ONETOMANY,
1556
+ backref,
1557
+ backref_name,
1558
+ referred_cls,
1559
+ local_cls,
1560
+ collection_class=collection_class,
1561
+ **o2m_kws,
1562
+ )
1563
+ else:
1564
+ backref_obj = None
1565
+ rel = generate_relationship(
1566
+ automap_base,
1567
+ interfaces.MANYTOONE,
1568
+ relationship,
1569
+ relationship_name,
1570
+ local_cls,
1571
+ referred_cls,
1572
+ foreign_keys=[fk.parent for fk in constraint.elements],
1573
+ backref=backref_obj,
1574
+ remote_side=[fk.column for fk in constraint.elements],
1575
+ )
1576
+ if rel is not None:
1577
+ map_config.properties[relationship_name] = rel
1578
+ if not create_backref:
1579
+ referred_cfg.properties[
1580
+ backref_name
1581
+ ].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501
1582
+ elif create_backref:
1583
+ rel = generate_relationship(
1584
+ automap_base,
1585
+ interfaces.ONETOMANY,
1586
+ relationship,
1587
+ backref_name,
1588
+ referred_cls,
1589
+ local_cls,
1590
+ foreign_keys=[fk.parent for fk in constraint.elements],
1591
+ back_populates=relationship_name,
1592
+ collection_class=collection_class,
1593
+ **o2m_kws,
1594
+ )
1595
+ if rel is not None:
1596
+ referred_cfg.properties[backref_name] = rel
1597
+ map_config.properties[
1598
+ relationship_name
1599
+ ].back_populates = backref_name # type: ignore[union-attr]
1600
+
1601
+
1602
+ def _m2m_relationship(
1603
+ automap_base: Type[Any],
1604
+ lcl_m2m: Table,
1605
+ rem_m2m: Table,
1606
+ m2m_const: List[ForeignKeyConstraint],
1607
+ table: Table,
1608
+ table_to_map_config: Union[
1609
+ Dict[Optional[Table], _DeferredDeclarativeConfig],
1610
+ Dict[Table, _DeferredDeclarativeConfig],
1611
+ ],
1612
+ collection_class: type,
1613
+ name_for_scalar_relationship: NameForCollectionRelationshipType,
1614
+ name_for_collection_relationship: NameForCollectionRelationshipType,
1615
+ generate_relationship: GenerateRelationshipType,
1616
+ ) -> None:
1617
+ map_config = table_to_map_config.get(lcl_m2m, None)
1618
+ referred_cfg = table_to_map_config.get(rem_m2m, None)
1619
+ if map_config is None or referred_cfg is None:
1620
+ return
1621
+
1622
+ local_cls = map_config.cls
1623
+ referred_cls = referred_cfg.cls
1624
+
1625
+ relationship_name = name_for_collection_relationship(
1626
+ automap_base, local_cls, referred_cls, m2m_const[0]
1627
+ )
1628
+ backref_name = name_for_collection_relationship(
1629
+ automap_base, referred_cls, local_cls, m2m_const[1]
1630
+ )
1631
+
1632
+ create_backref = backref_name not in referred_cfg.properties
1633
+
1634
+ if table in table_to_map_config:
1635
+ overlaps = "__*"
1636
+ else:
1637
+ overlaps = None
1638
+
1639
+ if relationship_name not in map_config.properties:
1640
+ if create_backref:
1641
+ backref_obj = generate_relationship(
1642
+ automap_base,
1643
+ interfaces.MANYTOMANY,
1644
+ backref,
1645
+ backref_name,
1646
+ referred_cls,
1647
+ local_cls,
1648
+ collection_class=collection_class,
1649
+ overlaps=overlaps,
1650
+ )
1651
+ else:
1652
+ backref_obj = None
1653
+
1654
+ rel = generate_relationship(
1655
+ automap_base,
1656
+ interfaces.MANYTOMANY,
1657
+ relationship,
1658
+ relationship_name,
1659
+ local_cls,
1660
+ referred_cls,
1661
+ overlaps=overlaps,
1662
+ secondary=table,
1663
+ primaryjoin=and_(
1664
+ fk.column == fk.parent for fk in m2m_const[0].elements
1665
+ ), # type: ignore [arg-type]
1666
+ secondaryjoin=and_(
1667
+ fk.column == fk.parent for fk in m2m_const[1].elements
1668
+ ), # type: ignore [arg-type]
1669
+ backref=backref_obj,
1670
+ collection_class=collection_class,
1671
+ )
1672
+ if rel is not None:
1673
+ map_config.properties[relationship_name] = rel
1674
+
1675
+ if not create_backref:
1676
+ referred_cfg.properties[
1677
+ backref_name
1678
+ ].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501
1679
+ elif create_backref:
1680
+ rel = generate_relationship(
1681
+ automap_base,
1682
+ interfaces.MANYTOMANY,
1683
+ relationship,
1684
+ backref_name,
1685
+ referred_cls,
1686
+ local_cls,
1687
+ overlaps=overlaps,
1688
+ secondary=table,
1689
+ primaryjoin=and_(
1690
+ fk.column == fk.parent for fk in m2m_const[1].elements
1691
+ ), # type: ignore [arg-type]
1692
+ secondaryjoin=and_(
1693
+ fk.column == fk.parent for fk in m2m_const[0].elements
1694
+ ), # type: ignore [arg-type]
1695
+ back_populates=relationship_name,
1696
+ collection_class=collection_class,
1697
+ )
1698
+ if rel is not None:
1699
+ referred_cfg.properties[backref_name] = rel
1700
+ map_config.properties[
1701
+ relationship_name
1702
+ ].back_populates = backref_name # type: ignore[union-attr]