connection.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /* connection.c - the connection type
  2. *
  3. * Copyright (C) 2004-2009 Gerhard Häring <gh@ghaering.de>
  4. *
  5. * This file is part of pysqlite.
  6. *
  7. * This software is provided 'as-is', without any express or implied
  8. * warranty. In no event will the authors be held liable for any damages
  9. * arising from the use of this software.
  10. *
  11. * Permission is granted to anyone to use this software for any purpose,
  12. * including commercial applications, and to alter it and redistribute it
  13. * freely, subject to the following restrictions:
  14. *
  15. * 1. The origin of this software must not be misrepresented; you must not
  16. * claim that you wrote the original software. If you use this software
  17. * in a product, an acknowledgment in the product documentation would be
  18. * appreciated but is not required.
  19. * 2. Altered source versions must be plainly marked as such, and must not be
  20. * misrepresented as being the original software.
  21. * 3. This notice may not be removed or altered from any source distribution.
  22. */
  23. #include "cache.h"
  24. #include "module.h"
  25. #include "connection.h"
  26. #include "statement.h"
  27. #include "cursor.h"
  28. #include "prepare_protocol.h"
  29. #include "util.h"
  30. #include "sqlitecompat.h"
  31. #include "pythread.h"
  32. #define ACTION_FINALIZE 1
  33. #define ACTION_RESET 2
  34. #if SQLITE_VERSION_NUMBER >= 3003008
  35. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36. #define HAVE_LOAD_EXTENSION
  37. #endif
  38. #endif
  39. static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
  40. static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
  41. static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
  42. {
  43. /* in older SQLite versions, calling sqlite3_result_error in callbacks
  44. * triggers a bug in SQLite that leads either to irritating results or
  45. * segfaults, depending on the SQLite version */
  46. #if SQLITE_VERSION_NUMBER >= 3003003
  47. sqlite3_result_error(ctx, errmsg, len);
  48. #else
  49. PyErr_SetString(pysqlite_OperationalError, errmsg);
  50. #endif
  51. }
  52. int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  53. {
  54. static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
  55. PyObject* database;
  56. int detect_types = 0;
  57. PyObject* isolation_level = NULL;
  58. PyObject* factory = NULL;
  59. int check_same_thread = 1;
  60. int cached_statements = 100;
  61. double timeout = 5.0;
  62. int rc;
  63. PyObject* class_attr = NULL;
  64. PyObject* class_attr_str = NULL;
  65. int is_apsw_connection = 0;
  66. PyObject* database_utf8;
  67. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|diOiOi", kwlist,
  68. &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
  69. {
  70. return -1;
  71. }
  72. self->initialized = 1;
  73. self->begin_statement = NULL;
  74. self->statement_cache = NULL;
  75. self->statements = NULL;
  76. self->cursors = NULL;
  77. Py_INCREF(Py_None);
  78. self->row_factory = Py_None;
  79. Py_INCREF(&PyUnicode_Type);
  80. self->text_factory = (PyObject*)&PyUnicode_Type;
  81. if (PyString_Check(database) || PyUnicode_Check(database)) {
  82. if (PyString_Check(database)) {
  83. database_utf8 = database;
  84. Py_INCREF(database_utf8);
  85. } else {
  86. database_utf8 = PyUnicode_AsUTF8String(database);
  87. if (!database_utf8) {
  88. return -1;
  89. }
  90. }
  91. Py_BEGIN_ALLOW_THREADS
  92. rc = sqlite3_open(PyString_AsString(database_utf8), &self->db);
  93. Py_END_ALLOW_THREADS
  94. Py_DECREF(database_utf8);
  95. if (rc != SQLITE_OK) {
  96. _pysqlite_seterror(self->db, NULL);
  97. return -1;
  98. }
  99. } else {
  100. /* Create a pysqlite connection from a APSW connection */
  101. class_attr = PyObject_GetAttrString(database, "__class__");
  102. if (class_attr) {
  103. class_attr_str = PyObject_Str(class_attr);
  104. if (class_attr_str) {
  105. if (strcmp(PyString_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) {
  106. /* In the APSW Connection object, the first entry after
  107. * PyObject_HEAD is the sqlite3* we want to get hold of.
  108. * Luckily, this is the same layout as we have in our
  109. * pysqlite_Connection */
  110. self->db = ((pysqlite_Connection*)database)->db;
  111. Py_INCREF(database);
  112. self->apsw_connection = database;
  113. is_apsw_connection = 1;
  114. }
  115. }
  116. }
  117. Py_XDECREF(class_attr_str);
  118. Py_XDECREF(class_attr);
  119. if (!is_apsw_connection) {
  120. PyErr_SetString(PyExc_ValueError, "database parameter must be string or APSW Connection object");
  121. return -1;
  122. }
  123. }
  124. if (!isolation_level) {
  125. isolation_level = PyString_FromString("");
  126. if (!isolation_level) {
  127. return -1;
  128. }
  129. } else {
  130. Py_INCREF(isolation_level);
  131. }
  132. self->isolation_level = NULL;
  133. pysqlite_connection_set_isolation_level(self, isolation_level);
  134. Py_DECREF(isolation_level);
  135. self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
  136. if (PyErr_Occurred()) {
  137. return -1;
  138. }
  139. self->created_statements = 0;
  140. self->created_cursors = 0;
  141. /* Create lists of weak references to statements/cursors */
  142. self->statements = PyList_New(0);
  143. self->cursors = PyList_New(0);
  144. if (!self->statements || !self->cursors) {
  145. return -1;
  146. }
  147. /* By default, the Cache class INCREFs the factory in its initializer, and
  148. * decrefs it in its deallocator method. Since this would create a circular
  149. * reference here, we're breaking it by decrementing self, and telling the
  150. * cache class to not decref the factory (self) in its deallocator.
  151. */
  152. self->statement_cache->decref_factory = 0;
  153. Py_DECREF(self);
  154. self->inTransaction = 0;
  155. self->detect_types = detect_types;
  156. self->timeout = timeout;
  157. (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
  158. self->thread_ident = PyThread_get_thread_ident();
  159. self->check_same_thread = check_same_thread;
  160. self->function_pinboard = PyDict_New();
  161. if (!self->function_pinboard) {
  162. return -1;
  163. }
  164. self->collations = PyDict_New();
  165. if (!self->collations) {
  166. return -1;
  167. }
  168. self->Warning = pysqlite_Warning;
  169. self->Error = pysqlite_Error;
  170. self->InterfaceError = pysqlite_InterfaceError;
  171. self->DatabaseError = pysqlite_DatabaseError;
  172. self->DataError = pysqlite_DataError;
  173. self->OperationalError = pysqlite_OperationalError;
  174. self->IntegrityError = pysqlite_IntegrityError;
  175. self->InternalError = pysqlite_InternalError;
  176. self->ProgrammingError = pysqlite_ProgrammingError;
  177. self->NotSupportedError = pysqlite_NotSupportedError;
  178. return 0;
  179. }
  180. /* Empty the entire statement cache of this connection */
  181. void pysqlite_flush_statement_cache(pysqlite_Connection* self)
  182. {
  183. pysqlite_Node* node;
  184. pysqlite_Statement* statement;
  185. node = self->statement_cache->first;
  186. while (node) {
  187. statement = (pysqlite_Statement*)(node->data);
  188. (void)pysqlite_statement_finalize(statement);
  189. node = node->next;
  190. }
  191. Py_DECREF(self->statement_cache);
  192. self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
  193. Py_DECREF(self);
  194. self->statement_cache->decref_factory = 0;
  195. }
  196. /* action in (ACTION_RESET, ACTION_FINALIZE) */
  197. void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
  198. {
  199. int i;
  200. PyObject* weakref;
  201. PyObject* statement;
  202. pysqlite_Cursor* cursor;
  203. for (i = 0; i < PyList_Size(self->statements); i++) {
  204. weakref = PyList_GetItem(self->statements, i);
  205. statement = PyWeakref_GetObject(weakref);
  206. if (statement != Py_None) {
  207. if (action == ACTION_RESET) {
  208. (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
  209. } else {
  210. (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
  211. }
  212. }
  213. }
  214. if (reset_cursors) {
  215. for (i = 0; i < PyList_Size(self->cursors); i++) {
  216. weakref = PyList_GetItem(self->cursors, i);
  217. cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
  218. if ((PyObject*)cursor != Py_None) {
  219. cursor->reset = 1;
  220. }
  221. }
  222. }
  223. }
  224. void pysqlite_connection_dealloc(pysqlite_Connection* self)
  225. {
  226. PyObject* ret = NULL;
  227. Py_XDECREF(self->statement_cache);
  228. /* Clean up if user has not called .close() explicitly. */
  229. if (self->db) {
  230. Py_BEGIN_ALLOW_THREADS
  231. sqlite3_close(self->db);
  232. Py_END_ALLOW_THREADS
  233. } else if (self->apsw_connection) {
  234. ret = PyObject_CallMethod(self->apsw_connection, "close", "");
  235. Py_XDECREF(ret);
  236. Py_XDECREF(self->apsw_connection);
  237. }
  238. if (self->begin_statement) {
  239. PyMem_Free(self->begin_statement);
  240. }
  241. Py_XDECREF(self->isolation_level);
  242. Py_XDECREF(self->function_pinboard);
  243. Py_XDECREF(self->row_factory);
  244. Py_XDECREF(self->text_factory);
  245. Py_XDECREF(self->collations);
  246. Py_XDECREF(self->statements);
  247. Py_XDECREF(self->cursors);
  248. self->ob_type->tp_free((PyObject*)self);
  249. }
  250. /*
  251. * Registers a cursor with the connection.
  252. *
  253. * 0 => error; 1 => ok
  254. */
  255. int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
  256. {
  257. PyObject* weakref;
  258. weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
  259. if (!weakref) {
  260. goto error;
  261. }
  262. if (PyList_Append(connection->cursors, weakref) != 0) {
  263. Py_CLEAR(weakref);
  264. goto error;
  265. }
  266. Py_DECREF(weakref);
  267. return 1;
  268. error:
  269. return 0;
  270. }
  271. PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  272. {
  273. static char *kwlist[] = {"factory", NULL, NULL};
  274. PyObject* factory = NULL;
  275. PyObject* cursor;
  276. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
  277. &factory)) {
  278. return NULL;
  279. }
  280. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  281. return NULL;
  282. }
  283. if (factory == NULL) {
  284. factory = (PyObject*)&pysqlite_CursorType;
  285. }
  286. cursor = PyObject_CallFunction(factory, "O", self);
  287. _pysqlite_drop_unused_cursor_references(self);
  288. if (cursor && self->row_factory != Py_None) {
  289. Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
  290. Py_INCREF(self->row_factory);
  291. ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
  292. }
  293. return cursor;
  294. }
  295. PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
  296. {
  297. PyObject* ret;
  298. int rc;
  299. if (!pysqlite_check_thread(self)) {
  300. return NULL;
  301. }
  302. pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
  303. if (self->db) {
  304. if (self->apsw_connection) {
  305. ret = PyObject_CallMethod(self->apsw_connection, "close", "");
  306. Py_XDECREF(ret);
  307. Py_XDECREF(self->apsw_connection);
  308. self->apsw_connection = NULL;
  309. self->db = NULL;
  310. } else {
  311. Py_BEGIN_ALLOW_THREADS
  312. rc = sqlite3_close(self->db);
  313. Py_END_ALLOW_THREADS
  314. if (rc != SQLITE_OK) {
  315. _pysqlite_seterror(self->db, NULL);
  316. return NULL;
  317. } else {
  318. self->db = NULL;
  319. }
  320. }
  321. }
  322. Py_INCREF(Py_None);
  323. return Py_None;
  324. }
  325. /*
  326. * Checks if a connection object is usable.
  327. *
  328. * 0 => error; 1 => ok
  329. */
  330. int pysqlite_check_connection(pysqlite_Connection* con)
  331. {
  332. if (!con->initialized) {
  333. PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
  334. return 0;
  335. }
  336. if (!con->db) {
  337. PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
  338. return 0;
  339. } else {
  340. return 1;
  341. }
  342. }
  343. PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
  344. {
  345. int rc;
  346. const char* tail;
  347. sqlite3_stmt* statement;
  348. Py_BEGIN_ALLOW_THREADS
  349. rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
  350. Py_END_ALLOW_THREADS
  351. if (rc != SQLITE_OK) {
  352. _pysqlite_seterror(self->db, statement);
  353. goto error;
  354. }
  355. rc = pysqlite_step(statement, self);
  356. if (rc == SQLITE_DONE) {
  357. self->inTransaction = 1;
  358. } else {
  359. _pysqlite_seterror(self->db, statement);
  360. }
  361. Py_BEGIN_ALLOW_THREADS
  362. rc = sqlite3_finalize(statement);
  363. Py_END_ALLOW_THREADS
  364. if (rc != SQLITE_OK && !PyErr_Occurred()) {
  365. _pysqlite_seterror(self->db, NULL);
  366. }
  367. error:
  368. if (PyErr_Occurred()) {
  369. return NULL;
  370. } else {
  371. Py_INCREF(Py_None);
  372. return Py_None;
  373. }
  374. }
  375. PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
  376. {
  377. int rc;
  378. const char* tail;
  379. sqlite3_stmt* statement;
  380. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  381. return NULL;
  382. }
  383. if (self->inTransaction) {
  384. pysqlite_do_all_statements(self, ACTION_RESET, 0);
  385. Py_BEGIN_ALLOW_THREADS
  386. rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
  387. Py_END_ALLOW_THREADS
  388. if (rc != SQLITE_OK) {
  389. _pysqlite_seterror(self->db, NULL);
  390. goto error;
  391. }
  392. rc = pysqlite_step(statement, self);
  393. if (rc == SQLITE_DONE) {
  394. self->inTransaction = 0;
  395. } else {
  396. _pysqlite_seterror(self->db, statement);
  397. }
  398. Py_BEGIN_ALLOW_THREADS
  399. rc = sqlite3_finalize(statement);
  400. Py_END_ALLOW_THREADS
  401. if (rc != SQLITE_OK && !PyErr_Occurred()) {
  402. _pysqlite_seterror(self->db, NULL);
  403. }
  404. }
  405. error:
  406. if (PyErr_Occurred()) {
  407. return NULL;
  408. } else {
  409. Py_INCREF(Py_None);
  410. return Py_None;
  411. }
  412. }
  413. PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
  414. {
  415. int rc;
  416. const char* tail;
  417. sqlite3_stmt* statement;
  418. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  419. return NULL;
  420. }
  421. if (self->inTransaction) {
  422. pysqlite_do_all_statements(self, ACTION_RESET, 1);
  423. Py_BEGIN_ALLOW_THREADS
  424. rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
  425. Py_END_ALLOW_THREADS
  426. if (rc != SQLITE_OK) {
  427. _pysqlite_seterror(self->db, NULL);
  428. goto error;
  429. }
  430. rc = pysqlite_step(statement, self);
  431. if (rc == SQLITE_DONE) {
  432. self->inTransaction = 0;
  433. } else {
  434. _pysqlite_seterror(self->db, statement);
  435. }
  436. Py_BEGIN_ALLOW_THREADS
  437. rc = sqlite3_finalize(statement);
  438. Py_END_ALLOW_THREADS
  439. if (rc != SQLITE_OK && !PyErr_Occurred()) {
  440. _pysqlite_seterror(self->db, NULL);
  441. }
  442. }
  443. error:
  444. if (PyErr_Occurred()) {
  445. return NULL;
  446. } else {
  447. Py_INCREF(Py_None);
  448. return Py_None;
  449. }
  450. }
  451. void _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
  452. {
  453. long longval;
  454. const char* buffer;
  455. Py_ssize_t buflen;
  456. PyObject* stringval;
  457. if ((!py_val) || PyErr_Occurred()) {
  458. sqlite3_result_null(context);
  459. } else if (py_val == Py_None) {
  460. sqlite3_result_null(context);
  461. } else if (PyInt_Check(py_val)) {
  462. longval = PyInt_AsLong(py_val);
  463. sqlite3_result_int64(context, (PY_LONG_LONG)longval);
  464. } else if (PyFloat_Check(py_val)) {
  465. sqlite3_result_double(context, PyFloat_AsDouble(py_val));
  466. } else if (PyBuffer_Check(py_val)) {
  467. if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
  468. PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
  469. } else {
  470. sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
  471. }
  472. } else if (PyString_Check(py_val)) {
  473. sqlite3_result_text(context, PyString_AsString(py_val), -1, SQLITE_TRANSIENT);
  474. } else if (PyUnicode_Check(py_val)) {
  475. stringval = PyUnicode_AsUTF8String(py_val);
  476. if (stringval) {
  477. sqlite3_result_text(context, PyString_AsString(stringval), -1, SQLITE_TRANSIENT);
  478. Py_DECREF(stringval);
  479. }
  480. } else {
  481. /* TODO: raise error */
  482. }
  483. }
  484. PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
  485. {
  486. PyObject* args;
  487. int i;
  488. sqlite3_value* cur_value;
  489. PyObject* cur_py_value;
  490. const char* val_str;
  491. PY_LONG_LONG val_int;
  492. Py_ssize_t buflen;
  493. void* raw_buffer;
  494. args = PyTuple_New(argc);
  495. if (!args) {
  496. return NULL;
  497. }
  498. for (i = 0; i < argc; i++) {
  499. cur_value = argv[i];
  500. switch (sqlite3_value_type(argv[i])) {
  501. case SQLITE_INTEGER:
  502. val_int = sqlite3_value_int64(cur_value);
  503. cur_py_value = PyInt_FromLong((long)val_int);
  504. break;
  505. case SQLITE_FLOAT:
  506. cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
  507. break;
  508. case SQLITE_TEXT:
  509. val_str = (const char*)sqlite3_value_text(cur_value);
  510. cur_py_value = PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL);
  511. /* TODO: have a way to show errors here */
  512. if (!cur_py_value) {
  513. PyErr_Clear();
  514. Py_INCREF(Py_None);
  515. cur_py_value = Py_None;
  516. }
  517. break;
  518. case SQLITE_BLOB:
  519. buflen = sqlite3_value_bytes(cur_value);
  520. cur_py_value = PyBuffer_New(buflen);
  521. if (!cur_py_value) {
  522. break;
  523. }
  524. if (PyObject_AsWriteBuffer(cur_py_value, &raw_buffer, &buflen)) {
  525. Py_DECREF(cur_py_value);
  526. cur_py_value = NULL;
  527. break;
  528. }
  529. memcpy(raw_buffer, sqlite3_value_blob(cur_value), buflen);
  530. break;
  531. case SQLITE_NULL:
  532. default:
  533. Py_INCREF(Py_None);
  534. cur_py_value = Py_None;
  535. }
  536. if (!cur_py_value) {
  537. Py_DECREF(args);
  538. return NULL;
  539. }
  540. PyTuple_SetItem(args, i, cur_py_value);
  541. }
  542. return args;
  543. }
  544. void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
  545. {
  546. PyObject* args;
  547. PyObject* py_func;
  548. PyObject* py_retval = NULL;
  549. PyGILState_STATE threadstate;
  550. threadstate = PyGILState_Ensure();
  551. py_func = (PyObject*)sqlite3_user_data(context);
  552. args = _pysqlite_build_py_params(context, argc, argv);
  553. if (args) {
  554. py_retval = PyObject_CallObject(py_func, args);
  555. Py_DECREF(args);
  556. }
  557. if (py_retval) {
  558. _pysqlite_set_result(context, py_retval);
  559. Py_DECREF(py_retval);
  560. } else {
  561. if (_enable_callback_tracebacks) {
  562. PyErr_Print();
  563. } else {
  564. PyErr_Clear();
  565. }
  566. _sqlite3_result_error(context, "user-defined function raised exception", -1);
  567. }
  568. PyGILState_Release(threadstate);
  569. }
  570. static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
  571. {
  572. PyObject* args;
  573. PyObject* function_result = NULL;
  574. PyObject* aggregate_class;
  575. PyObject** aggregate_instance;
  576. PyObject* stepmethod = NULL;
  577. PyGILState_STATE threadstate;
  578. threadstate = PyGILState_Ensure();
  579. aggregate_class = (PyObject*)sqlite3_user_data(context);
  580. aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
  581. if (*aggregate_instance == 0) {
  582. *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
  583. if (PyErr_Occurred()) {
  584. *aggregate_instance = 0;
  585. if (_enable_callback_tracebacks) {
  586. PyErr_Print();
  587. } else {
  588. PyErr_Clear();
  589. }
  590. _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
  591. goto error;
  592. }
  593. }
  594. stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
  595. if (!stepmethod) {
  596. goto error;
  597. }
  598. args = _pysqlite_build_py_params(context, argc, params);
  599. if (!args) {
  600. goto error;
  601. }
  602. function_result = PyObject_CallObject(stepmethod, args);
  603. Py_DECREF(args);
  604. if (!function_result) {
  605. if (_enable_callback_tracebacks) {
  606. PyErr_Print();
  607. } else {
  608. PyErr_Clear();
  609. }
  610. _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
  611. }
  612. error:
  613. Py_XDECREF(stepmethod);
  614. Py_XDECREF(function_result);
  615. PyGILState_Release(threadstate);
  616. }
  617. void _pysqlite_final_callback(sqlite3_context* context)
  618. {
  619. PyObject* function_result = NULL;
  620. PyObject** aggregate_instance;
  621. PyObject* aggregate_class;
  622. PyGILState_STATE threadstate;
  623. threadstate = PyGILState_Ensure();
  624. aggregate_class = (PyObject*)sqlite3_user_data(context);
  625. aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
  626. if (!*aggregate_instance) {
  627. /* this branch is executed if there was an exception in the aggregate's
  628. * __init__ */
  629. goto error;
  630. }
  631. function_result = PyObject_CallMethod(*aggregate_instance, "finalize", "");
  632. if (!function_result) {
  633. if (_enable_callback_tracebacks) {
  634. PyErr_Print();
  635. } else {
  636. PyErr_Clear();
  637. }
  638. _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
  639. } else {
  640. _pysqlite_set_result(context, function_result);
  641. }
  642. error:
  643. Py_XDECREF(*aggregate_instance);
  644. Py_XDECREF(function_result);
  645. PyGILState_Release(threadstate);
  646. }
  647. static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
  648. {
  649. PyObject* new_list;
  650. PyObject* weakref;
  651. int i;
  652. /* we only need to do this once in a while */
  653. if (self->created_statements++ < 200) {
  654. return;
  655. }
  656. self->created_statements = 0;
  657. new_list = PyList_New(0);
  658. if (!new_list) {
  659. return;
  660. }
  661. for (i = 0; i < PyList_Size(self->statements); i++) {
  662. weakref = PyList_GetItem(self->statements, i);
  663. if (PyWeakref_GetObject(weakref) != Py_None) {
  664. if (PyList_Append(new_list, weakref) != 0) {
  665. Py_DECREF(new_list);
  666. return;
  667. }
  668. }
  669. }
  670. Py_DECREF(self->statements);
  671. self->statements = new_list;
  672. }
  673. static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
  674. {
  675. PyObject* new_list;
  676. PyObject* weakref;
  677. int i;
  678. /* we only need to do this once in a while */
  679. if (self->created_cursors++ < 200) {
  680. return;
  681. }
  682. self->created_cursors = 0;
  683. new_list = PyList_New(0);
  684. if (!new_list) {
  685. return;
  686. }
  687. for (i = 0; i < PyList_Size(self->cursors); i++) {
  688. weakref = PyList_GetItem(self->cursors, i);
  689. if (PyWeakref_GetObject(weakref) != Py_None) {
  690. if (PyList_Append(new_list, weakref) != 0) {
  691. Py_DECREF(new_list);
  692. return;
  693. }
  694. }
  695. }
  696. Py_DECREF(self->cursors);
  697. self->cursors = new_list;
  698. }
  699. PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  700. {
  701. static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
  702. PyObject* func;
  703. char* name;
  704. int narg;
  705. int rc;
  706. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
  707. &name, &narg, &func))
  708. {
  709. return NULL;
  710. }
  711. rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
  712. if (rc != SQLITE_OK) {
  713. /* Workaround for SQLite bug: no error code or string is available here */
  714. PyErr_SetString(pysqlite_OperationalError, "Error creating function");
  715. return NULL;
  716. } else {
  717. PyDict_SetItem(self->function_pinboard, func, Py_None);
  718. Py_INCREF(Py_None);
  719. return Py_None;
  720. }
  721. }
  722. PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  723. {
  724. PyObject* aggregate_class;
  725. int n_arg;
  726. char* name;
  727. static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
  728. int rc;
  729. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
  730. kwlist, &name, &n_arg, &aggregate_class)) {
  731. return NULL;
  732. }
  733. rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
  734. if (rc != SQLITE_OK) {
  735. /* Workaround for SQLite bug: no error code or string is available here */
  736. PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
  737. return NULL;
  738. } else {
  739. PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
  740. Py_INCREF(Py_None);
  741. return Py_None;
  742. }
  743. }
  744. static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
  745. {
  746. PyObject *ret;
  747. int rc;
  748. PyGILState_STATE gilstate;
  749. gilstate = PyGILState_Ensure();
  750. ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
  751. if (!ret) {
  752. if (_enable_callback_tracebacks) {
  753. PyErr_Print();
  754. } else {
  755. PyErr_Clear();
  756. }
  757. rc = SQLITE_DENY;
  758. } else {
  759. if (PyInt_Check(ret)) {
  760. rc = (int)PyInt_AsLong(ret);
  761. } else {
  762. rc = SQLITE_DENY;
  763. }
  764. Py_DECREF(ret);
  765. }
  766. PyGILState_Release(gilstate);
  767. return rc;
  768. }
  769. static int _progress_handler(void* user_arg)
  770. {
  771. int rc;
  772. PyObject *ret;
  773. PyGILState_STATE gilstate;
  774. gilstate = PyGILState_Ensure();
  775. ret = PyObject_CallFunction((PyObject*)user_arg, "");
  776. if (!ret) {
  777. if (_enable_callback_tracebacks) {
  778. PyErr_Print();
  779. } else {
  780. PyErr_Clear();
  781. }
  782. /* abort query if error occured */
  783. rc = 1;
  784. } else {
  785. rc = (int)PyObject_IsTrue(ret);
  786. Py_DECREF(ret);
  787. }
  788. PyGILState_Release(gilstate);
  789. return rc;
  790. }
  791. static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  792. {
  793. PyObject* authorizer_cb;
  794. static char *kwlist[] = { "authorizer_callback", NULL };
  795. int rc;
  796. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
  797. kwlist, &authorizer_cb)) {
  798. return NULL;
  799. }
  800. rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
  801. if (rc != SQLITE_OK) {
  802. PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
  803. return NULL;
  804. } else {
  805. PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None);
  806. Py_INCREF(Py_None);
  807. return Py_None;
  808. }
  809. }
  810. static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  811. {
  812. PyObject* progress_handler;
  813. int n;
  814. static char *kwlist[] = { "progress_handler", "n", NULL };
  815. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
  816. kwlist, &progress_handler, &n)) {
  817. return NULL;
  818. }
  819. if (progress_handler == Py_None) {
  820. /* None clears the progress handler previously set */
  821. sqlite3_progress_handler(self->db, 0, 0, (void*)0);
  822. } else {
  823. sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
  824. PyDict_SetItem(self->function_pinboard, progress_handler, Py_None);
  825. }
  826. Py_INCREF(Py_None);
  827. return Py_None;
  828. }
  829. #ifdef HAVE_LOAD_EXTENSION
  830. static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
  831. {
  832. int rc;
  833. int onoff;
  834. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  835. return NULL;
  836. }
  837. if (!PyArg_ParseTuple(args, "i", &onoff)) {
  838. return NULL;
  839. }
  840. rc = sqlite3_enable_load_extension(self->db, onoff);
  841. if (rc != SQLITE_OK) {
  842. PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
  843. return NULL;
  844. } else {
  845. Py_INCREF(Py_None);
  846. return Py_None;
  847. }
  848. }
  849. static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
  850. {
  851. int rc;
  852. char* extension_name;
  853. char* errmsg;
  854. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  855. return NULL;
  856. }
  857. if (!PyArg_ParseTuple(args, "s", &extension_name)) {
  858. return NULL;
  859. }
  860. rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
  861. if (rc != 0) {
  862. PyErr_SetString(pysqlite_OperationalError, errmsg);
  863. return NULL;
  864. } else {
  865. Py_INCREF(Py_None);
  866. return Py_None;
  867. }
  868. }
  869. #endif
  870. int pysqlite_check_thread(pysqlite_Connection* self)
  871. {
  872. if (self->check_same_thread) {
  873. if (PyThread_get_thread_ident() != self->thread_ident) {
  874. PyErr_Format(pysqlite_ProgrammingError,
  875. "SQLite objects created in a thread can only be used in that same thread."
  876. "The object was created in thread id %ld and this is thread id %ld",
  877. self->thread_ident, PyThread_get_thread_ident());
  878. return 0;
  879. }
  880. }
  881. return 1;
  882. }
  883. static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
  884. {
  885. Py_INCREF(self->isolation_level);
  886. return self->isolation_level;
  887. }
  888. static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
  889. {
  890. if (!pysqlite_check_connection(self)) {
  891. return NULL;
  892. } else {
  893. return Py_BuildValue("i", sqlite3_total_changes(self->db));
  894. }
  895. }
  896. static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
  897. {
  898. PyObject* res;
  899. PyObject* begin_statement;
  900. char* begin_statement_str;
  901. Py_XDECREF(self->isolation_level);
  902. if (self->begin_statement) {
  903. PyMem_Free(self->begin_statement);
  904. self->begin_statement = NULL;
  905. }
  906. if (isolation_level == Py_None) {
  907. Py_INCREF(Py_None);
  908. self->isolation_level = Py_None;
  909. res = pysqlite_connection_commit(self, NULL);
  910. if (!res) {
  911. return -1;
  912. }
  913. Py_DECREF(res);
  914. self->inTransaction = 0;
  915. } else {
  916. Py_INCREF(isolation_level);
  917. self->isolation_level = isolation_level;
  918. begin_statement = PyString_FromString("BEGIN ");
  919. if (!begin_statement) {
  920. return -1;
  921. }
  922. PyString_Concat(&begin_statement, isolation_level);
  923. if (!begin_statement) {
  924. return -1;
  925. }
  926. begin_statement_str = PyString_AsString(begin_statement);
  927. if (!begin_statement_str) {
  928. Py_DECREF(begin_statement);
  929. return -1;
  930. }
  931. self->begin_statement = PyMem_Malloc(strlen(begin_statement_str) + 2);
  932. if (!self->begin_statement) {
  933. Py_DECREF(begin_statement);
  934. return -1;
  935. }
  936. strcpy(self->begin_statement, begin_statement_str);
  937. Py_DECREF(begin_statement);
  938. }
  939. return 0;
  940. }
  941. PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  942. {
  943. PyObject* sql;
  944. pysqlite_Statement* statement;
  945. PyObject* weakref;
  946. int rc;
  947. if (!PyArg_ParseTuple(args, "O", &sql)) {
  948. return NULL;
  949. }
  950. _pysqlite_drop_unused_statement_references(self);
  951. statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
  952. if (!statement) {
  953. return NULL;
  954. }
  955. rc = pysqlite_statement_create(statement, self, sql);
  956. if (rc != SQLITE_OK) {
  957. if (rc == PYSQLITE_TOO_MUCH_SQL) {
  958. PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
  959. } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
  960. PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
  961. } else {
  962. (void)pysqlite_statement_reset(statement);
  963. _pysqlite_seterror(self->db, NULL);
  964. }
  965. Py_CLEAR(statement);
  966. } else {
  967. weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
  968. if (!weakref) {
  969. Py_CLEAR(statement);
  970. goto error;
  971. }
  972. if (PyList_Append(self->statements, weakref) != 0) {
  973. Py_CLEAR(weakref);
  974. goto error;
  975. }
  976. Py_DECREF(weakref);
  977. }
  978. error:
  979. return (PyObject*)statement;
  980. }
  981. PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  982. {
  983. PyObject* cursor = 0;
  984. PyObject* result = 0;
  985. PyObject* method = 0;
  986. cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
  987. if (!cursor) {
  988. goto error;
  989. }
  990. method = PyObject_GetAttrString(cursor, "execute");
  991. if (!method) {
  992. Py_CLEAR(cursor);
  993. goto error;
  994. }
  995. result = PyObject_CallObject(method, args);
  996. if (!result) {
  997. Py_CLEAR(cursor);
  998. }
  999. error:
  1000. Py_XDECREF(result);
  1001. Py_XDECREF(method);
  1002. return cursor;
  1003. }
  1004. PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  1005. {
  1006. PyObject* cursor = 0;
  1007. PyObject* result = 0;
  1008. PyObject* method = 0;
  1009. cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
  1010. if (!cursor) {
  1011. goto error;
  1012. }
  1013. method = PyObject_GetAttrString(cursor, "executemany");
  1014. if (!method) {
  1015. Py_CLEAR(cursor);
  1016. goto error;
  1017. }
  1018. result = PyObject_CallObject(method, args);
  1019. if (!result) {
  1020. Py_CLEAR(cursor);
  1021. }
  1022. error:
  1023. Py_XDECREF(result);
  1024. Py_XDECREF(method);
  1025. return cursor;
  1026. }
  1027. PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
  1028. {
  1029. PyObject* cursor = 0;
  1030. PyObject* result = 0;
  1031. PyObject* method = 0;
  1032. cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
  1033. if (!cursor) {
  1034. goto error;
  1035. }
  1036. method = PyObject_GetAttrString(cursor, "executescript");
  1037. if (!method) {
  1038. Py_CLEAR(cursor);
  1039. goto error;
  1040. }
  1041. result = PyObject_CallObject(method, args);
  1042. if (!result) {
  1043. Py_CLEAR(cursor);
  1044. }
  1045. error:
  1046. Py_XDECREF(result);
  1047. Py_XDECREF(method);
  1048. return cursor;
  1049. }
  1050. /* ------------------------- COLLATION CODE ------------------------ */
  1051. static int
  1052. pysqlite_collation_callback(
  1053. void* context,
  1054. int text1_length, const void* text1_data,
  1055. int text2_length, const void* text2_data)
  1056. {
  1057. PyObject* callback = (PyObject*)context;
  1058. PyObject* string1 = 0;
  1059. PyObject* string2 = 0;
  1060. PyGILState_STATE gilstate;
  1061. PyObject* retval = NULL;
  1062. int result = 0;
  1063. gilstate = PyGILState_Ensure();
  1064. if (PyErr_Occurred()) {
  1065. goto finally;
  1066. }
  1067. string1 = PyString_FromStringAndSize((const char*)text1_data, text1_length);
  1068. string2 = PyString_FromStringAndSize((const char*)text2_data, text2_length);
  1069. if (!string1 || !string2) {
  1070. goto finally; /* failed to allocate strings */
  1071. }
  1072. retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
  1073. if (!retval) {
  1074. /* execution failed */
  1075. goto finally;
  1076. }
  1077. result = PyInt_AsLong(retval);
  1078. if (PyErr_Occurred()) {
  1079. result = 0;
  1080. }
  1081. finally:
  1082. Py_XDECREF(string1);
  1083. Py_XDECREF(string2);
  1084. Py_XDECREF(retval);
  1085. PyGILState_Release(gilstate);
  1086. return result;
  1087. }
  1088. static PyObject *
  1089. pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
  1090. {
  1091. PyObject* retval = NULL;
  1092. if (!pysqlite_check_connection(self)) {
  1093. goto finally;
  1094. }
  1095. sqlite3_interrupt(self->db);
  1096. Py_INCREF(Py_None);
  1097. retval = Py_None;
  1098. finally:
  1099. return retval;
  1100. }
  1101. /* Function author: Paul Kippes <kippesp@gmail.com>
  1102. * Class method of Connection to call the Python function _iterdump
  1103. * of the sqlite3 module.
  1104. */
  1105. static PyObject *
  1106. pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
  1107. {
  1108. PyObject* retval = NULL;
  1109. PyObject* module = NULL;
  1110. PyObject* module_dict;
  1111. PyObject* pyfn_iterdump;
  1112. if (!pysqlite_check_connection(self)) {
  1113. goto finally;
  1114. }
  1115. module = PyImport_ImportModule("pysqlite2.dump");
  1116. if (!module) {
  1117. goto finally;
  1118. }
  1119. module_dict = PyModule_GetDict(module);
  1120. if (!module_dict) {
  1121. goto finally;
  1122. }
  1123. pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
  1124. if (!pyfn_iterdump) {
  1125. PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
  1126. goto finally;
  1127. }
  1128. args = PyTuple_New(1);
  1129. if (!args) {
  1130. goto finally;
  1131. }
  1132. Py_INCREF(self);
  1133. PyTuple_SetItem(args, 0, (PyObject*)self);
  1134. retval = PyObject_CallObject(pyfn_iterdump, args);
  1135. finally:
  1136. Py_XDECREF(args);
  1137. Py_XDECREF(module);
  1138. return retval;
  1139. }
  1140. static PyObject *
  1141. pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
  1142. {
  1143. PyObject* callable;
  1144. PyObject* uppercase_name = 0;
  1145. PyObject* name;
  1146. PyObject* retval;
  1147. char* chk;
  1148. int rc;
  1149. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1150. goto finally;
  1151. }
  1152. if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyString_Type, &name, &callable)) {
  1153. goto finally;
  1154. }
  1155. uppercase_name = PyObject_CallMethod(name, "upper", "");
  1156. if (!uppercase_name) {
  1157. goto finally;
  1158. }
  1159. chk = PyString_AsString(uppercase_name);
  1160. while (*chk) {
  1161. if ((*chk >= '0' && *chk <= '9')
  1162. || (*chk >= 'A' && *chk <= 'Z')
  1163. || (*chk == '_'))
  1164. {
  1165. chk++;
  1166. } else {
  1167. PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
  1168. goto finally;
  1169. }
  1170. }
  1171. if (callable != Py_None && !PyCallable_Check(callable)) {
  1172. PyErr_SetString(PyExc_TypeError, "parameter must be callable");
  1173. goto finally;
  1174. }
  1175. if (callable != Py_None) {
  1176. PyDict_SetItem(self->collations, uppercase_name, callable);
  1177. } else {
  1178. PyDict_DelItem(self->collations, uppercase_name);
  1179. }
  1180. rc = sqlite3_create_collation(self->db,
  1181. PyString_AsString(uppercase_name),
  1182. SQLITE_UTF8,
  1183. (callable != Py_None) ? callable : NULL,
  1184. (callable != Py_None) ? pysqlite_collation_callback : NULL);
  1185. if (rc != SQLITE_OK) {
  1186. PyDict_DelItem(self->collations, uppercase_name);
  1187. _pysqlite_seterror(self->db, NULL);
  1188. goto finally;
  1189. }
  1190. finally:
  1191. Py_XDECREF(uppercase_name);
  1192. if (PyErr_Occurred()) {
  1193. retval = NULL;
  1194. } else {
  1195. Py_INCREF(Py_None);
  1196. retval = Py_None;
  1197. }
  1198. return retval;
  1199. }
  1200. /* Called when the connection is used as a context manager. Returns itself as a
  1201. * convenience to the caller. */
  1202. static PyObject *
  1203. pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
  1204. {
  1205. Py_INCREF(self);
  1206. return (PyObject*)self;
  1207. }
  1208. /** Called when the connection is used as a context manager. If there was any
  1209. * exception, a rollback takes place; otherwise we commit. */
  1210. static PyObject *
  1211. pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
  1212. {
  1213. PyObject* exc_type, *exc_value, *exc_tb;
  1214. char* method_name;
  1215. PyObject* result;
  1216. if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
  1217. return NULL;
  1218. }
  1219. if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
  1220. method_name = "commit";
  1221. } else {
  1222. method_name = "rollback";
  1223. }
  1224. result = PyObject_CallMethod((PyObject*)self, method_name, "");
  1225. if (!result) {
  1226. return NULL;
  1227. }
  1228. Py_DECREF(result);
  1229. Py_INCREF(Py_False);
  1230. return Py_False;
  1231. }
  1232. static char connection_doc[] =
  1233. PyDoc_STR("SQLite database connection object.");
  1234. static PyGetSetDef connection_getset[] = {
  1235. {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
  1236. {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
  1237. {NULL}
  1238. };
  1239. static PyMethodDef connection_methods[] = {
  1240. {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
  1241. PyDoc_STR("Return a cursor for the connection.")},
  1242. {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
  1243. PyDoc_STR("Closes the connection.")},
  1244. {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
  1245. PyDoc_STR("Commit the current transaction.")},
  1246. {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
  1247. PyDoc_STR("Roll back the current transaction.")},
  1248. {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
  1249. PyDoc_STR("Creates a new function. Non-standard.")},
  1250. {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
  1251. PyDoc_STR("Creates a new aggregate. Non-standard.")},
  1252. {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
  1253. PyDoc_STR("Sets authorizer callback. Non-standard.")},
  1254. #ifdef HAVE_LOAD_EXTENSION
  1255. {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
  1256. PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
  1257. {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
  1258. PyDoc_STR("Load SQLite extension module. Non-standard.")},
  1259. #endif
  1260. {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
  1261. PyDoc_STR("Sets progress handler callback. Non-standard.")},
  1262. {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
  1263. PyDoc_STR("Executes a SQL statement. Non-standard.")},
  1264. {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
  1265. PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
  1266. {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
  1267. PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
  1268. {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
  1269. PyDoc_STR("Creates a collation function. Non-standard.")},
  1270. {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
  1271. PyDoc_STR("Abort any pending database operation. Non-standard.")},
  1272. {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
  1273. PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
  1274. {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
  1275. PyDoc_STR("For context manager. Non-standard.")},
  1276. {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
  1277. PyDoc_STR("For context manager. Non-standard.")},
  1278. {NULL, NULL}
  1279. };
  1280. static struct PyMemberDef connection_members[] =
  1281. {
  1282. {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), RO},
  1283. {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), RO},
  1284. {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), RO},
  1285. {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), RO},
  1286. {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), RO},
  1287. {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), RO},
  1288. {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), RO},
  1289. {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), RO},
  1290. {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), RO},
  1291. {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), RO},
  1292. {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
  1293. {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
  1294. {NULL}
  1295. };
  1296. PyTypeObject pysqlite_ConnectionType = {
  1297. PyObject_HEAD_INIT(NULL)
  1298. 0, /* ob_size */
  1299. MODULE_NAME ".Connection", /* tp_name */
  1300. sizeof(pysqlite_Connection), /* tp_basicsize */
  1301. 0, /* tp_itemsize */
  1302. (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
  1303. 0, /* tp_print */
  1304. 0, /* tp_getattr */
  1305. 0, /* tp_setattr */
  1306. 0, /* tp_compare */
  1307. 0, /* tp_repr */
  1308. 0, /* tp_as_number */
  1309. 0, /* tp_as_sequence */
  1310. 0, /* tp_as_mapping */
  1311. 0, /* tp_hash */
  1312. (ternaryfunc)pysqlite_connection_call, /* tp_call */
  1313. 0, /* tp_str */
  1314. 0, /* tp_getattro */
  1315. 0, /* tp_setattro */
  1316. 0, /* tp_as_buffer */
  1317. Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
  1318. connection_doc, /* tp_doc */
  1319. 0, /* tp_traverse */
  1320. 0, /* tp_clear */
  1321. 0, /* tp_richcompare */
  1322. 0, /* tp_weaklistoffset */
  1323. 0, /* tp_iter */
  1324. 0, /* tp_iternext */
  1325. connection_methods, /* tp_methods */
  1326. connection_members, /* tp_members */
  1327. connection_getset, /* tp_getset */
  1328. 0, /* tp_base */
  1329. 0, /* tp_dict */
  1330. 0, /* tp_descr_get */
  1331. 0, /* tp_descr_set */
  1332. 0, /* tp_dictoffset */
  1333. (initproc)pysqlite_connection_init, /* tp_init */
  1334. 0, /* tp_alloc */
  1335. 0, /* tp_new */
  1336. 0 /* tp_free */
  1337. };
  1338. extern int pysqlite_connection_setup_types(void)
  1339. {
  1340. pysqlite_ConnectionType.tp_new = PyType_GenericNew;
  1341. return PyType_Ready(&pysqlite_ConnectionType);
  1342. }