Debian Codegraph @

test/jpypetest/test_sql_sqlite.py

raw symbols SCIP
1 # This file is Public Domain and may be used without restrictions,
2 # because nobody should have to waste their lives typing this again.
3 import datetime
4 import decimal
5 import threading
6
7 import pytest
8
9 import common
10 import jpype
11 import jpype.dbapi2 as dbapi2
12 from jpype import java
13 from jpype.types import JArray, JByte
14
15 try:
16 import zlib
17 except ImportError:
18 zlib = None # type: ignore[assignment]
19
20
21 db_name = "jdbc:sqlite::memory:"
22
23 def setUpModule(module):
24 from common import java_version
25 version = java_version()
26 if version[0] == 1 and version[1] == 8:
27 pytest.skip("jdk8 unsupported", allow_module_level=True)
28
29
30 class ConnectTestCase(common.JPypeTestCase):
31 def setUp(self):
32 common.JPypeTestCase.setUp(self)
33 if common.fast:
34 raise common.unittest.SkipTest("fast")
35
36 def testConnect(self):
37 cx = dbapi2.connect(db_name)
38 self.assertIsInstance(cx, dbapi2.Connection)
39
40 def testClose(self):
41 cx = dbapi2.connect(db_name)
42 cx.close()
43 # Closing twice is an error
44 with self.assertRaises(dbapi2.ProgrammingError):
45 cx.close()
46
47 def testScope(self):
48 with dbapi2.connect(db_name) as cx:
49 pass
50 with self.assertRaises(dbapi2.ProgrammingError):
51 cx.close()
52
53 def testAdapters(self):
54 cx = dbapi2.connect(db_name)
55 self.assertEqual(cx.adapters, dbapi2._default_adapters)
56 cx = dbapi2.connect(db_name, adapters=None)
57 self.assertEqual(cx.adapters, {})
58 m = {}
59 cx = dbapi2.connect(db_name, adapters=m)
60 self.assertEqual(cx.adapters, m)
61
62 def testConverters(self):
63 cx = dbapi2.connect(db_name)
64 self.assertEqual(cx.converters, dbapi2._default_converters)
65 cx = dbapi2.connect(db_name, converters=None)
66 self.assertEqual(cx.converters, {})
67 m = {}
68 cx = dbapi2.connect(db_name, converters=m)
69 self.assertEqual(cx.converters, m)
70
71
72 class ConnectionTestCase(common.JPypeTestCase):
73 def setUp(self):
74 common.JPypeTestCase.setUp(self)
75 if common.fast:
76 raise common.unittest.SkipTest("fast")
77
78 def test_commit(self):
79 with dbapi2.connect(db_name) as cx:
80 # Commit must work without a command
81 cx.commit()
82
83 def test_rollback(self):
84 with dbapi2.connect(db_name) as cx:
85 # Commit must work without a command
86 cx.rollback()
87
88 def test_cursor(self):
89 with dbapi2.connect(db_name) as cx:
90 self.assertIsInstance(cx.cursor(), dbapi2.Cursor)
91
92 def testAdapters(self):
93 with dbapi2.connect(db_name) as cx:
94 m = {'foo': 1}
95 cx.adapters = m
96 self.assertEqual(cx._adapters, m)
97 with self.assertRaises(TypeError):
98 cx.adapters = object()
99
100 def testConverters(self):
101 with dbapi2.connect(db_name) as cx:
102 m = {'foo': 1}
103 cx.converters = m
104 self.assertEqual(cx._converters, m)
105 with self.assertRaises(TypeError):
106 cx.converters = object()
107
108 def testClosedClass(self):
109 with dbapi2.connect(db_name) as cx:
110 with self.assertRaises(AttributeError):
111 cx.seters = object()
112
113 def testAutocommitFail(self):
114 with dbapi2.connect(db_name) as cx:
115 cx.autocommit = True
116 with self.assertRaises(dbapi2.NotSupportedError):
117 cx.commit()
118 with self.assertRaises(dbapi2.NotSupportedError):
119 cx.rollback()
120
121 def test_typeinfo(self):
122 with dbapi2.connect(db_name) as cx:
123 ti = cx.typeinfo
124 self.assertIsInstance(ti, dict)
125 for p, v in ti.items():
126 self.assertIsInstance(p, str)
127 self.assertIsInstance(v, dbapi2.JDBCType)
128 with self.assertRaises(dbapi2.ProgrammingError):
129 ti = cx.typeinfo
130
131 def test_connection(self):
132 with dbapi2.connect(db_name) as cx:
133 c = cx.connection
134 self.assertIsInstance(c, java.sql.Connection)
135
136 def test_getters(self):
137 with dbapi2.connect(db_name) as cx:
138 cx.getters = dbapi2.GETTERS_BY_NAME
139 self.assertEqual(cx._getters, dbapi2.GETTERS_BY_NAME)
140 self.assertEqual(cx.getters, dbapi2.GETTERS_BY_NAME)
141 cx.getters = dbapi2.GETTERS_BY_TYPE
142 self.assertEqual(cx._getters, dbapi2.GETTERS_BY_TYPE)
143 self.assertEqual(cx.getters, dbapi2.GETTERS_BY_TYPE)
144
145 def test_setters(self):
146 with dbapi2.connect(db_name) as cx:
147 cx.setters = dbapi2.SETTERS_BY_META
148 self.assertEqual(cx._setters, dbapi2.SETTERS_BY_META)
149 self.assertEqual(cx.setters, dbapi2.SETTERS_BY_META)
150 cx.setters = dbapi2.SETTERS_BY_TYPE
151 self.assertEqual(cx._setters, dbapi2.SETTERS_BY_TYPE)
152 self.assertEqual(cx.setters, dbapi2.SETTERS_BY_TYPE)
153
154 def test_adapters(self):
155 with dbapi2.connect(db_name) as cx:
156 self.assertEqual(cx.adapters, dbapi2._default_adapters)
157 cx.adapters = None
158 self.assertEqual(cx.adapters, {})
159 m = {}
160 cx.adapters = m
161 self.assertEqual(cx.adapters, m)
162 with self.assertRaises(dbapi2.InterfaceError):
163 cx.adapters = object()
164
165 def test_converters(self):
166 with dbapi2.connect(db_name) as cx:
167 self.assertEqual(cx.converters, dbapi2._default_converters)
168 cx.converters = None
169 self.assertEqual(cx.converters, {})
170 m = {}
171 cx.converters = m
172 self.assertEqual(cx.converters, m)
173 with self.assertRaises(dbapi2.InterfaceError):
174 cx.converters = object()
175
176
177 class CursorTestCase(common.JPypeTestCase):
178 def setUp(self):
179 common.JPypeTestCase.setUp(self)
180 if common.fast:
181 raise common.unittest.SkipTest("fast")
182
183 def tearDown(self):
184 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
185 try:
186 cur.execute("drop table booze")
187 except dbapi2.Error:
188 pass
189 try:
190 cur.execute("drop table barflys")
191 except dbapi2.Error:
192 pass
193
194 def testCursorIsolation(self):
195 with dbapi2.connect(db_name) as cx:
196 # Make sure cursors created from the same connection have
197 # the documented transaction isolation level
198 cur1 = cx.cursor()
199 cur2 = cx.cursor()
200 cur1.execute("create table booze (name varchar(20))")
201 cur1.execute("insert into booze values ('Victoria Bitter')")
202 cur2.execute("select name from booze")
203 booze = cur2.fetchall()
204 self.assertEqual(len(booze), 1)
205 self.assertEqual(len(booze[0]), 1)
206 self.assertEqual(booze[0][0], "Victoria Bitter")
207
208 def testDescription(self):
209 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
210 cur.execute("create table booze (name varchar(20))")
211 self.assertEqual(
212 cur.description,
213 None,
214 "cursor.description should be none after executing a "
215 "statement that can return no rows (such as create table)",
216 )
217 cur.execute("select name from booze")
218 self.assertEqual(
219 len(cur.description), 1, "cursor.description describes too many columns"
220 )
221 self.assertEqual(
222 len(cur.description[0]),
223 7,
224 "cursor.description[x] tuples must have 7 elements",
225 )
226 self.assertEqual(
227 cur.description[0][0].lower(),
228 "name",
229 "cursor.description[x][0] must return column name",
230 )
231 self.assertEqual(
232 cur.description[0][1],
233 dbapi2.STRING,
234 "cursor.description[x][1] must return column type. Got %r"
235 % cur.description[0][1],
236 )
237
238 # Make sure self.description gets reset
239 cur.execute("create table barflys (name varchar(20))")
240 self.assertEqual(
241 cur.description,
242 None,
243 "cursor.description not being set to None when executing "
244 "no-result statements (eg. create table)",
245 )
246
247 def testRowcount(self):
248 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
249 cur.execute("create table booze (name varchar(20))")
250 # This was dropped from the specification
251 # self.assertEqual(
252 # cur.rowcount,
253 # -1,
254 # "cursor.rowcount should be -1 after executing no-result " "statements",
255 # )
256 cur.execute("insert into booze values ('Victoria Bitter')")
257 self.assertEqual(
258 cur.rowcount, 1,
259 "cursor.rowcount should == number or rows inserted, or "
260 "set to -1 after executing an insert statement",
261 )
262 cur.execute("select name from booze")
263 self.assertEqual(
264 cur.rowcount, -1,
265 "cursor.rowcount should == number of rows returned, or "
266 "set to -1 after executing a select statement",
267 )
268 cur.execute("create table barflys (name varchar(20))")
269 # THis test does not match jdbc parameters
270 # self.assertEqual(
271 # cur.rowcount,
272 # -1,
273 # "cursor.rowcount not being reset to -1 after executing "
274 # "no-result statements",
275 # )
276
277 def testClose(self):
278 cx = dbapi2.connect(db_name)
279 try:
280 cur = cx.cursor()
281 finally:
282 cx.close()
283
284 # cursor.execute should raise an Error if called after connection
285 # closed
286 with self.assertRaises(dbapi2.Error):
287 cur.execute("create table booze (name varchar(20))")
288
289 # connection.commit should raise an Error if called after connection'
290 # closed.'
291 self.assertRaises(dbapi2.Error, cx.commit)
292
293 # connection.close should raise an Error if called more than once
294 self.assertRaises(dbapi2.Error, cx.close)
295
296 def test_None(self):
297 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
298 cur.execute("create table booze (name varchar(20))")
299 cur.execute("insert into booze values (NULL)")
300 cur.execute("select name from booze")
301 r = cur.fetchall()
302 self.assertEqual(len(r), 1)
303 self.assertEqual(len(r[0]), 1)
304 self.assertEqual(r[0][0], None, "NULL value not returned as None")
305
306 def testArraysize(self):
307 # Not much here - rest of the tests for this are in test_fetchmany
308 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
309 self.assertTrue(
310 hasattr(cur, "arraysize"), "cursor.arraysize must be defined"
311 )
312
313 def _paraminsert(self, cur):
314 cur.execute("create table booze (name varchar(20))")
315 cur.execute("insert into booze values ('Victoria Bitter')")
316 self.assertTrue(cur.rowcount in (-1, 1))
317 cur.execute("insert into booze values (?)", ("Cooper's",))
318 self.assertTrue(cur.rowcount in (-1, 1))
319 cur.execute("select name from booze")
320 res = cur.fetchall()
321 self.assertEqual(len(res), 2, "cursor.fetchall returned too few rows")
322 beers = [res[0][0], res[1][0]]
323 beers.sort()
324 self.assertEqual(
325 beers[0],
326 "Cooper's",
327 "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly",
328 )
329 self.assertEqual(
330 beers[1],
331 "Victoria Bitter",
332 "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly",
333 )
334
335 def test_execute(self):
336 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
337 self._paraminsert(cur)
338
339 def test_executeBad(self):
340 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
341 with self.assertRaises(dbapi2.InterfaceError):
342 cur.execute("insert into booze values (?)", object())
343 with self.assertRaises(dbapi2.InterfaceError):
344 cur.execute(object())
345 with self.assertRaises(dbapi2.ProgrammingError):
346 cur.execute("inert into booze values (?)", [["?"]])
347
348 def test_setinputsizes(self):
349 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
350 cur.setinputsizes((25,))
351 self._paraminsert(cur) # Make sure cursor still works
352
353 def test_setoutputsize_basic(self):
354 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
355 cur.setoutputsize(1000)
356 cur.setoutputsize(2000, 0)
357 self._paraminsert(cur) # Make sure the cursor still works
358
359 def test_executemany(self):
360 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
361 cur.execute("create table booze (name varchar(20))")
362 largs = [("Cooper's",), ("Boag's",)]
363 margs = [{"beer": "Cooper's"}, {"beer": "Boag's"}]
364 cur.executemany("insert into booze values (?)", largs)
365 self.assertEqual(
366 cur.rowcount, 2,
367 "insert using cursor.executemany set cursor.rowcount to "
368 "incorrect value %r" % cur.rowcount,
369 )
370 cur.execute("select name from booze")
371 res = cur.fetchall()
372 self.assertEqual(
373 len(res), 2, "cursor.fetchall retrieved incorrect number of rows"
374 )
375 beers = [res[0][0], res[1][0]]
376 beers.sort()
377 self.assertEqual(beers[0], "Boag's", "incorrect data retrieved")
378 self.assertEqual(beers[1], "Cooper's", "incorrect data retrieved")
379
380 def test_executemanyGenerator(self):
381 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
382 def mygen(ls):
383 for i in ls:
384 yield [i]
385 cu.execute("create table booze (name varchar(20))")
386 cu.executemany("insert into booze values (?)", mygen(self.samples))
387 cu.execute("select * from booze")
388 f = cu.fetchall()
389 for i, v in enumerate(self.samples):
390 self.assertEqual(f[i][0], v)
391
392 def test_executemanyIterator(self):
393 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
394 class myiter:
395 def __init__(self, ls):
396 self.ls = ls
397 self.i = 0
398
399 def __iter__(self):
400 return self
401
402 def __next__(self):
403 if self.i == len(self.ls):
404 raise StopIteration
405 rc = [self.ls[self.i]]
406 self.i += 1
407 return rc
408 cu.execute("create table booze (name varchar(20))")
409 cu.executemany("insert into booze values (?)", myiter(self.samples))
410 cu.execute("select * from booze")
411 f = cu.fetchall()
412 for i, v in enumerate(self.samples):
413 self.assertEqual(f[i][0], v)
414
415 def test_executemanyBad(self):
416 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
417 cu.execute("create table booze (name varchar(20))")
418 with self.assertRaises(TypeError):
419 cu.executemany("insert into booze values (?)", object())
420 with self.assertRaises(dbapi2.InterfaceError):
421 cu.executemany("insert into booze values (?)", object())
422 with self.assertRaises(dbapi2.InterfaceError):
423 cu.executemany(object(), [])
424 cu.executemany("insert into booze values (?)", None)
425 with self.assertRaises(dbapi2.ProgrammingError):
426 cu.executemany("inert into booze values (?)", [['?']])
427
428 def test_fetchone(self):
429 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
430 # cursor.fetchone should raise an Error if called before
431 # executing a select-type query
432 self.assertRaises(dbapi2.ProgrammingError, cur.fetchone)
433
434 # cursor.fetchone should raise an Error if called after
435 # executing a query that cannot return rows
436 cur.execute("create table booze (name varchar(20))")
437 self.assertRaises(dbapi2.Error, cur.fetchone)
438
439 cur.execute("select name from booze")
440 self.assertEqual(
441 cur.fetchone(),
442 None,
443 "cursor.fetchone should return None if a query retrieves " "no rows",
444 )
445 self.assertEqual(cur.rowcount, 0)
446
447 # cursor.fetchone should raise an Error if called after
448 # executing a query that cannot return rows
449 cur.execute("insert into booze values ('Victoria Bitter')")
450 self.assertRaises(dbapi2.Error, cur.fetchone)
451
452 cur.execute("select name from booze")
453 r = cur.fetchone()
454 self.assertEqual(
455 len(r), 1, "cursor.fetchone should have retrieved a single row"
456 )
457 self.assertEqual(
458 r[0], "Victoria Bitter", "cursor.fetchone retrieved incorrect data"
459 )
460 self.assertEqual(
461 cur.fetchone(),
462 None,
463 "cursor.fetchone should return None if no more rows available",
464 )
465 self.assertEqual(cur.rowcount, -1)
466
467 samples = [
468 "Carlton Cold",
469 "Carlton Draft",
470 "Mountain Goat",
471 "Redback",
472 "Victoria Bitter",
473 "XXXX",
474 ]
475
476 def _populate(self):
477 """ Return a list of sql commands to setup the DB for the fetch
478 tests.
479 """
480 populate = [
481 "insert into booze values ('{}')".format(s)
482 for s in self.samples
483 ]
484 return populate
485
486 def test_fetchmany(self):
487 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
488
489 # cursor.fetchmany should raise an Error if called without
490 # issuing a query
491 self.assertRaises(dbapi2.ProgrammingError, cur.fetchmany, 4)
492
493 cur.execute("create table booze (name varchar(20))")
494 for sql in self._populate():
495 cur.execute(sql)
496
497 cur.execute("select name from booze")
498 r = cur.fetchmany()
499 self.assertEqual(
500 len(r),
501 1,
502 "cursor.fetchmany retrieved incorrect number of rows, "
503 "default of arraysize is one.",
504 )
505 cur.arraysize = 10
506 r = cur.fetchmany(3) # Should get 3 rows
507 self.assertEqual(
508 len(r), 3, "cursor.fetchmany retrieved incorrect number of rows"
509 )
510 r = cur.fetchmany(4) # Should get 2 more
511 self.assertEqual(
512 len(r), 2, "cursor.fetchmany retrieved incorrect number of rows"
513 )
514 r = cur.fetchmany(4) # Should be an empty sequence
515 self.assertEqual(
516 len(r),
517 0,
518 "cursor.fetchmany should return an empty sequence after "
519 "results are exhausted",
520 )
521 self.assertEqual(cur.rowcount, -1)
522
523 # Same as above, using cursor.arraysize
524 cur.arraysize = 4
525 cur.execute("select name from booze")
526 r = cur.fetchmany() # Should get 4 rows
527 self.assertEqual(
528 len(r), 4, "cursor.arraysize not being honoured by fetchmany"
529 )
530 r = cur.fetchmany() # Should get 2 more
531 self.assertEqual(len(r), 2)
532 r = cur.fetchmany() # Should be an empty sequence
533 self.assertEqual(len(r), 0)
534 self.assertEqual(cur.rowcount, -1)
535
536 cur.arraysize = 6
537 cur.execute("select name from booze")
538 rows = cur.fetchmany() # Should get all rows
539 self.assertTrue(cur.rowcount in (-1, 6))
540 self.assertEqual(len(rows), 6)
541 self.assertEqual(len(rows), 6)
542 rows = [r[0] for r in rows]
543 rows.sort()
544
545 # Make sure we get the right data back out
546 for i in range(0, 6):
547 self.assertEqual(
548 rows[i],
549 self.samples[i],
550 "incorrect data retrieved by cursor.fetchmany",
551 )
552
553 rows = cur.fetchmany() # Should return an empty list
554 self.assertEqual(
555 len(rows),
556 0,
557 "cursor.fetchmany should return an empty sequence if "
558 "called after the whole result set has been fetched",
559 )
560 self.assertEqual(cur.rowcount, -1)
561
562 cur.execute("create table barflys (name varchar(20))")
563 cur.execute("select name from barflys")
564 r = cur.fetchmany() # Should get empty sequence
565 self.assertEqual(
566 len(r),
567 0,
568 "cursor.fetchmany should return an empty sequence if "
569 "query retrieved no rows",
570 )
571
572 def test_fetchall(self):
573 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
574 # cursor.fetchall should raise an Error if called
575 # without executing a query that may return rows (such
576 # as a select)
577 self.assertRaises(dbapi2.Error, cur.fetchall)
578
579 cur.execute("create table booze (name varchar(20))")
580 for sql in self._populate():
581 cur.execute(sql)
582
583 # cursor.fetchall should raise an Error if called
584 # after executing a statement that cannot return rows
585 self.assertRaises(dbapi2.ProgrammingError, cur.fetchall)
586
587 cur.execute("select name from booze")
588 rows = cur.fetchall()
589 self.assertEqual(cur.rowcount, -1)
590 self.assertEqual(
591 len(rows),
592 len(self.samples),
593 "cursor.fetchall did not retrieve all rows",
594 )
595 rows = [r[0] for r in rows]
596 rows.sort()
597 for i in range(0, len(self.samples)):
598 self.assertEqual(
599 rows[i], self.samples[i], "cursor.fetchall retrieved incorrect rows"
600 )
601 rows = cur.fetchall()
602 self.assertEqual(
603 len(rows),
604 0,
605 "cursor.fetchall should return an empty list if called "
606 "after the whole result set has been fetched",
607 )
608 self.assertEqual(cur.rowcount, -1)
609
610 cur.execute("create table barflys (name varchar(20))")
611 cur.execute("select name from barflys")
612 rows = cur.fetchall()
613 self.assertEqual(cur.rowcount, 1)
614 self.assertEqual(
615 len(rows),
616 0,
617 "cursor.fetchall should return an empty list if "
618 "a select query returns no rows",
619 )
620
621 def test_mixedfetch(self):
622 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
623 cur.execute("create table booze (name varchar(20))")
624 for sql in self._populate():
625 cur.execute(sql)
626
627 cur.execute("select name from booze")
628 self.assertEqual(cur.rowcount, -1)
629 rows1 = cur.fetchone()
630 rows23 = cur.fetchmany(2)
631 rows4 = cur.fetchone()
632 rows56 = cur.fetchall()
633 self.assertEqual(cur.rowcount, -1)
634 self.assertEqual(
635 len(rows23), 2, "fetchmany returned incorrect number of rows"
636 )
637 self.assertEqual(
638 len(rows56), 2, "fetchall returned incorrect number of rows"
639 )
640
641 rows = [rows1[0]]
642 rows.extend([rows23[0][0], rows23[1][0]])
643 rows.append(rows4[0])
644 rows.extend([rows56[0][0], rows56[1][0]])
645 rows.sort()
646 for i in range(0, len(self.samples)):
647 self.assertEqual(
648 rows[i], self.samples[i], "incorrect data retrieved or inserted"
649 )
650
651 def test_nextset(self):
652 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
653 cu.execute("create table booze (name varchar(20))")
654 booze = ["Wiskey", ]
655 cu.execute("insert into booze(name) values (?)", booze)
656 self.assertEqual(cu.rowcount, 1)
657 cu.execute("select * from booze; select * from booze")
658 self.assertEqual(cu.fetchone(), booze)
659 nxt = cu.nextset()
660 self.assertTrue(nxt in (True, None))
661 # H2 does not support multiple result sets
662 if nxt:
663 self.assertEqual(cu.fetchone(), booze)
664
665 @common.unittest.skip # type: ignore
666 def test_lastrowid(self):
667 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
668 cu.execute("create table booze(id INTEGER IDENTITY PRIMARY KEY, name varchar(255))")
669 cu.execute("insert into booze(name) values('hello')", keys=True)
670 id0 = cu.lastrowid
671 self.assertIsInstance(id0, int)
672 # Call more than once
673 id1 = cu.lastrowid
674 self.assertIsInstance(id1, int)
675 cx.commit()
676 cu.execute("insert into booze(name) values('there')", keys=True)
677 id2 = cu.lastrowid
678 self.assertIsInstance(id2, int)
679 cu.execute("select * from booze")
680 f = cu.fetchall()
681 self.assertEqual(cu.lastrowid, None) # sqlite has weird behaviors
682 self.assertEqual(f[0][0], id0)
683 self.assertEqual(f[1][0], id2)
684
685 @common.unittest.skip # type: ignore
686 def test_lastrowidMany(self):
687 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
688 cu.execute("create table booze(id INTEGER IDENTITY PRIMARY KEY, name varchar(255))")
689 cu.executemany("insert into booze(name) values(?)", [['Redback'], ['Fat Yak']], keys=True)
690 ids = cu.lastrowid
691 self.assertIsInstance(ids, list)
692 self.assertEqual(len(ids), 2)
693 cu.execute("select * from booze")
694 f = cu.fetchall()
695 self.assertEqual(f[0][0], ids[0])
696 self.assertEqual(f[1][0], ids[1])
697
698 def test_iter(self):
699 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
700 ls = [['Tooheys Old'], ['Nine Tales Original Amber Ale'], ['Dogbolter']]
701 cu.execute("create table booze(name varchar(255))")
702 cu.executemany("insert into booze(name) values(?)", ls, keys=True)
703
704 # make sure we throw if there is no result set
705 with self.assertRaises(dbapi2.ProgrammingError):
706 for booze in cu:
707 pass
708 cu.execute("select * from booze")
709 for i, booze in enumerate(cu):
710 self.assertEqual(ls[i], booze)
711
712 def testNoAdapter(self):
713 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
714 cu.execute("create table booze(name varchar(50))")
715 with self.assertRaises(dbapi2.InterfaceError):
716 cu.execute("insert into booze(name) values(?)", [object()])
717
718 def testBadParameters(self):
719 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
720 cu.execute("create table booze(name varchar(50))")
721 with self.assertRaises(dbapi2.InterfaceError):
722 cu.execute("insert into booze(name) values(?)", object())
723
724 def test_callproc(self):
725 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
726 with self.assertRaises(dbapi2.ProgrammingError):
727 r = cu.callproc("lower", ("FOO",))
728
729 @common.unittest.skip # type: ignore
730 def test_callprocBad(self):
731 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
732 with self.assertRaises(dbapi2.ProgrammingError):
733 r = cu.callproc("not_there", ("FOO",))
734 with self.assertRaises(dbapi2.InterfaceError):
735 r = cu.callproc(object(), ("FOO",))
736 with self.assertRaises(dbapi2.InterfaceError):
737 r = cu.callproc("lower", (object(),))
738 with self.assertRaises(dbapi2.InterfaceError):
739 r = cu.callproc("lower", object())
740
741 def test_close(self):
742 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
743 cu.close()
744 with self.assertRaises(dbapi2.ProgrammingError):
745 cu.close()
746
747 def test_parameters(self):
748 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
749 with self.assertRaises(dbapi2.ProgrammingError):
750 p = cu.parameters
751 cu.execute("create table booze(name varchar(50))")
752 cu.execute("insert into booze(name) values(?)", ('Hahn Super Dry',))
753 p = cu.parameters
754 self.assertEqual(p[0][0:2], ('VARCHAR', dbapi2.VARCHAR))
755
756 def test_resultSet(self):
757 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
758 cu.execute("create table booze(name varchar(50))")
759 cu.execute("insert into booze(name) values(?)", ('Hahn Super Dry',))
760 cu.execute("select * from booze")
761 rs = cu.resultSet
762 self.assertIsInstance(rs, java.sql.ResultSet)
763
764 def test_fetchClosed(self):
765 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
766 cu.execute("create table booze(name varchar(50))")
767 cu.execute("insert into booze(name) values(?)", ('Hahn Super Dry',))
768 cu.execute("select * from booze")
769 cu.close()
770 with self.assertRaises(dbapi2.ProgrammingError):
771 cu.fetchone()
772 with self.assertRaises(dbapi2.ProgrammingError):
773 cu.fetchmany()
774 with self.assertRaises(dbapi2.ProgrammingError):
775 cu.fetchall()
776 self.assertEqual(cu.resultSet, None)
777
778 def test_executeBadParameters(self):
779 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
780 def mygen(ls):
781 for i in ls:
782 yield i
783 cu.execute("create table booze(name varchar(50), price integer)")
784 with self.assertRaises(dbapi2.ProgrammingError):
785 cu.executemany("insert into booze(name,price) values(?,?)", [('Hahn Super Dry', 2), ('Coors',)])
786 with self.assertRaises(dbapi2.InterfaceError):
787 cu.execute("insert into booze(name,price) values(?,?)", {'name': 'Budweiser', 'price': 10})
788 with self.assertRaises(dbapi2.ProgrammingError):
789 cu.executemany("insert into booze(name,price) values(?,?)", mygen([['Budweiser']]))
790 cu.execute("insert into booze(name,price) values(?,?)", mygen(['Pabst Blue Robot', 20000]))
791 with self.assertRaises(dbapi2.ProgrammingError):
792 cu.execute("insert into booze(name,price) values(?,?)", mygen(['Budweiser']))
793 with self.assertRaises(dbapi2.InterfaceError):
794 cu.execute("insert into booze(name,price) values(?,?)", 'Budweiser')
795 with self.assertRaises(dbapi2.ProgrammingError):
796 cu.execute("insert into booze(name,price) values(?,?)", mygen(['Budweiser', 2, 'no']))
797 with self.assertRaises(dbapi2.InterfaceError):
798 cu.execute("insert into booze(name,price) values(?,?)", object())
799
800
801 @common.unittest.skipUnless(zlib, "requires zlib")
802 class AdapterTestCase(common.JPypeTestCase):
803 def setUp(self):
804 common.JPypeTestCase.setUp(self)
805 if common.fast:
806 raise common.unittest.SkipTest("fast")
807 self.testdata = b"abcdefg" * 10
808 self.params = memoryview(zlib.compress(self.testdata))
809
810 def tearDown(self):
811 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
812 try:
813 cur.execute("drop table test")
814 except dbapi2.Error:
815 pass
816
817 def testOnConnector(self):
818 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
819 cu.execute("create table test(name varchar(255))")
820 cx.adapters[object] = lambda x: "none"
821 cu.execute("insert into test(name) values(?)", [object()])
822 cu.execute("select * from test")
823 f = cu.fetchall()
824 self.assertEqual(f[0][0], "none")
825
826
827 @common.unittest.skipUnless(zlib, "requires zlib")
828 class ConverterTestCase(common.JPypeTestCase):
829 def setUp(self):
830 common.JPypeTestCase.setUp(self)
831 if common.fast:
832 raise common.unittest.SkipTest("fast")
833 self.testdata = b"abcdefg" * 10
834 self.params = memoryview(zlib.compress(self.testdata))
835
836 def tearDown(self):
837 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
838 try:
839 cur.execute("drop table test")
840 except dbapi2.Error:
841 pass
842
843 @staticmethod
844 def convert(s):
845 return zlib.decompress(s)
846
847 def testConvertersBad(self):
848 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
849 cu.execute("create table test(name varchar(20))")
850 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
851 cu.execute("select name from test")
852 with self.assertRaises(dbapi2.ProgrammingError):
853 cu.fetchone(converters=[])
854 cu.execute("select name from test")
855 with self.assertRaises(dbapi2.InterfaceError):
856 cu.fetchone(converters=[int])
857 cu.execute("select name from test")
858 with self.assertRaises(dbapi2.ProgrammingError):
859 cu.fetchone(converters=[str, str])
860
861 def testConvertersNone(self):
862 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
863 cu.execute("create table test(name varchar(20))")
864 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
865 cu.execute("select name from test")
866 f = cu.fetchone(converters=None)
867 self.assertIsInstance(f[0], java.lang.String)
868 cu.execute("select name from test")
869
870 def testConvertersPositional(self):
871 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
872 cu.execute("create table test(name varchar(20))")
873 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
874 cu.execute("select name from test")
875 f = cu.fetchone(converters=[str])
876 self.assertIsInstance(f[0], str)
877 cu.execute("select name from test")
878
879 def test_fetchoneTypesPositional(self):
880 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
881 cu.execute("create table test(name varchar(20))")
882 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
883 cu.execute("select name from test")
884 f = cu.fetchone(types=[dbapi2.STRING])
885 self.assertIsInstance(f[0], str)
886
887 def test_fetchmanyTypesPositional(self):
888 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
889 cu.execute("create table test(name varchar(20))")
890 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
891 cu.execute("select name from test")
892 f = cu.fetchmany(types=[dbapi2.STRING])
893 self.assertIsInstance(f[0][0], str)
894
895 def test_fetchallTypesPositional(self):
896 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
897 cu.execute("create table test(name varchar(20))")
898 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
899 cu.execute("select name from test")
900 f = cu.fetchall(types=[dbapi2.STRING])
901 self.assertIsInstance(f[0][0], str)
902
903 def testTypesPositionalBAD(self):
904 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
905 cu.execute("create table test(name varchar(20))")
906 cu.executemany("insert into test(name) values(?)", [['alice'], ['bob'], ['charlie']])
907 cu.execute("select name from test")
908 with self.assertRaises(dbapi2.ProgrammingError):
909 f = cu.fetchone(types=[dbapi2.STRING, dbapi2.STRING])
910 with self.assertRaises(dbapi2.ProgrammingError):
911 f = cu.fetchone(types=[])
912
913
914 @common.unittest.skipUnless(zlib, "requires zlib")
915 class GettersTestCase(common.JPypeTestCase):
916 def setUp(self):
917 common.JPypeTestCase.setUp(self)
918 if common.fast:
919 raise common.unittest.SkipTest("fast")
920 self.testdata = b"abcdefg" * 10
921 self.params = memoryview(zlib.compress(self.testdata))
922
923 def tearDown(self):
924 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
925 try:
926 cur.execute("drop table test")
927 except dbapi2.Error:
928 pass
929
930
931 @common.unittest.skip # type: ignore
932 class TransactionsTestCase(common.JPypeTestCase):
933 def setUp(self):
934 common.JPypeTestCase.setUp(self)
935 if common.fast:
936 raise common.unittest.SkipTest("fast")
937
938 def tearDown(self):
939 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
940 try:
941 cur.execute("drop table test")
942 except dbapi2.Error:
943 pass
944
945 def testTransactionRollbackCreate(self):
946 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
947 cx.commit() # needed before starting transactions
948 cu.execute("begin")
949 cu.execute("create table test(name VARCHAR(10))")
950 cx.rollback()
951 # with self.assertRaises(dbapi2.ProgrammingError):
952 cu.execute("select * from test")
953
954 def testTransactionRollbackInsert(self):
955 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
956 cx.commit() # needed before starting transactions
957 cu.execute("create table test(name VARCHAR(10))")
958 cx.commit()
959 cu.execute("begin")
960 cu.execute("insert into test(name) values('alice')")
961 cx.rollback()
962 # Alice should go away
963 result = cu.execute("select * from test").fetchall()
964 self.assertEqual(result, [])
965
966 def testTransactionRollbackClose(self):
967 with dbapi2.connect(db_name) as cx2:
968 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
969 cx.commit() # needed before starting transactions
970 cu.execute("create table test(name VARCHAR(10))")
971 cu.execute("insert into test(name) values('alice')")
972 cx.commit()
973 cu.execute("begin")
974 cu.execute("insert into test(name) values('bob')")
975 result = cu.execute("select * from test").fetchall()
976 self.assertEqual(result, [['alice'], ['bob']])
977 # Bob should go away
978 with cx2.cursor() as cu:
979 result = cu.execute("select * from test").fetchall()
980 self.assertEqual(result, [['alice']])
981
982
983 class TypeTestCase(common.JPypeTestCase):
984 """ This test is db dependent, but needed to check all
985 code paths. """
986
987 def setUp(self):
988 common.JPypeTestCase.setUp(self)
989 if common.fast:
990 raise common.unittest.SkipTest("fast")
991
992 def tearDown(self):
993 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
994 try:
995 cur.execute("drop table test")
996 except dbapi2.Error:
997 pass
998
999 def testTime(self):
1000 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1001 cu.execute("create table test(NAME TIME)")
1002 cu.execute("select * from test")
1003 t1 = jpype.java.sql.Time(1, 2, 3)
1004 cu.execute("insert into test(NAME) values(?)", [t1])
1005 f = cu.execute('select * from test').fetchone()
1006 self.assertIsInstance(f[0], datetime.time)
1007 cu.execute("delete from test")
1008 cu.execute("insert into test(NAME) values(?)", f)
1009 f2 = cu.execute('select * from test').fetchone()
1010 self.assertEqual(f2, f)
1011 cu.execute("delete from test")
1012
1013 # Test with Java
1014 t1 = jpype.java.sql.Time(1, 2, 3)
1015 cu.execute("insert into test(NAME) values(?)", [t1])
1016 f3 = cu.execute('select * from test').fetchone()
1017 self.assertEqual(f3[0], datetime.time(1, 2, 3))
1018 f4 = cu.execute('select * from test').fetchone(converters=None)
1019 self.assertEqual(f4[0], t1)
1020 self.assertIsInstance(f4[0], jpype.java.sql.Time)
1021 cu.execute("delete from test")
1022
1023 # Test with dbapi2.Time
1024 t1 = dbapi2.Time(6, 21, 32)
1025 cu.execute("insert into test(NAME) values(?)", [t1])
1026 f3 = cu.execute('select * from test').fetchone()
1027 self.assertEqual(f3[0], datetime.time(6, 21, 32))
1028
1029 def testDate(self):
1030 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1031 cu.execute("create table test(NAME DATE)")
1032 cu.execute("select * from test")
1033 t1 = java.sql.Date(2012 - 1900, 2 - 1, 5)
1034 cu.execute("insert into test(NAME) values(?)", [t1])
1035 #cu.execute("insert into test(NAME) values('2012-02-05')")
1036 f = cu.execute('select * from test').fetchone()
1037 self.assertIsInstance(f[0], datetime.date)
1038 cu.execute("delete from test")
1039 cu.execute("insert into test(NAME) values(?)", f)
1040 f2 = cu.execute('select * from test').fetchone()
1041 self.assertEqual(f2, f)
1042 cu.execute("delete from test")
1043
1044 # Test with Java
1045 t1 = java.sql.Date(1972 - 1900, 4 - 1, 1)
1046 cu.execute("insert into test(NAME) values(?)", [t1])
1047 f3 = cu.execute('select * from test').fetchone()
1048 self.assertEqual(f3[0], datetime.date(1972, 4, 1))
1049 f4 = cu.execute('select * from test').fetchone(converters=None)
1050 self.assertEqual(f4[0], t1)
1051 self.assertIsInstance(f4[0], java.sql.Date)
1052 cu.execute("delete from test")
1053
1054 # Test with dbapi2.Date
1055 t1 = dbapi2.Date(2020, 5, 21)
1056 cu.execute("insert into test(NAME) values(?)", [t1])
1057 f3 = cu.execute('select * from test').fetchone()
1058 self.assertEqual(f3[0], datetime.date(2020, 5, 21))
1059
1060 def testTimestamp(self):
1061 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1062 cu.execute("create table test(NAME TIMESTAMP)")
1063 cu.execute("select * from test")
1064 cu.execute("insert into test(NAME) values('2012-02-05 12:02:45.123')")
1065 f = cu.execute('select * from test').fetchone()
1066 self.assertIsInstance(f[0], datetime.date)
1067 cu.execute("delete from test")
1068 cu.execute("insert into test(NAME) values(?)", f)
1069 f2 = cu.execute('select * from test').fetchone()
1070 self.assertEqual(f2, f)
1071 cu.execute("delete from test")
1072
1073 # Test with Java
1074 t1 = java.sql.Timestamp(1972 - 1900, 4 - 1, 1, 12, 2, 45, 123000000)
1075 cu.execute("insert into test(NAME) values(?)", [t1])
1076 f3 = cu.execute('select * from test').fetchone()
1077 self.assertEqual(f3[0], datetime.datetime(1972, 4, 1, 12, 2, 45, 123000))
1078 f4 = cu.execute('select * from test').fetchone(converters=None)
1079 self.assertEqual(f4[0], t1)
1080 self.assertIsInstance(f4[0], java.sql.Timestamp)
1081 cu.execute("delete from test")
1082
1083 # Test with dbapi2.Date
1084 t1 = dbapi2.Timestamp(2020, 5, 21, 3, 4, 5, 123000000)
1085 cu.execute("insert into test(NAME) values(?)", [t1])
1086 f3 = cu.execute('select * from test').fetchone()
1087 self.assertEqual(f3[0], datetime.datetime(2020, 5, 21, 3, 4, 5, 123000))
1088
1089 def _testInt(self, tp, desc, jtype, null=True):
1090 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1091 cu.execute("create table test(NAME %s)" % tp)
1092 cu.execute("insert into test(NAME) values(?)", [123])
1093 f = cu.execute("select * from test").fetchone()
1094 self.assertEqual(f[0], 123)
1095 self.assertIsInstance(f[0], int)
1096 self.assertEqual(cu.description[0][0:2], desc)
1097 f = cu.execute("select * from test").fetchone(converters=None)
1098 self.assertEqual(f[0], 123)
1099 self.assertIsInstance(f[0], jtype)
1100 cu.execute("delete from test")
1101 if null:
1102 cu.execute("insert into test(NAME) values(?)", [None])
1103 f = cu.execute("select * from test").fetchone(converters=None)
1104 self.assertEqual(f[0], None)
1105
1106 def testTinyInt(self):
1107 self._testInt('TINYiNT', ('NAME', 'TINYINT'), jpype.JShort)
1108
1109 def testBigInt(self):
1110 self._testInt('BIGINT', ('NAME', 'BIGINT'), jpype.JLong)
1111
1112 def testIdentity(self):
1113 self._testInt('IDENTITY', ('NAME', 'IDENTITY'), jpype.JInt, False)
1114
1115 def testInteger(self):
1116 self._testInt('INTEGER', ('NAME', 'INTEGER'), jpype.JInt)
1117
1118 def testSmallInt(self):
1119 self._testInt('SMALLINT', ('NAME', 'SMALLINT'), jpype.JShort)
1120
1121 def _testFloat(self, tp, desc, jtype):
1122 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1123 cu.execute("create table test(NAME %s)" % tp)
1124 cu.execute("insert into test(NAME) values(?)", [1.25])
1125 f = cu.execute("select * from test").fetchone()
1126 self.assertEqual(f[0], 1.25)
1127 self.assertIsInstance(f[0], float)
1128 self.assertEqual(cu.description[0][0:2], desc)
1129 f = cu.execute("select * from test").fetchone(converters=None)
1130 self.assertEqual(f[0], 1.25)
1131 self.assertIsInstance(f[0], jtype)
1132 cu.execute("delete from test")
1133 cu.execute("insert into test(NAME) values(?)", [None])
1134 f = cu.execute("select * from test").fetchone(converters=None)
1135 self.assertEqual(f[0], None)
1136
1137 def testFloat(self):
1138 self._testFloat('FLOAT', ('NAME', 'FLOAT'), jpype.JDouble)
1139
1140 def testDouble(self):
1141 self._testFloat('DOUBLE', ('NAME', 'DOUBLE'), jpype.JDouble)
1142
1143 def testReal(self):
1144 self._testFloat('REAL', ('NAME', 'REAL'), jpype.JFloat)
1145
1146 def _testNumeric(self, tp, desc, jtype):
1147 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1148 cu.execute("create table test(NAME %s(5,2))" % tp)
1149 cu.execute("insert into test(NAME) values(?)", [1.25])
1150 f = cu.execute("select * from test").fetchone()
1151 self.assertEqual(f[0], 1.25)
1152 self.assertIsInstance(f[0], decimal.Decimal)
1153 self.assertEqual(cu.description[0][0:2], desc)
1154 f = cu.execute("select * from test").fetchone(converters=None)
1155 self.assertEqual(f[0], decimal.Decimal(1.25))
1156 self.assertIsInstance(f[0], jtype)
1157 cu.execute("delete from test")
1158 cu.execute("insert into test(NAME) values(?)", [None])
1159 f = cu.execute("select * from test").fetchone(converters=None)
1160 self.assertEqual(f[0], None)
1161
1162 def testNumeric(self):
1163 self._testNumeric('NUMERIC', ('NAME', 'NUMERIC'), java.math.BigDecimal)
1164
1165 def testDecimal(self):
1166 self._testNumeric('DECIMAL', ('NAME', 'DECIMAL'), java.math.BigDecimal)
1167
1168 def _testBinary(self, tp, desc, jtype):
1169 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1170 cu.execute("create table test(NAME %s)" % tp)
1171 v = bytes([1, 2, 3])
1172 cu.execute("insert into test(NAME) values(?)", [v])
1173 f = cu.execute("select * from test").fetchone()
1174 self.assertEqual(f[0], v)
1175 self.assertIsInstance(f[0], bytes)
1176 self.assertEqual(cu.description[0][0:2], desc)
1177 f = cu.execute("select * from test").fetchone(converters=None)
1178 self.assertEqual(bytes(f[0]), v)
1179 self.assertIsInstance(f[0], jtype)
1180 cu.execute("delete from test")
1181 cu.execute("insert into test(NAME) values(?)", [None])
1182 f = cu.execute("select * from test").fetchone(converters=None)
1183 self.assertEqual(f[0], None)
1184
1185 def testBinary(self):
1186 self._testBinary('BINARY(3)', ('NAME', 'BINARY'), JArray(JByte))
1187
1188 def testBlob(self):
1189 self._testBinary('BLOB', ('NAME', 'BLOB'), JArray(JByte))
1190
1191 def testLongVarBinary(self):
1192 self._testBinary('LONGVARBINARY', ('NAME', 'LONGVARBINARY'), JArray(JByte))
1193
1194 def testVarBinary(self):
1195 self._testBinary('VARBINARY(10)', ('NAME', 'VARBINARY'), JArray(JByte))
1196
1197 def _testChars(self, tp, desc, jtype, v="hello"):
1198 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1199 cu.execute("create table test(NAME %s)" % tp)
1200 cu.execute("insert into test(NAME) values(?)", [v])
1201 f = cu.execute("select * from test").fetchone()
1202 self.assertEqual(f[0], v)
1203 self.assertIsInstance(f[0], str)
1204 self.assertEqual(cu.description[0][0:2], desc)
1205 f = cu.execute("select * from test").fetchone(converters=None)
1206 self.assertEqual(f[0], v)
1207 self.assertIsInstance(f[0], jtype)
1208 cu.execute("delete from test")
1209 cu.execute("insert into test(NAME) values(?)", [None])
1210 f = cu.execute("select * from test").fetchone(converters=None)
1211 self.assertEqual(f[0], None)
1212
1213 def testChar(self):
1214 self._testChars('CHAR', ('NAME', 'CHAR'), java.lang.String, 'a')
1215
1216 def testVarChar(self):
1217 self._testChars('VARCHAR', ('NAME', 'VARCHAR'), java.lang.String)
1218
1219 def testLongVarChar(self):
1220 self._testChars('LONGVARCHAR', ('NAME', 'LONGVARCHAR'), java.lang.String)
1221
1222 def testClob(self):
1223 self._testChars('CLOB', ('NAME', 'CLOB'), java.lang.String)
1224
1225 def testBoolean(self):
1226 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1227 cu.execute("create table test(NAME BOOLEAN)")
1228 cu.execute("insert into test(NAME) values(?)", [True])
1229 f = cu.execute("select * from test").fetchone()
1230 self.assertEqual(f[0], True)
1231 self.assertIsInstance(f[0], int)
1232 self.assertEqual(cu.description[0][0:2], ('NAME', 'BOOLEAN'))
1233 f = cu.execute("select * from test").fetchone(converters=None)
1234 self.assertEqual(f[0], True)
1235 self.assertIsInstance(f[0], type(True))
1236 cu.execute("delete from test")
1237 cu.execute("insert into test(NAME) values(?)", [None])
1238 f = cu.execute("select * from test").fetchone(converters=None)
1239 self.assertEqual(f[0], None)
1240
1241
1242 class OtherTestCase(common.JPypeTestCase):
1243 """ This test is db dependent, but needed to check all
1244 code paths. """
1245
1246 def setUp(self):
1247 common.JPypeTestCase.setUp(self)
1248 if common.fast:
1249 raise common.unittest.SkipTest("fast")
1250
1251 def tearDown(self):
1252 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
1253 try:
1254 cur.execute("drop table test")
1255 except dbapi2.Error:
1256 pass
1257
1258 def testJSON(self):
1259 got = []
1260
1261 class MyType(dbapi2.JDBCType):
1262 def get(self, rs, column, st):
1263 got.append(column)
1264 return dbapi2.JDBCType.get(self, rs, column, st)
1265 # Register a new type
1266 JSON = MyType("JSON", None)
1267 with dbapi2.connect(db_name, getters=dbapi2.GETTERS_BY_NAME) as cx, cx.cursor() as cu:
1268 cu.execute("create table test(name JSON)")
1269 cu.execute("insert into test(name) values('{age: 31}')")
1270 f = cu.execute("select * from test").fetchone()
1271 self.assertEqual(got, [1])
1272 del dbapi2._registry[JSON]
1273
1274
1275 class ThreadingTestCase(common.JPypeTestCase):
1276 def setUp(self):
1277 common.JPypeTestCase.setUp(self)
1278 if common.fast:
1279 raise common.unittest.SkipTest("fast")
1280
1281 def tearDown(self):
1282 with dbapi2.connect(db_name) as cx, cx.cursor() as cur:
1283 try:
1284 cur.execute("drop table test")
1285 except dbapi2.Error:
1286 pass
1287
1288 def _testThread(self, cu, cmd, args, exc):
1289 error = []
1290
1291 def run():
1292 try:
1293 cmd(*args)
1294 except Exception as ex:
1295 error.append(ex)
1296 t = threading.Thread(target=run)
1297 t.start()
1298 t.join()
1299 self.assertEqual(len(error), 1)
1300 with self.assertRaises(exc):
1301 raise error[0]
1302
1303 def test_execute(self):
1304 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1305 cu.execute("create table test(name VARCHAR(10))")
1306 self._testThread(cu, cu.execute, ("insert into test(name) values ('a')",), dbapi2.ProgrammingError)
1307
1308 def test_executemany(self):
1309 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1310 cu.execute("create table test(name VARCHAR(10))")
1311 self._testThread(cu, cu.executemany, ("insert into test(name) values ('?')", [[1]]), dbapi2.ProgrammingError)
1312
1313 def test_fetchone(self):
1314 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1315 cu.execute("create table test(name VARCHAR(10))")
1316 cu.execute("insert into test(name) values('a')")
1317 self._testThread(cu, cu.fetchone, (), dbapi2.ProgrammingError)
1318
1319 def test_fetchmany(self):
1320 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1321 cu.execute("create table test(name VARCHAR(10))")
1322 cu.execute("insert into test(name) values('a')")
1323 self._testThread(cu, cu.fetchmany, (), dbapi2.ProgrammingError)
1324
1325 def test_fetchall(self):
1326 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1327 cu.execute("create table test(name VARCHAR(10))")
1328 cu.execute("insert into test(name) values('a')")
1329 self._testThread(cu, cu.fetchall, (), dbapi2.ProgrammingError)
1330
1331 def test_close(self):
1332 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1333 cu.execute("create table test(name VARCHAR(10))")
1334 cu.execute("insert into test(name) values('a')")
1335 self._testThread(cu, cu.close, (), dbapi2.ProgrammingError)
1336
1337 @common.unittest.skip # type: ignore
1338 def test_callproc(self):
1339 with dbapi2.connect(db_name) as cx, cx.cursor() as cu:
1340 cu.execute("create table test(name VARCHAR(10))")
1341 cu.execute("insert into test(name) values('a')")
1342 self._testThread(cu, cu.callproc, ("lower", ["FOO"]), dbapi2.ProgrammingError)