SQLAlchemy 2.0.36__cp313-cp313-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 (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,2141 @@
1
+ # testing/suite/test_types.py
2
+ # Copyright (C) 2005-2024 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 datetime
11
+ import decimal
12
+ import json
13
+ import re
14
+ import uuid
15
+
16
+ from .. import config
17
+ from .. import engines
18
+ from .. import fixtures
19
+ from .. import mock
20
+ from ..assertions import eq_
21
+ from ..assertions import is_
22
+ from ..assertions import ne_
23
+ from ..config import requirements
24
+ from ..schema import Column
25
+ from ..schema import Table
26
+ from ... import and_
27
+ from ... import ARRAY
28
+ from ... import BigInteger
29
+ from ... import bindparam
30
+ from ... import Boolean
31
+ from ... import case
32
+ from ... import cast
33
+ from ... import Date
34
+ from ... import DateTime
35
+ from ... import Enum
36
+ from ... import Float
37
+ from ... import Integer
38
+ from ... import Interval
39
+ from ... import JSON
40
+ from ... import literal
41
+ from ... import literal_column
42
+ from ... import MetaData
43
+ from ... import null
44
+ from ... import Numeric
45
+ from ... import select
46
+ from ... import String
47
+ from ... import testing
48
+ from ... import Text
49
+ from ... import Time
50
+ from ... import TIMESTAMP
51
+ from ... import type_coerce
52
+ from ... import TypeDecorator
53
+ from ... import Unicode
54
+ from ... import UnicodeText
55
+ from ... import UUID
56
+ from ... import Uuid
57
+ from ...orm import declarative_base
58
+ from ...orm import Session
59
+ from ...sql import sqltypes
60
+ from ...sql.sqltypes import LargeBinary
61
+ from ...sql.sqltypes import PickleType
62
+
63
+
64
+ class _LiteralRoundTripFixture:
65
+ supports_whereclause = True
66
+
67
+ @testing.fixture
68
+ def literal_round_trip(self, metadata, connection):
69
+ """test literal rendering"""
70
+
71
+ # for literal, we test the literal render in an INSERT
72
+ # into a typed column. we can then SELECT it back as its
73
+ # official type; ideally we'd be able to use CAST here
74
+ # but MySQL in particular can't CAST fully
75
+
76
+ def run(
77
+ type_,
78
+ input_,
79
+ output,
80
+ filter_=None,
81
+ compare=None,
82
+ support_whereclause=True,
83
+ ):
84
+ t = Table("t", metadata, Column("x", type_))
85
+ t.create(connection)
86
+
87
+ for value in input_:
88
+ ins = t.insert().values(
89
+ x=literal(value, type_, literal_execute=True)
90
+ )
91
+ connection.execute(ins)
92
+
93
+ ins = t.insert().values(
94
+ x=literal(None, type_, literal_execute=True)
95
+ )
96
+ connection.execute(ins)
97
+
98
+ if support_whereclause and self.supports_whereclause:
99
+ if compare:
100
+ stmt = t.select().where(
101
+ t.c.x
102
+ == literal(
103
+ compare,
104
+ type_,
105
+ literal_execute=True,
106
+ ),
107
+ t.c.x
108
+ == literal(
109
+ input_[0],
110
+ type_,
111
+ literal_execute=True,
112
+ ),
113
+ )
114
+ else:
115
+ stmt = t.select().where(
116
+ t.c.x
117
+ == literal(
118
+ compare if compare is not None else input_[0],
119
+ type_,
120
+ literal_execute=True,
121
+ )
122
+ )
123
+ else:
124
+ stmt = t.select().where(t.c.x.is_not(None))
125
+
126
+ rows = connection.execute(stmt).all()
127
+ assert rows, "No rows returned"
128
+ for row in rows:
129
+ value = row[0]
130
+ if filter_ is not None:
131
+ value = filter_(value)
132
+ assert value in output
133
+
134
+ stmt = t.select().where(t.c.x.is_(None))
135
+ rows = connection.execute(stmt).all()
136
+ eq_(rows, [(None,)])
137
+
138
+ return run
139
+
140
+
141
+ class _UnicodeFixture(_LiteralRoundTripFixture, fixtures.TestBase):
142
+ __requires__ = ("unicode_data",)
143
+
144
+ data = (
145
+ "Alors vous imaginez ma 🐍 surprise, au lever du jour, "
146
+ "quand une drôle de petite 🐍 voix m’a réveillé. Elle "
147
+ "disait: « S’il vous plaît… dessine-moi 🐍 un mouton! »"
148
+ )
149
+
150
+ @property
151
+ def supports_whereclause(self):
152
+ return config.requirements.expressions_against_unbounded_text.enabled
153
+
154
+ @classmethod
155
+ def define_tables(cls, metadata):
156
+ Table(
157
+ "unicode_table",
158
+ metadata,
159
+ Column(
160
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
161
+ ),
162
+ Column("unicode_data", cls.datatype),
163
+ )
164
+
165
+ def test_round_trip(self, connection):
166
+ unicode_table = self.tables.unicode_table
167
+
168
+ connection.execute(
169
+ unicode_table.insert(), {"id": 1, "unicode_data": self.data}
170
+ )
171
+
172
+ row = connection.execute(select(unicode_table.c.unicode_data)).first()
173
+
174
+ eq_(row, (self.data,))
175
+ assert isinstance(row[0], str)
176
+
177
+ def test_round_trip_executemany(self, connection):
178
+ unicode_table = self.tables.unicode_table
179
+
180
+ connection.execute(
181
+ unicode_table.insert(),
182
+ [{"id": i, "unicode_data": self.data} for i in range(1, 4)],
183
+ )
184
+
185
+ rows = connection.execute(
186
+ select(unicode_table.c.unicode_data)
187
+ ).fetchall()
188
+ eq_(rows, [(self.data,) for i in range(1, 4)])
189
+ for row in rows:
190
+ assert isinstance(row[0], str)
191
+
192
+ def _test_null_strings(self, connection):
193
+ unicode_table = self.tables.unicode_table
194
+
195
+ connection.execute(
196
+ unicode_table.insert(), {"id": 1, "unicode_data": None}
197
+ )
198
+ row = connection.execute(select(unicode_table.c.unicode_data)).first()
199
+ eq_(row, (None,))
200
+
201
+ def _test_empty_strings(self, connection):
202
+ unicode_table = self.tables.unicode_table
203
+
204
+ connection.execute(
205
+ unicode_table.insert(), {"id": 1, "unicode_data": ""}
206
+ )
207
+ row = connection.execute(select(unicode_table.c.unicode_data)).first()
208
+ eq_(row, ("",))
209
+
210
+ def test_literal(self, literal_round_trip):
211
+ literal_round_trip(self.datatype, [self.data], [self.data])
212
+
213
+ def test_literal_non_ascii(self, literal_round_trip):
214
+ literal_round_trip(self.datatype, ["réve🐍 illé"], ["réve🐍 illé"])
215
+
216
+
217
+ class UnicodeVarcharTest(_UnicodeFixture, fixtures.TablesTest):
218
+ __requires__ = ("unicode_data",)
219
+ __backend__ = True
220
+
221
+ datatype = Unicode(255)
222
+
223
+ @requirements.empty_strings_varchar
224
+ def test_empty_strings_varchar(self, connection):
225
+ self._test_empty_strings(connection)
226
+
227
+ def test_null_strings_varchar(self, connection):
228
+ self._test_null_strings(connection)
229
+
230
+
231
+ class UnicodeTextTest(_UnicodeFixture, fixtures.TablesTest):
232
+ __requires__ = "unicode_data", "text_type"
233
+ __backend__ = True
234
+
235
+ datatype = UnicodeText()
236
+
237
+ @requirements.empty_strings_text
238
+ def test_empty_strings_text(self, connection):
239
+ self._test_empty_strings(connection)
240
+
241
+ def test_null_strings_text(self, connection):
242
+ self._test_null_strings(connection)
243
+
244
+
245
+ class ArrayTest(_LiteralRoundTripFixture, fixtures.TablesTest):
246
+ """Add ARRAY test suite, #8138.
247
+
248
+ This only works on PostgreSQL right now.
249
+
250
+ """
251
+
252
+ __requires__ = ("array_type",)
253
+ __backend__ = True
254
+
255
+ @classmethod
256
+ def define_tables(cls, metadata):
257
+ Table(
258
+ "array_table",
259
+ metadata,
260
+ Column(
261
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
262
+ ),
263
+ Column("single_dim", ARRAY(Integer)),
264
+ Column("multi_dim", ARRAY(String, dimensions=2)),
265
+ )
266
+
267
+ def test_array_roundtrip(self, connection):
268
+ array_table = self.tables.array_table
269
+
270
+ connection.execute(
271
+ array_table.insert(),
272
+ {
273
+ "id": 1,
274
+ "single_dim": [1, 2, 3],
275
+ "multi_dim": [["one", "two"], ["thr'ee", "réve🐍 illé"]],
276
+ },
277
+ )
278
+ row = connection.execute(
279
+ select(array_table.c.single_dim, array_table.c.multi_dim)
280
+ ).first()
281
+ eq_(row, ([1, 2, 3], [["one", "two"], ["thr'ee", "réve🐍 illé"]]))
282
+
283
+ def test_literal_simple(self, literal_round_trip):
284
+ literal_round_trip(
285
+ ARRAY(Integer),
286
+ ([1, 2, 3],),
287
+ ([1, 2, 3],),
288
+ support_whereclause=False,
289
+ )
290
+
291
+ def test_literal_complex(self, literal_round_trip):
292
+ literal_round_trip(
293
+ ARRAY(String, dimensions=2),
294
+ ([["one", "two"], ["thr'ee", "réve🐍 illé"]],),
295
+ ([["one", "two"], ["thr'ee", "réve🐍 illé"]],),
296
+ support_whereclause=False,
297
+ )
298
+
299
+
300
+ class BinaryTest(_LiteralRoundTripFixture, fixtures.TablesTest):
301
+ __backend__ = True
302
+
303
+ @classmethod
304
+ def define_tables(cls, metadata):
305
+ Table(
306
+ "binary_table",
307
+ metadata,
308
+ Column(
309
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
310
+ ),
311
+ Column("binary_data", LargeBinary),
312
+ Column("pickle_data", PickleType),
313
+ )
314
+
315
+ @testing.combinations(b"this is binary", b"7\xe7\x9f", argnames="data")
316
+ def test_binary_roundtrip(self, connection, data):
317
+ binary_table = self.tables.binary_table
318
+
319
+ connection.execute(
320
+ binary_table.insert(), {"id": 1, "binary_data": data}
321
+ )
322
+ row = connection.execute(select(binary_table.c.binary_data)).first()
323
+ eq_(row, (data,))
324
+
325
+ def test_pickle_roundtrip(self, connection):
326
+ binary_table = self.tables.binary_table
327
+
328
+ connection.execute(
329
+ binary_table.insert(),
330
+ {"id": 1, "pickle_data": {"foo": [1, 2, 3], "bar": "bat"}},
331
+ )
332
+ row = connection.execute(select(binary_table.c.pickle_data)).first()
333
+ eq_(row, ({"foo": [1, 2, 3], "bar": "bat"},))
334
+
335
+
336
+ class TextTest(_LiteralRoundTripFixture, fixtures.TablesTest):
337
+ __requires__ = ("text_type",)
338
+ __backend__ = True
339
+
340
+ @property
341
+ def supports_whereclause(self):
342
+ return config.requirements.expressions_against_unbounded_text.enabled
343
+
344
+ @classmethod
345
+ def define_tables(cls, metadata):
346
+ Table(
347
+ "text_table",
348
+ metadata,
349
+ Column(
350
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
351
+ ),
352
+ Column("text_data", Text),
353
+ )
354
+
355
+ def test_text_roundtrip(self, connection):
356
+ text_table = self.tables.text_table
357
+
358
+ connection.execute(
359
+ text_table.insert(), {"id": 1, "text_data": "some text"}
360
+ )
361
+ row = connection.execute(select(text_table.c.text_data)).first()
362
+ eq_(row, ("some text",))
363
+
364
+ @testing.requires.empty_strings_text
365
+ def test_text_empty_strings(self, connection):
366
+ text_table = self.tables.text_table
367
+
368
+ connection.execute(text_table.insert(), {"id": 1, "text_data": ""})
369
+ row = connection.execute(select(text_table.c.text_data)).first()
370
+ eq_(row, ("",))
371
+
372
+ def test_text_null_strings(self, connection):
373
+ text_table = self.tables.text_table
374
+
375
+ connection.execute(text_table.insert(), {"id": 1, "text_data": None})
376
+ row = connection.execute(select(text_table.c.text_data)).first()
377
+ eq_(row, (None,))
378
+
379
+ def test_literal(self, literal_round_trip):
380
+ literal_round_trip(Text, ["some text"], ["some text"])
381
+
382
+ @requirements.unicode_data_no_special_types
383
+ def test_literal_non_ascii(self, literal_round_trip):
384
+ literal_round_trip(Text, ["réve🐍 illé"], ["réve🐍 illé"])
385
+
386
+ def test_literal_quoting(self, literal_round_trip):
387
+ data = """some 'text' hey "hi there" that's text"""
388
+ literal_round_trip(Text, [data], [data])
389
+
390
+ def test_literal_backslashes(self, literal_round_trip):
391
+ data = r"backslash one \ backslash two \\ end"
392
+ literal_round_trip(Text, [data], [data])
393
+
394
+ def test_literal_percentsigns(self, literal_round_trip):
395
+ data = r"percent % signs %% percent"
396
+ literal_round_trip(Text, [data], [data])
397
+
398
+
399
+ class StringTest(_LiteralRoundTripFixture, fixtures.TestBase):
400
+ __backend__ = True
401
+
402
+ @requirements.unbounded_varchar
403
+ def test_nolength_string(self):
404
+ metadata = MetaData()
405
+ foo = Table("foo", metadata, Column("one", String))
406
+
407
+ foo.create(config.db)
408
+ foo.drop(config.db)
409
+
410
+ def test_literal(self, literal_round_trip):
411
+ # note that in Python 3, this invokes the Unicode
412
+ # datatype for the literal part because all strings are unicode
413
+ literal_round_trip(String(40), ["some text"], ["some text"])
414
+
415
+ @requirements.unicode_data_no_special_types
416
+ def test_literal_non_ascii(self, literal_round_trip):
417
+ literal_round_trip(String(40), ["réve🐍 illé"], ["réve🐍 illé"])
418
+
419
+ @testing.combinations(
420
+ ("%B%", ["AB", "BC"]),
421
+ ("A%C", ["AC"]),
422
+ ("A%C%Z", []),
423
+ argnames="expr, expected",
424
+ )
425
+ def test_dont_truncate_rightside(
426
+ self, metadata, connection, expr, expected
427
+ ):
428
+ t = Table("t", metadata, Column("x", String(2)))
429
+ t.create(connection)
430
+
431
+ connection.execute(t.insert(), [{"x": "AB"}, {"x": "BC"}, {"x": "AC"}])
432
+
433
+ eq_(
434
+ connection.scalars(select(t.c.x).where(t.c.x.like(expr))).all(),
435
+ expected,
436
+ )
437
+
438
+ def test_literal_quoting(self, literal_round_trip):
439
+ data = """some 'text' hey "hi there" that's text"""
440
+ literal_round_trip(String(40), [data], [data])
441
+
442
+ def test_literal_backslashes(self, literal_round_trip):
443
+ data = r"backslash one \ backslash two \\ end"
444
+ literal_round_trip(String(40), [data], [data])
445
+
446
+ def test_concatenate_binary(self, connection):
447
+ """dialects with special string concatenation operators should
448
+ implement visit_concat_op_binary() and visit_concat_op_clauselist()
449
+ in their compiler.
450
+
451
+ .. versionchanged:: 2.0 visit_concat_op_clauselist() is also needed
452
+ for dialects to override the string concatenation operator.
453
+
454
+ """
455
+ eq_(connection.scalar(select(literal("a") + "b")), "ab")
456
+
457
+ def test_concatenate_clauselist(self, connection):
458
+ """dialects with special string concatenation operators should
459
+ implement visit_concat_op_binary() and visit_concat_op_clauselist()
460
+ in their compiler.
461
+
462
+ .. versionchanged:: 2.0 visit_concat_op_clauselist() is also needed
463
+ for dialects to override the string concatenation operator.
464
+
465
+ """
466
+ eq_(
467
+ connection.scalar(select(literal("a") + "b" + "c" + "d" + "e")),
468
+ "abcde",
469
+ )
470
+
471
+
472
+ class IntervalTest(_LiteralRoundTripFixture, fixtures.TestBase):
473
+ __requires__ = ("datetime_interval",)
474
+ __backend__ = True
475
+
476
+ datatype = Interval
477
+ data = datetime.timedelta(days=1, seconds=4)
478
+
479
+ def test_literal(self, literal_round_trip):
480
+ literal_round_trip(self.datatype, [self.data], [self.data])
481
+
482
+ def test_select_direct_literal_interval(self, connection):
483
+ row = connection.execute(select(literal(self.data))).first()
484
+ eq_(row, (self.data,))
485
+
486
+ def test_arithmetic_operation_literal_interval(self, connection):
487
+ now = datetime.datetime.now().replace(microsecond=0)
488
+ # Able to subtract
489
+ row = connection.execute(
490
+ select(literal(now) - literal(self.data))
491
+ ).scalar()
492
+ eq_(row, now - self.data)
493
+
494
+ # Able to Add
495
+ row = connection.execute(
496
+ select(literal(now) + literal(self.data))
497
+ ).scalar()
498
+ eq_(row, now + self.data)
499
+
500
+ @testing.fixture
501
+ def arithmetic_table_fixture(cls, metadata, connection):
502
+ class Decorated(TypeDecorator):
503
+ impl = cls.datatype
504
+ cache_ok = True
505
+
506
+ it = Table(
507
+ "interval_table",
508
+ metadata,
509
+ Column(
510
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
511
+ ),
512
+ Column("interval_data", cls.datatype),
513
+ Column("date_data", DateTime),
514
+ Column("decorated_interval_data", Decorated),
515
+ )
516
+ it.create(connection)
517
+ return it
518
+
519
+ def test_arithmetic_operation_table_interval_and_literal_interval(
520
+ self, connection, arithmetic_table_fixture
521
+ ):
522
+ interval_table = arithmetic_table_fixture
523
+ data = datetime.timedelta(days=2, seconds=5)
524
+ connection.execute(
525
+ interval_table.insert(), {"id": 1, "interval_data": data}
526
+ )
527
+ # Subtraction Operation
528
+ value = connection.execute(
529
+ select(interval_table.c.interval_data - literal(self.data))
530
+ ).scalar()
531
+ eq_(value, data - self.data)
532
+
533
+ # Addition Operation
534
+ value = connection.execute(
535
+ select(interval_table.c.interval_data + literal(self.data))
536
+ ).scalar()
537
+ eq_(value, data + self.data)
538
+
539
+ def test_arithmetic_operation_table_date_and_literal_interval(
540
+ self, connection, arithmetic_table_fixture
541
+ ):
542
+ interval_table = arithmetic_table_fixture
543
+ now = datetime.datetime.now().replace(microsecond=0)
544
+ connection.execute(
545
+ interval_table.insert(), {"id": 1, "date_data": now}
546
+ )
547
+ # Subtraction Operation
548
+ value = connection.execute(
549
+ select(interval_table.c.date_data - literal(self.data))
550
+ ).scalar()
551
+ eq_(value, (now - self.data))
552
+
553
+ # Addition Operation
554
+ value = connection.execute(
555
+ select(interval_table.c.date_data + literal(self.data))
556
+ ).scalar()
557
+ eq_(value, (now + self.data))
558
+
559
+
560
+ class PrecisionIntervalTest(IntervalTest):
561
+ __requires__ = ("datetime_interval",)
562
+ __backend__ = True
563
+
564
+ datatype = Interval(day_precision=9, second_precision=9)
565
+ data = datetime.timedelta(days=103, seconds=4)
566
+
567
+
568
+ class _DateFixture(_LiteralRoundTripFixture, fixtures.TestBase):
569
+ compare = None
570
+
571
+ @classmethod
572
+ def define_tables(cls, metadata):
573
+ class Decorated(TypeDecorator):
574
+ impl = cls.datatype
575
+ cache_ok = True
576
+
577
+ Table(
578
+ "date_table",
579
+ metadata,
580
+ Column(
581
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
582
+ ),
583
+ Column("date_data", cls.datatype),
584
+ Column("decorated_date_data", Decorated),
585
+ )
586
+
587
+ def test_round_trip(self, connection):
588
+ date_table = self.tables.date_table
589
+
590
+ connection.execute(
591
+ date_table.insert(), {"id": 1, "date_data": self.data}
592
+ )
593
+
594
+ row = connection.execute(select(date_table.c.date_data)).first()
595
+
596
+ compare = self.compare or self.data
597
+ eq_(row, (compare,))
598
+ assert isinstance(row[0], type(compare))
599
+
600
+ def test_round_trip_decorated(self, connection):
601
+ date_table = self.tables.date_table
602
+
603
+ connection.execute(
604
+ date_table.insert(), {"id": 1, "decorated_date_data": self.data}
605
+ )
606
+
607
+ row = connection.execute(
608
+ select(date_table.c.decorated_date_data)
609
+ ).first()
610
+
611
+ compare = self.compare or self.data
612
+ eq_(row, (compare,))
613
+ assert isinstance(row[0], type(compare))
614
+
615
+ def test_null(self, connection):
616
+ date_table = self.tables.date_table
617
+
618
+ connection.execute(date_table.insert(), {"id": 1, "date_data": None})
619
+
620
+ row = connection.execute(select(date_table.c.date_data)).first()
621
+ eq_(row, (None,))
622
+
623
+ @testing.requires.datetime_literals
624
+ def test_literal(self, literal_round_trip):
625
+ compare = self.compare or self.data
626
+
627
+ literal_round_trip(
628
+ self.datatype, [self.data], [compare], compare=compare
629
+ )
630
+
631
+ @testing.requires.standalone_null_binds_whereclause
632
+ def test_null_bound_comparison(self):
633
+ # this test is based on an Oracle issue observed in #4886.
634
+ # passing NULL for an expression that needs to be interpreted as
635
+ # a certain type, does the DBAPI have the info it needs to do this.
636
+ date_table = self.tables.date_table
637
+ with config.db.begin() as conn:
638
+ result = conn.execute(
639
+ date_table.insert(), {"id": 1, "date_data": self.data}
640
+ )
641
+ id_ = result.inserted_primary_key[0]
642
+ stmt = select(date_table.c.id).where(
643
+ case(
644
+ (
645
+ bindparam("foo", type_=self.datatype) != None,
646
+ bindparam("foo", type_=self.datatype),
647
+ ),
648
+ else_=date_table.c.date_data,
649
+ )
650
+ == date_table.c.date_data
651
+ )
652
+
653
+ row = conn.execute(stmt, {"foo": None}).first()
654
+ eq_(row[0], id_)
655
+
656
+
657
+ class DateTimeTest(_DateFixture, fixtures.TablesTest):
658
+ __requires__ = ("datetime",)
659
+ __backend__ = True
660
+ datatype = DateTime
661
+ data = datetime.datetime(2012, 10, 15, 12, 57, 18)
662
+
663
+ @testing.requires.datetime_implicit_bound
664
+ def test_select_direct(self, connection):
665
+ result = connection.scalar(select(literal(self.data)))
666
+ eq_(result, self.data)
667
+
668
+
669
+ class DateTimeTZTest(_DateFixture, fixtures.TablesTest):
670
+ __requires__ = ("datetime_timezone",)
671
+ __backend__ = True
672
+ datatype = DateTime(timezone=True)
673
+ data = datetime.datetime(
674
+ 2012, 10, 15, 12, 57, 18, tzinfo=datetime.timezone.utc
675
+ )
676
+
677
+ @testing.requires.datetime_implicit_bound
678
+ def test_select_direct(self, connection):
679
+ result = connection.scalar(select(literal(self.data)))
680
+ eq_(result, self.data)
681
+
682
+
683
+ class DateTimeMicrosecondsTest(_DateFixture, fixtures.TablesTest):
684
+ __requires__ = ("datetime_microseconds",)
685
+ __backend__ = True
686
+ datatype = DateTime
687
+ data = datetime.datetime(2012, 10, 15, 12, 57, 18, 39642)
688
+
689
+
690
+ class TimestampMicrosecondsTest(_DateFixture, fixtures.TablesTest):
691
+ __requires__ = ("timestamp_microseconds",)
692
+ __backend__ = True
693
+ datatype = TIMESTAMP
694
+ data = datetime.datetime(2012, 10, 15, 12, 57, 18, 396)
695
+
696
+ @testing.requires.timestamp_microseconds_implicit_bound
697
+ def test_select_direct(self, connection):
698
+ result = connection.scalar(select(literal(self.data)))
699
+ eq_(result, self.data)
700
+
701
+
702
+ class TimeTest(_DateFixture, fixtures.TablesTest):
703
+ __requires__ = ("time",)
704
+ __backend__ = True
705
+ datatype = Time
706
+ data = datetime.time(12, 57, 18)
707
+
708
+ @testing.requires.time_implicit_bound
709
+ def test_select_direct(self, connection):
710
+ result = connection.scalar(select(literal(self.data)))
711
+ eq_(result, self.data)
712
+
713
+
714
+ class TimeTZTest(_DateFixture, fixtures.TablesTest):
715
+ __requires__ = ("time_timezone",)
716
+ __backend__ = True
717
+ datatype = Time(timezone=True)
718
+ data = datetime.time(12, 57, 18, tzinfo=datetime.timezone.utc)
719
+
720
+ @testing.requires.time_implicit_bound
721
+ def test_select_direct(self, connection):
722
+ result = connection.scalar(select(literal(self.data)))
723
+ eq_(result, self.data)
724
+
725
+
726
+ class TimeMicrosecondsTest(_DateFixture, fixtures.TablesTest):
727
+ __requires__ = ("time_microseconds",)
728
+ __backend__ = True
729
+ datatype = Time
730
+ data = datetime.time(12, 57, 18, 396)
731
+
732
+ @testing.requires.time_implicit_bound
733
+ def test_select_direct(self, connection):
734
+ result = connection.scalar(select(literal(self.data)))
735
+ eq_(result, self.data)
736
+
737
+
738
+ class DateTest(_DateFixture, fixtures.TablesTest):
739
+ __requires__ = ("date",)
740
+ __backend__ = True
741
+ datatype = Date
742
+ data = datetime.date(2012, 10, 15)
743
+
744
+ @testing.requires.date_implicit_bound
745
+ def test_select_direct(self, connection):
746
+ result = connection.scalar(select(literal(self.data)))
747
+ eq_(result, self.data)
748
+
749
+
750
+ class DateTimeCoercedToDateTimeTest(_DateFixture, fixtures.TablesTest):
751
+ """this particular suite is testing that datetime parameters get
752
+ coerced to dates, which tends to be something DBAPIs do.
753
+
754
+ """
755
+
756
+ __requires__ = "date", "date_coerces_from_datetime"
757
+ __backend__ = True
758
+ datatype = Date
759
+ data = datetime.datetime(2012, 10, 15, 12, 57, 18)
760
+ compare = datetime.date(2012, 10, 15)
761
+
762
+ @testing.requires.datetime_implicit_bound
763
+ def test_select_direct(self, connection):
764
+ result = connection.scalar(select(literal(self.data)))
765
+ eq_(result, self.data)
766
+
767
+
768
+ class DateTimeHistoricTest(_DateFixture, fixtures.TablesTest):
769
+ __requires__ = ("datetime_historic",)
770
+ __backend__ = True
771
+ datatype = DateTime
772
+ data = datetime.datetime(1850, 11, 10, 11, 52, 35)
773
+
774
+ @testing.requires.date_implicit_bound
775
+ def test_select_direct(self, connection):
776
+ result = connection.scalar(select(literal(self.data)))
777
+ eq_(result, self.data)
778
+
779
+
780
+ class DateHistoricTest(_DateFixture, fixtures.TablesTest):
781
+ __requires__ = ("date_historic",)
782
+ __backend__ = True
783
+ datatype = Date
784
+ data = datetime.date(1727, 4, 1)
785
+
786
+ @testing.requires.date_implicit_bound
787
+ def test_select_direct(self, connection):
788
+ result = connection.scalar(select(literal(self.data)))
789
+ eq_(result, self.data)
790
+
791
+
792
+ class IntegerTest(_LiteralRoundTripFixture, fixtures.TestBase):
793
+ __backend__ = True
794
+
795
+ def test_literal(self, literal_round_trip):
796
+ literal_round_trip(Integer, [5], [5])
797
+
798
+ def _huge_ints():
799
+ return testing.combinations(
800
+ 2147483649, # 32 bits
801
+ 2147483648, # 32 bits
802
+ 2147483647, # 31 bits
803
+ 2147483646, # 31 bits
804
+ -2147483649, # 32 bits
805
+ -2147483648, # 32 interestingly, asyncpg accepts this one as int32
806
+ -2147483647, # 31
807
+ -2147483646, # 31
808
+ 0,
809
+ 1376537018368127,
810
+ -1376537018368127,
811
+ argnames="intvalue",
812
+ )
813
+
814
+ @_huge_ints()
815
+ def test_huge_int_auto_accommodation(self, connection, intvalue):
816
+ """test #7909"""
817
+
818
+ eq_(
819
+ connection.scalar(
820
+ select(intvalue).where(literal(intvalue) == intvalue)
821
+ ),
822
+ intvalue,
823
+ )
824
+
825
+ @_huge_ints()
826
+ def test_huge_int(self, integer_round_trip, intvalue):
827
+ integer_round_trip(BigInteger, intvalue)
828
+
829
+ @testing.fixture
830
+ def integer_round_trip(self, metadata, connection):
831
+ def run(datatype, data):
832
+ int_table = Table(
833
+ "integer_table",
834
+ metadata,
835
+ Column(
836
+ "id",
837
+ Integer,
838
+ primary_key=True,
839
+ test_needs_autoincrement=True,
840
+ ),
841
+ Column("integer_data", datatype),
842
+ )
843
+
844
+ metadata.create_all(config.db)
845
+
846
+ connection.execute(
847
+ int_table.insert(), {"id": 1, "integer_data": data}
848
+ )
849
+
850
+ row = connection.execute(select(int_table.c.integer_data)).first()
851
+
852
+ eq_(row, (data,))
853
+
854
+ assert isinstance(row[0], int)
855
+
856
+ return run
857
+
858
+
859
+ class CastTypeDecoratorTest(_LiteralRoundTripFixture, fixtures.TestBase):
860
+ __backend__ = True
861
+
862
+ @testing.fixture
863
+ def string_as_int(self):
864
+ class StringAsInt(TypeDecorator):
865
+ impl = String(50)
866
+ cache_ok = True
867
+
868
+ def column_expression(self, col):
869
+ return cast(col, Integer)
870
+
871
+ def bind_expression(self, col):
872
+ return cast(type_coerce(col, Integer), String(50))
873
+
874
+ return StringAsInt()
875
+
876
+ def test_special_type(self, metadata, connection, string_as_int):
877
+ type_ = string_as_int
878
+
879
+ t = Table("t", metadata, Column("x", type_))
880
+ t.create(connection)
881
+
882
+ connection.execute(t.insert(), [{"x": x} for x in [1, 2, 3]])
883
+
884
+ result = {row[0] for row in connection.execute(t.select())}
885
+ eq_(result, {1, 2, 3})
886
+
887
+ result = {
888
+ row[0] for row in connection.execute(t.select().where(t.c.x == 2))
889
+ }
890
+ eq_(result, {2})
891
+
892
+
893
+ class TrueDivTest(fixtures.TestBase):
894
+ __backend__ = True
895
+
896
+ @testing.combinations(
897
+ ("15", "10", 1.5),
898
+ ("-15", "10", -1.5),
899
+ argnames="left, right, expected",
900
+ )
901
+ def test_truediv_integer(self, connection, left, right, expected):
902
+ """test #4926"""
903
+
904
+ eq_(
905
+ connection.scalar(
906
+ select(
907
+ literal_column(left, type_=Integer())
908
+ / literal_column(right, type_=Integer())
909
+ )
910
+ ),
911
+ expected,
912
+ )
913
+
914
+ @testing.combinations(
915
+ ("15", "10", 1), ("-15", "5", -3), argnames="left, right, expected"
916
+ )
917
+ def test_floordiv_integer(self, connection, left, right, expected):
918
+ """test #4926"""
919
+
920
+ eq_(
921
+ connection.scalar(
922
+ select(
923
+ literal_column(left, type_=Integer())
924
+ // literal_column(right, type_=Integer())
925
+ )
926
+ ),
927
+ expected,
928
+ )
929
+
930
+ @testing.combinations(
931
+ ("5.52", "2.4", "2.3"), argnames="left, right, expected"
932
+ )
933
+ def test_truediv_numeric(self, connection, left, right, expected):
934
+ """test #4926"""
935
+
936
+ eq_(
937
+ connection.scalar(
938
+ select(
939
+ literal_column(left, type_=Numeric(10, 2))
940
+ / literal_column(right, type_=Numeric(10, 2))
941
+ )
942
+ ),
943
+ decimal.Decimal(expected),
944
+ )
945
+
946
+ @testing.combinations(
947
+ ("5.52", "2.4", 2.3), argnames="left, right, expected"
948
+ )
949
+ def test_truediv_float(self, connection, left, right, expected):
950
+ """test #4926"""
951
+
952
+ eq_(
953
+ connection.scalar(
954
+ select(
955
+ literal_column(left, type_=Float())
956
+ / literal_column(right, type_=Float())
957
+ )
958
+ ),
959
+ expected,
960
+ )
961
+
962
+ @testing.combinations(
963
+ ("5.52", "2.4", "2.0"), argnames="left, right, expected"
964
+ )
965
+ def test_floordiv_numeric(self, connection, left, right, expected):
966
+ """test #4926"""
967
+
968
+ eq_(
969
+ connection.scalar(
970
+ select(
971
+ literal_column(left, type_=Numeric())
972
+ // literal_column(right, type_=Numeric())
973
+ )
974
+ ),
975
+ decimal.Decimal(expected),
976
+ )
977
+
978
+ def test_truediv_integer_bound(self, connection):
979
+ """test #4926"""
980
+
981
+ eq_(
982
+ connection.scalar(select(literal(15) / literal(10))),
983
+ 1.5,
984
+ )
985
+
986
+ def test_floordiv_integer_bound(self, connection):
987
+ """test #4926"""
988
+
989
+ eq_(
990
+ connection.scalar(select(literal(15) // literal(10))),
991
+ 1,
992
+ )
993
+
994
+
995
+ class NumericTest(_LiteralRoundTripFixture, fixtures.TestBase):
996
+ __backend__ = True
997
+
998
+ @testing.fixture
999
+ def do_numeric_test(self, metadata, connection):
1000
+ def run(type_, input_, output, filter_=None, check_scale=False):
1001
+ t = Table("t", metadata, Column("x", type_))
1002
+ t.create(connection)
1003
+ connection.execute(t.insert(), [{"x": x} for x in input_])
1004
+
1005
+ result = {row[0] for row in connection.execute(t.select())}
1006
+ output = set(output)
1007
+ if filter_:
1008
+ result = {filter_(x) for x in result}
1009
+ output = {filter_(x) for x in output}
1010
+ eq_(result, output)
1011
+ if check_scale:
1012
+ eq_([str(x) for x in result], [str(x) for x in output])
1013
+
1014
+ connection.execute(t.delete())
1015
+
1016
+ # test that this is actually a number!
1017
+ # note we have tiny scale here as we have tests with very
1018
+ # small scale Numeric types. PostgreSQL will raise an error
1019
+ # if you use values outside the available scale.
1020
+ if type_.asdecimal:
1021
+ test_value = decimal.Decimal("2.9")
1022
+ add_value = decimal.Decimal("37.12")
1023
+ else:
1024
+ test_value = 2.9
1025
+ add_value = 37.12
1026
+
1027
+ connection.execute(t.insert(), {"x": test_value})
1028
+ assert_we_are_a_number = connection.scalar(
1029
+ select(type_coerce(t.c.x + add_value, type_))
1030
+ )
1031
+ eq_(
1032
+ round(assert_we_are_a_number, 3),
1033
+ round(test_value + add_value, 3),
1034
+ )
1035
+
1036
+ return run
1037
+
1038
+ def test_render_literal_numeric(self, literal_round_trip):
1039
+ literal_round_trip(
1040
+ Numeric(precision=8, scale=4),
1041
+ [15.7563, decimal.Decimal("15.7563")],
1042
+ [decimal.Decimal("15.7563")],
1043
+ )
1044
+
1045
+ def test_render_literal_numeric_asfloat(self, literal_round_trip):
1046
+ literal_round_trip(
1047
+ Numeric(precision=8, scale=4, asdecimal=False),
1048
+ [15.7563, decimal.Decimal("15.7563")],
1049
+ [15.7563],
1050
+ )
1051
+
1052
+ def test_render_literal_float(self, literal_round_trip):
1053
+ literal_round_trip(
1054
+ Float(),
1055
+ [15.7563, decimal.Decimal("15.7563")],
1056
+ [15.7563],
1057
+ filter_=lambda n: n is not None and round(n, 5) or None,
1058
+ support_whereclause=False,
1059
+ )
1060
+
1061
+ @testing.requires.precision_generic_float_type
1062
+ def test_float_custom_scale(self, do_numeric_test):
1063
+ do_numeric_test(
1064
+ Float(None, decimal_return_scale=7, asdecimal=True),
1065
+ [15.7563827, decimal.Decimal("15.7563827")],
1066
+ [decimal.Decimal("15.7563827")],
1067
+ check_scale=True,
1068
+ )
1069
+
1070
+ def test_numeric_as_decimal(self, do_numeric_test):
1071
+ do_numeric_test(
1072
+ Numeric(precision=8, scale=4),
1073
+ [15.7563, decimal.Decimal("15.7563")],
1074
+ [decimal.Decimal("15.7563")],
1075
+ )
1076
+
1077
+ def test_numeric_as_float(self, do_numeric_test):
1078
+ do_numeric_test(
1079
+ Numeric(precision=8, scale=4, asdecimal=False),
1080
+ [15.7563, decimal.Decimal("15.7563")],
1081
+ [15.7563],
1082
+ )
1083
+
1084
+ @testing.requires.infinity_floats
1085
+ def test_infinity_floats(self, do_numeric_test):
1086
+ """test for #977, #7283"""
1087
+
1088
+ do_numeric_test(
1089
+ Float(None),
1090
+ [float("inf")],
1091
+ [float("inf")],
1092
+ )
1093
+
1094
+ @testing.requires.fetch_null_from_numeric
1095
+ def test_numeric_null_as_decimal(self, do_numeric_test):
1096
+ do_numeric_test(Numeric(precision=8, scale=4), [None], [None])
1097
+
1098
+ @testing.requires.fetch_null_from_numeric
1099
+ def test_numeric_null_as_float(self, do_numeric_test):
1100
+ do_numeric_test(
1101
+ Numeric(precision=8, scale=4, asdecimal=False), [None], [None]
1102
+ )
1103
+
1104
+ @testing.requires.floats_to_four_decimals
1105
+ def test_float_as_decimal(self, do_numeric_test):
1106
+ do_numeric_test(
1107
+ Float(asdecimal=True),
1108
+ [15.756, decimal.Decimal("15.756"), None],
1109
+ [decimal.Decimal("15.756"), None],
1110
+ filter_=lambda n: n is not None and round(n, 4) or None,
1111
+ )
1112
+
1113
+ def test_float_as_float(self, do_numeric_test):
1114
+ do_numeric_test(
1115
+ Float(),
1116
+ [15.756, decimal.Decimal("15.756")],
1117
+ [15.756],
1118
+ filter_=lambda n: n is not None and round(n, 5) or None,
1119
+ )
1120
+
1121
+ @testing.requires.literal_float_coercion
1122
+ def test_float_coerce_round_trip(self, connection):
1123
+ expr = 15.7563
1124
+
1125
+ val = connection.scalar(select(literal(expr)))
1126
+ eq_(val, expr)
1127
+
1128
+ # this does not work in MySQL, see #4036, however we choose not
1129
+ # to render CAST unconditionally since this is kind of an edge case.
1130
+
1131
+ @testing.requires.implicit_decimal_binds
1132
+ def test_decimal_coerce_round_trip(self, connection):
1133
+ expr = decimal.Decimal("15.7563")
1134
+
1135
+ val = connection.scalar(select(literal(expr)))
1136
+ eq_(val, expr)
1137
+
1138
+ def test_decimal_coerce_round_trip_w_cast(self, connection):
1139
+ expr = decimal.Decimal("15.7563")
1140
+
1141
+ val = connection.scalar(select(cast(expr, Numeric(10, 4))))
1142
+ eq_(val, expr)
1143
+
1144
+ @testing.requires.precision_numerics_general
1145
+ def test_precision_decimal(self, do_numeric_test):
1146
+ numbers = {
1147
+ decimal.Decimal("54.234246451650"),
1148
+ decimal.Decimal("0.004354"),
1149
+ decimal.Decimal("900.0"),
1150
+ }
1151
+
1152
+ do_numeric_test(Numeric(precision=18, scale=12), numbers, numbers)
1153
+
1154
+ @testing.requires.precision_numerics_enotation_large
1155
+ def test_enotation_decimal(self, do_numeric_test):
1156
+ """test exceedingly small decimals.
1157
+
1158
+ Decimal reports values with E notation when the exponent
1159
+ is greater than 6.
1160
+
1161
+ """
1162
+
1163
+ numbers = {
1164
+ decimal.Decimal("1E-2"),
1165
+ decimal.Decimal("1E-3"),
1166
+ decimal.Decimal("1E-4"),
1167
+ decimal.Decimal("1E-5"),
1168
+ decimal.Decimal("1E-6"),
1169
+ decimal.Decimal("1E-7"),
1170
+ decimal.Decimal("1E-8"),
1171
+ decimal.Decimal("0.01000005940696"),
1172
+ decimal.Decimal("0.00000005940696"),
1173
+ decimal.Decimal("0.00000000000696"),
1174
+ decimal.Decimal("0.70000000000696"),
1175
+ decimal.Decimal("696E-12"),
1176
+ }
1177
+ do_numeric_test(Numeric(precision=18, scale=14), numbers, numbers)
1178
+
1179
+ @testing.requires.precision_numerics_enotation_large
1180
+ def test_enotation_decimal_large(self, do_numeric_test):
1181
+ """test exceedingly large decimals."""
1182
+
1183
+ numbers = {
1184
+ decimal.Decimal("4E+8"),
1185
+ decimal.Decimal("5748E+15"),
1186
+ decimal.Decimal("1.521E+15"),
1187
+ decimal.Decimal("00000000000000.1E+12"),
1188
+ }
1189
+ do_numeric_test(Numeric(precision=25, scale=2), numbers, numbers)
1190
+
1191
+ @testing.requires.precision_numerics_many_significant_digits
1192
+ def test_many_significant_digits(self, do_numeric_test):
1193
+ numbers = {
1194
+ decimal.Decimal("31943874831932418390.01"),
1195
+ decimal.Decimal("319438950232418390.273596"),
1196
+ decimal.Decimal("87673.594069654243"),
1197
+ }
1198
+ do_numeric_test(Numeric(precision=38, scale=12), numbers, numbers)
1199
+
1200
+ @testing.requires.precision_numerics_retains_significant_digits
1201
+ def test_numeric_no_decimal(self, do_numeric_test):
1202
+ numbers = {decimal.Decimal("1.000")}
1203
+ do_numeric_test(
1204
+ Numeric(precision=5, scale=3), numbers, numbers, check_scale=True
1205
+ )
1206
+
1207
+ @testing.combinations(sqltypes.Float, sqltypes.Double, argnames="cls_")
1208
+ @testing.requires.float_is_numeric
1209
+ def test_float_is_not_numeric(self, connection, cls_):
1210
+ target_type = cls_().dialect_impl(connection.dialect)
1211
+ numeric_type = sqltypes.Numeric().dialect_impl(connection.dialect)
1212
+
1213
+ ne_(target_type.__visit_name__, numeric_type.__visit_name__)
1214
+ ne_(target_type.__class__, numeric_type.__class__)
1215
+
1216
+
1217
+ class BooleanTest(_LiteralRoundTripFixture, fixtures.TablesTest):
1218
+ __backend__ = True
1219
+
1220
+ @classmethod
1221
+ def define_tables(cls, metadata):
1222
+ Table(
1223
+ "boolean_table",
1224
+ metadata,
1225
+ Column("id", Integer, primary_key=True, autoincrement=False),
1226
+ Column("value", Boolean),
1227
+ Column("unconstrained_value", Boolean(create_constraint=False)),
1228
+ )
1229
+
1230
+ def test_render_literal_bool(self, literal_round_trip):
1231
+ literal_round_trip(Boolean(), [True, False], [True, False])
1232
+
1233
+ def test_round_trip(self, connection):
1234
+ boolean_table = self.tables.boolean_table
1235
+
1236
+ connection.execute(
1237
+ boolean_table.insert(),
1238
+ {"id": 1, "value": True, "unconstrained_value": False},
1239
+ )
1240
+
1241
+ row = connection.execute(
1242
+ select(boolean_table.c.value, boolean_table.c.unconstrained_value)
1243
+ ).first()
1244
+
1245
+ eq_(row, (True, False))
1246
+ assert isinstance(row[0], bool)
1247
+
1248
+ @testing.requires.nullable_booleans
1249
+ def test_null(self, connection):
1250
+ boolean_table = self.tables.boolean_table
1251
+
1252
+ connection.execute(
1253
+ boolean_table.insert(),
1254
+ {"id": 1, "value": None, "unconstrained_value": None},
1255
+ )
1256
+
1257
+ row = connection.execute(
1258
+ select(boolean_table.c.value, boolean_table.c.unconstrained_value)
1259
+ ).first()
1260
+
1261
+ eq_(row, (None, None))
1262
+
1263
+ def test_whereclause(self):
1264
+ # testing "WHERE <column>" renders a compatible expression
1265
+ boolean_table = self.tables.boolean_table
1266
+
1267
+ with config.db.begin() as conn:
1268
+ conn.execute(
1269
+ boolean_table.insert(),
1270
+ [
1271
+ {"id": 1, "value": True, "unconstrained_value": True},
1272
+ {"id": 2, "value": False, "unconstrained_value": False},
1273
+ ],
1274
+ )
1275
+
1276
+ eq_(
1277
+ conn.scalar(
1278
+ select(boolean_table.c.id).where(boolean_table.c.value)
1279
+ ),
1280
+ 1,
1281
+ )
1282
+ eq_(
1283
+ conn.scalar(
1284
+ select(boolean_table.c.id).where(
1285
+ boolean_table.c.unconstrained_value
1286
+ )
1287
+ ),
1288
+ 1,
1289
+ )
1290
+ eq_(
1291
+ conn.scalar(
1292
+ select(boolean_table.c.id).where(~boolean_table.c.value)
1293
+ ),
1294
+ 2,
1295
+ )
1296
+ eq_(
1297
+ conn.scalar(
1298
+ select(boolean_table.c.id).where(
1299
+ ~boolean_table.c.unconstrained_value
1300
+ )
1301
+ ),
1302
+ 2,
1303
+ )
1304
+
1305
+
1306
+ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest):
1307
+ __requires__ = ("json_type",)
1308
+ __backend__ = True
1309
+
1310
+ datatype = JSON
1311
+
1312
+ @classmethod
1313
+ def define_tables(cls, metadata):
1314
+ Table(
1315
+ "data_table",
1316
+ metadata,
1317
+ Column("id", Integer, primary_key=True),
1318
+ Column("name", String(30), nullable=False),
1319
+ Column("data", cls.datatype, nullable=False),
1320
+ Column("nulldata", cls.datatype(none_as_null=True)),
1321
+ )
1322
+
1323
+ def test_round_trip_data1(self, connection):
1324
+ self._test_round_trip({"key1": "value1", "key2": "value2"}, connection)
1325
+
1326
+ @testing.combinations(
1327
+ ("unicode", True), ("ascii", False), argnames="unicode_", id_="ia"
1328
+ )
1329
+ @testing.combinations(100, 1999, 3000, 4000, 5000, 9000, argnames="length")
1330
+ def test_round_trip_pretty_large_data(self, connection, unicode_, length):
1331
+ if unicode_:
1332
+ data = "réve🐍illé" * ((length // 9) + 1)
1333
+ data = data[0 : (length // 2)]
1334
+ else:
1335
+ data = "abcdefg" * ((length // 7) + 1)
1336
+ data = data[0:length]
1337
+
1338
+ self._test_round_trip({"key1": data, "key2": data}, connection)
1339
+
1340
+ def _test_round_trip(self, data_element, connection):
1341
+ data_table = self.tables.data_table
1342
+
1343
+ connection.execute(
1344
+ data_table.insert(),
1345
+ {"id": 1, "name": "row1", "data": data_element},
1346
+ )
1347
+
1348
+ row = connection.execute(select(data_table.c.data)).first()
1349
+
1350
+ eq_(row, (data_element,))
1351
+
1352
+ def _index_fixtures(include_comparison):
1353
+ if include_comparison:
1354
+ # basically SQL Server and MariaDB can kind of do json
1355
+ # comparison, MySQL, PG and SQLite can't. not worth it.
1356
+ json_elements = []
1357
+ else:
1358
+ json_elements = [
1359
+ ("json", {"foo": "bar"}),
1360
+ ("json", ["one", "two", "three"]),
1361
+ (None, {"foo": "bar"}),
1362
+ (None, ["one", "two", "three"]),
1363
+ ]
1364
+
1365
+ elements = [
1366
+ ("boolean", True),
1367
+ ("boolean", False),
1368
+ ("boolean", None),
1369
+ ("string", "some string"),
1370
+ ("string", None),
1371
+ ("string", "réve illé"),
1372
+ (
1373
+ "string",
1374
+ "réve🐍 illé",
1375
+ testing.requires.json_index_supplementary_unicode_element,
1376
+ ),
1377
+ ("integer", 15),
1378
+ ("integer", 1),
1379
+ ("integer", 0),
1380
+ ("integer", None),
1381
+ ("float", 28.5),
1382
+ ("float", None),
1383
+ ("float", 1234567.89, testing.requires.literal_float_coercion),
1384
+ ("numeric", 1234567.89),
1385
+ # this one "works" because the float value you see here is
1386
+ # lost immediately to floating point stuff
1387
+ (
1388
+ "numeric",
1389
+ 99998969694839.983485848,
1390
+ ),
1391
+ ("numeric", 99939.983485848),
1392
+ ("_decimal", decimal.Decimal("1234567.89")),
1393
+ (
1394
+ "_decimal",
1395
+ decimal.Decimal("99998969694839.983485848"),
1396
+ # fails on SQLite and MySQL (non-mariadb)
1397
+ requirements.cast_precision_numerics_many_significant_digits,
1398
+ ),
1399
+ (
1400
+ "_decimal",
1401
+ decimal.Decimal("99939.983485848"),
1402
+ ),
1403
+ ] + json_elements
1404
+
1405
+ def decorate(fn):
1406
+ fn = testing.combinations(id_="sa", *elements)(fn)
1407
+
1408
+ return fn
1409
+
1410
+ return decorate
1411
+
1412
+ def _json_value_insert(self, connection, datatype, value, data_element):
1413
+ data_table = self.tables.data_table
1414
+ if datatype == "_decimal":
1415
+ # Python's builtin json serializer basically doesn't support
1416
+ # Decimal objects without implicit float conversion period.
1417
+ # users can otherwise use simplejson which supports
1418
+ # precision decimals
1419
+
1420
+ # https://bugs.python.org/issue16535
1421
+
1422
+ # inserting as strings to avoid a new fixture around the
1423
+ # dialect which would have idiosyncrasies for different
1424
+ # backends.
1425
+
1426
+ class DecimalEncoder(json.JSONEncoder):
1427
+ def default(self, o):
1428
+ if isinstance(o, decimal.Decimal):
1429
+ return str(o)
1430
+ return super().default(o)
1431
+
1432
+ json_data = json.dumps(data_element, cls=DecimalEncoder)
1433
+
1434
+ # take the quotes out. yup, there is *literally* no other
1435
+ # way to get Python's json.dumps() to put all the digits in
1436
+ # the string
1437
+ json_data = re.sub(r'"(%s)"' % str(value), str(value), json_data)
1438
+
1439
+ datatype = "numeric"
1440
+
1441
+ connection.execute(
1442
+ data_table.insert().values(
1443
+ name="row1",
1444
+ # to pass the string directly to every backend, including
1445
+ # PostgreSQL which needs the value to be CAST as JSON
1446
+ # both in the SQL as well as at the prepared statement
1447
+ # level for asyncpg, while at the same time MySQL
1448
+ # doesn't even support CAST for JSON, here we are
1449
+ # sending the string embedded in the SQL without using
1450
+ # a parameter.
1451
+ data=bindparam(None, json_data, literal_execute=True),
1452
+ nulldata=bindparam(None, json_data, literal_execute=True),
1453
+ ),
1454
+ )
1455
+ else:
1456
+ connection.execute(
1457
+ data_table.insert(),
1458
+ {
1459
+ "name": "row1",
1460
+ "data": data_element,
1461
+ "nulldata": data_element,
1462
+ },
1463
+ )
1464
+
1465
+ p_s = None
1466
+
1467
+ if datatype:
1468
+ if datatype == "numeric":
1469
+ a, b = str(value).split(".")
1470
+ s = len(b)
1471
+ p = len(a) + s
1472
+
1473
+ if isinstance(value, decimal.Decimal):
1474
+ compare_value = value
1475
+ else:
1476
+ compare_value = decimal.Decimal(str(value))
1477
+
1478
+ p_s = (p, s)
1479
+ else:
1480
+ compare_value = value
1481
+ else:
1482
+ compare_value = value
1483
+
1484
+ return datatype, compare_value, p_s
1485
+
1486
+ @_index_fixtures(False)
1487
+ def test_index_typed_access(self, datatype, value):
1488
+ data_table = self.tables.data_table
1489
+ data_element = {"key1": value}
1490
+
1491
+ with config.db.begin() as conn:
1492
+ datatype, compare_value, p_s = self._json_value_insert(
1493
+ conn, datatype, value, data_element
1494
+ )
1495
+
1496
+ expr = data_table.c.data["key1"]
1497
+ if datatype:
1498
+ if datatype == "numeric" and p_s:
1499
+ expr = expr.as_numeric(*p_s)
1500
+ else:
1501
+ expr = getattr(expr, "as_%s" % datatype)()
1502
+
1503
+ roundtrip = conn.scalar(select(expr))
1504
+ eq_(roundtrip, compare_value)
1505
+ is_(type(roundtrip), type(compare_value))
1506
+
1507
+ @_index_fixtures(True)
1508
+ def test_index_typed_comparison(self, datatype, value):
1509
+ data_table = self.tables.data_table
1510
+ data_element = {"key1": value}
1511
+
1512
+ with config.db.begin() as conn:
1513
+ datatype, compare_value, p_s = self._json_value_insert(
1514
+ conn, datatype, value, data_element
1515
+ )
1516
+
1517
+ expr = data_table.c.data["key1"]
1518
+ if datatype:
1519
+ if datatype == "numeric" and p_s:
1520
+ expr = expr.as_numeric(*p_s)
1521
+ else:
1522
+ expr = getattr(expr, "as_%s" % datatype)()
1523
+
1524
+ row = conn.execute(
1525
+ select(expr).where(expr == compare_value)
1526
+ ).first()
1527
+
1528
+ # make sure we get a row even if value is None
1529
+ eq_(row, (compare_value,))
1530
+
1531
+ @_index_fixtures(True)
1532
+ def test_path_typed_comparison(self, datatype, value):
1533
+ data_table = self.tables.data_table
1534
+ data_element = {"key1": {"subkey1": value}}
1535
+ with config.db.begin() as conn:
1536
+ datatype, compare_value, p_s = self._json_value_insert(
1537
+ conn, datatype, value, data_element
1538
+ )
1539
+
1540
+ expr = data_table.c.data[("key1", "subkey1")]
1541
+
1542
+ if datatype:
1543
+ if datatype == "numeric" and p_s:
1544
+ expr = expr.as_numeric(*p_s)
1545
+ else:
1546
+ expr = getattr(expr, "as_%s" % datatype)()
1547
+
1548
+ row = conn.execute(
1549
+ select(expr).where(expr == compare_value)
1550
+ ).first()
1551
+
1552
+ # make sure we get a row even if value is None
1553
+ eq_(row, (compare_value,))
1554
+
1555
+ @testing.combinations(
1556
+ (True,),
1557
+ (False,),
1558
+ (None,),
1559
+ (15,),
1560
+ (0,),
1561
+ (-1,),
1562
+ (-1.0,),
1563
+ (15.052,),
1564
+ ("a string",),
1565
+ ("réve illé",),
1566
+ ("réve🐍 illé",),
1567
+ )
1568
+ def test_single_element_round_trip(self, element):
1569
+ data_table = self.tables.data_table
1570
+ data_element = element
1571
+ with config.db.begin() as conn:
1572
+ conn.execute(
1573
+ data_table.insert(),
1574
+ {
1575
+ "name": "row1",
1576
+ "data": data_element,
1577
+ "nulldata": data_element,
1578
+ },
1579
+ )
1580
+
1581
+ row = conn.execute(
1582
+ select(data_table.c.data, data_table.c.nulldata)
1583
+ ).first()
1584
+
1585
+ eq_(row, (data_element, data_element))
1586
+
1587
+ def test_round_trip_custom_json(self):
1588
+ data_table = self.tables.data_table
1589
+ data_element = {"key1": "data1"}
1590
+
1591
+ js = mock.Mock(side_effect=json.dumps)
1592
+ jd = mock.Mock(side_effect=json.loads)
1593
+ engine = engines.testing_engine(
1594
+ options=dict(json_serializer=js, json_deserializer=jd)
1595
+ )
1596
+
1597
+ # support sqlite :memory: database...
1598
+ data_table.create(engine, checkfirst=True)
1599
+ with engine.begin() as conn:
1600
+ conn.execute(
1601
+ data_table.insert(), {"name": "row1", "data": data_element}
1602
+ )
1603
+ row = conn.execute(select(data_table.c.data)).first()
1604
+
1605
+ eq_(row, (data_element,))
1606
+ eq_(js.mock_calls, [mock.call(data_element)])
1607
+ if testing.requires.json_deserializer_binary.enabled:
1608
+ eq_(
1609
+ jd.mock_calls,
1610
+ [mock.call(json.dumps(data_element).encode())],
1611
+ )
1612
+ else:
1613
+ eq_(jd.mock_calls, [mock.call(json.dumps(data_element))])
1614
+
1615
+ @testing.combinations(
1616
+ ("parameters",),
1617
+ ("multiparameters",),
1618
+ ("values",),
1619
+ ("omit",),
1620
+ argnames="insert_type",
1621
+ )
1622
+ def test_round_trip_none_as_sql_null(self, connection, insert_type):
1623
+ col = self.tables.data_table.c["nulldata"]
1624
+
1625
+ conn = connection
1626
+
1627
+ if insert_type == "parameters":
1628
+ stmt, params = self.tables.data_table.insert(), {
1629
+ "name": "r1",
1630
+ "nulldata": None,
1631
+ "data": None,
1632
+ }
1633
+ elif insert_type == "multiparameters":
1634
+ stmt, params = self.tables.data_table.insert(), [
1635
+ {"name": "r1", "nulldata": None, "data": None}
1636
+ ]
1637
+ elif insert_type == "values":
1638
+ stmt, params = (
1639
+ self.tables.data_table.insert().values(
1640
+ name="r1",
1641
+ nulldata=None,
1642
+ data=None,
1643
+ ),
1644
+ {},
1645
+ )
1646
+ elif insert_type == "omit":
1647
+ stmt, params = (
1648
+ self.tables.data_table.insert(),
1649
+ {"name": "r1", "data": None},
1650
+ )
1651
+
1652
+ else:
1653
+ assert False
1654
+
1655
+ conn.execute(stmt, params)
1656
+
1657
+ eq_(
1658
+ conn.scalar(
1659
+ select(self.tables.data_table.c.name).where(col.is_(null()))
1660
+ ),
1661
+ "r1",
1662
+ )
1663
+
1664
+ eq_(conn.scalar(select(col)), None)
1665
+
1666
+ def test_round_trip_json_null_as_json_null(self, connection):
1667
+ col = self.tables.data_table.c["data"]
1668
+
1669
+ conn = connection
1670
+ conn.execute(
1671
+ self.tables.data_table.insert(),
1672
+ {"name": "r1", "data": JSON.NULL},
1673
+ )
1674
+
1675
+ eq_(
1676
+ conn.scalar(
1677
+ select(self.tables.data_table.c.name).where(
1678
+ cast(col, String) == "null"
1679
+ )
1680
+ ),
1681
+ "r1",
1682
+ )
1683
+
1684
+ eq_(conn.scalar(select(col)), None)
1685
+
1686
+ @testing.combinations(
1687
+ ("parameters",),
1688
+ ("multiparameters",),
1689
+ ("values",),
1690
+ argnames="insert_type",
1691
+ )
1692
+ def test_round_trip_none_as_json_null(self, connection, insert_type):
1693
+ col = self.tables.data_table.c["data"]
1694
+
1695
+ if insert_type == "parameters":
1696
+ stmt, params = self.tables.data_table.insert(), {
1697
+ "name": "r1",
1698
+ "data": None,
1699
+ }
1700
+ elif insert_type == "multiparameters":
1701
+ stmt, params = self.tables.data_table.insert(), [
1702
+ {"name": "r1", "data": None}
1703
+ ]
1704
+ elif insert_type == "values":
1705
+ stmt, params = (
1706
+ self.tables.data_table.insert().values(name="r1", data=None),
1707
+ {},
1708
+ )
1709
+ else:
1710
+ assert False
1711
+
1712
+ conn = connection
1713
+ conn.execute(stmt, params)
1714
+
1715
+ eq_(
1716
+ conn.scalar(
1717
+ select(self.tables.data_table.c.name).where(
1718
+ cast(col, String) == "null"
1719
+ )
1720
+ ),
1721
+ "r1",
1722
+ )
1723
+
1724
+ eq_(conn.scalar(select(col)), None)
1725
+
1726
+ def test_unicode_round_trip(self):
1727
+ # note we include Unicode supplementary characters as well
1728
+ with config.db.begin() as conn:
1729
+ conn.execute(
1730
+ self.tables.data_table.insert(),
1731
+ {
1732
+ "name": "r1",
1733
+ "data": {
1734
+ "réve🐍 illé": "réve🐍 illé",
1735
+ "data": {"k1": "drôl🐍e"},
1736
+ },
1737
+ },
1738
+ )
1739
+
1740
+ eq_(
1741
+ conn.scalar(select(self.tables.data_table.c.data)),
1742
+ {
1743
+ "réve🐍 illé": "réve🐍 illé",
1744
+ "data": {"k1": "drôl🐍e"},
1745
+ },
1746
+ )
1747
+
1748
+ def test_eval_none_flag_orm(self, connection):
1749
+ Base = declarative_base()
1750
+
1751
+ class Data(Base):
1752
+ __table__ = self.tables.data_table
1753
+
1754
+ with Session(connection) as s:
1755
+ d1 = Data(name="d1", data=None, nulldata=None)
1756
+ s.add(d1)
1757
+ s.commit()
1758
+
1759
+ s.bulk_insert_mappings(
1760
+ Data, [{"name": "d2", "data": None, "nulldata": None}]
1761
+ )
1762
+ eq_(
1763
+ s.query(
1764
+ cast(self.tables.data_table.c.data, String()),
1765
+ cast(self.tables.data_table.c.nulldata, String),
1766
+ )
1767
+ .filter(self.tables.data_table.c.name == "d1")
1768
+ .first(),
1769
+ ("null", None),
1770
+ )
1771
+ eq_(
1772
+ s.query(
1773
+ cast(self.tables.data_table.c.data, String()),
1774
+ cast(self.tables.data_table.c.nulldata, String),
1775
+ )
1776
+ .filter(self.tables.data_table.c.name == "d2")
1777
+ .first(),
1778
+ ("null", None),
1779
+ )
1780
+
1781
+
1782
+ class JSONLegacyStringCastIndexTest(
1783
+ _LiteralRoundTripFixture, fixtures.TablesTest
1784
+ ):
1785
+ """test JSON index access with "cast to string", which we have documented
1786
+ for a long time as how to compare JSON values, but is ultimately not
1787
+ reliable in all cases. The "as_XYZ()" comparators should be used
1788
+ instead.
1789
+
1790
+ """
1791
+
1792
+ __requires__ = ("json_type", "legacy_unconditional_json_extract")
1793
+ __backend__ = True
1794
+
1795
+ datatype = JSON
1796
+
1797
+ data1 = {"key1": "value1", "key2": "value2"}
1798
+
1799
+ data2 = {
1800
+ "Key 'One'": "value1",
1801
+ "key two": "value2",
1802
+ "key three": "value ' three '",
1803
+ }
1804
+
1805
+ data3 = {
1806
+ "key1": [1, 2, 3],
1807
+ "key2": ["one", "two", "three"],
1808
+ "key3": [{"four": "five"}, {"six": "seven"}],
1809
+ }
1810
+
1811
+ data4 = ["one", "two", "three"]
1812
+
1813
+ data5 = {
1814
+ "nested": {
1815
+ "elem1": [{"a": "b", "c": "d"}, {"e": "f", "g": "h"}],
1816
+ "elem2": {"elem3": {"elem4": "elem5"}},
1817
+ }
1818
+ }
1819
+
1820
+ data6 = {"a": 5, "b": "some value", "c": {"foo": "bar"}}
1821
+
1822
+ @classmethod
1823
+ def define_tables(cls, metadata):
1824
+ Table(
1825
+ "data_table",
1826
+ metadata,
1827
+ Column("id", Integer, primary_key=True),
1828
+ Column("name", String(30), nullable=False),
1829
+ Column("data", cls.datatype),
1830
+ Column("nulldata", cls.datatype(none_as_null=True)),
1831
+ )
1832
+
1833
+ def _criteria_fixture(self):
1834
+ with config.db.begin() as conn:
1835
+ conn.execute(
1836
+ self.tables.data_table.insert(),
1837
+ [
1838
+ {"name": "r1", "data": self.data1},
1839
+ {"name": "r2", "data": self.data2},
1840
+ {"name": "r3", "data": self.data3},
1841
+ {"name": "r4", "data": self.data4},
1842
+ {"name": "r5", "data": self.data5},
1843
+ {"name": "r6", "data": self.data6},
1844
+ ],
1845
+ )
1846
+
1847
+ def _test_index_criteria(self, crit, expected, test_literal=True):
1848
+ self._criteria_fixture()
1849
+ with config.db.connect() as conn:
1850
+ stmt = select(self.tables.data_table.c.name).where(crit)
1851
+
1852
+ eq_(conn.scalar(stmt), expected)
1853
+
1854
+ if test_literal:
1855
+ literal_sql = str(
1856
+ stmt.compile(
1857
+ config.db, compile_kwargs={"literal_binds": True}
1858
+ )
1859
+ )
1860
+
1861
+ eq_(conn.exec_driver_sql(literal_sql).scalar(), expected)
1862
+
1863
+ def test_string_cast_crit_spaces_in_key(self):
1864
+ name = self.tables.data_table.c.name
1865
+ col = self.tables.data_table.c["data"]
1866
+
1867
+ # limit the rows here to avoid PG error
1868
+ # "cannot extract field from a non-object", which is
1869
+ # fixed in 9.4 but may exist in 9.3
1870
+ self._test_index_criteria(
1871
+ and_(
1872
+ name.in_(["r1", "r2", "r3"]),
1873
+ cast(col["key two"], String) == '"value2"',
1874
+ ),
1875
+ "r2",
1876
+ )
1877
+
1878
+ @config.requirements.json_array_indexes
1879
+ def test_string_cast_crit_simple_int(self):
1880
+ name = self.tables.data_table.c.name
1881
+ col = self.tables.data_table.c["data"]
1882
+
1883
+ # limit the rows here to avoid PG error
1884
+ # "cannot extract array element from a non-array", which is
1885
+ # fixed in 9.4 but may exist in 9.3
1886
+ self._test_index_criteria(
1887
+ and_(
1888
+ name == "r4",
1889
+ cast(col[1], String) == '"two"',
1890
+ ),
1891
+ "r4",
1892
+ )
1893
+
1894
+ def test_string_cast_crit_mixed_path(self):
1895
+ col = self.tables.data_table.c["data"]
1896
+ self._test_index_criteria(
1897
+ cast(col[("key3", 1, "six")], String) == '"seven"',
1898
+ "r3",
1899
+ )
1900
+
1901
+ def test_string_cast_crit_string_path(self):
1902
+ col = self.tables.data_table.c["data"]
1903
+ self._test_index_criteria(
1904
+ cast(col[("nested", "elem2", "elem3", "elem4")], String)
1905
+ == '"elem5"',
1906
+ "r5",
1907
+ )
1908
+
1909
+ def test_string_cast_crit_against_string_basic(self):
1910
+ name = self.tables.data_table.c.name
1911
+ col = self.tables.data_table.c["data"]
1912
+
1913
+ self._test_index_criteria(
1914
+ and_(
1915
+ name == "r6",
1916
+ cast(col["b"], String) == '"some value"',
1917
+ ),
1918
+ "r6",
1919
+ )
1920
+
1921
+
1922
+ class EnumTest(_LiteralRoundTripFixture, fixtures.TablesTest):
1923
+ __backend__ = True
1924
+
1925
+ enum_values = "a", "b", "a%", "b%percent", "réveillé"
1926
+
1927
+ datatype = Enum(*enum_values, name="myenum")
1928
+
1929
+ @classmethod
1930
+ def define_tables(cls, metadata):
1931
+ Table(
1932
+ "enum_table",
1933
+ metadata,
1934
+ Column("id", Integer, primary_key=True),
1935
+ Column("enum_data", cls.datatype),
1936
+ )
1937
+
1938
+ @testing.combinations(*enum_values, argnames="data")
1939
+ def test_round_trip(self, data, connection):
1940
+ connection.execute(
1941
+ self.tables.enum_table.insert(), {"id": 1, "enum_data": data}
1942
+ )
1943
+
1944
+ eq_(
1945
+ connection.scalar(
1946
+ select(self.tables.enum_table.c.enum_data).where(
1947
+ self.tables.enum_table.c.id == 1
1948
+ )
1949
+ ),
1950
+ data,
1951
+ )
1952
+
1953
+ def test_round_trip_executemany(self, connection):
1954
+ connection.execute(
1955
+ self.tables.enum_table.insert(),
1956
+ [
1957
+ {"id": 1, "enum_data": "b%percent"},
1958
+ {"id": 2, "enum_data": "réveillé"},
1959
+ {"id": 3, "enum_data": "b"},
1960
+ {"id": 4, "enum_data": "a%"},
1961
+ ],
1962
+ )
1963
+
1964
+ eq_(
1965
+ connection.scalars(
1966
+ select(self.tables.enum_table.c.enum_data).order_by(
1967
+ self.tables.enum_table.c.id
1968
+ )
1969
+ ).all(),
1970
+ ["b%percent", "réveillé", "b", "a%"],
1971
+ )
1972
+
1973
+ @testing.requires.insert_executemany_returning
1974
+ def test_round_trip_executemany_returning(self, connection):
1975
+ result = connection.execute(
1976
+ self.tables.enum_table.insert().returning(
1977
+ self.tables.enum_table.c.enum_data
1978
+ ),
1979
+ [
1980
+ {"id": 1, "enum_data": "b%percent"},
1981
+ {"id": 2, "enum_data": "réveillé"},
1982
+ {"id": 3, "enum_data": "b"},
1983
+ {"id": 4, "enum_data": "a%"},
1984
+ ],
1985
+ )
1986
+
1987
+ eq_(result.scalars().all(), ["b%percent", "réveillé", "b", "a%"])
1988
+
1989
+
1990
+ class UuidTest(_LiteralRoundTripFixture, fixtures.TablesTest):
1991
+ __backend__ = True
1992
+
1993
+ datatype = Uuid
1994
+
1995
+ @classmethod
1996
+ def define_tables(cls, metadata):
1997
+ Table(
1998
+ "uuid_table",
1999
+ metadata,
2000
+ Column(
2001
+ "id", Integer, primary_key=True, test_needs_autoincrement=True
2002
+ ),
2003
+ Column("uuid_data", cls.datatype),
2004
+ Column("uuid_text_data", cls.datatype(as_uuid=False)),
2005
+ Column("uuid_data_nonnative", Uuid(native_uuid=False)),
2006
+ Column(
2007
+ "uuid_text_data_nonnative",
2008
+ Uuid(as_uuid=False, native_uuid=False),
2009
+ ),
2010
+ )
2011
+
2012
+ def test_uuid_round_trip(self, connection):
2013
+ data = uuid.uuid4()
2014
+ uuid_table = self.tables.uuid_table
2015
+
2016
+ connection.execute(
2017
+ uuid_table.insert(),
2018
+ {"id": 1, "uuid_data": data, "uuid_data_nonnative": data},
2019
+ )
2020
+ row = connection.execute(
2021
+ select(
2022
+ uuid_table.c.uuid_data, uuid_table.c.uuid_data_nonnative
2023
+ ).where(
2024
+ uuid_table.c.uuid_data == data,
2025
+ uuid_table.c.uuid_data_nonnative == data,
2026
+ )
2027
+ ).first()
2028
+ eq_(row, (data, data))
2029
+
2030
+ def test_uuid_text_round_trip(self, connection):
2031
+ data = str(uuid.uuid4())
2032
+ uuid_table = self.tables.uuid_table
2033
+
2034
+ connection.execute(
2035
+ uuid_table.insert(),
2036
+ {
2037
+ "id": 1,
2038
+ "uuid_text_data": data,
2039
+ "uuid_text_data_nonnative": data,
2040
+ },
2041
+ )
2042
+ row = connection.execute(
2043
+ select(
2044
+ uuid_table.c.uuid_text_data,
2045
+ uuid_table.c.uuid_text_data_nonnative,
2046
+ ).where(
2047
+ uuid_table.c.uuid_text_data == data,
2048
+ uuid_table.c.uuid_text_data_nonnative == data,
2049
+ )
2050
+ ).first()
2051
+ eq_((row[0].lower(), row[1].lower()), (data, data))
2052
+
2053
+ def test_literal_uuid(self, literal_round_trip):
2054
+ data = uuid.uuid4()
2055
+ literal_round_trip(self.datatype, [data], [data])
2056
+
2057
+ def test_literal_text(self, literal_round_trip):
2058
+ data = str(uuid.uuid4())
2059
+ literal_round_trip(
2060
+ self.datatype(as_uuid=False),
2061
+ [data],
2062
+ [data],
2063
+ filter_=lambda x: x.lower(),
2064
+ )
2065
+
2066
+ def test_literal_nonnative_uuid(self, literal_round_trip):
2067
+ data = uuid.uuid4()
2068
+ literal_round_trip(Uuid(native_uuid=False), [data], [data])
2069
+
2070
+ def test_literal_nonnative_text(self, literal_round_trip):
2071
+ data = str(uuid.uuid4())
2072
+ literal_round_trip(
2073
+ Uuid(as_uuid=False, native_uuid=False),
2074
+ [data],
2075
+ [data],
2076
+ filter_=lambda x: x.lower(),
2077
+ )
2078
+
2079
+ @testing.requires.insert_returning
2080
+ def test_uuid_returning(self, connection):
2081
+ data = uuid.uuid4()
2082
+ str_data = str(data)
2083
+ uuid_table = self.tables.uuid_table
2084
+
2085
+ result = connection.execute(
2086
+ uuid_table.insert().returning(
2087
+ uuid_table.c.uuid_data,
2088
+ uuid_table.c.uuid_text_data,
2089
+ uuid_table.c.uuid_data_nonnative,
2090
+ uuid_table.c.uuid_text_data_nonnative,
2091
+ ),
2092
+ {
2093
+ "id": 1,
2094
+ "uuid_data": data,
2095
+ "uuid_text_data": str_data,
2096
+ "uuid_data_nonnative": data,
2097
+ "uuid_text_data_nonnative": str_data,
2098
+ },
2099
+ )
2100
+ row = result.first()
2101
+
2102
+ eq_(row, (data, str_data, data, str_data))
2103
+
2104
+
2105
+ class NativeUUIDTest(UuidTest):
2106
+ __requires__ = ("uuid_data_type",)
2107
+
2108
+ datatype = UUID
2109
+
2110
+
2111
+ __all__ = (
2112
+ "ArrayTest",
2113
+ "BinaryTest",
2114
+ "UnicodeVarcharTest",
2115
+ "UnicodeTextTest",
2116
+ "JSONTest",
2117
+ "JSONLegacyStringCastIndexTest",
2118
+ "DateTest",
2119
+ "DateTimeTest",
2120
+ "DateTimeTZTest",
2121
+ "TextTest",
2122
+ "NumericTest",
2123
+ "IntegerTest",
2124
+ "IntervalTest",
2125
+ "PrecisionIntervalTest",
2126
+ "CastTypeDecoratorTest",
2127
+ "DateTimeHistoricTest",
2128
+ "DateTimeCoercedToDateTimeTest",
2129
+ "TimeMicrosecondsTest",
2130
+ "TimestampMicrosecondsTest",
2131
+ "TimeTest",
2132
+ "TimeTZTest",
2133
+ "TrueDivTest",
2134
+ "DateTimeMicrosecondsTest",
2135
+ "DateHistoricTest",
2136
+ "StringTest",
2137
+ "BooleanTest",
2138
+ "EnumTest",
2139
+ "UuidTest",
2140
+ "NativeUUIDTest",
2141
+ )