test_results.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. from .. import fixtures, config
  2. from ..config import requirements
  3. from .. import exclusions
  4. from ..assertions import eq_
  5. from .. import engines
  6. from ... import testing
  7. from sqlalchemy import Integer, String, select, util, sql, DateTime, text, func
  8. import datetime
  9. from ..schema import Table, Column
  10. class RowFetchTest(fixtures.TablesTest):
  11. __backend__ = True
  12. @classmethod
  13. def define_tables(cls, metadata):
  14. Table('plain_pk', metadata,
  15. Column('id', Integer, primary_key=True),
  16. Column('data', String(50))
  17. )
  18. Table('has_dates', metadata,
  19. Column('id', Integer, primary_key=True),
  20. Column('today', DateTime)
  21. )
  22. @classmethod
  23. def insert_data(cls):
  24. config.db.execute(
  25. cls.tables.plain_pk.insert(),
  26. [
  27. {"id": 1, "data": "d1"},
  28. {"id": 2, "data": "d2"},
  29. {"id": 3, "data": "d3"},
  30. ]
  31. )
  32. config.db.execute(
  33. cls.tables.has_dates.insert(),
  34. [
  35. {"id": 1, "today": datetime.datetime(2006, 5, 12, 12, 0, 0)}
  36. ]
  37. )
  38. def test_via_string(self):
  39. row = config.db.execute(
  40. self.tables.plain_pk.select().
  41. order_by(self.tables.plain_pk.c.id)
  42. ).first()
  43. eq_(
  44. row['id'], 1
  45. )
  46. eq_(
  47. row['data'], "d1"
  48. )
  49. def test_via_int(self):
  50. row = config.db.execute(
  51. self.tables.plain_pk.select().
  52. order_by(self.tables.plain_pk.c.id)
  53. ).first()
  54. eq_(
  55. row[0], 1
  56. )
  57. eq_(
  58. row[1], "d1"
  59. )
  60. def test_via_col_object(self):
  61. row = config.db.execute(
  62. self.tables.plain_pk.select().
  63. order_by(self.tables.plain_pk.c.id)
  64. ).first()
  65. eq_(
  66. row[self.tables.plain_pk.c.id], 1
  67. )
  68. eq_(
  69. row[self.tables.plain_pk.c.data], "d1"
  70. )
  71. @requirements.duplicate_names_in_cursor_description
  72. def test_row_with_dupe_names(self):
  73. result = config.db.execute(
  74. select([self.tables.plain_pk.c.data,
  75. self.tables.plain_pk.c.data.label('data')]).
  76. order_by(self.tables.plain_pk.c.id)
  77. )
  78. row = result.first()
  79. eq_(result.keys(), ['data', 'data'])
  80. eq_(row, ('d1', 'd1'))
  81. def test_row_w_scalar_select(self):
  82. """test that a scalar select as a column is returned as such
  83. and that type conversion works OK.
  84. (this is half a SQLAlchemy Core test and half to catch database
  85. backends that may have unusual behavior with scalar selects.)
  86. """
  87. datetable = self.tables.has_dates
  88. s = select([datetable.alias('x').c.today]).as_scalar()
  89. s2 = select([datetable.c.id, s.label('somelabel')])
  90. row = config.db.execute(s2).first()
  91. eq_(row['somelabel'], datetime.datetime(2006, 5, 12, 12, 0, 0))
  92. class PercentSchemaNamesTest(fixtures.TablesTest):
  93. """tests using percent signs, spaces in table and column names.
  94. This is a very fringe use case, doesn't work for MySQL
  95. or PostgreSQL. the requirement, "percent_schema_names",
  96. is marked "skip" by default.
  97. """
  98. __requires__ = ('percent_schema_names', )
  99. __backend__ = True
  100. @classmethod
  101. def define_tables(cls, metadata):
  102. cls.tables.percent_table = Table('percent%table', metadata,
  103. Column("percent%", Integer),
  104. Column(
  105. "spaces % more spaces", Integer),
  106. )
  107. cls.tables.lightweight_percent_table = sql.table(
  108. 'percent%table', sql.column("percent%"),
  109. sql.column("spaces % more spaces")
  110. )
  111. def test_single_roundtrip(self):
  112. percent_table = self.tables.percent_table
  113. for params in [
  114. {'percent%': 5, 'spaces % more spaces': 12},
  115. {'percent%': 7, 'spaces % more spaces': 11},
  116. {'percent%': 9, 'spaces % more spaces': 10},
  117. {'percent%': 11, 'spaces % more spaces': 9}
  118. ]:
  119. config.db.execute(percent_table.insert(), params)
  120. self._assert_table()
  121. def test_executemany_roundtrip(self):
  122. percent_table = self.tables.percent_table
  123. config.db.execute(
  124. percent_table.insert(),
  125. {'percent%': 5, 'spaces % more spaces': 12}
  126. )
  127. config.db.execute(
  128. percent_table.insert(),
  129. [{'percent%': 7, 'spaces % more spaces': 11},
  130. {'percent%': 9, 'spaces % more spaces': 10},
  131. {'percent%': 11, 'spaces % more spaces': 9}]
  132. )
  133. self._assert_table()
  134. def _assert_table(self):
  135. percent_table = self.tables.percent_table
  136. lightweight_percent_table = self.tables.lightweight_percent_table
  137. for table in (
  138. percent_table,
  139. percent_table.alias(),
  140. lightweight_percent_table,
  141. lightweight_percent_table.alias()):
  142. eq_(
  143. list(
  144. config.db.execute(
  145. table.select().order_by(table.c['percent%'])
  146. )
  147. ),
  148. [
  149. (5, 12),
  150. (7, 11),
  151. (9, 10),
  152. (11, 9)
  153. ]
  154. )
  155. eq_(
  156. list(
  157. config.db.execute(
  158. table.select().
  159. where(table.c['spaces % more spaces'].in_([9, 10])).
  160. order_by(table.c['percent%']),
  161. )
  162. ),
  163. [
  164. (9, 10),
  165. (11, 9)
  166. ]
  167. )
  168. row = config.db.execute(table.select().
  169. order_by(table.c['percent%'])).first()
  170. eq_(row['percent%'], 5)
  171. eq_(row['spaces % more spaces'], 12)
  172. eq_(row[table.c['percent%']], 5)
  173. eq_(row[table.c['spaces % more spaces']], 12)
  174. config.db.execute(
  175. percent_table.update().values(
  176. {percent_table.c['spaces % more spaces']: 15}
  177. )
  178. )
  179. eq_(
  180. list(
  181. config.db.execute(
  182. percent_table.
  183. select().
  184. order_by(percent_table.c['percent%'])
  185. )
  186. ),
  187. [(5, 15), (7, 15), (9, 15), (11, 15)]
  188. )
  189. class ServerSideCursorsTest(fixtures.TestBase, testing.AssertsExecutionResults):
  190. __requires__ = ('server_side_cursors', )
  191. __backend__ = True
  192. def _is_server_side(self, cursor):
  193. if self.engine.url.drivername == 'postgresql':
  194. return cursor.name
  195. elif self.engine.url.drivername == 'mysql':
  196. sscursor = __import__('MySQLdb.cursors').cursors.SSCursor
  197. return isinstance(cursor, sscursor)
  198. elif self.engine.url.drivername == 'mysql+pymysql':
  199. sscursor = __import__('pymysql.cursors').cursors.SSCursor
  200. return isinstance(cursor, sscursor)
  201. else:
  202. return False
  203. def _fixture(self, server_side_cursors):
  204. self.engine = engines.testing_engine(
  205. options={'server_side_cursors': server_side_cursors}
  206. )
  207. return self.engine
  208. def tearDown(self):
  209. engines.testing_reaper.close_all()
  210. self.engine.dispose()
  211. def test_global_string(self):
  212. engine = self._fixture(True)
  213. result = engine.execute('select 1')
  214. assert self._is_server_side(result.cursor)
  215. def test_global_text(self):
  216. engine = self._fixture(True)
  217. result = engine.execute(text('select 1'))
  218. assert self._is_server_side(result.cursor)
  219. def test_global_expr(self):
  220. engine = self._fixture(True)
  221. result = engine.execute(select([1]))
  222. assert self._is_server_side(result.cursor)
  223. def test_global_off_explicit(self):
  224. engine = self._fixture(False)
  225. result = engine.execute(text('select 1'))
  226. # It should be off globally ...
  227. assert not self._is_server_side(result.cursor)
  228. def test_stmt_option(self):
  229. engine = self._fixture(False)
  230. s = select([1]).execution_options(stream_results=True)
  231. result = engine.execute(s)
  232. # ... but enabled for this one.
  233. assert self._is_server_side(result.cursor)
  234. def test_conn_option(self):
  235. engine = self._fixture(False)
  236. # and this one
  237. result = \
  238. engine.connect().execution_options(stream_results=True).\
  239. execute('select 1'
  240. )
  241. assert self._is_server_side(result.cursor)
  242. def test_stmt_enabled_conn_option_disabled(self):
  243. engine = self._fixture(False)
  244. s = select([1]).execution_options(stream_results=True)
  245. # not this one
  246. result = \
  247. engine.connect().execution_options(stream_results=False).\
  248. execute(s)
  249. assert not self._is_server_side(result.cursor)
  250. def test_stmt_option_disabled(self):
  251. engine = self._fixture(True)
  252. s = select([1]).execution_options(stream_results=False)
  253. result = engine.execute(s)
  254. assert not self._is_server_side(result.cursor)
  255. def test_aliases_and_ss(self):
  256. engine = self._fixture(False)
  257. s1 = select([1]).execution_options(stream_results=True).alias()
  258. result = engine.execute(s1)
  259. assert self._is_server_side(result.cursor)
  260. # s1's options shouldn't affect s2 when s2 is used as a
  261. # from_obj.
  262. s2 = select([1], from_obj=s1)
  263. result = engine.execute(s2)
  264. assert not self._is_server_side(result.cursor)
  265. def test_for_update_expr(self):
  266. engine = self._fixture(True)
  267. s1 = select([1], for_update=True)
  268. result = engine.execute(s1)
  269. assert self._is_server_side(result.cursor)
  270. def test_for_update_string(self):
  271. engine = self._fixture(True)
  272. result = engine.execute('SELECT 1 FOR UPDATE')
  273. assert self._is_server_side(result.cursor)
  274. def test_text_no_ss(self):
  275. engine = self._fixture(False)
  276. s = text('select 42')
  277. result = engine.execute(s)
  278. assert not self._is_server_side(result.cursor)
  279. def test_text_ss_option(self):
  280. engine = self._fixture(False)
  281. s = text('select 42').execution_options(stream_results=True)
  282. result = engine.execute(s)
  283. assert self._is_server_side(result.cursor)
  284. @testing.provide_metadata
  285. def test_roundtrip(self):
  286. md = self.metadata
  287. engine = self._fixture(True)
  288. test_table = Table('test_table', md,
  289. Column('id', Integer, primary_key=True),
  290. Column('data', String(50)))
  291. test_table.create(checkfirst=True)
  292. test_table.insert().execute(data='data1')
  293. test_table.insert().execute(data='data2')
  294. eq_(test_table.select().execute().fetchall(), [(1, 'data1'
  295. ), (2, 'data2')])
  296. test_table.update().where(
  297. test_table.c.id == 2).values(
  298. data=test_table.c.data +
  299. ' updated').execute()
  300. eq_(test_table.select().execute().fetchall(),
  301. [(1, 'data1'), (2, 'data2 updated')])
  302. test_table.delete().execute()
  303. eq_(select([func.count('*')]).select_from(test_table).scalar(), 0)