SQLAlchemy 2.1.0rc1__cp315-cp315-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win_arm64.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win_arm64.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win_arm64.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win_arm64.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,440 @@
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
+
130
+ from __future__ import annotations
131
+
132
+ from typing import Any
133
+ from typing import Callable
134
+ from typing import Dict
135
+ from typing import Iterable
136
+ from typing import List
137
+ from typing import Optional
138
+ from typing import overload
139
+ from typing import Sequence
140
+ from typing import SupportsIndex
141
+ from typing import Type
142
+ from typing import TypeVar
143
+ from typing import Union
144
+
145
+ from ..orm.collections import collection
146
+ from ..orm.collections import collection_adapter
147
+
148
+ _T = TypeVar("_T")
149
+ OrderingFunc = Callable[[int, Sequence[_T]], object]
150
+
151
+
152
+ __all__ = ["ordering_list"]
153
+
154
+
155
+ def ordering_list(
156
+ attr: str,
157
+ count_from: Optional[int] = None,
158
+ ordering_func: Optional[OrderingFunc[_T]] = None,
159
+ reorder_on_append: bool = False,
160
+ ) -> Callable[[], OrderingList[_T]]:
161
+ """Prepares an :class:`OrderingList` factory for use in mapper definitions.
162
+
163
+ Returns an object suitable for use as an argument to a Mapper
164
+ relationship's ``collection_class`` option. e.g.::
165
+
166
+ from sqlalchemy.ext.orderinglist import ordering_list
167
+
168
+
169
+ class Slide(Base):
170
+ __tablename__ = "slide"
171
+
172
+ id = Column(Integer, primary_key=True)
173
+ name = Column(String)
174
+
175
+ bullets = relationship(
176
+ "Bullet",
177
+ order_by="Bullet.position",
178
+ collection_class=ordering_list("position"),
179
+ )
180
+
181
+ :param attr:
182
+ Name of the mapped attribute to use for storage and retrieval of
183
+ ordering information
184
+
185
+ :param count_from:
186
+ Set up an integer-based ordering, starting at ``count_from``. For
187
+ example, ``ordering_list('pos', count_from=1)`` would create a 1-based
188
+ list in SQL, storing the value in the 'pos' column. Ignored if
189
+ ``ordering_func`` is supplied.
190
+
191
+ Additional arguments are passed to the :class:`.OrderingList` constructor.
192
+
193
+ """
194
+
195
+ kw = _unsugar_count_from(
196
+ count_from=count_from,
197
+ ordering_func=ordering_func,
198
+ reorder_on_append=reorder_on_append,
199
+ )
200
+ return lambda: OrderingList(attr, **kw)
201
+
202
+
203
+ # Ordering utility functions
204
+
205
+
206
+ def count_from_0(index: int, collection: object) -> int:
207
+ """Numbering function: consecutive integers starting at 0."""
208
+
209
+ return index
210
+
211
+
212
+ def count_from_1(index: int, collection: object) -> int:
213
+ """Numbering function: consecutive integers starting at 1."""
214
+
215
+ return index + 1
216
+
217
+
218
+ def count_from_n_factory(start: int) -> OrderingFunc[Any]:
219
+ """Numbering function: consecutive integers starting at arbitrary start."""
220
+
221
+ def f(index: int, collection: object) -> int:
222
+ return index + start
223
+
224
+ try:
225
+ f.__name__ = "count_from_%i" % start
226
+ except TypeError:
227
+ pass
228
+ return f
229
+
230
+
231
+ def _unsugar_count_from(**kw: Any) -> Dict[str, Any]:
232
+ """Builds counting functions from keyword arguments.
233
+
234
+ Keyword argument filter, prepares a simple ``ordering_func`` from a
235
+ ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged.
236
+ """
237
+
238
+ count_from = kw.pop("count_from", None)
239
+ if kw.get("ordering_func", None) is None and count_from is not None:
240
+ if count_from == 0:
241
+ kw["ordering_func"] = count_from_0
242
+ elif count_from == 1:
243
+ kw["ordering_func"] = count_from_1
244
+ else:
245
+ kw["ordering_func"] = count_from_n_factory(count_from)
246
+ return kw
247
+
248
+
249
+ class OrderingList(List[_T]):
250
+ """A custom list that manages position information for its children.
251
+
252
+ The :class:`.OrderingList` object is normally set up using the
253
+ :func:`.ordering_list` factory function, used in conjunction with
254
+ the :func:`_orm.relationship` function.
255
+
256
+ """
257
+
258
+ ordering_attr: str
259
+ ordering_func: OrderingFunc[_T]
260
+ reorder_on_append: bool
261
+
262
+ def __init__(
263
+ self,
264
+ ordering_attr: str,
265
+ ordering_func: Optional[OrderingFunc[_T]] = None,
266
+ reorder_on_append: bool = False,
267
+ ):
268
+ """A custom list that manages position information for its children.
269
+
270
+ ``OrderingList`` is a ``collection_class`` list implementation that
271
+ syncs position in a Python list with a position attribute on the
272
+ mapped objects.
273
+
274
+ This implementation relies on the list starting in the proper order,
275
+ so be **sure** to put an ``order_by`` on your relationship.
276
+
277
+ :param ordering_attr:
278
+ Name of the attribute that stores the object's order in the
279
+ relationship.
280
+
281
+ :param ordering_func: Optional. A function that maps the position in
282
+ the Python list to a value to store in the
283
+ ``ordering_attr``. Values returned are usually (but need not be!)
284
+ integers.
285
+
286
+ An ``ordering_func`` is called with two positional parameters: the
287
+ index of the element in the list, and the list itself.
288
+
289
+ If omitted, Python list indexes are used for the attribute values.
290
+ Two basic pre-built numbering functions are provided in this module:
291
+ ``count_from_0`` and ``count_from_1``. For more exotic examples
292
+ like stepped numbering, alphabetical and Fibonacci numbering, see
293
+ the unit tests.
294
+
295
+ :param reorder_on_append:
296
+ Default False. When appending an object with an existing (non-None)
297
+ ordering value, that value will be left untouched unless
298
+ ``reorder_on_append`` is true. This is an optimization to avoid a
299
+ variety of dangerous unexpected database writes.
300
+
301
+ SQLAlchemy will add instances to the list via append() when your
302
+ object loads. If for some reason the result set from the database
303
+ skips a step in the ordering (say, row '1' is missing but you get
304
+ '2', '3', and '4'), reorder_on_append=True would immediately
305
+ renumber the items to '1', '2', '3'. If you have multiple sessions
306
+ making changes, any of whom happen to load this collection even in
307
+ passing, all of the sessions would try to "clean up" the numbering
308
+ in their commits, possibly causing all but one to fail with a
309
+ concurrent modification error.
310
+
311
+ Recommend leaving this with the default of False, and just call
312
+ ``reorder()`` if you're doing ``append()`` operations with
313
+ previously ordered instances or when doing some housekeeping after
314
+ manual sql operations.
315
+
316
+ """
317
+ self.ordering_attr = ordering_attr
318
+ if ordering_func is None:
319
+ ordering_func = count_from_0
320
+ self.ordering_func = ordering_func
321
+ self.reorder_on_append = reorder_on_append
322
+
323
+ # More complex serialization schemes (multi column, e.g.) are possible by
324
+ # subclassing and reimplementing these two methods.
325
+ def _get_order_value(self, entity: _T) -> Any:
326
+ return getattr(entity, self.ordering_attr)
327
+
328
+ def _set_order_value(self, entity: _T, value: Any) -> None:
329
+ setattr(entity, self.ordering_attr, value)
330
+
331
+ def reorder(self) -> None:
332
+ """Synchronize ordering for the entire collection.
333
+
334
+ Sweeps through the list and ensures that each object has accurate
335
+ ordering information set.
336
+
337
+ """
338
+ for index, entity in enumerate(self):
339
+ self._order_entity(index, entity, True)
340
+
341
+ # As of 0.5, _reorder is no longer semi-private
342
+ _reorder = reorder
343
+
344
+ def _order_entity(
345
+ self, index: int, entity: _T, reorder: bool = True
346
+ ) -> None:
347
+ have = self._get_order_value(entity)
348
+
349
+ # Don't disturb existing ordering if reorder is False
350
+ if have is not None and not reorder:
351
+ return
352
+
353
+ should_be = self.ordering_func(index, self)
354
+ if have != should_be:
355
+ self._set_order_value(entity, should_be)
356
+
357
+ def append(self, entity: _T) -> None:
358
+ super().append(entity)
359
+ self._order_entity(len(self) - 1, entity, self.reorder_on_append)
360
+
361
+ def _raw_append(self, entity: _T) -> None:
362
+ """Append without any ordering behavior."""
363
+
364
+ super().append(entity)
365
+
366
+ _raw_append = collection.adds(1)(_raw_append)
367
+
368
+ def insert(self, index: SupportsIndex, entity: _T) -> None:
369
+ super().insert(index, entity)
370
+ self._reorder()
371
+
372
+ def remove(self, entity: _T) -> None:
373
+ super().remove(entity)
374
+
375
+ adapter = collection_adapter(self)
376
+ if adapter and adapter._referenced_by_owner:
377
+ self._reorder()
378
+
379
+ def pop(self, index: SupportsIndex = -1) -> _T:
380
+ entity = super().pop(index)
381
+ self._reorder()
382
+ return entity
383
+
384
+ @overload
385
+ def __setitem__(self, index: SupportsIndex, entity: _T) -> None: ...
386
+
387
+ @overload
388
+ def __setitem__(self, index: slice, entity: Iterable[_T]) -> None: ...
389
+
390
+ def __setitem__(
391
+ self,
392
+ index: Union[SupportsIndex, slice],
393
+ entity: Union[_T, Iterable[_T]],
394
+ ) -> None:
395
+ if isinstance(index, slice):
396
+ step = index.step or 1
397
+ start = index.start or 0
398
+ if start < 0:
399
+ start += len(self)
400
+ stop = index.stop or len(self)
401
+ if stop < 0:
402
+ stop += len(self)
403
+ entities = list(entity) # type: ignore[arg-type]
404
+ for i in range(start, stop, step):
405
+ self.__setitem__(i, entities[i])
406
+ else:
407
+ self._order_entity(int(index), entity, True) # type: ignore[arg-type] # noqa: E501
408
+ super().__setitem__(index, entity) # type: ignore[assignment]
409
+
410
+ def __delitem__(self, index: Union[SupportsIndex, slice]) -> None:
411
+ super().__delitem__(index)
412
+ self._reorder()
413
+
414
+ def __reduce__(self) -> Any:
415
+ return _reconstitute, (self.__class__, self.__dict__, list(self))
416
+
417
+ for func_name, func in list(locals().items()):
418
+ if (
419
+ callable(func)
420
+ and func.__name__ == func_name
421
+ and not func.__doc__
422
+ and hasattr(list, func_name)
423
+ ):
424
+ func.__doc__ = getattr(list, func_name).__doc__
425
+ del func_name, func
426
+
427
+
428
+ def _reconstitute(
429
+ cls: Type[OrderingList[_T]], dict_: Dict[str, Any], items: List[_T]
430
+ ) -> OrderingList[_T]:
431
+ """Reconstitute an :class:`.OrderingList`.
432
+
433
+ This is the adjoint to :meth:`.OrderingList.__reduce__`. It is used for
434
+ unpickling :class:`.OrderingList` objects.
435
+
436
+ """
437
+ obj = cls.__new__(cls)
438
+ obj.__dict__.update(dict_)
439
+ list.extend(obj, items)
440
+ return obj
@@ -0,0 +1,184 @@
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
+ __all__ = ["Serializer", "Deserializer", "dumps", "loads"]
86
+
87
+
88
+ class Serializer(pickle.Pickler):
89
+
90
+ def persistent_id(self, obj):
91
+ # print "serializing:", repr(obj)
92
+ if isinstance(obj, Mapper):
93
+ id_ = "mapper:" + b64encode(pickle.dumps(obj.class_))
94
+ elif isinstance(obj, MapperProperty):
95
+ id_ = (
96
+ "mapperprop:"
97
+ + b64encode(pickle.dumps(obj.parent.class_))
98
+ + ":"
99
+ + obj.key
100
+ )
101
+ elif isinstance(obj, Table):
102
+ if "parententity" in obj._annotations:
103
+ id_ = "mapper_selectable:" + b64encode(
104
+ pickle.dumps(obj._annotations["parententity"].class_)
105
+ )
106
+ else:
107
+ id_ = f"table:{obj.key}"
108
+ elif isinstance(obj, Column) and isinstance(obj.table, Table):
109
+ id_ = f"column:{obj.table.key}:{obj.key}"
110
+ elif isinstance(obj, Session):
111
+ id_ = "session:"
112
+ elif isinstance(obj, Engine):
113
+ id_ = "engine:"
114
+ else:
115
+ return None
116
+ return id_
117
+
118
+
119
+ our_ids = re.compile(
120
+ r"(mapperprop|mapper|mapper_selectable|table|column|"
121
+ r"session|attribute|engine):(.*)"
122
+ )
123
+
124
+
125
+ class Deserializer(pickle.Unpickler):
126
+
127
+ def __init__(self, file, metadata=None, scoped_session=None, engine=None):
128
+ super().__init__(file)
129
+ self.metadata = metadata
130
+ self.scoped_session = scoped_session
131
+ self.engine = engine
132
+
133
+ def get_engine(self):
134
+ if self.engine:
135
+ return self.engine
136
+ elif self.scoped_session and self.scoped_session().bind:
137
+ return self.scoped_session().bind
138
+ else:
139
+ return None
140
+
141
+ def persistent_load(self, id_):
142
+ m = our_ids.match(str(id_))
143
+ if not m:
144
+ return None
145
+ else:
146
+ type_, args = m.group(1, 2)
147
+ if type_ == "attribute":
148
+ key, clsarg = args.split(":")
149
+ cls = pickle.loads(b64decode(clsarg))
150
+ return getattr(cls, key)
151
+ elif type_ == "mapper":
152
+ cls = pickle.loads(b64decode(args))
153
+ return class_mapper(cls)
154
+ elif type_ == "mapper_selectable":
155
+ cls = pickle.loads(b64decode(args))
156
+ return class_mapper(cls).__clause_element__()
157
+ elif type_ == "mapperprop":
158
+ mapper, keyname = args.split(":")
159
+ cls = pickle.loads(b64decode(mapper))
160
+ return class_mapper(cls).attrs[keyname]
161
+ elif type_ == "table":
162
+ return self.metadata.tables[args]
163
+ elif type_ == "column":
164
+ table, colname = args.split(":")
165
+ return self.metadata.tables[table].c[colname]
166
+ elif type_ == "session":
167
+ return self.scoped_session()
168
+ elif type_ == "engine":
169
+ return self.get_engine()
170
+ else:
171
+ raise Exception("Unknown token: %s" % type_)
172
+
173
+
174
+ def dumps(obj, protocol=pickle.HIGHEST_PROTOCOL):
175
+ buf = BytesIO()
176
+ pickler = Serializer(buf, protocol)
177
+ pickler.dump(obj)
178
+ return buf.getvalue()
179
+
180
+
181
+ def loads(data, metadata=None, scoped_session=None, engine=None):
182
+ buf = BytesIO(data)
183
+ unpickler = Deserializer(buf, metadata, scoped_session, engine)
184
+ return unpickler.load()
@@ -0,0 +1,17 @@
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
+
14
+ from .engine import Connection as Connection
15
+ from .engine import create_engine as create_engine
16
+ from .engine import Engine as Engine
17
+ 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