test_select.py 61 KB

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