regression.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #-*- coding: iso-8859-1 -*-
  2. # pysqlite2/test/regression.py: pysqlite regression tests
  3. #
  4. # Copyright (C) 2006-2010 Gerhard Häring <gh@ghaering.de>
  5. #
  6. # This file is part of pysqlite.
  7. #
  8. # This software is provided 'as-is', without any express or implied
  9. # warranty. In no event will the authors be held liable for any damages
  10. # arising from the use of this software.
  11. #
  12. # Permission is granted to anyone to use this software for any purpose,
  13. # including commercial applications, and to alter it and redistribute it
  14. # freely, subject to the following restrictions:
  15. #
  16. # 1. The origin of this software must not be misrepresented; you must not
  17. # claim that you wrote the original software. If you use this software
  18. # in a product, an acknowledgment in the product documentation would be
  19. # appreciated but is not required.
  20. # 2. Altered source versions must be plainly marked as such, and must not be
  21. # misrepresented as being the original software.
  22. # 3. This notice may not be removed or altered from any source distribution.
  23. import datetime
  24. import unittest
  25. import sqlite3 as sqlite
  26. import weakref
  27. import functools
  28. from test import support
  29. from unittest.mock import patch
  30. class RegressionTests(unittest.TestCase):
  31. def setUp(self):
  32. self.con = sqlite.connect(":memory:")
  33. def tearDown(self):
  34. self.con.close()
  35. def CheckPragmaUserVersion(self):
  36. # This used to crash pysqlite because this pragma command returns NULL for the column name
  37. cur = self.con.cursor()
  38. cur.execute("pragma user_version")
  39. def CheckPragmaSchemaVersion(self):
  40. # This still crashed pysqlite <= 2.2.1
  41. con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
  42. try:
  43. cur = self.con.cursor()
  44. cur.execute("pragma schema_version")
  45. finally:
  46. cur.close()
  47. con.close()
  48. def CheckStatementReset(self):
  49. # pysqlite 2.1.0 to 2.2.0 have the problem that not all statements are
  50. # reset before a rollback, but only those that are still in the
  51. # statement cache. The others are not accessible from the connection object.
  52. con = sqlite.connect(":memory:", cached_statements=5)
  53. cursors = [con.cursor() for x in range(5)]
  54. cursors[0].execute("create table test(x)")
  55. for i in range(10):
  56. cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
  57. for i in range(5):
  58. cursors[i].execute(" " * i + "select x from test")
  59. con.rollback()
  60. def CheckColumnNameWithSpaces(self):
  61. cur = self.con.cursor()
  62. cur.execute('select 1 as "foo bar [datetime]"')
  63. self.assertEqual(cur.description[0][0], "foo bar [datetime]")
  64. cur.execute('select 1 as "foo baz"')
  65. self.assertEqual(cur.description[0][0], "foo baz")
  66. def CheckStatementFinalizationOnCloseDb(self):
  67. # pysqlite versions <= 2.3.3 only finalized statements in the statement
  68. # cache when closing the database. statements that were still
  69. # referenced in cursors weren't closed and could provoke "
  70. # "OperationalError: Unable to close due to unfinalised statements".
  71. con = sqlite.connect(":memory:")
  72. cursors = []
  73. # default statement cache size is 100
  74. for i in range(105):
  75. cur = con.cursor()
  76. cursors.append(cur)
  77. cur.execute("select 1 x union select " + str(i))
  78. con.close()
  79. @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 2), 'needs sqlite 3.2.2 or newer')
  80. def CheckOnConflictRollback(self):
  81. con = sqlite.connect(":memory:")
  82. con.execute("create table foo(x, unique(x) on conflict rollback)")
  83. con.execute("insert into foo(x) values (1)")
  84. try:
  85. con.execute("insert into foo(x) values (1)")
  86. except sqlite.DatabaseError:
  87. pass
  88. con.execute("insert into foo(x) values (2)")
  89. try:
  90. con.commit()
  91. except sqlite.OperationalError:
  92. self.fail("pysqlite knew nothing about the implicit ROLLBACK")
  93. def CheckWorkaroundForBuggySqliteTransferBindings(self):
  94. """
  95. pysqlite would crash with older SQLite versions unless
  96. a workaround is implemented.
  97. """
  98. self.con.execute("create table foo(bar)")
  99. self.con.execute("drop table foo")
  100. self.con.execute("create table foo(bar)")
  101. def CheckEmptyStatement(self):
  102. """
  103. pysqlite used to segfault with SQLite versions 3.5.x. These return NULL
  104. for "no-operation" statements
  105. """
  106. self.con.execute("")
  107. def CheckTypeMapUsage(self):
  108. """
  109. pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
  110. a statement. This test exhibits the problem.
  111. """
  112. SELECT = "select * from foo"
  113. con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES)
  114. con.execute("create table foo(bar timestamp)")
  115. con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),))
  116. con.execute(SELECT).close()
  117. con.execute("drop table foo")
  118. con.execute("create table foo(bar integer)")
  119. con.execute("insert into foo(bar) values (5)")
  120. con.execute(SELECT).close()
  121. def CheckBindMutatingList(self):
  122. # Issue41662: Crash when mutate a list of parameters during iteration.
  123. class X:
  124. def __conform__(self, protocol):
  125. parameters.clear()
  126. return "..."
  127. parameters = [X(), 0]
  128. con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES)
  129. con.execute("create table foo(bar X, baz integer)")
  130. # Should not crash
  131. with self.assertRaises(IndexError):
  132. con.execute("insert into foo(bar, baz) values (?, ?)", parameters)
  133. def CheckErrorMsgDecodeError(self):
  134. # When porting the module to Python 3.0, the error message about
  135. # decoding errors disappeared. This verifies they're back again.
  136. with self.assertRaises(sqlite.OperationalError) as cm:
  137. self.con.execute("select 'xxx' || ? || 'yyy' colname",
  138. (bytes(bytearray([250])),)).fetchone()
  139. msg = "Could not decode to UTF-8 column 'colname' with text 'xxx"
  140. self.assertIn(msg, str(cm.exception))
  141. def CheckRegisterAdapter(self):
  142. """
  143. See issue 3312.
  144. """
  145. self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
  146. def CheckSetIsolationLevel(self):
  147. # See issue 27881.
  148. class CustomStr(str):
  149. def upper(self):
  150. return None
  151. def __del__(self):
  152. con.isolation_level = ""
  153. con = sqlite.connect(":memory:")
  154. con.isolation_level = None
  155. for level in "", "DEFERRED", "IMMEDIATE", "EXCLUSIVE":
  156. with self.subTest(level=level):
  157. con.isolation_level = level
  158. con.isolation_level = level.lower()
  159. con.isolation_level = level.capitalize()
  160. con.isolation_level = CustomStr(level)
  161. # setting isolation_level failure should not alter previous state
  162. con.isolation_level = None
  163. con.isolation_level = "DEFERRED"
  164. pairs = [
  165. (1, TypeError), (b'', TypeError), ("abc", ValueError),
  166. ("IMMEDIATE\0EXCLUSIVE", ValueError), ("\xe9", ValueError),
  167. ]
  168. for value, exc in pairs:
  169. with self.subTest(level=value):
  170. with self.assertRaises(exc):
  171. con.isolation_level = value
  172. self.assertEqual(con.isolation_level, "DEFERRED")
  173. def CheckCursorConstructorCallCheck(self):
  174. """
  175. Verifies that cursor methods check whether base class __init__ was
  176. called.
  177. """
  178. class Cursor(sqlite.Cursor):
  179. def __init__(self, con):
  180. pass
  181. con = sqlite.connect(":memory:")
  182. cur = Cursor(con)
  183. with self.assertRaises(sqlite.ProgrammingError):
  184. cur.execute("select 4+5").fetchall()
  185. with self.assertRaisesRegex(sqlite.ProgrammingError,
  186. r'^Base Cursor\.__init__ not called\.$'):
  187. cur.close()
  188. def CheckStrSubclass(self):
  189. """
  190. The Python 3.0 port of the module didn't cope with values of subclasses of str.
  191. """
  192. class MyStr(str): pass
  193. self.con.execute("select ?", (MyStr("abc"),))
  194. def CheckConnectionConstructorCallCheck(self):
  195. """
  196. Verifies that connection methods check whether base class __init__ was
  197. called.
  198. """
  199. class Connection(sqlite.Connection):
  200. def __init__(self, name):
  201. pass
  202. con = Connection(":memory:")
  203. with self.assertRaises(sqlite.ProgrammingError):
  204. cur = con.cursor()
  205. def CheckCursorRegistration(self):
  206. """
  207. Verifies that subclassed cursor classes are correctly registered with
  208. the connection object, too. (fetch-across-rollback problem)
  209. """
  210. class Connection(sqlite.Connection):
  211. def cursor(self):
  212. return Cursor(self)
  213. class Cursor(sqlite.Cursor):
  214. def __init__(self, con):
  215. sqlite.Cursor.__init__(self, con)
  216. con = Connection(":memory:")
  217. cur = con.cursor()
  218. cur.execute("create table foo(x)")
  219. cur.executemany("insert into foo(x) values (?)", [(3,), (4,), (5,)])
  220. cur.execute("select x from foo")
  221. con.rollback()
  222. with self.assertRaises(sqlite.InterfaceError):
  223. cur.fetchall()
  224. def CheckAutoCommit(self):
  225. """
  226. Verifies that creating a connection in autocommit mode works.
  227. 2.5.3 introduced a regression so that these could no longer
  228. be created.
  229. """
  230. con = sqlite.connect(":memory:", isolation_level=None)
  231. def CheckPragmaAutocommit(self):
  232. """
  233. Verifies that running a PRAGMA statement that does an autocommit does
  234. work. This did not work in 2.5.3/2.5.4.
  235. """
  236. cur = self.con.cursor()
  237. cur.execute("create table foo(bar)")
  238. cur.execute("insert into foo(bar) values (5)")
  239. cur.execute("pragma page_size")
  240. row = cur.fetchone()
  241. def CheckConnectionCall(self):
  242. """
  243. Call a connection with a non-string SQL request: check error handling
  244. of the statement constructor.
  245. """
  246. self.assertRaises(TypeError, self.con, 1)
  247. def CheckCollation(self):
  248. def collation_cb(a, b):
  249. return 1
  250. self.assertRaises(sqlite.ProgrammingError, self.con.create_collation,
  251. # Lone surrogate cannot be encoded to the default encoding (utf8)
  252. "\uDC80", collation_cb)
  253. def CheckRecursiveCursorUse(self):
  254. """
  255. http://bugs.python.org/issue10811
  256. Recursively using a cursor, such as when reusing it from a generator led to segfaults.
  257. Now we catch recursive cursor usage and raise a ProgrammingError.
  258. """
  259. con = sqlite.connect(":memory:")
  260. cur = con.cursor()
  261. cur.execute("create table a (bar)")
  262. cur.execute("create table b (baz)")
  263. def foo():
  264. cur.execute("insert into a (bar) values (?)", (1,))
  265. yield 1
  266. with self.assertRaises(sqlite.ProgrammingError):
  267. cur.executemany("insert into b (baz) values (?)",
  268. ((i,) for i in foo()))
  269. def CheckConvertTimestampMicrosecondPadding(self):
  270. """
  271. http://bugs.python.org/issue14720
  272. The microsecond parsing of convert_timestamp() should pad with zeros,
  273. since the microsecond string "456" actually represents "456000".
  274. """
  275. con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
  276. cur = con.cursor()
  277. cur.execute("CREATE TABLE t (x TIMESTAMP)")
  278. # Microseconds should be 456000
  279. cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')")
  280. # Microseconds should be truncated to 123456
  281. cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.123456789')")
  282. cur.execute("SELECT * FROM t")
  283. values = [x[0] for x in cur.fetchall()]
  284. self.assertEqual(values, [
  285. datetime.datetime(2012, 4, 4, 15, 6, 0, 456000),
  286. datetime.datetime(2012, 4, 4, 15, 6, 0, 123456),
  287. ])
  288. def CheckInvalidIsolationLevelType(self):
  289. # isolation level is a string, not an integer
  290. self.assertRaises(TypeError,
  291. sqlite.connect, ":memory:", isolation_level=123)
  292. def CheckNullCharacter(self):
  293. # Issue #21147
  294. con = sqlite.connect(":memory:")
  295. self.assertRaises(ValueError, con, "\0select 1")
  296. self.assertRaises(ValueError, con, "select 1\0")
  297. cur = con.cursor()
  298. self.assertRaises(ValueError, cur.execute, " \0select 2")
  299. self.assertRaises(ValueError, cur.execute, "select 2\0")
  300. def CheckCommitCursorReset(self):
  301. """
  302. Connection.commit() did reset cursors, which made sqlite3
  303. to return rows multiple times when fetched from cursors
  304. after commit. See issues 10513 and 23129 for details.
  305. """
  306. con = sqlite.connect(":memory:")
  307. con.executescript("""
  308. create table t(c);
  309. create table t2(c);
  310. insert into t values(0);
  311. insert into t values(1);
  312. insert into t values(2);
  313. """)
  314. self.assertEqual(con.isolation_level, "")
  315. counter = 0
  316. for i, row in enumerate(con.execute("select c from t")):
  317. with self.subTest(i=i, row=row):
  318. con.execute("insert into t2(c) values (?)", (i,))
  319. con.commit()
  320. if counter == 0:
  321. self.assertEqual(row[0], 0)
  322. elif counter == 1:
  323. self.assertEqual(row[0], 1)
  324. elif counter == 2:
  325. self.assertEqual(row[0], 2)
  326. counter += 1
  327. self.assertEqual(counter, 3, "should have returned exactly three rows")
  328. def CheckBpo31770(self):
  329. """
  330. The interpreter shouldn't crash in case Cursor.__init__() is called
  331. more than once.
  332. """
  333. def callback(*args):
  334. pass
  335. con = sqlite.connect(":memory:")
  336. cur = sqlite.Cursor(con)
  337. ref = weakref.ref(cur, callback)
  338. cur.__init__(con)
  339. del cur
  340. # The interpreter shouldn't crash when ref is collected.
  341. del ref
  342. support.gc_collect()
  343. def CheckDelIsolation_levelSegfault(self):
  344. with self.assertRaises(AttributeError):
  345. del self.con.isolation_level
  346. def CheckBpo37347(self):
  347. class Printer:
  348. def log(self, *args):
  349. return sqlite.SQLITE_OK
  350. for method in [self.con.set_trace_callback,
  351. functools.partial(self.con.set_progress_handler, n=1),
  352. self.con.set_authorizer]:
  353. printer_instance = Printer()
  354. method(printer_instance.log)
  355. method(printer_instance.log)
  356. self.con.execute("select 1") # trigger seg fault
  357. method(None)
  358. class RecursiveUseOfCursors(unittest.TestCase):
  359. # GH-80254: sqlite3 should not segfault for recursive use of cursors.
  360. msg = "Recursive use of cursors not allowed"
  361. def setUp(self):
  362. self.con = sqlite.connect(":memory:",
  363. detect_types=sqlite.PARSE_COLNAMES)
  364. self.cur = self.con.cursor()
  365. self.cur.execute("create table test(x foo)")
  366. self.cur.executemany("insert into test(x) values (?)",
  367. [("foo",), ("bar",)])
  368. def tearDown(self):
  369. self.cur.close()
  370. self.con.close()
  371. del self.cur
  372. del self.con
  373. def test_recursive_cursor_init(self):
  374. conv = lambda x: self.cur.__init__(self.con)
  375. with patch.dict(sqlite.converters, {"INIT": conv}):
  376. with self.assertRaisesRegex(sqlite.ProgrammingError, self.msg):
  377. self.cur.execute(f'select x as "x [INIT]", x from test')
  378. def test_recursive_cursor_close(self):
  379. conv = lambda x: self.cur.close()
  380. with patch.dict(sqlite.converters, {"CLOSE": conv}):
  381. with self.assertRaisesRegex(sqlite.ProgrammingError, self.msg):
  382. self.cur.execute(f'select x as "x [CLOSE]", x from test')
  383. def test_recursive_cursor_fetch(self):
  384. conv = lambda x, l=[]: self.cur.fetchone() if l else l.append(None)
  385. with patch.dict(sqlite.converters, {"ITER": conv}):
  386. self.cur.execute(f'select x as "x [ITER]", x from test')
  387. with self.assertRaisesRegex(sqlite.ProgrammingError, self.msg):
  388. self.cur.fetchall()
  389. def suite():
  390. regression_suite = unittest.makeSuite(RegressionTests, "Check")
  391. recursive_cursor = unittest.makeSuite(RecursiveUseOfCursors)
  392. return unittest.TestSuite((
  393. regression_suite,
  394. recursive_cursor,
  395. ))
  396. def test():
  397. runner = unittest.TextTestRunner()
  398. runner.run(suite())
  399. if __name__ == "__main__":
  400. test()