SQLAlchemy 2.0.47__cp313-cp313t-win32.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.
- sqlalchemy/__init__.py +283 -0
- sqlalchemy/connectors/__init__.py +18 -0
- sqlalchemy/connectors/aioodbc.py +184 -0
- sqlalchemy/connectors/asyncio.py +429 -0
- sqlalchemy/connectors/pyodbc.py +250 -0
- sqlalchemy/cyextension/__init__.py +6 -0
- sqlalchemy/cyextension/collections.cp313t-win32.pyd +0 -0
- sqlalchemy/cyextension/collections.pyx +409 -0
- sqlalchemy/cyextension/immutabledict.cp313t-win32.pyd +0 -0
- sqlalchemy/cyextension/immutabledict.pxd +8 -0
- sqlalchemy/cyextension/immutabledict.pyx +133 -0
- sqlalchemy/cyextension/processors.cp313t-win32.pyd +0 -0
- sqlalchemy/cyextension/processors.pyx +68 -0
- sqlalchemy/cyextension/resultproxy.cp313t-win32.pyd +0 -0
- sqlalchemy/cyextension/resultproxy.pyx +102 -0
- sqlalchemy/cyextension/util.cp313t-win32.pyd +0 -0
- sqlalchemy/cyextension/util.pyx +90 -0
- sqlalchemy/dialects/__init__.py +62 -0
- sqlalchemy/dialects/_typing.py +30 -0
- sqlalchemy/dialects/mssql/__init__.py +88 -0
- sqlalchemy/dialects/mssql/aioodbc.py +63 -0
- sqlalchemy/dialects/mssql/base.py +4093 -0
- sqlalchemy/dialects/mssql/information_schema.py +285 -0
- sqlalchemy/dialects/mssql/json.py +129 -0
- sqlalchemy/dialects/mssql/provision.py +185 -0
- sqlalchemy/dialects/mssql/pymssql.py +126 -0
- sqlalchemy/dialects/mssql/pyodbc.py +760 -0
- sqlalchemy/dialects/mysql/__init__.py +104 -0
- sqlalchemy/dialects/mysql/aiomysql.py +250 -0
- sqlalchemy/dialects/mysql/asyncmy.py +231 -0
- sqlalchemy/dialects/mysql/base.py +3949 -0
- sqlalchemy/dialects/mysql/cymysql.py +106 -0
- sqlalchemy/dialects/mysql/dml.py +225 -0
- sqlalchemy/dialects/mysql/enumerated.py +282 -0
- sqlalchemy/dialects/mysql/expression.py +146 -0
- sqlalchemy/dialects/mysql/json.py +91 -0
- sqlalchemy/dialects/mysql/mariadb.py +72 -0
- sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
- sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
- sqlalchemy/dialects/mysql/mysqldb.py +314 -0
- sqlalchemy/dialects/mysql/provision.py +153 -0
- sqlalchemy/dialects/mysql/pymysql.py +158 -0
- sqlalchemy/dialects/mysql/pyodbc.py +157 -0
- sqlalchemy/dialects/mysql/reflection.py +727 -0
- sqlalchemy/dialects/mysql/reserved_words.py +570 -0
- sqlalchemy/dialects/mysql/types.py +835 -0
- sqlalchemy/dialects/oracle/__init__.py +81 -0
- sqlalchemy/dialects/oracle/base.py +3802 -0
- sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
- sqlalchemy/dialects/oracle/dictionary.py +507 -0
- sqlalchemy/dialects/oracle/oracledb.py +941 -0
- sqlalchemy/dialects/oracle/provision.py +297 -0
- sqlalchemy/dialects/oracle/types.py +316 -0
- sqlalchemy/dialects/oracle/vector.py +365 -0
- sqlalchemy/dialects/postgresql/__init__.py +167 -0
- sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
- sqlalchemy/dialects/postgresql/array.py +519 -0
- sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
- sqlalchemy/dialects/postgresql/base.py +5378 -0
- sqlalchemy/dialects/postgresql/dml.py +339 -0
- sqlalchemy/dialects/postgresql/ext.py +540 -0
- sqlalchemy/dialects/postgresql/hstore.py +406 -0
- sqlalchemy/dialects/postgresql/json.py +404 -0
- sqlalchemy/dialects/postgresql/named_types.py +524 -0
- sqlalchemy/dialects/postgresql/operators.py +129 -0
- sqlalchemy/dialects/postgresql/pg8000.py +669 -0
- sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
- sqlalchemy/dialects/postgresql/provision.py +183 -0
- sqlalchemy/dialects/postgresql/psycopg.py +862 -0
- sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
- sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
- sqlalchemy/dialects/postgresql/ranges.py +1031 -0
- sqlalchemy/dialects/postgresql/types.py +313 -0
- sqlalchemy/dialects/sqlite/__init__.py +57 -0
- sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
- sqlalchemy/dialects/sqlite/base.py +3056 -0
- sqlalchemy/dialects/sqlite/dml.py +263 -0
- sqlalchemy/dialects/sqlite/json.py +92 -0
- sqlalchemy/dialects/sqlite/provision.py +229 -0
- sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
- sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
- sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
- sqlalchemy/engine/__init__.py +62 -0
- sqlalchemy/engine/_py_processors.py +136 -0
- sqlalchemy/engine/_py_row.py +128 -0
- sqlalchemy/engine/_py_util.py +74 -0
- sqlalchemy/engine/base.py +3390 -0
- sqlalchemy/engine/characteristics.py +155 -0
- sqlalchemy/engine/create.py +893 -0
- sqlalchemy/engine/cursor.py +2298 -0
- sqlalchemy/engine/default.py +2394 -0
- sqlalchemy/engine/events.py +965 -0
- sqlalchemy/engine/interfaces.py +3471 -0
- sqlalchemy/engine/mock.py +134 -0
- sqlalchemy/engine/processors.py +61 -0
- sqlalchemy/engine/reflection.py +2102 -0
- sqlalchemy/engine/result.py +2399 -0
- sqlalchemy/engine/row.py +400 -0
- sqlalchemy/engine/strategies.py +16 -0
- sqlalchemy/engine/url.py +924 -0
- sqlalchemy/engine/util.py +167 -0
- sqlalchemy/event/__init__.py +26 -0
- sqlalchemy/event/api.py +220 -0
- sqlalchemy/event/attr.py +676 -0
- sqlalchemy/event/base.py +472 -0
- sqlalchemy/event/legacy.py +258 -0
- sqlalchemy/event/registry.py +390 -0
- sqlalchemy/events.py +17 -0
- sqlalchemy/exc.py +832 -0
- sqlalchemy/ext/__init__.py +11 -0
- sqlalchemy/ext/associationproxy.py +2027 -0
- sqlalchemy/ext/asyncio/__init__.py +25 -0
- sqlalchemy/ext/asyncio/base.py +281 -0
- sqlalchemy/ext/asyncio/engine.py +1471 -0
- sqlalchemy/ext/asyncio/exc.py +21 -0
- sqlalchemy/ext/asyncio/result.py +965 -0
- sqlalchemy/ext/asyncio/scoping.py +1599 -0
- sqlalchemy/ext/asyncio/session.py +1947 -0
- sqlalchemy/ext/automap.py +1701 -0
- sqlalchemy/ext/baked.py +570 -0
- sqlalchemy/ext/compiler.py +600 -0
- sqlalchemy/ext/declarative/__init__.py +65 -0
- sqlalchemy/ext/declarative/extensions.py +564 -0
- sqlalchemy/ext/horizontal_shard.py +478 -0
- sqlalchemy/ext/hybrid.py +1535 -0
- sqlalchemy/ext/indexable.py +364 -0
- sqlalchemy/ext/instrumentation.py +450 -0
- sqlalchemy/ext/mutable.py +1085 -0
- sqlalchemy/ext/mypy/__init__.py +6 -0
- sqlalchemy/ext/mypy/apply.py +324 -0
- sqlalchemy/ext/mypy/decl_class.py +515 -0
- sqlalchemy/ext/mypy/infer.py +590 -0
- sqlalchemy/ext/mypy/names.py +335 -0
- sqlalchemy/ext/mypy/plugin.py +303 -0
- sqlalchemy/ext/mypy/util.py +357 -0
- sqlalchemy/ext/orderinglist.py +439 -0
- sqlalchemy/ext/serializer.py +185 -0
- sqlalchemy/future/__init__.py +16 -0
- sqlalchemy/future/engine.py +15 -0
- sqlalchemy/inspection.py +174 -0
- sqlalchemy/log.py +288 -0
- sqlalchemy/orm/__init__.py +171 -0
- sqlalchemy/orm/_orm_constructors.py +2661 -0
- sqlalchemy/orm/_typing.py +179 -0
- sqlalchemy/orm/attributes.py +2845 -0
- sqlalchemy/orm/base.py +971 -0
- sqlalchemy/orm/bulk_persistence.py +2135 -0
- sqlalchemy/orm/clsregistry.py +571 -0
- sqlalchemy/orm/collections.py +1627 -0
- sqlalchemy/orm/context.py +3334 -0
- sqlalchemy/orm/decl_api.py +2004 -0
- sqlalchemy/orm/decl_base.py +2192 -0
- sqlalchemy/orm/dependency.py +1302 -0
- sqlalchemy/orm/descriptor_props.py +1092 -0
- sqlalchemy/orm/dynamic.py +300 -0
- sqlalchemy/orm/evaluator.py +379 -0
- sqlalchemy/orm/events.py +3252 -0
- sqlalchemy/orm/exc.py +237 -0
- sqlalchemy/orm/identity.py +302 -0
- sqlalchemy/orm/instrumentation.py +754 -0
- sqlalchemy/orm/interfaces.py +1496 -0
- sqlalchemy/orm/loading.py +1686 -0
- sqlalchemy/orm/mapped_collection.py +557 -0
- sqlalchemy/orm/mapper.py +4444 -0
- sqlalchemy/orm/path_registry.py +809 -0
- sqlalchemy/orm/persistence.py +1788 -0
- sqlalchemy/orm/properties.py +935 -0
- sqlalchemy/orm/query.py +3459 -0
- sqlalchemy/orm/relationships.py +3508 -0
- sqlalchemy/orm/scoping.py +2148 -0
- sqlalchemy/orm/session.py +5280 -0
- sqlalchemy/orm/state.py +1168 -0
- sqlalchemy/orm/state_changes.py +196 -0
- sqlalchemy/orm/strategies.py +3470 -0
- sqlalchemy/orm/strategy_options.py +2568 -0
- sqlalchemy/orm/sync.py +164 -0
- sqlalchemy/orm/unitofwork.py +796 -0
- sqlalchemy/orm/util.py +2403 -0
- sqlalchemy/orm/writeonly.py +674 -0
- sqlalchemy/pool/__init__.py +44 -0
- sqlalchemy/pool/base.py +1524 -0
- sqlalchemy/pool/events.py +375 -0
- sqlalchemy/pool/impl.py +588 -0
- sqlalchemy/py.typed +0 -0
- sqlalchemy/schema.py +69 -0
- sqlalchemy/sql/__init__.py +145 -0
- sqlalchemy/sql/_dml_constructors.py +132 -0
- sqlalchemy/sql/_elements_constructors.py +1872 -0
- sqlalchemy/sql/_orm_types.py +20 -0
- sqlalchemy/sql/_py_util.py +75 -0
- sqlalchemy/sql/_selectable_constructors.py +763 -0
- sqlalchemy/sql/_typing.py +482 -0
- sqlalchemy/sql/annotation.py +587 -0
- sqlalchemy/sql/base.py +2293 -0
- sqlalchemy/sql/cache_key.py +1057 -0
- sqlalchemy/sql/coercions.py +1404 -0
- sqlalchemy/sql/compiler.py +8081 -0
- sqlalchemy/sql/crud.py +1752 -0
- sqlalchemy/sql/ddl.py +1444 -0
- sqlalchemy/sql/default_comparator.py +551 -0
- sqlalchemy/sql/dml.py +1850 -0
- sqlalchemy/sql/elements.py +5589 -0
- sqlalchemy/sql/events.py +458 -0
- sqlalchemy/sql/expression.py +159 -0
- sqlalchemy/sql/functions.py +2158 -0
- sqlalchemy/sql/lambdas.py +1442 -0
- sqlalchemy/sql/naming.py +209 -0
- sqlalchemy/sql/operators.py +2623 -0
- sqlalchemy/sql/roles.py +323 -0
- sqlalchemy/sql/schema.py +6222 -0
- sqlalchemy/sql/selectable.py +7265 -0
- sqlalchemy/sql/sqltypes.py +3930 -0
- sqlalchemy/sql/traversals.py +1024 -0
- sqlalchemy/sql/type_api.py +2368 -0
- sqlalchemy/sql/util.py +1485 -0
- sqlalchemy/sql/visitors.py +1164 -0
- sqlalchemy/testing/__init__.py +96 -0
- sqlalchemy/testing/assertions.py +994 -0
- sqlalchemy/testing/assertsql.py +520 -0
- sqlalchemy/testing/asyncio.py +135 -0
- sqlalchemy/testing/config.py +434 -0
- sqlalchemy/testing/engines.py +483 -0
- sqlalchemy/testing/entities.py +117 -0
- sqlalchemy/testing/exclusions.py +476 -0
- sqlalchemy/testing/fixtures/__init__.py +28 -0
- sqlalchemy/testing/fixtures/base.py +384 -0
- sqlalchemy/testing/fixtures/mypy.py +332 -0
- sqlalchemy/testing/fixtures/orm.py +227 -0
- sqlalchemy/testing/fixtures/sql.py +482 -0
- sqlalchemy/testing/pickleable.py +155 -0
- sqlalchemy/testing/plugin/__init__.py +6 -0
- sqlalchemy/testing/plugin/bootstrap.py +51 -0
- sqlalchemy/testing/plugin/plugin_base.py +828 -0
- sqlalchemy/testing/plugin/pytestplugin.py +892 -0
- sqlalchemy/testing/profiling.py +329 -0
- sqlalchemy/testing/provision.py +603 -0
- sqlalchemy/testing/requirements.py +1945 -0
- sqlalchemy/testing/schema.py +198 -0
- sqlalchemy/testing/suite/__init__.py +19 -0
- sqlalchemy/testing/suite/test_cte.py +237 -0
- sqlalchemy/testing/suite/test_ddl.py +389 -0
- sqlalchemy/testing/suite/test_deprecations.py +153 -0
- sqlalchemy/testing/suite/test_dialect.py +776 -0
- sqlalchemy/testing/suite/test_insert.py +630 -0
- sqlalchemy/testing/suite/test_reflection.py +3557 -0
- sqlalchemy/testing/suite/test_results.py +504 -0
- sqlalchemy/testing/suite/test_rowcount.py +258 -0
- sqlalchemy/testing/suite/test_select.py +2010 -0
- sqlalchemy/testing/suite/test_sequence.py +317 -0
- sqlalchemy/testing/suite/test_types.py +2147 -0
- sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
- sqlalchemy/testing/suite/test_update_delete.py +139 -0
- sqlalchemy/testing/util.py +535 -0
- sqlalchemy/testing/warnings.py +52 -0
- sqlalchemy/types.py +74 -0
- sqlalchemy/util/__init__.py +162 -0
- sqlalchemy/util/_collections.py +712 -0
- sqlalchemy/util/_concurrency_py3k.py +288 -0
- sqlalchemy/util/_has_cy.py +40 -0
- sqlalchemy/util/_py_collections.py +541 -0
- sqlalchemy/util/compat.py +421 -0
- sqlalchemy/util/concurrency.py +110 -0
- sqlalchemy/util/deprecations.py +401 -0
- sqlalchemy/util/langhelpers.py +2203 -0
- sqlalchemy/util/preloaded.py +150 -0
- sqlalchemy/util/queue.py +322 -0
- sqlalchemy/util/tool_support.py +201 -0
- sqlalchemy/util/topological.py +120 -0
- sqlalchemy/util/typing.py +734 -0
- sqlalchemy-2.0.47.dist-info/METADATA +243 -0
- sqlalchemy-2.0.47.dist-info/RECORD +274 -0
- sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
- sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
- sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1701 @@
|
|
|
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
|
+
from __future__ import annotations
|
|
714
|
+
|
|
715
|
+
import dataclasses
|
|
716
|
+
from typing import Any
|
|
717
|
+
from typing import Callable
|
|
718
|
+
from typing import cast
|
|
719
|
+
from typing import ClassVar
|
|
720
|
+
from typing import Dict
|
|
721
|
+
from typing import List
|
|
722
|
+
from typing import NoReturn
|
|
723
|
+
from typing import Optional
|
|
724
|
+
from typing import overload
|
|
725
|
+
from typing import Set
|
|
726
|
+
from typing import Tuple
|
|
727
|
+
from typing import Type
|
|
728
|
+
from typing import TYPE_CHECKING
|
|
729
|
+
from typing import TypeVar
|
|
730
|
+
from typing import Union
|
|
731
|
+
|
|
732
|
+
from .. import util
|
|
733
|
+
from ..orm import backref
|
|
734
|
+
from ..orm import declarative_base as _declarative_base
|
|
735
|
+
from ..orm import exc as orm_exc
|
|
736
|
+
from ..orm import interfaces
|
|
737
|
+
from ..orm import relationship
|
|
738
|
+
from ..orm.decl_base import _DeferredMapperConfig
|
|
739
|
+
from ..orm.mapper import _CONFIGURE_MUTEX
|
|
740
|
+
from ..schema import ForeignKeyConstraint
|
|
741
|
+
from ..sql import and_
|
|
742
|
+
from ..util import Properties
|
|
743
|
+
from ..util.typing import Protocol
|
|
744
|
+
|
|
745
|
+
if TYPE_CHECKING:
|
|
746
|
+
from ..engine.base import Engine
|
|
747
|
+
from ..orm.base import RelationshipDirection
|
|
748
|
+
from ..orm.relationships import ORMBackrefArgument
|
|
749
|
+
from ..orm.relationships import Relationship
|
|
750
|
+
from ..sql.schema import Column
|
|
751
|
+
from ..sql.schema import MetaData
|
|
752
|
+
from ..sql.schema import Table
|
|
753
|
+
from ..util import immutabledict
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
_KT = TypeVar("_KT", bound=Any)
|
|
757
|
+
_VT = TypeVar("_VT", bound=Any)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
class PythonNameForTableType(Protocol):
|
|
761
|
+
def __call__(
|
|
762
|
+
self, base: Type[Any], tablename: str, table: Table
|
|
763
|
+
) -> str: ...
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def classname_for_table(
|
|
767
|
+
base: Type[Any],
|
|
768
|
+
tablename: str,
|
|
769
|
+
table: Table,
|
|
770
|
+
) -> str:
|
|
771
|
+
"""Return the class name that should be used, given the name
|
|
772
|
+
of a table.
|
|
773
|
+
|
|
774
|
+
The default implementation is::
|
|
775
|
+
|
|
776
|
+
return str(tablename)
|
|
777
|
+
|
|
778
|
+
Alternate implementations can be specified using the
|
|
779
|
+
:paramref:`.AutomapBase.prepare.classname_for_table`
|
|
780
|
+
parameter.
|
|
781
|
+
|
|
782
|
+
:param base: the :class:`.AutomapBase` class doing the prepare.
|
|
783
|
+
|
|
784
|
+
:param tablename: string name of the :class:`_schema.Table`.
|
|
785
|
+
|
|
786
|
+
:param table: the :class:`_schema.Table` object itself.
|
|
787
|
+
|
|
788
|
+
:return: a string class name.
|
|
789
|
+
|
|
790
|
+
.. note::
|
|
791
|
+
|
|
792
|
+
In Python 2, the string used for the class name **must** be a
|
|
793
|
+
non-Unicode object, e.g. a ``str()`` object. The ``.name`` attribute
|
|
794
|
+
of :class:`_schema.Table` is typically a Python unicode subclass,
|
|
795
|
+
so the
|
|
796
|
+
``str()`` function should be applied to this name, after accounting for
|
|
797
|
+
any non-ASCII characters.
|
|
798
|
+
|
|
799
|
+
"""
|
|
800
|
+
return str(tablename)
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class NameForScalarRelationshipType(Protocol):
|
|
804
|
+
def __call__(
|
|
805
|
+
self,
|
|
806
|
+
base: Type[Any],
|
|
807
|
+
local_cls: Type[Any],
|
|
808
|
+
referred_cls: Type[Any],
|
|
809
|
+
constraint: ForeignKeyConstraint,
|
|
810
|
+
) -> str: ...
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def name_for_scalar_relationship(
|
|
814
|
+
base: Type[Any],
|
|
815
|
+
local_cls: Type[Any],
|
|
816
|
+
referred_cls: Type[Any],
|
|
817
|
+
constraint: ForeignKeyConstraint,
|
|
818
|
+
) -> str:
|
|
819
|
+
"""Return the attribute name that should be used to refer from one
|
|
820
|
+
class to another, for a scalar object reference.
|
|
821
|
+
|
|
822
|
+
The default implementation is::
|
|
823
|
+
|
|
824
|
+
return referred_cls.__name__.lower()
|
|
825
|
+
|
|
826
|
+
Alternate implementations can be specified using the
|
|
827
|
+
:paramref:`.AutomapBase.prepare.name_for_scalar_relationship`
|
|
828
|
+
parameter.
|
|
829
|
+
|
|
830
|
+
:param base: the :class:`.AutomapBase` class doing the prepare.
|
|
831
|
+
|
|
832
|
+
:param local_cls: the class to be mapped on the local side.
|
|
833
|
+
|
|
834
|
+
:param referred_cls: the class to be mapped on the referring side.
|
|
835
|
+
|
|
836
|
+
:param constraint: the :class:`_schema.ForeignKeyConstraint` that is being
|
|
837
|
+
inspected to produce this relationship.
|
|
838
|
+
|
|
839
|
+
"""
|
|
840
|
+
return referred_cls.__name__.lower()
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
class NameForCollectionRelationshipType(Protocol):
|
|
844
|
+
def __call__(
|
|
845
|
+
self,
|
|
846
|
+
base: Type[Any],
|
|
847
|
+
local_cls: Type[Any],
|
|
848
|
+
referred_cls: Type[Any],
|
|
849
|
+
constraint: ForeignKeyConstraint,
|
|
850
|
+
) -> str: ...
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def name_for_collection_relationship(
|
|
854
|
+
base: Type[Any],
|
|
855
|
+
local_cls: Type[Any],
|
|
856
|
+
referred_cls: Type[Any],
|
|
857
|
+
constraint: ForeignKeyConstraint,
|
|
858
|
+
) -> str:
|
|
859
|
+
"""Return the attribute name that should be used to refer from one
|
|
860
|
+
class to another, for a collection reference.
|
|
861
|
+
|
|
862
|
+
The default implementation is::
|
|
863
|
+
|
|
864
|
+
return referred_cls.__name__.lower() + "_collection"
|
|
865
|
+
|
|
866
|
+
Alternate implementations
|
|
867
|
+
can be specified using the
|
|
868
|
+
:paramref:`.AutomapBase.prepare.name_for_collection_relationship`
|
|
869
|
+
parameter.
|
|
870
|
+
|
|
871
|
+
:param base: the :class:`.AutomapBase` class doing the prepare.
|
|
872
|
+
|
|
873
|
+
:param local_cls: the class to be mapped on the local side.
|
|
874
|
+
|
|
875
|
+
:param referred_cls: the class to be mapped on the referring side.
|
|
876
|
+
|
|
877
|
+
:param constraint: the :class:`_schema.ForeignKeyConstraint` that is being
|
|
878
|
+
inspected to produce this relationship.
|
|
879
|
+
|
|
880
|
+
"""
|
|
881
|
+
return referred_cls.__name__.lower() + "_collection"
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
class GenerateRelationshipType(Protocol):
|
|
885
|
+
@overload
|
|
886
|
+
def __call__(
|
|
887
|
+
self,
|
|
888
|
+
base: Type[Any],
|
|
889
|
+
direction: RelationshipDirection,
|
|
890
|
+
return_fn: Callable[..., Relationship[Any]],
|
|
891
|
+
attrname: str,
|
|
892
|
+
local_cls: Type[Any],
|
|
893
|
+
referred_cls: Type[Any],
|
|
894
|
+
**kw: Any,
|
|
895
|
+
) -> Relationship[Any]: ...
|
|
896
|
+
|
|
897
|
+
@overload
|
|
898
|
+
def __call__(
|
|
899
|
+
self,
|
|
900
|
+
base: Type[Any],
|
|
901
|
+
direction: RelationshipDirection,
|
|
902
|
+
return_fn: Callable[..., ORMBackrefArgument],
|
|
903
|
+
attrname: str,
|
|
904
|
+
local_cls: Type[Any],
|
|
905
|
+
referred_cls: Type[Any],
|
|
906
|
+
**kw: Any,
|
|
907
|
+
) -> ORMBackrefArgument: ...
|
|
908
|
+
|
|
909
|
+
def __call__(
|
|
910
|
+
self,
|
|
911
|
+
base: Type[Any],
|
|
912
|
+
direction: RelationshipDirection,
|
|
913
|
+
return_fn: Union[
|
|
914
|
+
Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument]
|
|
915
|
+
],
|
|
916
|
+
attrname: str,
|
|
917
|
+
local_cls: Type[Any],
|
|
918
|
+
referred_cls: Type[Any],
|
|
919
|
+
**kw: Any,
|
|
920
|
+
) -> Union[ORMBackrefArgument, Relationship[Any]]: ...
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
@overload
|
|
924
|
+
def generate_relationship(
|
|
925
|
+
base: Type[Any],
|
|
926
|
+
direction: RelationshipDirection,
|
|
927
|
+
return_fn: Callable[..., Relationship[Any]],
|
|
928
|
+
attrname: str,
|
|
929
|
+
local_cls: Type[Any],
|
|
930
|
+
referred_cls: Type[Any],
|
|
931
|
+
**kw: Any,
|
|
932
|
+
) -> Relationship[Any]: ...
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
@overload
|
|
936
|
+
def generate_relationship(
|
|
937
|
+
base: Type[Any],
|
|
938
|
+
direction: RelationshipDirection,
|
|
939
|
+
return_fn: Callable[..., ORMBackrefArgument],
|
|
940
|
+
attrname: str,
|
|
941
|
+
local_cls: Type[Any],
|
|
942
|
+
referred_cls: Type[Any],
|
|
943
|
+
**kw: Any,
|
|
944
|
+
) -> ORMBackrefArgument: ...
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def generate_relationship(
|
|
948
|
+
base: Type[Any],
|
|
949
|
+
direction: RelationshipDirection,
|
|
950
|
+
return_fn: Union[
|
|
951
|
+
Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument]
|
|
952
|
+
],
|
|
953
|
+
attrname: str,
|
|
954
|
+
local_cls: Type[Any],
|
|
955
|
+
referred_cls: Type[Any],
|
|
956
|
+
**kw: Any,
|
|
957
|
+
) -> Union[Relationship[Any], ORMBackrefArgument]:
|
|
958
|
+
r"""Generate a :func:`_orm.relationship` or :func:`.backref`
|
|
959
|
+
on behalf of two
|
|
960
|
+
mapped classes.
|
|
961
|
+
|
|
962
|
+
An alternate implementation of this function can be specified using the
|
|
963
|
+
:paramref:`.AutomapBase.prepare.generate_relationship` parameter.
|
|
964
|
+
|
|
965
|
+
The default implementation of this function is as follows::
|
|
966
|
+
|
|
967
|
+
if return_fn is backref:
|
|
968
|
+
return return_fn(attrname, **kw)
|
|
969
|
+
elif return_fn is relationship:
|
|
970
|
+
return return_fn(referred_cls, **kw)
|
|
971
|
+
else:
|
|
972
|
+
raise TypeError("Unknown relationship function: %s" % return_fn)
|
|
973
|
+
|
|
974
|
+
:param base: the :class:`.AutomapBase` class doing the prepare.
|
|
975
|
+
|
|
976
|
+
:param direction: indicate the "direction" of the relationship; this will
|
|
977
|
+
be one of :data:`.ONETOMANY`, :data:`.MANYTOONE`, :data:`.MANYTOMANY`.
|
|
978
|
+
|
|
979
|
+
:param return_fn: the function that is used by default to create the
|
|
980
|
+
relationship. This will be either :func:`_orm.relationship` or
|
|
981
|
+
:func:`.backref`. The :func:`.backref` function's result will be used to
|
|
982
|
+
produce a new :func:`_orm.relationship` in a second step,
|
|
983
|
+
so it is critical
|
|
984
|
+
that user-defined implementations correctly differentiate between the two
|
|
985
|
+
functions, if a custom relationship function is being used.
|
|
986
|
+
|
|
987
|
+
:param attrname: the attribute name to which this relationship is being
|
|
988
|
+
assigned. If the value of :paramref:`.generate_relationship.return_fn` is
|
|
989
|
+
the :func:`.backref` function, then this name is the name that is being
|
|
990
|
+
assigned to the backref.
|
|
991
|
+
|
|
992
|
+
:param local_cls: the "local" class to which this relationship or backref
|
|
993
|
+
will be locally present.
|
|
994
|
+
|
|
995
|
+
:param referred_cls: the "referred" class to which the relationship or
|
|
996
|
+
backref refers to.
|
|
997
|
+
|
|
998
|
+
:param \**kw: all additional keyword arguments are passed along to the
|
|
999
|
+
function.
|
|
1000
|
+
|
|
1001
|
+
:return: a :func:`_orm.relationship` or :func:`.backref` construct,
|
|
1002
|
+
as dictated
|
|
1003
|
+
by the :paramref:`.generate_relationship.return_fn` parameter.
|
|
1004
|
+
|
|
1005
|
+
"""
|
|
1006
|
+
|
|
1007
|
+
if return_fn is backref:
|
|
1008
|
+
return return_fn(attrname, **kw)
|
|
1009
|
+
elif return_fn is relationship:
|
|
1010
|
+
return return_fn(referred_cls, **kw)
|
|
1011
|
+
else:
|
|
1012
|
+
raise TypeError("Unknown relationship function: %s" % return_fn)
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
ByModuleProperties = Properties[Union["ByModuleProperties", Type[Any]]]
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
class AutomapBase:
|
|
1019
|
+
"""Base class for an "automap" schema.
|
|
1020
|
+
|
|
1021
|
+
The :class:`.AutomapBase` class can be compared to the "declarative base"
|
|
1022
|
+
class that is produced by the :func:`.declarative.declarative_base`
|
|
1023
|
+
function. In practice, the :class:`.AutomapBase` class is always used
|
|
1024
|
+
as a mixin along with an actual declarative base.
|
|
1025
|
+
|
|
1026
|
+
A new subclassable :class:`.AutomapBase` is typically instantiated
|
|
1027
|
+
using the :func:`.automap_base` function.
|
|
1028
|
+
|
|
1029
|
+
.. seealso::
|
|
1030
|
+
|
|
1031
|
+
:ref:`automap_toplevel`
|
|
1032
|
+
|
|
1033
|
+
"""
|
|
1034
|
+
|
|
1035
|
+
__abstract__ = True
|
|
1036
|
+
|
|
1037
|
+
classes: ClassVar[Properties[Type[Any]]]
|
|
1038
|
+
"""An instance of :class:`.util.Properties` containing classes.
|
|
1039
|
+
|
|
1040
|
+
This object behaves much like the ``.c`` collection on a table. Classes
|
|
1041
|
+
are present under the name they were given, e.g.::
|
|
1042
|
+
|
|
1043
|
+
Base = automap_base()
|
|
1044
|
+
Base.prepare(autoload_with=some_engine)
|
|
1045
|
+
|
|
1046
|
+
User, Address = Base.classes.User, Base.classes.Address
|
|
1047
|
+
|
|
1048
|
+
For class names that overlap with a method name of
|
|
1049
|
+
:class:`.util.Properties`, such as ``items()``, the getitem form
|
|
1050
|
+
is also supported::
|
|
1051
|
+
|
|
1052
|
+
Item = Base.classes["items"]
|
|
1053
|
+
|
|
1054
|
+
"""
|
|
1055
|
+
|
|
1056
|
+
by_module: ClassVar[ByModuleProperties]
|
|
1057
|
+
"""An instance of :class:`.util.Properties` containing a hierarchal
|
|
1058
|
+
structure of dot-separated module names linked to classes.
|
|
1059
|
+
|
|
1060
|
+
This collection is an alternative to the :attr:`.AutomapBase.classes`
|
|
1061
|
+
collection that is useful when making use of the
|
|
1062
|
+
:paramref:`.AutomapBase.prepare.modulename_for_table` parameter, which will
|
|
1063
|
+
apply distinct ``__module__`` attributes to generated classes.
|
|
1064
|
+
|
|
1065
|
+
The default ``__module__`` an automap-generated class is
|
|
1066
|
+
``sqlalchemy.ext.automap``; to access this namespace using
|
|
1067
|
+
:attr:`.AutomapBase.by_module` looks like::
|
|
1068
|
+
|
|
1069
|
+
User = Base.by_module.sqlalchemy.ext.automap.User
|
|
1070
|
+
|
|
1071
|
+
If a class had a ``__module__`` of ``mymodule.account``, accessing
|
|
1072
|
+
this namespace looks like::
|
|
1073
|
+
|
|
1074
|
+
MyClass = Base.by_module.mymodule.account.MyClass
|
|
1075
|
+
|
|
1076
|
+
.. versionadded:: 2.0
|
|
1077
|
+
|
|
1078
|
+
.. seealso::
|
|
1079
|
+
|
|
1080
|
+
:ref:`automap_by_module`
|
|
1081
|
+
|
|
1082
|
+
"""
|
|
1083
|
+
|
|
1084
|
+
metadata: ClassVar[MetaData]
|
|
1085
|
+
"""Refers to the :class:`_schema.MetaData` collection that will be used
|
|
1086
|
+
for new :class:`_schema.Table` objects.
|
|
1087
|
+
|
|
1088
|
+
.. seealso::
|
|
1089
|
+
|
|
1090
|
+
:ref:`orm_declarative_metadata`
|
|
1091
|
+
|
|
1092
|
+
"""
|
|
1093
|
+
|
|
1094
|
+
_sa_automapbase_bookkeeping: ClassVar[_Bookkeeping]
|
|
1095
|
+
|
|
1096
|
+
@classmethod
|
|
1097
|
+
@util.deprecated_params(
|
|
1098
|
+
engine=(
|
|
1099
|
+
"2.0",
|
|
1100
|
+
"The :paramref:`_automap.AutomapBase.prepare.engine` parameter "
|
|
1101
|
+
"is deprecated and will be removed in a future release. "
|
|
1102
|
+
"Please use the "
|
|
1103
|
+
":paramref:`_automap.AutomapBase.prepare.autoload_with` "
|
|
1104
|
+
"parameter.",
|
|
1105
|
+
),
|
|
1106
|
+
reflect=(
|
|
1107
|
+
"2.0",
|
|
1108
|
+
"The :paramref:`_automap.AutomapBase.prepare.reflect` "
|
|
1109
|
+
"parameter is deprecated and will be removed in a future "
|
|
1110
|
+
"release. Reflection is enabled when "
|
|
1111
|
+
":paramref:`_automap.AutomapBase.prepare.autoload_with` "
|
|
1112
|
+
"is passed.",
|
|
1113
|
+
),
|
|
1114
|
+
)
|
|
1115
|
+
def prepare(
|
|
1116
|
+
cls: Type[AutomapBase],
|
|
1117
|
+
autoload_with: Optional[Engine] = None,
|
|
1118
|
+
engine: Optional[Any] = None,
|
|
1119
|
+
reflect: bool = False,
|
|
1120
|
+
schema: Optional[str] = None,
|
|
1121
|
+
classname_for_table: Optional[PythonNameForTableType] = None,
|
|
1122
|
+
modulename_for_table: Optional[PythonNameForTableType] = None,
|
|
1123
|
+
collection_class: Optional[Any] = None,
|
|
1124
|
+
name_for_scalar_relationship: Optional[
|
|
1125
|
+
NameForScalarRelationshipType
|
|
1126
|
+
] = None,
|
|
1127
|
+
name_for_collection_relationship: Optional[
|
|
1128
|
+
NameForCollectionRelationshipType
|
|
1129
|
+
] = None,
|
|
1130
|
+
generate_relationship: Optional[GenerateRelationshipType] = None,
|
|
1131
|
+
reflection_options: Union[
|
|
1132
|
+
Dict[_KT, _VT], immutabledict[_KT, _VT]
|
|
1133
|
+
] = util.EMPTY_DICT,
|
|
1134
|
+
) -> None:
|
|
1135
|
+
"""Extract mapped classes and relationships from the
|
|
1136
|
+
:class:`_schema.MetaData` and perform mappings.
|
|
1137
|
+
|
|
1138
|
+
For full documentation and examples see
|
|
1139
|
+
:ref:`automap_basic_use`.
|
|
1140
|
+
|
|
1141
|
+
:param autoload_with: an :class:`_engine.Engine` or
|
|
1142
|
+
:class:`_engine.Connection` with which
|
|
1143
|
+
to perform schema reflection; when specified, the
|
|
1144
|
+
:meth:`_schema.MetaData.reflect` method will be invoked within
|
|
1145
|
+
the scope of this method.
|
|
1146
|
+
|
|
1147
|
+
:param engine: legacy; use :paramref:`.AutomapBase.autoload_with`.
|
|
1148
|
+
Used to indicate the :class:`_engine.Engine` or
|
|
1149
|
+
:class:`_engine.Connection` with which to reflect tables with,
|
|
1150
|
+
if :paramref:`.AutomapBase.reflect` is True.
|
|
1151
|
+
|
|
1152
|
+
:param reflect: legacy; use :paramref:`.AutomapBase.autoload_with`.
|
|
1153
|
+
Indicates that :meth:`_schema.MetaData.reflect` should be invoked.
|
|
1154
|
+
|
|
1155
|
+
:param classname_for_table: callable function which will be used to
|
|
1156
|
+
produce new class names, given a table name. Defaults to
|
|
1157
|
+
:func:`.classname_for_table`.
|
|
1158
|
+
|
|
1159
|
+
:param modulename_for_table: callable function which will be used to
|
|
1160
|
+
produce the effective ``__module__`` for an internally generated
|
|
1161
|
+
class, to allow for multiple classes of the same name in a single
|
|
1162
|
+
automap base which would be in different "modules".
|
|
1163
|
+
|
|
1164
|
+
Defaults to ``None``, which will indicate that ``__module__`` will not
|
|
1165
|
+
be set explicitly; the Python runtime will use the value
|
|
1166
|
+
``sqlalchemy.ext.automap`` for these classes.
|
|
1167
|
+
|
|
1168
|
+
When assigning ``__module__`` to generated classes, they can be
|
|
1169
|
+
accessed based on dot-separated module names using the
|
|
1170
|
+
:attr:`.AutomapBase.by_module` collection. Classes that have
|
|
1171
|
+
an explicit ``__module_`` assigned using this hook do **not** get
|
|
1172
|
+
placed into the :attr:`.AutomapBase.classes` collection, only
|
|
1173
|
+
into :attr:`.AutomapBase.by_module`.
|
|
1174
|
+
|
|
1175
|
+
.. versionadded:: 2.0
|
|
1176
|
+
|
|
1177
|
+
.. seealso::
|
|
1178
|
+
|
|
1179
|
+
:ref:`automap_by_module`
|
|
1180
|
+
|
|
1181
|
+
:param name_for_scalar_relationship: callable function which will be
|
|
1182
|
+
used to produce relationship names for scalar relationships. Defaults
|
|
1183
|
+
to :func:`.name_for_scalar_relationship`.
|
|
1184
|
+
|
|
1185
|
+
:param name_for_collection_relationship: callable function which will
|
|
1186
|
+
be used to produce relationship names for collection-oriented
|
|
1187
|
+
relationships. Defaults to :func:`.name_for_collection_relationship`.
|
|
1188
|
+
|
|
1189
|
+
:param generate_relationship: callable function which will be used to
|
|
1190
|
+
actually generate :func:`_orm.relationship` and :func:`.backref`
|
|
1191
|
+
constructs. Defaults to :func:`.generate_relationship`.
|
|
1192
|
+
|
|
1193
|
+
:param collection_class: the Python collection class that will be used
|
|
1194
|
+
when a new :func:`_orm.relationship`
|
|
1195
|
+
object is created that represents a
|
|
1196
|
+
collection. Defaults to ``list``.
|
|
1197
|
+
|
|
1198
|
+
:param schema: Schema name to reflect when reflecting tables using
|
|
1199
|
+
the :paramref:`.AutomapBase.prepare.autoload_with` parameter. The name
|
|
1200
|
+
is passed to the :paramref:`_schema.MetaData.reflect.schema` parameter
|
|
1201
|
+
of :meth:`_schema.MetaData.reflect`. When omitted, the default schema
|
|
1202
|
+
in use by the database connection is used.
|
|
1203
|
+
|
|
1204
|
+
.. note:: The :paramref:`.AutomapBase.prepare.schema`
|
|
1205
|
+
parameter supports reflection of a single schema at a time.
|
|
1206
|
+
In order to include tables from many schemas, use
|
|
1207
|
+
multiple calls to :meth:`.AutomapBase.prepare`.
|
|
1208
|
+
|
|
1209
|
+
For an overview of multiple-schema automap including the use
|
|
1210
|
+
of additional naming conventions to resolve table name
|
|
1211
|
+
conflicts, see the section :ref:`automap_by_module`.
|
|
1212
|
+
|
|
1213
|
+
.. versionadded:: 2.0 :meth:`.AutomapBase.prepare` supports being
|
|
1214
|
+
directly invoked any number of times, keeping track of tables
|
|
1215
|
+
that have already been processed to avoid processing them
|
|
1216
|
+
a second time.
|
|
1217
|
+
|
|
1218
|
+
:param reflection_options: When present, this dictionary of options
|
|
1219
|
+
will be passed to :meth:`_schema.MetaData.reflect`
|
|
1220
|
+
to supply general reflection-specific options like ``only`` and/or
|
|
1221
|
+
dialect-specific options like ``oracle_resolve_synonyms``.
|
|
1222
|
+
|
|
1223
|
+
.. versionadded:: 1.4
|
|
1224
|
+
|
|
1225
|
+
"""
|
|
1226
|
+
|
|
1227
|
+
for mr in cls.__mro__:
|
|
1228
|
+
if "_sa_automapbase_bookkeeping" in mr.__dict__:
|
|
1229
|
+
automap_base = cast("Type[AutomapBase]", mr)
|
|
1230
|
+
break
|
|
1231
|
+
else:
|
|
1232
|
+
assert False, "Can't locate automap base in class hierarchy"
|
|
1233
|
+
|
|
1234
|
+
glbls = globals()
|
|
1235
|
+
if classname_for_table is None:
|
|
1236
|
+
classname_for_table = glbls["classname_for_table"]
|
|
1237
|
+
if name_for_scalar_relationship is None:
|
|
1238
|
+
name_for_scalar_relationship = glbls[
|
|
1239
|
+
"name_for_scalar_relationship"
|
|
1240
|
+
]
|
|
1241
|
+
if name_for_collection_relationship is None:
|
|
1242
|
+
name_for_collection_relationship = glbls[
|
|
1243
|
+
"name_for_collection_relationship"
|
|
1244
|
+
]
|
|
1245
|
+
if generate_relationship is None:
|
|
1246
|
+
generate_relationship = glbls["generate_relationship"]
|
|
1247
|
+
if collection_class is None:
|
|
1248
|
+
collection_class = list
|
|
1249
|
+
|
|
1250
|
+
if autoload_with:
|
|
1251
|
+
reflect = True
|
|
1252
|
+
|
|
1253
|
+
if engine:
|
|
1254
|
+
autoload_with = engine
|
|
1255
|
+
|
|
1256
|
+
if reflect:
|
|
1257
|
+
assert autoload_with
|
|
1258
|
+
opts = dict(
|
|
1259
|
+
schema=schema,
|
|
1260
|
+
extend_existing=True,
|
|
1261
|
+
autoload_replace=False,
|
|
1262
|
+
)
|
|
1263
|
+
if reflection_options:
|
|
1264
|
+
opts.update(reflection_options)
|
|
1265
|
+
cls.metadata.reflect(autoload_with, **opts) # type: ignore[arg-type] # noqa: E501
|
|
1266
|
+
|
|
1267
|
+
with _CONFIGURE_MUTEX:
|
|
1268
|
+
table_to_map_config: Union[
|
|
1269
|
+
Dict[Optional[Table], _DeferredMapperConfig],
|
|
1270
|
+
Dict[Table, _DeferredMapperConfig],
|
|
1271
|
+
] = {
|
|
1272
|
+
cast("Table", m.local_table): m
|
|
1273
|
+
for m in _DeferredMapperConfig.classes_for_base(
|
|
1274
|
+
cls, sort=False
|
|
1275
|
+
)
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
many_to_many: List[
|
|
1279
|
+
Tuple[Table, Table, List[ForeignKeyConstraint], Table]
|
|
1280
|
+
]
|
|
1281
|
+
many_to_many = []
|
|
1282
|
+
|
|
1283
|
+
bookkeeping = automap_base._sa_automapbase_bookkeeping
|
|
1284
|
+
metadata_tables = cls.metadata.tables
|
|
1285
|
+
|
|
1286
|
+
for table_key in set(metadata_tables).difference(
|
|
1287
|
+
bookkeeping.table_keys
|
|
1288
|
+
):
|
|
1289
|
+
table = metadata_tables[table_key]
|
|
1290
|
+
bookkeeping.table_keys.add(table_key)
|
|
1291
|
+
|
|
1292
|
+
lcl_m2m, rem_m2m, m2m_const = _is_many_to_many(cls, table)
|
|
1293
|
+
if lcl_m2m is not None:
|
|
1294
|
+
assert rem_m2m is not None
|
|
1295
|
+
assert m2m_const is not None
|
|
1296
|
+
many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table))
|
|
1297
|
+
elif not table.primary_key:
|
|
1298
|
+
continue
|
|
1299
|
+
elif table not in table_to_map_config:
|
|
1300
|
+
clsdict: Dict[str, Any] = {"__table__": table}
|
|
1301
|
+
if modulename_for_table is not None:
|
|
1302
|
+
new_module = modulename_for_table(
|
|
1303
|
+
cls, table.name, table
|
|
1304
|
+
)
|
|
1305
|
+
if new_module is not None:
|
|
1306
|
+
clsdict["__module__"] = new_module
|
|
1307
|
+
else:
|
|
1308
|
+
new_module = None
|
|
1309
|
+
|
|
1310
|
+
newname = classname_for_table(cls, table.name, table)
|
|
1311
|
+
if new_module is None and newname in cls.classes:
|
|
1312
|
+
util.warn(
|
|
1313
|
+
"Ignoring duplicate class name "
|
|
1314
|
+
f"'{newname}' "
|
|
1315
|
+
"received in automap base for table "
|
|
1316
|
+
f"{table.key} without "
|
|
1317
|
+
"``__module__`` being set; consider using the "
|
|
1318
|
+
"``modulename_for_table`` hook"
|
|
1319
|
+
)
|
|
1320
|
+
continue
|
|
1321
|
+
|
|
1322
|
+
mapped_cls = type(
|
|
1323
|
+
newname,
|
|
1324
|
+
(automap_base,),
|
|
1325
|
+
clsdict,
|
|
1326
|
+
)
|
|
1327
|
+
map_config = _DeferredMapperConfig.config_for_cls(
|
|
1328
|
+
mapped_cls
|
|
1329
|
+
)
|
|
1330
|
+
assert map_config.cls.__name__ == newname
|
|
1331
|
+
if new_module is None:
|
|
1332
|
+
cls.classes[newname] = mapped_cls
|
|
1333
|
+
|
|
1334
|
+
by_module_properties: ByModuleProperties = cls.by_module
|
|
1335
|
+
for token in map_config.cls.__module__.split("."):
|
|
1336
|
+
if token not in by_module_properties:
|
|
1337
|
+
by_module_properties[token] = util.Properties({})
|
|
1338
|
+
|
|
1339
|
+
props = by_module_properties[token]
|
|
1340
|
+
|
|
1341
|
+
# we can assert this because the clsregistry
|
|
1342
|
+
# module would have raised if there was a mismatch
|
|
1343
|
+
# between modules/classes already.
|
|
1344
|
+
# see test_cls_schema_name_conflict
|
|
1345
|
+
assert isinstance(props, Properties)
|
|
1346
|
+
by_module_properties = props
|
|
1347
|
+
|
|
1348
|
+
by_module_properties[map_config.cls.__name__] = mapped_cls
|
|
1349
|
+
|
|
1350
|
+
table_to_map_config[table] = map_config
|
|
1351
|
+
|
|
1352
|
+
for map_config in table_to_map_config.values():
|
|
1353
|
+
_relationships_for_fks(
|
|
1354
|
+
automap_base,
|
|
1355
|
+
map_config,
|
|
1356
|
+
table_to_map_config,
|
|
1357
|
+
collection_class,
|
|
1358
|
+
name_for_scalar_relationship,
|
|
1359
|
+
name_for_collection_relationship,
|
|
1360
|
+
generate_relationship,
|
|
1361
|
+
)
|
|
1362
|
+
|
|
1363
|
+
for lcl_m2m, rem_m2m, m2m_const, table in many_to_many:
|
|
1364
|
+
_m2m_relationship(
|
|
1365
|
+
automap_base,
|
|
1366
|
+
lcl_m2m,
|
|
1367
|
+
rem_m2m,
|
|
1368
|
+
m2m_const,
|
|
1369
|
+
table,
|
|
1370
|
+
table_to_map_config,
|
|
1371
|
+
collection_class,
|
|
1372
|
+
name_for_scalar_relationship,
|
|
1373
|
+
name_for_collection_relationship,
|
|
1374
|
+
generate_relationship,
|
|
1375
|
+
)
|
|
1376
|
+
|
|
1377
|
+
for map_config in _DeferredMapperConfig.classes_for_base(
|
|
1378
|
+
automap_base
|
|
1379
|
+
):
|
|
1380
|
+
map_config.map()
|
|
1381
|
+
|
|
1382
|
+
_sa_decl_prepare = True
|
|
1383
|
+
"""Indicate that the mapping of classes should be deferred.
|
|
1384
|
+
|
|
1385
|
+
The presence of this attribute name indicates to declarative
|
|
1386
|
+
that the call to mapper() should not occur immediately; instead,
|
|
1387
|
+
information about the table and attributes to be mapped are gathered
|
|
1388
|
+
into an internal structure called _DeferredMapperConfig. These
|
|
1389
|
+
objects can be collected later using classes_for_base(), additional
|
|
1390
|
+
mapping decisions can be made, and then the map() method will actually
|
|
1391
|
+
apply the mapping.
|
|
1392
|
+
|
|
1393
|
+
The only real reason this deferral of the whole
|
|
1394
|
+
thing is needed is to support primary key columns that aren't reflected
|
|
1395
|
+
yet when the class is declared; everything else can theoretically be
|
|
1396
|
+
added to the mapper later. However, the _DeferredMapperConfig is a
|
|
1397
|
+
nice interface in any case which exists at that not usually exposed point
|
|
1398
|
+
at which declarative has the class and the Table but hasn't called
|
|
1399
|
+
mapper() yet.
|
|
1400
|
+
|
|
1401
|
+
"""
|
|
1402
|
+
|
|
1403
|
+
@classmethod
|
|
1404
|
+
def _sa_raise_deferred_config(cls) -> NoReturn:
|
|
1405
|
+
raise orm_exc.UnmappedClassError(
|
|
1406
|
+
cls,
|
|
1407
|
+
msg="Class %s is a subclass of AutomapBase. "
|
|
1408
|
+
"Mappings are not produced until the .prepare() "
|
|
1409
|
+
"method is called on the class hierarchy."
|
|
1410
|
+
% orm_exc._safe_cls_name(cls),
|
|
1411
|
+
)
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
@dataclasses.dataclass
|
|
1415
|
+
class _Bookkeeping:
|
|
1416
|
+
__slots__ = ("table_keys",)
|
|
1417
|
+
|
|
1418
|
+
table_keys: Set[str]
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
def automap_base(
|
|
1422
|
+
declarative_base: Optional[Type[Any]] = None, **kw: Any
|
|
1423
|
+
) -> Any:
|
|
1424
|
+
r"""Produce a declarative automap base.
|
|
1425
|
+
|
|
1426
|
+
This function produces a new base class that is a product of the
|
|
1427
|
+
:class:`.AutomapBase` class as well a declarative base produced by
|
|
1428
|
+
:func:`.declarative.declarative_base`.
|
|
1429
|
+
|
|
1430
|
+
All parameters other than ``declarative_base`` are keyword arguments
|
|
1431
|
+
that are passed directly to the :func:`.declarative.declarative_base`
|
|
1432
|
+
function.
|
|
1433
|
+
|
|
1434
|
+
:param declarative_base: an existing class produced by
|
|
1435
|
+
:func:`.declarative.declarative_base`. When this is passed, the function
|
|
1436
|
+
no longer invokes :func:`.declarative.declarative_base` itself, and all
|
|
1437
|
+
other keyword arguments are ignored.
|
|
1438
|
+
|
|
1439
|
+
:param \**kw: keyword arguments are passed along to
|
|
1440
|
+
:func:`.declarative.declarative_base`.
|
|
1441
|
+
|
|
1442
|
+
"""
|
|
1443
|
+
if declarative_base is None:
|
|
1444
|
+
Base = _declarative_base(**kw)
|
|
1445
|
+
else:
|
|
1446
|
+
Base = declarative_base
|
|
1447
|
+
|
|
1448
|
+
return type(
|
|
1449
|
+
Base.__name__,
|
|
1450
|
+
(AutomapBase, Base),
|
|
1451
|
+
{
|
|
1452
|
+
"__abstract__": True,
|
|
1453
|
+
"classes": util.Properties({}),
|
|
1454
|
+
"by_module": util.Properties({}),
|
|
1455
|
+
"_sa_automapbase_bookkeeping": _Bookkeeping(set()),
|
|
1456
|
+
},
|
|
1457
|
+
)
|
|
1458
|
+
|
|
1459
|
+
|
|
1460
|
+
def _is_many_to_many(
|
|
1461
|
+
automap_base: Type[Any], table: Table
|
|
1462
|
+
) -> Tuple[
|
|
1463
|
+
Optional[Table], Optional[Table], Optional[list[ForeignKeyConstraint]]
|
|
1464
|
+
]:
|
|
1465
|
+
fk_constraints = [
|
|
1466
|
+
const
|
|
1467
|
+
for const in table.constraints
|
|
1468
|
+
if isinstance(const, ForeignKeyConstraint)
|
|
1469
|
+
]
|
|
1470
|
+
if len(fk_constraints) != 2:
|
|
1471
|
+
return None, None, None
|
|
1472
|
+
|
|
1473
|
+
cols: List[Column[Any]] = sum(
|
|
1474
|
+
[
|
|
1475
|
+
[fk.parent for fk in fk_constraint.elements]
|
|
1476
|
+
for fk_constraint in fk_constraints
|
|
1477
|
+
],
|
|
1478
|
+
[],
|
|
1479
|
+
)
|
|
1480
|
+
|
|
1481
|
+
if set(cols) != set(table.c):
|
|
1482
|
+
return None, None, None
|
|
1483
|
+
|
|
1484
|
+
return (
|
|
1485
|
+
fk_constraints[0].elements[0].column.table,
|
|
1486
|
+
fk_constraints[1].elements[0].column.table,
|
|
1487
|
+
fk_constraints,
|
|
1488
|
+
)
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _relationships_for_fks(
|
|
1492
|
+
automap_base: Type[Any],
|
|
1493
|
+
map_config: _DeferredMapperConfig,
|
|
1494
|
+
table_to_map_config: Union[
|
|
1495
|
+
Dict[Optional[Table], _DeferredMapperConfig],
|
|
1496
|
+
Dict[Table, _DeferredMapperConfig],
|
|
1497
|
+
],
|
|
1498
|
+
collection_class: type,
|
|
1499
|
+
name_for_scalar_relationship: NameForScalarRelationshipType,
|
|
1500
|
+
name_for_collection_relationship: NameForCollectionRelationshipType,
|
|
1501
|
+
generate_relationship: GenerateRelationshipType,
|
|
1502
|
+
) -> None:
|
|
1503
|
+
local_table = cast("Optional[Table]", map_config.local_table)
|
|
1504
|
+
local_cls = cast(
|
|
1505
|
+
"Optional[Type[Any]]", map_config.cls
|
|
1506
|
+
) # derived from a weakref, may be None
|
|
1507
|
+
|
|
1508
|
+
if local_table is None or local_cls is None:
|
|
1509
|
+
return
|
|
1510
|
+
for constraint in local_table.constraints:
|
|
1511
|
+
if isinstance(constraint, ForeignKeyConstraint):
|
|
1512
|
+
fks = constraint.elements
|
|
1513
|
+
referred_table = fks[0].column.table
|
|
1514
|
+
referred_cfg = table_to_map_config.get(referred_table, None)
|
|
1515
|
+
if referred_cfg is None:
|
|
1516
|
+
continue
|
|
1517
|
+
referred_cls = referred_cfg.cls
|
|
1518
|
+
|
|
1519
|
+
if local_cls is not referred_cls and issubclass(
|
|
1520
|
+
local_cls, referred_cls
|
|
1521
|
+
):
|
|
1522
|
+
continue
|
|
1523
|
+
|
|
1524
|
+
relationship_name = name_for_scalar_relationship(
|
|
1525
|
+
automap_base, local_cls, referred_cls, constraint
|
|
1526
|
+
)
|
|
1527
|
+
backref_name = name_for_collection_relationship(
|
|
1528
|
+
automap_base, referred_cls, local_cls, constraint
|
|
1529
|
+
)
|
|
1530
|
+
|
|
1531
|
+
o2m_kws: Dict[str, Union[str, bool]] = {}
|
|
1532
|
+
nullable = False not in {fk.parent.nullable for fk in fks}
|
|
1533
|
+
if not nullable:
|
|
1534
|
+
o2m_kws["cascade"] = "all, delete-orphan"
|
|
1535
|
+
|
|
1536
|
+
if (
|
|
1537
|
+
constraint.ondelete
|
|
1538
|
+
and constraint.ondelete.lower() == "cascade"
|
|
1539
|
+
):
|
|
1540
|
+
o2m_kws["passive_deletes"] = True
|
|
1541
|
+
else:
|
|
1542
|
+
if (
|
|
1543
|
+
constraint.ondelete
|
|
1544
|
+
and constraint.ondelete.lower() == "set null"
|
|
1545
|
+
):
|
|
1546
|
+
o2m_kws["passive_deletes"] = True
|
|
1547
|
+
|
|
1548
|
+
create_backref = backref_name not in referred_cfg.properties
|
|
1549
|
+
|
|
1550
|
+
if relationship_name not in map_config.properties:
|
|
1551
|
+
if create_backref:
|
|
1552
|
+
backref_obj = generate_relationship(
|
|
1553
|
+
automap_base,
|
|
1554
|
+
interfaces.ONETOMANY,
|
|
1555
|
+
backref,
|
|
1556
|
+
backref_name,
|
|
1557
|
+
referred_cls,
|
|
1558
|
+
local_cls,
|
|
1559
|
+
collection_class=collection_class,
|
|
1560
|
+
**o2m_kws,
|
|
1561
|
+
)
|
|
1562
|
+
else:
|
|
1563
|
+
backref_obj = None
|
|
1564
|
+
rel = generate_relationship(
|
|
1565
|
+
automap_base,
|
|
1566
|
+
interfaces.MANYTOONE,
|
|
1567
|
+
relationship,
|
|
1568
|
+
relationship_name,
|
|
1569
|
+
local_cls,
|
|
1570
|
+
referred_cls,
|
|
1571
|
+
foreign_keys=[fk.parent for fk in constraint.elements],
|
|
1572
|
+
backref=backref_obj,
|
|
1573
|
+
remote_side=[fk.column for fk in constraint.elements],
|
|
1574
|
+
)
|
|
1575
|
+
if rel is not None:
|
|
1576
|
+
map_config.properties[relationship_name] = rel
|
|
1577
|
+
if not create_backref:
|
|
1578
|
+
referred_cfg.properties[
|
|
1579
|
+
backref_name
|
|
1580
|
+
].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501
|
|
1581
|
+
elif create_backref:
|
|
1582
|
+
rel = generate_relationship(
|
|
1583
|
+
automap_base,
|
|
1584
|
+
interfaces.ONETOMANY,
|
|
1585
|
+
relationship,
|
|
1586
|
+
backref_name,
|
|
1587
|
+
referred_cls,
|
|
1588
|
+
local_cls,
|
|
1589
|
+
foreign_keys=[fk.parent for fk in constraint.elements],
|
|
1590
|
+
back_populates=relationship_name,
|
|
1591
|
+
collection_class=collection_class,
|
|
1592
|
+
**o2m_kws,
|
|
1593
|
+
)
|
|
1594
|
+
if rel is not None:
|
|
1595
|
+
referred_cfg.properties[backref_name] = rel
|
|
1596
|
+
map_config.properties[
|
|
1597
|
+
relationship_name
|
|
1598
|
+
].back_populates = backref_name # type: ignore[union-attr]
|
|
1599
|
+
|
|
1600
|
+
|
|
1601
|
+
def _m2m_relationship(
|
|
1602
|
+
automap_base: Type[Any],
|
|
1603
|
+
lcl_m2m: Table,
|
|
1604
|
+
rem_m2m: Table,
|
|
1605
|
+
m2m_const: List[ForeignKeyConstraint],
|
|
1606
|
+
table: Table,
|
|
1607
|
+
table_to_map_config: Union[
|
|
1608
|
+
Dict[Optional[Table], _DeferredMapperConfig],
|
|
1609
|
+
Dict[Table, _DeferredMapperConfig],
|
|
1610
|
+
],
|
|
1611
|
+
collection_class: type,
|
|
1612
|
+
name_for_scalar_relationship: NameForCollectionRelationshipType,
|
|
1613
|
+
name_for_collection_relationship: NameForCollectionRelationshipType,
|
|
1614
|
+
generate_relationship: GenerateRelationshipType,
|
|
1615
|
+
) -> None:
|
|
1616
|
+
map_config = table_to_map_config.get(lcl_m2m, None)
|
|
1617
|
+
referred_cfg = table_to_map_config.get(rem_m2m, None)
|
|
1618
|
+
if map_config is None or referred_cfg is None:
|
|
1619
|
+
return
|
|
1620
|
+
|
|
1621
|
+
local_cls = map_config.cls
|
|
1622
|
+
referred_cls = referred_cfg.cls
|
|
1623
|
+
|
|
1624
|
+
relationship_name = name_for_collection_relationship(
|
|
1625
|
+
automap_base, local_cls, referred_cls, m2m_const[0]
|
|
1626
|
+
)
|
|
1627
|
+
backref_name = name_for_collection_relationship(
|
|
1628
|
+
automap_base, referred_cls, local_cls, m2m_const[1]
|
|
1629
|
+
)
|
|
1630
|
+
|
|
1631
|
+
create_backref = backref_name not in referred_cfg.properties
|
|
1632
|
+
|
|
1633
|
+
if table in table_to_map_config:
|
|
1634
|
+
overlaps = "__*"
|
|
1635
|
+
else:
|
|
1636
|
+
overlaps = None
|
|
1637
|
+
|
|
1638
|
+
if relationship_name not in map_config.properties:
|
|
1639
|
+
if create_backref:
|
|
1640
|
+
backref_obj = generate_relationship(
|
|
1641
|
+
automap_base,
|
|
1642
|
+
interfaces.MANYTOMANY,
|
|
1643
|
+
backref,
|
|
1644
|
+
backref_name,
|
|
1645
|
+
referred_cls,
|
|
1646
|
+
local_cls,
|
|
1647
|
+
collection_class=collection_class,
|
|
1648
|
+
overlaps=overlaps,
|
|
1649
|
+
)
|
|
1650
|
+
else:
|
|
1651
|
+
backref_obj = None
|
|
1652
|
+
|
|
1653
|
+
rel = generate_relationship(
|
|
1654
|
+
automap_base,
|
|
1655
|
+
interfaces.MANYTOMANY,
|
|
1656
|
+
relationship,
|
|
1657
|
+
relationship_name,
|
|
1658
|
+
local_cls,
|
|
1659
|
+
referred_cls,
|
|
1660
|
+
overlaps=overlaps,
|
|
1661
|
+
secondary=table,
|
|
1662
|
+
primaryjoin=and_(
|
|
1663
|
+
fk.column == fk.parent for fk in m2m_const[0].elements
|
|
1664
|
+
), # type: ignore [arg-type]
|
|
1665
|
+
secondaryjoin=and_(
|
|
1666
|
+
fk.column == fk.parent for fk in m2m_const[1].elements
|
|
1667
|
+
), # type: ignore [arg-type]
|
|
1668
|
+
backref=backref_obj,
|
|
1669
|
+
collection_class=collection_class,
|
|
1670
|
+
)
|
|
1671
|
+
if rel is not None:
|
|
1672
|
+
map_config.properties[relationship_name] = rel
|
|
1673
|
+
|
|
1674
|
+
if not create_backref:
|
|
1675
|
+
referred_cfg.properties[
|
|
1676
|
+
backref_name
|
|
1677
|
+
].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501
|
|
1678
|
+
elif create_backref:
|
|
1679
|
+
rel = generate_relationship(
|
|
1680
|
+
automap_base,
|
|
1681
|
+
interfaces.MANYTOMANY,
|
|
1682
|
+
relationship,
|
|
1683
|
+
backref_name,
|
|
1684
|
+
referred_cls,
|
|
1685
|
+
local_cls,
|
|
1686
|
+
overlaps=overlaps,
|
|
1687
|
+
secondary=table,
|
|
1688
|
+
primaryjoin=and_(
|
|
1689
|
+
fk.column == fk.parent for fk in m2m_const[1].elements
|
|
1690
|
+
), # type: ignore [arg-type]
|
|
1691
|
+
secondaryjoin=and_(
|
|
1692
|
+
fk.column == fk.parent for fk in m2m_const[0].elements
|
|
1693
|
+
), # type: ignore [arg-type]
|
|
1694
|
+
back_populates=relationship_name,
|
|
1695
|
+
collection_class=collection_class,
|
|
1696
|
+
)
|
|
1697
|
+
if rel is not None:
|
|
1698
|
+
referred_cfg.properties[backref_name] = rel
|
|
1699
|
+
map_config.properties[
|
|
1700
|
+
relationship_name
|
|
1701
|
+
].back_populates = backref_name # type: ignore[union-attr]
|