PageRenderTime 75ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib_pypy/_sqlite3.py

https://bitbucket.org/dac_io/pypy
Python | 1365 lines | 1225 code | 99 blank | 41 comment | 130 complexity | d987c64d415a55b704623d13c49a7c35 MD5 | raw file
  1. #-*- coding: utf-8 -*-
  2. # pysqlite2/dbapi.py: pysqlite DB-API module
  3. #
  4. # Copyright (C) 2007-2008 Gerhard ¤ring <gh@ghaering.de>
  5. #
  6. # This file is part of pysqlite.
  7. #
  8. # This software is provided 'as-is', without any express or implied
  9. # warranty. In no event will the authors be held liable for any damages
  10. # arising from the use of this software.
  11. #
  12. # Permission is granted to anyone to use this software for any purpose,
  13. # including commercial applications, and to alter it and redistribute it
  14. # freely, subject to the following restrictions:
  15. #
  16. # 1. The origin of this software must not be misrepresented; you must not
  17. # claim that you wrote the original software. If you use this software
  18. # in a product, an acknowledgment in the product documentation would be
  19. # appreciated but is not required.
  20. # 2. Altered source versions must be plainly marked as such, and must not be
  21. # misrepresented as being the original software.
  22. # 3. This notice may not be removed or altered from any source distribution.
  23. #
  24. # Note: This software has been modified for use in PyPy.
  25. from ctypes import c_void_p, c_int, c_double, c_int64, c_char_p, cdll
  26. from ctypes import POINTER, byref, string_at, CFUNCTYPE, cast
  27. from ctypes import sizeof, c_ssize_t
  28. from collections import OrderedDict
  29. import datetime
  30. import sys
  31. import weakref
  32. from threading import _get_ident as thread_get_ident
  33. names = "sqlite3.dll libsqlite3.so.0 libsqlite3.so libsqlite3.dylib".split()
  34. for name in names:
  35. try:
  36. sqlite = cdll.LoadLibrary(name)
  37. break
  38. except OSError:
  39. continue
  40. else:
  41. raise ImportError("Could not load C-library, tried: %s" %(names,))
  42. # pysqlite version information
  43. version = "2.6.0"
  44. # pysqlite constants
  45. PARSE_COLNAMES = 1
  46. PARSE_DECLTYPES = 2
  47. ##########################################
  48. # BEGIN Wrapped SQLite C API and constants
  49. ##########################################
  50. SQLITE_OK = 0
  51. SQLITE_ERROR = 1
  52. SQLITE_INTERNAL = 2
  53. SQLITE_PERM = 3
  54. SQLITE_ABORT = 4
  55. SQLITE_BUSY = 5
  56. SQLITE_LOCKED = 6
  57. SQLITE_NOMEM = 7
  58. SQLITE_READONLY = 8
  59. SQLITE_INTERRUPT = 9
  60. SQLITE_IOERR = 10
  61. SQLITE_CORRUPT = 11
  62. SQLITE_NOTFOUND = 12
  63. SQLITE_FULL = 13
  64. SQLITE_CANTOPEN = 14
  65. SQLITE_PROTOCOL = 15
  66. SQLITE_EMPTY = 16
  67. SQLITE_SCHEMA = 17
  68. SQLITE_TOOBIG = 18
  69. SQLITE_CONSTRAINT = 19
  70. SQLITE_MISMATCH = 20
  71. SQLITE_MISUSE = 21
  72. SQLITE_NOLFS = 22
  73. SQLITE_AUTH = 23
  74. SQLITE_FORMAT = 24
  75. SQLITE_RANGE = 25
  76. SQLITE_NOTADB = 26
  77. SQLITE_ROW = 100
  78. SQLITE_DONE = 101
  79. SQLITE_INTEGER = 1
  80. SQLITE_FLOAT = 2
  81. SQLITE_BLOB = 4
  82. SQLITE_NULL = 5
  83. SQLITE_TEXT = 3
  84. SQLITE3_TEXT = 3
  85. SQLITE_TRANSIENT = cast(-1, c_void_p)
  86. SQLITE_UTF8 = 1
  87. SQLITE_DENY = 1
  88. SQLITE_IGNORE = 2
  89. SQLITE_CREATE_INDEX = 1
  90. SQLITE_CREATE_TABLE = 2
  91. SQLITE_CREATE_TEMP_INDEX = 3
  92. SQLITE_CREATE_TEMP_TABLE = 4
  93. SQLITE_CREATE_TEMP_TRIGGER = 5
  94. SQLITE_CREATE_TEMP_VIEW = 6
  95. SQLITE_CREATE_TRIGGER = 7
  96. SQLITE_CREATE_VIEW = 8
  97. SQLITE_DELETE = 9
  98. SQLITE_DROP_INDEX = 10
  99. SQLITE_DROP_TABLE = 11
  100. SQLITE_DROP_TEMP_INDEX = 12
  101. SQLITE_DROP_TEMP_TABLE = 13
  102. SQLITE_DROP_TEMP_TRIGGER = 14
  103. SQLITE_DROP_TEMP_VIEW = 15
  104. SQLITE_DROP_TRIGGER = 16
  105. SQLITE_DROP_VIEW = 17
  106. SQLITE_INSERT = 18
  107. SQLITE_PRAGMA = 19
  108. SQLITE_READ = 20
  109. SQLITE_SELECT = 21
  110. SQLITE_TRANSACTION = 22
  111. SQLITE_UPDATE = 23
  112. SQLITE_ATTACH = 24
  113. SQLITE_DETACH = 25
  114. SQLITE_ALTER_TABLE = 26
  115. SQLITE_REINDEX = 27
  116. SQLITE_ANALYZE = 28
  117. SQLITE_CREATE_VTABLE = 29
  118. SQLITE_DROP_VTABLE = 30
  119. SQLITE_FUNCTION = 31
  120. # SQLite C API
  121. sqlite.sqlite3_value_int.argtypes = [c_void_p]
  122. sqlite.sqlite3_value_int.restype = c_int
  123. sqlite.sqlite3_value_int64.argtypes = [c_void_p]
  124. sqlite.sqlite3_value_int64.restype = c_int64
  125. sqlite.sqlite3_value_blob.argtypes = [c_void_p]
  126. sqlite.sqlite3_value_blob.restype = c_void_p
  127. sqlite.sqlite3_value_bytes.argtypes = [c_void_p]
  128. sqlite.sqlite3_value_bytes.restype = c_int
  129. sqlite.sqlite3_value_double.argtypes = [c_void_p]
  130. sqlite.sqlite3_value_double.restype = c_double
  131. sqlite.sqlite3_value_text.argtypes = [c_void_p]
  132. sqlite.sqlite3_value_text.restype = c_char_p
  133. sqlite.sqlite3_value_type.argtypes = [c_void_p]
  134. sqlite.sqlite3_value_type.restype = c_int
  135. sqlite.sqlite3_bind_blob.argtypes = [c_void_p, c_int, c_void_p, c_int,c_void_p]
  136. sqlite.sqlite3_bind_blob.restype = c_int
  137. sqlite.sqlite3_bind_double.argtypes = [c_void_p, c_int, c_double]
  138. sqlite.sqlite3_bind_double.restype = c_int
  139. sqlite.sqlite3_bind_int.argtypes = [c_void_p, c_int, c_int]
  140. sqlite.sqlite3_bind_int.restype = c_int
  141. sqlite.sqlite3_bind_int64.argtypes = [c_void_p, c_int, c_int64]
  142. sqlite.sqlite3_bind_int64.restype = c_int
  143. sqlite.sqlite3_bind_null.argtypes = [c_void_p, c_int]
  144. sqlite.sqlite3_bind_null.restype = c_int
  145. sqlite.sqlite3_bind_parameter_count.argtypes = [c_void_p]
  146. sqlite.sqlite3_bind_parameter_count.restype = c_int
  147. sqlite.sqlite3_bind_parameter_index.argtypes = [c_void_p, c_char_p]
  148. sqlite.sqlite3_bind_parameter_index.restype = c_int
  149. sqlite.sqlite3_bind_parameter_name.argtypes = [c_void_p, c_int]
  150. sqlite.sqlite3_bind_parameter_name.restype = c_char_p
  151. sqlite.sqlite3_bind_text.argtypes = [c_void_p, c_int, c_char_p, c_int,c_void_p]
  152. sqlite.sqlite3_bind_text.restype = c_int
  153. sqlite.sqlite3_busy_timeout.argtypes = [c_void_p, c_int]
  154. sqlite.sqlite3_busy_timeout.restype = c_int
  155. sqlite.sqlite3_changes.argtypes = [c_void_p]
  156. sqlite.sqlite3_changes.restype = c_int
  157. sqlite.sqlite3_close.argtypes = [c_void_p]
  158. sqlite.sqlite3_close.restype = c_int
  159. sqlite.sqlite3_column_blob.argtypes = [c_void_p, c_int]
  160. sqlite.sqlite3_column_blob.restype = c_void_p
  161. sqlite.sqlite3_column_bytes.argtypes = [c_void_p, c_int]
  162. sqlite.sqlite3_column_bytes.restype = c_int
  163. sqlite.sqlite3_column_count.argtypes = [c_void_p]
  164. sqlite.sqlite3_column_count.restype = c_int
  165. sqlite.sqlite3_column_decltype.argtypes = [c_void_p, c_int]
  166. sqlite.sqlite3_column_decltype.restype = c_char_p
  167. sqlite.sqlite3_column_double.argtypes = [c_void_p, c_int]
  168. sqlite.sqlite3_column_double.restype = c_double
  169. sqlite.sqlite3_column_int64.argtypes = [c_void_p, c_int]
  170. sqlite.sqlite3_column_int64.restype = c_int64
  171. sqlite.sqlite3_column_name.argtypes = [c_void_p, c_int]
  172. sqlite.sqlite3_column_name.restype = c_char_p
  173. sqlite.sqlite3_column_text.argtypes = [c_void_p, c_int]
  174. sqlite.sqlite3_column_text.restype = c_char_p
  175. sqlite.sqlite3_column_type.argtypes = [c_void_p, c_int]
  176. sqlite.sqlite3_column_type.restype = c_int
  177. sqlite.sqlite3_complete.argtypes = [c_char_p]
  178. sqlite.sqlite3_complete.restype = c_int
  179. sqlite.sqlite3_errcode.restype = c_int
  180. sqlite.sqlite3_errmsg.argtypes = [c_void_p]
  181. sqlite.sqlite3_errmsg.restype = c_char_p
  182. sqlite.sqlite3_finalize.argtypes = [c_void_p]
  183. sqlite.sqlite3_finalize.restype = c_int
  184. sqlite.sqlite3_get_autocommit.argtypes = [c_void_p]
  185. sqlite.sqlite3_get_autocommit.restype = c_int
  186. sqlite.sqlite3_last_insert_rowid.argtypes = [c_void_p]
  187. sqlite.sqlite3_last_insert_rowid.restype = c_int64
  188. sqlite.sqlite3_libversion.argtypes = []
  189. sqlite.sqlite3_libversion.restype = c_char_p
  190. sqlite.sqlite3_open.argtypes = [c_char_p, c_void_p]
  191. sqlite.sqlite3_open.restype = c_int
  192. sqlite.sqlite3_prepare.argtypes = [c_void_p, c_char_p, c_int, c_void_p, POINTER(c_char_p)]
  193. sqlite.sqlite3_prepare.restype = c_int
  194. sqlite.sqlite3_prepare_v2.argtypes = [c_void_p, c_char_p, c_int, c_void_p, POINTER(c_char_p)]
  195. sqlite.sqlite3_prepare_v2.restype = c_int
  196. sqlite.sqlite3_step.argtypes = [c_void_p]
  197. sqlite.sqlite3_step.restype = c_int
  198. sqlite.sqlite3_reset.argtypes = [c_void_p]
  199. sqlite.sqlite3_reset.restype = c_int
  200. sqlite.sqlite3_total_changes.argtypes = [c_void_p]
  201. sqlite.sqlite3_total_changes.restype = c_int
  202. sqlite.sqlite3_result_blob.argtypes = [c_void_p, c_char_p, c_int, c_void_p]
  203. sqlite.sqlite3_result_blob.restype = None
  204. sqlite.sqlite3_result_int64.argtypes = [c_void_p, c_int64]
  205. sqlite.sqlite3_result_int64.restype = None
  206. sqlite.sqlite3_result_null.argtypes = [c_void_p]
  207. sqlite.sqlite3_result_null.restype = None
  208. sqlite.sqlite3_result_double.argtypes = [c_void_p, c_double]
  209. sqlite.sqlite3_result_double.restype = None
  210. sqlite.sqlite3_result_error.argtypes = [c_void_p, c_char_p, c_int]
  211. sqlite.sqlite3_result_error.restype = None
  212. sqlite.sqlite3_result_text.argtypes = [c_void_p, c_char_p, c_int, c_void_p]
  213. sqlite.sqlite3_result_text.restype = None
  214. HAS_LOAD_EXTENSION = hasattr(sqlite, "sqlite3_enable_load_extension")
  215. if HAS_LOAD_EXTENSION:
  216. sqlite.sqlite3_enable_load_extension.argtypes = [c_void_p, c_int]
  217. sqlite.sqlite3_enable_load_extension.restype = c_int
  218. ##########################################
  219. # END Wrapped SQLite C API and constants
  220. ##########################################
  221. # SQLite version information
  222. sqlite_version = sqlite.sqlite3_libversion()
  223. class Error(StandardError):
  224. pass
  225. class Warning(StandardError):
  226. pass
  227. class InterfaceError(Error):
  228. pass
  229. class DatabaseError(Error):
  230. pass
  231. class InternalError(DatabaseError):
  232. pass
  233. class OperationalError(DatabaseError):
  234. pass
  235. class ProgrammingError(DatabaseError):
  236. pass
  237. class IntegrityError(DatabaseError):
  238. pass
  239. class DataError(DatabaseError):
  240. pass
  241. class NotSupportedError(DatabaseError):
  242. pass
  243. def connect(database, **kwargs):
  244. factory = kwargs.get("factory", Connection)
  245. return factory(database, **kwargs)
  246. def unicode_text_factory(x):
  247. return unicode(x, 'utf-8')
  248. class StatementCache(object):
  249. def __init__(self, connection, maxcount):
  250. self.connection = connection
  251. self.maxcount = maxcount
  252. self.cache = OrderedDict()
  253. def get(self, sql, cursor, row_factory):
  254. try:
  255. stat = self.cache[sql]
  256. except KeyError:
  257. stat = Statement(self.connection, sql)
  258. self.cache[sql] = stat
  259. if len(self.cache) > self.maxcount:
  260. self.cache.popitem(0)
  261. #
  262. if stat.in_use:
  263. stat = Statement(self.connection, sql)
  264. stat.set_row_factory(row_factory)
  265. return stat
  266. class Connection(object):
  267. def __init__(self, database, timeout=5.0, detect_types=0, isolation_level="",
  268. check_same_thread=True, factory=None, cached_statements=100):
  269. self.db = c_void_p()
  270. if sqlite.sqlite3_open(database, byref(self.db)) != SQLITE_OK:
  271. raise OperationalError("Could not open database")
  272. if timeout is not None:
  273. timeout = int(timeout * 1000) # pysqlite2 uses timeout in seconds
  274. sqlite.sqlite3_busy_timeout(self.db, timeout)
  275. self.text_factory = unicode_text_factory
  276. self.closed = False
  277. self.statements = []
  278. self.statement_counter = 0
  279. self.row_factory = None
  280. self._isolation_level = isolation_level
  281. self.detect_types = detect_types
  282. self.statement_cache = StatementCache(self, cached_statements)
  283. self.cursors = []
  284. self.Error = Error
  285. self.Warning = Warning
  286. self.InterfaceError = InterfaceError
  287. self.DatabaseError = DatabaseError
  288. self.InternalError = InternalError
  289. self.OperationalError = OperationalError
  290. self.ProgrammingError = ProgrammingError
  291. self.IntegrityError = IntegrityError
  292. self.DataError = DataError
  293. self.NotSupportedError = NotSupportedError
  294. self.func_cache = {}
  295. self._aggregates = {}
  296. self.aggregate_instances = {}
  297. self._collations = {}
  298. if check_same_thread:
  299. self.thread_ident = thread_get_ident()
  300. def _get_exception(self, error_code = None):
  301. if error_code is None:
  302. error_code = sqlite.sqlite3_errcode(self.db)
  303. error_message = sqlite.sqlite3_errmsg(self.db)
  304. if error_code == SQLITE_OK:
  305. raise ValueError("error signalled but got SQLITE_OK")
  306. elif error_code in (SQLITE_INTERNAL, SQLITE_NOTFOUND):
  307. exc = InternalError
  308. elif error_code == SQLITE_NOMEM:
  309. exc = MemoryError
  310. elif error_code in (SQLITE_ERROR, SQLITE_PERM, SQLITE_ABORT, SQLITE_BUSY, SQLITE_LOCKED,
  311. SQLITE_READONLY, SQLITE_INTERRUPT, SQLITE_IOERR, SQLITE_FULL, SQLITE_CANTOPEN,
  312. SQLITE_PROTOCOL, SQLITE_EMPTY, SQLITE_SCHEMA):
  313. exc = OperationalError
  314. elif error_code == SQLITE_CORRUPT:
  315. exc = DatabaseError
  316. elif error_code == SQLITE_TOOBIG:
  317. exc = DataError
  318. elif error_code in (SQLITE_CONSTRAINT, SQLITE_MISMATCH):
  319. exc = IntegrityError
  320. elif error_code == SQLITE_MISUSE:
  321. exc = ProgrammingError
  322. else:
  323. exc = DatabaseError
  324. exc = exc(error_message)
  325. exc.error_code = error_code
  326. return exc
  327. def _remember_statement(self, statement):
  328. self.statements.append(weakref.ref(statement))
  329. self.statement_counter += 1
  330. if self.statement_counter % 100 == 0:
  331. self.statements = [ref for ref in self.statements if ref() is not None]
  332. def _check_thread(self):
  333. if not hasattr(self, 'thread_ident'):
  334. return
  335. if self.thread_ident != thread_get_ident():
  336. raise ProgrammingError(
  337. "SQLite objects created in a thread can only be used in that same thread."
  338. "The object was created in thread id %d and this is thread id %d",
  339. self.thread_ident, thread_get_ident())
  340. def _reset_cursors(self):
  341. for cursor_ref in self.cursors:
  342. cursor = cursor_ref()
  343. if cursor:
  344. cursor.reset = True
  345. def cursor(self, factory=None):
  346. self._check_thread()
  347. self._check_closed()
  348. if factory is None:
  349. factory = Cursor
  350. cur = factory(self)
  351. if self.row_factory is not None:
  352. cur.row_factory = self.row_factory
  353. return cur
  354. def executemany(self, *args):
  355. self._check_closed()
  356. cur = Cursor(self)
  357. if self.row_factory is not None:
  358. cur.row_factory = self.row_factory
  359. return cur.executemany(*args)
  360. def execute(self, *args):
  361. self._check_closed()
  362. cur = Cursor(self)
  363. if self.row_factory is not None:
  364. cur.row_factory = self.row_factory
  365. return cur.execute(*args)
  366. def executescript(self, *args):
  367. self._check_closed()
  368. cur = Cursor(self)
  369. if self.row_factory is not None:
  370. cur.row_factory = self.row_factory
  371. return cur.executescript(*args)
  372. def __call__(self, sql):
  373. self._check_closed()
  374. cur = Cursor(self)
  375. if not isinstance(sql, (str, unicode)):
  376. raise Warning("SQL is of wrong type. Must be string or unicode.")
  377. statement = self.statement_cache.get(sql, cur, self.row_factory)
  378. return statement
  379. def _get_isolation_level(self):
  380. return self._isolation_level
  381. def _set_isolation_level(self, val):
  382. if val is None:
  383. self.commit()
  384. if isinstance(val, unicode):
  385. val = str(val)
  386. self._isolation_level = val
  387. isolation_level = property(_get_isolation_level, _set_isolation_level)
  388. def _begin(self):
  389. self._check_closed()
  390. if self._isolation_level is None:
  391. return
  392. if sqlite.sqlite3_get_autocommit(self.db):
  393. try:
  394. sql = "BEGIN " + self._isolation_level
  395. statement = c_void_p()
  396. next_char = c_char_p()
  397. ret = sqlite.sqlite3_prepare_v2(self.db, sql, -1, byref(statement), next_char)
  398. if ret != SQLITE_OK:
  399. raise self._get_exception(ret)
  400. ret = sqlite.sqlite3_step(statement)
  401. if ret != SQLITE_DONE:
  402. raise self._get_exception(ret)
  403. finally:
  404. sqlite.sqlite3_finalize(statement)
  405. def commit(self):
  406. self._check_thread()
  407. self._check_closed()
  408. if sqlite.sqlite3_get_autocommit(self.db):
  409. return
  410. for statement in self.statements:
  411. obj = statement()
  412. if obj is not None:
  413. obj.reset()
  414. try:
  415. sql = "COMMIT"
  416. statement = c_void_p()
  417. next_char = c_char_p()
  418. ret = sqlite.sqlite3_prepare_v2(self.db, sql, -1, byref(statement), next_char)
  419. if ret != SQLITE_OK:
  420. raise self._get_exception(ret)
  421. ret = sqlite.sqlite3_step(statement)
  422. if ret != SQLITE_DONE:
  423. raise self._get_exception(ret)
  424. finally:
  425. sqlite.sqlite3_finalize(statement)
  426. def rollback(self):
  427. self._check_thread()
  428. self._check_closed()
  429. if sqlite.sqlite3_get_autocommit(self.db):
  430. return
  431. for statement in self.statements:
  432. obj = statement()
  433. if obj is not None:
  434. obj.reset()
  435. try:
  436. sql = "ROLLBACK"
  437. statement = c_void_p()
  438. next_char = c_char_p()
  439. ret = sqlite.sqlite3_prepare_v2(self.db, sql, -1, byref(statement), next_char)
  440. if ret != SQLITE_OK:
  441. raise self._get_exception(ret)
  442. ret = sqlite.sqlite3_step(statement)
  443. if ret != SQLITE_DONE:
  444. raise self._get_exception(ret)
  445. finally:
  446. sqlite.sqlite3_finalize(statement)
  447. self._reset_cursors()
  448. def _check_closed(self):
  449. if getattr(self, 'closed', True):
  450. raise ProgrammingError("Cannot operate on a closed database.")
  451. def __enter__(self):
  452. return self
  453. def __exit__(self, exc_type, exc_value, exc_tb):
  454. if exc_type is None and exc_value is None and exc_tb is None:
  455. self.commit()
  456. else:
  457. self.rollback()
  458. def _get_total_changes(self):
  459. return sqlite.sqlite3_total_changes(self.db)
  460. total_changes = property(_get_total_changes)
  461. def close(self):
  462. self._check_thread()
  463. if self.closed:
  464. return
  465. for statement in self.statements:
  466. obj = statement()
  467. if obj is not None:
  468. obj.finalize()
  469. self.closed = True
  470. ret = sqlite.sqlite3_close(self.db)
  471. self._reset_cursors()
  472. if ret != SQLITE_OK:
  473. raise self._get_exception(ret)
  474. def create_collation(self, name, callback):
  475. self._check_thread()
  476. self._check_closed()
  477. name = name.upper()
  478. if not name.replace('_', '').isalnum():
  479. raise ProgrammingError("invalid character in collation name")
  480. if callback is None:
  481. del self._collations[name]
  482. c_collation_callback = cast(None, COLLATION)
  483. else:
  484. if not callable(callback):
  485. raise TypeError("parameter must be callable")
  486. def collation_callback(context, len1, str1, len2, str2):
  487. text1 = string_at(str1, len1)
  488. text2 = string_at(str2, len2)
  489. return callback(text1, text2)
  490. c_collation_callback = COLLATION(collation_callback)
  491. self._collations[name] = c_collation_callback
  492. ret = sqlite.sqlite3_create_collation(self.db, name,
  493. SQLITE_UTF8,
  494. None,
  495. c_collation_callback)
  496. if ret != SQLITE_OK:
  497. raise self._get_exception(ret)
  498. def set_progress_handler(self, callable, nsteps):
  499. self._check_thread()
  500. self._check_closed()
  501. if callable is None:
  502. c_progress_handler = cast(None, PROGRESS)
  503. else:
  504. try:
  505. c_progress_handler, _ = self.func_cache[callable]
  506. except KeyError:
  507. def progress_handler(userdata):
  508. try:
  509. ret = callable()
  510. return bool(ret)
  511. except Exception:
  512. # abort query if error occurred
  513. return 1
  514. c_progress_handler = PROGRESS(progress_handler)
  515. self.func_cache[callable] = c_progress_handler, progress_handler
  516. ret = sqlite.sqlite3_progress_handler(self.db, nsteps,
  517. c_progress_handler,
  518. None)
  519. if ret != SQLITE_OK:
  520. raise self._get_exception(ret)
  521. def set_authorizer(self, callback):
  522. self._check_thread()
  523. self._check_closed()
  524. try:
  525. c_authorizer, _ = self.func_cache[callback]
  526. except KeyError:
  527. def authorizer(userdata, action, arg1, arg2, dbname, source):
  528. try:
  529. return int(callback(action, arg1, arg2, dbname, source))
  530. except Exception:
  531. return SQLITE_DENY
  532. c_authorizer = AUTHORIZER(authorizer)
  533. self.func_cache[callback] = c_authorizer, authorizer
  534. ret = sqlite.sqlite3_set_authorizer(self.db,
  535. c_authorizer,
  536. None)
  537. if ret != SQLITE_OK:
  538. raise self._get_exception(ret)
  539. def create_function(self, name, num_args, callback):
  540. self._check_thread()
  541. self._check_closed()
  542. try:
  543. c_closure, _ = self.func_cache[callback]
  544. except KeyError:
  545. def closure(context, nargs, c_params):
  546. function_callback(callback, context, nargs, c_params)
  547. c_closure = FUNC(closure)
  548. self.func_cache[callback] = c_closure, closure
  549. ret = sqlite.sqlite3_create_function(self.db, name, num_args,
  550. SQLITE_UTF8, None,
  551. c_closure,
  552. cast(None, STEP),
  553. cast(None, FINAL))
  554. if ret != SQLITE_OK:
  555. raise self.OperationalError("Error creating function")
  556. def create_aggregate(self, name, num_args, cls):
  557. self._check_thread()
  558. self._check_closed()
  559. try:
  560. c_step_callback, c_final_callback, _, _ = self._aggregates[cls]
  561. except KeyError:
  562. def step_callback(context, argc, c_params):
  563. aggregate_ptr = cast(
  564. sqlite.sqlite3_aggregate_context(
  565. context, sizeof(c_ssize_t)),
  566. POINTER(c_ssize_t))
  567. if not aggregate_ptr[0]:
  568. try:
  569. aggregate = cls()
  570. except Exception:
  571. msg = ("user-defined aggregate's '__init__' "
  572. "method raised error")
  573. sqlite.sqlite3_result_error(context, msg, len(msg))
  574. return
  575. aggregate_id = id(aggregate)
  576. self.aggregate_instances[aggregate_id] = aggregate
  577. aggregate_ptr[0] = aggregate_id
  578. else:
  579. aggregate = self.aggregate_instances[aggregate_ptr[0]]
  580. params = _convert_params(context, argc, c_params)
  581. try:
  582. aggregate.step(*params)
  583. except Exception:
  584. msg = ("user-defined aggregate's 'step' "
  585. "method raised error")
  586. sqlite.sqlite3_result_error(context, msg, len(msg))
  587. def final_callback(context):
  588. aggregate_ptr = cast(
  589. sqlite.sqlite3_aggregate_context(
  590. context, sizeof(c_ssize_t)),
  591. POINTER(c_ssize_t))
  592. if aggregate_ptr[0]:
  593. aggregate = self.aggregate_instances[aggregate_ptr[0]]
  594. try:
  595. val = aggregate.finalize()
  596. except Exception:
  597. msg = ("user-defined aggregate's 'finalize' "
  598. "method raised error")
  599. sqlite.sqlite3_result_error(context, msg, len(msg))
  600. else:
  601. _convert_result(context, val)
  602. finally:
  603. del self.aggregate_instances[aggregate_ptr[0]]
  604. c_step_callback = STEP(step_callback)
  605. c_final_callback = FINAL(final_callback)
  606. self._aggregates[cls] = (c_step_callback, c_final_callback,
  607. step_callback, final_callback)
  608. ret = sqlite.sqlite3_create_function(self.db, name, num_args,
  609. SQLITE_UTF8, None,
  610. cast(None, FUNC),
  611. c_step_callback,
  612. c_final_callback)
  613. if ret != SQLITE_OK:
  614. raise self._get_exception(ret)
  615. def iterdump(self):
  616. from sqlite3.dump import _iterdump
  617. return _iterdump(self)
  618. if HAS_LOAD_EXTENSION:
  619. def enable_load_extension(self, enabled):
  620. self._check_thread()
  621. self._check_closed()
  622. rc = sqlite.sqlite3_enable_load_extension(self.db, int(enabled))
  623. if rc != SQLITE_OK:
  624. raise OperationalError("Error enabling load extension")
  625. DML, DQL, DDL = range(3)
  626. class Cursor(object):
  627. def __init__(self, con):
  628. if not isinstance(con, Connection):
  629. raise TypeError
  630. con._check_thread()
  631. con._check_closed()
  632. con.cursors.append(weakref.ref(self))
  633. self.connection = con
  634. self._description = None
  635. self.arraysize = 1
  636. self.row_factory = None
  637. self.rowcount = -1
  638. self.statement = None
  639. self.reset = False
  640. def _check_closed(self):
  641. if not getattr(self, 'connection', None):
  642. raise ProgrammingError("Cannot operate on a closed cursor.")
  643. self.connection._check_thread()
  644. self.connection._check_closed()
  645. def execute(self, sql, params=None):
  646. self._description = None
  647. self.reset = False
  648. if type(sql) is unicode:
  649. sql = sql.encode("utf-8")
  650. self._check_closed()
  651. self.statement = self.connection.statement_cache.get(sql, self, self.row_factory)
  652. if self.connection._isolation_level is not None:
  653. if self.statement.kind == DDL:
  654. self.connection.commit()
  655. elif self.statement.kind == DML:
  656. self.connection._begin()
  657. self.statement.set_params(params)
  658. # Actually execute the SQL statement
  659. ret = sqlite.sqlite3_step(self.statement.statement)
  660. if ret not in (SQLITE_DONE, SQLITE_ROW):
  661. self.statement.reset()
  662. raise self.connection._get_exception(ret)
  663. if self.statement.kind == DQL and ret == SQLITE_ROW:
  664. self.statement._build_row_cast_map()
  665. self.statement._readahead(self)
  666. else:
  667. self.statement.item = None
  668. self.statement.exhausted = True
  669. if self.statement.kind == DML:
  670. self.statement.reset()
  671. self.rowcount = -1
  672. if self.statement.kind == DML:
  673. self.rowcount = sqlite.sqlite3_changes(self.connection.db)
  674. return self
  675. def executemany(self, sql, many_params):
  676. self._description = None
  677. self.reset = False
  678. if type(sql) is unicode:
  679. sql = sql.encode("utf-8")
  680. self._check_closed()
  681. self.statement = self.connection.statement_cache.get(sql, self, self.row_factory)
  682. if self.statement.kind == DML:
  683. self.connection._begin()
  684. else:
  685. raise ProgrammingError("executemany is only for DML statements")
  686. self.rowcount = 0
  687. for params in many_params:
  688. self.statement.set_params(params)
  689. ret = sqlite.sqlite3_step(self.statement.statement)
  690. if ret != SQLITE_DONE:
  691. raise self.connection._get_exception(ret)
  692. self.rowcount += sqlite.sqlite3_changes(self.connection.db)
  693. return self
  694. def executescript(self, sql):
  695. self._description = None
  696. self.reset = False
  697. if type(sql) is unicode:
  698. sql = sql.encode("utf-8")
  699. self._check_closed()
  700. statement = c_void_p()
  701. c_sql = c_char_p(sql)
  702. self.connection.commit()
  703. while True:
  704. rc = sqlite.sqlite3_prepare(self.connection.db, c_sql, -1, byref(statement), byref(c_sql))
  705. if rc != SQLITE_OK:
  706. raise self.connection._get_exception(rc)
  707. rc = SQLITE_ROW
  708. while rc == SQLITE_ROW:
  709. if not statement:
  710. rc = SQLITE_OK
  711. else:
  712. rc = sqlite.sqlite3_step(statement)
  713. if rc != SQLITE_DONE:
  714. sqlite.sqlite3_finalize(statement)
  715. if rc == SQLITE_OK:
  716. return self
  717. else:
  718. raise self.connection._get_exception(rc)
  719. rc = sqlite.sqlite3_finalize(statement)
  720. if rc != SQLITE_OK:
  721. raise self.connection._get_exception(rc)
  722. if not c_sql.value:
  723. break
  724. return self
  725. def __iter__(self):
  726. return iter(self.fetchone, None)
  727. def _check_reset(self):
  728. if self.reset:
  729. raise self.connection.InterfaceError("Cursor needed to be reset because "
  730. "of commit/rollback and can "
  731. "no longer be fetched from.")
  732. # do all statements
  733. def fetchone(self):
  734. self._check_closed()
  735. self._check_reset()
  736. if self.statement is None:
  737. return None
  738. try:
  739. return self.statement.next(self)
  740. except StopIteration:
  741. return None
  742. def fetchmany(self, size=None):
  743. self._check_closed()
  744. self._check_reset()
  745. if self.statement is None:
  746. return []
  747. if size is None:
  748. size = self.arraysize
  749. lst = []
  750. for row in self:
  751. lst.append(row)
  752. if len(lst) == size:
  753. break
  754. return lst
  755. def fetchall(self):
  756. self._check_closed()
  757. self._check_reset()
  758. if self.statement is None:
  759. return []
  760. return list(self)
  761. def _getdescription(self):
  762. if self._description is None:
  763. self._description = self.statement._get_description()
  764. return self._description
  765. def _getlastrowid(self):
  766. return sqlite.sqlite3_last_insert_rowid(self.connection.db)
  767. def close(self):
  768. if not self.connection:
  769. return
  770. self._check_closed()
  771. if self.statement:
  772. self.statement.reset()
  773. self.statement = None
  774. self.connection.cursors.remove(weakref.ref(self))
  775. self.connection = None
  776. def setinputsizes(self, *args):
  777. pass
  778. def setoutputsize(self, *args):
  779. pass
  780. description = property(_getdescription)
  781. lastrowid = property(_getlastrowid)
  782. class Statement(object):
  783. def __init__(self, connection, sql):
  784. self.statement = None
  785. if not isinstance(sql, str):
  786. raise ValueError("sql must be a string")
  787. self.con = connection
  788. self.sql = sql # DEBUG ONLY
  789. first_word = self._statement_kind = sql.lstrip().split(" ")[0].upper()
  790. if first_word in ("INSERT", "UPDATE", "DELETE", "REPLACE"):
  791. self.kind = DML
  792. elif first_word in ("SELECT", "PRAGMA"):
  793. self.kind = DQL
  794. else:
  795. self.kind = DDL
  796. self.exhausted = False
  797. self.in_use = False
  798. #
  799. # set by set_row_factory
  800. self.row_factory = None
  801. self.statement = c_void_p()
  802. next_char = c_char_p()
  803. sql_char = c_char_p(sql)
  804. ret = sqlite.sqlite3_prepare_v2(self.con.db, sql_char, -1, byref(self.statement), byref(next_char))
  805. if ret == SQLITE_OK and self.statement.value is None:
  806. # an empty statement, we work around that, as it's the least trouble
  807. ret = sqlite.sqlite3_prepare_v2(self.con.db, "select 42", -1, byref(self.statement), byref(next_char))
  808. self.kind = DQL
  809. if ret != SQLITE_OK:
  810. raise self.con._get_exception(ret)
  811. self.con._remember_statement(self)
  812. if _check_remaining_sql(next_char.value):
  813. raise Warning("One and only one statement required: %r" % (
  814. next_char.value,))
  815. # sql_char should remain alive until here
  816. self._build_row_cast_map()
  817. def set_row_factory(self, row_factory):
  818. self.row_factory = row_factory
  819. def _build_row_cast_map(self):
  820. self.row_cast_map = []
  821. for i in xrange(sqlite.sqlite3_column_count(self.statement)):
  822. converter = None
  823. if self.con.detect_types & PARSE_COLNAMES:
  824. colname = sqlite.sqlite3_column_name(self.statement, i)
  825. if colname is not None:
  826. type_start = -1
  827. key = None
  828. for pos in range(len(colname)):
  829. if colname[pos] == '[':
  830. type_start = pos + 1
  831. elif colname[pos] == ']' and type_start != -1:
  832. key = colname[type_start:pos]
  833. converter = converters[key.upper()]
  834. if converter is None and self.con.detect_types & PARSE_DECLTYPES:
  835. decltype = sqlite.sqlite3_column_decltype(self.statement, i)
  836. if decltype is not None:
  837. decltype = decltype.split()[0] # if multiple words, use first, eg. "INTEGER NOT NULL" => "INTEGER"
  838. if '(' in decltype:
  839. decltype = decltype[:decltype.index('(')]
  840. converter = converters.get(decltype.upper(), None)
  841. self.row_cast_map.append(converter)
  842. def _check_decodable(self, param):
  843. if self.con.text_factory in (unicode, OptimizedUnicode, unicode_text_factory):
  844. for c in param:
  845. if ord(c) & 0x80 != 0:
  846. raise self.con.ProgrammingError(
  847. "You must not use 8-bit bytestrings unless "
  848. "you use a text_factory that can interpret "
  849. "8-bit bytestrings (like text_factory = str). "
  850. "It is highly recommended that you instead "
  851. "just switch your application to Unicode strings.")
  852. def set_param(self, idx, param):
  853. cvt = converters.get(type(param))
  854. if cvt is not None:
  855. cvt = param = cvt(param)
  856. param = adapt(param)
  857. if param is None:
  858. sqlite.sqlite3_bind_null(self.statement, idx)
  859. elif type(param) in (bool, int, long):
  860. if -2147483648 <= param <= 2147483647:
  861. sqlite.sqlite3_bind_int(self.statement, idx, param)
  862. else:
  863. sqlite.sqlite3_bind_int64(self.statement, idx, param)
  864. elif type(param) is float:
  865. sqlite.sqlite3_bind_double(self.statement, idx, param)
  866. elif isinstance(param, str):
  867. self._check_decodable(param)
  868. sqlite.sqlite3_bind_text(self.statement, idx, param, -1, SQLITE_TRANSIENT)
  869. elif isinstance(param, unicode):
  870. param = param.encode("utf-8")
  871. sqlite.sqlite3_bind_text(self.statement, idx, param, -1, SQLITE_TRANSIENT)
  872. elif type(param) is buffer:
  873. sqlite.sqlite3_bind_blob(self.statement, idx, str(param), len(param), SQLITE_TRANSIENT)
  874. else:
  875. raise InterfaceError("parameter type %s is not supported" % str(type(param)))
  876. def set_params(self, params):
  877. ret = sqlite.sqlite3_reset(self.statement)
  878. if ret != SQLITE_OK:
  879. raise self.con._get_exception(ret)
  880. self.mark_dirty()
  881. if params is None:
  882. if sqlite.sqlite3_bind_parameter_count(self.statement) != 0:
  883. raise ProgrammingError("wrong number of arguments")
  884. return
  885. params_type = None
  886. if isinstance(params, dict):
  887. params_type = dict
  888. else:
  889. params_type = list
  890. if params_type == list:
  891. if len(params) != sqlite.sqlite3_bind_parameter_count(self.statement):
  892. raise ProgrammingError("wrong number of arguments")
  893. for i in range(len(params)):
  894. self.set_param(i+1, params[i])
  895. else:
  896. for idx in range(1, sqlite.sqlite3_bind_parameter_count(self.statement) + 1):
  897. param_name = sqlite.sqlite3_bind_parameter_name(self.statement, idx)
  898. if param_name is None:
  899. raise ProgrammingError("need named parameters")
  900. param_name = param_name[1:]
  901. try:
  902. param = params[param_name]
  903. except KeyError:
  904. raise ProgrammingError("missing parameter '%s'" %param)
  905. self.set_param(idx, param)
  906. def next(self, cursor):
  907. self.con._check_closed()
  908. self.con._check_thread()
  909. if self.exhausted:
  910. raise StopIteration
  911. item = self.item
  912. ret = sqlite.sqlite3_step(self.statement)
  913. if ret == SQLITE_DONE:
  914. self.exhausted = True
  915. self.item = None
  916. elif ret != SQLITE_ROW:
  917. exc = self.con._get_exception(ret)
  918. sqlite.sqlite3_reset(self.statement)
  919. raise exc
  920. self._readahead(cursor)
  921. return item
  922. def _readahead(self, cursor):
  923. self.column_count = sqlite.sqlite3_column_count(self.statement)
  924. row = []
  925. for i in xrange(self.column_count):
  926. typ = sqlite.sqlite3_column_type(self.statement, i)
  927. converter = self.row_cast_map[i]
  928. if converter is None:
  929. if typ == SQLITE_INTEGER:
  930. val = sqlite.sqlite3_column_int64(self.statement, i)
  931. if -sys.maxint-1 <= val <= sys.maxint:
  932. val = int(val)
  933. elif typ == SQLITE_FLOAT:
  934. val = sqlite.sqlite3_column_double(self.statement, i)
  935. elif typ == SQLITE_BLOB:
  936. blob_len = sqlite.sqlite3_column_bytes(self.statement, i)
  937. blob = sqlite.sqlite3_column_blob(self.statement, i)
  938. val = buffer(string_at(blob, blob_len))
  939. elif typ == SQLITE_NULL:
  940. val = None
  941. elif typ == SQLITE_TEXT:
  942. val = sqlite.sqlite3_column_text(self.statement, i)
  943. val = self.con.text_factory(val)
  944. else:
  945. blob = sqlite.sqlite3_column_blob(self.statement, i)
  946. if not blob:
  947. val = None
  948. else:
  949. blob_len = sqlite.sqlite3_column_bytes(self.statement, i)
  950. val = string_at(blob, blob_len)
  951. val = converter(val)
  952. row.append(val)
  953. row = tuple(row)
  954. if self.row_factory is not None:
  955. row = self.row_factory(cursor, row)
  956. self.item = row
  957. def reset(self):
  958. self.row_cast_map = None
  959. ret = sqlite.sqlite3_reset(self.statement)
  960. self.in_use = False
  961. self.exhausted = False
  962. return ret
  963. def finalize(self):
  964. sqlite.sqlite3_finalize(self.statement)
  965. self.statement = None
  966. self.in_use = False
  967. def mark_dirty(self):
  968. self.in_use = True
  969. def __del__(self):
  970. sqlite.sqlite3_finalize(self.statement)
  971. self.statement = None
  972. def _get_description(self):
  973. if self.kind == DML:
  974. return None
  975. desc = []
  976. for i in xrange(sqlite.sqlite3_column_count(self.statement)):
  977. name = sqlite.sqlite3_column_name(self.statement, i).split("[")[0].strip()
  978. desc.append((name, None, None, None, None, None, None))
  979. return desc
  980. class Row(object):
  981. def __init__(self, cursor, values):
  982. self.description = cursor.description
  983. self.values = values
  984. def __getitem__(self, item):
  985. if type(item) is int:
  986. return self.values[item]
  987. else:
  988. item = item.lower()
  989. for idx, desc in enumerate(self.description):
  990. if desc[0].lower() == item:
  991. return self.values[idx]
  992. raise KeyError
  993. def keys(self):
  994. return [desc[0] for desc in self.description]
  995. def __eq__(self, other):
  996. if not isinstance(other, Row):
  997. return NotImplemented
  998. if self.description != other.description:
  999. return False
  1000. if self.values != other.values:
  1001. return False
  1002. return True
  1003. def __ne__(self, other):
  1004. return not self == other
  1005. def __hash__(self):
  1006. return hash(tuple(self.description)) ^ hash(tuple(self.values))
  1007. def _check_remaining_sql(s):
  1008. state = "NORMAL"
  1009. for char in s:
  1010. if char == chr(0):
  1011. return 0
  1012. elif char == '-':
  1013. if state == "NORMAL":
  1014. state = "LINECOMMENT_1"
  1015. elif state == "LINECOMMENT_1":
  1016. state = "IN_LINECOMMENT"
  1017. elif char in (' ', '\t'):
  1018. pass
  1019. elif char == '\n':
  1020. if state == "IN_LINECOMMENT":
  1021. state = "NORMAL"
  1022. elif char == '/':
  1023. if state == "NORMAL":
  1024. state = "COMMENTSTART_1"
  1025. elif state == "COMMENTEND_1":
  1026. state = "NORMAL"
  1027. elif state == "COMMENTSTART_1":
  1028. return 1
  1029. elif char == '*':
  1030. if state == "NORMAL":
  1031. return 1
  1032. elif state == "LINECOMMENT_1":
  1033. return 1
  1034. elif state == "COMMENTSTART_1":
  1035. state = "IN_COMMENT"
  1036. elif state == "IN_COMMENT":
  1037. state = "COMMENTEND_1"
  1038. else:
  1039. if state == "COMMENTEND_1":
  1040. state = "IN_COMMENT"
  1041. elif state == "IN_LINECOMMENT":
  1042. pass
  1043. elif state == "IN_COMMENT":
  1044. pass
  1045. else:
  1046. return 1
  1047. return 0
  1048. def _convert_params(con, nargs, params):
  1049. _params = []
  1050. for i in range(nargs):
  1051. typ = sqlite.sqlite3_value_type(params[i])
  1052. if typ == SQLITE_INTEGER:
  1053. val = sqlite.sqlite3_value_int64(params[i])
  1054. if -sys.maxint-1 <= val <= sys.maxint:
  1055. val = int(val)
  1056. elif typ == SQLITE_FLOAT:
  1057. val = sqlite.sqlite3_value_double(params[i])
  1058. elif typ == SQLITE_BLOB:
  1059. blob_len = sqlite.sqlite3_value_bytes(params[i])
  1060. blob = sqlite.sqlite3_value_blob(params[i])
  1061. val = buffer(string_at(blob, blob_len))
  1062. elif typ == SQLITE_NULL:
  1063. val = None
  1064. elif typ == SQLITE_TEXT:
  1065. val = sqlite.sqlite3_value_text(params[i])
  1066. # XXX changed from con.text_factory
  1067. val = unicode(val, 'utf-8')
  1068. else:
  1069. raise NotImplementedError
  1070. _params.append(val)
  1071. return _params
  1072. def _convert_result(con, val):
  1073. if val is None:
  1074. sqlite.sqlite3_result_null(con)
  1075. elif isinstance(val, (bool, int, long)):
  1076. sqlite.sqlite3_result_int64(con, int(val))
  1077. elif isinstance(val, str):
  1078. # XXX ignoring unicode issue
  1079. sqlite.sqlite3_result_text(con, val, len(val), SQLITE_TRANSIENT)
  1080. elif isinstance(val, unicode):
  1081. val = val.encode('utf-8')
  1082. sqlite.sqlite3_result_text(con, val, len(val), SQLITE_TRANSIENT)
  1083. elif isinstance(val, float):
  1084. sqlite.sqlite3_result_double(con, val)
  1085. elif isinstance(val, buffer):
  1086. sqlite.sqlite3_result_blob(con, str(val), len(val), SQLITE_TRANSIENT)
  1087. else:
  1088. raise NotImplementedError
  1089. def function_callback(real_cb, context, nargs, c_params):
  1090. params = _convert_params(context, nargs, c_params)
  1091. try:
  1092. val = real_cb(*params)
  1093. except Exception:
  1094. msg = "user-defined function raised exception"
  1095. sqlite.sqlite3_result_error(context, msg, len(msg))
  1096. else:
  1097. _convert_result(context, val)
  1098. FUNC = CFUNCTYPE(None, c_void_p, c_int, POINTER(c_void_p))
  1099. STEP = CFUNCTYPE(None, c_void_p, c_int, POINTER(c_void_p))
  1100. FINAL = CFUNCTYPE(None, c_void_p)
  1101. sqlite.sqlite3_create_function.argtypes = [c_void_p, c_char_p, c_int, c_int, c_void_p, FUNC, STEP, FINAL]
  1102. sqlite.sqlite3_create_function.restype = c_int
  1103. sqlite.sqlite3_aggregate_context.argtypes = [c_void_p, c_int]
  1104. sqlite.sqlite3_aggregate_context.restype = c_void_p
  1105. COLLATION = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p, c_int, c_void_p)
  1106. sqlite.sqlite3_create_collation.argtypes = [c_void_p, c_char_p, c_int, c_void_p, COLLATION]
  1107. sqlite.sqlite3_create_collation.restype = c_int
  1108. PROGRESS = CFUNCTYPE(c_int, c_void_p)
  1109. sqlite.sqlite3_progress_handler.argtypes = [c_void_p, c_int, PROGRESS, c_void_p]
  1110. sqlite.sqlite3_progress_handler.restype = c_int
  1111. AUTHORIZER = CFUNCTYPE(c_int, c_void_p, c_int, c_char_p, c_char_p, c_char_p, c_char_p)
  1112. sqlite.sqlite3_set_authorizer.argtypes = [c_void_p, AUTHORIZER, c_void_p]
  1113. sqlite.sqlite3_set_authorizer.restype = c_int
  1114. converters = {}
  1115. adapters = {}
  1116. class PrepareProtocol(object):
  1117. pass
  1118. def register_adapter(typ, callable):
  1119. adapters[typ, PrepareProtocol] = callable
  1120. def register_converter(name, callable):
  1121. converters[name.upper()] = callable
  1122. def register_adapters_and_converters():
  1123. def adapt_date(val):
  1124. return val.isoformat()
  1125. def adapt_datetime(val):
  1126. return val.isoformat(" ")
  1127. def convert_date(val):
  1128. return datetime.date(*map(int, val.split("-")))
  1129. def convert_timestamp(val):
  1130. datepart, timepart = val.split(" ")
  1131. year, month, day = map(int, datepart.split("-"))
  1132. timepart_full = timepart.split(".")
  1133. hours, minutes, seconds = map(int, timepart_full[0].split(":"))
  1134. if len(timepart_full) == 2:
  1135. microseconds = int(timepart_full[1])
  1136. else:
  1137. microseconds = 0
  1138. val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds)
  1139. return val
  1140. register_adapter(datetime.date, adapt_date)
  1141. register_adapter(datetime.datetime, adapt_datetime)
  1142. register_converter("date", convert_date)
  1143. register_converter("timestamp", convert_timestamp)
  1144. def adapt(val, proto=PrepareProtocol):
  1145. # look for an adapter in the registry
  1146. adapter = adapters.get((type(val), proto), None)
  1147. if adapter is not None:
  1148. return adapter(val)
  1149. # try to have the protocol adapt this object
  1150. if hasattr(proto, '__adapt__'):
  1151. try:
  1152. adapted = proto.__adapt__(val)
  1153. except TypeError:
  1154. pass
  1155. else:
  1156. if adapted is not None:
  1157. return adapted
  1158. # and finally try to have the object adapt itself
  1159. if hasattr(val, '__conform__'):
  1160. try:
  1161. adapted = val.__conform__(proto)
  1162. except TypeError:
  1163. pass
  1164. else:
  1165. if adapted is not None:
  1166. return adapted
  1167. return val
  1168. register_adapters_and_converters()
  1169. def OptimizedUnicode(s):
  1170. try:
  1171. val = unicode(s, "ascii").encode("ascii")
  1172. except UnicodeDecodeError:
  1173. val = unicode(s, "utf-8")
  1174. return val