test_results.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. import datetime
  8. from .. import engines
  9. from .. import fixtures
  10. from ..assertions import eq_
  11. from ..config import requirements
  12. from ..schema import Column
  13. from ..schema import Table
  14. from ... import DateTime
  15. from ... import func
  16. from ... import Integer
  17. from ... import select
  18. from ... import sql
  19. from ... import String
  20. from ... import testing
  21. from ... import text
  22. from ... import util
  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. def _assert_table(self, conn):
  144. percent_table = self.tables.percent_table
  145. lightweight_percent_table = self.tables.lightweight_percent_table
  146. for table in (
  147. percent_table,
  148. percent_table.alias(),
  149. lightweight_percent_table,
  150. lightweight_percent_table.alias(),
  151. ):
  152. eq_(
  153. list(
  154. conn.execute(table.select().order_by(table.c["percent%"]))
  155. ),
  156. [(5, 12), (7, 11), (9, 10), (11, 9)],
  157. )
  158. eq_(
  159. list(
  160. conn.execute(
  161. table.select()
  162. .where(table.c["spaces % more spaces"].in_([9, 10]))
  163. .order_by(table.c["percent%"])
  164. )
  165. ),
  166. [(9, 10), (11, 9)],
  167. )
  168. row = conn.execute(
  169. table.select().order_by(table.c["percent%"])
  170. ).first()
  171. eq_(row._mapping["percent%"], 5)
  172. eq_(row._mapping["spaces % more spaces"], 12)
  173. eq_(row._mapping[table.c["percent%"]], 5)
  174. eq_(row._mapping[table.c["spaces % more spaces"]], 12)
  175. conn.execute(
  176. percent_table.update().values(
  177. {percent_table.c["spaces % more spaces"]: 15}
  178. )
  179. )
  180. eq_(
  181. list(
  182. conn.execute(
  183. percent_table.select().order_by(
  184. percent_table.c["percent%"]
  185. )
  186. )
  187. ),
  188. [(5, 15), (7, 15), (9, 15), (11, 15)],
  189. )
  190. class ServerSideCursorsTest(
  191. fixtures.TestBase, testing.AssertsExecutionResults
  192. ):
  193. __requires__ = ("server_side_cursors",)
  194. __backend__ = True
  195. def _is_server_side(self, cursor):
  196. # TODO: this is a huge issue as it prevents these tests from being
  197. # usable by third party dialects.
  198. if self.engine.dialect.driver == "psycopg2":
  199. return bool(cursor.name)
  200. elif self.engine.dialect.driver == "pymysql":
  201. sscursor = __import__("pymysql.cursors").cursors.SSCursor
  202. return isinstance(cursor, sscursor)
  203. elif self.engine.dialect.driver in ("aiomysql", "asyncmy"):
  204. return cursor.server_side
  205. elif self.engine.dialect.driver == "mysqldb":
  206. sscursor = __import__("MySQLdb.cursors").cursors.SSCursor
  207. return isinstance(cursor, sscursor)
  208. elif self.engine.dialect.driver == "mariadbconnector":
  209. return not cursor.buffered
  210. elif self.engine.dialect.driver in ("asyncpg", "aiosqlite"):
  211. return cursor.server_side
  212. elif self.engine.dialect.driver == "pg8000":
  213. return getattr(cursor, "server_side", False)
  214. else:
  215. return False
  216. def _fixture(self, server_side_cursors):
  217. if server_side_cursors:
  218. with testing.expect_deprecated(
  219. "The create_engine.server_side_cursors parameter is "
  220. "deprecated and will be removed in a future release. "
  221. "Please use the Connection.execution_options.stream_results "
  222. "parameter."
  223. ):
  224. self.engine = engines.testing_engine(
  225. options={"server_side_cursors": server_side_cursors}
  226. )
  227. else:
  228. self.engine = engines.testing_engine(
  229. options={"server_side_cursors": server_side_cursors}
  230. )
  231. return self.engine
  232. @testing.combinations(
  233. ("global_string", True, "select 1", True),
  234. ("global_text", True, text("select 1"), True),
  235. ("global_expr", True, select(1), True),
  236. ("global_off_explicit", False, text("select 1"), False),
  237. (
  238. "stmt_option",
  239. False,
  240. select(1).execution_options(stream_results=True),
  241. True,
  242. ),
  243. (
  244. "stmt_option_disabled",
  245. True,
  246. select(1).execution_options(stream_results=False),
  247. False,
  248. ),
  249. ("for_update_expr", True, select(1).with_for_update(), True),
  250. # TODO: need a real requirement for this, or dont use this test
  251. (
  252. "for_update_string",
  253. True,
  254. "SELECT 1 FOR UPDATE",
  255. True,
  256. testing.skip_if("sqlite"),
  257. ),
  258. ("text_no_ss", False, text("select 42"), False),
  259. (
  260. "text_ss_option",
  261. False,
  262. text("select 42").execution_options(stream_results=True),
  263. True,
  264. ),
  265. id_="iaaa",
  266. argnames="engine_ss_arg, statement, cursor_ss_status",
  267. )
  268. def test_ss_cursor_status(
  269. self, engine_ss_arg, statement, cursor_ss_status
  270. ):
  271. engine = self._fixture(engine_ss_arg)
  272. with engine.begin() as conn:
  273. if isinstance(statement, util.string_types):
  274. result = conn.exec_driver_sql(statement)
  275. else:
  276. result = conn.execute(statement)
  277. eq_(self._is_server_side(result.cursor), cursor_ss_status)
  278. result.close()
  279. def test_conn_option(self):
  280. engine = self._fixture(False)
  281. with engine.connect() as conn:
  282. # should be enabled for this one
  283. result = conn.execution_options(
  284. stream_results=True
  285. ).exec_driver_sql("select 1")
  286. assert self._is_server_side(result.cursor)
  287. def test_stmt_enabled_conn_option_disabled(self):
  288. engine = self._fixture(False)
  289. s = select(1).execution_options(stream_results=True)
  290. with engine.connect() as conn:
  291. # not this one
  292. result = conn.execution_options(stream_results=False).execute(s)
  293. assert not self._is_server_side(result.cursor)
  294. def test_aliases_and_ss(self):
  295. engine = self._fixture(False)
  296. s1 = (
  297. select(sql.literal_column("1").label("x"))
  298. .execution_options(stream_results=True)
  299. .subquery()
  300. )
  301. # options don't propagate out when subquery is used as a FROM clause
  302. with engine.begin() as conn:
  303. result = conn.execute(s1.select())
  304. assert not self._is_server_side(result.cursor)
  305. result.close()
  306. s2 = select(1).select_from(s1)
  307. with engine.begin() as conn:
  308. result = conn.execute(s2)
  309. assert not self._is_server_side(result.cursor)
  310. result.close()
  311. def test_roundtrip_fetchall(self, metadata):
  312. md = self.metadata
  313. engine = self._fixture(True)
  314. test_table = Table(
  315. "test_table",
  316. md,
  317. Column("id", Integer, primary_key=True),
  318. Column("data", String(50)),
  319. )
  320. with engine.begin() as connection:
  321. test_table.create(connection, checkfirst=True)
  322. connection.execute(test_table.insert(), dict(data="data1"))
  323. connection.execute(test_table.insert(), dict(data="data2"))
  324. eq_(
  325. connection.execute(
  326. test_table.select().order_by(test_table.c.id)
  327. ).fetchall(),
  328. [(1, "data1"), (2, "data2")],
  329. )
  330. connection.execute(
  331. test_table.update()
  332. .where(test_table.c.id == 2)
  333. .values(data=test_table.c.data + " updated")
  334. )
  335. eq_(
  336. connection.execute(
  337. test_table.select().order_by(test_table.c.id)
  338. ).fetchall(),
  339. [(1, "data1"), (2, "data2 updated")],
  340. )
  341. connection.execute(test_table.delete())
  342. eq_(
  343. connection.scalar(
  344. select(func.count("*")).select_from(test_table)
  345. ),
  346. 0,
  347. )
  348. def test_roundtrip_fetchmany(self, metadata):
  349. md = self.metadata
  350. engine = self._fixture(True)
  351. test_table = Table(
  352. "test_table",
  353. md,
  354. Column("id", Integer, primary_key=True),
  355. Column("data", String(50)),
  356. )
  357. with engine.begin() as connection:
  358. test_table.create(connection, checkfirst=True)
  359. connection.execute(
  360. test_table.insert(),
  361. [dict(data="data%d" % i) for i in range(1, 20)],
  362. )
  363. result = connection.execute(
  364. test_table.select().order_by(test_table.c.id)
  365. )
  366. eq_(
  367. result.fetchmany(5),
  368. [(i, "data%d" % i) for i in range(1, 6)],
  369. )
  370. eq_(
  371. result.fetchmany(10),
  372. [(i, "data%d" % i) for i in range(6, 16)],
  373. )
  374. eq_(result.fetchall(), [(i, "data%d" % i) for i in range(16, 20)])