test_select.py 61 KB

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