Debian Codegraph @

test/jpypetest/test_sql_hsqldb.py

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