forked from rogerbinns/apsw
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tests.py
8437 lines (7518 loc) · 327 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# See the accompanying LICENSE file.
# APSW test suite - runs under both Python 2 and Python 3 hence a lot
# of weird constructs to be simultaneously compatible with both.
# (2to3 is not used).
import apsw
import sys
import os
import codecs
write=sys.stdout.write
def print_version_info(write=write):
write(" Python "+sys.executable+" "+str(sys.version_info)+"\n")
write("Testing with APSW file "+apsw.__file__+"\n")
write(" APSW version "+apsw.apswversion()+"\n")
write(" SQLite lib version "+apsw.sqlitelibversion()+"\n")
write("SQLite headers version "+str(apsw.SQLITE_VERSION_NUMBER)+"\n")
write(" Using amalgamation "+str(apsw.using_amalgamation)+"\n")
if [int(x) for x in apsw.sqlitelibversion().split(".")]<[3,7,8]:
write("You are using an earlier version of SQLite than recommended\n")
sys.stdout.flush()
# sigh
iswindows=sys.platform in ('win32', 'win64')
py3=sys.version_info>=(3,0)
# prefix for test files (eg if you want it on tmpfs)
TESTFILEPREFIX=os.environ.get("APSWTESTPREFIX", "")
def read_whole_file(name, mode, encoding=None):
if encoding:
f=codecs.open(name, mode, encoding)
else:
f=open(name, mode)
try:
return f.read()
finally:
f.close()
# If two is present then one is encoding
def write_whole_file(name, mode, one, two=None):
if two:
f=codecs.open(name, mode, one)
data=two
else:
f=open(name, mode)
data=one
try:
f.write(data)
finally:
f.close()
# unittest stuff from here on
import unittest
import math
import random
import time
import threading
import glob
import pickle
import shutil
import getpass
if py3:
import queue as Queue
else:
import Queue
import traceback
import re
import gc
try:
import ctypes
import _ctypes
except:
ctypes=None
_ctypes=None
# yay
is64bit=ctypes and ctypes.sizeof(ctypes.c_size_t)>=8
# Unicode string/bytes prefix
if py3:
UPREFIX=""
BPREFIX="b"
else:
UPREFIX="u"
BPREFIX=""
# Return a unicode string - x should have been raw
def u(x):
return eval(UPREFIX+"'''"+x+"'''")
# Return a bytes (py3)/buffer (py2) - x should have been raw
def b(x):
if py3:
return eval(BPREFIX+"'''"+x+"'''")
return eval("buffer('''"+x+"''')")
# return bytes (py3)/string (py2) - x should have been raw
# Use this instead of b for file i/o data as py2 uses str
def BYTES(x):
if py3: return b(x)
return eval("'''"+x+"'''")
def l(x):
if py3: return eval(x)
return eval(x+"L")
# Various py3 things
if py3:
long=int
if not py3:
# emulation of py3 next built-in. In py2 the iternext method is exposed
# as object.next() but in py3 it is object.__next__().
def next(iterator, *args):
if len(args)>1:
raise TypeError("bad args")
try:
return iterator.next()
except StopIteration:
if len(args):
return args[0]
raise
# Make next switch between the iterator and fetchone alternately
_realnext=next
_nextcounter=0
def next(cursor, *args):
global _nextcounter
_nextcounter+=1
if _nextcounter%2:
return _realnext(cursor, *args)
res=cursor.fetchone()
if res is None:
if args:
return args[0]
return None
return res
# py3 has a useless sys.excepthook mainly to avoid allocating any
# memory as the exception could have been running out of memory. So
# we use our own which is also valuable on py2 as it says it is an
# unraiseable exception (with testcode you sometimes can't tell if it
# is unittest showing you an exception or the unraiseable). It is
# mainly VFS code that needs to raise these.
def ehook(etype, evalue, etraceback):
sys.stderr.write("Unraiseable exception "+str(etype)+":"+str(evalue)+"\n")
traceback.print_tb(etraceback)
sys.excepthook=ehook
# exec is a huge amount of fun having different syntax
if py3:
def execwrapper(astring, theglobals, thelocals):
thelocals=thelocals.copy()
thelocals["astring"]=astring
exec("exec(astring, theglobals, thelocals)")
else:
def execwrapper(astring, theglobals, thelocals):
thelocals=thelocals.copy()
thelocals["astring"]=astring
exec ("exec astring in theglobals, thelocals")
# helper functions
def randomintegers(howmany):
for i in range(howmany):
yield (random.randint(0,9999999999),)
def randomstring(length):
l=list("abcdefghijklmnopqrstuvwxyz0123456789")
while len(l)<length:
l.extend(l)
l=l[:length]
random.shuffle(l)
return "".join(l)
# An instance of this class is used to get the -1 return value to the
# C api PyObject_IsTrue
class BadIsTrue(int):
# py2 does this
def __nonzero__(self):
1/0
# py3 does this
def __bool__(self):
1/0
# helper class - runs code in a separate thread
class ThreadRunner(threading.Thread):
def __init__(self, callable, *args, **kwargs):
threading.Thread.__init__(self)
self.setDaemon(True)
self.callable=callable
self.args=args
self.kwargs=kwargs
self.q=Queue.Queue()
self.started=False
def start(self):
if not self.started:
self.started=True
threading.Thread.start(self)
def go(self):
self.start()
t,res=self.q.get()
if t: # result
return res
else: # exception
if py3:
exec("raise res[1].with_traceback(res[2])")
else:
exec("raise res[0], res[1], res[2]")
def run(self):
try:
self.q.put( (True, self.callable(*self.args, **self.kwargs)) )
except:
self.q.put( (False, sys.exc_info()) )
# Windows doesn't allow files that are open to be deleted. Even after
# we close them, tagalongs such as virus scanners, tortoisesvn etc can
# keep them open. But the good news is that we can rename a file that
# is in use. This background thread does the background deletions of the
# renamed files
def bgdel():
q=bgdelq
while True:
name=q.get()
while os.path.exists(name):
try:
if os.path.isfile(name):
os.remove(name)
else:
shutil.rmtree(name)
except:
pass
if os.path.exists(name):
time.sleep(0.1)
bgdelq=Queue.Queue()
bgdelthread=threading.Thread(target=bgdel)
bgdelthread.setDaemon(True)
bgdelthread.start()
def deletefile(name):
l=list("abcdefghijklmn")
random.shuffle(l)
newname=name+"-n-"+"".join(l)
count=0
while os.path.exists(name):
count+=1
try:
os.rename(name, newname)
except:
if count>30: # 3 seconds we have been at this!
# So give up and give it a stupid name. The sooner
# this so called operating system withers into obscurity
# the better
n=list("abcdefghijklmnopqrstuvwxyz")
random.shuffle(n)
n="".join(n)
try:
os.rename(name, "windowssucks-"+n+".deletememanually")
except:
pass
break
# Make windows happy
time.sleep(0.1)
gc.collect()
if os.path.exists(newname):
bgdelq.put(newname)
# Give bg thread a chance to run
time.sleep(0.1)
# Monkey patching FTW
if not hasattr(unittest.TestCase, "assertTrue"):
unittest.TestCase.assertTrue=unittest.TestCase.assert_
openflags=apsw.SQLITE_OPEN_READWRITE|apsw.SQLITE_OPEN_CREATE|apsw.SQLITE_OPEN_URI
# main test class/code
class APSW(unittest.TestCase):
connection_nargs={ # number of args for function. those not listed take zero
'createaggregatefunction': 2,
'createcollation': 2,
'createscalarfunction': 3,
'collationneeded': 1,
'setauthorizer': 1,
'setbusyhandler': 1,
'setbusytimeout': 1,
'setcommithook': 1,
'setprofile': 1,
'setrollbackhook': 1,
'setupdatehook': 1,
'setprogresshandler': 2,
'enableloadextension': 1,
'createmodule': 2,
'filecontrol': 3,
'setexectrace': 1,
'setrowtrace': 1,
'__enter__': 0,
'__exit__': 3,
'backup': 3,
'wal_autocheckpoint': 1,
'setwalhook': 1,
'readonly': 1,
'db_filename': 1,
'set_last_insert_rowid': 1,
}
cursor_nargs={
'execute': 1,
'executemany': 2,
'setexectrace': 1,
'setrowtrace': 1,
}
blob_nargs={
'write': 1,
'read': 1,
'readinto': 1,
'reopen': 1,
'seek': 2
}
def deltempfiles(self):
for name in ("testdb", "testdb2", "testdb3", "testfile", "testfile2", "testdb2x",
"test-shell-1", "test-shell-1.py",
"test-shell-in", "test-shell-out", "test-shell-err"):
for i in "-wal", "-journal", "":
if os.path.exists(TESTFILEPREFIX+name+i):
deletefile(TESTFILEPREFIX+name+i)
saved_connection_hooks=[]
def setUp(self):
# clean out database and journals from last runs
self.saved_connection_hooks.append(apsw.connection_hooks)
gc.collect()
self.deltempfiles()
self.db=apsw.Connection(TESTFILEPREFIX+"testdb", flags=openflags)
def tearDown(self):
if self.db is not None:
self.db.close(True)
del self.db
apsw.connection_hooks=self.saved_connection_hooks.pop() # back to original value
gc.collect()
self.deltempfiles()
def assertTableExists(self, tablename):
self.assertEqual(next(self.db.cursor().execute("select count(*) from ["+tablename+"]"))[0], 0)
def assertTableNotExists(self, tablename):
# you get SQLError if the table doesn't exist!
self.assertRaises(apsw.SQLError, self.db.cursor().execute, "select count(*) from ["+tablename+"]")
def assertTablesEqual(self, dbl, left, dbr, right):
# Ensure tables have the same contents. Rowids can be
# different and select gives unordered results so this is
# quite challenging
l=dbl.cursor()
r=dbr.cursor()
# check same number of rows
lcount=l.execute("select count(*) from ["+left+"]").fetchall()[0][0]
rcount=r.execute("select count(*) from ["+right+"]").fetchall()[0][0]
self.assertEqual(lcount, rcount)
# check same number and names and order for columns
lnames=[row[1] for row in l.execute("pragma table_info(["+left+"])")]
rnames=[row[1] for row in r.execute("pragma table_info(["+left+"])")]
self.assertEqual(lnames, rnames)
# read in contents, sort and compare
lcontents=l.execute("select * from ["+left+"]").fetchall()
rcontents=r.execute("select * from ["+right+"]").fetchall()
lcontents.sort()
rcontents.sort()
self.assertEqual(lcontents, rcontents)
def assertRaisesUnraisable(self, exc, func, *args, **kwargs):
return self.baseAssertRaisesUnraisable(True, exc, func, args, kwargs)
def assertMayRaiseUnraisable(self, exc, func, *args, **kwargs):
"""Like assertRaisesUnraiseable but no exception may be raised.
If one is raised, it must have the expected type.
"""
return self.baseAssertRaisesUnraisable(False, exc, func, args, kwargs)
def baseAssertRaisesUnraisable(self, must_raise, exc, func, args, kwargs):
orig=sys.excepthook
try:
called=[]
def ehook(t,v,tb):
called.append( (t,v,tb) )
sys.excepthook=ehook
try:
try:
return func(*args, **kwargs)
except:
# This ensures frames have their local variables
# cleared before we put the original excepthook
# back. Clearing the variables results in some
# more SQLite operations which also can raise
# unraisables. traceback.clear_frames was
# introduced in Python 3.4 and unittest was
# updated to call it in assertRaises. See issue
# 164
if hasattr(traceback, "clear_frames"):
traceback.clear_frames(sys.exc_info()[2])
raise
finally:
if must_raise and len(called)<1:
self.fail("Call %s(*%s, **%s) did not do any unraiseable" % (func, args, kwargs) )
if len(called):
self.assertEqual(exc, called[0][0]) # check it was the correct type
finally:
sys.excepthook=orig
def testSanity(self):
"Check all parts compiled and are present"
# check some error codes etc are present - picked first middle and last from lists in code
apsw.SQLError
apsw.MisuseError
apsw.NotADBError
apsw.ThreadingViolationError
apsw.BindingsError
apsw.ExecTraceAbort
apsw.SQLITE_FCNTL_SIZE_HINT
apsw.mapping_file_control["SQLITE_FCNTL_SIZE_HINT"]==apsw.SQLITE_FCNTL_SIZE_HINT
apsw.URIFilename
self.assertTrue(len(apsw.sqlite3_sourceid())>10)
def testConnection(self):
"Test connection opening"
# bad keyword arg
self.assertRaises(TypeError, apsw.Connection, ":memory:", user="nobody")
# wrong types
self.assertRaises(TypeError, apsw.Connection, 3)
# non-unicode
if not py3:
self.assertRaises(UnicodeDecodeError, apsw.Connection, "\xef\x22\xd3\x9e")
# bad file (cwd)
self.assertRaises(apsw.CantOpenError, apsw.Connection, ".")
# bad open flags can't be tested as sqlite accepts them all - ticket #3037
# self.assertRaises(apsw.CantOpenError, apsw.Connection, "<non-existent-file>", flags=65535)
# bad vfs
self.assertRaises(TypeError, apsw.Connection, "foo", vfs=3, flags=-1)
self.assertRaises(apsw.SQLError, apsw.Connection, "foo", vfs="jhjkds")
def testConnectionFileControl(self):
"Verify sqlite3_file_control"
# Note that testVFS deals with success cases and the actual vfs backend
self.assertRaises(TypeError, self.db.filecontrol, 1, 2)
self.assertRaises(TypeError, self.db.filecontrol, "main", 1001, "foo")
self.assertRaises(OverflowError, self.db.filecontrol, "main", 1001, l("45236748972389749283"))
self.assertEqual(self.db.filecontrol("main", 1001, 25), False)
def testConnectionConfig(self):
"Test Connection.config function"
self.assertRaises(TypeError, self.db.config)
self.assertRaises(TypeError, self.db.config, "three")
x=long(0x7fffffff)
self.assertRaises(OverflowError, self.db.config, x*x*x*x*x)
self.assertRaises(ValueError, self.db.config, 82397)
self.assertRaises(TypeError, self.db.config, apsw.SQLITE_DBCONFIG_ENABLE_FKEY, "banana")
for i in apsw.SQLITE_DBCONFIG_ENABLE_FKEY, apsw.SQLITE_DBCONFIG_ENABLE_TRIGGER, apsw.SQLITE_DBCONFIG_ENABLE_QPSG:
self.assertEqual(1, self.db.config(i, 1))
self.assertEqual(1, self.db.config(i, -1))
self.assertEqual(0, self.db.config(i, 0))
def testMemoryLeaks(self):
"MemoryLeaks: Run with a memory profiler such as valgrind and debug Python"
# make and toss away a bunch of db objects, cursors, functions etc - if you use memory profiling then
# simple memory leaks will show up
c=self.db.cursor()
c.execute("create table foo(x)")
vals=[ [1], [None], [math.pi], ["kjkljkljl"], [u(r"\u1234\u345432432423423kjgjklhdfgkjhsdfjkghdfjskh")],
[b(r"78696ghgjhgjhkgjkhgjhg\xfe\xdf")] ]
c.executemany("insert into foo values(?)", vals)
for i in range(MEMLEAKITERATIONS):
db=apsw.Connection(TESTFILEPREFIX+"testdb")
db.createaggregatefunction("aggfunc", lambda x: x)
db.createscalarfunction("scalarfunc", lambda x: x)
db.setbusyhandler(lambda x: False)
db.setbusytimeout(1000)
db.setcommithook(lambda x=1: 0)
db.setrollbackhook(lambda x=2: 1)
db.setupdatehook(lambda x=3: 2)
db.setwalhook(lambda *args: 0)
db.collationneeded(lambda x: 4)
def rt1(c,r):
db.setrowtrace(rt2)
return r
def rt2(c,r):
c.setrowtrace(rt1)
return r
def et1(c,s,b):
db.setexectrace(et2)
return True
def et2(c,s,b):
c.setexectrace(et1)
return True
for i in range(120):
c2=db.cursor()
c2.setrowtrace(rt1)
c2.setexectrace(et1)
for row in c2.execute("select * from foo"+" "*i): # spaces on end defeat statement cache
pass
del c2
db.close()
def testBindings(self):
"Check bindings work correctly"
c=self.db.cursor()
c.execute("create table foo(x,y,z)")
vals=(
("(?,?,?)", (1,2,3)),
("(?,?,?)", [1,2,3]),
("(?,?,?)", range(1,4)),
("(:a,$b,:c)", {'a': 1, 'b': 2, 'c': 3}),
("(1,?,3)", (2,)),
("(1,$a,$c)", {'a': 2, 'b': 99, 'c': 3}),
# some unicode fun
(u(r"($\N{LATIN SMALL LETTER E WITH CIRCUMFLEX},:\N{LATIN SMALL LETTER A WITH TILDE},$\N{LATIN SMALL LETTER O WITH DIAERESIS})"), (1,2,3)),
(u(r"($\N{LATIN SMALL LETTER E WITH CIRCUMFLEX},:\N{LATIN SMALL LETTER A WITH TILDE},$\N{LATIN SMALL LETTER O WITH DIAERESIS})"),
{u(r"\N{LATIN SMALL LETTER E WITH CIRCUMFLEX}"): 1,
u(r"\N{LATIN SMALL LETTER A WITH TILDE}"): 2,
u(r"\N{LATIN SMALL LETTER O WITH DIAERESIS}"): 3,})
)
for str,bindings in vals:
c.execute("insert into foo values"+str, bindings)
self.assertEqual(next(c.execute("select * from foo")), (1,2,3))
c.execute("delete from foo")
# currently missing dict keys come out as null
c.execute("insert into foo values(:a,:b,$c)", {'a': 1, 'c':3}) # 'b' deliberately missing
self.assertEqual((1,None,3), next(c.execute("select * from foo")))
c.execute("delete from foo")
# these ones should cause errors
vals=(
(apsw.BindingsError, "(?,?,?)", (1,2)), # too few
(apsw.BindingsError, "(?,?,?)", (1,2,3,4)), # too many
(apsw.BindingsError, "(?,?,?)", None), # none at all
(apsw.BindingsError, "(?,?,?)", {'a': 1}), # ? type, dict bindings (note that the reverse will work since all
# named bindings are also implicitly numbered
(TypeError, "(?,?,?)", 2), # not a dict or sequence
(TypeError, "(:a,:b,:c)", {'a': 1, 'b': 2, 'c': self}), # bad type for c
)
for exc,str,bindings in vals:
self.assertRaises(exc, c.execute, "insert into foo values"+str, bindings)
# with multiple statements
c.execute("insert into foo values(?,?,?); insert into foo values(?,?,?)", (99,100,101,102,103,104))
self.assertRaises(apsw.BindingsError, c.execute, "insert into foo values(?,?,?); insert into foo values(?,?,?); insert some more",
(100,100,101,1000,103)) # too few
self.assertRaises(apsw.BindingsError, c.execute, "insert into foo values(?,?,?); insert into foo values(?,?,?)",
(101,100,101,1000,103,104,105)) # too many
# check the relevant statements did or didn't execute as appropriate
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=99"))[0], 1)
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=102"))[0], 1)
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=100"))[0], 1)
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=1000"))[0], 0)
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=101"))[0], 1)
self.assertEqual(next(self.db.cursor().execute("select count(*) from foo where x=105"))[0], 0)
# check there are some bindings!
self.assertRaises(apsw.BindingsError, c.execute, "create table bar(x,y,z);insert into bar values(?,?,?)")
# across executemany
vals=( (1,2,3), (4,5,6), (7,8,9) )
c.executemany("insert into foo values(?,?,?);", vals)
for x,y,z in vals:
self.assertEqual(next(c.execute("select * from foo where x=?",(x,))), (x,y,z))
# with an iterator
def myvals():
for i in range(10):
yield {'a': i, 'b': i*10, 'c': i*100}
c.execute("delete from foo")
c.executemany("insert into foo values($a,:b,$c)", myvals())
c.execute("delete from foo")
# errors for executemany
self.assertRaises(TypeError, c.executemany, "statement", 12, 34, 56) # incorrect num params
self.assertRaises(TypeError, c.executemany, "statement", 12) # wrong type
self.assertRaises(apsw.SQLError, c.executemany, "syntax error", [(1,)]) # error in prepare
def myiter():
yield 1/0
self.assertRaises(ZeroDivisionError, c.executemany, "statement", myiter()) # immediate error in iterator
def myiter():
yield self
self.assertRaises(TypeError, c.executemany, "statement", myiter()) # immediate bad type
self.assertRaises(TypeError, c.executemany, "select ?", ((self,), (1))) # bad val
c.executemany("statement", ()) # empty sequence
# error in iterator after a while
def myvals():
for i in range(2):
yield {'a': i, 'b': i*10, 'c': i*100}
1/0
self.assertRaises(ZeroDivisionError, c.executemany, "insert into foo values($a,:b,$c)", myvals())
self.assertEqual(next(c.execute("select count(*) from foo"))[0], 2)
c.execute("delete from foo")
# return bad type from iterator after a while
def myvals():
for i in range(2):
yield {'a': i, 'b': i*10, 'c': i*100}
yield self
self.assertRaises(TypeError, c.executemany, "insert into foo values($a,:b,$c)", myvals())
self.assertEqual(next(c.execute("select count(*) from foo"))[0], 2)
c.execute("delete from foo")
# some errors in executemany
self.assertRaises(apsw.BindingsError, c.executemany, "insert into foo values(?,?,?)", ( (1,2,3), (1,2,3,4)))
self.assertRaises(apsw.BindingsError, c.executemany, "insert into foo values(?,?,?)", ( (1,2,3), (1,2)))
# incomplete execution across executemany
c.executemany("select * from foo; select ?", ( (1,), (2,) )) # we don't read
self.assertRaises(apsw.IncompleteExecutionError, c.executemany, "begin")
# set type (pysqlite error with this)
if sys.version_info>=(2, 4, 0):
c.execute("create table xxset(x,y,z)")
c.execute("insert into xxset values(?,?,?)", set((1,2,3)))
c.executemany("insert into xxset values(?,?,?)", (set((4,5,6)),))
result=[(1,2,3), (4,5,6)]
for i,v in enumerate(c.execute("select * from xxset order by x")):
self.assertEqual(v, result[i])
def testCursor(self):
"Check functionality of the cursor"
c=self.db.cursor()
# shouldn't be able to manually create
self.assertRaises(TypeError, type(c))
# give bad params
self.assertRaises(TypeError, c.execute)
self.assertRaises(TypeError, c.execute, "foo", "bar", "bam")
# empty statements
c.execute("")
c.execute(" ;\n\t\r;;")
# unicode
self.assertEqual(3, next(c.execute(u("select 3")))[0])
if not py3:
self.assertRaises(UnicodeDecodeError, c.execute, "\x99\xaa\xbb\xcc")
# does it work?
c.execute("create table foo(x,y,z)")
# table should be empty
entry=-1
for entry,values in enumerate(c.execute("select * from foo")):
pass
self.assertEqual(entry,-1, "No rows should have been returned")
# add ten rows
for i in range(10):
c.execute("insert into foo values(1,2,3)")
for entry,values in enumerate(c.execute("select * from foo")):
# check we get back out what we put in
self.assertEqual(values, (1,2,3))
self.assertEqual(entry, 9, "There should have been ten rows")
# does getconnection return the right object
self.assertTrue(c.getconnection() is self.db)
# check getdescription - note column with space in name and [] syntax to quote it
cols=(
("x a space", "integer"),
("y", "text"),
("z", "foo"),
("a", "char"),
(u(r"\N{LATIN SMALL LETTER E WITH CIRCUMFLEX}\N{LATIN SMALL LETTER A WITH TILDE}"),
u(r"\N{LATIN SMALL LETTER O WITH DIAERESIS}\N{LATIN SMALL LETTER U WITH CIRCUMFLEX}")),
)
c.execute("drop table foo; create table foo (%s)" % (", ".join(["[%s] %s" % (n,t) for n,t in cols]),))
c.execute("insert into foo([x a space]) values(1)")
for row in c.execute("select * from foo"):
self.assertEqual(cols, c.getdescription())
self.assertEqual(cols, tuple([d[:2] for d in c.description]))
self.assertEqual((None,None,None,None,None), c.description[0][2:])
self.assertEqual(list(map(len, c.description)), [7]*len(cols))
# check description caching isn't broken
cols2=cols[1:4]
for row in c.execute("select y,z,a from foo"):
self.assertEqual(cols2, c.getdescription())
self.assertEqual(cols2, tuple([d[:2] for d in c.description]))
self.assertEqual((None,None,None,None,None), c.description[0][2:])
self.assertEqual(list(map(len, c.description)), [7]*len(cols2))
# execution is complete ...
self.assertRaises(apsw.ExecutionCompleteError, c.getdescription)
self.assertRaises(apsw.ExecutionCompleteError, lambda: c.description)
self.assertRaises(StopIteration, lambda xx=0: _realnext(c))
self.assertRaises(StopIteration, lambda xx=0: _realnext(c))
# fetchone is used throughout, check end behaviour
self.assertEqual(None, c.fetchone())
self.assertEqual(None, c.fetchone())
self.assertEqual(None, c.fetchone())
# nulls for getdescription
for row in c.execute("pragma user_version"):
self.assertEqual(c.getdescription(), ( ('user_version', None), ))
# incomplete
c.execute("select * from foo; create table bar(x)") # we don't bother reading leaving
self.assertRaises(apsw.IncompleteExecutionError, c.execute, "select * from foo") # execution incomplete
self.assertTableNotExists("bar")
# autocommit
self.assertEqual(True, self.db.getautocommit())
c.execute("begin immediate")
self.assertEqual(False, self.db.getautocommit())
# pragma
c.execute("pragma user_version")
c.execute("pragma pure=nonsense")
# error
self.assertRaises(apsw.SQLError, c.execute, "create table bar(x,y,z); this is a syntax error; create table bam(x,y,z)")
self.assertTableExists("bar")
self.assertTableNotExists("bam")
# fetchall
self.assertEqual(c.fetchall(), [])
self.assertEqual(c.execute("select 3; select 4").fetchall(), [(3,), (4,)] )
def testTypes(self):
"Check type information is maintained"
c=self.db.cursor()
c.execute("create table foo(row,x)")
vals=test_types_vals
for i,v in enumerate(vals):
c.execute("insert into foo values(?,?)", (i, v))
# add function to test conversion back as well
def snap(*args):
return args[0]
self.db.createscalarfunction("snap", snap)
# now see what we got out
count=0
for row,v,fv in c.execute("select row,x,snap(x) from foo"):
count+=1
if type(vals[row]) is float:
self.assertAlmostEqual(vals[row], v)
self.assertAlmostEqual(vals[row], fv)
else:
self.assertEqual(vals[row], v)
self.assertEqual(vals[row], fv)
self.assertEqual(count, len(vals))
# check some out of bounds conditions
# integer greater than signed 64 quantity (SQLite only supports up to that)
self.assertRaises(OverflowError, c.execute, "insert into foo values(9999,?)", (922337203685477580799,))
self.assertRaises(OverflowError, c.execute, "insert into foo values(9999,?)", (-922337203685477580799,))
# invalid character data - non-ascii data must be provided in unicode
if not py3: # py3 - all strings are unicode so not a problem
self.assertRaises(UnicodeDecodeError, c.execute, "insert into foo values(9999,?)", ("\xfe\xfb\x80\x92",))
# not valid types for SQLite
self.assertRaises(TypeError, c.execute, "insert into foo values(9999,?)", (apsw,)) # a module
self.assertRaises(TypeError, c.execute, "insert into foo values(9999,?)", (type,)) # type
self.assertRaises(TypeError, c.execute, "insert into foo values(9999,?)", (dir,)) # function
# check nothing got inserted
self.assertEqual(0, next(c.execute("select count(*) from foo where row=9999"))[0])
# playing with default encoding and non-ascii strings - py2 only
if py3: return
enc=sys.getdefaultencoding()
reload(sys) # gets setdefaultencoding function back
try:
for v in vals:
if type(v)!=unicode:
continue
def encoding(*args):
return v.encode("utf8") # returns as str not unicode
self.db.createscalarfunction("encoding", encoding)
sys.setdefaultencoding("utf8")
for row in c.execute("select encoding(3)"):
self.assertEqual(v, row[0])
c.execute("insert into foo values(1234,?)", (v.encode("utf8"),))
for row in c.execute("select x from foo where rowid="+str(self.db.last_insert_rowid())):
self.assertEqual(v, row[0])
finally:
sys.setdefaultencoding(enc)
def testFormatSQLValue(self):
"Verify text formatting of values"
vals=(
(3, "3"),
(3.1, "3.1"),
(-3, "-3"),
(-3.1, "-3.1"),
(9223372036854775807, "9223372036854775807"),
(-9223372036854775808, "-9223372036854775808"),
(None, "NULL"),
("ABC", "'ABC'"),
(u(r"\N{BLACK STAR} \N{WHITE STAR} \N{LIGHTNING} \N{COMET} "), "'"+u(r"\N{BLACK STAR} \N{WHITE STAR} \N{LIGHTNING} \N{COMET} ")+"'"),
("", "''"),
("'", "''''"),
("'a", "'''a'"),
("a'", "'a'''"),
("''", "''''''"),
("'"*20000, "'"+"'"*40000+"'"),
("\0", "''||X'00'||''"),
("AB\0C", "'AB'||X'00'||'C'"),
("A'B'\0C", "'A''B'''||X'00'||'C'"),
("\0A'B", "''||X'00'||'A''B'"),
("A'B\0", "'A''B'||X'00'||''"),
(b(r"AB\0C"), "X'41420043'"),
)
for vin, vout in vals:
if not py3:
if isinstance(vin, str):
vin=unicode(vin)
out=apsw.format_sql_value(vin)
if not py3:
self.assertEqual(out, unicode(vout))
else:
self.assertEqual(out, vout)
# Errors
if not py3:
self.assertRaises(TypeError, apsw.format_sql_value, "plain string")
self.assertRaises(TypeError, apsw.format_sql_value, apsw)
self.assertRaises(TypeError, apsw.format_sql_value)
def testWAL(self):
"Test WAL functions"
# note that it is harmless calling wal functions on a db not in wal mode
self.assertRaises(TypeError, self.db.wal_autocheckpoint)
self.assertRaises(TypeError, self.db.wal_autocheckpoint, "a strinbg")
self.db.wal_autocheckpoint(8912)
self.assertRaises(TypeError, self.db.wal_checkpoint, -1)
self.db.wal_checkpoint()
self.db.wal_checkpoint("main")
if sys.version_info>(2,4): # 2.3 barfs internally
v=self.db.wal_checkpoint(mode=apsw.SQLITE_CHECKPOINT_PASSIVE)
self.assertTrue(isinstance(v, tuple) and len(v)==2 and isinstance(v[0], int) and isinstance(v[1], int))
self.assertRaises(apsw.MisuseError, self.db.wal_checkpoint, mode=876786)
self.assertRaises(TypeError, self.db.setwalhook)
self.assertRaises(TypeError, self.db.setwalhook, 12)
self.db.setwalhook(None)
# check we can set wal mode
self.assertEqual("wal", self.db.cursor().execute("pragma journal_mode=wal").fetchall()[0][0])
# errors in wal callback
def zerodiv(*args): 1/0
self.db.setwalhook(zerodiv)
self.assertRaises(ZeroDivisionError, self.db.cursor().execute, "create table one(x)")
# the error happens after the wal commit so the table should exist
self.assertTableExists("one")
def badreturn(*args): return "three"
self.db.setwalhook(badreturn)
self.assertRaises(TypeError, self.db.cursor().execute, "create table two(x)")
self.assertTableExists("two")
expectdbname=""
def walhook(conn, dbname, pages):
self.assertTrue(conn is self.db)
self.assertTrue(pages>0)
self.assertEqual(dbname, expectdbname)
return apsw.SQLITE_OK
expectdbname="main"
self.db.setwalhook(walhook)
self.db.cursor().execute("create table three(x)")
self.db.cursor().execute("attach '%stestdb2?psow=0' as fred" % ("file:"+TESTFILEPREFIX,) )
self.assertEqual("wal", self.db.cursor().execute("pragma fred.journal_mode=wal").fetchall()[0][0])
expectdbname="fred"
self.db.cursor().execute("create table fred.three(x)")
def testAuthorizer(self):
"Verify the authorizer works"
retval=apsw.SQLITE_DENY
def authorizer(operation, paramone, paramtwo, databasename, triggerorview):
# we fail creates of tables starting with "private"
if operation==apsw.SQLITE_CREATE_TABLE and paramone.startswith("private"):
return retval
return apsw.SQLITE_OK
c=self.db.cursor()
# this should succeed
c.execute("create table privateone(x)")
# this should fail
self.assertRaises(TypeError, self.db.setauthorizer, 12) # must be callable
self.db.setauthorizer(authorizer)
for val in apsw.SQLITE_DENY, long(apsw.SQLITE_DENY), 0x800276889000212112:
retval=val
if val<100:
self.assertRaises(apsw.AuthError, c.execute, "create table privatetwo(x)")
else:
self.assertRaises(OverflowError, c.execute, "create table privatetwo(x)")
# this should succeed
self.db.setauthorizer(None)
c.execute("create table privatethree(x)")
self.assertTableExists("privateone")
self.assertTableNotExists("privatetwo")
self.assertTableExists("privatethree")
# error in callback
def authorizer(operation, *args):
if operation==apsw.SQLITE_CREATE_TABLE:
1/0
return apsw.SQLITE_OK
self.db.setauthorizer(authorizer)
self.assertRaises(ZeroDivisionError, c.execute, "create table shouldfail(x)")
self.assertTableNotExists("shouldfail")
# bad return type in callback
def authorizer(operation, *args):
return "a silly string"
self.db.setauthorizer(authorizer)
self.assertRaises(TypeError, c.execute, "create table shouldfail(x); select 3+5")
self.db.setauthorizer(None) # otherwise next line will fail!
self.assertTableNotExists("shouldfail")
# back to normal
self.db.setauthorizer(None)
c.execute("create table shouldsucceed(x)")
self.assertTableExists("shouldsucceed")
def testExecTracing(self):
"Verify tracing of executed statements and bindings"
self.db.setexectrace(None)
c=self.db.cursor()
cmds=[] # this is maniulated in tracefunc
def tracefunc(cursor, cmd, bindings):
cmds.append( (cmd, bindings) )
return True
c.execute("create table one(x,y,z)")
self.assertEqual(len(cmds),0)
self.assertRaises(TypeError, c.setexectrace, 12) # must be callable
self.assertRaises(TypeError, self.db.setexectrace, 12) # must be callable
c.setexectrace(tracefunc)
statements=[
("insert into one values(?,?,?)", (1,2,3)),
("insert into one values(:a,$b,$c)", {'a': 1, 'b': "string", 'c': None}),
]
for cmd,values in statements:
c.execute(cmd, values)
self.assertEqual(cmds, statements)
self.assertTrue(c.getexectrace() is tracefunc)
c.setexectrace(None)
self.assertTrue(c.getexectrace() is None)
c.execute("create table bar(x,y,z)")
# cmds should be unchanged
self.assertEqual(cmds, statements)
# tracefunc can abort execution
count=next(c.execute("select count(*) from one"))[0]
def tracefunc(cursor, cmd, bindings):
return False # abort
c.setexectrace(tracefunc)
self.assertRaises(apsw.ExecTraceAbort, c.execute, "insert into one values(1,2,3)")
# table should not have been modified
c.setexectrace(None)
self.assertEqual(count, next(c.execute("select count(*) from one"))[0])
# error in tracefunc
def tracefunc(cursor, cmd, bindings):
1/0
c.setexectrace(tracefunc)
self.assertRaises(ZeroDivisionError, c.execute, "insert into one values(1,2,3)")
c.setexectrace(None)
self.assertEqual(count, next(c.execute("select count(*) from one"))[0])
# test across executemany and multiple statments
counter=[0]
def tracefunc(cursor, cmd, bindings):
counter[0]=counter[0]+1
return True
c.setexectrace(tracefunc)
c.execute("create table two(x);insert into two values(1); insert into two values(2); insert into two values(?); insert into two values(?)",
(3, 4))
self.assertEqual(counter[0], 5)
counter[0]=0
c.executemany("insert into two values(?); insert into two values(?)", [[n,n+1] for n in range(5)])
self.assertEqual(counter[0], 10)
# error in func but only after a while
c.execute("delete from two")
counter[0]=0
def tracefunc(cursor, cmd, bindings):
counter[0]=counter[0]+1
if counter[0]>3:
1/0
return True
c.setexectrace(tracefunc)
self.assertRaises(ZeroDivisionError, c.execute,