SQLAlchemy 2.1.0b1__cp313-cp313-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 (267) hide show
  1. sqlalchemy/__init__.py +295 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +161 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4110 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +129 -0
  13. sqlalchemy/dialects/mssql/provision.py +185 -0
  14. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  15. sqlalchemy/dialects/mssql/pyodbc.py +758 -0
  16. sqlalchemy/dialects/mysql/__init__.py +106 -0
  17. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  18. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  19. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  20. sqlalchemy/dialects/mysql/base.py +3870 -0
  21. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  22. sqlalchemy/dialects/mysql/dml.py +279 -0
  23. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  24. sqlalchemy/dialects/mysql/expression.py +146 -0
  25. sqlalchemy/dialects/mysql/json.py +91 -0
  26. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  27. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  28. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  29. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  30. sqlalchemy/dialects/mysql/provision.py +147 -0
  31. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  32. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  33. sqlalchemy/dialects/mysql/reflection.py +724 -0
  34. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  35. sqlalchemy/dialects/mysql/types.py +845 -0
  36. sqlalchemy/dialects/oracle/__init__.py +83 -0
  37. sqlalchemy/dialects/oracle/base.py +3871 -0
  38. sqlalchemy/dialects/oracle/cx_oracle.py +1522 -0
  39. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  40. sqlalchemy/dialects/oracle/oracledb.py +894 -0
  41. sqlalchemy/dialects/oracle/provision.py +288 -0
  42. sqlalchemy/dialects/oracle/types.py +350 -0
  43. sqlalchemy/dialects/oracle/vector.py +368 -0
  44. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  45. sqlalchemy/dialects/postgresql/_psycopg_common.py +193 -0
  46. sqlalchemy/dialects/postgresql/array.py +534 -0
  47. sqlalchemy/dialects/postgresql/asyncpg.py +1331 -0
  48. sqlalchemy/dialects/postgresql/base.py +5729 -0
  49. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  50. sqlalchemy/dialects/postgresql/dml.py +360 -0
  51. sqlalchemy/dialects/postgresql/ext.py +593 -0
  52. sqlalchemy/dialects/postgresql/hstore.py +413 -0
  53. sqlalchemy/dialects/postgresql/json.py +407 -0
  54. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  55. sqlalchemy/dialects/postgresql/operators.py +130 -0
  56. sqlalchemy/dialects/postgresql/pg8000.py +672 -0
  57. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  58. sqlalchemy/dialects/postgresql/provision.py +175 -0
  59. sqlalchemy/dialects/postgresql/psycopg.py +815 -0
  60. sqlalchemy/dialects/postgresql/psycopg2.py +887 -0
  61. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  62. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  63. sqlalchemy/dialects/postgresql/types.py +388 -0
  64. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  65. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  66. sqlalchemy/dialects/sqlite/base.py +3050 -0
  67. sqlalchemy/dialects/sqlite/dml.py +279 -0
  68. sqlalchemy/dialects/sqlite/json.py +89 -0
  69. sqlalchemy/dialects/sqlite/provision.py +223 -0
  70. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  71. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  72. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  73. sqlalchemy/engine/__init__.py +62 -0
  74. sqlalchemy/engine/_processors_cy.cp313-win_arm64.pyd +0 -0
  75. sqlalchemy/engine/_processors_cy.py +92 -0
  76. sqlalchemy/engine/_result_cy.cp313-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_result_cy.py +633 -0
  78. sqlalchemy/engine/_row_cy.cp313-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_row_cy.py +232 -0
  80. sqlalchemy/engine/_util_cy.cp313-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_util_cy.py +136 -0
  82. sqlalchemy/engine/base.py +3334 -0
  83. sqlalchemy/engine/characteristics.py +155 -0
  84. sqlalchemy/engine/create.py +869 -0
  85. sqlalchemy/engine/cursor.py +2416 -0
  86. sqlalchemy/engine/default.py +2393 -0
  87. sqlalchemy/engine/events.py +965 -0
  88. sqlalchemy/engine/interfaces.py +3465 -0
  89. sqlalchemy/engine/mock.py +134 -0
  90. sqlalchemy/engine/processors.py +82 -0
  91. sqlalchemy/engine/reflection.py +2100 -0
  92. sqlalchemy/engine/result.py +1932 -0
  93. sqlalchemy/engine/row.py +397 -0
  94. sqlalchemy/engine/strategies.py +16 -0
  95. sqlalchemy/engine/url.py +922 -0
  96. sqlalchemy/engine/util.py +156 -0
  97. sqlalchemy/event/__init__.py +26 -0
  98. sqlalchemy/event/api.py +220 -0
  99. sqlalchemy/event/attr.py +674 -0
  100. sqlalchemy/event/base.py +472 -0
  101. sqlalchemy/event/legacy.py +258 -0
  102. sqlalchemy/event/registry.py +390 -0
  103. sqlalchemy/events.py +17 -0
  104. sqlalchemy/exc.py +922 -0
  105. sqlalchemy/ext/__init__.py +11 -0
  106. sqlalchemy/ext/associationproxy.py +2072 -0
  107. sqlalchemy/ext/asyncio/__init__.py +29 -0
  108. sqlalchemy/ext/asyncio/base.py +281 -0
  109. sqlalchemy/ext/asyncio/engine.py +1475 -0
  110. sqlalchemy/ext/asyncio/exc.py +21 -0
  111. sqlalchemy/ext/asyncio/result.py +994 -0
  112. sqlalchemy/ext/asyncio/scoping.py +1667 -0
  113. sqlalchemy/ext/asyncio/session.py +1993 -0
  114. sqlalchemy/ext/automap.py +1701 -0
  115. sqlalchemy/ext/baked.py +559 -0
  116. sqlalchemy/ext/compiler.py +600 -0
  117. sqlalchemy/ext/declarative/__init__.py +65 -0
  118. sqlalchemy/ext/declarative/extensions.py +560 -0
  119. sqlalchemy/ext/horizontal_shard.py +481 -0
  120. sqlalchemy/ext/hybrid.py +1877 -0
  121. sqlalchemy/ext/indexable.py +364 -0
  122. sqlalchemy/ext/instrumentation.py +450 -0
  123. sqlalchemy/ext/mutable.py +1081 -0
  124. sqlalchemy/ext/orderinglist.py +439 -0
  125. sqlalchemy/ext/serializer.py +185 -0
  126. sqlalchemy/future/__init__.py +16 -0
  127. sqlalchemy/future/engine.py +15 -0
  128. sqlalchemy/inspection.py +174 -0
  129. sqlalchemy/log.py +283 -0
  130. sqlalchemy/orm/__init__.py +175 -0
  131. sqlalchemy/orm/_orm_constructors.py +2694 -0
  132. sqlalchemy/orm/_typing.py +179 -0
  133. sqlalchemy/orm/attributes.py +2868 -0
  134. sqlalchemy/orm/base.py +970 -0
  135. sqlalchemy/orm/bulk_persistence.py +2152 -0
  136. sqlalchemy/orm/clsregistry.py +582 -0
  137. sqlalchemy/orm/collections.py +1568 -0
  138. sqlalchemy/orm/context.py +3471 -0
  139. sqlalchemy/orm/decl_api.py +2257 -0
  140. sqlalchemy/orm/decl_base.py +2304 -0
  141. sqlalchemy/orm/dependency.py +1306 -0
  142. sqlalchemy/orm/descriptor_props.py +1183 -0
  143. sqlalchemy/orm/dynamic.py +300 -0
  144. sqlalchemy/orm/evaluator.py +379 -0
  145. sqlalchemy/orm/events.py +3386 -0
  146. sqlalchemy/orm/exc.py +237 -0
  147. sqlalchemy/orm/identity.py +302 -0
  148. sqlalchemy/orm/instrumentation.py +746 -0
  149. sqlalchemy/orm/interfaces.py +1589 -0
  150. sqlalchemy/orm/loading.py +1684 -0
  151. sqlalchemy/orm/mapped_collection.py +557 -0
  152. sqlalchemy/orm/mapper.py +4406 -0
  153. sqlalchemy/orm/path_registry.py +814 -0
  154. sqlalchemy/orm/persistence.py +1789 -0
  155. sqlalchemy/orm/properties.py +973 -0
  156. sqlalchemy/orm/query.py +3521 -0
  157. sqlalchemy/orm/relationships.py +3570 -0
  158. sqlalchemy/orm/scoping.py +2220 -0
  159. sqlalchemy/orm/session.py +5389 -0
  160. sqlalchemy/orm/state.py +1175 -0
  161. sqlalchemy/orm/state_changes.py +196 -0
  162. sqlalchemy/orm/strategies.py +3480 -0
  163. sqlalchemy/orm/strategy_options.py +2544 -0
  164. sqlalchemy/orm/sync.py +164 -0
  165. sqlalchemy/orm/unitofwork.py +798 -0
  166. sqlalchemy/orm/util.py +2435 -0
  167. sqlalchemy/orm/writeonly.py +694 -0
  168. sqlalchemy/pool/__init__.py +41 -0
  169. sqlalchemy/pool/base.py +1514 -0
  170. sqlalchemy/pool/events.py +372 -0
  171. sqlalchemy/pool/impl.py +582 -0
  172. sqlalchemy/py.typed +0 -0
  173. sqlalchemy/schema.py +72 -0
  174. sqlalchemy/sql/__init__.py +153 -0
  175. sqlalchemy/sql/_dml_constructors.py +132 -0
  176. sqlalchemy/sql/_elements_constructors.py +2147 -0
  177. sqlalchemy/sql/_orm_types.py +20 -0
  178. sqlalchemy/sql/_selectable_constructors.py +773 -0
  179. sqlalchemy/sql/_typing.py +486 -0
  180. sqlalchemy/sql/_util_cy.cp313-win_arm64.pyd +0 -0
  181. sqlalchemy/sql/_util_cy.py +127 -0
  182. sqlalchemy/sql/annotation.py +590 -0
  183. sqlalchemy/sql/base.py +2602 -0
  184. sqlalchemy/sql/cache_key.py +1066 -0
  185. sqlalchemy/sql/coercions.py +1373 -0
  186. sqlalchemy/sql/compiler.py +8259 -0
  187. sqlalchemy/sql/crud.py +1807 -0
  188. sqlalchemy/sql/ddl.py +1928 -0
  189. sqlalchemy/sql/default_comparator.py +654 -0
  190. sqlalchemy/sql/dml.py +1974 -0
  191. sqlalchemy/sql/elements.py +6016 -0
  192. sqlalchemy/sql/events.py +458 -0
  193. sqlalchemy/sql/expression.py +170 -0
  194. sqlalchemy/sql/functions.py +2257 -0
  195. sqlalchemy/sql/lambdas.py +1443 -0
  196. sqlalchemy/sql/naming.py +209 -0
  197. sqlalchemy/sql/operators.py +2897 -0
  198. sqlalchemy/sql/roles.py +332 -0
  199. sqlalchemy/sql/schema.py +6560 -0
  200. sqlalchemy/sql/selectable.py +7497 -0
  201. sqlalchemy/sql/sqltypes.py +4050 -0
  202. sqlalchemy/sql/traversals.py +1042 -0
  203. sqlalchemy/sql/type_api.py +2425 -0
  204. sqlalchemy/sql/util.py +1495 -0
  205. sqlalchemy/sql/visitors.py +1157 -0
  206. sqlalchemy/testing/__init__.py +96 -0
  207. sqlalchemy/testing/assertions.py +1007 -0
  208. sqlalchemy/testing/assertsql.py +519 -0
  209. sqlalchemy/testing/asyncio.py +128 -0
  210. sqlalchemy/testing/config.py +440 -0
  211. sqlalchemy/testing/engines.py +478 -0
  212. sqlalchemy/testing/entities.py +117 -0
  213. sqlalchemy/testing/exclusions.py +476 -0
  214. sqlalchemy/testing/fixtures/__init__.py +30 -0
  215. sqlalchemy/testing/fixtures/base.py +366 -0
  216. sqlalchemy/testing/fixtures/mypy.py +247 -0
  217. sqlalchemy/testing/fixtures/orm.py +227 -0
  218. sqlalchemy/testing/fixtures/sql.py +538 -0
  219. sqlalchemy/testing/pickleable.py +155 -0
  220. sqlalchemy/testing/plugin/__init__.py +6 -0
  221. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  222. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  223. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  224. sqlalchemy/testing/profiling.py +329 -0
  225. sqlalchemy/testing/provision.py +596 -0
  226. sqlalchemy/testing/requirements.py +1973 -0
  227. sqlalchemy/testing/schema.py +198 -0
  228. sqlalchemy/testing/suite/__init__.py +19 -0
  229. sqlalchemy/testing/suite/test_cte.py +237 -0
  230. sqlalchemy/testing/suite/test_ddl.py +420 -0
  231. sqlalchemy/testing/suite/test_dialect.py +776 -0
  232. sqlalchemy/testing/suite/test_insert.py +630 -0
  233. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  234. sqlalchemy/testing/suite/test_results.py +660 -0
  235. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  236. sqlalchemy/testing/suite/test_select.py +2112 -0
  237. sqlalchemy/testing/suite/test_sequence.py +317 -0
  238. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  239. sqlalchemy/testing/suite/test_types.py +2253 -0
  240. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  241. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  242. sqlalchemy/testing/util.py +535 -0
  243. sqlalchemy/testing/warnings.py +52 -0
  244. sqlalchemy/types.py +76 -0
  245. sqlalchemy/util/__init__.py +157 -0
  246. sqlalchemy/util/_collections.py +693 -0
  247. sqlalchemy/util/_collections_cy.cp313-win_arm64.pyd +0 -0
  248. sqlalchemy/util/_collections_cy.pxd +8 -0
  249. sqlalchemy/util/_collections_cy.py +516 -0
  250. sqlalchemy/util/_has_cython.py +46 -0
  251. sqlalchemy/util/_immutabledict_cy.cp313-win_arm64.pyd +0 -0
  252. sqlalchemy/util/_immutabledict_cy.py +240 -0
  253. sqlalchemy/util/compat.py +287 -0
  254. sqlalchemy/util/concurrency.py +322 -0
  255. sqlalchemy/util/cython.py +79 -0
  256. sqlalchemy/util/deprecations.py +401 -0
  257. sqlalchemy/util/langhelpers.py +2256 -0
  258. sqlalchemy/util/preloaded.py +152 -0
  259. sqlalchemy/util/queue.py +304 -0
  260. sqlalchemy/util/tool_support.py +201 -0
  261. sqlalchemy/util/topological.py +120 -0
  262. sqlalchemy/util/typing.py +711 -0
  263. sqlalchemy-2.1.0b1.dist-info/METADATA +267 -0
  264. sqlalchemy-2.1.0b1.dist-info/RECORD +267 -0
  265. sqlalchemy-2.1.0b1.dist-info/WHEEL +5 -0
  266. sqlalchemy-2.1.0b1.dist-info/licenses/LICENSE +19 -0
  267. sqlalchemy-2.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,413 @@
