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.
Files changed (274) hide show
  1. sqlalchemy/__init__.py +283 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +184 -0
  4. sqlalchemy/connectors/asyncio.py +429 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/cyextension/__init__.py +6 -0
  7. sqlalchemy/cyextension/collections.cp313t-win32.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win32.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win32.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win32.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win32.pyd +0 -0
  17. sqlalchemy/cyextension/util.pyx +90 -0
  18. sqlalchemy/dialects/__init__.py +62 -0
  19. sqlalchemy/dialects/_typing.py +30 -0
  20. sqlalchemy/dialects/mssql/__init__.py +88 -0
  21. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  22. sqlalchemy/dialects/mssql/base.py +4093 -0
  23. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  24. sqlalchemy/dialects/mssql/json.py +129 -0
  25. sqlalchemy/dialects/mssql/provision.py +185 -0
  26. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  27. sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  28. sqlalchemy/dialects/mysql/__init__.py +104 -0
  29. sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  30. sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  31. sqlalchemy/dialects/mysql/base.py +3949 -0
  32. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  33. sqlalchemy/dialects/mysql/dml.py +225 -0
  34. sqlalchemy/dialects/mysql/enumerated.py +282 -0
  35. sqlalchemy/dialects/mysql/expression.py +146 -0
  36. sqlalchemy/dialects/mysql/json.py +91 -0
  37. sqlalchemy/dialects/mysql/mariadb.py +72 -0
  38. sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  39. sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  40. sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  41. sqlalchemy/dialects/mysql/provision.py +153 -0
  42. sqlalchemy/dialects/mysql/pymysql.py +158 -0
  43. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  44. sqlalchemy/dialects/mysql/reflection.py +727 -0
  45. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  46. sqlalchemy/dialects/mysql/types.py +835 -0
  47. sqlalchemy/dialects/oracle/__init__.py +81 -0
  48. sqlalchemy/dialects/oracle/base.py +3802 -0
  49. sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
  50. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  51. sqlalchemy/dialects/oracle/oracledb.py +941 -0
  52. sqlalchemy/dialects/oracle/provision.py +297 -0
  53. sqlalchemy/dialects/oracle/types.py +316 -0
  54. sqlalchemy/dialects/oracle/vector.py +365 -0
  55. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  56. sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
  57. sqlalchemy/dialects/postgresql/array.py +519 -0
  58. sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
  59. sqlalchemy/dialects/postgresql/base.py +5378 -0
  60. sqlalchemy/dialects/postgresql/dml.py +339 -0
  61. sqlalchemy/dialects/postgresql/ext.py +540 -0
  62. sqlalchemy/dialects/postgresql/hstore.py +406 -0
  63. sqlalchemy/dialects/postgresql/json.py +404 -0
  64. sqlalchemy/dialects/postgresql/named_types.py +524 -0
  65. sqlalchemy/dialects/postgresql/operators.py +129 -0
  66. sqlalchemy/dialects/postgresql/pg8000.py +669 -0
  67. sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
  68. sqlalchemy/dialects/postgresql/provision.py +183 -0
  69. sqlalchemy/dialects/postgresql/psycopg.py +862 -0
  70. sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
  71. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  72. sqlalchemy/dialects/postgresql/ranges.py +1031 -0
  73. sqlalchemy/dialects/postgresql/types.py +313 -0
  74. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  75. sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
  76. sqlalchemy/dialects/sqlite/base.py +3056 -0
  77. sqlalchemy/dialects/sqlite/dml.py +263 -0
  78. sqlalchemy/dialects/sqlite/json.py +92 -0
  79. sqlalchemy/dialects/sqlite/provision.py +229 -0
  80. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  81. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  82. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  83. sqlalchemy/engine/__init__.py +62 -0
  84. sqlalchemy/engine/_py_processors.py +136 -0
  85. sqlalchemy/engine/_py_row.py +128 -0
  86. sqlalchemy/engine/_py_util.py +74 -0
  87. sqlalchemy/engine/base.py +3390 -0
  88. sqlalchemy/engine/characteristics.py +155 -0
  89. sqlalchemy/engine/create.py +893 -0
  90. sqlalchemy/engine/cursor.py +2298 -0
  91. sqlalchemy/engine/default.py +2394 -0
  92. sqlalchemy/engine/events.py +965 -0
  93. sqlalchemy/engine/interfaces.py +3471 -0
  94. sqlalchemy/engine/mock.py +134 -0
  95. sqlalchemy/engine/processors.py +61 -0
  96. sqlalchemy/engine/reflection.py +2102 -0
  97. sqlalchemy/engine/result.py +2399 -0
  98. sqlalchemy/engine/row.py +400 -0
  99. sqlalchemy/engine/strategies.py +16 -0
  100. sqlalchemy/engine/url.py +924 -0
  101. sqlalchemy/engine/util.py +167 -0
  102. sqlalchemy/event/__init__.py +26 -0
  103. sqlalchemy/event/api.py +220 -0
  104. sqlalchemy/event/attr.py +676 -0
  105. sqlalchemy/event/base.py +472 -0
  106. sqlalchemy/event/legacy.py +258 -0
  107. sqlalchemy/event/registry.py +390 -0
  108. sqlalchemy/events.py +17 -0
  109. sqlalchemy/exc.py +832 -0
  110. sqlalchemy/ext/__init__.py +11 -0
  111. sqlalchemy/ext/associationproxy.py +2027 -0
  112. sqlalchemy/ext/asyncio/__init__.py +25 -0
  113. sqlalchemy/ext/asyncio/base.py +281 -0
  114. sqlalchemy/ext/asyncio/engine.py +1471 -0
  115. sqlalchemy/ext/asyncio/exc.py +21 -0
  116. sqlalchemy/ext/asyncio/result.py +965 -0
  117. sqlalchemy/ext/asyncio/scoping.py +1599 -0
  118. sqlalchemy/ext/asyncio/session.py +1947 -0
  119. sqlalchemy/ext/automap.py +1701 -0
  120. sqlalchemy/ext/baked.py +570 -0
  121. sqlalchemy/ext/compiler.py +600 -0
  122. sqlalchemy/ext/declarative/__init__.py +65 -0
  123. sqlalchemy/ext/declarative/extensions.py +564 -0
  124. sqlalchemy/ext/horizontal_shard.py +478 -0
  125. sqlalchemy/ext/hybrid.py +1535 -0
  126. sqlalchemy/ext/indexable.py +364 -0
  127. sqlalchemy/ext/instrumentation.py +450 -0
  128. sqlalchemy/ext/mutable.py +1085 -0
  129. sqlalchemy/ext/mypy/__init__.py +6 -0
  130. sqlalchemy/ext/mypy/apply.py +324 -0
  131. sqlalchemy/ext/mypy/decl_class.py +515 -0
  132. sqlalchemy/ext/mypy/infer.py +590 -0
  133. sqlalchemy/ext/mypy/names.py +335 -0
  134. sqlalchemy/ext/mypy/plugin.py +303 -0
  135. sqlalchemy/ext/mypy/util.py +357 -0
  136. sqlalchemy/ext/orderinglist.py +439 -0
  137. sqlalchemy/ext/serializer.py +185 -0
  138. sqlalchemy/future/__init__.py +16 -0
  139. sqlalchemy/future/engine.py +15 -0
  140. sqlalchemy/inspection.py +174 -0
  141. sqlalchemy/log.py +288 -0
  142. sqlalchemy/orm/__init__.py +171 -0
  143. sqlalchemy/orm/_orm_constructors.py +2661 -0
  144. sqlalchemy/orm/_typing.py +179 -0
  145. sqlalchemy/orm/attributes.py +2845 -0
  146. sqlalchemy/orm/base.py +971 -0
  147. sqlalchemy/orm/bulk_persistence.py +2135 -0
  148. sqlalchemy/orm/clsregistry.py +571 -0
  149. sqlalchemy/orm/collections.py +1627 -0
  150. sqlalchemy/orm/context.py +3334 -0
  151. sqlalchemy/orm/decl_api.py +2004 -0
  152. sqlalchemy/orm/decl_base.py +2192 -0
  153. sqlalchemy/orm/dependency.py +1302 -0
  154. sqlalchemy/orm/descriptor_props.py +1092 -0
  155. sqlalchemy/orm/dynamic.py +300 -0
  156. sqlalchemy/orm/evaluator.py +379 -0
  157. sqlalchemy/orm/events.py +3252 -0
  158. sqlalchemy/orm/exc.py +237 -0
  159. sqlalchemy/orm/identity.py +302 -0
  160. sqlalchemy/orm/instrumentation.py +754 -0
  161. sqlalchemy/orm/interfaces.py +1496 -0
  162. sqlalchemy/orm/loading.py +1686 -0
  163. sqlalchemy/orm/mapped_collection.py +557 -0
  164. sqlalchemy/orm/mapper.py +4444 -0
  165. sqlalchemy/orm/path_registry.py +809 -0
  166. sqlalchemy/orm/persistence.py +1788 -0
  167. sqlalchemy/orm/properties.py +935 -0
  168. sqlalchemy/orm/query.py +3459 -0
  169. sqlalchemy/orm/relationships.py +3508 -0
  170. sqlalchemy/orm/scoping.py +2148 -0
  171. sqlalchemy/orm/session.py +5280 -0
  172. sqlalchemy/orm/state.py +1168 -0
  173. sqlalchemy/orm/state_changes.py +196 -0
  174. sqlalchemy/orm/strategies.py +3470 -0
  175. sqlalchemy/orm/strategy_options.py +2568 -0
  176. sqlalchemy/orm/sync.py +164 -0
  177. sqlalchemy/orm/unitofwork.py +796 -0
  178. sqlalchemy/orm/util.py +2403 -0
  179. sqlalchemy/orm/writeonly.py +674 -0
  180. sqlalchemy/pool/__init__.py +44 -0
  181. sqlalchemy/pool/base.py +1524 -0
  182. sqlalchemy/pool/events.py +375 -0
  183. sqlalchemy/pool/impl.py +588 -0
  184. sqlalchemy/py.typed +0 -0
  185. sqlalchemy/schema.py +69 -0
  186. sqlalchemy/sql/__init__.py +145 -0
  187. sqlalchemy/sql/_dml_constructors.py +132 -0
  188. sqlalchemy/sql/_elements_constructors.py +1872 -0
  189. sqlalchemy/sql/_orm_types.py +20 -0
  190. sqlalchemy/sql/_py_util.py +75 -0
  191. sqlalchemy/sql/_selectable_constructors.py +763 -0
  192. sqlalchemy/sql/_typing.py +482 -0
  193. sqlalchemy/sql/annotation.py +587 -0
  194. sqlalchemy/sql/base.py +2293 -0
  195. sqlalchemy/sql/cache_key.py +1057 -0
  196. sqlalchemy/sql/coercions.py +1404 -0
  197. sqlalchemy/sql/compiler.py +8081 -0
  198. sqlalchemy/sql/crud.py +1752 -0
  199. sqlalchemy/sql/ddl.py +1444 -0
  200. sqlalchemy/sql/default_comparator.py +551 -0
  201. sqlalchemy/sql/dml.py +1850 -0
  202. sqlalchemy/sql/elements.py +5589 -0
  203. sqlalchemy/sql/events.py +458 -0
  204. sqlalchemy/sql/expression.py +159 -0
  205. sqlalchemy/sql/functions.py +2158 -0
  206. sqlalchemy/sql/lambdas.py +1442 -0
  207. sqlalchemy/sql/naming.py +209 -0
  208. sqlalchemy/sql/operators.py +2623 -0
  209. sqlalchemy/sql/roles.py +323 -0
  210. sqlalchemy/sql/schema.py +6222 -0
  211. sqlalchemy/sql/selectable.py +7265 -0
  212. sqlalchemy/sql/sqltypes.py +3930 -0
  213. sqlalchemy/sql/traversals.py +1024 -0
  214. sqlalchemy/sql/type_api.py +2368 -0
  215. sqlalchemy/sql/util.py +1485 -0
  216. sqlalchemy/sql/visitors.py +1164 -0
  217. sqlalchemy/testing/__init__.py +96 -0
  218. sqlalchemy/testing/assertions.py +994 -0
  219. sqlalchemy/testing/assertsql.py +520 -0
  220. sqlalchemy/testing/asyncio.py +135 -0
  221. sqlalchemy/testing/config.py +434 -0
  222. sqlalchemy/testing/engines.py +483 -0
  223. sqlalchemy/testing/entities.py +117 -0
  224. sqlalchemy/testing/exclusions.py +476 -0
  225. sqlalchemy/testing/fixtures/__init__.py +28 -0
  226. sqlalchemy/testing/fixtures/base.py +384 -0
  227. sqlalchemy/testing/fixtures/mypy.py +332 -0
  228. sqlalchemy/testing/fixtures/orm.py +227 -0
  229. sqlalchemy/testing/fixtures/sql.py +482 -0
  230. sqlalchemy/testing/pickleable.py +155 -0
  231. sqlalchemy/testing/plugin/__init__.py +6 -0
  232. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  233. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  234. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  235. sqlalchemy/testing/profiling.py +329 -0
  236. sqlalchemy/testing/provision.py +603 -0
  237. sqlalchemy/testing/requirements.py +1945 -0
  238. sqlalchemy/testing/schema.py +198 -0
  239. sqlalchemy/testing/suite/__init__.py +19 -0
  240. sqlalchemy/testing/suite/test_cte.py +237 -0
  241. sqlalchemy/testing/suite/test_ddl.py +389 -0
  242. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  243. sqlalchemy/testing/suite/test_dialect.py +776 -0
  244. sqlalchemy/testing/suite/test_insert.py +630 -0
  245. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  246. sqlalchemy/testing/suite/test_results.py +504 -0
  247. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  248. sqlalchemy/testing/suite/test_select.py +2010 -0
  249. sqlalchemy/testing/suite/test_sequence.py +317 -0
  250. sqlalchemy/testing/suite/test_types.py +2147 -0
  251. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  252. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  253. sqlalchemy/testing/util.py +535 -0
  254. sqlalchemy/testing/warnings.py +52 -0
  255. sqlalchemy/types.py +74 -0
  256. sqlalchemy/util/__init__.py +162 -0
  257. sqlalchemy/util/_collections.py +712 -0
  258. sqlalchemy/util/_concurrency_py3k.py +288 -0
  259. sqlalchemy/util/_has_cy.py +40 -0
  260. sqlalchemy/util/_py_collections.py +541 -0
  261. sqlalchemy/util/compat.py +421 -0
  262. sqlalchemy/util/concurrency.py +110 -0
  263. sqlalchemy/util/deprecations.py +401 -0
  264. sqlalchemy/util/langhelpers.py +2203 -0
  265. sqlalchemy/util/preloaded.py +150 -0
  266. sqlalchemy/util/queue.py +322 -0
  267. sqlalchemy/util/tool_support.py +201 -0
  268. sqlalchemy/util/topological.py +120 -0
  269. sqlalchemy/util/typing.py +734 -0
  270. sqlalchemy-2.0.47.dist-info/METADATA +243 -0
  271. sqlalchemy-2.0.47.dist-info/RECORD +274 -0
  272. sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
  273. sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
  274. sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
