SQLAlchemy 2.0.36__cp313-cp313-win_amd64.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-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.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,1999 @@
1
+ # testing/suite/test_select.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
+ import collections.abc as collections_abc
10
+ import itertools
11
+
12
+ from .. import AssertsCompiledSQL
13
+ from .. import AssertsExecutionResults
14
+ from .. import config
15
+ from .. import fixtures
16
+ from ..assertions import assert_raises
17
+ from ..assertions import eq_
18
+ from ..assertions import in_
19
+ from ..assertsql import CursorSQL
20
+ from ..schema import Column
21
+ from ..schema import Table
22
+ from ... import bindparam
23
+ from ... import case
24
+ from ... import column
25
+ from ... import Computed
26
+ from ... import exists
27
+ from ... import false
28
+ from ... import ForeignKey
29
+ from ... import func
30
+ from ... import Identity
31
+ from ... import Integer
32
+ from ... import literal
33
+ from ... import literal_column
34
+ from ... import null
35
+ from ... import select
36
+ from ... import String
37
+ from ... import table
38
+ from ... import testing
39
+ from ... import text
40
+ from ... import true
41
+ from ... import tuple_
42
+ from ... import TupleType
43
+ from ... import union
44
+ from ... import values
45
+ from ...exc import DatabaseError
46
+ from ...exc import ProgrammingError
47
+
48
+
49
+ class CollateTest(fixtures.TablesTest):
50
+ __backend__ = True
51
+
52
+ @classmethod
53
+ def define_tables(cls, metadata):
54
+ Table(
55
+ "some_table",
56
+ metadata,
57
+ Column("id", Integer, primary_key=True),
58
+ Column("data", String(100)),
59
+ )
60
+
61
+ @classmethod
62
+ def insert_data(cls, connection):
63
+ connection.execute(
64
+ cls.tables.some_table.insert(),
65
+ [
66
+ {"id": 1, "data": "collate data1"},
67
+ {"id": 2, "data": "collate data2"},
68
+ ],
69
+ )
70
+
71
+ def _assert_result(self, select, result):
72
+ with config.db.connect() as conn:
73
+ eq_(conn.execute(select).fetchall(), result)
74
+
75
+ @testing.requires.order_by_collation
76
+ def test_collate_order_by(self):
77
+ collation = testing.requires.get_order_by_collation(testing.config)
78
+
79
+ self._assert_result(
80
+ select(self.tables.some_table).order_by(
81
+ self.tables.some_table.c.data.collate(collation).asc()
82
+ ),
83
+ [(1, "collate data1"), (2, "collate data2")],
84
+ )
85
+
86
+
87
+ class OrderByLabelTest(fixtures.TablesTest):
88
+ """Test the dialect sends appropriate ORDER BY expressions when
89
+ labels are used.
90
+
91
+ This essentially exercises the "supports_simple_order_by_label"
92
+ setting.
93
+
94
+ """
95
+
96
+ __backend__ = True
97
+
98
+ @classmethod
99
+ def define_tables(cls, metadata):
100
+ Table(
101
+ "some_table",
102
+ metadata,
103
+ Column("id", Integer, primary_key=True),
104
+ Column("x", Integer),
105
+ Column("y", Integer),
106
+ Column("q", String(50)),
107
+ Column("p", String(50)),
108
+ )
109
+
110
+ @classmethod
111
+ def insert_data(cls, connection):
112
+ connection.execute(
113
+ cls.tables.some_table.insert(),
114
+ [
115
+ {"id": 1, "x": 1, "y": 2, "q": "q1", "p": "p3"},
116
+ {"id": 2, "x": 2, "y": 3, "q": "q2", "p": "p2"},
117
+ {"id": 3, "x": 3, "y": 4, "q": "q3", "p": "p1"},
118
+ ],
119
+ )
120
+
121
+ def _assert_result(self, select, result):
122
+ with config.db.connect() as conn:
123
+ eq_(conn.execute(select).fetchall(), result)
124
+
125
+ def test_plain(self):
126
+ table = self.tables.some_table
127
+ lx = table.c.x.label("lx")
128
+ self._assert_result(select(lx).order_by(lx), [(1,), (2,), (3,)])
129
+
130
+ def test_composed_int(self):
131
+ table = self.tables.some_table
132
+ lx = (table.c.x + table.c.y).label("lx")
133
+ self._assert_result(select(lx).order_by(lx), [(3,), (5,), (7,)])
134
+
135
+ def test_composed_multiple(self):
136
+ table = self.tables.some_table
137
+ lx = (table.c.x + table.c.y).label("lx")
138
+ ly = (func.lower(table.c.q) + table.c.p).label("ly")
139
+ self._assert_result(
140
+ select(lx, ly).order_by(lx, ly.desc()),
141
+ [(3, "q1p3"), (5, "q2p2"), (7, "q3p1")],
142
+ )
143
+
144
+ def test_plain_desc(self):
145
+ table = self.tables.some_table
146
+ lx = table.c.x.label("lx")
147
+ self._assert_result(select(lx).order_by(lx.desc()), [(3,), (2,), (1,)])
148
+
149
+ def test_composed_int_desc(self):
150
+ table = self.tables.some_table
151
+ lx = (table.c.x + table.c.y).label("lx")
152
+ self._assert_result(select(lx).order_by(lx.desc()), [(7,), (5,), (3,)])
153
+
154
+ @testing.requires.group_by_complex_expression
155
+ def test_group_by_composed(self):
156
+ table = self.tables.some_table
157
+ expr = (table.c.x + table.c.y).label("lx")
158
+ stmt = (
159
+ select(func.count(table.c.id), expr).group_by(expr).order_by(expr)
160
+ )
161
+ self._assert_result(stmt, [(1, 3), (1, 5), (1, 7)])
162
+
163
+
164
+ class ValuesExpressionTest(fixtures.TestBase):
165
+ __requires__ = ("table_value_constructor",)
166
+
167
+ __backend__ = True
168
+
169
+ def test_tuples(self, connection):
170
+ value_expr = values(
171
+ column("id", Integer), column("name", String), name="my_values"
172
+ ).data([(1, "name1"), (2, "name2"), (3, "name3")])
173
+
174
+ eq_(
175
+ connection.execute(select(value_expr)).all(),
176
+ [(1, "name1"), (2, "name2"), (3, "name3")],
177
+ )
178
+
179
+
180
+ class FetchLimitOffsetTest(fixtures.TablesTest):
181
+ __backend__ = True
182
+
183
+ @classmethod
184
+ def define_tables(cls, metadata):
185
+ Table(
186
+ "some_table",
187
+ metadata,
188
+ Column("id", Integer, primary_key=True),
189
+ Column("x", Integer),
190
+ Column("y", Integer),
191
+ )
192
+
193
+ @classmethod
194
+ def insert_data(cls, connection):
195
+ connection.execute(
196
+ cls.tables.some_table.insert(),
197
+ [
198
+ {"id": 1, "x": 1, "y": 2},
199
+ {"id": 2, "x": 2, "y": 3},
200
+ {"id": 3, "x": 3, "y": 4},
201
+ {"id": 4, "x": 4, "y": 5},
202
+ {"id": 5, "x": 4, "y": 6},
203
+ ],
204
+ )
205
+
206
+ def _assert_result(
207
+ self, connection, select, result, params=(), set_=False
208
+ ):
209
+ if set_:
210
+ query_res = connection.execute(select, params).fetchall()
211
+ eq_(len(query_res), len(result))
212
+ eq_(set(query_res), set(result))
213
+
214
+ else:
215
+ eq_(connection.execute(select, params).fetchall(), result)
216
+
217
+ def _assert_result_str(self, select, result, params=()):
218
+ with config.db.connect() as conn:
219
+ eq_(conn.exec_driver_sql(select, params).fetchall(), result)
220
+
221
+ def test_simple_limit(self, connection):
222
+ table = self.tables.some_table
223
+ stmt = select(table).order_by(table.c.id)
224
+ self._assert_result(
225
+ connection,
226
+ stmt.limit(2),
227
+ [(1, 1, 2), (2, 2, 3)],
228
+ )
229
+ self._assert_result(
230
+ connection,
231
+ stmt.limit(3),
232
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4)],
233
+ )
234
+
235
+ def test_limit_render_multiple_times(self, connection):
236
+ table = self.tables.some_table
237
+ stmt = select(table.c.id).limit(1).scalar_subquery()
238
+
239
+ u = union(select(stmt), select(stmt)).subquery().select()
240
+
241
+ self._assert_result(
242
+ connection,
243
+ u,
244
+ [
245
+ (1,),
246
+ ],
247
+ )
248
+
249
+ @testing.requires.fetch_first
250
+ def test_simple_fetch(self, connection):
251
+ table = self.tables.some_table
252
+ self._assert_result(
253
+ connection,
254
+ select(table).order_by(table.c.id).fetch(2),
255
+ [(1, 1, 2), (2, 2, 3)],
256
+ )
257
+ self._assert_result(
258
+ connection,
259
+ select(table).order_by(table.c.id).fetch(3),
260
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4)],
261
+ )
262
+
263
+ @testing.requires.offset
264
+ def test_simple_offset(self, connection):
265
+ table = self.tables.some_table
266
+ self._assert_result(
267
+ connection,
268
+ select(table).order_by(table.c.id).offset(2),
269
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
270
+ )
271
+ self._assert_result(
272
+ connection,
273
+ select(table).order_by(table.c.id).offset(3),
274
+ [(4, 4, 5), (5, 4, 6)],
275
+ )
276
+
277
+ @testing.combinations(
278
+ ([(2, 0), (2, 1), (3, 2)]),
279
+ ([(2, 1), (2, 0), (3, 2)]),
280
+ ([(3, 1), (2, 1), (3, 1)]),
281
+ argnames="cases",
282
+ )
283
+ @testing.requires.offset
284
+ def test_simple_limit_offset(self, connection, cases):
285
+ table = self.tables.some_table
286
+ connection = connection.execution_options(compiled_cache={})
287
+
288
+ assert_data = [(1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5), (5, 4, 6)]
289
+
290
+ for limit, offset in cases:
291
+ expected = assert_data[offset : offset + limit]
292
+ self._assert_result(
293
+ connection,
294
+ select(table).order_by(table.c.id).limit(limit).offset(offset),
295
+ expected,
296
+ )
297
+
298
+ @testing.requires.fetch_first
299
+ def test_simple_fetch_offset(self, connection):
300
+ table = self.tables.some_table
301
+ self._assert_result(
302
+ connection,
303
+ select(table).order_by(table.c.id).fetch(2).offset(1),
304
+ [(2, 2, 3), (3, 3, 4)],
305
+ )
306
+
307
+ self._assert_result(
308
+ connection,
309
+ select(table).order_by(table.c.id).fetch(3).offset(2),
310
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
311
+ )
312
+
313
+ @testing.requires.fetch_no_order_by
314
+ def test_fetch_offset_no_order(self, connection):
315
+ table = self.tables.some_table
316
+ self._assert_result(
317
+ connection,
318
+ select(table).fetch(10),
319
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5), (5, 4, 6)],
320
+ set_=True,
321
+ )
322
+
323
+ @testing.requires.offset
324
+ def test_simple_offset_zero(self, connection):
325
+ table = self.tables.some_table
326
+ self._assert_result(
327
+ connection,
328
+ select(table).order_by(table.c.id).offset(0),
329
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5), (5, 4, 6)],
330
+ )
331
+
332
+ self._assert_result(
333
+ connection,
334
+ select(table).order_by(table.c.id).offset(1),
335
+ [(2, 2, 3), (3, 3, 4), (4, 4, 5), (5, 4, 6)],
336
+ )
337
+
338
+ @testing.requires.offset
339
+ def test_limit_offset_nobinds(self):
340
+ """test that 'literal binds' mode works - no bound params."""
341
+
342
+ table = self.tables.some_table
343
+ stmt = select(table).order_by(table.c.id).limit(2).offset(1)
344
+ sql = stmt.compile(
345
+ dialect=config.db.dialect, compile_kwargs={"literal_binds": True}
346
+ )
347
+ sql = str(sql)
348
+
349
+ self._assert_result_str(sql, [(2, 2, 3), (3, 3, 4)])
350
+
351
+ @testing.requires.fetch_first
352
+ def test_fetch_offset_nobinds(self):
353
+ """test that 'literal binds' mode works - no bound params."""
354
+
355
+ table = self.tables.some_table
356
+ stmt = select(table).order_by(table.c.id).fetch(2).offset(1)
357
+ sql = stmt.compile(
358
+ dialect=config.db.dialect, compile_kwargs={"literal_binds": True}
359
+ )
360
+ sql = str(sql)
361
+
362
+ self._assert_result_str(sql, [(2, 2, 3), (3, 3, 4)])
363
+
364
+ @testing.requires.bound_limit_offset
365
+ def test_bound_limit(self, connection):
366
+ table = self.tables.some_table
367
+ self._assert_result(
368
+ connection,
369
+ select(table).order_by(table.c.id).limit(bindparam("l")),
370
+ [(1, 1, 2), (2, 2, 3)],
371
+ params={"l": 2},
372
+ )
373
+
374
+ self._assert_result(
375
+ connection,
376
+ select(table).order_by(table.c.id).limit(bindparam("l")),
377
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4)],
378
+ params={"l": 3},
379
+ )
380
+
381
+ @testing.requires.bound_limit_offset
382
+ def test_bound_offset(self, connection):
383
+ table = self.tables.some_table
384
+ self._assert_result(
385
+ connection,
386
+ select(table).order_by(table.c.id).offset(bindparam("o")),
387
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
388
+ params={"o": 2},
389
+ )
390
+
391
+ self._assert_result(
392
+ connection,
393
+ select(table).order_by(table.c.id).offset(bindparam("o")),
394
+ [(2, 2, 3), (3, 3, 4), (4, 4, 5), (5, 4, 6)],
395
+ params={"o": 1},
396
+ )
397
+
398
+ @testing.requires.bound_limit_offset
399
+ def test_bound_limit_offset(self, connection):
400
+ table = self.tables.some_table
401
+ self._assert_result(
402
+ connection,
403
+ select(table)
404
+ .order_by(table.c.id)
405
+ .limit(bindparam("l"))
406
+ .offset(bindparam("o")),
407
+ [(2, 2, 3), (3, 3, 4)],
408
+ params={"l": 2, "o": 1},
409
+ )
410
+
411
+ self._assert_result(
412
+ connection,
413
+ select(table)
414
+ .order_by(table.c.id)
415
+ .limit(bindparam("l"))
416
+ .offset(bindparam("o")),
417
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
418
+ params={"l": 3, "o": 2},
419
+ )
420
+
421
+ @testing.requires.fetch_first
422
+ def test_bound_fetch_offset(self, connection):
423
+ table = self.tables.some_table
424
+ self._assert_result(
425
+ connection,
426
+ select(table)
427
+ .order_by(table.c.id)
428
+ .fetch(bindparam("f"))
429
+ .offset(bindparam("o")),
430
+ [(2, 2, 3), (3, 3, 4)],
431
+ params={"f": 2, "o": 1},
432
+ )
433
+
434
+ self._assert_result(
435
+ connection,
436
+ select(table)
437
+ .order_by(table.c.id)
438
+ .fetch(bindparam("f"))
439
+ .offset(bindparam("o")),
440
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
441
+ params={"f": 3, "o": 2},
442
+ )
443
+
444
+ @testing.requires.sql_expression_limit_offset
445
+ def test_expr_offset(self, connection):
446
+ table = self.tables.some_table
447
+ self._assert_result(
448
+ connection,
449
+ select(table)
450
+ .order_by(table.c.id)
451
+ .offset(literal_column("1") + literal_column("2")),
452
+ [(4, 4, 5), (5, 4, 6)],
453
+ )
454
+
455
+ @testing.requires.sql_expression_limit_offset
456
+ def test_expr_limit(self, connection):
457
+ table = self.tables.some_table
458
+ self._assert_result(
459
+ connection,
460
+ select(table)
461
+ .order_by(table.c.id)
462
+ .limit(literal_column("1") + literal_column("2")),
463
+ [(1, 1, 2), (2, 2, 3), (3, 3, 4)],
464
+ )
465
+
466
+ @testing.requires.sql_expression_limit_offset
467
+ def test_expr_limit_offset(self, connection):
468
+ table = self.tables.some_table
469
+ self._assert_result(
470
+ connection,
471
+ select(table)
472
+ .order_by(table.c.id)
473
+ .limit(literal_column("1") + literal_column("1"))
474
+ .offset(literal_column("1") + literal_column("1")),
475
+ [(3, 3, 4), (4, 4, 5)],
476
+ )
477
+
478
+ @testing.requires.fetch_first
479
+ @testing.requires.fetch_expression
480
+ def test_expr_fetch_offset(self, connection):
481
+ table = self.tables.some_table
482
+ self._assert_result(
483
+ connection,
484
+ select(table)
485
+ .order_by(table.c.id)
486
+ .fetch(literal_column("1") + literal_column("1"))
487
+ .offset(literal_column("1") + literal_column("1")),
488
+ [(3, 3, 4), (4, 4, 5)],
489
+ )
490
+
491
+ @testing.requires.sql_expression_limit_offset
492
+ def test_simple_limit_expr_offset(self, connection):
493
+ table = self.tables.some_table
494
+ self._assert_result(
495
+ connection,
496
+ select(table)
497
+ .order_by(table.c.id)
498
+ .limit(2)
499
+ .offset(literal_column("1") + literal_column("1")),
500
+ [(3, 3, 4), (4, 4, 5)],
501
+ )
502
+
503
+ self._assert_result(
504
+ connection,
505
+ select(table)
506
+ .order_by(table.c.id)
507
+ .limit(3)
508
+ .offset(literal_column("1") + literal_column("1")),
509
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
510
+ )
511
+
512
+ @testing.requires.sql_expression_limit_offset
513
+ def test_expr_limit_simple_offset(self, connection):
514
+ table = self.tables.some_table
515
+ self._assert_result(
516
+ connection,
517
+ select(table)
518
+ .order_by(table.c.id)
519
+ .limit(literal_column("1") + literal_column("1"))
520
+ .offset(2),
521
+ [(3, 3, 4), (4, 4, 5)],
522
+ )
523
+
524
+ self._assert_result(
525
+ connection,
526
+ select(table)
527
+ .order_by(table.c.id)
528
+ .limit(literal_column("1") + literal_column("1"))
529
+ .offset(1),
530
+ [(2, 2, 3), (3, 3, 4)],
531
+ )
532
+
533
+ @testing.requires.fetch_ties
534
+ def test_simple_fetch_ties(self, connection):
535
+ table = self.tables.some_table
536
+ self._assert_result(
537
+ connection,
538
+ select(table).order_by(table.c.x.desc()).fetch(1, with_ties=True),
539
+ [(4, 4, 5), (5, 4, 6)],
540
+ set_=True,
541
+ )
542
+
543
+ self._assert_result(
544
+ connection,
545
+ select(table).order_by(table.c.x.desc()).fetch(3, with_ties=True),
546
+ [(3, 3, 4), (4, 4, 5), (5, 4, 6)],
547
+ set_=True,
548
+ )
549
+
550
+ @testing.requires.fetch_ties
551
+ @testing.requires.fetch_offset_with_options
552
+ def test_fetch_offset_ties(self, connection):
553
+ table = self.tables.some_table
554
+ fa = connection.execute(
555
+ select(table)
556
+ .order_by(table.c.x)
557
+ .fetch(2, with_ties=True)
558
+ .offset(2)
559
+ ).fetchall()
560
+ eq_(fa[0], (3, 3, 4))
561
+ eq_(set(fa), {(3, 3, 4), (4, 4, 5), (5, 4, 6)})
562
+
563
+ @testing.requires.fetch_ties
564
+ @testing.requires.fetch_offset_with_options
565
+ def test_fetch_offset_ties_exact_number(self, connection):
566
+ table = self.tables.some_table
567
+ self._assert_result(
568
+ connection,
569
+ select(table)
570
+ .order_by(table.c.x)
571
+ .fetch(2, with_ties=True)
572
+ .offset(1),
573
+ [(2, 2, 3), (3, 3, 4)],
574
+ )
575
+
576
+ self._assert_result(
577
+ connection,
578
+ select(table)
579
+ .order_by(table.c.x)
580
+ .fetch(3, with_ties=True)
581
+ .offset(3),
582
+ [(4, 4, 5), (5, 4, 6)],
583
+ )
584
+
585
+ @testing.requires.fetch_percent
586
+ def test_simple_fetch_percent(self, connection):
587
+ table = self.tables.some_table
588
+ self._assert_result(
589
+ connection,
590
+ select(table).order_by(table.c.id).fetch(20, percent=True),
591
+ [(1, 1, 2)],
592
+ )
593
+
594
+ @testing.requires.fetch_percent
595
+ @testing.requires.fetch_offset_with_options
596
+ def test_fetch_offset_percent(self, connection):
597
+ table = self.tables.some_table
598
+ self._assert_result(
599
+ connection,
600
+ select(table)
601
+ .order_by(table.c.id)
602
+ .fetch(40, percent=True)
603
+ .offset(1),
604
+ [(2, 2, 3), (3, 3, 4)],
605
+ )
606
+
607
+ @testing.requires.fetch_ties
608
+ @testing.requires.fetch_percent
609
+ def test_simple_fetch_percent_ties(self, connection):
610
+ table = self.tables.some_table
611
+ self._assert_result(
612
+ connection,
613
+ select(table)
614
+ .order_by(table.c.x.desc())
615
+ .fetch(20, percent=True, with_ties=True),
616
+ [(4, 4, 5), (5, 4, 6)],
617
+ set_=True,
618
+ )
619
+
620
+ @testing.requires.fetch_ties
621
+ @testing.requires.fetch_percent
622
+ @testing.requires.fetch_offset_with_options
623
+ def test_fetch_offset_percent_ties(self, connection):
624
+ table = self.tables.some_table
625
+ fa = connection.execute(
626
+ select(table)
627
+ .order_by(table.c.x)
628
+ .fetch(40, percent=True, with_ties=True)
629
+ .offset(2)
630
+ ).fetchall()
631
+ eq_(fa[0], (3, 3, 4))
632
+ eq_(set(fa), {(3, 3, 4), (4, 4, 5), (5, 4, 6)})
633
+
634
+
635
+ class SameNamedSchemaTableTest(fixtures.TablesTest):
636
+ """tests for #7471"""
637
+
638
+ __backend__ = True
639
+
640
+ __requires__ = ("schemas",)
641
+
642
+ @classmethod
643
+ def define_tables(cls, metadata):
644
+ Table(
645
+ "some_table",
646
+ metadata,
647
+ Column("id", Integer, primary_key=True),
648
+ schema=config.test_schema,
649
+ )
650
+ Table(
651
+ "some_table",
652
+ metadata,
653
+ Column("id", Integer, primary_key=True),
654
+ Column(
655
+ "some_table_id",
656
+ Integer,
657
+ # ForeignKey("%s.some_table.id" % config.test_schema),
658
+ nullable=False,
659
+ ),
660
+ )
661
+
662
+ @classmethod
663
+ def insert_data(cls, connection):
664
+ some_table, some_table_schema = cls.tables(
665
+ "some_table", "%s.some_table" % config.test_schema
666
+ )
667
+ connection.execute(some_table_schema.insert(), {"id": 1})
668
+ connection.execute(some_table.insert(), {"id": 1, "some_table_id": 1})
669
+
670
+ def test_simple_join_both_tables(self, connection):
671
+ some_table, some_table_schema = self.tables(
672
+ "some_table", "%s.some_table" % config.test_schema
673
+ )
674
+
675
+ eq_(
676
+ connection.execute(
677
+ select(some_table, some_table_schema).join_from(
678
+ some_table,
679
+ some_table_schema,
680
+ some_table.c.some_table_id == some_table_schema.c.id,
681
+ )
682
+ ).first(),
683
+ (1, 1, 1),
684
+ )
685
+
686
+ def test_simple_join_whereclause_only(self, connection):
687
+ some_table, some_table_schema = self.tables(
688
+ "some_table", "%s.some_table" % config.test_schema
689
+ )
690
+
691
+ eq_(
692
+ connection.execute(
693
+ select(some_table)
694
+ .join_from(
695
+ some_table,
696
+ some_table_schema,
697
+ some_table.c.some_table_id == some_table_schema.c.id,
698
+ )
699
+ .where(some_table.c.id == 1)
700
+ ).first(),
701
+ (1, 1),
702
+ )
703
+
704
+ def test_subquery(self, connection):
705
+ some_table, some_table_schema = self.tables(
706
+ "some_table", "%s.some_table" % config.test_schema
707
+ )
708
+
709
+ subq = (
710
+ select(some_table)
711
+ .join_from(
712
+ some_table,
713
+ some_table_schema,
714
+ some_table.c.some_table_id == some_table_schema.c.id,
715
+ )
716
+ .where(some_table.c.id == 1)
717
+ .subquery()
718
+ )
719
+
720
+ eq_(
721
+ connection.execute(
722
+ select(some_table, subq.c.id)
723
+ .join_from(
724
+ some_table,
725
+ subq,
726
+ some_table.c.some_table_id == subq.c.id,
727
+ )
728
+ .where(some_table.c.id == 1)
729
+ ).first(),
730
+ (1, 1, 1),
731
+ )
732
+
733
+
734
+ class JoinTest(fixtures.TablesTest):
735
+ __backend__ = True
736
+
737
+ def _assert_result(self, select, result, params=()):
738
+ with config.db.connect() as conn:
739
+ eq_(conn.execute(select, params).fetchall(), result)
740
+
741
+ @classmethod
742
+ def define_tables(cls, metadata):
743
+ Table("a", metadata, Column("id", Integer, primary_key=True))
744
+ Table(
745
+ "b",
746
+ metadata,
747
+ Column("id", Integer, primary_key=True),
748
+ Column("a_id", ForeignKey("a.id"), nullable=False),
749
+ )
750
+
751
+ @classmethod
752
+ def insert_data(cls, connection):
753
+ connection.execute(
754
+ cls.tables.a.insert(),
755
+ [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}],
756
+ )
757
+
758
+ connection.execute(
759
+ cls.tables.b.insert(),
760
+ [
761
+ {"id": 1, "a_id": 1},
762
+ {"id": 2, "a_id": 1},
763
+ {"id": 4, "a_id": 2},
764
+ {"id": 5, "a_id": 3},
765
+ ],
766
+ )
767
+
768
+ def test_inner_join_fk(self):
769
+ a, b = self.tables("a", "b")
770
+
771
+ stmt = select(a, b).select_from(a.join(b)).order_by(a.c.id, b.c.id)
772
+
773
+ self._assert_result(stmt, [(1, 1, 1), (1, 2, 1), (2, 4, 2), (3, 5, 3)])
774
+
775
+ def test_inner_join_true(self):
776
+ a, b = self.tables("a", "b")
777
+
778
+ stmt = (
779
+ select(a, b)
780
+ .select_from(a.join(b, true()))
781
+ .order_by(a.c.id, b.c.id)
782
+ )
783
+
784
+ self._assert_result(
785
+ stmt,
786
+ [
787
+ (a, b, c)
788
+ for (a,), (b, c) in itertools.product(
789
+ [(1,), (2,), (3,), (4,), (5,)],
790
+ [(1, 1), (2, 1), (4, 2), (5, 3)],
791
+ )
792
+ ],
793
+ )
794
+
795
+ def test_inner_join_false(self):
796
+ a, b = self.tables("a", "b")
797
+
798
+ stmt = (
799
+ select(a, b)
800
+ .select_from(a.join(b, false()))
801
+ .order_by(a.c.id, b.c.id)
802
+ )
803
+
804
+ self._assert_result(stmt, [])
805
+
806
+ def test_outer_join_false(self):
807
+ a, b = self.tables("a", "b")
808
+
809
+ stmt = (
810
+ select(a, b)
811
+ .select_from(a.outerjoin(b, false()))
812
+ .order_by(a.c.id, b.c.id)
813
+ )
814
+
815
+ self._assert_result(
816
+ stmt,
817
+ [
818
+ (1, None, None),
819
+ (2, None, None),
820
+ (3, None, None),
821
+ (4, None, None),
822
+ (5, None, None),
823
+ ],
824
+ )
825
+
826
+ def test_outer_join_fk(self):
827
+ a, b = self.tables("a", "b")
828
+
829
+ stmt = select(a, b).select_from(a.join(b)).order_by(a.c.id, b.c.id)
830
+
831
+ self._assert_result(stmt, [(1, 1, 1), (1, 2, 1), (2, 4, 2), (3, 5, 3)])
832
+
833
+
834
+ class CompoundSelectTest(fixtures.TablesTest):
835
+ __backend__ = True
836
+
837
+ @classmethod
838
+ def define_tables(cls, metadata):
839
+ Table(
840
+ "some_table",
841
+ metadata,
842
+ Column("id", Integer, primary_key=True),
843
+ Column("x", Integer),
844
+ Column("y", Integer),
845
+ )
846
+
847
+ @classmethod
848
+ def insert_data(cls, connection):
849
+ connection.execute(
850
+ cls.tables.some_table.insert(),
851
+ [
852
+ {"id": 1, "x": 1, "y": 2},
853
+ {"id": 2, "x": 2, "y": 3},
854
+ {"id": 3, "x": 3, "y": 4},
855
+ {"id": 4, "x": 4, "y": 5},
856
+ ],
857
+ )
858
+
859
+ def _assert_result(self, select, result, params=()):
860
+ with config.db.connect() as conn:
861
+ eq_(conn.execute(select, params).fetchall(), result)
862
+
863
+ def test_plain_union(self):
864
+ table = self.tables.some_table
865
+ s1 = select(table).where(table.c.id == 2)
866
+ s2 = select(table).where(table.c.id == 3)
867
+
868
+ u1 = union(s1, s2)
869
+ self._assert_result(
870
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
871
+ )
872
+
873
+ def test_select_from_plain_union(self):
874
+ table = self.tables.some_table
875
+ s1 = select(table).where(table.c.id == 2)
876
+ s2 = select(table).where(table.c.id == 3)
877
+
878
+ u1 = union(s1, s2).alias().select()
879
+ self._assert_result(
880
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
881
+ )
882
+
883
+ @testing.requires.order_by_col_from_union
884
+ @testing.requires.parens_in_union_contained_select_w_limit_offset
885
+ def test_limit_offset_selectable_in_unions(self):
886
+ table = self.tables.some_table
887
+ s1 = select(table).where(table.c.id == 2).limit(1).order_by(table.c.id)
888
+ s2 = select(table).where(table.c.id == 3).limit(1).order_by(table.c.id)
889
+
890
+ u1 = union(s1, s2).limit(2)
891
+ self._assert_result(
892
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
893
+ )
894
+
895
+ @testing.requires.parens_in_union_contained_select_wo_limit_offset
896
+ def test_order_by_selectable_in_unions(self):
897
+ table = self.tables.some_table
898
+ s1 = select(table).where(table.c.id == 2).order_by(table.c.id)
899
+ s2 = select(table).where(table.c.id == 3).order_by(table.c.id)
900
+
901
+ u1 = union(s1, s2).limit(2)
902
+ self._assert_result(
903
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
904
+ )
905
+
906
+ def test_distinct_selectable_in_unions(self):
907
+ table = self.tables.some_table
908
+ s1 = select(table).where(table.c.id == 2).distinct()
909
+ s2 = select(table).where(table.c.id == 3).distinct()
910
+
911
+ u1 = union(s1, s2).limit(2)
912
+ self._assert_result(
913
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
914
+ )
915
+
916
+ @testing.requires.parens_in_union_contained_select_w_limit_offset
917
+ def test_limit_offset_in_unions_from_alias(self):
918
+ table = self.tables.some_table
919
+ s1 = select(table).where(table.c.id == 2).limit(1).order_by(table.c.id)
920
+ s2 = select(table).where(table.c.id == 3).limit(1).order_by(table.c.id)
921
+
922
+ # this necessarily has double parens
923
+ u1 = union(s1, s2).alias()
924
+ self._assert_result(
925
+ u1.select().limit(2).order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]
926
+ )
927
+
928
+ def test_limit_offset_aliased_selectable_in_unions(self):
929
+ table = self.tables.some_table
930
+ s1 = (
931
+ select(table)
932
+ .where(table.c.id == 2)
933
+ .limit(1)
934
+ .order_by(table.c.id)
935
+ .alias()
936
+ .select()
937
+ )
938
+ s2 = (
939
+ select(table)
940
+ .where(table.c.id == 3)
941
+ .limit(1)
942
+ .order_by(table.c.id)
943
+ .alias()
944
+ .select()
945
+ )
946
+
947
+ u1 = union(s1, s2).limit(2)
948
+ self._assert_result(
949
+ u1.order_by(u1.selected_columns.id), [(2, 2, 3), (3, 3, 4)]
950
+ )
951
+
952
+
953
+ class PostCompileParamsTest(
954
+ AssertsExecutionResults, AssertsCompiledSQL, fixtures.TablesTest
955
+ ):
956
+ __backend__ = True
957
+
958
+ __requires__ = ("standard_cursor_sql",)
959
+
960
+ @classmethod
961
+ def define_tables(cls, metadata):
962
+ Table(
963
+ "some_table",
964
+ metadata,
965
+ Column("id", Integer, primary_key=True),
966
+ Column("x", Integer),
967
+ Column("y", Integer),
968
+ Column("z", String(50)),
969
+ )
970
+
971
+ @classmethod
972
+ def insert_data(cls, connection):
973
+ connection.execute(
974
+ cls.tables.some_table.insert(),
975
+ [
976
+ {"id": 1, "x": 1, "y": 2, "z": "z1"},
977
+ {"id": 2, "x": 2, "y": 3, "z": "z2"},
978
+ {"id": 3, "x": 3, "y": 4, "z": "z3"},
979
+ {"id": 4, "x": 4, "y": 5, "z": "z4"},
980
+ ],
981
+ )
982
+
983
+ def test_compile(self):
984
+ table = self.tables.some_table
985
+
986
+ stmt = select(table.c.id).where(
987
+ table.c.x == bindparam("q", literal_execute=True)
988
+ )
989
+
990
+ self.assert_compile(
991
+ stmt,
992
+ "SELECT some_table.id FROM some_table "
993
+ "WHERE some_table.x = __[POSTCOMPILE_q]",
994
+ {},
995
+ )
996
+
997
+ def test_compile_literal_binds(self):
998
+ table = self.tables.some_table
999
+
1000
+ stmt = select(table.c.id).where(
1001
+ table.c.x == bindparam("q", 10, literal_execute=True)
1002
+ )
1003
+
1004
+ self.assert_compile(
1005
+ stmt,
1006
+ "SELECT some_table.id FROM some_table WHERE some_table.x = 10",
1007
+ {},
1008
+ literal_binds=True,
1009
+ )
1010
+
1011
+ def test_execute(self):
1012
+ table = self.tables.some_table
1013
+
1014
+ stmt = select(table.c.id).where(
1015
+ table.c.x == bindparam("q", literal_execute=True)
1016
+ )
1017
+
1018
+ with self.sql_execution_asserter() as asserter:
1019
+ with config.db.connect() as conn:
1020
+ conn.execute(stmt, dict(q=10))
1021
+
1022
+ asserter.assert_(
1023
+ CursorSQL(
1024
+ "SELECT some_table.id \nFROM some_table "
1025
+ "\nWHERE some_table.x = 10",
1026
+ () if config.db.dialect.positional else {},
1027
+ )
1028
+ )
1029
+
1030
+ def test_execute_expanding_plus_literal_execute(self):
1031
+ table = self.tables.some_table
1032
+
1033
+ stmt = select(table.c.id).where(
1034
+ table.c.x.in_(bindparam("q", expanding=True, literal_execute=True))
1035
+ )
1036
+
1037
+ with self.sql_execution_asserter() as asserter:
1038
+ with config.db.connect() as conn:
1039
+ conn.execute(stmt, dict(q=[5, 6, 7]))
1040
+
1041
+ asserter.assert_(
1042
+ CursorSQL(
1043
+ "SELECT some_table.id \nFROM some_table "
1044
+ "\nWHERE some_table.x IN (5, 6, 7)",
1045
+ () if config.db.dialect.positional else {},
1046
+ )
1047
+ )
1048
+
1049
+ @testing.requires.tuple_in
1050
+ def test_execute_tuple_expanding_plus_literal_execute(self):
1051
+ table = self.tables.some_table
1052
+
1053
+ stmt = select(table.c.id).where(
1054
+ tuple_(table.c.x, table.c.y).in_(
1055
+ bindparam("q", expanding=True, literal_execute=True)
1056
+ )
1057
+ )
1058
+
1059
+ with self.sql_execution_asserter() as asserter:
1060
+ with config.db.connect() as conn:
1061
+ conn.execute(stmt, dict(q=[(5, 10), (12, 18)]))
1062
+
1063
+ asserter.assert_(
1064
+ CursorSQL(
1065
+ "SELECT some_table.id \nFROM some_table "
1066
+ "\nWHERE (some_table.x, some_table.y) "
1067
+ "IN (%s(5, 10), (12, 18))"
1068
+ % ("VALUES " if config.db.dialect.tuple_in_values else ""),
1069
+ () if config.db.dialect.positional else {},
1070
+ )
1071
+ )
1072
+
1073
+ @testing.requires.tuple_in
1074
+ def test_execute_tuple_expanding_plus_literal_heterogeneous_execute(self):
1075
+ table = self.tables.some_table
1076
+
1077
+ stmt = select(table.c.id).where(
1078
+ tuple_(table.c.x, table.c.z).in_(
1079
+ bindparam("q", expanding=True, literal_execute=True)
1080
+ )
1081
+ )
1082
+
1083
+ with self.sql_execution_asserter() as asserter:
1084
+ with config.db.connect() as conn:
1085
+ conn.execute(stmt, dict(q=[(5, "z1"), (12, "z3")]))
1086
+
1087
+ asserter.assert_(
1088
+ CursorSQL(
1089
+ "SELECT some_table.id \nFROM some_table "
1090
+ "\nWHERE (some_table.x, some_table.z) "
1091
+ "IN (%s(5, 'z1'), (12, 'z3'))"
1092
+ % ("VALUES " if config.db.dialect.tuple_in_values else ""),
1093
+ () if config.db.dialect.positional else {},
1094
+ )
1095
+ )
1096
+
1097
+
1098
+ class ExpandingBoundInTest(fixtures.TablesTest):
1099
+ __backend__ = True
1100
+
1101
+ @classmethod
1102
+ def define_tables(cls, metadata):
1103
+ Table(
1104
+ "some_table",
1105
+ metadata,
1106
+ Column("id", Integer, primary_key=True),
1107
+ Column("x", Integer),
1108
+ Column("y", Integer),
1109
+ Column("z", String(50)),
1110
+ )
1111
+
1112
+ @classmethod
1113
+ def insert_data(cls, connection):
1114
+ connection.execute(
1115
+ cls.tables.some_table.insert(),
1116
+ [
1117
+ {"id": 1, "x": 1, "y": 2, "z": "z1"},
1118
+ {"id": 2, "x": 2, "y": 3, "z": "z2"},
1119
+ {"id": 3, "x": 3, "y": 4, "z": "z3"},
1120
+ {"id": 4, "x": 4, "y": 5, "z": "z4"},
1121
+ ],
1122
+ )
1123
+
1124
+ def _assert_result(self, select, result, params=()):
1125
+ with config.db.connect() as conn:
1126
+ eq_(conn.execute(select, params).fetchall(), result)
1127
+
1128
+ def test_multiple_empty_sets_bindparam(self):
1129
+ # test that any anonymous aliasing used by the dialect
1130
+ # is fine with duplicates
1131
+ table = self.tables.some_table
1132
+ stmt = (
1133
+ select(table.c.id)
1134
+ .where(table.c.x.in_(bindparam("q")))
1135
+ .where(table.c.y.in_(bindparam("p")))
1136
+ .order_by(table.c.id)
1137
+ )
1138
+ self._assert_result(stmt, [], params={"q": [], "p": []})
1139
+
1140
+ def test_multiple_empty_sets_direct(self):
1141
+ # test that any anonymous aliasing used by the dialect
1142
+ # is fine with duplicates
1143
+ table = self.tables.some_table
1144
+ stmt = (
1145
+ select(table.c.id)
1146
+ .where(table.c.x.in_([]))
1147
+ .where(table.c.y.in_([]))
1148
+ .order_by(table.c.id)
1149
+ )
1150
+ self._assert_result(stmt, [])
1151
+
1152
+ @testing.requires.tuple_in_w_empty
1153
+ def test_empty_heterogeneous_tuples_bindparam(self):
1154
+ table = self.tables.some_table
1155
+ stmt = (
1156
+ select(table.c.id)
1157
+ .where(tuple_(table.c.x, table.c.z).in_(bindparam("q")))
1158
+ .order_by(table.c.id)
1159
+ )
1160
+ self._assert_result(stmt, [], params={"q": []})
1161
+
1162
+ @testing.requires.tuple_in_w_empty
1163
+ def test_empty_heterogeneous_tuples_direct(self):
1164
+ table = self.tables.some_table
1165
+
1166
+ def go(val, expected):
1167
+ stmt = (
1168
+ select(table.c.id)
1169
+ .where(tuple_(table.c.x, table.c.z).in_(val))
1170
+ .order_by(table.c.id)
1171
+ )
1172
+ self._assert_result(stmt, expected)
1173
+
1174
+ go([], [])
1175
+ go([(2, "z2"), (3, "z3"), (4, "z4")], [(2,), (3,), (4,)])
1176
+ go([], [])
1177
+
1178
+ @testing.requires.tuple_in_w_empty
1179
+ def test_empty_homogeneous_tuples_bindparam(self):
1180
+ table = self.tables.some_table
1181
+ stmt = (
1182
+ select(table.c.id)
1183
+ .where(tuple_(table.c.x, table.c.y).in_(bindparam("q")))
1184
+ .order_by(table.c.id)
1185
+ )
1186
+ self._assert_result(stmt, [], params={"q": []})
1187
+
1188
+ @testing.requires.tuple_in_w_empty
1189
+ def test_empty_homogeneous_tuples_direct(self):
1190
+ table = self.tables.some_table
1191
+
1192
+ def go(val, expected):
1193
+ stmt = (
1194
+ select(table.c.id)
1195
+ .where(tuple_(table.c.x, table.c.y).in_(val))
1196
+ .order_by(table.c.id)
1197
+ )
1198
+ self._assert_result(stmt, expected)
1199
+
1200
+ go([], [])
1201
+ go([(1, 2), (2, 3), (3, 4)], [(1,), (2,), (3,)])
1202
+ go([], [])
1203
+
1204
+ def test_bound_in_scalar_bindparam(self):
1205
+ table = self.tables.some_table
1206
+ stmt = (
1207
+ select(table.c.id)
1208
+ .where(table.c.x.in_(bindparam("q")))
1209
+ .order_by(table.c.id)
1210
+ )
1211
+ self._assert_result(stmt, [(2,), (3,), (4,)], params={"q": [2, 3, 4]})
1212
+
1213
+ def test_bound_in_scalar_direct(self):
1214
+ table = self.tables.some_table
1215
+ stmt = (
1216
+ select(table.c.id)
1217
+ .where(table.c.x.in_([2, 3, 4]))
1218
+ .order_by(table.c.id)
1219
+ )
1220
+ self._assert_result(stmt, [(2,), (3,), (4,)])
1221
+
1222
+ def test_nonempty_in_plus_empty_notin(self):
1223
+ table = self.tables.some_table
1224
+ stmt = (
1225
+ select(table.c.id)
1226
+ .where(table.c.x.in_([2, 3]))
1227
+ .where(table.c.id.not_in([]))
1228
+ .order_by(table.c.id)
1229
+ )
1230
+ self._assert_result(stmt, [(2,), (3,)])
1231
+
1232
+ def test_empty_in_plus_notempty_notin(self):
1233
+ table = self.tables.some_table
1234
+ stmt = (
1235
+ select(table.c.id)
1236
+ .where(table.c.x.in_([]))
1237
+ .where(table.c.id.not_in([2, 3]))
1238
+ .order_by(table.c.id)
1239
+ )
1240
+ self._assert_result(stmt, [])
1241
+
1242
+ def test_typed_str_in(self):
1243
+ """test related to #7292.
1244
+
1245
+ as a type is given to the bound param, there is no ambiguity
1246
+ to the type of element.
1247
+
1248
+ """
1249
+
1250
+ stmt = text(
1251
+ "select id FROM some_table WHERE z IN :q ORDER BY id"
1252
+ ).bindparams(bindparam("q", type_=String, expanding=True))
1253
+ self._assert_result(
1254
+ stmt,
1255
+ [(2,), (3,), (4,)],
1256
+ params={"q": ["z2", "z3", "z4"]},
1257
+ )
1258
+
1259
+ def test_untyped_str_in(self):
1260
+ """test related to #7292.
1261
+
1262
+ for untyped expression, we look at the types of elements.
1263
+ Test for Sequence to detect tuple in. but not strings or bytes!
1264
+ as always....
1265
+
1266
+ """
1267
+
1268
+ stmt = text(
1269
+ "select id FROM some_table WHERE z IN :q ORDER BY id"
1270
+ ).bindparams(bindparam("q", expanding=True))
1271
+ self._assert_result(
1272
+ stmt,
1273
+ [(2,), (3,), (4,)],
1274
+ params={"q": ["z2", "z3", "z4"]},
1275
+ )
1276
+
1277
+ @testing.requires.tuple_in
1278
+ def test_bound_in_two_tuple_bindparam(self):
1279
+ table = self.tables.some_table
1280
+ stmt = (
1281
+ select(table.c.id)
1282
+ .where(tuple_(table.c.x, table.c.y).in_(bindparam("q")))
1283
+ .order_by(table.c.id)
1284
+ )
1285
+ self._assert_result(
1286
+ stmt, [(2,), (3,), (4,)], params={"q": [(2, 3), (3, 4), (4, 5)]}
1287
+ )
1288
+
1289
+ @testing.requires.tuple_in
1290
+ def test_bound_in_two_tuple_direct(self):
1291
+ table = self.tables.some_table
1292
+ stmt = (
1293
+ select(table.c.id)
1294
+ .where(tuple_(table.c.x, table.c.y).in_([(2, 3), (3, 4), (4, 5)]))
1295
+ .order_by(table.c.id)
1296
+ )
1297
+ self._assert_result(stmt, [(2,), (3,), (4,)])
1298
+
1299
+ @testing.requires.tuple_in
1300
+ def test_bound_in_heterogeneous_two_tuple_bindparam(self):
1301
+ table = self.tables.some_table
1302
+ stmt = (
1303
+ select(table.c.id)
1304
+ .where(tuple_(table.c.x, table.c.z).in_(bindparam("q")))
1305
+ .order_by(table.c.id)
1306
+ )
1307
+ self._assert_result(
1308
+ stmt,
1309
+ [(2,), (3,), (4,)],
1310
+ params={"q": [(2, "z2"), (3, "z3"), (4, "z4")]},
1311
+ )
1312
+
1313
+ @testing.requires.tuple_in
1314
+ def test_bound_in_heterogeneous_two_tuple_direct(self):
1315
+ table = self.tables.some_table
1316
+ stmt = (
1317
+ select(table.c.id)
1318
+ .where(
1319
+ tuple_(table.c.x, table.c.z).in_(
1320
+ [(2, "z2"), (3, "z3"), (4, "z4")]
1321
+ )
1322
+ )
1323
+ .order_by(table.c.id)
1324
+ )
1325
+ self._assert_result(
1326
+ stmt,
1327
+ [(2,), (3,), (4,)],
1328
+ )
1329
+
1330
+ @testing.requires.tuple_in
1331
+ def test_bound_in_heterogeneous_two_tuple_text_bindparam(self):
1332
+ # note this becomes ARRAY if we dont use expanding
1333
+ # explicitly right now
1334
+ stmt = text(
1335
+ "select id FROM some_table WHERE (x, z) IN :q ORDER BY id"
1336
+ ).bindparams(bindparam("q", expanding=True))
1337
+ self._assert_result(
1338
+ stmt,
1339
+ [(2,), (3,), (4,)],
1340
+ params={"q": [(2, "z2"), (3, "z3"), (4, "z4")]},
1341
+ )
1342
+
1343
+ @testing.requires.tuple_in
1344
+ def test_bound_in_heterogeneous_two_tuple_typed_bindparam_non_tuple(self):
1345
+ class LikeATuple(collections_abc.Sequence):
1346
+ def __init__(self, *data):
1347
+ self._data = data
1348
+
1349
+ def __iter__(self):
1350
+ return iter(self._data)
1351
+
1352
+ def __getitem__(self, idx):
1353
+ return self._data[idx]
1354
+
1355
+ def __len__(self):
1356
+ return len(self._data)
1357
+
1358
+ stmt = text(
1359
+ "select id FROM some_table WHERE (x, z) IN :q ORDER BY id"
1360
+ ).bindparams(
1361
+ bindparam(
1362
+ "q", type_=TupleType(Integer(), String()), expanding=True
1363
+ )
1364
+ )
1365
+ self._assert_result(
1366
+ stmt,
1367
+ [(2,), (3,), (4,)],
1368
+ params={
1369
+ "q": [
1370
+ LikeATuple(2, "z2"),
1371
+ LikeATuple(3, "z3"),
1372
+ LikeATuple(4, "z4"),
1373
+ ]
1374
+ },
1375
+ )
1376
+
1377
+ @testing.requires.tuple_in
1378
+ def test_bound_in_heterogeneous_two_tuple_text_bindparam_non_tuple(self):
1379
+ # note this becomes ARRAY if we dont use expanding
1380
+ # explicitly right now
1381
+
1382
+ class LikeATuple(collections_abc.Sequence):
1383
+ def __init__(self, *data):
1384
+ self._data = data
1385
+
1386
+ def __iter__(self):
1387
+ return iter(self._data)
1388
+
1389
+ def __getitem__(self, idx):
1390
+ return self._data[idx]
1391
+
1392
+ def __len__(self):
1393
+ return len(self._data)
1394
+
1395
+ stmt = text(
1396
+ "select id FROM some_table WHERE (x, z) IN :q ORDER BY id"
1397
+ ).bindparams(bindparam("q", expanding=True))
1398
+ self._assert_result(
1399
+ stmt,
1400
+ [(2,), (3,), (4,)],
1401
+ params={
1402
+ "q": [
1403
+ LikeATuple(2, "z2"),
1404
+ LikeATuple(3, "z3"),
1405
+ LikeATuple(4, "z4"),
1406
+ ]
1407
+ },
1408
+ )
1409
+
1410
+ def test_empty_set_against_integer_bindparam(self):
1411
+ table = self.tables.some_table
1412
+ stmt = (
1413
+ select(table.c.id)
1414
+ .where(table.c.x.in_(bindparam("q")))
1415
+ .order_by(table.c.id)
1416
+ )
1417
+ self._assert_result(stmt, [], params={"q": []})
1418
+
1419
+ def test_empty_set_against_integer_direct(self):
1420
+ table = self.tables.some_table
1421
+ stmt = select(table.c.id).where(table.c.x.in_([])).order_by(table.c.id)
1422
+ self._assert_result(stmt, [])
1423
+
1424
+ def test_empty_set_against_integer_negation_bindparam(self):
1425
+ table = self.tables.some_table
1426
+ stmt = (
1427
+ select(table.c.id)
1428
+ .where(table.c.x.not_in(bindparam("q")))
1429
+ .order_by(table.c.id)
1430
+ )
1431
+ self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
1432
+
1433
+ def test_empty_set_against_integer_negation_direct(self):
1434
+ table = self.tables.some_table
1435
+ stmt = (
1436
+ select(table.c.id).where(table.c.x.not_in([])).order_by(table.c.id)
1437
+ )
1438
+ self._assert_result(stmt, [(1,), (2,), (3,), (4,)])
1439
+
1440
+ def test_empty_set_against_string_bindparam(self):
1441
+ table = self.tables.some_table
1442
+ stmt = (
1443
+ select(table.c.id)
1444
+ .where(table.c.z.in_(bindparam("q")))
1445
+ .order_by(table.c.id)
1446
+ )
1447
+ self._assert_result(stmt, [], params={"q": []})
1448
+
1449
+ def test_empty_set_against_string_direct(self):
1450
+ table = self.tables.some_table
1451
+ stmt = select(table.c.id).where(table.c.z.in_([])).order_by(table.c.id)
1452
+ self._assert_result(stmt, [])
1453
+
1454
+ def test_empty_set_against_string_negation_bindparam(self):
1455
+ table = self.tables.some_table
1456
+ stmt = (
1457
+ select(table.c.id)
1458
+ .where(table.c.z.not_in(bindparam("q")))
1459
+ .order_by(table.c.id)
1460
+ )
1461
+ self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
1462
+
1463
+ def test_empty_set_against_string_negation_direct(self):
1464
+ table = self.tables.some_table
1465
+ stmt = (
1466
+ select(table.c.id).where(table.c.z.not_in([])).order_by(table.c.id)
1467
+ )
1468
+ self._assert_result(stmt, [(1,), (2,), (3,), (4,)])
1469
+
1470
+ def test_null_in_empty_set_is_false_bindparam(self, connection):
1471
+ stmt = select(
1472
+ case(
1473
+ (
1474
+ null().in_(bindparam("foo", value=())),
1475
+ true(),
1476
+ ),
1477
+ else_=false(),
1478
+ )
1479
+ )
1480
+ in_(connection.execute(stmt).fetchone()[0], (False, 0))
1481
+
1482
+ def test_null_in_empty_set_is_false_direct(self, connection):
1483
+ stmt = select(
1484
+ case(
1485
+ (
1486
+ null().in_([]),
1487
+ true(),
1488
+ ),
1489
+ else_=false(),
1490
+ )
1491
+ )
1492
+ in_(connection.execute(stmt).fetchone()[0], (False, 0))
1493
+
1494
+
1495
+ class LikeFunctionsTest(fixtures.TablesTest):
1496
+ __backend__ = True
1497
+
1498
+ run_inserts = "once"
1499
+ run_deletes = None
1500
+
1501
+ @classmethod
1502
+ def define_tables(cls, metadata):
1503
+ Table(
1504
+ "some_table",
1505
+ metadata,
1506
+ Column("id", Integer, primary_key=True),
1507
+ Column("data", String(50)),
1508
+ )
1509
+
1510
+ @classmethod
1511
+ def insert_data(cls, connection):
1512
+ connection.execute(
1513
+ cls.tables.some_table.insert(),
1514
+ [
1515
+ {"id": 1, "data": "abcdefg"},
1516
+ {"id": 2, "data": "ab/cdefg"},
1517
+ {"id": 3, "data": "ab%cdefg"},
1518
+ {"id": 4, "data": "ab_cdefg"},
1519
+ {"id": 5, "data": "abcde/fg"},
1520
+ {"id": 6, "data": "abcde%fg"},
1521
+ {"id": 7, "data": "ab#cdefg"},
1522
+ {"id": 8, "data": "ab9cdefg"},
1523
+ {"id": 9, "data": "abcde#fg"},
1524
+ {"id": 10, "data": "abcd9fg"},
1525
+ {"id": 11, "data": None},
1526
+ ],
1527
+ )
1528
+
1529
+ def _test(self, expr, expected):
1530
+ some_table = self.tables.some_table
1531
+
1532
+ with config.db.connect() as conn:
1533
+ rows = {
1534
+ value
1535
+ for value, in conn.execute(select(some_table.c.id).where(expr))
1536
+ }
1537
+
1538
+ eq_(rows, expected)
1539
+
1540
+ def test_startswith_unescaped(self):
1541
+ col = self.tables.some_table.c.data
1542
+ self._test(col.startswith("ab%c"), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
1543
+
1544
+ def test_startswith_autoescape(self):
1545
+ col = self.tables.some_table.c.data
1546
+ self._test(col.startswith("ab%c", autoescape=True), {3})
1547
+
1548
+ def test_startswith_sqlexpr(self):
1549
+ col = self.tables.some_table.c.data
1550
+ self._test(
1551
+ col.startswith(literal_column("'ab%c'")),
1552
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
1553
+ )
1554
+
1555
+ def test_startswith_escape(self):
1556
+ col = self.tables.some_table.c.data
1557
+ self._test(col.startswith("ab##c", escape="#"), {7})
1558
+
1559
+ def test_startswith_autoescape_escape(self):
1560
+ col = self.tables.some_table.c.data
1561
+ self._test(col.startswith("ab%c", autoescape=True, escape="#"), {3})
1562
+ self._test(col.startswith("ab#c", autoescape=True, escape="#"), {7})
1563
+
1564
+ def test_endswith_unescaped(self):
1565
+ col = self.tables.some_table.c.data
1566
+ self._test(col.endswith("e%fg"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
1567
+
1568
+ def test_endswith_sqlexpr(self):
1569
+ col = self.tables.some_table.c.data
1570
+ self._test(
1571
+ col.endswith(literal_column("'e%fg'")), {1, 2, 3, 4, 5, 6, 7, 8, 9}
1572
+ )
1573
+
1574
+ def test_endswith_autoescape(self):
1575
+ col = self.tables.some_table.c.data
1576
+ self._test(col.endswith("e%fg", autoescape=True), {6})
1577
+
1578
+ def test_endswith_escape(self):
1579
+ col = self.tables.some_table.c.data
1580
+ self._test(col.endswith("e##fg", escape="#"), {9})
1581
+
1582
+ def test_endswith_autoescape_escape(self):
1583
+ col = self.tables.some_table.c.data
1584
+ self._test(col.endswith("e%fg", autoescape=True, escape="#"), {6})
1585
+ self._test(col.endswith("e#fg", autoescape=True, escape="#"), {9})
1586
+
1587
+ def test_contains_unescaped(self):
1588
+ col = self.tables.some_table.c.data
1589
+ self._test(col.contains("b%cde"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
1590
+
1591
+ def test_contains_autoescape(self):
1592
+ col = self.tables.some_table.c.data
1593
+ self._test(col.contains("b%cde", autoescape=True), {3})
1594
+
1595
+ def test_contains_escape(self):
1596
+ col = self.tables.some_table.c.data
1597
+ self._test(col.contains("b##cde", escape="#"), {7})
1598
+
1599
+ def test_contains_autoescape_escape(self):
1600
+ col = self.tables.some_table.c.data
1601
+ self._test(col.contains("b%cd", autoescape=True, escape="#"), {3})
1602
+ self._test(col.contains("b#cd", autoescape=True, escape="#"), {7})
1603
+
1604
+ @testing.requires.regexp_match
1605
+ def test_not_regexp_match(self):
1606
+ col = self.tables.some_table.c.data
1607
+ self._test(~col.regexp_match("a.cde"), {2, 3, 4, 7, 8, 10})
1608
+
1609
+ @testing.requires.regexp_replace
1610
+ def test_regexp_replace(self):
1611
+ col = self.tables.some_table.c.data
1612
+ self._test(
1613
+ col.regexp_replace("a.cde", "FOO").contains("FOO"), {1, 5, 6, 9}
1614
+ )
1615
+
1616
+ @testing.requires.regexp_match
1617
+ @testing.combinations(
1618
+ ("a.cde", {1, 5, 6, 9}),
1619
+ ("abc", {1, 5, 6, 9, 10}),
1620
+ ("^abc", {1, 5, 6, 9, 10}),
1621
+ ("9cde", {8}),
1622
+ ("^a", set(range(1, 11))),
1623
+ ("(b|c)", set(range(1, 11))),
1624
+ ("^(b|c)", set()),
1625
+ )
1626
+ def test_regexp_match(self, text, expected):
1627
+ col = self.tables.some_table.c.data
1628
+ self._test(col.regexp_match(text), expected)
1629
+
1630
+
1631
+ class ComputedColumnTest(fixtures.TablesTest):
1632
+ __backend__ = True
1633
+ __requires__ = ("computed_columns",)
1634
+
1635
+ @classmethod
1636
+ def define_tables(cls, metadata):
1637
+ Table(
1638
+ "square",
1639
+ metadata,
1640
+ Column("id", Integer, primary_key=True),
1641
+ Column("side", Integer),
1642
+ Column("area", Integer, Computed("side * side")),
1643
+ Column("perimeter", Integer, Computed("4 * side")),
1644
+ )
1645
+
1646
+ @classmethod
1647
+ def insert_data(cls, connection):
1648
+ connection.execute(
1649
+ cls.tables.square.insert(),
1650
+ [{"id": 1, "side": 10}, {"id": 10, "side": 42}],
1651
+ )
1652
+
1653
+ def test_select_all(self):
1654
+ with config.db.connect() as conn:
1655
+ res = conn.execute(
1656
+ select(text("*"))
1657
+ .select_from(self.tables.square)
1658
+ .order_by(self.tables.square.c.id)
1659
+ ).fetchall()
1660
+ eq_(res, [(1, 10, 100, 40), (10, 42, 1764, 168)])
1661
+
1662
+ def test_select_columns(self):
1663
+ with config.db.connect() as conn:
1664
+ res = conn.execute(
1665
+ select(
1666
+ self.tables.square.c.area, self.tables.square.c.perimeter
1667
+ )
1668
+ .select_from(self.tables.square)
1669
+ .order_by(self.tables.square.c.id)
1670
+ ).fetchall()
1671
+ eq_(res, [(100, 40), (1764, 168)])
1672
+
1673
+
1674
+ class IdentityColumnTest(fixtures.TablesTest):
1675
+ __backend__ = True
1676
+ __requires__ = ("identity_columns",)
1677
+ run_inserts = "once"
1678
+ run_deletes = "once"
1679
+
1680
+ @classmethod
1681
+ def define_tables(cls, metadata):
1682
+ Table(
1683
+ "tbl_a",
1684
+ metadata,
1685
+ Column(
1686
+ "id",
1687
+ Integer,
1688
+ Identity(
1689
+ always=True, start=42, nominvalue=True, nomaxvalue=True
1690
+ ),
1691
+ primary_key=True,
1692
+ ),
1693
+ Column("desc", String(100)),
1694
+ )
1695
+ Table(
1696
+ "tbl_b",
1697
+ metadata,
1698
+ Column(
1699
+ "id",
1700
+ Integer,
1701
+ Identity(increment=-5, start=0, minvalue=-1000, maxvalue=0),
1702
+ primary_key=True,
1703
+ ),
1704
+ Column("desc", String(100)),
1705
+ )
1706
+
1707
+ @classmethod
1708
+ def insert_data(cls, connection):
1709
+ connection.execute(
1710
+ cls.tables.tbl_a.insert(),
1711
+ [{"desc": "a"}, {"desc": "b"}],
1712
+ )
1713
+ connection.execute(
1714
+ cls.tables.tbl_b.insert(),
1715
+ [{"desc": "a"}, {"desc": "b"}],
1716
+ )
1717
+ connection.execute(
1718
+ cls.tables.tbl_b.insert(),
1719
+ [{"id": 42, "desc": "c"}],
1720
+ )
1721
+
1722
+ def test_select_all(self, connection):
1723
+ res = connection.execute(
1724
+ select(text("*"))
1725
+ .select_from(self.tables.tbl_a)
1726
+ .order_by(self.tables.tbl_a.c.id)
1727
+ ).fetchall()
1728
+ eq_(res, [(42, "a"), (43, "b")])
1729
+
1730
+ res = connection.execute(
1731
+ select(text("*"))
1732
+ .select_from(self.tables.tbl_b)
1733
+ .order_by(self.tables.tbl_b.c.id)
1734
+ ).fetchall()
1735
+ eq_(res, [(-5, "b"), (0, "a"), (42, "c")])
1736
+
1737
+ def test_select_columns(self, connection):
1738
+ res = connection.execute(
1739
+ select(self.tables.tbl_a.c.id).order_by(self.tables.tbl_a.c.id)
1740
+ ).fetchall()
1741
+ eq_(res, [(42,), (43,)])
1742
+
1743
+ @testing.requires.identity_columns_standard
1744
+ def test_insert_always_error(self, connection):
1745
+ def fn():
1746
+ connection.execute(
1747
+ self.tables.tbl_a.insert(),
1748
+ [{"id": 200, "desc": "a"}],
1749
+ )
1750
+
1751
+ assert_raises((DatabaseError, ProgrammingError), fn)
1752
+
1753
+
1754
+ class IdentityAutoincrementTest(fixtures.TablesTest):
1755
+ __backend__ = True
1756
+ __requires__ = ("autoincrement_without_sequence",)
1757
+
1758
+ @classmethod
1759
+ def define_tables(cls, metadata):
1760
+ Table(
1761
+ "tbl",
1762
+ metadata,
1763
+ Column(
1764
+ "id",
1765
+ Integer,
1766
+ Identity(),
1767
+ primary_key=True,
1768
+ autoincrement=True,
1769
+ ),
1770
+ Column("desc", String(100)),
1771
+ )
1772
+
1773
+ def test_autoincrement_with_identity(self, connection):
1774
+ res = connection.execute(self.tables.tbl.insert(), {"desc": "row"})
1775
+ res = connection.execute(self.tables.tbl.select()).first()
1776
+ eq_(res, (1, "row"))
1777
+
1778
+
1779
+ class ExistsTest(fixtures.TablesTest):
1780
+ __backend__ = True
1781
+
1782
+ @classmethod
1783
+ def define_tables(cls, metadata):
1784
+ Table(
1785
+ "stuff",
1786
+ metadata,
1787
+ Column("id", Integer, primary_key=True),
1788
+ Column("data", String(50)),
1789
+ )
1790
+
1791
+ @classmethod
1792
+ def insert_data(cls, connection):
1793
+ connection.execute(
1794
+ cls.tables.stuff.insert(),
1795
+ [
1796
+ {"id": 1, "data": "some data"},
1797
+ {"id": 2, "data": "some data"},
1798
+ {"id": 3, "data": "some data"},
1799
+ {"id": 4, "data": "some other data"},
1800
+ ],
1801
+ )
1802
+
1803
+ def test_select_exists(self, connection):
1804
+ stuff = self.tables.stuff
1805
+ eq_(
1806
+ connection.execute(
1807
+ select(literal(1)).where(
1808
+ exists().where(stuff.c.data == "some data")
1809
+ )
1810
+ ).fetchall(),
1811
+ [(1,)],
1812
+ )
1813
+
1814
+ def test_select_exists_false(self, connection):
1815
+ stuff = self.tables.stuff
1816
+ eq_(
1817
+ connection.execute(
1818
+ select(literal(1)).where(
1819
+ exists().where(stuff.c.data == "no data")
1820
+ )
1821
+ ).fetchall(),
1822
+ [],
1823
+ )
1824
+
1825
+
1826
+ class DistinctOnTest(AssertsCompiledSQL, fixtures.TablesTest):
1827
+ __backend__ = True
1828
+
1829
+ @testing.fails_if(testing.requires.supports_distinct_on)
1830
+ def test_distinct_on(self):
1831
+ stm = select("*").distinct(column("q")).select_from(table("foo"))
1832
+ with testing.expect_deprecated(
1833
+ "DISTINCT ON is currently supported only by the PostgreSQL "
1834
+ ):
1835
+ self.assert_compile(stm, "SELECT DISTINCT * FROM foo")
1836
+
1837
+
1838
+ class IsOrIsNotDistinctFromTest(fixtures.TablesTest):
1839
+ __backend__ = True
1840
+ __requires__ = ("supports_is_distinct_from",)
1841
+
1842
+ @classmethod
1843
+ def define_tables(cls, metadata):
1844
+ Table(
1845
+ "is_distinct_test",
1846
+ metadata,
1847
+ Column("id", Integer, primary_key=True),
1848
+ Column("col_a", Integer, nullable=True),
1849
+ Column("col_b", Integer, nullable=True),
1850
+ )
1851
+
1852
+ @testing.combinations(
1853
+ ("both_int_different", 0, 1, 1),
1854
+ ("both_int_same", 1, 1, 0),
1855
+ ("one_null_first", None, 1, 1),
1856
+ ("one_null_second", 0, None, 1),
1857
+ ("both_null", None, None, 0),
1858
+ id_="iaaa",
1859
+ argnames="col_a_value, col_b_value, expected_row_count_for_is",
1860
+ )
1861
+ def test_is_or_is_not_distinct_from(
1862
+ self, col_a_value, col_b_value, expected_row_count_for_is, connection
1863
+ ):
1864
+ tbl = self.tables.is_distinct_test
1865
+
1866
+ connection.execute(
1867
+ tbl.insert(),
1868
+ [{"id": 1, "col_a": col_a_value, "col_b": col_b_value}],
1869
+ )
1870
+
1871
+ result = connection.execute(
1872
+ tbl.select().where(tbl.c.col_a.is_distinct_from(tbl.c.col_b))
1873
+ ).fetchall()
1874
+ eq_(
1875
+ len(result),
1876
+ expected_row_count_for_is,
1877
+ )
1878
+
1879
+ expected_row_count_for_is_not = (
1880
+ 1 if expected_row_count_for_is == 0 else 0
1881
+ )
1882
+ result = connection.execute(
1883
+ tbl.select().where(tbl.c.col_a.is_not_distinct_from(tbl.c.col_b))
1884
+ ).fetchall()
1885
+ eq_(
1886
+ len(result),
1887
+ expected_row_count_for_is_not,
1888
+ )
1889
+
1890
+
1891
+ class WindowFunctionTest(fixtures.TablesTest):
1892
+ __requires__ = ("window_functions",)
1893
+
1894
+ __backend__ = True
1895
+
1896
+ @classmethod
1897
+ def define_tables(cls, metadata):
1898
+ Table(
1899
+ "some_table",
1900
+ metadata,
1901
+ Column("id", Integer, primary_key=True),
1902
+ Column("col1", Integer),
1903
+ Column("col2", Integer),
1904
+ )
1905
+
1906
+ @classmethod
1907
+ def insert_data(cls, connection):
1908
+ connection.execute(
1909
+ cls.tables.some_table.insert(),
1910
+ [{"id": i, "col1": i, "col2": i * 5} for i in range(1, 50)],
1911
+ )
1912
+
1913
+ def test_window(self, connection):
1914
+ some_table = self.tables.some_table
1915
+ rows = connection.execute(
1916
+ select(
1917
+ func.max(some_table.c.col2).over(
1918
+ order_by=[some_table.c.col1.desc()]
1919
+ )
1920
+ ).where(some_table.c.col1 < 20)
1921
+ ).all()
1922
+
1923
+ eq_(rows, [(95,) for i in range(19)])
1924
+
1925
+ def test_window_rows_between(self, connection):
1926
+ some_table = self.tables.some_table
1927
+
1928
+ # note the rows are part of the cache key right now, not handled
1929
+ # as binds. this is issue #11515
1930
+ rows = connection.execute(
1931
+ select(
1932
+ func.max(some_table.c.col2).over(
1933
+ order_by=[some_table.c.col1],
1934
+ rows=(-5, 0),
1935
+ )
1936
+ )
1937
+ ).all()
1938
+
1939
+ eq_(rows, [(i,) for i in range(5, 250, 5)])
1940
+
1941
+
1942
+ class BitwiseTest(fixtures.TablesTest):
1943
+ __backend__ = True
1944
+ run_inserts = run_deletes = "once"
1945
+
1946
+ inserted_data = [{"a": i, "b": i + 1} for i in range(10)]
1947
+
1948
+ @classmethod
1949
+ def define_tables(cls, metadata):
1950
+ Table("bitwise", metadata, Column("a", Integer), Column("b", Integer))
1951
+
1952
+ @classmethod
1953
+ def insert_data(cls, connection):
1954
+ connection.execute(cls.tables.bitwise.insert(), cls.inserted_data)
1955
+
1956
+ @testing.combinations(
1957
+ (
1958
+ lambda a: a.bitwise_xor(5),
1959
+ [i for i in range(10) if i != 5],
1960
+ testing.requires.supports_bitwise_xor,
1961
+ ),
1962
+ (
1963
+ lambda a: a.bitwise_or(1),
1964
+ list(range(10)),
1965
+ testing.requires.supports_bitwise_or,
1966
+ ),
1967
+ (
1968
+ lambda a: a.bitwise_and(4),
1969
+ list(range(4, 8)),
1970
+ testing.requires.supports_bitwise_and,
1971
+ ),
1972
+ (
1973
+ lambda a: (a - 2).bitwise_not(),
1974
+ [0],
1975
+ testing.requires.supports_bitwise_not,
1976
+ ),
1977
+ (
1978
+ lambda a: a.bitwise_lshift(1),
1979
+ list(range(1, 10)),
1980
+ testing.requires.supports_bitwise_shift,
1981
+ ),
1982
+ (
1983
+ lambda a: a.bitwise_rshift(2),
1984
+ list(range(4, 10)),
1985
+ testing.requires.supports_bitwise_shift,
1986
+ ),
1987
+ argnames="case, expected",
1988
+ )
1989
+ def test_bitwise(self, case, expected, connection):
1990
+ tbl = self.tables.bitwise
1991
+
1992
+ a = tbl.c.a
1993
+
1994
+ op = testing.resolve_lambda(case, a=a)
1995
+
1996
+ stmt = select(tbl).where(op > 0).order_by(a)
1997
+
1998
+ res = connection.execute(stmt).mappings().all()
1999
+ eq_(res, [self.inserted_data[i] for i in expected])