test_results.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # testing/suite/test_results.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. import datetime
  9. from .. import engines
  10. from .. import fixtures
  11. from ..assertions import eq_
  12. from ..config import requirements
  13. from ..schema import Column
  14. from ..schema import Table
  15. from ... import DateTime
  16. from ... import func
  17. from ... import Integer
  18. from ... import select
  19. from ... import sql
  20. from ... import String
  21. from ... import testing
  22. from ... import text
  23. class RowFetchTest(fixtures.TablesTest):
  24. __backend__ = True
  25. @classmethod
  26. def define_tables(cls, metadata):
  27. Table(
  28. "plain_pk",
  29. metadata,
  30. Column("id", Integer, primary_key=True),
  31. Column("data", String(50)),
  32. )
  33. Table(
  34. "has_dates",
  35. metadata,
  36. Column("id", Integer, primary_key=True),
  37. Column("today", DateTime),
  38. )
  39. @classmethod
  40. def insert_data(cls, connection):
  41. connection.execute(
  42. cls.tables.plain_pk.insert(),
  43. [
  44. {"id": 1, "data": "d1"},
  45. {"id": 2, "data": "d2"},
  46. {"id": 3, "data": "d3"},
  47. ],
  48. )
  49. connection.execute(
  50. cls.tables.has_dates.insert(),
  51. [{"id": 1, "today": datetime.datetime(2006, 5, 12, 12, 0, 0)}],
  52. )
  53. def test_via_attr(self, connection):
  54. row = connection.execute(
  55. self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id)
  56. ).first()
  57. eq_(row.id, 1)
  58. eq_(row.data, "d1")
  59. def test_via_string(self, connection):
  60. row = connection.execute(
  61. self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id)
  62. ).first()
  63. eq_(row._mapping["id"], 1)
  64. eq_(row._mapping["data"], "d1")
  65. def test_via_int(self, connection):
  66. row = connection.execute(
  67. self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id)
  68. ).first()
  69. eq_(row[0], 1)
  70. eq_(row[1], "d1")
  71. def test_via_col_object(self, connection):
  72. row = connection.execute(
  73. self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id)
  74. ).first()
  75. eq_(row._mapping[self.tables.plain_pk.c.id], 1)
  76. eq_(row._mapping[self.tables.plain_pk.c.data], "d1")
  77. @requirements.duplicate_names_in_cursor_description
  78. def test_row_with_dupe_names(self, connection):
  79. result = connection.execute(
  80. select(
  81. self.tables.plain_pk.c.data,
  82. self.tables.plain_pk.c.data.label("data"),
  83. ).order_by(self.tables.plain_pk.c.id)
  84. )
  85. row = result.first()
  86. eq_(result.keys(), ["data", "data"])
  87. eq_(row, ("d1", "d1"))
  88. def test_row_w_scalar_select(self, connection):
  89. """test that a scalar select as a column is returned as such
  90. and that type conversion works OK.
  91. (this is half a SQLAlchemy Core test and half to catch database
  92. backends that may have unusual behavior with scalar selects.)
  93. """
  94. datetable = self.tables.has_dates
  95. s = select(datetable.alias("x").c.today).scalar_subquery()
  96. s2 = select(datetable.c.id, s.label("somelabel"))
  97. row = connection.execute(s2).first()
  98. eq_(row.somelabel, datetime.datetime(2006, 5, 12, 12, 0, 0))
  99. class PercentSchemaNamesTest(fixtures.TablesTest):
  100. """tests using percent signs, spaces in table and column names.
  101. This didn't work for PostgreSQL / MySQL drivers for a long time
  102. but is now supported.
  103. """
  104. __requires__ = ("percent_schema_names",)
  105. __backend__ = True
  106. @classmethod
  107. def define_tables(cls, metadata):
  108. cls.tables.percent_table = Table(
  109. "percent%table",
  110. metadata,
  111. Column("percent%", Integer),
  112. Column("spaces % more spaces", Integer),
  113. )
  114. cls.tables.lightweight_percent_table = sql.table(
  115. "percent%table",
  116. sql.column("percent%"),
  117. sql.column("spaces % more spaces"),
  118. )
  119. def test_single_roundtrip(self, connection):
  120. percent_table = self.tables.percent_table
  121. for params in [
  122. {"percent%": 5, "spaces % more spaces": 12},
  123. {"percent%": 7, "spaces % more spaces": 11},
  124. {"percent%": 9, "spaces % more spaces": 10},
  125. {"percent%": 11, "spaces % more spaces": 9},
  126. ]:
  127. connection.execute(percent_table.insert(), params)
  128. self._assert_table(connection)
  129. def test_executemany_roundtrip(self, connection):
  130. percent_table = self.tables.percent_table
  131. connection.execute(
  132. percent_table.insert(), {"percent%": 5, "spaces % more spaces": 12}
  133. )
  134. connection.execute(
  135. percent_table.insert(),
  136. [
  137. {"percent%": 7, "spaces % more spaces": 11},
  138. {"percent%": 9, "spaces % more spaces": 10},
  139. {"percent%": 11, "spaces % more spaces": 9},
  140. ],
  141. )
  142. self._assert_table(connection)
  143. @requirements.insert_executemany_returning
  144. def test_executemany_returning_roundtrip(self, connection):
  145. percent_table = self.tables.percent_table
  146. connection.execute(
  147. percent_table.insert(), {"percent%": 5, "spaces % more spaces": 12}
  148. )
  149. result = connection.execute(
  150. percent_table.insert().returning(
  151. percent_table.c["percent%"],
  152. percent_table.c["spaces % more spaces"],
  153. ),
  154. [
  155. {"percent%": 7, "spaces % more spaces": 11},
  156. {"percent%": 9, "spaces % more spaces": 10},
  157. {"percent%": 11, "spaces % more spaces": 9},
  158. ],
  159. )
  160. eq_(result.all(), [(7, 11), (9, 10), (11, 9)])
  161. self._assert_table(connection)
  162. def _assert_table(self, conn):
  163. percent_table = self.tables.percent_table
  164. lightweight_percent_table = self.tables.lightweight_percent_table
  165. for table in (
  166. percent_table,
  167. percent_table.alias(),
  168. lightweight_percent_table,
  169. lightweight_percent_table.alias(),
  170. ):
  171. eq_(
  172. list(
  173. conn.execute(table.select().order_by(table.c["percent%"]))
  174. ),
  175. [(5, 12), (7, 11), (9, 10), (11, 9)],
  176. )
  177. eq_(
  178. list(
  179. conn.execute(
  180. table.select()
  181. .where(table.c["spaces % more spaces"].in_([9, 10]))
  182. .order_by(table.c["percent%"])
  183. )
  184. ),
  185. [(9, 10), (11, 9)],
  186. )
  187. row = conn.execute(
  188. table.select().order_by(table.c["percent%"])
  189. ).first()
  190. eq_(row._mapping["percent%"], 5)
  191. eq_(row._mapping["spaces % more spaces"], 12)
  192. eq_(row._mapping[table.c["percent%"]], 5)
  193. eq_(row._mapping[table.c["spaces % more spaces"]], 12)
  194. conn.execute(
  195. percent_table.update().values(
  196. {percent_table.c["spaces % more spaces"]: 15}
  197. )
  198. )
  199. eq_(
  200. list(
  201. conn.execute(
  202. percent_table.select().order_by(
  203. percent_table.c["percent%"]
  204. )
  205. )
  206. ),
  207. [(5, 15), (7, 15), (9, 15), (11, 15)],
  208. )
  209. class ServerSideCursorsTest(
  210. fixtures.TestBase, testing.AssertsExecutionResults
  211. ):
  212. __requires__ = ("server_side_cursors",)
  213. __backend__ = True
  214. def _is_server_side(self, cursor):
  215. # TODO: this is a huge issue as it prevents these tests from being
  216. # usable by third party dialects.
  217. if self.engine.dialect.driver == "psycopg2":
  218. return bool(cursor.name)
  219. elif self.engine.dialect.driver == "pymysql":
  220. sscursor = __import__("pymysql.cursors").cursors.SSCursor
  221. return isinstance(cursor, sscursor)
  222. elif self.engine.dialect.driver in ("aiomysql", "asyncmy", "aioodbc"):
  223. return cursor.server_side
  224. elif self.engine.dialect.driver == "mysqldb":
  225. sscursor = __import__("MySQLdb.cursors").cursors.SSCursor
  226. return isinstance(cursor, sscursor)
  227. elif self.engine.dialect.driver == "mariadbconnector":
  228. return not cursor.buffered
  229. elif self.engine.dialect.driver in ("asyncpg", "aiosqlite"):
  230. return cursor.server_side
  231. elif self.engine.dialect.driver == "pg8000":
  232. return getattr(cursor, "server_side", False)
  233. elif self.engine.dialect.driver == "psycopg":
  234. return bool(getattr(cursor, "name", False))
  235. else:
  236. return False
  237. def _fixture(self, server_side_cursors):
  238. if server_side_cursors:
  239. with testing.expect_deprecated(
  240. "The create_engine.server_side_cursors parameter is "
  241. "deprecated and will be removed in a future release. "
  242. "Please use the Connection.execution_options.stream_results "
  243. "parameter."
  244. ):
  245. self.engine = engines.testing_engine(
  246. options={"server_side_cursors": server_side_cursors}
  247. )
  248. else:
  249. self.engine = engines.testing_engine(
  250. options={"server_side_cursors": server_side_cursors}
  251. )
  252. return self.engine
  253. @testing.combinations(
  254. ("global_string", True, "select 1", True),
  255. ("global_text", True, text("select 1"), True),
  256. ("global_expr", True, select(1), True),
  257. ("global_off_explicit", False, text("select 1"), False),
  258. (
  259. "stmt_option",
  260. False,
  261. select(1).execution_options(stream_results=True),
  262. True,
  263. ),
  264. (
  265. "stmt_option_disabled",
  266. True,
  267. select(1).execution_options(stream_results=False),
  268. False,
  269. ),
  270. ("for_update_expr", True, select(1).with_for_update(), True),
  271. # TODO: need a real requirement for this, or dont use this test
  272. (
  273. "for_update_string",
  274. True,
  275. "SELECT 1 FOR UPDATE",
  276. True,
  277. testing.skip_if(["sqlite", "mssql"]),
  278. ),
  279. ("text_no_ss", False, text("select 42"), False),
  280. (
  281. "text_ss_option",
  282. False,
  283. text("select 42").execution_options(stream_results=True),
  284. True,
  285. ),
  286. id_="iaaa",
  287. argnames="engine_ss_arg, statement, cursor_ss_status",
  288. )
  289. def test_ss_cursor_status(
  290. self, engine_ss_arg, statement, cursor_ss_status
  291. ):
  292. engine = self._fixture(engine_ss_arg)
  293. with engine.begin() as conn:
  294. if isinstance(statement, str):
  295. result = conn.exec_driver_sql(statement)
  296. else:
  297. result = conn.execute(statement)
  298. eq_(self._is_server_side(result.cursor), cursor_ss_status)
  299. result.close()
  300. def test_conn_option(self):
  301. engine = self._fixture(False)
  302. with engine.connect() as conn:
  303. # should be enabled for this one
  304. result = conn.execution_options(
  305. stream_results=True
  306. ).exec_driver_sql("select 1")
  307. assert self._is_server_side(result.cursor)
  308. # the connection has autobegun, which means at the end of the
  309. # block, we will roll back, which on MySQL at least will fail
  310. # with "Commands out of sync" if the result set
  311. # is not closed, so we close it first.
  312. #
  313. # fun fact! why did we not have this result.close() in this test
  314. # before 2.0? don't we roll back in the connection pool
  315. # unconditionally? yes! and in fact if you run this test in 1.4
  316. # with stdout shown, there is in fact "Exception during reset or
  317. # similar" with "Commands out sync" emitted a warning! 2.0's
  318. # architecture finds and fixes what was previously an expensive
  319. # silent error condition.
  320. result.close()
  321. def test_stmt_enabled_conn_option_disabled(self):
  322. engine = self._fixture(False)
  323. s = select(1).execution_options(stream_results=True)
  324. with engine.connect() as conn:
  325. # not this one
  326. result = conn.execution_options(stream_results=False).execute(s)
  327. assert not self._is_server_side(result.cursor)
  328. def test_aliases_and_ss(self):
  329. engine = self._fixture(False)
  330. s1 = (
  331. select(sql.literal_column("1").label("x"))
  332. .execution_options(stream_results=True)
  333. .subquery()
  334. )
  335. # options don't propagate out when subquery is used as a FROM clause
  336. with engine.begin() as conn:
  337. result = conn.execute(s1.select())
  338. assert not self._is_server_side(result.cursor)
  339. result.close()
  340. s2 = select(1).select_from(s1)
  341. with engine.begin() as conn:
  342. result = conn.execute(s2)
  343. assert not self._is_server_side(result.cursor)
  344. result.close()
  345. def test_roundtrip_fetchall(self, metadata):
  346. md = self.metadata
  347. engine = self._fixture(True)
  348. test_table = Table(
  349. "test_table",
  350. md,
  351. Column("id", Integer, primary_key=True),
  352. Column("data", String(50)),
  353. )
  354. with engine.begin() as connection:
  355. test_table.create(connection, checkfirst=True)
  356. connection.execute(test_table.insert(), dict(data="data1"))
  357. connection.execute(test_table.insert(), dict(data="data2"))
  358. eq_(
  359. connection.execute(
  360. test_table.select().order_by(test_table.c.id)
  361. ).fetchall(),
  362. [(1, "data1"), (2, "data2")],
  363. )
  364. connection.execute(
  365. test_table.update()
  366. .where(test_table.c.id == 2)
  367. .values(data=test_table.c.data + " updated")
  368. )
  369. eq_(
  370. connection.execute(
  371. test_table.select().order_by(test_table.c.id)
  372. ).fetchall(),
  373. [(1, "data1"), (2, "data2 updated")],
  374. )
  375. connection.execute(test_table.delete())
  376. eq_(
  377. connection.scalar(
  378. select(func.count("*")).select_from(test_table)
  379. ),
  380. 0,
  381. )
  382. def test_roundtrip_fetchmany(self, metadata):
  383. md = self.metadata
  384. engine = self._fixture(True)
  385. test_table = Table(
  386. "test_table",
  387. md,
  388. Column("id", Integer, primary_key=True),
  389. Column("data", String(50)),
  390. )
  391. with engine.begin() as connection:
  392. test_table.create(connection, checkfirst=True)
  393. connection.execute(
  394. test_table.insert(),
  395. [dict(data="data%d" % i) for i in range(1, 20)],
  396. )
  397. result = connection.execute(
  398. test_table.select().order_by(test_table.c.id)
  399. )
  400. eq_(
  401. result.fetchmany(5),
  402. [(i, "data%d" % i) for i in range(1, 6)],
  403. )
  404. eq_(
  405. result.fetchmany(10),
  406. [(i, "data%d" % i) for i in range(6, 16)],
  407. )
  408. eq_(result.fetchall(), [(i, "data%d" % i) for i in range(16, 20)])