| 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 |
import datetime |
| 27 |
import os |
| 28 |
import string |
| 29 |
import struct |
| 30 |
import sys |
| 31 |
import threading |
| 32 |
import traceback |
| 33 |
import types |
| 34 |
import weakref |
| 35 |
import operator |
| 36 |
from collections import OrderedDict |
| 37 |
from functools import wraps |
| 38 |
|
| 39 |
try: |
| 40 |
from __pypy__ import newlist_hint, add_memory_pressure |
| 41 |
except ImportError: |
| 42 |
assert '__pypy__' not in sys.builtin_module_names |
| 43 |
newlist_hint = lambda sizehint: [] |
| 44 |
add_memory_pressure = lambda size: None |
| 45 |
|
| 46 |
if sys.version_info[0] >= 3: |
| 47 |
StandardError = Exception |
| 48 |
cmp = lambda x, y: (x > y) - (x < y) |
| 49 |
long = int |
| 50 |
xrange = range |
| 51 |
basestring = unicode = str |
| 52 |
buffer = memoryview |
| 53 |
_BLOB_TYPE = bytes |
| 54 |
else: |
| 55 |
_BLOB_TYPE = buffer |
| 56 |
|
| 57 |
from _sqlite3_cffi import ffi as _ffi, lib as _lib |
| 58 |
|
| 59 |
_UNSUPPORTED_TYPE = object() |
| 60 |
|
| 61 |
exported_sqlite_symbols = [ |
| 62 |
'SQLITE_ABORT', |
| 63 |
'SQLITE_ABORT_ROLLBACK', |
| 64 |
'SQLITE_ALTER_TABLE', |
| 65 |
'SQLITE_ANALYZE', |
| 66 |
'SQLITE_ATTACH', |
| 67 |
'SQLITE_AUTH', |
| 68 |
'SQLITE_AUTH_USER', |
| 69 |
'SQLITE_BUSY', |
| 70 |
'SQLITE_BUSY_RECOVERY', |
| 71 |
'SQLITE_BUSY_SNAPSHOT', |
| 72 |
'SQLITE_BUSY_TIMEOUT', |
| 73 |
'SQLITE_CANTOPEN', |
| 74 |
'SQLITE_CANTOPEN_CONVPATH', |
| 75 |
'SQLITE_CANTOPEN_DIRTYWAL', |
| 76 |
'SQLITE_CANTOPEN_FULLPATH', |
| 77 |
'SQLITE_CANTOPEN_ISDIR', |
| 78 |
'SQLITE_CANTOPEN_NOTEMPDIR', |
| 79 |
'SQLITE_CANTOPEN_SYMLINK', |
| 80 |
'SQLITE_CONSTRAINT', |
| 81 |
'SQLITE_CONSTRAINT_CHECK', |
| 82 |
'SQLITE_CONSTRAINT_COMMITHOOK', |
| 83 |
'SQLITE_CONSTRAINT_FOREIGNKEY', |
| 84 |
'SQLITE_CONSTRAINT_FUNCTION', |
| 85 |
'SQLITE_CONSTRAINT_NOTNULL', |
| 86 |
'SQLITE_CONSTRAINT_PINNED', |
| 87 |
'SQLITE_CONSTRAINT_PRIMARYKEY', |
| 88 |
'SQLITE_CONSTRAINT_ROWID', |
| 89 |
'SQLITE_CONSTRAINT_TRIGGER', |
| 90 |
'SQLITE_CONSTRAINT_UNIQUE', |
| 91 |
'SQLITE_CONSTRAINT_VTAB', |
| 92 |
'SQLITE_CORRUPT', |
| 93 |
'SQLITE_CORRUPT_INDEX', |
| 94 |
'SQLITE_CORRUPT_SEQUENCE', |
| 95 |
'SQLITE_CORRUPT_VTAB', |
| 96 |
'SQLITE_CREATE_INDEX', |
| 97 |
'SQLITE_CREATE_TABLE', |
| 98 |
'SQLITE_CREATE_TEMP_INDEX', |
| 99 |
'SQLITE_CREATE_TEMP_TABLE', |
| 100 |
'SQLITE_CREATE_TEMP_TRIGGER', |
| 101 |
'SQLITE_CREATE_TEMP_VIEW', |
| 102 |
'SQLITE_CREATE_TRIGGER', |
| 103 |
'SQLITE_CREATE_VIEW', |
| 104 |
'SQLITE_CREATE_VTABLE', |
| 105 |
'SQLITE_DELETE', |
| 106 |
'SQLITE_DENY', |
| 107 |
'SQLITE_DETACH', |
| 108 |
'SQLITE_DONE', |
| 109 |
'SQLITE_DROP_INDEX', |
| 110 |
'SQLITE_DROP_TABLE', |
| 111 |
'SQLITE_DROP_TEMP_INDEX', |
| 112 |
'SQLITE_DROP_TEMP_TABLE', |
| 113 |
'SQLITE_DROP_TEMP_TRIGGER', |
| 114 |
'SQLITE_DROP_TEMP_VIEW', |
| 115 |
'SQLITE_DROP_TRIGGER', |
| 116 |
'SQLITE_DROP_VIEW', |
| 117 |
'SQLITE_DROP_VTABLE', |
| 118 |
'SQLITE_EMPTY', |
| 119 |
'SQLITE_ERROR', |
| 120 |
'SQLITE_ERROR_MISSING_COLLSEQ', |
| 121 |
'SQLITE_ERROR_RETRY', |
| 122 |
'SQLITE_ERROR_SNAPSHOT', |
| 123 |
'SQLITE_FORMAT', |
| 124 |
'SQLITE_FULL', |
| 125 |
'SQLITE_FUNCTION', |
| 126 |
'SQLITE_IGNORE', |
| 127 |
'SQLITE_INSERT', |
| 128 |
'SQLITE_INTERNAL', |
| 129 |
'SQLITE_INTERRUPT', |
| 130 |
'SQLITE_IOERR', |
| 131 |
'SQLITE_IOERR_ACCESS', |
| 132 |
'SQLITE_IOERR_AUTH', |
| 133 |
'SQLITE_IOERR_BEGIN_ATOMIC', |
| 134 |
'SQLITE_IOERR_BLOCKED', |
| 135 |
'SQLITE_IOERR_CHECKRESERVEDLOCK', |
| 136 |
'SQLITE_IOERR_CLOSE', |
| 137 |
'SQLITE_IOERR_COMMIT_ATOMIC', |
| 138 |
'SQLITE_IOERR_CONVPATH', |
| 139 |
'SQLITE_IOERR_CORRUPTFS', |
| 140 |
'SQLITE_IOERR_DATA', |
| 141 |
'SQLITE_IOERR_DELETE', |
| 142 |
'SQLITE_IOERR_DELETE_NOENT', |
| 143 |
'SQLITE_IOERR_DIR_CLOSE', |
| 144 |
'SQLITE_IOERR_DIR_FSYNC', |
| 145 |
'SQLITE_IOERR_FSTAT', |
| 146 |
'SQLITE_IOERR_FSYNC', |
| 147 |
'SQLITE_IOERR_GETTEMPPATH', |
| 148 |
'SQLITE_IOERR_LOCK', |
| 149 |
'SQLITE_IOERR_MMAP', |
| 150 |
'SQLITE_IOERR_NOMEM', |
| 151 |
'SQLITE_IOERR_RDLOCK', |
| 152 |
'SQLITE_IOERR_READ', |
| 153 |
'SQLITE_IOERR_ROLLBACK_ATOMIC', |
| 154 |
'SQLITE_IOERR_SEEK', |
| 155 |
'SQLITE_IOERR_SHMLOCK', |
| 156 |
'SQLITE_IOERR_SHMMAP', |
| 157 |
'SQLITE_IOERR_SHMOPEN', |
| 158 |
'SQLITE_IOERR_SHMSIZE', |
| 159 |
'SQLITE_IOERR_SHORT_READ', |
| 160 |
'SQLITE_IOERR_TRUNCATE', |
| 161 |
'SQLITE_IOERR_UNLOCK', |
| 162 |
'SQLITE_IOERR_VNODE', |
| 163 |
'SQLITE_IOERR_WRITE', |
| 164 |
'SQLITE_LIMIT_ATTACHED', |
| 165 |
'SQLITE_LIMIT_COLUMN', |
| 166 |
'SQLITE_LIMIT_COMPOUND_SELECT', |
| 167 |
'SQLITE_LIMIT_EXPR_DEPTH', |
| 168 |
'SQLITE_LIMIT_FUNCTION_ARG', |
| 169 |
'SQLITE_LIMIT_LENGTH', |
| 170 |
'SQLITE_LIMIT_LIKE_PATTERN_LENGTH', |
| 171 |
'SQLITE_LIMIT_SQL_LENGTH', |
| 172 |
'SQLITE_LIMIT_TRIGGER_DEPTH', |
| 173 |
'SQLITE_LIMIT_VARIABLE_NUMBER', |
| 174 |
'SQLITE_LIMIT_VDBE_OP', |
| 175 |
'SQLITE_LIMIT_WORKER_THREADS', |
| 176 |
'SQLITE_LOCKED', |
| 177 |
'SQLITE_LOCKED_SHAREDCACHE', |
| 178 |
'SQLITE_LOCKED_VTAB', |
| 179 |
'SQLITE_MISMATCH', |
| 180 |
'SQLITE_MISUSE', |
| 181 |
'SQLITE_NOLFS', |
| 182 |
'SQLITE_NOMEM', |
| 183 |
'SQLITE_NOTADB', |
| 184 |
'SQLITE_NOTFOUND', |
| 185 |
'SQLITE_NOTICE', |
| 186 |
'SQLITE_NOTICE_RECOVER_ROLLBACK', |
| 187 |
'SQLITE_NOTICE_RECOVER_WAL', |
| 188 |
'SQLITE_OK', |
| 189 |
'SQLITE_OK_LOAD_PERMANENTLY', |
| 190 |
'SQLITE_OK_SYMLINK', |
| 191 |
'SQLITE_PERM', |
| 192 |
'SQLITE_PRAGMA', |
| 193 |
'SQLITE_PROTOCOL', |
| 194 |
'SQLITE_RANGE', |
| 195 |
'SQLITE_READ', |
| 196 |
'SQLITE_READONLY', |
| 197 |
'SQLITE_READONLY_CANTINIT', |
| 198 |
'SQLITE_READONLY_CANTLOCK', |
| 199 |
'SQLITE_READONLY_DBMOVED', |
| 200 |
'SQLITE_READONLY_DIRECTORY', |
| 201 |
'SQLITE_READONLY_RECOVERY', |
| 202 |
'SQLITE_READONLY_ROLLBACK', |
| 203 |
'SQLITE_RECURSIVE', |
| 204 |
'SQLITE_REINDEX', |
| 205 |
'SQLITE_ROW', |
| 206 |
'SQLITE_SAVEPOINT', |
| 207 |
'SQLITE_SCHEMA', |
| 208 |
'SQLITE_SELECT', |
| 209 |
'SQLITE_TOOBIG', |
| 210 |
'SQLITE_TRANSACTION', |
| 211 |
'SQLITE_UPDATE', |
| 212 |
'SQLITE_WARNING', |
| 213 |
'SQLITE_WARNING_AUTOINDEX', |
| 214 |
] |
| 215 |
|
| 216 |
|
| 217 |
for symbol in exported_sqlite_symbols: |
| 218 |
if hasattr(_lib, symbol): |
| 219 |
globals()[symbol] = getattr(_lib, symbol) |
| 220 |
|
| 221 |
_SQLITE_TRANSIENT = _lib.SQLITE_TRANSIENT |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
_error_names = { |
| 226 |
globals()[name] : name for name in [ |
| 227 |
"SQLITE_ABORT", |
| 228 |
"SQLITE_AUTH", |
| 229 |
"SQLITE_BUSY", |
| 230 |
"SQLITE_CANTOPEN", |
| 231 |
"SQLITE_CONSTRAINT", |
| 232 |
"SQLITE_CONSTRAINT_CHECK", |
| 233 |
"SQLITE_CONSTRAINT_COMMITHOOK", |
| 234 |
"SQLITE_CONSTRAINT_FOREIGNKEY", |
| 235 |
"SQLITE_CONSTRAINT_FUNCTION", |
| 236 |
"SQLITE_CONSTRAINT_NOTNULL", |
| 237 |
"SQLITE_CONSTRAINT_PINNED", |
| 238 |
"SQLITE_CONSTRAINT_PRIMARYKEY", |
| 239 |
"SQLITE_CONSTRAINT_ROWID", |
| 240 |
"SQLITE_CONSTRAINT_TRIGGER", |
| 241 |
"SQLITE_CONSTRAINT_UNIQUE", |
| 242 |
"SQLITE_CONSTRAINT_VTAB", |
| 243 |
"SQLITE_CORRUPT", |
| 244 |
"SQLITE_DONE", |
| 245 |
"SQLITE_EMPTY", |
| 246 |
"SQLITE_ERROR", |
| 247 |
"SQLITE_FORMAT", |
| 248 |
"SQLITE_FULL", |
| 249 |
"SQLITE_INTERNAL", |
| 250 |
"SQLITE_INTERRUPT", |
| 251 |
"SQLITE_IOERR", |
| 252 |
"SQLITE_LOCKED", |
| 253 |
"SQLITE_MISMATCH", |
| 254 |
"SQLITE_MISUSE", |
| 255 |
"SQLITE_NOLFS", |
| 256 |
"SQLITE_NOMEM", |
| 257 |
"SQLITE_NOTADB", |
| 258 |
"SQLITE_NOTFOUND", |
| 259 |
"SQLITE_OK", |
| 260 |
"SQLITE_PERM", |
| 261 |
"SQLITE_PROTOCOL", |
| 262 |
"SQLITE_READONLY", |
| 263 |
"SQLITE_ROW", |
| 264 |
"SQLITE_SCHEMA", |
| 265 |
"SQLITE_TOOBIG", |
| 266 |
"SQLITE_NOTICE", |
| 267 |
"SQLITE_WARNING", |
| 268 |
] |
| 269 |
} |
| 270 |
|
| 271 |
|
| 272 |
version = "2.6.0" |
| 273 |
|
| 274 |
|
| 275 |
PARSE_COLNAMES = 1 |
| 276 |
PARSE_DECLTYPES = 2 |
| 277 |
|
| 278 |
|
| 279 |
sqlite_version = str(_ffi.string(_lib.sqlite3_libversion()).decode('ascii')) |
| 280 |
_sqlite_version_triple = tuple(int(x) for x in sqlite_version.split('.')) |
| 281 |
|
| 282 |
|
| 283 |
BASE_TYPE_ADAPTED = False |
| 284 |
|
| 285 |
|
| 286 |
BASE_TYPES = {bytearray, bytes, float, int, str, NoneType} |
| 287 |
|
| 288 |
class Error(StandardError): |
| 289 |
pass |
| 290 |
|
| 291 |
|
| 292 |
class Warning(StandardError): |
| 293 |
pass |
| 294 |
|
| 295 |
|
| 296 |
class InterfaceError(Error): |
| 297 |
pass |
| 298 |
|
| 299 |
|
| 300 |
class DatabaseError(Error): |
| 301 |
pass |
| 302 |
|
| 303 |
|
| 304 |
class InternalError(DatabaseError): |
| 305 |
pass |
| 306 |
|
| 307 |
|
| 308 |
class OperationalError(DatabaseError): |
| 309 |
pass |
| 310 |
|
| 311 |
|
| 312 |
class ProgrammingError(DatabaseError): |
| 313 |
pass |
| 314 |
|
| 315 |
|
| 316 |
class IntegrityError(DatabaseError): |
| 317 |
pass |
| 318 |
|
| 319 |
|
| 320 |
class DataError(DatabaseError): |
| 321 |
pass |
| 322 |
|
| 323 |
|
| 324 |
class NotSupportedError(DatabaseError): |
| 325 |
pass |
| 326 |
|
| 327 |
for _cls in (Error, Warning, InterfaceError, DatabaseError, InternalError, |
| 328 |
OperationalError, ProgrammingError, IntegrityError, |
| 329 |
DataError, NotSupportedError): |
| 330 |
_cls.__module__ = 'sqlite3' |
| 331 |
del _cls |
| 332 |
|
| 333 |
def connect(database, timeout=5.0, detect_types=0, isolation_level="", |
| 334 |
check_same_thread=True, factory=None, cached_statements=100, |
| 335 |
uri=0): |
| 336 |
factory = Connection if not factory else factory |
| 337 |
|
| 338 |
|
| 339 |
res = factory(database=database, timeout=timeout, |
| 340 |
detect_types=detect_types, isolation_level=isolation_level, |
| 341 |
check_same_thread=check_same_thread, factory=factory, |
| 342 |
cached_statements=cached_statements, uri=uri) |
| 343 |
add_memory_pressure(100 * 1024) |
| 344 |
return res |
| 345 |
|
| 346 |
|
| 347 |
def _unicode_text_factory(x): |
| 348 |
return unicode(x, 'utf-8') |
| 349 |
|
| 350 |
|
| 351 |
class _StatementCache(object): |
| 352 |
def __init__(self, connection, maxcount): |
| 353 |
self.connection = connection |
| 354 |
self.maxcount = maxcount |
| 355 |
self.cache = OrderedDict() |
| 356 |
|
| 357 |
def get(self, sql): |
| 358 |
stat = self.cache.get(sql, None) |
| 359 |
not_there = stat is None |
| 360 |
if not_there or stat._in_use_token: |
| 361 |
stat = object.__new__(Statement) |
| 362 |
stat.__init__(self.connection, sql) |
| 363 |
self.cache[sql] = stat |
| 364 |
if not_there and len(self.cache) > self.maxcount: |
| 365 |
self.cache.popitem(0) |
| 366 |
return stat |
| 367 |
|
| 368 |
BEGIN_STATMENTS = ( |
| 369 |
"BEGIN ", |
| 370 |
"BEGIN DEFERRED", |
| 371 |
"BEGIN IMMEDIATE", |
| 372 |
"BEGIN EXCLUSIVE", |
| 373 |
) |
| 374 |
|
| 375 |
class Connection(object): |
| 376 |
__initialized = False |
| 377 |
_db = None |
| 378 |
|
| 379 |
def __init__(self, database, timeout=5.0, detect_types=0, isolation_level="", |
| 380 |
check_same_thread=True, factory=None, cached_statements=100, uri=0): |
| 381 |
sys.audit("sqlite3.connect", database) |
| 382 |
self.__initialized = False |
| 383 |
db_star = _ffi.new('sqlite3 **') |
| 384 |
|
| 385 |
database = os.fsencode(database) |
| 386 |
if _lib.SQLITE_OPEN_URI != 0: |
| 387 |
if uri and _lib.SQLITE_OPEN_URI == 0: |
| 388 |
raise NotSupportedError("URIs not supported") |
| 389 |
flags = _lib.SQLITE_OPEN_READWRITE | _lib.SQLITE_OPEN_CREATE |
| 390 |
if uri: |
| 391 |
flags |= _lib.SQLITE_OPEN_URI |
| 392 |
rc = _lib.sqlite3_open_v2(database, db_star, flags, _ffi.NULL) |
| 393 |
if rc != _lib.SQLITE_OK: |
| 394 |
raise self.__exc(OperationalError, "unable to open database file", rc) |
| 395 |
else: |
| 396 |
rc = _lib.sqlite3_open(database, db_star) |
| 397 |
if rc != _lib.SQLITE_OK: |
| 398 |
raise self.__exc(OperationalError, "unable to open database file", rc) |
| 399 |
self.__initialized = True |
| 400 |
self._db = db_star[0] |
| 401 |
if timeout is not None: |
| 402 |
timeout = int(timeout * 1000) |
| 403 |
_lib.sqlite3_busy_timeout(self._db, timeout) |
| 404 |
|
| 405 |
self.row_factory = None |
| 406 |
self.text_factory = _unicode_text_factory |
| 407 |
|
| 408 |
self._detect_types = detect_types |
| 409 |
self.isolation_level = isolation_level |
| 410 |
|
| 411 |
self.__cursors = set() |
| 412 |
self.__statements = set() |
| 413 |
self.__rawstatements = set() |
| 414 |
self._statement_cache = _StatementCache(self, cached_statements) |
| 415 |
self.__statements_already_committed = [] |
| 416 |
|
| 417 |
self.__blobs = [] |
| 418 |
|
| 419 |
self.__func_cache = {} |
| 420 |
self.__aggregates = {} |
| 421 |
self.__aggregate_instances = {} |
| 422 |
self.__collations = {} |
| 423 |
if check_same_thread: |
| 424 |
self.__thread_ident = threading.get_ident() |
| 425 |
if not check_same_thread and _lib.sqlite3_libversion_number() < 3003001: |
| 426 |
raise NotSupportedError("shared connections not available") |
| 427 |
|
| 428 |
self.__windows = {} |
| 429 |
self.__window_instances = {} |
| 430 |
|
| 431 |
self.Error = Error |
| 432 |
self.Warning = Warning |
| 433 |
self.InterfaceError = InterfaceError |
| 434 |
self.DatabaseError = DatabaseError |
| 435 |
self.InternalError = InternalError |
| 436 |
self.OperationalError = OperationalError |
| 437 |
self.ProgrammingError = ProgrammingError |
| 438 |
self.IntegrityError = IntegrityError |
| 439 |
self.DataError = DataError |
| 440 |
self.NotSupportedError = NotSupportedError |
| 441 |
sys.audit("sqlite3.connect/handle", self) |
| 442 |
|
| 443 |
def __del__(self): |
| 444 |
if self._db: |
| 445 |
_lib.sqlite3_close(self._db) |
| 446 |
|
| 447 |
def close(self): |
| 448 |
if not self.__initialized: |
| 449 |
raise ProgrammingError("Base Connection.__init__ not called.") |
| 450 |
self._check_thread() |
| 451 |
|
| 452 |
self.__do_all_statements(Statement._finalize, True) |
| 453 |
|
| 454 |
|
| 455 |
for blobref in self.__blobs: |
| 456 |
blob = blobref() |
| 457 |
if blob is None: |
| 458 |
continue |
| 459 |
blob.close() |
| 460 |
self.__blobs.clear() |
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
if self.__rawstatements is not None: |
| 466 |
for stmt in list(self.__rawstatements): |
| 467 |
self._finalize_raw_statement(stmt) |
| 468 |
self.__rawstatements = None |
| 469 |
|
| 470 |
if self._db: |
| 471 |
ret = _lib.sqlite3_close(self._db) |
| 472 |
if ret != _lib.SQLITE_OK: |
| 473 |
raise self._get_exception(ret) |
| 474 |
self._db = None |
| 475 |
|
| 476 |
def _check_closed(self): |
| 477 |
if not self.__initialized: |
| 478 |
raise ProgrammingError("Base Connection.__init__ not called.") |
| 479 |
if not self._db: |
| 480 |
raise ProgrammingError("Cannot operate on a closed database.") |
| 481 |
|
| 482 |
def _check_closed_wrap(func): |
| 483 |
@wraps(func) |
| 484 |
def wrapper(self, *args, **kwargs): |
| 485 |
self._check_closed() |
| 486 |
return func(self, *args, **kwargs) |
| 487 |
return wrapper |
| 488 |
|
| 489 |
def _check_thread(self): |
| 490 |
try: |
| 491 |
if self.__thread_ident == threading.get_ident(): |
| 492 |
return |
| 493 |
except AttributeError: |
| 494 |
pass |
| 495 |
else: |
| 496 |
raise ProgrammingError( |
| 497 |
"SQLite objects created in a thread can only be used in that " |
| 498 |
"same thread. The object was created in thread id %d and this " |
| 499 |
"is thread id %d" % (self.__thread_ident, threading.get_ident())) |
| 500 |
|
| 501 |
def _check_thread_wrap(func): |
| 502 |
@wraps(func) |
| 503 |
def wrapper(self, *args, **kwargs): |
| 504 |
self._check_thread() |
| 505 |
return func(self, *args, **kwargs) |
| 506 |
return wrapper |
| 507 |
|
| 508 |
def _check_closed_and_thread_wrap(func): |
| 509 |
@wraps(func) |
| 510 |
def wrapper(self, *args, **kwargs): |
| 511 |
self._check_thread() |
| 512 |
self._check_closed() |
| 513 |
return func(self, *args, **kwargs) |
| 514 |
return wrapper |
| 515 |
|
| 516 |
def _get_exception(self, error_code=None): |
| 517 |
if error_code is None: |
| 518 |
error_code = _lib.sqlite3_errcode(self._db) |
| 519 |
error_message = _ffi.string(_lib.sqlite3_errmsg(self._db)).decode('utf-8') |
| 520 |
|
| 521 |
if error_code == _lib.SQLITE_OK: |
| 522 |
raise ValueError("error signalled but got SQLITE_OK") |
| 523 |
elif error_code in (_lib.SQLITE_INTERNAL, _lib.SQLITE_NOTFOUND): |
| 524 |
exc = InternalError |
| 525 |
elif error_code == _lib.SQLITE_NOMEM: |
| 526 |
exc = MemoryError |
| 527 |
elif error_code in ( |
| 528 |
_lib.SQLITE_ERROR, _lib.SQLITE_PERM, _lib.SQLITE_ABORT, |
| 529 |
_lib.SQLITE_BUSY, _lib.SQLITE_LOCKED, _lib.SQLITE_READONLY, |
| 530 |
_lib.SQLITE_INTERRUPT, _lib.SQLITE_IOERR, _lib.SQLITE_FULL, |
| 531 |
_lib.SQLITE_CANTOPEN, _lib.SQLITE_PROTOCOL, _lib.SQLITE_EMPTY, |
| 532 |
_lib.SQLITE_SCHEMA): |
| 533 |
exc = OperationalError |
| 534 |
elif error_code == _lib.SQLITE_CORRUPT: |
| 535 |
exc = DatabaseError |
| 536 |
elif error_code == _lib.SQLITE_TOOBIG: |
| 537 |
exc = DataError |
| 538 |
elif error_code in (_lib.SQLITE_CONSTRAINT, _lib.SQLITE_MISMATCH): |
| 539 |
exc = IntegrityError |
| 540 |
elif error_code == _lib.SQLITE_MISUSE: |
| 541 |
exc = ProgrammingError |
| 542 |
else: |
| 543 |
exc = DatabaseError |
| 544 |
error_code = _lib.sqlite3_extended_errcode(self._db) |
| 545 |
return self.__exc(exc, error_message, error_code) |
| 546 |
|
| 547 |
def __exc(self, cls, error_message, error_code): |
| 548 |
exc = cls(error_message) |
| 549 |
exc.error_code = error_code |
| 550 |
exc.sqlite_errorcode = error_code |
| 551 |
if error_code in _error_names: |
| 552 |
exc.sqlite_errorname = _error_names[error_code] |
| 553 |
return exc |
| 554 |
|
| 555 |
def _remember_cursor(self, cursor): |
| 556 |
ref = weakref.ref(cursor, self.__cursors.discard) |
| 557 |
self.__cursors.add(ref) |
| 558 |
cursor._connection_ref = ref |
| 559 |
|
| 560 |
def _forget_cursor(self, cursor_ref): |
| 561 |
self.__cursors.discard(cursor_ref) |
| 562 |
|
| 563 |
def _remember_statement(self, statement): |
| 564 |
self.__rawstatements.add(statement._statement) |
| 565 |
ref = weakref.ref(statement, self.__statements.discard) |
| 566 |
self.__statements.add(ref) |
| 567 |
|
| 568 |
def _finalize_raw_statement(self, _statement): |
| 569 |
if self.__rawstatements is not None: |
| 570 |
try: |
| 571 |
self.__rawstatements.remove(_statement) |
| 572 |
except KeyError: |
| 573 |
return |
| 574 |
_lib.sqlite3_finalize(_statement) |
| 575 |
|
| 576 |
def __do_all_statements(self, action, reset_cursors): |
| 577 |
for ref in list(self.__statements): |
| 578 |
statement = ref() |
| 579 |
if statement is not None: |
| 580 |
action(statement) |
| 581 |
|
| 582 |
if reset_cursors: |
| 583 |
for ref in list(self.__cursors): |
| 584 |
cursor = ref() |
| 585 |
if cursor is not None: |
| 586 |
cursor._reset = True |
| 587 |
|
| 588 |
def _reset_already_committed_statements(self): |
| 589 |
lst = self.__statements_already_committed |
| 590 |
self.__statements_already_committed = [] |
| 591 |
for weakref in lst: |
| 592 |
statement = weakref() |
| 593 |
if statement is not None: |
| 594 |
statement._force_reset() |
| 595 |
|
| 596 |
@_check_thread_wrap |
| 597 |
@_check_closed_wrap |
| 598 |
def __call__(self, sql): |
| 599 |
return self._statement_cache.get(sql) |
| 600 |
|
| 601 |
def _default_cursor_factory(self): |
| 602 |
return Cursor(self) |
| 603 |
|
| 604 |
def cursor(self, factory=_default_cursor_factory): |
| 605 |
self._check_thread() |
| 606 |
self._check_closed() |
| 607 |
cur = factory(self) |
| 608 |
if not issubclass(type(cur), Cursor): |
| 609 |
raise TypeError("factory must return a cursor, not %s" |
| 610 |
% (type(cur).__name__,)) |
| 611 |
if self.row_factory is not None: |
| 612 |
cur.row_factory = self.row_factory |
| 613 |
return cur |
| 614 |
|
| 615 |
def execute(self, *args): |
| 616 |
cur = self.cursor() |
| 617 |
return cur.execute(*args) |
| 618 |
|
| 619 |
def executemany(self, *args): |
| 620 |
cur = self.cursor() |
| 621 |
return cur.executemany(*args) |
| 622 |
|
| 623 |
def executescript(self, *args): |
| 624 |
cur = self.cursor() |
| 625 |
return cur.executescript(*args) |
| 626 |
|
| 627 |
def iterdump(self): |
| 628 |
from sqlite3.dump import _iterdump |
| 629 |
self._check_closed() |
| 630 |
return _iterdump(self) |
| 631 |
|
| 632 |
def _begin(self): |
| 633 |
statement_star = _ffi.new('sqlite3_stmt **') |
| 634 |
ret = _lib.sqlite3_prepare_v2(self._db, self._begin_statement, -1, |
| 635 |
statement_star, _ffi.NULL) |
| 636 |
try: |
| 637 |
if ret != _lib.SQLITE_OK: |
| 638 |
raise self._get_exception(ret) |
| 639 |
ret = _lib.sqlite3_step(statement_star[0]) |
| 640 |
if ret != _lib.SQLITE_DONE: |
| 641 |
raise self._get_exception(ret) |
| 642 |
finally: |
| 643 |
_lib.sqlite3_finalize(statement_star[0]) |
| 644 |
|
| 645 |
def commit(self): |
| 646 |
self._check_thread() |
| 647 |
self._check_closed() |
| 648 |
if not self.in_transaction: |
| 649 |
return |
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
self.__statements_already_committed = list(self.__statements) |
| 663 |
|
| 664 |
statement_star = _ffi.new('sqlite3_stmt **') |
| 665 |
ret = _lib.sqlite3_prepare_v2(self._db, b"COMMIT", -1, |
| 666 |
statement_star, _ffi.NULL) |
| 667 |
try: |
| 668 |
if ret != _lib.SQLITE_OK: |
| 669 |
raise self._get_exception(ret) |
| 670 |
ret = _lib.sqlite3_step(statement_star[0]) |
| 671 |
if ret != _lib.SQLITE_DONE: |
| 672 |
raise self._get_exception(ret) |
| 673 |
finally: |
| 674 |
_lib.sqlite3_finalize(statement_star[0]) |
| 675 |
|
| 676 |
def rollback(self): |
| 677 |
self._check_thread() |
| 678 |
self._check_closed() |
| 679 |
if not self.in_transaction: |
| 680 |
return |
| 681 |
|
| 682 |
statement_star = _ffi.new('sqlite3_stmt **') |
| 683 |
ret = _lib.sqlite3_prepare_v2(self._db, b"ROLLBACK", -1, |
| 684 |
statement_star, _ffi.NULL) |
| 685 |
try: |
| 686 |
if ret != _lib.SQLITE_OK: |
| 687 |
raise self._get_exception(ret) |
| 688 |
ret = _lib.sqlite3_step(statement_star[0]) |
| 689 |
if ret != _lib.SQLITE_DONE: |
| 690 |
raise self._get_exception(ret) |
| 691 |
finally: |
| 692 |
_lib.sqlite3_finalize(statement_star[0]) |
| 693 |
|
| 694 |
def __enter__(self): |
| 695 |
return self |
| 696 |
|
| 697 |
def __exit__(self, exc_type, exc_value, exc_tb): |
| 698 |
if exc_type is None and exc_value is None and exc_tb is None: |
| 699 |
self.commit() |
| 700 |
else: |
| 701 |
self.rollback() |
| 702 |
|
| 703 |
@_check_thread_wrap |
| 704 |
@_check_closed_wrap |
| 705 |
def create_function(self, name, nargs, func, *, deterministic=False): |
| 706 |
try: |
| 707 |
closure = self.__func_cache[func] |
| 708 |
except KeyError: |
| 709 |
@_ffi.callback("void(sqlite3_context*, int, sqlite3_value**)") |
| 710 |
def closure(context, nargs, c_params): |
| 711 |
_function_callback(func, context, nargs, c_params) |
| 712 |
self.__func_cache[func] = closure |
| 713 |
|
| 714 |
if isinstance(name, unicode): |
| 715 |
name = name.encode('utf-8') |
| 716 |
flags = _lib.SQLITE_UTF8 |
| 717 |
if deterministic: |
| 718 |
if not hasattr(_lib, 'SQLITE_DETERMINISTIC'): |
| 719 |
raise NotSupportedError( |
| 720 |
"deterministic=True requires building _sqlite3 with " |
| 721 |
"SQLite 3.8.3 or higher") |
| 722 |
|
| 723 |
if _lib.sqlite3_libversion_number() < 3008003: |
| 724 |
raise NotSupportedError( |
| 725 |
"deterministic=True requires SQLite 3.8.3 or higher") |
| 726 |
flags |= _lib.SQLITE_DETERMINISTIC |
| 727 |
ret = _lib.sqlite3_create_function(self._db, name, nargs, |
| 728 |
flags, _ffi.NULL, |
| 729 |
closure, _ffi.NULL, _ffi.NULL) |
| 730 |
if ret != _lib.SQLITE_OK: |
| 731 |
raise self.OperationalError("Error creating function") |
| 732 |
|
| 733 |
@_check_thread_wrap |
| 734 |
@_check_closed_wrap |
| 735 |
def create_aggregate(self, name, num_args, cls): |
| 736 |
try: |
| 737 |
step_callback, final_callback = self.__aggregates[cls] |
| 738 |
except KeyError: |
| 739 |
step_callback = self.__make_step_callback(cls) |
| 740 |
final_callback = self.__make_final_callback(cls) |
| 741 |
self.__aggregates[cls] = (step_callback, final_callback) |
| 742 |
|
| 743 |
if isinstance(name, unicode): |
| 744 |
name = name.encode('utf-8') |
| 745 |
ret = _lib.sqlite3_create_function(self._db, name, num_args, |
| 746 |
_lib.SQLITE_UTF8, _ffi.NULL, |
| 747 |
_ffi.NULL, |
| 748 |
step_callback, |
| 749 |
final_callback) |
| 750 |
if ret != _lib.SQLITE_OK: |
| 751 |
raise self._get_exception(ret) |
| 752 |
|
| 753 |
def __make_step_callback(self, cls): |
| 754 |
@_ffi.callback("void(sqlite3_context*, int, sqlite3_value**)") |
| 755 |
def step_callback(context, argc, c_params): |
| 756 |
res = _lib.sqlite3_aggregate_context(context, |
| 757 |
_ffi.sizeof("size_t")) |
| 758 |
aggregate_ptr = _ffi.cast("size_t[1]", res) |
| 759 |
|
| 760 |
if not aggregate_ptr[0]: |
| 761 |
try: |
| 762 |
aggregate = cls() |
| 763 |
except Exception as e: |
| 764 |
msg = (b"user-defined aggregate's '__init__' " |
| 765 |
b"method raised error") |
| 766 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 767 |
return |
| 768 |
aggregate_id = id(aggregate) |
| 769 |
self.__aggregate_instances[aggregate_id] = aggregate |
| 770 |
aggregate_ptr[0] = aggregate_id |
| 771 |
else: |
| 772 |
aggregate = self.__aggregate_instances[aggregate_ptr[0]] |
| 773 |
|
| 774 |
try: |
| 775 |
meth = aggregate.step |
| 776 |
except AttributeError as e: |
| 777 |
msg = (b"user-defined aggregate's 'step' " |
| 778 |
b"method not defined") |
| 779 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 780 |
else: |
| 781 |
params = _convert_params(context, argc, c_params) |
| 782 |
try: |
| 783 |
meth(*params) |
| 784 |
except Exception as e: |
| 785 |
msg = (b"user-defined aggregate's 'step' " |
| 786 |
b"method raised error") |
| 787 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 788 |
return step_callback |
| 789 |
|
| 790 |
def __make_final_callback(self, cls): |
| 791 |
@_ffi.callback("void(sqlite3_context*)") |
| 792 |
def final_callback(context): |
| 793 |
res = _lib.sqlite3_aggregate_context(context, |
| 794 |
_ffi.sizeof("size_t")) |
| 795 |
aggregate_ptr = _ffi.cast("size_t[1]", res) |
| 796 |
|
| 797 |
if aggregate_ptr[0]: |
| 798 |
aggregate = self.__aggregate_instances[aggregate_ptr[0]] |
| 799 |
try: |
| 800 |
try: |
| 801 |
meth = aggregate.finalize |
| 802 |
except AttributeError as e: |
| 803 |
msg = (b"user-defined aggregate's 'finalize' " |
| 804 |
b"method not defined") |
| 805 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 806 |
else: |
| 807 |
try: |
| 808 |
val = meth() |
| 809 |
except Exception as e: |
| 810 |
msg = (b"user-defined aggregate's 'finalize' " |
| 811 |
b"method raised error") |
| 812 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 813 |
else: |
| 814 |
_convert_result(context, val) |
| 815 |
finally: |
| 816 |
del self.__aggregate_instances[aggregate_ptr[0]] |
| 817 |
return final_callback |
| 818 |
|
| 819 |
@_check_thread_wrap |
| 820 |
@_check_closed_wrap |
| 821 |
def create_collation(self, name, callback): |
| 822 |
if not isinstance(name, str): |
| 823 |
raise TypeError("create_collation() argument 1 must be str, not '%s'" % (type(name).__name__, )) |
| 824 |
if "\x00" in name: |
| 825 |
raise ValueError("embedded null character") |
| 826 |
|
| 827 |
if callback is None: |
| 828 |
del self.__collations[name] |
| 829 |
collation_callback = _ffi.NULL |
| 830 |
else: |
| 831 |
if not callable(callback): |
| 832 |
raise TypeError("parameter must be callable") |
| 833 |
|
| 834 |
@_ffi.callback("int(void*, int, const void*, int, const void*)") |
| 835 |
def collation_callback(context, len1, str1, len2, str2): |
| 836 |
text1 = _ffi.buffer(str1, len1)[:] |
| 837 |
text2 = _ffi.buffer(str2, len2)[:] |
| 838 |
try: |
| 839 |
ret = callback(text1, text2) |
| 840 |
assert isinstance(ret, (int, long)) |
| 841 |
return cmp(ret, 0) |
| 842 |
except Exception: |
| 843 |
if _enable_callback_tracebacks[0]: |
| 844 |
print(traceback.format_exc()) |
| 845 |
return 0 |
| 846 |
|
| 847 |
self.__collations[name] = collation_callback |
| 848 |
|
| 849 |
if isinstance(name, unicode): |
| 850 |
name = name.encode('utf-8') |
| 851 |
ret = _lib.sqlite3_create_collation(self._db, name, |
| 852 |
_lib.SQLITE_UTF8, |
| 853 |
_ffi.NULL, |
| 854 |
collation_callback) |
| 855 |
if ret != _lib.SQLITE_OK: |
| 856 |
raise self._get_exception(ret) |
| 857 |
|
| 858 |
@_check_thread_wrap |
| 859 |
@_check_closed_wrap |
| 860 |
def set_authorizer(self, callback): |
| 861 |
""" Sets authorizer callback. """ |
| 862 |
try: |
| 863 |
authorizer = self.__func_cache[callback] |
| 864 |
except KeyError: |
| 865 |
if callback is not None: |
| 866 |
@_ffi.callback("int(void*, int, const char*, const char*, " |
| 867 |
"const char*, const char*)") |
| 868 |
def authorizer(userdata, action, arg1, arg2, dbname, source): |
| 869 |
try: |
| 870 |
ret = callback(action, arg1, arg2, dbname, source) |
| 871 |
assert isinstance(ret, int) |
| 872 |
|
| 873 |
|
| 874 |
assert int(_ffi.cast('int', ret)) == ret |
| 875 |
return ret |
| 876 |
except Exception as e: |
| 877 |
print_or_clear_traceback(callback, e) |
| 878 |
return _lib.SQLITE_DENY |
| 879 |
self.__func_cache[callback] = authorizer |
| 880 |
else: |
| 881 |
authorizer = _ffi.NULL |
| 882 |
|
| 883 |
ret = _lib.sqlite3_set_authorizer(self._db, authorizer, _ffi.NULL) |
| 884 |
if ret != _lib.SQLITE_OK: |
| 885 |
raise self._get_exception(ret) |
| 886 |
|
| 887 |
@_check_thread_wrap |
| 888 |
@_check_closed_wrap |
| 889 |
def set_progress_handler(self, callable, n): |
| 890 |
if callable is None: |
| 891 |
progress_handler = _ffi.NULL |
| 892 |
else: |
| 893 |
try: |
| 894 |
progress_handler = self.__func_cache[callable] |
| 895 |
except KeyError: |
| 896 |
@_ffi.callback("int(void*)") |
| 897 |
def progress_handler(userdata): |
| 898 |
try: |
| 899 |
return bool(callable()) |
| 900 |
except Exception as exc: |
| 901 |
|
| 902 |
print_or_clear_traceback(callable, exc) |
| 903 |
return 1 |
| 904 |
self.__func_cache[callable] = progress_handler |
| 905 |
_lib.sqlite3_progress_handler(self._db, n, progress_handler, |
| 906 |
_ffi.NULL) |
| 907 |
|
| 908 |
@_check_thread_wrap |
| 909 |
@_check_closed_wrap |
| 910 |
def set_trace_callback(self, callable): |
| 911 |
if callable is None: |
| 912 |
trace_callback = _ffi.NULL |
| 913 |
else: |
| 914 |
try: |
| 915 |
trace_callback = self.__func_cache[callable] |
| 916 |
except KeyError: |
| 917 |
@_ffi.callback("int(unsigned, void*, void*, void*)") |
| 918 |
def trace_callback(typ, ctx, statement, sql): |
| 919 |
if typ != _lib.SQLITE_TRACE_STMT: |
| 920 |
return 0 |
| 921 |
expanded_sql = _lib.sqlite3_expanded_sql(statement) |
| 922 |
if not expanded_sql: |
| 923 |
exc = DataError("Expanded SQL string exceeds the maximum string length") |
| 924 |
print_or_clear_traceback(self, exc) |
| 925 |
stmt = _ffi.string(_ffi.cast('char*', sql)).decode('utf-8') |
| 926 |
else: |
| 927 |
try: |
| 928 |
stmt = _ffi.string(expanded_sql).decode('utf-8') |
| 929 |
finally: |
| 930 |
_lib.sqlite3_free(expanded_sql) |
| 931 |
try: |
| 932 |
callable(stmt) |
| 933 |
except Exception as exc: |
| 934 |
print_or_clear_traceback(self, exc) |
| 935 |
return 0 |
| 936 |
self.__func_cache[callable] = trace_callback |
| 937 |
_lib.sqlite3_trace_v2(self._db, _lib.SQLITE_TRACE_STMT, |
| 938 |
trace_callback, _ffi.NULL) |
| 939 |
|
| 940 |
@property |
| 941 |
@_check_closed_wrap |
| 942 |
def in_transaction(self): |
| 943 |
return not _lib.sqlite3_get_autocommit(self._db) |
| 944 |
|
| 945 |
def __get_total_changes(self): |
| 946 |
self._check_closed() |
| 947 |
return _lib.sqlite3_total_changes(self._db) |
| 948 |
total_changes = property(__get_total_changes) |
| 949 |
|
| 950 |
def __get_isolation_level(self): |
| 951 |
if not self.__initialized: |
| 952 |
raise ProgrammingError("Base Connection.__init__ not called") |
| 953 |
return self._isolation_level |
| 954 |
|
| 955 |
def __set_isolation_level(self, val): |
| 956 |
if val is None: |
| 957 |
self.commit() |
| 958 |
self._begin_statement = None |
| 959 |
else: |
| 960 |
if not isinstance(val, str): |
| 961 |
raise TypeError("isolation level must be " \ |
| 962 |
"a string or None, not %s" % type(val).__name__) |
| 963 |
stmt = str("BEGIN " + val).upper() |
| 964 |
if stmt not in BEGIN_STATMENTS: |
| 965 |
raise ValueError("isolation_level string must be '', 'DEFERRED', 'IMMEDIATE', or 'EXCLUSIVE'") |
| 966 |
self._begin_statement = stmt.encode('utf-8') |
| 967 |
self._isolation_level = val |
| 968 |
isolation_level = property(__get_isolation_level, __set_isolation_level) |
| 969 |
|
| 970 |
if hasattr(_lib, 'sqlite3_enable_load_extension'): |
| 971 |
@_check_thread_wrap |
| 972 |
@_check_closed_wrap |
| 973 |
def enable_load_extension(self, enabled): |
| 974 |
sys.audit("sqlite3.enable_load_extension", self, enabled) |
| 975 |
rc = _lib.sqlite3_enable_load_extension(self._db, int(enabled)) |
| 976 |
if rc != _lib.SQLITE_OK: |
| 977 |
raise OperationalError("Error enabling load extension") |
| 978 |
|
| 979 |
if hasattr(_lib, 'sqlite3_backup_init'): |
| 980 |
def backup(self, target, *, pages=0, progress=None, name="main", sleep=0.250): |
| 981 |
"""Makes a backup of the database. Non-standard.""" |
| 982 |
if not isinstance(target, Connection): |
| 983 |
raise TypeError("target is not a Connection") |
| 984 |
if target == self: |
| 985 |
raise ValueError("target cannot be the same connection instance") |
| 986 |
if progress is not None and not callable(progress): |
| 987 |
raise TypeError("progress argument must be a callable") |
| 988 |
if pages == 0: |
| 989 |
pages = -1 |
| 990 |
bck_conn = target._db |
| 991 |
if not bck_conn or not self._db: |
| 992 |
raise ProgrammingError("cannot operate on closed connection") |
| 993 |
self._check_closed() |
| 994 |
bck_handle = _lib.sqlite3_backup_init(bck_conn, b"main", self._db, name.encode("utf-8")) |
| 995 |
if not bck_handle: |
| 996 |
raise target._get_exception() |
| 997 |
while 1: |
| 998 |
rc = _lib.sqlite3_backup_step(bck_handle, pages) |
| 999 |
if progress: |
| 1000 |
try: |
| 1001 |
progress(rc, _lib.sqlite3_backup_remaining(bck_handle), _lib.sqlite3_backup_pagecount(bck_handle)) |
| 1002 |
except: |
| 1003 |
_lib.sqlite3_backup_finish(bck_handle) |
| 1004 |
raise |
| 1005 |
if rc == _lib.SQLITE_BUSY or rc == _lib.SQLITE_LOCKED: |
| 1006 |
_lib.sqlite3_sleep(sleep * 1000) |
| 1007 |
elif rc == _lib.SQLITE_OK: |
| 1008 |
pass |
| 1009 |
else: |
| 1010 |
break |
| 1011 |
rc = _lib.sqlite3_backup_finish(bck_handle); |
| 1012 |
if rc == _lib.SQLITE_OK: |
| 1013 |
return None |
| 1014 |
error = _lib.sqlite3_errstr(rc).decode("utf-8") |
| 1015 |
raise OperationalError(error) |
| 1016 |
|
| 1017 |
@_check_thread_wrap |
| 1018 |
@_check_closed_wrap |
| 1019 |
def load_extension(self, ext_name): |
| 1020 |
sys.audit("sqlite3.load_extension", self, ext_name) |
| 1021 |
errmsg = _ffi.new('char **') |
| 1022 |
ext_name_b = ext_name.encode() |
| 1023 |
null = _ffi.cast('char *', 0) |
| 1024 |
rc = _lib.sqlite3_load_extension(self._db, ext_name_b, null, errmsg) |
| 1025 |
if rc != 0: |
| 1026 |
raise OperationalError(_ffi.string(errmsg[0]).decode()) |
| 1027 |
|
| 1028 |
|
| 1029 |
@_check_thread_wrap |
| 1030 |
@_check_closed_wrap |
| 1031 |
def setlimit(self, category, limit): |
| 1032 |
""" |
| 1033 |
category: int |
| 1034 |
The limit category to be set. |
| 1035 |
limit: int |
| 1036 |
The new limit. If the new limit is a negative number, the limit is |
| 1037 |
unchanged |
| 1038 |
|
| 1039 |
Set connection run-time limits. |
| 1040 |
Attempts to increase a limit above its hard upper bound are silently truncated |
| 1041 |
to the hard upper bound. Regardless of whether or not the limit was changed, |
| 1042 |
the prior value of the limit is returned. |
| 1043 |
""" |
| 1044 |
oldlimit = _lib.sqlite3_limit(self._db, category, limit) |
| 1045 |
if oldlimit < 0: |
| 1046 |
raise ProgrammingError("'category' is out of bounds"); |
| 1047 |
return oldlimit |
| 1048 |
|
| 1049 |
def getlimit(self, category): |
| 1050 |
""" |
| 1051 |
category: int |
| 1052 |
The limit category to be queried. |
| 1053 |
|
| 1054 |
Get connection run-time limits. |
| 1055 |
""" |
| 1056 |
return self.setlimit(category, -1) |
| 1057 |
|
| 1058 |
@_check_thread_wrap |
| 1059 |
@_check_closed_wrap |
| 1060 |
def create_window_function(self, name, num_params, aggregate_class): |
| 1061 |
""" |
| 1062 |
name: str |
| 1063 |
The name of the SQL aggregate window function to be created or |
| 1064 |
redefined. |
| 1065 |
num_params: int |
| 1066 |
The number of arguments the step and inverse methods takes. |
| 1067 |
aggregate_class: object |
| 1068 |
A class with step(), finalize(), value(), and inverse() methods. |
| 1069 |
Set to None to clear the window function. |
| 1070 |
|
| 1071 |
Creates or redefines an aggregate window function. Non-standard. |
| 1072 |
""" |
| 1073 |
try: |
| 1074 |
(step_callback, final_callback, |
| 1075 |
value_callback, inverse_callback) = self.__windows[aggregate_class] |
| 1076 |
except KeyError: |
| 1077 |
step_callback = self.__make_step_callback(aggregate_class) |
| 1078 |
final_callback = self.__make_final_callback(aggregate_class) |
| 1079 |
value_callback = self.__make_value_callback(aggregate_class) |
| 1080 |
inverse_callback = self.__make_inverse_callback(aggregate_class) |
| 1081 |
|
| 1082 |
self.__windows[aggregate_class] = ( |
| 1083 |
step_callback, final_callback, |
| 1084 |
value_callback, inverse_callback) |
| 1085 |
|
| 1086 |
if isinstance(name, unicode): |
| 1087 |
name = name.encode('utf-8') |
| 1088 |
ret = _lib.sqlite3_create_window_function( |
| 1089 |
self._db, name, num_params, |
| 1090 |
_lib.SQLITE_UTF8, |
| 1091 |
_ffi.NULL, |
| 1092 |
step_callback, |
| 1093 |
final_callback, |
| 1094 |
value_callback, |
| 1095 |
inverse_callback, |
| 1096 |
_ffi.NULL) |
| 1097 |
if ret != _lib.SQLITE_OK: |
| 1098 |
raise self._get_exception(ret) |
| 1099 |
|
| 1100 |
def __make_value_callback(self, cls): |
| 1101 |
@_ffi.callback("void(sqlite3_context*)") |
| 1102 |
def value_callback(context): |
| 1103 |
res = _lib.sqlite3_aggregate_context(context, |
| 1104 |
_ffi.sizeof("size_t")) |
| 1105 |
aggregate_ptr = _ffi.cast("size_t[1]", res) |
| 1106 |
|
| 1107 |
if not aggregate_ptr[0]: |
| 1108 |
try: |
| 1109 |
aggregate = cls() |
| 1110 |
except Exception as e: |
| 1111 |
msg = (b"user-defined aggregate's '__init__' " |
| 1112 |
b"method raised error") |
| 1113 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1114 |
return |
| 1115 |
aggregate_id = id(aggregate) |
| 1116 |
self.__aggregate_instances[aggregate_id] = aggregate |
| 1117 |
aggregate_ptr[0] = aggregate_id |
| 1118 |
else: |
| 1119 |
aggregate = self.__aggregate_instances[aggregate_ptr[0]] |
| 1120 |
|
| 1121 |
try: |
| 1122 |
meth = aggregate.value |
| 1123 |
except AttributeError as e: |
| 1124 |
msg = (b"user-defined aggregate's 'value' " |
| 1125 |
b"method not defined") |
| 1126 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1127 |
else: |
| 1128 |
try: |
| 1129 |
val = meth() |
| 1130 |
except Exception as e: |
| 1131 |
msg = (b"user-defined aggregate's 'value' " |
| 1132 |
b"method raised error") |
| 1133 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1134 |
else: |
| 1135 |
try: |
| 1136 |
_convert_result(context, val) |
| 1137 |
except Exception as e: |
| 1138 |
msg = b"user-defined function raised exception" |
| 1139 |
set_sqlite_error(context, msg, e) |
| 1140 |
return value_callback |
| 1141 |
|
| 1142 |
def __make_inverse_callback(self, cls): |
| 1143 |
@_ffi.callback("void(sqlite3_context*, int, sqlite3_value**)") |
| 1144 |
def inverse_callback(context, argc, c_params): |
| 1145 |
res = _lib.sqlite3_aggregate_context(context, |
| 1146 |
_ffi.sizeof("size_t")) |
| 1147 |
aggregate_ptr = _ffi.cast("size_t[1]", res) |
| 1148 |
|
| 1149 |
if not aggregate_ptr[0]: |
| 1150 |
try: |
| 1151 |
aggregate = cls() |
| 1152 |
except Exception as e: |
| 1153 |
msg = (b"user-defined aggregate's '__init__' " |
| 1154 |
b"method raised error") |
| 1155 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1156 |
return |
| 1157 |
aggregate_id = id(aggregate) |
| 1158 |
self.__aggregate_instances[aggregate_id] = aggregate |
| 1159 |
aggregate_ptr[0] = aggregate_id |
| 1160 |
else: |
| 1161 |
aggregate = self.__aggregate_instances[aggregate_ptr[0]] |
| 1162 |
|
| 1163 |
try: |
| 1164 |
meth = aggregate.inverse |
| 1165 |
except AttributeError as e: |
| 1166 |
msg = (b"user-defined aggregate's 'inverse' " |
| 1167 |
b"method not defined") |
| 1168 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1169 |
else: |
| 1170 |
params = _convert_params(context, argc, c_params) |
| 1171 |
try: |
| 1172 |
meth(*params) |
| 1173 |
except Exception as e: |
| 1174 |
msg = (b"user-defined aggregate's 'inverse' " |
| 1175 |
b"method raised error") |
| 1176 |
set_sqlite_error(context, msg, e, unraisable_obj=cls) |
| 1177 |
return inverse_callback |
| 1178 |
|
| 1179 |
if _sqlite_version_triple >= (3, 36, 0): |
| 1180 |
@_check_thread_wrap |
| 1181 |
@_check_closed_wrap |
| 1182 |
def serialize(self, name="main"): |
| 1183 |
""" |
| 1184 |
name: Which database to serialize. |
| 1185 |
|
| 1186 |
Serialize a database into a byte string. |
| 1187 |
For an ordinary on-disk database file, the serialization is just a copy of the |
| 1188 |
disk file. For an in-memory database or a "temp" database, the serialization is |
| 1189 |
the same sequence of bytes which would be written to disk if that database |
| 1190 |
were backed up to disk. |
| 1191 |
""" |
| 1192 |
encname = name.encode('utf-8') |
| 1193 |
flags = _lib.SQLITE_SERIALIZE_NOCOPY |
| 1194 |
sizemem = _ffi.new('sqlite3_int64 *') |
| 1195 |
data = _lib.sqlite3_serialize(self._db, encname, sizemem, flags) |
| 1196 |
if data: |
| 1197 |
return bytes(_ffi.buffer(data, sizemem[0])) |
| 1198 |
flags &= ~_lib.SQLITE_SERIALIZE_NOCOPY |
| 1199 |
data = _lib.sqlite3_serialize(self._db, encname, sizemem, flags) |
| 1200 |
if not data: |
| 1201 |
raise OperationalError("unable to serialize '%s'" % (name, )) |
| 1202 |
try: |
| 1203 |
return bytes(_ffi.buffer(data, sizemem[0])) |
| 1204 |
finally: |
| 1205 |
_lib.sqlite3_free(data) |
| 1206 |
|
| 1207 |
@_check_thread_wrap |
| 1208 |
@_check_closed_wrap |
| 1209 |
def deserialize(self, data, name="main"): |
| 1210 |
""" |
| 1211 |
data: |
| 1212 |
The serialized database content. |
| 1213 |
name: str = "main" |
| 1214 |
Which database to reopen with the deserialization. |
| 1215 |
|
| 1216 |
Load a serialized database. |
| 1217 |
The deserialize interface causes the database connection to disconnect from the |
| 1218 |
target database, and then reopen it as an in-memory database based on the given |
| 1219 |
serialized data. |
| 1220 |
The deserialize interface will fail with SQLITE_BUSY if the database is |
| 1221 |
currently in a read transaction or is involved in a backup operation. |
| 1222 |
""" |
| 1223 |
if isinstance(data, memoryview) and not data.c_contiguous: |
| 1224 |
raise BufferError('only contiguous buffers are supported') |
| 1225 |
if isinstance(data, list): |
| 1226 |
raise TypeError("need bytes, not 'list'") |
| 1227 |
size = len(data) |
| 1228 |
buf = _lib.sqlite3_malloc64(size) |
| 1229 |
if not buf: |
| 1230 |
raise MemoryError() |
| 1231 |
_ffi.memmove(buf, data, size) |
| 1232 |
flags = _lib.SQLITE_DESERIALIZE_FREEONCLOSE | _lib.SQLITE_DESERIALIZE_RESIZEABLE |
| 1233 |
rc = _lib.sqlite3_deserialize(self._db, name.encode('utf-8'), buf, size, size, flags) |
| 1234 |
if rc != _lib.SQLITE_OK: |
| 1235 |
raise self._get_exception(rc) |
| 1236 |
|
| 1237 |
@_check_closed_and_thread_wrap |
| 1238 |
def blobopen(self, table, column, row, readonly=False, name='main'): |
| 1239 |
""" |
| 1240 |
table: str |
| 1241 |
Table name. |
| 1242 |
column: str |
| 1243 |
Column name. |
| 1244 |
row: int |
| 1245 |
Row index. |
| 1246 |
readonly = False: |
| 1247 |
Open the BLOB without write permissions. |
| 1248 |
name: str = "main" |
| 1249 |
Database name. |
| 1250 |
|
| 1251 |
Open and return a BLOB object. |
| 1252 |
""" |
| 1253 |
blob_ref = _ffi.new("sqlite3_blob **") |
| 1254 |
nameenc = name.encode('utf-8') |
| 1255 |
tableenc = table.encode('utf-8') |
| 1256 |
columnenc = column.encode('utf-8') |
| 1257 |
rc = _lib.sqlite3_blob_open( |
| 1258 |
self._db, nameenc, tableenc, columnenc, |
| 1259 |
row, not readonly, blob_ref) |
| 1260 |
if rc != _lib.SQLITE_OK: |
| 1261 |
raise self._get_exception(rc) |
| 1262 |
res = object.__new__(Blob) |
| 1263 |
res.__init__(self, blob_ref[0]) |
| 1264 |
self.__blobs.append(weakref.ref(res)) |
| 1265 |
return res |
| 1266 |
|
| 1267 |
@_check_closed_and_thread_wrap |
| 1268 |
def interrupt(self): |
| 1269 |
""" |
| 1270 |
Abort any pending database operation. |
| 1271 |
""" |
| 1272 |
_lib.sqlite3_interrupt(self._db) |
| 1273 |
|
| 1274 |
|
| 1275 |
class Cursor(object): |
| 1276 |
__initialized = False |
| 1277 |
__statement = None |
| 1278 |
__locked = False |
| 1279 |
|
| 1280 |
def __init__(self, con): |
| 1281 |
if self.__locked: |
| 1282 |
raise ProgrammingError("Recursive use of cursors not allowed.") |
| 1283 |
if not isinstance(con, Connection): |
| 1284 |
raise TypeError |
| 1285 |
self.__connection = con |
| 1286 |
|
| 1287 |
self.arraysize = 1 |
| 1288 |
self.row_factory = None |
| 1289 |
self._reset = False |
| 1290 |
self.__locked = False |
| 1291 |
self.__closed = False |
| 1292 |
self.__have_next_row = False |
| 1293 |
self.__lastrowid = None |
| 1294 |
self.__rowcount = -1 |
| 1295 |
self._connection_ref = None |
| 1296 |
|
| 1297 |
con._check_thread() |
| 1298 |
con._remember_cursor(self) |
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
self.__in_use_token = _InUseToken() |
| 1304 |
self.__initialized = True |
| 1305 |
|
| 1306 |
def __del__(self): |
| 1307 |
|
| 1308 |
if self.__statement: |
| 1309 |
self.__statement._reset(self.__in_use_token) |
| 1310 |
|
| 1311 |
def close(self): |
| 1312 |
if not self.__initialized: |
| 1313 |
raise ProgrammingError("Base Cursor.__init__ not called.") |
| 1314 |
if self.__locked: |
| 1315 |
raise ProgrammingError("Recursive use of cursors not allowed.") |
| 1316 |
self.__connection._check_thread() |
| 1317 |
self.__connection._check_closed() |
| 1318 |
if self.__statement: |
| 1319 |
self.__statement._reset(self.__in_use_token) |
| 1320 |
self.__statement = None |
| 1321 |
self.__closed = True |
| 1322 |
if self._connection_ref is not None: |
| 1323 |
self.__connection._forget_cursor(self._connection_ref) |
| 1324 |
self._connection_ref = None |
| 1325 |
|
| 1326 |
def __check_cursor(self): |
| 1327 |
if not self.__initialized: |
| 1328 |
raise ProgrammingError("Base Cursor.__init__ not called.") |
| 1329 |
if self.__closed: |
| 1330 |
raise ProgrammingError("Cannot operate on a closed cursor.") |
| 1331 |
if self.__locked: |
| 1332 |
raise ProgrammingError("Recursive use of cursors not allowed.") |
| 1333 |
self.__connection._check_thread() |
| 1334 |
self.__connection._check_closed() |
| 1335 |
|
| 1336 |
def __check_cursor_wrap(func): |
| 1337 |
@wraps(func) |
| 1338 |
def wrapper(self, *args, **kwargs): |
| 1339 |
self.__check_cursor() |
| 1340 |
return func(self, *args, **kwargs) |
| 1341 |
return wrapper |
| 1342 |
|
| 1343 |
def __check_reset(self): |
| 1344 |
if self._reset: |
| 1345 |
raise InterfaceError( |
| 1346 |
"Cursor needed to be reset because of commit/rollback " |
| 1347 |
"and can no longer be fetched from.") |
| 1348 |
|
| 1349 |
def __build_row_cast_map(self): |
| 1350 |
if not self.__connection._detect_types: |
| 1351 |
return |
| 1352 |
self.__row_cast_map = [] |
| 1353 |
for i in xrange(_lib.sqlite3_column_count(self.__statement._statement)): |
| 1354 |
converter = None |
| 1355 |
|
| 1356 |
if self.__connection._detect_types & PARSE_COLNAMES: |
| 1357 |
colname = _lib.sqlite3_column_name(self.__statement._statement, i) |
| 1358 |
if colname: |
| 1359 |
colname = _ffi.string(colname).decode('utf-8') |
| 1360 |
type_start = -1 |
| 1361 |
key = None |
| 1362 |
for pos in range(len(colname)): |
| 1363 |
if colname[pos] == '[': |
| 1364 |
type_start = pos + 1 |
| 1365 |
elif colname[pos] == ']' and type_start != -1: |
| 1366 |
key = colname[type_start:pos] |
| 1367 |
converter = converters[key.upper()] |
| 1368 |
|
| 1369 |
if converter is None and self.__connection._detect_types & PARSE_DECLTYPES: |
| 1370 |
decltype = _lib.sqlite3_column_decltype(self.__statement._statement, i) |
| 1371 |
if decltype: |
| 1372 |
decltype = _ffi.string(decltype).decode('utf-8') |
| 1373 |
|
| 1374 |
|
| 1375 |
decltype = decltype.split()[0] |
| 1376 |
if '(' in decltype: |
| 1377 |
decltype = decltype[:decltype.index('(')] |
| 1378 |
converter = converters.get(decltype.upper(), None) |
| 1379 |
|
| 1380 |
self.__row_cast_map.append(converter) |
| 1381 |
|
| 1382 |
def __fetch_one_row(self): |
| 1383 |
num_cols = _lib.sqlite3_data_count(self.__statement._statement) |
| 1384 |
row = newlist_hint(num_cols) |
| 1385 |
for i in xrange(num_cols): |
| 1386 |
if self.__connection._detect_types: |
| 1387 |
converter = self.__row_cast_map[i] |
| 1388 |
else: |
| 1389 |
converter = None |
| 1390 |
|
| 1391 |
if converter is not None: |
| 1392 |
blob = _lib.sqlite3_column_blob(self.__statement._statement, i) |
| 1393 |
if not blob: |
| 1394 |
val = None |
| 1395 |
else: |
| 1396 |
blob_len = _lib.sqlite3_column_bytes(self.__statement._statement, i) |
| 1397 |
val = _ffi.buffer(blob, blob_len)[:] |
| 1398 |
val = converter(val) |
| 1399 |
else: |
| 1400 |
typ = _lib.sqlite3_column_type(self.__statement._statement, i) |
| 1401 |
if typ == _lib.SQLITE_NULL: |
| 1402 |
val = None |
| 1403 |
elif typ == _lib.SQLITE_INTEGER: |
| 1404 |
val = _lib.sqlite3_column_int64(self.__statement._statement, i) |
| 1405 |
val = int(val) |
| 1406 |
elif typ == _lib.SQLITE_FLOAT: |
| 1407 |
val = _lib.sqlite3_column_double(self.__statement._statement, i) |
| 1408 |
elif typ == _lib.SQLITE_TEXT: |
| 1409 |
text = _lib.sqlite3_column_text(self.__statement._statement, i) |
| 1410 |
text_len = _lib.sqlite3_column_bytes(self.__statement._statement, i) |
| 1411 |
val = _ffi.buffer(text, text_len)[:] |
| 1412 |
try: |
| 1413 |
val = self.__connection.text_factory(val) |
| 1414 |
except Exception: |
| 1415 |
column_name = _lib.sqlite3_column_name( |
| 1416 |
self.__statement._statement, i) |
| 1417 |
if column_name: |
| 1418 |
column_name = _ffi.string(column_name).decode('utf-8') |
| 1419 |
else: |
| 1420 |
column_name = "<unknown column name>" |
| 1421 |
val = val.decode('ascii', 'replace') |
| 1422 |
raise OperationalError( |
| 1423 |
"Could not decode to UTF-8 column '%s' with text '%s'" % ( |
| 1424 |
column_name, val)) |
| 1425 |
elif typ == _lib.SQLITE_BLOB: |
| 1426 |
blob = _lib.sqlite3_column_blob(self.__statement._statement, i) |
| 1427 |
blob_len = _lib.sqlite3_column_bytes(self.__statement._statement, i) |
| 1428 |
val = _BLOB_TYPE(_ffi.buffer(blob, blob_len)[:]) |
| 1429 |
row.append(val) |
| 1430 |
return tuple(row) |
| 1431 |
|
| 1432 |
def __execute(self, multiple, sql, many_params): |
| 1433 |
self.__locked = True |
| 1434 |
self._reset = False |
| 1435 |
self.__have_next_row = False |
| 1436 |
try: |
| 1437 |
if not isinstance(sql, basestring): |
| 1438 |
raise TypeError("operation parameter must be str or unicode, not %s" % (type(sql).__name__, )) |
| 1439 |
try: |
| 1440 |
del self.__description |
| 1441 |
except AttributeError: |
| 1442 |
pass |
| 1443 |
self.__rowcount = -1 |
| 1444 |
if self.__statement: |
| 1445 |
self.__statement._reset(self.__in_use_token) |
| 1446 |
self.__statement = self.__connection._statement_cache.get(sql) |
| 1447 |
|
| 1448 |
if self.__connection._begin_statement and self.__statement._is_dml: |
| 1449 |
if _lib.sqlite3_get_autocommit(self.__connection._db): |
| 1450 |
self.__connection._begin() |
| 1451 |
|
| 1452 |
for params in many_params: |
| 1453 |
self.__statement._set_params(params, self.__in_use_token) |
| 1454 |
|
| 1455 |
|
| 1456 |
|
| 1457 |
ret = _lib.sqlite3_step(self.__statement._statement) |
| 1458 |
|
| 1459 |
|
| 1460 |
|
| 1461 |
|
| 1462 |
|
| 1463 |
|
| 1464 |
if ret == _lib.SQLITE_LOCKED: |
| 1465 |
self.__connection._reset_already_committed_statements() |
| 1466 |
ret = _lib.sqlite3_step(self.__statement._statement) |
| 1467 |
|
| 1468 |
if self.__statement._is_dml: |
| 1469 |
if self.__rowcount == -1: |
| 1470 |
self.__rowcount = 0 |
| 1471 |
self.__rowcount += _lib.sqlite3_changes(self.__connection._db) |
| 1472 |
else: |
| 1473 |
self.__rowcount = -1 |
| 1474 |
|
| 1475 |
if not multiple: |
| 1476 |
self.__lastrowid = _lib.sqlite3_last_insert_rowid(self.__connection._db) |
| 1477 |
|
| 1478 |
if ret == _lib.SQLITE_ROW: |
| 1479 |
if multiple: |
| 1480 |
raise ProgrammingError("executemany() can only execute DML statements.") |
| 1481 |
self.__build_row_cast_map() |
| 1482 |
self.__have_next_row = True |
| 1483 |
elif ret == _lib.SQLITE_DONE: |
| 1484 |
if not multiple: |
| 1485 |
self.__statement._reset(self.__in_use_token) |
| 1486 |
else: |
| 1487 |
self.__statement._reset(self.__in_use_token) |
| 1488 |
raise self.__connection._get_exception(ret) |
| 1489 |
|
| 1490 |
if multiple: |
| 1491 |
self.__statement._reset(self.__in_use_token) |
| 1492 |
finally: |
| 1493 |
self.__locked = False |
| 1494 |
return self |
| 1495 |
|
| 1496 |
@__check_cursor_wrap |
| 1497 |
def execute(self, sql, params=[]): |
| 1498 |
return self.__execute(False, sql, [params]) |
| 1499 |
|
| 1500 |
@__check_cursor_wrap |
| 1501 |
def executemany(self, sql, many_params): |
| 1502 |
return self.__execute(True, sql, many_params) |
| 1503 |
|
| 1504 |
def executescript(self, sql): |
| 1505 |
self.__check_cursor() |
| 1506 |
self._reset = False |
| 1507 |
if isinstance(sql, unicode): |
| 1508 |
sql = sql.encode('utf-8') |
| 1509 |
elif not isinstance(sql, str): |
| 1510 |
raise TypeError("script argument must be unicode.") |
| 1511 |
if len(sql) > _lib.sqlite3_limit(self.__connection._db, SQLITE_LIMIT_SQL_LENGTH, -1): |
| 1512 |
raise DataError("query string is too large") |
| 1513 |
if b'\x00' in sql: |
| 1514 |
raise ValueError("the query contains a null character") |
| 1515 |
statement_star = _ffi.new('sqlite3_stmt **') |
| 1516 |
next_char = _ffi.new('char **') |
| 1517 |
|
| 1518 |
self.__connection.commit() |
| 1519 |
while True: |
| 1520 |
c_sql = _ffi.new("char[]", sql) |
| 1521 |
rc = _lib.sqlite3_prepare(self.__connection._db, c_sql, -1, |
| 1522 |
statement_star, next_char) |
| 1523 |
if rc != _lib.SQLITE_OK: |
| 1524 |
raise self.__connection._get_exception(rc) |
| 1525 |
|
| 1526 |
rc = _lib.SQLITE_ROW |
| 1527 |
while rc == _lib.SQLITE_ROW: |
| 1528 |
if not statement_star[0]: |
| 1529 |
rc = _lib.SQLITE_OK |
| 1530 |
else: |
| 1531 |
rc = _lib.sqlite3_step(statement_star[0]) |
| 1532 |
|
| 1533 |
if rc != _lib.SQLITE_DONE: |
| 1534 |
_lib.sqlite3_finalize(statement_star[0]) |
| 1535 |
if rc == _lib.SQLITE_OK: |
| 1536 |
break |
| 1537 |
else: |
| 1538 |
raise self.__connection._get_exception(rc) |
| 1539 |
|
| 1540 |
rc = _lib.sqlite3_finalize(statement_star[0]) |
| 1541 |
if rc != _lib.SQLITE_OK: |
| 1542 |
raise self.__connection._get_exception(rc) |
| 1543 |
|
| 1544 |
sql = _ffi.string(next_char[0]) |
| 1545 |
if not sql: |
| 1546 |
break |
| 1547 |
return self |
| 1548 |
|
| 1549 |
def __iter__(self): |
| 1550 |
return self |
| 1551 |
|
| 1552 |
def __next__(self): |
| 1553 |
self.__check_cursor() |
| 1554 |
self.__check_reset() |
| 1555 |
if not self.__statement: |
| 1556 |
raise StopIteration |
| 1557 |
if not self.__have_next_row: |
| 1558 |
raise StopIteration |
| 1559 |
|
| 1560 |
assert not self.__locked |
| 1561 |
self.__locked = True |
| 1562 |
try: |
| 1563 |
next_row = self.__fetch_one_row() |
| 1564 |
finally: |
| 1565 |
self.__locked = False |
| 1566 |
if self.row_factory is not None: |
| 1567 |
next_row = self.row_factory(self, next_row) |
| 1568 |
|
| 1569 |
ret = _lib.sqlite3_step(self.__statement._statement) |
| 1570 |
if ret == _lib.SQLITE_ROW: |
| 1571 |
self.__have_next_row = True |
| 1572 |
else: |
| 1573 |
self.__have_next_row = False |
| 1574 |
self.__statement._reset(self.__in_use_token) |
| 1575 |
if ret != _lib.SQLITE_DONE: |
| 1576 |
raise self.__connection._get_exception(ret) |
| 1577 |
return next_row |
| 1578 |
|
| 1579 |
if sys.version_info[0] < 3: |
| 1580 |
next = __next__ |
| 1581 |
del __next__ |
| 1582 |
|
| 1583 |
def fetchone(self): |
| 1584 |
return next(self, None) |
| 1585 |
|
| 1586 |
def fetchmany(self, size=None): |
| 1587 |
if size is None: |
| 1588 |
size = self.arraysize |
| 1589 |
lst = [] |
| 1590 |
for row in self: |
| 1591 |
lst.append(row) |
| 1592 |
if len(lst) == size: |
| 1593 |
break |
| 1594 |
return lst |
| 1595 |
|
| 1596 |
def fetchall(self): |
| 1597 |
return list(self) |
| 1598 |
|
| 1599 |
def __get_connection(self): |
| 1600 |
self.__check_cursor() |
| 1601 |
return self.__connection |
| 1602 |
connection = property(__get_connection) |
| 1603 |
|
| 1604 |
def __get_rowcount(self): |
| 1605 |
return self.__rowcount |
| 1606 |
rowcount = property(__get_rowcount) |
| 1607 |
|
| 1608 |
def __get_description(self): |
| 1609 |
try: |
| 1610 |
return self.__description |
| 1611 |
except AttributeError: |
| 1612 |
if not self.__statement: |
| 1613 |
return None |
| 1614 |
statement = self.__statement |
| 1615 |
if not statement._valid: |
| 1616 |
return None |
| 1617 |
|
| 1618 |
numcols = _lib.sqlite3_column_count(statement._statement) |
| 1619 |
if numcols <= 0: |
| 1620 |
self.__description = None |
| 1621 |
return None |
| 1622 |
desc = [] |
| 1623 |
for i in xrange(numcols): |
| 1624 |
name = _lib.sqlite3_column_name(statement._statement, i) |
| 1625 |
if name: |
| 1626 |
name = _ffi.string(name).decode('utf-8') |
| 1627 |
if self.__connection._detect_types & PARSE_COLNAMES: |
| 1628 |
name = name.split("[", 1)[0].strip() |
| 1629 |
desc.append((name, None, None, None, None, None, None)) |
| 1630 |
self.__description = tuple(desc) |
| 1631 |
return self.__description |
| 1632 |
description = property(__get_description) |
| 1633 |
|
| 1634 |
def __get_lastrowid(self): |
| 1635 |
return self.__lastrowid |
| 1636 |
lastrowid = property(__get_lastrowid) |
| 1637 |
|
| 1638 |
def setinputsizes(self, *args): |
| 1639 |
pass |
| 1640 |
|
| 1641 |
def setoutputsize(self, *args): |
| 1642 |
pass |
| 1643 |
|
| 1644 |
class _InUseToken(object): |
| 1645 |
__slots__ = () |
| 1646 |
|
| 1647 |
class Statement(object): |
| 1648 |
_statement = None |
| 1649 |
|
| 1650 |
def __init__(self, connection, sql): |
| 1651 |
self.__con = connection |
| 1652 |
|
| 1653 |
self._in_use_token = None |
| 1654 |
|
| 1655 |
if not isinstance(sql, basestring): |
| 1656 |
raise TypeError("sql argument must be str, not %s" % (type(sql).__name__, )) |
| 1657 |
if '\0' in sql: |
| 1658 |
raise ProgrammingError("the query contains a null character") |
| 1659 |
|
| 1660 |
to_check = _sql_lstrip_comments(sql).upper() |
| 1661 |
self._valid = bool(to_check) |
| 1662 |
self._is_dml = to_check.startswith(('INSERT', 'UPDATE', 'DELETE', 'REPLACE')) |
| 1663 |
|
| 1664 |
statement_star = _ffi.new('sqlite3_stmt **') |
| 1665 |
next_char = _ffi.new('char **') |
| 1666 |
encoded = sql.encode('utf-8') |
| 1667 |
if len(encoded) > _lib.sqlite3_limit(self.__con._db, SQLITE_LIMIT_SQL_LENGTH, -1): |
| 1668 |
raise DataError("query string is too large") |
| 1669 |
c_sql = _ffi.new("char[]", encoded) |
| 1670 |
ret = _lib.sqlite3_prepare_v2(self.__con._db, c_sql, -1, |
| 1671 |
statement_star, next_char) |
| 1672 |
self._statement = statement_star[0] |
| 1673 |
|
| 1674 |
if ret == _lib.SQLITE_OK and not self._statement: |
| 1675 |
|
| 1676 |
c_sql = _ffi.new("char[]", b"select 42 where 42 = 23") |
| 1677 |
ret = _lib.sqlite3_prepare_v2(self.__con._db, c_sql, -1, |
| 1678 |
statement_star, next_char) |
| 1679 |
self._statement = statement_star[0] |
| 1680 |
self._valid = False |
| 1681 |
|
| 1682 |
if ret != _lib.SQLITE_OK: |
| 1683 |
raise self.__con._get_exception(ret) |
| 1684 |
|
| 1685 |
self.__con._remember_statement(self) |
| 1686 |
|
| 1687 |
tail = _ffi.string(next_char[0]).decode('utf-8') |
| 1688 |
if _sql_lstrip_comments(tail): |
| 1689 |
raise ProgrammingError("You can only execute one statement at a time.") |
| 1690 |
|
| 1691 |
def __new__(cls, *args): |
| 1692 |
raise TypeError("cannot create '_sqlite3.Statement' instances") |
| 1693 |
|
| 1694 |
def __del__(self): |
| 1695 |
if self._statement: |
| 1696 |
self.__con._finalize_raw_statement(self._statement) |
| 1697 |
|
| 1698 |
def _finalize(self): |
| 1699 |
if self._statement: |
| 1700 |
self.__con._finalize_raw_statement(self._statement) |
| 1701 |
self._statement = None |
| 1702 |
self._in_use_token = None |
| 1703 |
|
| 1704 |
def _reset(self, token): |
| 1705 |
assert isinstance(token, _InUseToken) |
| 1706 |
if self._in_use_token is token and self._statement: |
| 1707 |
_lib.sqlite3_reset(self._statement) |
| 1708 |
self._in_use_token = None |
| 1709 |
|
| 1710 |
def _force_reset(self): |
| 1711 |
if self._in_use_token and self._statement: |
| 1712 |
_lib.sqlite3_reset(self._statement) |
| 1713 |
self._in_use_token = None |
| 1714 |
|
| 1715 |
def __set_param(self, idx, param): |
| 1716 |
typ = type(param) |
| 1717 |
if BASE_TYPE_ADAPTED or ( |
| 1718 |
typ is not bytearray |
| 1719 |
and typ is not bytes |
| 1720 |
and typ is not float |
| 1721 |
and typ is not int |
| 1722 |
and typ is not str |
| 1723 |
and typ is not NoneType |
| 1724 |
): |
| 1725 |
param = _adapt(param) |
| 1726 |
|
| 1727 |
if param is None: |
| 1728 |
rc = _lib.sqlite3_bind_null(self._statement, idx) |
| 1729 |
elif isinstance(param, (bool, int, long)): |
| 1730 |
if -2147483648 <= param <= 2147483647: |
| 1731 |
rc = _lib.sqlite3_bind_int(self._statement, idx, param) |
| 1732 |
else: |
| 1733 |
try: |
| 1734 |
rc = _lib.sqlite3_bind_int64(self._statement, idx, param) |
| 1735 |
except OverflowError: |
| 1736 |
raise OverflowError( |
| 1737 |
"Python int too large to convert to SQLite INTEGER" |
| 1738 |
) |
| 1739 |
elif isinstance(param, float): |
| 1740 |
rc = _lib.sqlite3_bind_double(self._statement, idx, param) |
| 1741 |
elif isinstance(param, str): |
| 1742 |
param = param.encode("utf-8") |
| 1743 |
rc = _lib.sqlite3_bind_text(self._statement, idx, param, |
| 1744 |
len(param), _SQLITE_TRANSIENT) |
| 1745 |
elif isinstance(param, (buffer, bytes, bytearray)): |
| 1746 |
if isinstance(param, buffer) and not param.c_contiguous: |
| 1747 |
raise BufferError('underlying buffer is not C-contiguous') |
| 1748 |
param = bytes(param) |
| 1749 |
rc = _lib.sqlite3_bind_blob(self._statement, idx, param, |
| 1750 |
len(param), _SQLITE_TRANSIENT) |
| 1751 |
else: |
| 1752 |
rc = _UNSUPPORTED_TYPE |
| 1753 |
return rc |
| 1754 |
|
| 1755 |
def _set_params(self, params, token): |
| 1756 |
assert isinstance(token, _InUseToken) |
| 1757 |
self._in_use_token = token |
| 1758 |
|
| 1759 |
num_params_needed = _lib.sqlite3_bind_parameter_count(self._statement) |
| 1760 |
if isinstance(params, (tuple, list)) or \ |
| 1761 |
not isinstance(params, dict) and \ |
| 1762 |
hasattr(params, '__getitem__'): |
| 1763 |
try: |
| 1764 |
num_params = len(params) |
| 1765 |
except TypeError: |
| 1766 |
num_params = -1 |
| 1767 |
if num_params != num_params_needed: |
| 1768 |
raise ProgrammingError("Incorrect number of bindings supplied. " |
| 1769 |
"The current statement uses %d, and " |
| 1770 |
"there are %d supplied." % |
| 1771 |
(num_params_needed, num_params)) |
| 1772 |
for i in range(num_params): |
| 1773 |
rc = self.__set_param(i + 1, params[i]) |
| 1774 |
if rc is _UNSUPPORTED_TYPE: |
| 1775 |
raise ProgrammingError("Error binding parameter %d - " |
| 1776 |
"Type '%s' is not supported." % |
| 1777 |
(i, type(params[i]).__name__)) |
| 1778 |
if rc != _lib.SQLITE_OK: |
| 1779 |
raise self.__con._get_exception(rc) |
| 1780 |
elif isinstance(params, dict): |
| 1781 |
for i in range(1, num_params_needed + 1): |
| 1782 |
param_name = _lib.sqlite3_bind_parameter_name(self._statement, i) |
| 1783 |
if not param_name: |
| 1784 |
raise ProgrammingError("Binding %d has no name, but you " |
| 1785 |
"supplied a dictionary (which has " |
| 1786 |
"only names)." % i) |
| 1787 |
param_name = _ffi.string(param_name).decode('utf-8')[1:] |
| 1788 |
try: |
| 1789 |
param = params[param_name] |
| 1790 |
except KeyError: |
| 1791 |
raise ProgrammingError("You did not supply a value for " |
| 1792 |
"binding %d." % i) |
| 1793 |
rc = self.__set_param(i, param) |
| 1794 |
if rc is _UNSUPPORTED_TYPE: |
| 1795 |
raise ProgrammingError("Error binding parameter :%s - " |
| 1796 |
"Type '%s' is not supported." % |
| 1797 |
(param_name, type(param).__name__)) |
| 1798 |
if rc != _lib.SQLITE_OK: |
| 1799 |
raise self.__con._get_exception(rc) |
| 1800 |
else: |
| 1801 |
raise ProgrammingError("parameters are of unsupported type") |
| 1802 |
|
| 1803 |
|
| 1804 |
class Row(object): |
| 1805 |
def __init__(self, cursor, values): |
| 1806 |
if not (type(cursor) is Cursor or issubclass(type(cursor), Cursor)): |
| 1807 |
raise TypeError("instance of cursor required for first argument") |
| 1808 |
self.description = cursor.description |
| 1809 |
self.values = values |
| 1810 |
|
| 1811 |
def __len__(self): |
| 1812 |
return len(self.values) |
| 1813 |
|
| 1814 |
def __getitem__(self, item): |
| 1815 |
if isinstance(item, (int, long)): |
| 1816 |
return self.values[item] |
| 1817 |
elif isinstance(item, slice): |
| 1818 |
return self.values[item] |
| 1819 |
elif isinstance(item, str): |
| 1820 |
for idx, desc in enumerate(self.description): |
| 1821 |
|
| 1822 |
|
| 1823 |
if desc[0] == item: |
| 1824 |
return self.values[idx] |
| 1825 |
if not desc[0].isascii() or not item.isascii(): |
| 1826 |
continue |
| 1827 |
if desc[0].lower() == item.lower(): |
| 1828 |
return self.values[idx] |
| 1829 |
raise IndexError("No item with that key") |
| 1830 |
raise IndexError(f"index must be int or string, not '{type(item).__name__}'") |
| 1831 |
|
| 1832 |
def keys(self): |
| 1833 |
return [desc[0] for desc in self.description] |
| 1834 |
|
| 1835 |
def __eq__(self, other): |
| 1836 |
if not isinstance(other, Row): |
| 1837 |
return NotImplemented |
| 1838 |
if self.description != other.description: |
| 1839 |
return False |
| 1840 |
if self.values != other.values: |
| 1841 |
return False |
| 1842 |
return True |
| 1843 |
|
| 1844 |
def __ne__(self, other): |
| 1845 |
return not self == other |
| 1846 |
|
| 1847 |
def __hash__(self): |
| 1848 |
return hash(tuple(self.description)) ^ hash(tuple(self.values)) |
| 1849 |
|
| 1850 |
_INT_MIN = -2**(struct.calcsize('i') * 8 - 1) |
| 1851 |
_INT_MAX = ~_INT_MIN |
| 1852 |
|
| 1853 |
class Blob(object): |
| 1854 |
def __new__(self, *args, **kwargs): |
| 1855 |
raise TypeError("cannot create '_sqlite3.Blob' instances") |
| 1856 |
|
| 1857 |
def __init__(self, con, blob): |
| 1858 |
if not isinstance(con, Connection): |
| 1859 |
raise TypeError |
| 1860 |
self.__connection = con |
| 1861 |
self.__blob = blob |
| 1862 |
self.__offset = 0 |
| 1863 |
|
| 1864 |
def _check(self): |
| 1865 |
self.__connection._check_closed() |
| 1866 |
self.__connection._check_thread() |
| 1867 |
if not self.__blob: |
| 1868 |
raise ProgrammingError("Cannot operate on a closed blob") |
| 1869 |
|
| 1870 |
def __del__(self): |
| 1871 |
self.close() |
| 1872 |
|
| 1873 |
def close(self): |
| 1874 |
""" Close the blob. """ |
| 1875 |
if self.__blob: |
| 1876 |
_lib.sqlite3_blob_close(self.__blob) |
| 1877 |
self.__blob = _ffi.NULL |
| 1878 |
|
| 1879 |
def read(self, length=-1): |
| 1880 |
""" |
| 1881 |
length: int = -1 |
| 1882 |
Read length in bytes. |
| 1883 |
|
| 1884 |
Read data at the current offset position. |
| 1885 |
If the end of the blob is reached, the data up to end of file will be returned. |
| 1886 |
When length is not specified, or is negative, Blob.read() will read until the |
| 1887 |
end of the blob. |
| 1888 |
""" |
| 1889 |
self._check() |
| 1890 |
|
| 1891 |
|
| 1892 |
blob_len = _lib.sqlite3_blob_bytes(self.__blob) |
| 1893 |
max_read_len = blob_len - self.__offset |
| 1894 |
if length < 0 or length > max_read_len: |
| 1895 |
length = max_read_len |
| 1896 |
buffer = self.__inner_read(length, self.__offset) |
| 1897 |
self.__offset += length |
| 1898 |
return buffer |
| 1899 |
|
| 1900 |
def __inner_read(self, length, offset): |
| 1901 |
raw_buffer = _ffi.new("char[]", length) |
| 1902 |
rc = _lib.sqlite3_blob_read(self.__blob, raw_buffer, length, offset) |
| 1903 |
if rc != _lib.SQLITE_OK: |
| 1904 |
raise self.__connection._get_exception(rc) |
| 1905 |
return _ffi.buffer(raw_buffer, length)[:] |
| 1906 |
|
| 1907 |
def write(self, data): |
| 1908 |
""" |
| 1909 |
data: Py_buffer |
| 1910 |
|
| 1911 |
Write data at the current offset. |
| 1912 |
|
| 1913 |
This function cannot change the blob length. Writing beyond the end of the |
| 1914 |
blob will result in an exception being raised. |
| 1915 |
""" |
| 1916 |
self._check() |
| 1917 |
self.__inner_write(data, self.__offset) |
| 1918 |
self.__offset += len(data) |
| 1919 |
|
| 1920 |
def __inner_write(self, data, offset): |
| 1921 |
blob_len = _lib.sqlite3_blob_bytes(self.__blob) |
| 1922 |
remaining_len = blob_len - offset |
| 1923 |
if len(data) > remaining_len: |
| 1924 |
raise ValueError("data longer than blob length") |
| 1925 |
rc = _lib.sqlite3_blob_write(self.__blob, _ffi.from_buffer(data), |
| 1926 |
len(data), offset) |
| 1927 |
if rc != _lib.SQLITE_OK: |
| 1928 |
raise self.__connection._get_exception(rc) |
| 1929 |
|
| 1930 |
def seek(self, offset, origin=0): |
| 1931 |
""" |
| 1932 |
offset: int |
| 1933 |
origin: int = 0 |
| 1934 |
|
| 1935 |
Set the current access position to offset. |
| 1936 |
|
| 1937 |
The origin argument defaults to os.SEEK_SET (absolute blob positioning). |
| 1938 |
Other values for origin are os.SEEK_CUR (seek relative to the current position) |
| 1939 |
and os.SEEK_END (seek relative to the blob's end). |
| 1940 |
""" |
| 1941 |
self._check() |
| 1942 |
blob_len = _lib.sqlite3_blob_bytes(self.__blob) |
| 1943 |
offset = operator.index(offset) |
| 1944 |
if origin == 0: |
| 1945 |
pass |
| 1946 |
elif origin == os.SEEK_CUR: |
| 1947 |
offset += self.__offset |
| 1948 |
elif origin == os.SEEK_END: |
| 1949 |
offset += blob_len |
| 1950 |
else: |
| 1951 |
raise ValueError("'origin' should be os.SEEK_SET, os.SEEK_CUR, or " |
| 1952 |
"os.SEEK_END") |
| 1953 |
if not 0 <= offset <= blob_len: |
| 1954 |
if not _INT_MIN <= offset <= _INT_MAX: |
| 1955 |
raise OverflowError('seek offset results in overflow') |
| 1956 |
raise ValueError("offset out of blob range") |
| 1957 |
self.__offset = offset |
| 1958 |
|
| 1959 |
def tell(self): |
| 1960 |
""" Return the current access position for the blob.""" |
| 1961 |
self._check() |
| 1962 |
return self.__offset |
| 1963 |
|
| 1964 |
def __getitem__(self, item): |
| 1965 |
self._check() |
| 1966 |
blob_len = _lib.sqlite3_blob_bytes(self.__blob) |
| 1967 |
if isinstance(item, slice): |
| 1968 |
start, stop, stride = item.indices(blob_len) |
| 1969 |
length = len(range(start, stop, stride)) |
| 1970 |
if stride == 1: |
| 1971 |
readlen = length |
| 1972 |
else: |
| 1973 |
readlen = stop - start |
| 1974 |
raw_buffer = _ffi.new("char[]", readlen) |
| 1975 |
rc = _lib.sqlite3_blob_read(self.__blob, raw_buffer, readlen, start) |
| 1976 |
if rc != _lib.SQLITE_OK: |
| 1977 |
raise self.__connection._get_exception(rc) |
| 1978 |
return _ffi.buffer(raw_buffer, readlen)[::stride] |
| 1979 |
else: |
| 1980 |
offset = operator.index(item) |
| 1981 |
if offset < 0: |
| 1982 |
offset += blob_len |
| 1983 |
if not 0 <= offset < blob_len: |
| 1984 |
if offset > _INT_MAX: |
| 1985 |
raise IndexError("cannot fit 'int'") |
| 1986 |
raise IndexError("index out of range") |
| 1987 |
raw_buffer = _ffi.new("char[]", 1) |
| 1988 |
rc = _lib.sqlite3_blob_read(self.__blob, raw_buffer, 1, offset) |
| 1989 |
if rc != _lib.SQLITE_OK: |
| 1990 |
raise self.__connection._get_exception(rc) |
| 1991 |
return _ffi.buffer(raw_buffer, 1)[0][0] |
| 1992 |
|
| 1993 |
def __setitem__(self, item, value): |
| 1994 |
self._check() |
| 1995 |
blob_len = _lib.sqlite3_blob_bytes(self.__blob) |
| 1996 |
if isinstance(item, slice): |
| 1997 |
start, stop, stride = item.indices(blob_len) |
| 1998 |
length = len(range(start, stop, stride)) |
| 1999 |
if length != len(value): |
| 2000 |
raise IndexError("Blob slice assignment is wrong size") |
| 2001 |
if stride == 1: |
| 2002 |
rc = _lib.sqlite3_blob_write(self.__blob, _ffi.from_buffer(value), |
| 2003 |
len(value), start) |
| 2004 |
if rc != _lib.SQLITE_OK: |
| 2005 |
raise self.__connection._get_exception(rc) |
| 2006 |
else: |
| 2007 |
readlen = stop - start |
| 2008 |
raw_buffer = _ffi.new("unsigned char[]", readlen) |
| 2009 |
rc = _lib.sqlite3_blob_read(self.__blob, raw_buffer, readlen, start) |
| 2010 |
if rc != _lib.SQLITE_OK: |
| 2011 |
raise self.__connection._get_exception(rc) |
| 2012 |
|
| 2013 |
j = 0 |
| 2014 |
for i in range(0, readlen, stride): |
| 2015 |
raw_buffer[i] = value[j] |
| 2016 |
j += 1 |
| 2017 |
rc = _lib.sqlite3_blob_write(self.__blob, raw_buffer, |
| 2018 |
readlen, start) |
| 2019 |
if rc != _lib.SQLITE_OK: |
| 2020 |
raise self.__connection._get_exception(rc) |
| 2021 |
else: |
| 2022 |
offset = operator.index(item) |
| 2023 |
value = operator.index(value) |
| 2024 |
if offset < 0: |
| 2025 |
offset += blob_len |
| 2026 |
if not 0 <= offset < blob_len: |
| 2027 |
raise IndexError("Blob index out of range") |
| 2028 |
if not 0 <= value < 256: |
| 2029 |
raise ValueError("byte must be in range(0, 256)") |
| 2030 |
data = _ffi.new('unsigned char[1]') |
| 2031 |
data[0] = value |
| 2032 |
rc = _lib.sqlite3_blob_write(self.__blob, data, len(data), offset) |
| 2033 |
if rc != _lib.SQLITE_OK: |
| 2034 |
raise self.__connection._get_exception(rc) |
| 2035 |
|
| 2036 |
|
| 2037 |
def __iter__(self): |
| 2038 |
raise TypeError("blob is not iterable") |
| 2039 |
|
| 2040 |
def __enter__(self): |
| 2041 |
self._check() |
| 2042 |
return self |
| 2043 |
|
| 2044 |
def __exit__(self, typ, val, tb): |
| 2045 |
self._check() |
| 2046 |
self.close() |
| 2047 |
return False |
| 2048 |
|
| 2049 |
def __len__(self): |
| 2050 |
self._check() |
| 2051 |
return _lib.sqlite3_blob_bytes(self.__blob) |
| 2052 |
|
| 2053 |
def _sql_lstrip_comments(s): |
| 2054 |
index = 0 |
| 2055 |
while index < len(s): |
| 2056 |
char = s[index] |
| 2057 |
index += 1 |
| 2058 |
if char in ' \t\f\n\r': |
| 2059 |
continue |
| 2060 |
elif char == '-': |
| 2061 |
|
| 2062 |
if index < len(s) and s[index] == '-': |
| 2063 |
while index < len(s): |
| 2064 |
char = s[index] |
| 2065 |
index += 1 |
| 2066 |
if char == '\n': |
| 2067 |
break |
| 2068 |
if index == len(s): |
| 2069 |
return '' |
| 2070 |
continue |
| 2071 |
elif char == '/': |
| 2072 |
|
| 2073 |
if index < len(s) and s[index] == '*': |
| 2074 |
while index < len(s): |
| 2075 |
char = s[index] |
| 2076 |
index += 1 |
| 2077 |
if char == '*' and index < len(s) and s[index] == '/': |
| 2078 |
index += 1 |
| 2079 |
break |
| 2080 |
continue |
| 2081 |
return s[index-1:] |
| 2082 |
return '' |
| 2083 |
|
| 2084 |
|
| 2085 |
def _convert_params(con, nargs, params): |
| 2086 |
_params = [] |
| 2087 |
for i in range(nargs): |
| 2088 |
typ = _lib.sqlite3_value_type(params[i]) |
| 2089 |
if typ == _lib.SQLITE_NULL: |
| 2090 |
val = None |
| 2091 |
elif typ == _lib.SQLITE_INTEGER: |
| 2092 |
val = _lib.sqlite3_value_int64(params[i]) |
| 2093 |
val = int(val) |
| 2094 |
elif typ == _lib.SQLITE_FLOAT: |
| 2095 |
val = _lib.sqlite3_value_double(params[i]) |
| 2096 |
elif typ == _lib.SQLITE_TEXT: |
| 2097 |
val = _lib.sqlite3_value_text(params[i]) |
| 2098 |
length = _lib.sqlite3_value_bytes(params[i]) |
| 2099 |
val = _ffi.buffer(val, length)[:].decode('utf-8') |
| 2100 |
elif typ == _lib.SQLITE_BLOB: |
| 2101 |
blob = _lib.sqlite3_value_blob(params[i]) |
| 2102 |
blob_len = _lib.sqlite3_value_bytes(params[i]) |
| 2103 |
val = _BLOB_TYPE(_ffi.buffer(blob, blob_len)[:]) |
| 2104 |
else: |
| 2105 |
raise NotImplementedError |
| 2106 |
_params.append(val) |
| 2107 |
return _params |
| 2108 |
|
| 2109 |
|
| 2110 |
def _convert_result(con, val): |
| 2111 |
if val is None: |
| 2112 |
_lib.sqlite3_result_null(con) |
| 2113 |
elif isinstance(val, (bool, int, long)): |
| 2114 |
_lib.sqlite3_result_int64(con, int(val)) |
| 2115 |
elif isinstance(val, float): |
| 2116 |
_lib.sqlite3_result_double(con, val) |
| 2117 |
elif isinstance(val, str): |
| 2118 |
val = val.encode('utf-8') |
| 2119 |
_lib.sqlite3_result_text(con, val, len(val), _SQLITE_TRANSIENT) |
| 2120 |
elif isinstance(val, (buffer, bytes)): |
| 2121 |
if isinstance(val, buffer) and not val.c_contiguous: |
| 2122 |
raise BufferError('underlying buffer is not C-contiguous') |
| 2123 |
_lib.sqlite3_result_blob(con, bytes(val), len(val), _SQLITE_TRANSIENT) |
| 2124 |
else: |
| 2125 |
raise NotImplementedError |
| 2126 |
|
| 2127 |
def set_sqlite_error(context, msg, exc, unraisable_obj=None): |
| 2128 |
"""internal function to set sqlite3 error and maybe raise an exception |
| 2129 |
msg is bytes |
| 2130 |
""" |
| 2131 |
if isinstance(exc, MemoryError): |
| 2132 |
_lib.sqlite3_result_error_nomem(context) |
| 2133 |
elif isinstance(exc, OverflowError): |
| 2134 |
_lib.sqlite3_result_error_toobig(context) |
| 2135 |
else: |
| 2136 |
_lib.sqlite3_result_error(context, msg, len(msg)) |
| 2137 |
if unraisable_obj is None: |
| 2138 |
unraisable_obj = context |
| 2139 |
print_or_clear_traceback(unraisable_obj, exc) |
| 2140 |
|
| 2141 |
def print_or_clear_traceback(ctx, exc): |
| 2142 |
"""the function name matches CPython, but the functionality is a bit |
| 2143 |
different: there is no need to clear the excption |
| 2144 |
""" |
| 2145 |
if _enable_callback_tracebacks[0]: |
| 2146 |
import __pypy__ |
| 2147 |
try: |
| 2148 |
__pypy__.write_unraisable('in sqlite3 callback', exc, ctx) |
| 2149 |
except Exception as e: |
| 2150 |
|
| 2151 |
print(e, file=sys.stderr) |
| 2152 |
|
| 2153 |
def _function_callback(real_cb, context, nargs, c_params): |
| 2154 |
params = _convert_params(context, nargs, c_params) |
| 2155 |
try: |
| 2156 |
val = real_cb(*params) |
| 2157 |
except Exception as e: |
| 2158 |
msg = b"user-defined function raised exception" |
| 2159 |
set_sqlite_error(context, msg, e, unraisable_obj=real_cb) |
| 2160 |
else: |
| 2161 |
try: |
| 2162 |
_convert_result(context, val) |
| 2163 |
except Exception as e: |
| 2164 |
msg = b"user-defined function raised exception" |
| 2165 |
set_sqlite_error(context, msg, e, unraisable_obj=real_cb) |
| 2166 |
|
| 2167 |
converters = {} |
| 2168 |
adapters = {} |
| 2169 |
_enable_callback_tracebacks = [0] |
| 2170 |
|
| 2171 |
|
| 2172 |
class PrepareProtocol(object): |
| 2173 |
pass |
| 2174 |
|
| 2175 |
|
| 2176 |
def register_adapter(typ, callable): |
| 2177 |
global BASE_TYPE_ADAPTED |
| 2178 |
|
| 2179 |
if typ in BASE_TYPES: |
| 2180 |
BASE_TYPE_ADAPTED = True |
| 2181 |
|
| 2182 |
adapters[typ, PrepareProtocol] = callable |
| 2183 |
|
| 2184 |
|
| 2185 |
def register_converter(name, callable): |
| 2186 |
converters[name.upper()] = callable |
| 2187 |
|
| 2188 |
|
| 2189 |
def register_adapters_and_converters(): |
| 2190 |
def adapt_date(val): |
| 2191 |
return val.isoformat() |
| 2192 |
|
| 2193 |
def adapt_datetime(val): |
| 2194 |
return val.isoformat(" ") |
| 2195 |
|
| 2196 |
def convert_date(val): |
| 2197 |
return datetime.date(*map(int, val.split("-"))) |
| 2198 |
|
| 2199 |
def convert_timestamp(val): |
| 2200 |
datepart, timepart = val.split(" ") |
| 2201 |
year, month, day = map(int, datepart.split("-")) |
| 2202 |
timepart_full = timepart.split(".") |
| 2203 |
hours, minutes, seconds = map(int, timepart_full[0].split(":")) |
| 2204 |
if len(timepart_full) == 2: |
| 2205 |
microseconds = int(timepart_full[1]) |
| 2206 |
else: |
| 2207 |
microseconds = 0 |
| 2208 |
return datetime.datetime(year, month, day, hours, minutes, seconds, |
| 2209 |
microseconds) |
| 2210 |
|
| 2211 |
register_adapter(datetime.date, adapt_date) |
| 2212 |
register_adapter(datetime.datetime, adapt_datetime) |
| 2213 |
register_converter("date", convert_date) |
| 2214 |
register_converter("timestamp", convert_timestamp) |
| 2215 |
|
| 2216 |
|
| 2217 |
SENTINEL = object() |
| 2218 |
|
| 2219 |
def adapt(val, proto=PrepareProtocol, alt=SENTINEL): |
| 2220 |
return _adapt(val, proto, alt, raise_=True) |
| 2221 |
|
| 2222 |
def _adapt(val, proto=PrepareProtocol, alt=SENTINEL, raise_=False): |
| 2223 |
|
| 2224 |
adapter = adapters.get((type(val), proto), None) |
| 2225 |
if adapter is not None: |
| 2226 |
return adapter(val) |
| 2227 |
|
| 2228 |
|
| 2229 |
if hasattr(proto, '__adapt__'): |
| 2230 |
try: |
| 2231 |
adapted = proto.__adapt__(val) |
| 2232 |
except TypeError: |
| 2233 |
pass |
| 2234 |
else: |
| 2235 |
if adapted is not None: |
| 2236 |
return adapted |
| 2237 |
|
| 2238 |
|
| 2239 |
if hasattr(val, '__conform__'): |
| 2240 |
try: |
| 2241 |
adapted = val.__conform__(proto) |
| 2242 |
except TypeError: |
| 2243 |
pass |
| 2244 |
else: |
| 2245 |
if adapted is not None: |
| 2246 |
return adapted |
| 2247 |
if alt is not SENTINEL: |
| 2248 |
return alt |
| 2249 |
if raise_: |
| 2250 |
raise ProgrammingError("can't adapt") |
| 2251 |
return val |
| 2252 |
|
| 2253 |
def enable_shared_cache(enable): |
| 2254 |
raise OperationalError("enable_shared_cache not supported on PyPy (and it's deprecated anyway)") |
| 2255 |
|
| 2256 |
def complete_statement(statement=None): |
| 2257 |
"""Checks if a string contains a complete SQL statement. |
| 2258 |
""" |
| 2259 |
if not statement: |
| 2260 |
raise TypeError("complete_statement missing required argument 'statement' (pos 1)") |
| 2261 |
if not isinstance(statement, str): |
| 2262 |
raise TypeError(f"complete_statement() argument 'statement' must be str, not {type(statement)}") |
| 2263 |
ret = _lib.sqlite3_complete(statement.encode('utf-8')) |
| 2264 |
return bool(ret) |
| 2265 |
|
| 2266 |
def enable_callback_tracebacks(enable, /): |
| 2267 |
"""Enable or disable callback functions throwing errors to stderr. |
| 2268 |
""" |
| 2269 |
_enable_callback_tracebacks[0] = int(enable) |
| 2270 |
|
| 2271 |
|
| 2272 |
register_adapters_and_converters() |
| 2273 |
|
| 2274 |
threadsafety = [0, 3, 1][_lib.sqlite3_threadsafe()] |
| 2275 |
|