@@ -0,0 +1,439 @@
1
+ # ext/orderinglist.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
+ """A custom list that manages index/position information for contained
9
+ elements.
10
+
11
+ :author: Jason Kirtland
12
+
13
+ ``orderinglist`` is a helper for mutable ordered relationships. It will
14
+ intercept list operations performed on a :func:`_orm.relationship`-managed
15
+ collection and
16
+ automatically synchronize changes in list position onto a target scalar
17
+ attribute.
18
+
19
+ Example: A ``slide`` table, where each row refers to zero or more entries
20
+ in a related ``bullet`` table. The bullets within a slide are
21
+ displayed in order based on the value of the ``position`` column in the
22
+ ``bullet`` table. As entries are reordered in memory, the value of the
23
+ ``position`` attribute should be updated to reflect the new sort order::
24
+
25
+
26
+ Base = declarative_base()
27
+
28
+
29
+ class Slide(Base):
30
+ __tablename__ = "slide"
31
+
32
+ id = Column(Integer, primary_key=True)
33
+ name = Column(String)
34
+
35
+ bullets = relationship("Bullet", order_by="Bullet.position")
36
+
37
+
38
+ class Bullet(Base):
39
+ __tablename__ = "bullet"
40
+ id = Column(Integer, primary_key=True)
41
+ slide_id = Column(Integer, ForeignKey("slide.id"))
42
+ position = Column(Integer)
43
+ text = Column(String)
44
+
45
+ The standard relationship mapping will produce a list-like attribute on each
46
+ ``Slide`` containing all related ``Bullet`` objects,
47
+ but coping with changes in ordering is not handled automatically.
48
+ When appending a ``Bullet`` into ``Slide.bullets``, the ``Bullet.position``
49
+ attribute will remain unset until manually assigned. When the ``Bullet``
50
+ is inserted into the middle of the list, the following ``Bullet`` objects
51
+ will also need to be renumbered.
52
+
53
+ The :class:`.OrderingList` object automates this task, managing the
54
+ ``position`` attribute on all ``Bullet`` objects in the collection. It is
55
+ constructed using the :func:`.ordering_list` factory::
56
+
57
+ from sqlalchemy.ext.orderinglist import ordering_list
58
+
59
+ Base = declarative_base()
60
+
61
+
62
+ class Slide(Base):
63
+ __tablename__ = "slide"
64
+
65
+ id = Column(Integer, primary_key=True)
66
+ name = Column(String)
67
+
68
+ bullets = relationship(
69
+ "Bullet",
70
+ order_by="Bullet.position",
71
+ collection_class=ordering_list("position"),
72
+ )
73
+
74
+
75
+ class Bullet(Base):
76
+ __tablename__ = "bullet"
77
+ id = Column(Integer, primary_key=True)
78
+ slide_id = Column(Integer, ForeignKey("slide.id"))
79
+ position = Column(Integer)
80
+ text = Column(String)
81
+
82
+ With the above mapping the ``Bullet.position`` attribute is managed::
83
+
84
+ s = Slide()
85
+ s.bullets.append(Bullet())
86
+ s.bullets.append(Bullet())
87
+ s.bullets[1].position
88
+ >>> 1
89
+ s.bullets.insert(1, Bullet())
90
+ s.bullets[2].position
91
+ >>> 2
92
+
93
+ The :class:`.OrderingList` construct only works with **changes** to a
94
+ collection, and not the initial load from the database, and requires that the
95
+ list be sorted when loaded. Therefore, be sure to specify ``order_by`` on the
96
+ :func:`_orm.relationship` against the target ordering attribute, so that the
97
+ ordering is correct when first loaded.
98
+
99
+ .. warning::
100
+
101
+ :class:`.OrderingList` only provides limited functionality when a primary
102
+ key column or unique column is the target of the sort. Operations
103
+ that are unsupported or are problematic include:
104
+
105
+ * two entries must trade values. This is not supported directly in the
106
+ case of a primary key or unique constraint because it means at least
107
+ one row would need to be temporarily removed first, or changed to
108
+ a third, neutral value while the switch occurs.
109
+
110
+ * an entry must be deleted in order to make room for a new entry.
111
+ SQLAlchemy's unit of work performs all INSERTs before DELETEs within a
112
+ single flush. In the case of a primary key, it will trade
113
+ an INSERT/DELETE of the same primary key for an UPDATE statement in order
114
+ to lessen the impact of this limitation, however this does not take place
115
+ for a UNIQUE column.
116
+ A future feature will allow the "DELETE before INSERT" behavior to be
117
+ possible, alleviating this limitation, though this feature will require
118
+ explicit configuration at the mapper level for sets of columns that
119
+ are to be handled in this way.
120
+
121
+ :func:`.ordering_list` takes the name of the related object's ordering
122
+ attribute as an argument. By default, the zero-based integer index of the
123
+ object's position in the :func:`.ordering_list` is synchronized with the
124
+ ordering attribute: index 0 will get position 0, index 1 position 1, etc. To
125
+ start numbering at 1 or some other integer, provide ``count_from=1``.
126
+
127
+
128
+ """
129
+ from __future__ import annotations
130
+
131
+ from typing import Any
132
+ from typing import Callable
133
+ from typing import Dict
134
+ from typing import Iterable
135
+ from typing import List
136
+ from typing import Optional
137
+ from typing import overload
138
+ from typing import Sequence
139
+ from typing import Type
140
+ from typing import TypeVar
141
+ from typing import Union
142
+
143
+ from ..orm.collections import collection
144
+ from ..orm.collections import collection_adapter
145
+ from ..util.typing import SupportsIndex
146
+
147
+ _T = TypeVar("_T")
148
+ OrderingFunc = Callable[[int, Sequence[_T]], object]
149
+
150
+
151
+ __all__ = ["ordering_list"]
152
+
153
+
154
+ def ordering_list(
155
+ attr: str,
156
+ count_from: Optional[int] = None,
157
+ ordering_func: Optional[OrderingFunc[_T]] = None,
158
+ reorder_on_append: bool = False,
159
+ ) -> Callable[[], OrderingList[_T]]:
160
+ """Prepares an :class:`OrderingList` factory for use in mapper definitions.
161
+
162
+ Returns an object suitable for use as an argument to a Mapper
163
+ relationship's ``collection_class`` option. e.g.::
164
+
165
+ from sqlalchemy.ext.orderinglist import ordering_list
166
+
167
+
168
+ class Slide(Base):
169
+ __tablename__ = "slide"
170
+
171
+ id = Column(Integer, primary_key=True)
172
+ name = Column(String)
173
+
174
+ bullets = relationship(
175
+ "Bullet",
176
+ order_by="Bullet.position",
177
+ collection_class=ordering_list("position"),
178
+ )
179
+
180
+ :param attr:
181
+ Name of the mapped attribute to use for storage and retrieval of
182
+ ordering information
183
+
184
+ :param count_from:
185
+ Set up an integer-based ordering, starting at ``count_from``. For
186
+ example, ``ordering_list('pos', count_from=1)`` would create a 1-based
187
+ list in SQL, storing the value in the 'pos' column. Ignored if
188
+ ``ordering_func`` is supplied.
189
+
190
+ Additional arguments are passed to the :class:`.OrderingList` constructor.
191
+
192
+ """
193
+
194
+ kw = _unsugar_count_from(
195
+ count_from=count_from,
196
+ ordering_func=ordering_func,
197
+ reorder_on_append=reorder_on_append,
198
+ )
199
+ return lambda: OrderingList(attr, **kw)
200
+
201
+
202
+ # Ordering utility functions
203
+
204
+
205
+ def count_from_0(index: int, collection: object) -> int:
206
+ """Numbering function: consecutive integers starting at 0."""
207
+
208
+ return index
209
+
210
+
211
+ def count_from_1(index: int, collection: object) -> int:
212
+ """Numbering function: consecutive integers starting at 1."""
213
+
214
+ return index + 1
215
+
216
+
217
+ def count_from_n_factory(start: int) -> OrderingFunc[Any]:
218
+ """Numbering function: consecutive integers starting at arbitrary start."""
219
+
220
+ def f(index: int, collection: object) -> int:
221
+ return index + start
222
+
223
+ try:
224
+ f.__name__ = "count_from_%i" % start
225
+ except TypeError:
226
+ pass
227
+ return f
228
+
229
+
230
+ def _unsugar_count_from(**kw: Any) -> Dict[str, Any]:
231
+ """Builds counting functions from keyword arguments.
232
+
233
+ Keyword argument filter, prepares a simple ``ordering_func`` from a
234
+ ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged.
235
+ """
236
+
237
+ count_from = kw.pop("count_from", None)
238
+ if kw.get("ordering_func", None) is None and count_from is not None:
239
+ if count_from == 0:
240
+ kw["ordering_func"] = count_from_0
241
+ elif count_from == 1:
242
+ kw["ordering_func"] = count_from_1
243
+ else:
244
+ kw["ordering_func"] = count_from_n_factory(count_from)
245
+ return kw
246
+
247
+
248
+ class OrderingList(List[_T]):
249
+ """A custom list that manages position information for its children.
250
+
251
+ The :class:`.OrderingList` object is normally set up using the
252
+ :func:`.ordering_list` factory function, used in conjunction with
253
+ the :func:`_orm.relationship` function.
254
+
255
+ """
256
+
257
+ ordering_attr: str
258
+ ordering_func: OrderingFunc[_T]
259
+ reorder_on_append: bool
260
+
261
+ def __init__(
262
+ self,
263
+ ordering_attr: str,
264
+ ordering_func: Optional[OrderingFunc[_T]] = None,
265
+ reorder_on_append: bool = False,
266
+ ):
267
+ """A custom list that manages position information for its children.
268
+
269
+ ``OrderingList`` is a ``collection_class`` list implementation that
270
+ syncs position in a Python list with a position attribute on the
271
+ mapped objects.
272
+
273
+ This implementation relies on the list starting in the proper order,
274
+ so be **sure** to put an ``order_by`` on your relationship.
275
+
276
+ :param ordering_attr:
277
+ Name of the attribute that stores the object's order in the
278
+ relationship.
279
+
280
+ :param ordering_func: Optional. A function that maps the position in
281
+ the Python list to a value to store in the
282
+ ``ordering_attr``. Values returned are usually (but need not be!)
283
+ integers.
284
+
285
+ An ``ordering_func`` is called with two positional parameters: the
286
+ index of the element in the list, and the list itself.
287
+
288
+ If omitted, Python list indexes are used for the attribute values.
289
+ Two basic pre-built numbering functions are provided in this module:
290
+ ``count_from_0`` and ``count_from_1``. For more exotic examples
291
+ like stepped numbering, alphabetical and Fibonacci numbering, see
292
+ the unit tests.
293
+
294
+ :param reorder_on_append:
295
+ Default False. When appending an object with an existing (non-None)
296
+ ordering value, that value will be left untouched unless
297
+ ``reorder_on_append`` is true. This is an optimization to avoid a
298
+ variety of dangerous unexpected database writes.
299
+
300
+ SQLAlchemy will add instances to the list via append() when your
301
+ object loads. If for some reason the result set from the database
302
+ skips a step in the ordering (say, row '1' is missing but you get
303
+ '2', '3', and '4'), reorder_on_append=True would immediately
304
+ renumber the items to '1', '2', '3'. If you have multiple sessions
305
+ making changes, any of whom happen to load this collection even in
306
+ passing, all of the sessions would try to "clean up" the numbering
307
+ in their commits, possibly causing all but one to fail with a
308
+ concurrent modification error.
309
+
310
+ Recommend leaving this with the default of False, and just call
311
+ ``reorder()`` if you're doing ``append()`` operations with
312
+ previously ordered instances or when doing some housekeeping after
313
+ manual sql operations.
314
+
315
+ """
316
+ self.ordering_attr = ordering_attr
317
+ if ordering_func is None:
318
+ ordering_func = count_from_0
319
+ self.ordering_func = ordering_func
320
+ self.reorder_on_append = reorder_on_append
321
+
322
+ # More complex serialization schemes (multi column, e.g.) are possible by
323
+ # subclassing and reimplementing these two methods.
324
+ def _get_order_value(self, entity: _T) -> Any:
325
+ return getattr(entity, self.ordering_attr)
326
+
327
+ def _set_order_value(self, entity: _T, value: Any) -> None:
328
+ setattr(entity, self.ordering_attr, value)
329
+
330
+ def reorder(self) -> None:
331
+ """Synchronize ordering for the entire collection.
332
+
333
+ Sweeps through the list and ensures that each object has accurate
334
+ ordering information set.
335
+
336
+ """
337
+ for index, entity in enumerate(self):
338
+ self._order_entity(index, entity, True)
339
+
340
+ # As of 0.5, _reorder is no longer semi-private
341
+ _reorder = reorder
342
+
343
+ def _order_entity(
344
+ self, index: int, entity: _T, reorder: bool = True
345
+ ) -> None:
346
+ have = self._get_order_value(entity)
347
+
348
+ # Don't disturb existing ordering if reorder is False
349
+ if have is not None and not reorder:
350
+ return
351
+
352
+ should_be = self.ordering_func(index, self)
353
+ if have != should_be:
354
+ self._set_order_value(entity, should_be)
355
+
356
+ def append(self, entity: _T) -> None:
357
+ super().append(entity)
358
+ self._order_entity(len(self) - 1, entity, self.reorder_on_append)
359
+
360
+ def _raw_append(self, entity: _T) -> None:
361
+ """Append without any ordering behavior."""
362
+
363
+ super().append(entity)
364
+
365
+ _raw_append = collection.adds(1)(_raw_append)
366
+
367
+ def insert(self, index: SupportsIndex, entity: _T) -> None:
368
+ super().insert(index, entity)
369
+ self._reorder()
370
+
371
+ def remove(self, entity: _T) -> None:
372
+ super().remove(entity)
373
+
374
+ adapter = collection_adapter(self)
375
+ if adapter and adapter._referenced_by_owner:
376
+ self._reorder()
377
+
378
+ def pop(self, index: SupportsIndex = -1) -> _T:
379
+ entity = super().pop(index)
380
+ self._reorder()
381
+ return entity
382
+
383
+ @overload
384
+ def __setitem__(self, index: SupportsIndex, entity: _T) -> None: ...
385
+
386
+ @overload
387
+ def __setitem__(self, index: slice, entity: Iterable[_T]) -> None: ...
388
+
389
+ def __setitem__(
390
+ self,
391
+ index: Union[SupportsIndex, slice],
392
+ entity: Union[_T, Iterable[_T]],
393
+ ) -> None:
394
+ if isinstance(index, slice):
395
+ step = index.step or 1
396
+ start = index.start or 0
397
+ if start < 0:
398
+ start += len(self)
399
+ stop = index.stop or len(self)
400
+ if stop < 0:
401
+ stop += len(self)
402
+ entities = list(entity) # type: ignore[arg-type]
403
+ for i in range(start, stop, step):
404
+ self.__setitem__(i, entities[i])
405
+ else:
406
+ self._order_entity(int(index), entity, True) # type: ignore[arg-type] # noqa: E501
407
+ super().__setitem__(index, entity) # type: ignore[assignment]
408
+
409
+ def __delitem__(self, index: Union[SupportsIndex, slice]) -> None:
410
+ super().__delitem__(index)
411
+ self._reorder()
412
+
413
+ def __reduce__(self) -> Any:
414
+ return _reconstitute, (self.__class__, self.__dict__, list(self))
415
+
416
+ for func_name, func in list(locals().items()):
417
+ if (
418
+ callable(func)
419
+ and func.__name__ == func_name
420
+ and not func.__doc__
421
+ and hasattr(list, func_name)
422
+ ):
423
+ func.__doc__ = getattr(list, func_name).__doc__
424
+ del func_name, func
425
+
426
+
427
+ def _reconstitute(
428
+ cls: Type[OrderingList[_T]], dict_: Dict[str, Any], items: List[_T]
429
+ ) -> OrderingList[_T]:
430
+ """Reconstitute an :class:`.OrderingList`.
431
+
432
+ This is the adjoint to :meth:`.OrderingList.__reduce__`. It is used for
433
+ unpickling :class:`.OrderingList` objects.
434
+
435
+ """
436
+ obj = cls.__new__(cls)
437
+ obj.__dict__.update(dict_)
438
+ list.extend(obj, items)
439
+ return obj
@@ -0,0 +1,185 @@
1
+ # ext/serializer.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
+ # mypy: ignore-errors
8
+
9
+ """Serializer/Deserializer objects for usage with SQLAlchemy query structures,
10
+ allowing "contextual" deserialization.
11
+
12
+ .. legacy::
13
+
14
+ The serializer extension is **legacy** and should not be used for
15
+ new development.
16
+
17
+ Any SQLAlchemy query structure, either based on sqlalchemy.sql.*
18
+ or sqlalchemy.orm.* can be used. The mappers, Tables, Columns, Session
19
+ etc. which are referenced by the structure are not persisted in serialized
20
+ form, but are instead re-associated with the query structure
21
+ when it is deserialized.
22
+
23
+ .. warning:: The serializer extension uses pickle to serialize and
24
+ deserialize objects, so the same security consideration mentioned
25
+ in the `python documentation
26
+ <https://docs.python.org/3/library/pickle.html>`_ apply.
27
+
28
+ Usage is nearly the same as that of the standard Python pickle module::
29
+
30
+ from sqlalchemy.ext.serializer import loads, dumps
31
+
32
+ metadata = MetaData(bind=some_engine)
33
+ Session = scoped_session(sessionmaker())
34
+
35
+ # ... define mappers
36
+
37
+ query = (
38
+ Session.query(MyClass)
39
+ .filter(MyClass.somedata == "foo")
40
+ .order_by(MyClass.sortkey)
41
+ )
42
+
43
+ # pickle the query
44
+ serialized = dumps(query)
45
+
46
+ # unpickle. Pass in metadata + scoped_session
47
+ query2 = loads(serialized, metadata, Session)
48
+
49
+ print(query2.all())
50
+
51
+ Similar restrictions as when using raw pickle apply; mapped classes must be
52
+ themselves be pickleable, meaning they are importable from a module-level
53
+ namespace.
54
+
55
+ The serializer module is only appropriate for query structures. It is not
56
+ needed for:
57
+
58
+ * instances of user-defined classes. These contain no references to engines,
59
+ sessions or expression constructs in the typical case and can be serialized
60
+ directly.
61
+
62
+ * Table metadata that is to be loaded entirely from the serialized structure
63
+ (i.e. is not already declared in the application). Regular
64
+ pickle.loads()/dumps() can be used to fully dump any ``MetaData`` object,
65
+ typically one which was reflected from an existing database at some previous
66
+ point in time. The serializer module is specifically for the opposite case,
67
+ where the Table metadata is already present in memory.
68
+
69
+ """
70
+
71
+ from io import BytesIO
72
+ import pickle
73
+ import re
74
+
75
+ from .. import Column
76
+ from .. import Table
77
+ from ..engine import Engine
78
+ from ..orm import class_mapper
79
+ from ..orm.interfaces import MapperProperty
80
+ from ..orm.mapper import Mapper
81
+ from ..orm.session import Session
82
+ from ..util import b64decode
83
+ from ..util import b64encode
84
+
85
+
86
+ __all__ = ["Serializer", "Deserializer", "dumps", "loads"]
87
+
88
+
89
+ class Serializer(pickle.Pickler):
90
+
91
+ def persistent_id(self, obj):
92
+ # print "serializing:", repr(obj)
93
+ if isinstance(obj, Mapper) and not obj.non_primary:
94
+ id_ = "mapper:" + b64encode(pickle.dumps(obj.class_))
95
+ elif isinstance(obj, MapperProperty) and not obj.parent.non_primary:
96
+ id_ = (
97
+ "mapperprop:"
98
+ + b64encode(pickle.dumps(obj.parent.class_))
99
+ + ":"
100
+ + obj.key
101
+ )
102
+ elif isinstance(obj, Table):
103
+ if "parententity" in obj._annotations:
104
+ id_ = "mapper_selectable:" + b64encode(
105
+ pickle.dumps(obj._annotations["parententity"].class_)
106
+ )
107
+ else:
108
+ id_ = f"table:{obj.key}"
109
+ elif isinstance(obj, Column) and isinstance(obj.table, Table):
110
+ id_ = f"column:{obj.table.key}:{obj.key}"
111
+ elif isinstance(obj, Session):
112
+ id_ = "session:"
113
+ elif isinstance(obj, Engine):
114
+ id_ = "engine:"
115
+ else:
116
+ return None
117
+ return id_
118
+
119
+
120
+ our_ids = re.compile(
121
+ r"(mapperprop|mapper|mapper_selectable|table|column|"
122
+ r"session|attribute|engine):(.*)"
123
+ )
124
+
125
+
126
+ class Deserializer(pickle.Unpickler):
127
+
128
+ def __init__(self, file, metadata=None, scoped_session=None, engine=None):
129
+ super().__init__(file)
130
+ self.metadata = metadata
131
+ self.scoped_session = scoped_session
132
+ self.engine = engine
133
+
134
+ def get_engine(self):
135
+ if self.engine:
136
+ return self.engine
137
+ elif self.scoped_session and self.scoped_session().bind:
138
+ return self.scoped_session().bind
139
+ else:
140
+ return None
141
+
142
+ def persistent_load(self, id_):
143
+ m = our_ids.match(str(id_))
144
+ if not m:
145
+ return None
146
+ else:
147
+ type_, args = m.group(1, 2)
148
+ if type_ == "attribute":
149
+ key, clsarg = args.split(":")
150
+ cls = pickle.loads(b64decode(clsarg))
151
+ return getattr(cls, key)
152
+ elif type_ == "mapper":
153
+ cls = pickle.loads(b64decode(args))
154
+ return class_mapper(cls)
155
+ elif type_ == "mapper_selectable":
156
+ cls = pickle.loads(b64decode(args))
157
+ return class_mapper(cls).__clause_element__()
158
+ elif type_ == "mapperprop":
159
+ mapper, keyname = args.split(":")
160
+ cls = pickle.loads(b64decode(mapper))
161
+ return class_mapper(cls).attrs[keyname]
162
+ elif type_ == "table":
163
+ return self.metadata.tables[args]
164
+ elif type_ == "column":
165
+ table, colname = args.split(":")
166
+ return self.metadata.tables[table].c[colname]
167
+ elif type_ == "session":
168
+ return self.scoped_session()
169
+ elif type_ == "engine":
170
+ return self.get_engine()
171
+ else:
172
+ raise Exception("Unknown token: %s" % type_)
173
+
174
+
175
+ def dumps(obj, protocol=pickle.HIGHEST_PROTOCOL):
176
+ buf = BytesIO()
177
+ pickler = Serializer(buf, protocol)
178
+ pickler.dump(obj)
179
+ return buf.getvalue()
180
+
181
+
182
+ def loads(data, metadata=None, scoped_session=None, engine=None):
183
+ buf = BytesIO(data)
184
+ unpickler = Deserializer(buf, metadata, scoped_session, engine)
185
+ return unpickler.load()
@@ -0,0 +1,16 @@
1
+ # future/__init__.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
+ """2.0 API features.
9
+
10
+ this module is legacy as 2.0 APIs are now standard.
11
+
12
+ """
13
+ from .engine import Connection as Connection
14
+ from .engine import create_engine as create_engine
15
+ from .engine import Engine as Engine
16
+ from ..sql._selectable_constructors import select as select
@@ -0,0 +1,15 @@
1
+ # future/engine.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
+ """2.0 API features.
8
+
9
+ this module is legacy as 2.0 APIs are now standard.
10
+
11
+ """
12
+
13
+ from ..engine import Connection as Connection # noqa: F401
14
+ from ..engine import create_engine as create_engine # noqa: F401
15
+ from ..engine import Engine as Engine # noqa: F401