forked from nawalgupta/PythonBuddy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_sqlite3.py
More file actions
1396 lines (1189 loc) · 48.5 KB
/
Copy path_sqlite3.py
File metadata and controls
1396 lines (1189 loc) · 48.5 KB
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
#-*- coding: utf-8 -*-
# pysqlite2/dbapi.py: pysqlite DB-API module
#
# Copyright (C) 2007-2008 Gerhard Häring <gh@ghaering.de>
#
# This file is part of pysqlite.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
# Note: This software has been modified for use in PyPy.
from collections import OrderedDict
from functools import wraps
import datetime
import string
import sys
import weakref
from threading import _get_ident as _thread_get_ident
try:
from __pypy__ import newlist_hint
except ImportError:
assert '__pypy__' not in sys.builtin_module_names
newlist_hint = lambda sizehint: []
if sys.version_info[0] >= 3:
StandardError = Exception
cmp = lambda x, y: (x > y) - (x < y)
long = int
xrange = range
basestring = unicode = str
buffer = memoryview
_BLOB_TYPE = bytes
else:
_BLOB_TYPE = buffer
from _sqlite3_cffi import ffi as _ffi, lib as _lib
exported_sqlite_symbols = [
'SQLITE_ALTER_TABLE',
'SQLITE_ANALYZE',
'SQLITE_ATTACH',
'SQLITE_CREATE_INDEX',
'SQLITE_CREATE_TABLE',
'SQLITE_CREATE_TEMP_INDEX',
'SQLITE_CREATE_TEMP_TABLE',
'SQLITE_CREATE_TEMP_TRIGGER',
'SQLITE_CREATE_TEMP_VIEW',
'SQLITE_CREATE_TRIGGER',
'SQLITE_CREATE_VIEW',
'SQLITE_DELETE',
'SQLITE_DENY',
'SQLITE_DETACH',
'SQLITE_DROP_INDEX',
'SQLITE_DROP_TABLE',
'SQLITE_DROP_TEMP_INDEX',
'SQLITE_DROP_TEMP_TABLE',
'SQLITE_DROP_TEMP_TRIGGER',
'SQLITE_DROP_TEMP_VIEW',
'SQLITE_DROP_TRIGGER',
'SQLITE_DROP_VIEW',
'SQLITE_IGNORE',
'SQLITE_INSERT',
'SQLITE_OK',
'SQLITE_PRAGMA',
'SQLITE_READ',
'SQLITE_REINDEX',
'SQLITE_SELECT',
'SQLITE_TRANSACTION',
'SQLITE_UPDATE',
]
for symbol in exported_sqlite_symbols:
globals()[symbol] = getattr(_lib, symbol)
_SQLITE_TRANSIENT = _lib.SQLITE_TRANSIENT
# pysqlite version information
version = "2.6.0"
# pysqlite constants
PARSE_COLNAMES = 1
PARSE_DECLTYPES = 2
# SQLite version information
sqlite_version = str(_ffi.string(_lib.sqlite3_libversion()).decode('ascii'))
_STMT_TYPE_UPDATE = 0
_STMT_TYPE_DELETE = 1
_STMT_TYPE_INSERT = 2
_STMT_TYPE_REPLACE = 3
_STMT_TYPE_OTHER = 4
_STMT_TYPE_SELECT = 5
_STMT_TYPE_INVALID = 6
class Error(StandardError):
pass
class Warning(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class InternalError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class DataError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
def connect(database, timeout=5.0, detect_types=0, isolation_level="",
check_same_thread=True, factory=None, cached_statements=100):
factory = Connection if not factory else factory
return factory(database, timeout, detect_types, isolation_level,
check_same_thread, factory, cached_statements)
def _unicode_text_factory(x):
return unicode(x, 'utf-8')
if sys.version_info[0] < 3:
def OptimizedUnicode(s):
try:
val = unicode(s, "ascii").encode("ascii")
except UnicodeDecodeError:
val = unicode(s, "utf-8")
return val
else:
OptimizedUnicode = _unicode_text_factory
class _StatementCache(object):
def __init__(self, connection, maxcount):
self.connection = connection
self.maxcount = maxcount
self.cache = OrderedDict()
def get(self, sql):
try:
stat = self.cache[sql]
except KeyError:
stat = Statement(self.connection, sql)
self.cache[sql] = stat
if len(self.cache) > self.maxcount:
self.cache.popitem(0)
else:
if stat._in_use:
stat = Statement(self.connection, sql)
self.cache[sql] = stat
return stat
class Connection(object):
__initialized = False
_db = None
def __init__(self, database, timeout=5.0, detect_types=0, isolation_level="",
check_same_thread=True, factory=None, cached_statements=100):
self.__initialized = True
db_star = _ffi.new('sqlite3 **')
if isinstance(database, unicode):
database = database.encode('utf-8')
if _lib.sqlite3_open(database, db_star) != _lib.SQLITE_OK:
raise OperationalError("Could not open database")
self._db = db_star[0]
if timeout is not None:
timeout = int(timeout * 1000) # pysqlite2 uses timeout in seconds
_lib.sqlite3_busy_timeout(self._db, timeout)
self.row_factory = None
self.text_factory = _unicode_text_factory
self._detect_types = detect_types
self._in_transaction = False
self.isolation_level = isolation_level
self.__cursors = []
self.__cursors_counter = 0
self.__statements = []
self.__statements_counter = 0
self.__rawstatements = set()
self._statement_cache = _StatementCache(self, cached_statements)
self.__statements_already_committed = []
self.__func_cache = {}
self.__aggregates = {}
self.__aggregate_instances = {}
self.__collations = {}
if check_same_thread:
self.__thread_ident = _thread_get_ident()
self.Error = Error
self.Warning = Warning
self.InterfaceError = InterfaceError
self.DatabaseError = DatabaseError
self.InternalError = InternalError
self.OperationalError = OperationalError
self.ProgrammingError = ProgrammingError
self.IntegrityError = IntegrityError
self.DataError = DataError
self.NotSupportedError = NotSupportedError
def __del__(self):
if self._db:
_lib.sqlite3_close(self._db)
def close(self):
self._check_thread()
self.__do_all_statements(Statement._finalize, True)
# depending on when this close() is called, the statements' weakrefs
# may be already dead, even though Statement.__del__() was not called
# yet. In this case, self.__rawstatements is not empty.
if self.__rawstatements is not None:
for stmt in list(self.__rawstatements):
self._finalize_raw_statement(stmt)
self.__rawstatements = None
if self._db:
ret = _lib.sqlite3_close(self._db)
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
self._db = None
def _check_closed(self):
if not self.__initialized:
raise ProgrammingError("Base Connection.__init__ not called.")
if not self._db:
raise ProgrammingError("Cannot operate on a closed database.")
def _check_closed_wrap(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
self._check_closed()
return func(self, *args, **kwargs)
return wrapper
def _check_thread(self):
try:
if self.__thread_ident == _thread_get_ident():
return
except AttributeError:
pass
else:
raise ProgrammingError(
"SQLite objects created in a thread can only be used in that "
"same thread. The object was created in thread id %d and this "
"is thread id %d" % (self.__thread_ident, _thread_get_ident()))
def _check_thread_wrap(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
self._check_thread()
return func(self, *args, **kwargs)
return wrapper
def _get_exception(self, error_code=None):
if error_code is None:
error_code = _lib.sqlite3_errcode(self._db)
error_message = _ffi.string(_lib.sqlite3_errmsg(self._db)).decode('utf-8')
if error_code == _lib.SQLITE_OK:
raise ValueError("error signalled but got SQLITE_OK")
elif error_code in (_lib.SQLITE_INTERNAL, _lib.SQLITE_NOTFOUND):
exc = InternalError
elif error_code == _lib.SQLITE_NOMEM:
exc = MemoryError
elif error_code in (
_lib.SQLITE_ERROR, _lib.SQLITE_PERM, _lib.SQLITE_ABORT,
_lib.SQLITE_BUSY, _lib.SQLITE_LOCKED, _lib.SQLITE_READONLY,
_lib.SQLITE_INTERRUPT, _lib.SQLITE_IOERR, _lib.SQLITE_FULL,
_lib.SQLITE_CANTOPEN, _lib.SQLITE_PROTOCOL, _lib.SQLITE_EMPTY,
_lib.SQLITE_SCHEMA):
exc = OperationalError
elif error_code == _lib.SQLITE_CORRUPT:
exc = DatabaseError
elif error_code == _lib.SQLITE_TOOBIG:
exc = DataError
elif error_code in (_lib.SQLITE_CONSTRAINT, _lib.SQLITE_MISMATCH):
exc = IntegrityError
elif error_code == _lib.SQLITE_MISUSE:
exc = ProgrammingError
else:
exc = DatabaseError
exc = exc(error_message)
exc.error_code = error_code
return exc
def _remember_cursor(self, cursor):
self.__cursors.append(weakref.ref(cursor))
self.__cursors_counter += 1
if self.__cursors_counter < 200:
return
self.__cursors_counter = 0
self.__cursors = [r for r in self.__cursors if r() is not None]
def _remember_statement(self, statement):
self.__rawstatements.add(statement._statement)
self.__statements.append(weakref.ref(statement))
self.__statements_counter += 1
if self.__statements_counter < 200:
return
self.__statements_counter = 0
self.__statements = [r for r in self.__statements if r() is not None]
def _finalize_raw_statement(self, _statement):
if self.__rawstatements is not None:
try:
self.__rawstatements.remove(_statement)
except KeyError:
return # rare case: already finalized, see issue #2097
_lib.sqlite3_finalize(_statement)
def __do_all_statements(self, action, reset_cursors):
for weakref in self.__statements:
statement = weakref()
if statement is not None:
action(statement)
if reset_cursors:
for weakref in self.__cursors:
cursor = weakref()
if cursor is not None:
cursor._reset = True
def _reset_already_committed_statements(self):
lst = self.__statements_already_committed
self.__statements_already_committed = []
for weakref in lst:
statement = weakref()
if statement is not None:
statement._reset()
@_check_thread_wrap
@_check_closed_wrap
def __call__(self, sql):
return self._statement_cache.get(sql)
def _default_cursor_factory(self):
return Cursor(self)
def cursor(self, factory=_default_cursor_factory):
self._check_thread()
self._check_closed()
cur = factory(self)
if not issubclass(type(cur), Cursor):
raise TypeError("factory must return a cursor, not %s"
% (type(cur).__name__,))
if self.row_factory is not None:
cur.row_factory = self.row_factory
return cur
def execute(self, *args):
cur = self.cursor()
return cur.execute(*args)
def executemany(self, *args):
cur = self.cursor()
return cur.executemany(*args)
def executescript(self, *args):
cur = self.cursor()
return cur.executescript(*args)
def iterdump(self):
from sqlite3.dump import _iterdump
return _iterdump(self)
def _begin(self):
statement_star = _ffi.new('sqlite3_stmt **')
ret = _lib.sqlite3_prepare_v2(self._db, self.__begin_statement, -1,
statement_star, _ffi.NULL)
try:
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
ret = _lib.sqlite3_step(statement_star[0])
if ret != _lib.SQLITE_DONE:
raise self._get_exception(ret)
self._in_transaction = True
finally:
_lib.sqlite3_finalize(statement_star[0])
def commit(self):
self._check_thread()
self._check_closed()
if not self._in_transaction:
return
# PyPy fix for non-refcounting semantics: since 2.7.13 (and in
# <= 2.6.x), the statements are not automatically reset upon
# commit. However, if this is followed by some specific SQL
# operations like "drop table", these open statements come in
# the way and cause the "drop table" to fail. On CPython the
# problem is much less important because typically all the old
# statements are freed already by reference counting. So here,
# we copy all the still-alive statements to another list which
# is usually ignored, except if we get SQLITE_LOCKED
# afterwards---at which point we reset all statements in this
# list.
self.__statements_already_committed = self.__statements[:]
statement_star = _ffi.new('sqlite3_stmt **')
ret = _lib.sqlite3_prepare_v2(self._db, b"COMMIT", -1,
statement_star, _ffi.NULL)
try:
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
ret = _lib.sqlite3_step(statement_star[0])
if ret != _lib.SQLITE_DONE:
raise self._get_exception(ret)
self._in_transaction = False
finally:
_lib.sqlite3_finalize(statement_star[0])
def rollback(self):
self._check_thread()
self._check_closed()
if not self._in_transaction:
return
self.__do_all_statements(Statement._reset, True)
statement_star = _ffi.new('sqlite3_stmt **')
ret = _lib.sqlite3_prepare_v2(self._db, b"ROLLBACK", -1,
statement_star, _ffi.NULL)
try:
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
ret = _lib.sqlite3_step(statement_star[0])
if ret != _lib.SQLITE_DONE:
raise self._get_exception(ret)
self._in_transaction = False
finally:
_lib.sqlite3_finalize(statement_star[0])
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type is None and exc_value is None and exc_tb is None:
self.commit()
else:
self.rollback()
@_check_thread_wrap
@_check_closed_wrap
def create_function(self, name, num_args, callback):
try:
closure = self.__func_cache[callback]
except KeyError:
@_ffi.callback("void(sqlite3_context*, int, sqlite3_value**)")
def closure(context, nargs, c_params):
_function_callback(callback, context, nargs, c_params)
self.__func_cache[callback] = closure
if isinstance(name, unicode):
name = name.encode('utf-8')
ret = _lib.sqlite3_create_function(self._db, name, num_args,
_lib.SQLITE_UTF8, _ffi.NULL,
closure, _ffi.NULL, _ffi.NULL)
if ret != _lib.SQLITE_OK:
raise self.OperationalError("Error creating function")
@_check_thread_wrap
@_check_closed_wrap
def create_aggregate(self, name, num_args, cls):
try:
step_callback, final_callback = self.__aggregates[cls]
except KeyError:
@_ffi.callback("void(sqlite3_context*, int, sqlite3_value**)")
def step_callback(context, argc, c_params):
res = _lib.sqlite3_aggregate_context(context,
_ffi.sizeof("size_t"))
aggregate_ptr = _ffi.cast("size_t[1]", res)
if not aggregate_ptr[0]:
try:
aggregate = cls()
except Exception:
msg = (b"user-defined aggregate's '__init__' "
b"method raised error")
_lib.sqlite3_result_error(context, msg, len(msg))
return
aggregate_id = id(aggregate)
self.__aggregate_instances[aggregate_id] = aggregate
aggregate_ptr[0] = aggregate_id
else:
aggregate = self.__aggregate_instances[aggregate_ptr[0]]
params = _convert_params(context, argc, c_params)
try:
aggregate.step(*params)
except Exception:
msg = (b"user-defined aggregate's 'step' "
b"method raised error")
_lib.sqlite3_result_error(context, msg, len(msg))
@_ffi.callback("void(sqlite3_context*)")
def final_callback(context):
res = _lib.sqlite3_aggregate_context(context,
_ffi.sizeof("size_t"))
aggregate_ptr = _ffi.cast("size_t[1]", res)
if aggregate_ptr[0]:
aggregate = self.__aggregate_instances[aggregate_ptr[0]]
try:
val = aggregate.finalize()
except Exception:
msg = (b"user-defined aggregate's 'finalize' "
b"method raised error")
_lib.sqlite3_result_error(context, msg, len(msg))
else:
_convert_result(context, val)
finally:
del self.__aggregate_instances[aggregate_ptr[0]]
self.__aggregates[cls] = (step_callback, final_callback)
if isinstance(name, unicode):
name = name.encode('utf-8')
ret = _lib.sqlite3_create_function(self._db, name, num_args,
_lib.SQLITE_UTF8, _ffi.NULL,
_ffi.NULL,
step_callback,
final_callback)
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
@_check_thread_wrap
@_check_closed_wrap
def create_collation(self, name, callback):
name = str.upper(name)
if not all(c in string.ascii_uppercase + string.digits + '_' for c in name):
raise ProgrammingError("invalid character in collation name")
if callback is None:
del self.__collations[name]
collation_callback = _ffi.NULL
else:
if not callable(callback):
raise TypeError("parameter must be callable")
@_ffi.callback("int(void*, int, const void*, int, const void*)")
def collation_callback(context, len1, str1, len2, str2):
text1 = _ffi.buffer(str1, len1)[:]
text2 = _ffi.buffer(str2, len2)[:]
try:
ret = callback(text1, text2)
assert isinstance(ret, (int, long))
return cmp(ret, 0)
except Exception:
return 0
self.__collations[name] = collation_callback
if isinstance(name, unicode):
name = name.encode('utf-8')
ret = _lib.sqlite3_create_collation(self._db, name,
_lib.SQLITE_UTF8,
_ffi.NULL,
collation_callback)
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
@_check_thread_wrap
@_check_closed_wrap
def set_authorizer(self, callback):
try:
authorizer = self.__func_cache[callback]
except KeyError:
@_ffi.callback("int(void*, int, const char*, const char*, "
"const char*, const char*)")
def authorizer(userdata, action, arg1, arg2, dbname, source):
try:
ret = callback(action, arg1, arg2, dbname, source)
assert isinstance(ret, int)
# try to detect cases in which cffi would swallow
# OverflowError when casting the return value
assert int(_ffi.cast('int', ret)) == ret
return ret
except Exception:
return _lib.SQLITE_DENY
self.__func_cache[callback] = authorizer
ret = _lib.sqlite3_set_authorizer(self._db, authorizer, _ffi.NULL)
if ret != _lib.SQLITE_OK:
raise self._get_exception(ret)
@_check_thread_wrap
@_check_closed_wrap
def set_progress_handler(self, callable, nsteps):
if callable is None:
progress_handler = _ffi.NULL
else:
try:
progress_handler = self.__func_cache[callable]
except KeyError:
@_ffi.callback("int(void*)")
def progress_handler(userdata):
try:
return bool(callable())
except Exception:
# abort query if error occurred
return 1
self.__func_cache[callable] = progress_handler
_lib.sqlite3_progress_handler(self._db, nsteps, progress_handler,
_ffi.NULL)
if sys.version_info[0] >= 3:
def __get_in_transaction(self):
return self._in_transaction
in_transaction = property(__get_in_transaction)
def __get_total_changes(self):
self._check_closed()
return _lib.sqlite3_total_changes(self._db)
total_changes = property(__get_total_changes)
def __get_isolation_level(self):
return self._isolation_level
def __set_isolation_level(self, val):
if val is None:
self.commit()
else:
self.__begin_statement = str("BEGIN " + val).encode('utf-8')
self._isolation_level = val
isolation_level = property(__get_isolation_level, __set_isolation_level)
if hasattr(_lib, 'sqlite3_enable_load_extension'):
@_check_thread_wrap
@_check_closed_wrap
def enable_load_extension(self, enabled):
rc = _lib.sqlite3_enable_load_extension(self._db, int(enabled))
if rc != _lib.SQLITE_OK:
raise OperationalError("Error enabling load extension")
class Cursor(object):
__initialized = False
__statement = None
def __init__(self, con):
if not isinstance(con, Connection):
raise TypeError
self.__connection = con
self.arraysize = 1
self.row_factory = None
self._reset = False
self.__locked = False
self.__closed = False
self.__lastrowid = None
self.__rowcount = -1
con._check_thread()
con._remember_cursor(self)
self.__initialized = True
def close(self):
self.__connection._check_thread()
self.__connection._check_closed()
if self.__statement:
self.__statement._reset()
self.__statement = None
self.__closed = True
def __check_cursor(self):
if not self.__initialized:
raise ProgrammingError("Base Cursor.__init__ not called.")
if self.__closed:
raise ProgrammingError("Cannot operate on a closed cursor.")
if self.__locked:
raise ProgrammingError("Recursive use of cursors not allowed.")
self.__connection._check_thread()
self.__connection._check_closed()
def __check_cursor_wrap(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
self.__check_cursor()
return func(self, *args, **kwargs)
return wrapper
def __check_reset(self):
if self._reset:
raise InterfaceError(
"Cursor needed to be reset because of commit/rollback "
"and can no longer be fetched from.")
def __build_row_cast_map(self):
if not self.__connection._detect_types:
return
self.__row_cast_map = []
for i in xrange(_lib.sqlite3_column_count(self.__statement._statement)):
converter = None
if self.__connection._detect_types & PARSE_COLNAMES:
colname = _lib.sqlite3_column_name(self.__statement._statement, i)
if colname:
colname = _ffi.string(colname).decode('utf-8')
type_start = -1
key = None
for pos in range(len(colname)):
if colname[pos] == '[':
type_start = pos + 1
elif colname[pos] == ']' and type_start != -1:
key = colname[type_start:pos]
converter = converters[key.upper()]
if converter is None and self.__connection._detect_types & PARSE_DECLTYPES:
decltype = _lib.sqlite3_column_decltype(self.__statement._statement, i)
if decltype:
decltype = _ffi.string(decltype).decode('utf-8')
# if multiple words, use first, eg.
# "INTEGER NOT NULL" => "INTEGER"
decltype = decltype.split()[0]
if '(' in decltype:
decltype = decltype[:decltype.index('(')]
converter = converters.get(decltype.upper(), None)
self.__row_cast_map.append(converter)
def __fetch_one_row(self):
num_cols = _lib.sqlite3_data_count(self.__statement._statement)
row = newlist_hint(num_cols)
for i in xrange(num_cols):
if self.__connection._detect_types:
converter = self.__row_cast_map[i]
else:
converter = None
if converter is not None:
blob = _lib.sqlite3_column_blob(self.__statement._statement, i)
if not blob:
val = None
else:
blob_len = _lib.sqlite3_column_bytes(self.__statement._statement, i)
val = _ffi.buffer(blob, blob_len)[:]
val = converter(val)
else:
typ = _lib.sqlite3_column_type(self.__statement._statement, i)
if typ == _lib.SQLITE_NULL:
val = None
elif typ == _lib.SQLITE_INTEGER:
val = _lib.sqlite3_column_int64(self.__statement._statement, i)
val = int(val)
elif typ == _lib.SQLITE_FLOAT:
val = _lib.sqlite3_column_double(self.__statement._statement, i)
elif typ == _lib.SQLITE_TEXT:
text = _lib.sqlite3_column_text(self.__statement._statement, i)
text_len = _lib.sqlite3_column_bytes(self.__statement._statement, i)
val = _ffi.buffer(text, text_len)[:]
val = self.__connection.text_factory(val)
elif typ == _lib.SQLITE_BLOB:
blob = _lib.sqlite3_column_blob(self.__statement._statement, i)
blob_len = _lib.sqlite3_column_bytes(self.__statement._statement, i)
val = _BLOB_TYPE(_ffi.buffer(blob, blob_len)[:])
row.append(val)
return tuple(row)
def __execute(self, multiple, sql, many_params):
self.__locked = True
self._reset = False
try:
del self.__next_row
except AttributeError:
pass
try:
if not isinstance(sql, basestring):
raise ValueError("operation parameter must be str or unicode")
try:
del self.__description
except AttributeError:
pass
self.__rowcount = -1
self.__statement = self.__connection._statement_cache.get(sql)
if self.__connection._isolation_level is not None:
if self.__statement._type in (
_STMT_TYPE_UPDATE,
_STMT_TYPE_DELETE,
_STMT_TYPE_INSERT,
_STMT_TYPE_REPLACE
):
if not self.__connection._in_transaction:
self.__connection._begin()
elif self.__statement._type == _STMT_TYPE_OTHER:
if self.__connection._in_transaction:
self.__connection.commit()
elif self.__statement._type == _STMT_TYPE_SELECT:
if multiple:
raise ProgrammingError("You cannot execute SELECT "
"statements in executemany().")
for params in many_params:
self.__statement._set_params(params)
# Actually execute the SQL statement
ret = _lib.sqlite3_step(self.__statement._statement)
# PyPy: if we get SQLITE_LOCKED, it's probably because
# one of the cursors created previously is still alive
# and not reset and the operation we're trying to do
# makes Sqlite unhappy about that. In that case, we
# automatically reset all old cursors and try again.
if ret == _lib.SQLITE_LOCKED:
self.__connection._reset_already_committed_statements()
ret = _lib.sqlite3_step(self.__statement._statement)
if ret == _lib.SQLITE_ROW:
if multiple:
raise ProgrammingError("executemany() can only execute DML statements.")
self.__build_row_cast_map()
self.__next_row = self.__fetch_one_row()
elif ret == _lib.SQLITE_DONE:
if not multiple:
self.__statement._reset()
else:
self.__statement._reset()
raise self.__connection._get_exception(ret)
if self.__statement._type in (
_STMT_TYPE_UPDATE,
_STMT_TYPE_DELETE,
_STMT_TYPE_INSERT,
_STMT_TYPE_REPLACE
):
if self.__rowcount == -1:
self.__rowcount = 0
self.__rowcount += _lib.sqlite3_changes(self.__connection._db)
if not multiple and self.__statement._type == _STMT_TYPE_INSERT:
self.__lastrowid = _lib.sqlite3_last_insert_rowid(self.__connection._db)
else:
self.__lastrowid = None
if multiple:
self.__statement._reset()
finally:
self.__connection._in_transaction = \
not _lib.sqlite3_get_autocommit(self.__connection._db)
self.__locked = False
return self
@__check_cursor_wrap
def execute(self, sql, params=[]):
return self.__execute(False, sql, [params])
@__check_cursor_wrap
def executemany(self, sql, many_params):
return self.__execute(True, sql, many_params)
def executescript(self, sql):
self.__check_cursor()
self._reset = False
if isinstance(sql, unicode):
sql = sql.encode('utf-8')
elif not isinstance(sql, str):
raise ValueError("script argument must be unicode or string.")
statement_star = _ffi.new('sqlite3_stmt **')
next_char = _ffi.new('char **')
self.__connection.commit()
while True:
c_sql = _ffi.new("char[]", sql)
rc = _lib.sqlite3_prepare(self.__connection._db, c_sql, -1,
statement_star, next_char)
if rc != _lib.SQLITE_OK:
raise self.__connection._get_exception(rc)
rc = _lib.SQLITE_ROW
while rc == _lib.SQLITE_ROW:
if not statement_star[0]:
rc = _lib.SQLITE_OK
else:
rc = _lib.sqlite3_step(statement_star[0])
if rc != _lib.SQLITE_DONE:
_lib.sqlite3_finalize(statement_star[0])
if rc == _lib.SQLITE_OK:
break
else:
raise self.__connection._get_exception(rc)
rc = _lib.sqlite3_finalize(statement_star[0])
if rc != _lib.SQLITE_OK:
raise self.__connection._get_exception(rc)
sql = _ffi.string(next_char[0])
if not sql:
break
return self
def __iter__(self):
return self
def __next__(self):
self.__check_cursor()
self.__check_reset()
if not self.__statement:
raise StopIteration
try:
next_row = self.__next_row
except AttributeError:
raise StopIteration
del self.__next_row
if self.row_factory is not None:
next_row = self.row_factory(self, next_row)
ret = _lib.sqlite3_step(self.__statement._statement)
if ret == _lib.SQLITE_ROW:
self.__next_row = self.__fetch_one_row()
else:
self.__statement._reset()
if ret != _lib.SQLITE_DONE:
raise self.__connection._get_exception(ret)
return next_row
if sys.version_info[0] < 3:
next = __next__
del __next__
def fetchone(self):
return next(self, None)
def fetchmany(self, size=None):
if size is None:
size = self.arraysize
lst = []
for row in self:
lst.append(row)
if len(lst) == size:
break
return lst
def fetchall(self):
return list(self)
def __get_connection(self):
return self.__connection
connection = property(__get_connection)
def __get_rowcount(self):
return self.__rowcount
rowcount = property(__get_rowcount)
def __get_description(self):
try:
return self.__description
except AttributeError:
if self.__statement:
self.__description = self.__statement._get_description()
return self.__description
description = property(__get_description)