1
+ # dialects/postgresql/hstore.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
+
10
+ import re
11
+
12
+ from .array import ARRAY
13
+ from .operators import CONTAINED_BY
14
+ from .operators import CONTAINS
15
+ from .operators import GETITEM
16
+ from .operators import HAS_ALL
17
+ from .operators import HAS_ANY
18
+ from .operators import HAS_KEY
19
+ from ... import types as sqltypes
20
+ from ...sql import functions as sqlfunc
21
+ from ...types import OperatorClass
22
+
23
+ __all__ = ("HSTORE", "hstore")
24
+
25
+
26
+ class HSTORE(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine):
27
+ """Represent the PostgreSQL HSTORE type.
28
+
29
+ The :class:`.HSTORE` type stores dictionaries containing strings, e.g.::
30
+
31
+ data_table = Table(
32
+ "data_table",
33
+ metadata,
34
+ Column("id", Integer, primary_key=True),
35
+ Column("data", HSTORE),
36
+ )
37
+
38
+ with engine.connect() as conn:
39
+ conn.execute(
40
+ data_table.insert(), data={"key1": "value1", "key2": "value2"}
41
+ )
42
+
43
+ :class:`.HSTORE` provides for a wide range of operations, including:
44
+
45
+ * Index operations::
46
+
47
+ data_table.c.data["some key"] == "some value"
48
+
49
+ * Containment operations::
50
+
51
+ data_table.c.data.has_key("some key")
52
+
53
+ data_table.c.data.has_all(["one", "two", "three"])
54
+
55
+ * Concatenation::
56
+
57
+ data_table.c.data + {"k1": "v1"}
58
+
59
+ For a full list of special methods see
60
+ :class:`.HSTORE.comparator_factory`.
61
+
62
+ .. container:: topic
63
+
64
+ **Detecting Changes in HSTORE columns when using the ORM**
65
+
66
+ For usage with the SQLAlchemy ORM, it may be desirable to combine the
67
+ usage of :class:`.HSTORE` with :class:`.MutableDict` dictionary now
68
+ part of the :mod:`sqlalchemy.ext.mutable` extension. This extension
69
+ will allow "in-place" changes to the dictionary, e.g. addition of new
70
+ keys or replacement/removal of existing keys to/from the current
71
+ dictionary, to produce events which will be detected by the unit of
72
+ work::
73
+
74
+ from sqlalchemy.ext.mutable import MutableDict
75
+
76
+
77
+ class MyClass(Base):
78
+ __tablename__ = "data_table"
79
+
80
+ id = Column(Integer, primary_key=True)
81
+ data = Column(MutableDict.as_mutable(HSTORE))
82
+
83
+
84
+ my_object = session.query(MyClass).one()
85
+
86
+ # in-place mutation, requires Mutable extension
87
+ # in order for the ORM to detect
88
+ my_object.data["some_key"] = "some value"
89
+
90
+ session.commit()
91
+
92
+ When the :mod:`sqlalchemy.ext.mutable` extension is not used, the ORM
93
+ will not be alerted to any changes to the contents of an existing
94
+ dictionary, unless that dictionary value is re-assigned to the
95
+ HSTORE-attribute itself, thus generating a change event.
96
+
97
+ .. seealso::
98
+
99
+ :class:`.hstore` - render the PostgreSQL ``hstore()`` function.
100
+
101
+
102
+ """ # noqa: E501
103
+
104
+ __visit_name__ = "HSTORE"
105
+ hashable = False
106
+ text_type = sqltypes.Text()
107
+
108
+ operator_classes = (
109
+ OperatorClass.BASE
110
+ | OperatorClass.CONTAINS
111
+ | OperatorClass.INDEXABLE
112
+ | OperatorClass.CONCATENABLE
113
+ )
114
+
115
+ def __init__(self, text_type=None):
116
+ """Construct a new :class:`.HSTORE`.
117
+
118
+ :param text_type: the type that should be used for indexed values.
119
+ Defaults to :class:`_types.Text`.
120
+
121
+ """
122
+ if text_type is not None:
123
+ self.text_type = text_type
124
+
125
+ class Comparator(
126
+ sqltypes.Indexable.Comparator, sqltypes.Concatenable.Comparator
127
+ ):
128
+ """Define comparison operations for :class:`.HSTORE`."""
129
+
130
+ def has_key(self, other):
131
+ """Boolean expression. Test for presence of a key. Note that the
132
+ key may be a SQLA expression.
133
+ """
134
+ return self.operate(HAS_KEY, other, result_type=sqltypes.Boolean)
135
+
136
+ def has_all(self, other):
137
+ """Boolean expression. Test for presence of all keys in jsonb"""
138
+ return self.operate(HAS_ALL, other, result_type=sqltypes.Boolean)
139
+
140
+ def has_any(self, other):
141
+ """Boolean expression. Test for presence of any key in jsonb"""
142
+ return self.operate(HAS_ANY, other, result_type=sqltypes.Boolean)
143
+
144
+ def contains(self, other, **kwargs):
145
+ """Boolean expression. Test if keys (or array) are a superset
146
+ of/contained the keys of the argument jsonb expression.
147
+
148
+ kwargs may be ignored by this operator but are required for API
149
+ conformance.
150
+ """
151
+ return self.operate(CONTAINS, other, result_type=sqltypes.Boolean)
152
+
153
+ def contained_by(self, other):
154
+ """Boolean expression. Test if keys are a proper subset of the
155
+ keys of the argument jsonb expression.
156
+ """
157
+ return self.operate(
158
+ CONTAINED_BY, other, result_type=sqltypes.Boolean
159
+ )
160
+
161
+ def _setup_getitem(self, index):
162
+ return GETITEM, index, self.type.text_type
163
+
164
+ def defined(self, key):
165
+ """Boolean expression. Test for presence of a non-NULL value for
166
+ the key. Note that the key may be a SQLA expression.
167
+ """
168
+ return _HStoreDefinedFunction(self.expr, key)
169
+
170
+ def delete(self, key):
171
+ """HStore expression. Returns the contents of this hstore with the
172
+ given key deleted. Note that the key may be a SQLA expression.
173
+ """
174
+ if isinstance(key, dict):
175
+ key = _serialize_hstore(key)
176
+ return _HStoreDeleteFunction(self.expr, key)
177
+
178
+ def slice(self, array):
179
+ """HStore expression. Returns a subset of an hstore defined by
180
+ array of keys.
181
+ """
182
+ return _HStoreSliceFunction(self.expr, array)
183
+
184
+ def keys(self):
185
+ """Text array expression. Returns array of keys."""
186
+ return _HStoreKeysFunction(self.expr)
187
+
188
+ def vals(self):
189
+ """Text array expression. Returns array of values."""
190
+ return _HStoreValsFunction(self.expr)
191
+
192
+ def array(self):
193
+ """Text array expression. Returns array of alternating keys and
194
+ values.
195
+ """
196
+ return _HStoreArrayFunction(self.expr)
197
+
198
+ def matrix(self):
199
+ """Text array expression. Returns array of [key, value] pairs."""
200
+ return _HStoreMatrixFunction(self.expr)
201
+
202
+ comparator_factory = Comparator
203
+
204
+ def bind_processor(self, dialect):
205
+ # note that dialect-specific types like that of psycopg and
206
+ # psycopg2 will override this method to allow driver-level conversion
207
+ # instead, see _PsycopgHStore
208
+ def process(value):
209
+ if isinstance(value, dict):
210
+ return _serialize_hstore(value)
211
+ else:
212
+ return value
213
+
214
+ return process
215
+
216
+ def result_processor(self, dialect, coltype):
217
+ # note that dialect-specific types like that of psycopg and
218
+ # psycopg2 will override this method to allow driver-level conversion
219
+ # instead, see _PsycopgHStore
220
+ def process(value):
221
+ if value is not None:
222
+ return _parse_hstore(value)
223
+ else:
224
+ return value
225
+
226
+ return process
227
+
228
+
229
+ class hstore(sqlfunc.GenericFunction):
230
+ """Construct an hstore value within a SQL expression using the
231
+ PostgreSQL ``hstore()`` function.
232
+
233
+ The :class:`.hstore` function accepts one or two arguments as described
234
+ in the PostgreSQL documentation.
235
+
236
+ E.g.::
237
+
238
+ from sqlalchemy.dialects.postgresql import array, hstore
239
+
240
+ select(hstore("key1", "value1"))
241
+
242
+ select(
243
+ hstore(
244
+ array(["key1", "key2", "key3"]),
245
+ array(["value1", "value2", "value3"]),
246
+ )
247
+ )
248
+
249
+ .. seealso::
250
+
251
+ :class:`.HSTORE` - the PostgreSQL ``HSTORE`` datatype.
252
+
253
+ """
254
+
255
+ type = HSTORE
256
+ name = "hstore"
257
+ inherit_cache = True
258
+
259
+
260
+ class _HStoreDefinedFunction(sqlfunc.GenericFunction):
261
+ type = sqltypes.Boolean
262
+ name = "defined"
263
+ inherit_cache = True
264
+
265
+
266
+ class _HStoreDeleteFunction(sqlfunc.GenericFunction):
267
+ type = HSTORE
268
+ name = "delete"
269
+ inherit_cache = True
270
+
271
+
272
+ class _HStoreSliceFunction(sqlfunc.GenericFunction):
273
+ type = HSTORE
274
+ name = "slice"
275
+ inherit_cache = True
276
+
277
+
278
+ class _HStoreKeysFunction(sqlfunc.GenericFunction):
279
+ type = ARRAY(sqltypes.Text)
280
+ name = "akeys"
281
+ inherit_cache = True
282
+
283
+
284
+ class _HStoreValsFunction(sqlfunc.GenericFunction):
285
+ type = ARRAY(sqltypes.Text)
286
+ name = "avals"
287
+ inherit_cache = True
288
+
289
+
290
+ class _HStoreArrayFunction(sqlfunc.GenericFunction):
291
+ type = ARRAY(sqltypes.Text)
292
+ name = "hstore_to_array"
293
+ inherit_cache = True
294
+
295
+
296
+ class _HStoreMatrixFunction(sqlfunc.GenericFunction):
297
+ type = ARRAY(sqltypes.Text)
298
+ name = "hstore_to_matrix"
299
+ inherit_cache = True
300
+
301
+
302
+ #
303
+ # parsing. note that none of this is used with the psycopg2 backend,
304
+ # which provides its own native extensions.
305
+ #
306
+
307
+ # My best guess at the parsing rules of hstore literals, since no formal
308
+ # grammar is given. This is mostly reverse engineered from PG's input parser
309
+ # behavior.
310
+ HSTORE_PAIR_RE = re.compile(
311
+ r"""
312
+ (
313
+ "(?P<key> (\\ . | [^"])* )" # Quoted key
314
+ )
315
+ [ ]* => [ ]* # Pair operator, optional adjoining whitespace
316
+ (
317
+ (?P<value_null> NULL ) # NULL value
318
+ | "(?P<value> (\\ . | [^"])* )" # Quoted value
319
+ )
320
+ """,
321
+ re.VERBOSE,
322
+ )
323
+
324
+ HSTORE_DELIMITER_RE = re.compile(
325
+ r"""
326
+ [ ]* , [ ]*
327
+ """,
328
+ re.VERBOSE,
329
+ )
330
+
331
+
332
+ def _parse_error(hstore_str, pos):
333
+ """format an unmarshalling error."""
334
+
335
+ ctx = 20
336
+ hslen = len(hstore_str)
337
+
338
+ parsed_tail = hstore_str[max(pos - ctx - 1, 0) : min(pos, hslen)]
339
+ residual = hstore_str[min(pos, hslen) : min(pos + ctx + 1, hslen)]
340
+
341
+ if len(parsed_tail) > ctx:
342
+ parsed_tail = "[...]" + parsed_tail[1:]
343
+ if len(residual) > ctx:
344
+ residual = residual[:-1] + "[...]"
345
+
346
+ return "After %r, could not parse residual at position %d: %r" % (
347
+ parsed_tail,
348
+ pos,
349
+ residual,
350
+ )
351
+
352
+
353
+ def _parse_hstore(hstore_str):
354
+ """Parse an hstore from its literal string representation.
355
+
356
+ Attempts to approximate PG's hstore input parsing rules as closely as
357
+ possible. Although currently this is not strictly necessary, since the
358
+ current implementation of hstore's output syntax is stricter than what it
359
+ accepts as input, the documentation makes no guarantees that will always
360
+ be the case.
361
+
362
+
363
+
364
+ """
365
+ result = {}
366
+ pos = 0
367
+ pair_match = HSTORE_PAIR_RE.match(hstore_str)
368
+
369
+ while pair_match is not None:
370
+ key = pair_match.group("key").replace(r"\"", '"').replace("\\\\", "\\")
371
+ if pair_match.group("value_null"):
372
+ value = None
373
+ else:
374
+ value = (
375
+ pair_match.group("value")
376
+ .replace(r"\"", '"')
377
+ .replace("\\\\", "\\")
378
+ )
379
+ result[key] = value
380
+
381
+ pos += pair_match.end()
382
+
383
+ delim_match = HSTORE_DELIMITER_RE.match(hstore_str[pos:])
384
+ if delim_match is not None:
385
+ pos += delim_match.end()
386
+
387
+ pair_match = HSTORE_PAIR_RE.match(hstore_str[pos:])
388
+
389
+ if pos != len(hstore_str):
390
+ raise ValueError(_parse_error(hstore_str, pos))
391
+
392
+ return result
393
+
394
+
395
+ def _serialize_hstore(val):
396
+ """Serialize a dictionary into an hstore literal. Keys and values must
397
+ both be strings (except None for values).
398
+
399
+ """
400
+
401
+ def esc(s, position):
402
+ if position == "value" and s is None:
403
+ return "NULL"
404
+ elif isinstance(s, str):
405
+ return '"%s"' % s.replace("\\", "\\\\").replace('"', r"\"")
406
+ else:
407
+ raise ValueError(
408
+ "%r in %s position is not a string." % (s, position)
409
+ )
410
+
411
+ return ", ".join(
412
+ "%s=>%s" % (esc(k, "key"), esc(v, "value")) for k, v in val.items()
413
+ )