connection.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. /* connection.c - the connection type
  2. *
  3. * Copyright (C) 2004-2010 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 "module.h"
  24. #include "structmember.h" // PyMemberDef
  25. #include "connection.h"
  26. #include "statement.h"
  27. #include "cursor.h"
  28. #include "blob.h"
  29. #include "prepare_protocol.h"
  30. #include "util.h"
  31. #include <stdbool.h>
  32. #if SQLITE_VERSION_NUMBER >= 3014000
  33. #define HAVE_TRACE_V2
  34. #endif
  35. #if SQLITE_VERSION_NUMBER >= 3025000
  36. #define HAVE_WINDOW_FUNCTIONS
  37. #endif
  38. static const char *
  39. get_isolation_level(const char *level)
  40. {
  41. assert(level != NULL);
  42. static const char *const allowed_levels[] = {
  43. "",
  44. "DEFERRED",
  45. "IMMEDIATE",
  46. "EXCLUSIVE",
  47. NULL
  48. };
  49. for (int i = 0; allowed_levels[i] != NULL; i++) {
  50. const char *candidate = allowed_levels[i];
  51. if (sqlite3_stricmp(level, candidate) == 0) {
  52. return candidate;
  53. }
  54. }
  55. PyErr_SetString(PyExc_ValueError,
  56. "isolation_level string must be '', 'DEFERRED', "
  57. "'IMMEDIATE', or 'EXCLUSIVE'");
  58. return NULL;
  59. }
  60. static int
  61. isolation_level_converter(PyObject *str_or_none, const char **result)
  62. {
  63. if (Py_IsNone(str_or_none)) {
  64. *result = NULL;
  65. }
  66. else if (PyUnicode_Check(str_or_none)) {
  67. Py_ssize_t sz;
  68. const char *str = PyUnicode_AsUTF8AndSize(str_or_none, &sz);
  69. if (str == NULL) {
  70. return 0;
  71. }
  72. if (strlen(str) != (size_t)sz) {
  73. PyErr_SetString(PyExc_ValueError, "embedded null character");
  74. return 0;
  75. }
  76. const char *level = get_isolation_level(str);
  77. if (level == NULL) {
  78. return 0;
  79. }
  80. *result = level;
  81. }
  82. else {
  83. PyErr_SetString(PyExc_TypeError,
  84. "isolation_level must be str or None");
  85. return 0;
  86. }
  87. return 1;
  88. }
  89. static int
  90. autocommit_converter(PyObject *val, enum autocommit_mode *result)
  91. {
  92. if (Py_IsTrue(val)) {
  93. *result = AUTOCOMMIT_ENABLED;
  94. return 1;
  95. }
  96. if (Py_IsFalse(val)) {
  97. *result = AUTOCOMMIT_DISABLED;
  98. return 1;
  99. }
  100. if (PyLong_Check(val) &&
  101. PyLong_AsLong(val) == LEGACY_TRANSACTION_CONTROL)
  102. {
  103. *result = AUTOCOMMIT_LEGACY;
  104. return 1;
  105. }
  106. PyErr_SetString(PyExc_ValueError,
  107. "autocommit must be True, False, or "
  108. "sqlite3.LEGACY_TRANSACTION_CONTROL");
  109. return 0;
  110. }
  111. static int
  112. sqlite3_int64_converter(PyObject *obj, sqlite3_int64 *result)
  113. {
  114. if (!PyLong_Check(obj)) {
  115. PyErr_SetString(PyExc_TypeError, "expected 'int'");
  116. return 0;
  117. }
  118. *result = _pysqlite_long_as_int64(obj);
  119. if (PyErr_Occurred()) {
  120. return 0;
  121. }
  122. return 1;
  123. }
  124. #define clinic_state() (pysqlite_get_state_by_type(Py_TYPE(self)))
  125. #include "clinic/connection.c.h"
  126. #undef clinic_state
  127. /*[clinic input]
  128. module _sqlite3
  129. class _sqlite3.Connection "pysqlite_Connection *" "clinic_state()->ConnectionType"
  130. [clinic start generated code]*/
  131. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=67369db2faf80891]*/
  132. static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
  133. static void free_callback_context(callback_context *ctx);
  134. static void set_callback_context(callback_context **ctx_pp,
  135. callback_context *ctx);
  136. static int connection_close(pysqlite_Connection *self);
  137. PyObject *_pysqlite_query_execute(pysqlite_Cursor *, int, PyObject *, PyObject *);
  138. static PyObject *
  139. new_statement_cache(pysqlite_Connection *self, pysqlite_state *state,
  140. int maxsize)
  141. {
  142. PyObject *args[] = { NULL, PyLong_FromLong(maxsize), };
  143. if (args[1] == NULL) {
  144. return NULL;
  145. }
  146. PyObject *lru_cache = state->lru_cache;
  147. size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
  148. PyObject *inner = PyObject_Vectorcall(lru_cache, args + 1, nargsf, NULL);
  149. Py_DECREF(args[1]);
  150. if (inner == NULL) {
  151. return NULL;
  152. }
  153. args[1] = (PyObject *)self; // Borrowed ref.
  154. nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
  155. PyObject *res = PyObject_Vectorcall(inner, args + 1, nargsf, NULL);
  156. Py_DECREF(inner);
  157. return res;
  158. }
  159. static inline int
  160. connection_exec_stmt(pysqlite_Connection *self, const char *sql)
  161. {
  162. int rc;
  163. Py_BEGIN_ALLOW_THREADS
  164. int len = (int)strlen(sql) + 1;
  165. sqlite3_stmt *stmt;
  166. rc = sqlite3_prepare_v2(self->db, sql, len, &stmt, NULL);
  167. if (rc == SQLITE_OK) {
  168. (void)sqlite3_step(stmt);
  169. rc = sqlite3_finalize(stmt);
  170. }
  171. Py_END_ALLOW_THREADS
  172. if (rc != SQLITE_OK) {
  173. (void)_pysqlite_seterror(self->state, self->db);
  174. return -1;
  175. }
  176. return 0;
  177. }
  178. /*[python input]
  179. class IsolationLevel_converter(CConverter):
  180. type = "const char *"
  181. converter = "isolation_level_converter"
  182. class Autocommit_converter(CConverter):
  183. type = "enum autocommit_mode"
  184. converter = "autocommit_converter"
  185. class sqlite3_int64_converter(CConverter):
  186. type = "sqlite3_int64"
  187. converter = "sqlite3_int64_converter"
  188. [python start generated code]*/
  189. /*[python end generated code: output=da39a3ee5e6b4b0d input=dff8760fb1eba6a1]*/
  190. // NB: This needs to be in sync with the sqlite3.connect docstring
  191. /*[clinic input]
  192. _sqlite3.Connection.__init__ as pysqlite_connection_init
  193. database: object
  194. timeout: double = 5.0
  195. detect_types: int = 0
  196. isolation_level: IsolationLevel = ""
  197. check_same_thread: bool = True
  198. factory: object(c_default='(PyObject*)clinic_state()->ConnectionType') = ConnectionType
  199. cached_statements as cache_size: int = 128
  200. uri: bool = False
  201. *
  202. autocommit: Autocommit(c_default='LEGACY_TRANSACTION_CONTROL') = sqlite3.LEGACY_TRANSACTION_CONTROL
  203. [clinic start generated code]*/
  204. static int
  205. pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database,
  206. double timeout, int detect_types,
  207. const char *isolation_level,
  208. int check_same_thread, PyObject *factory,
  209. int cache_size, int uri,
  210. enum autocommit_mode autocommit)
  211. /*[clinic end generated code: output=cba057313ea7712f input=9b0ab6c12f674fa3]*/
  212. {
  213. if (PySys_Audit("sqlite3.connect", "O", database) < 0) {
  214. return -1;
  215. }
  216. PyObject *bytes;
  217. if (!PyUnicode_FSConverter(database, &bytes)) {
  218. return -1;
  219. }
  220. if (self->initialized) {
  221. self->initialized = 0;
  222. PyTypeObject *tp = Py_TYPE(self);
  223. tp->tp_clear((PyObject *)self);
  224. if (connection_close(self) < 0) {
  225. return -1;
  226. }
  227. }
  228. // Create and configure SQLite database object.
  229. sqlite3 *db;
  230. int rc;
  231. Py_BEGIN_ALLOW_THREADS
  232. rc = sqlite3_open_v2(PyBytes_AS_STRING(bytes), &db,
  233. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  234. (uri ? SQLITE_OPEN_URI : 0), NULL);
  235. if (rc == SQLITE_OK) {
  236. (void)sqlite3_busy_timeout(db, (int)(timeout*1000));
  237. }
  238. Py_END_ALLOW_THREADS
  239. Py_DECREF(bytes);
  240. if (db == NULL && rc == SQLITE_NOMEM) {
  241. PyErr_NoMemory();
  242. return -1;
  243. }
  244. pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(self));
  245. if (rc != SQLITE_OK) {
  246. _pysqlite_seterror(state, db);
  247. goto error;
  248. }
  249. // Create LRU statement cache; returns a new reference.
  250. PyObject *statement_cache = new_statement_cache(self, state, cache_size);
  251. if (statement_cache == NULL) {
  252. goto error;
  253. }
  254. /* Create lists of weak references to cursors and blobs */
  255. PyObject *cursors = PyList_New(0);
  256. if (cursors == NULL) {
  257. Py_DECREF(statement_cache);
  258. goto error;
  259. }
  260. PyObject *blobs = PyList_New(0);
  261. if (blobs == NULL) {
  262. Py_DECREF(statement_cache);
  263. Py_DECREF(cursors);
  264. goto error;
  265. }
  266. // Init connection state members.
  267. self->db = db;
  268. self->state = state;
  269. self->detect_types = detect_types;
  270. self->isolation_level = isolation_level;
  271. self->autocommit = autocommit;
  272. self->check_same_thread = check_same_thread;
  273. self->thread_ident = PyThread_get_thread_ident();
  274. self->statement_cache = statement_cache;
  275. self->cursors = cursors;
  276. self->blobs = blobs;
  277. self->created_cursors = 0;
  278. self->row_factory = Py_NewRef(Py_None);
  279. self->text_factory = Py_NewRef(&PyUnicode_Type);
  280. self->trace_ctx = NULL;
  281. self->progress_ctx = NULL;
  282. self->authorizer_ctx = NULL;
  283. // Borrowed refs
  284. self->Warning = state->Warning;
  285. self->Error = state->Error;
  286. self->InterfaceError = state->InterfaceError;
  287. self->DatabaseError = state->DatabaseError;
  288. self->DataError = state->DataError;
  289. self->OperationalError = state->OperationalError;
  290. self->IntegrityError = state->IntegrityError;
  291. self->InternalError = state->InternalError;
  292. self->ProgrammingError = state->ProgrammingError;
  293. self->NotSupportedError = state->NotSupportedError;
  294. if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
  295. return -1; // Don't goto error; at this point, dealloc will clean up.
  296. }
  297. self->initialized = 1;
  298. if (autocommit == AUTOCOMMIT_DISABLED) {
  299. if (connection_exec_stmt(self, "BEGIN") < 0) {
  300. return -1;
  301. }
  302. }
  303. return 0;
  304. error:
  305. // There are no statements or other SQLite objects attached to the
  306. // database, so sqlite3_close() should always return SQLITE_OK.
  307. rc = sqlite3_close(db);
  308. assert(rc == SQLITE_OK);
  309. return -1;
  310. }
  311. #define VISIT_CALLBACK_CONTEXT(ctx) \
  312. do { \
  313. if (ctx) { \
  314. Py_VISIT(ctx->callable); \
  315. Py_VISIT(ctx->module); \
  316. } \
  317. } while (0)
  318. static int
  319. connection_traverse(pysqlite_Connection *self, visitproc visit, void *arg)
  320. {
  321. Py_VISIT(Py_TYPE(self));
  322. Py_VISIT(self->statement_cache);
  323. Py_VISIT(self->cursors);
  324. Py_VISIT(self->blobs);
  325. Py_VISIT(self->row_factory);
  326. Py_VISIT(self->text_factory);
  327. VISIT_CALLBACK_CONTEXT(self->trace_ctx);
  328. VISIT_CALLBACK_CONTEXT(self->progress_ctx);
  329. VISIT_CALLBACK_CONTEXT(self->authorizer_ctx);
  330. #undef VISIT_CALLBACK_CONTEXT
  331. return 0;
  332. }
  333. static inline void
  334. clear_callback_context(callback_context *ctx)
  335. {
  336. if (ctx != NULL) {
  337. Py_CLEAR(ctx->callable);
  338. Py_CLEAR(ctx->module);
  339. }
  340. }
  341. static int
  342. connection_clear(pysqlite_Connection *self)
  343. {
  344. Py_CLEAR(self->statement_cache);
  345. Py_CLEAR(self->cursors);
  346. Py_CLEAR(self->blobs);
  347. Py_CLEAR(self->row_factory);
  348. Py_CLEAR(self->text_factory);
  349. clear_callback_context(self->trace_ctx);
  350. clear_callback_context(self->progress_ctx);
  351. clear_callback_context(self->authorizer_ctx);
  352. return 0;
  353. }
  354. static void
  355. free_callback_contexts(pysqlite_Connection *self)
  356. {
  357. set_callback_context(&self->trace_ctx, NULL);
  358. set_callback_context(&self->progress_ctx, NULL);
  359. set_callback_context(&self->authorizer_ctx, NULL);
  360. }
  361. static void
  362. remove_callbacks(sqlite3 *db)
  363. {
  364. assert(db != NULL);
  365. /* None of these APIs can fail, as long as they are given a valid
  366. * database pointer. */
  367. int rc;
  368. #ifdef HAVE_TRACE_V2
  369. rc = sqlite3_trace_v2(db, SQLITE_TRACE_STMT, 0, 0);
  370. assert(rc == SQLITE_OK), (void)rc;
  371. #else
  372. sqlite3_trace(db, 0, (void*)0);
  373. #endif
  374. sqlite3_progress_handler(db, 0, 0, (void *)0);
  375. rc = sqlite3_set_authorizer(db, NULL, NULL);
  376. assert(rc == SQLITE_OK), (void)rc;
  377. }
  378. static int
  379. connection_close(pysqlite_Connection *self)
  380. {
  381. if (self->db == NULL) {
  382. return 0;
  383. }
  384. int rc = 0;
  385. if (self->autocommit == AUTOCOMMIT_DISABLED &&
  386. !sqlite3_get_autocommit(self->db))
  387. {
  388. if (connection_exec_stmt(self, "ROLLBACK") < 0) {
  389. rc = -1;
  390. }
  391. }
  392. sqlite3 *db = self->db;
  393. self->db = NULL;
  394. Py_BEGIN_ALLOW_THREADS
  395. /* The v2 close call always returns SQLITE_OK if given a valid database
  396. * pointer (which we do), so we can safely ignore the return value */
  397. (void)sqlite3_close_v2(db);
  398. Py_END_ALLOW_THREADS
  399. free_callback_contexts(self);
  400. return rc;
  401. }
  402. static void
  403. connection_finalize(PyObject *self)
  404. {
  405. pysqlite_Connection *con = (pysqlite_Connection *)self;
  406. PyObject *exc = PyErr_GetRaisedException();
  407. /* If close is implicitly called as a result of interpreter
  408. * tear-down, we must not call back into Python. */
  409. PyInterpreterState *interp = PyInterpreterState_Get();
  410. int teardown = _Py_IsInterpreterFinalizing(interp);
  411. if (teardown && con->db) {
  412. remove_callbacks(con->db);
  413. }
  414. /* Clean up if user has not called .close() explicitly. */
  415. if (connection_close(con) < 0) {
  416. if (teardown) {
  417. PyErr_Clear();
  418. }
  419. else {
  420. PyErr_WriteUnraisable((PyObject *)self);
  421. }
  422. }
  423. PyErr_SetRaisedException(exc);
  424. }
  425. static void
  426. connection_dealloc(PyObject *self)
  427. {
  428. if (PyObject_CallFinalizerFromDealloc(self) < 0) {
  429. return;
  430. }
  431. PyTypeObject *tp = Py_TYPE(self);
  432. PyObject_GC_UnTrack(self);
  433. tp->tp_clear(self);
  434. tp->tp_free(self);
  435. Py_DECREF(tp);
  436. }
  437. /*[clinic input]
  438. _sqlite3.Connection.cursor as pysqlite_connection_cursor
  439. factory: object = NULL
  440. Return a cursor for the connection.
  441. [clinic start generated code]*/
  442. static PyObject *
  443. pysqlite_connection_cursor_impl(pysqlite_Connection *self, PyObject *factory)
  444. /*[clinic end generated code: output=562432a9e6af2aa1 input=4127345aa091b650]*/
  445. {
  446. PyObject* cursor;
  447. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  448. return NULL;
  449. }
  450. if (factory == NULL) {
  451. factory = (PyObject *)self->state->CursorType;
  452. }
  453. cursor = PyObject_CallOneArg(factory, (PyObject *)self);
  454. if (cursor == NULL)
  455. return NULL;
  456. if (!PyObject_TypeCheck(cursor, self->state->CursorType)) {
  457. PyErr_Format(PyExc_TypeError,
  458. "factory must return a cursor, not %.100s",
  459. Py_TYPE(cursor)->tp_name);
  460. Py_DECREF(cursor);
  461. return NULL;
  462. }
  463. _pysqlite_drop_unused_cursor_references(self);
  464. if (cursor && self->row_factory != Py_None) {
  465. Py_INCREF(self->row_factory);
  466. Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
  467. }
  468. return cursor;
  469. }
  470. /*[clinic input]
  471. _sqlite3.Connection.blobopen as blobopen
  472. table: str
  473. Table name.
  474. column as col: str
  475. Column name.
  476. row: sqlite3_int64
  477. Row index.
  478. /
  479. *
  480. readonly: bool = False
  481. Open the BLOB without write permissions.
  482. name: str = "main"
  483. Database name.
  484. Open and return a BLOB object.
  485. [clinic start generated code]*/
  486. static PyObject *
  487. blobopen_impl(pysqlite_Connection *self, const char *table, const char *col,
  488. sqlite3_int64 row, int readonly, const char *name)
  489. /*[clinic end generated code: output=6a02d43efb885d1c input=23576bd1108d8774]*/
  490. {
  491. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  492. return NULL;
  493. }
  494. int rc;
  495. sqlite3_blob *blob;
  496. Py_BEGIN_ALLOW_THREADS
  497. rc = sqlite3_blob_open(self->db, name, table, col, row, !readonly, &blob);
  498. Py_END_ALLOW_THREADS
  499. if (rc == SQLITE_MISUSE) {
  500. PyErr_Format(self->state->InterfaceError, sqlite3_errstr(rc));
  501. return NULL;
  502. }
  503. else if (rc != SQLITE_OK) {
  504. _pysqlite_seterror(self->state, self->db);
  505. return NULL;
  506. }
  507. pysqlite_Blob *obj = PyObject_GC_New(pysqlite_Blob, self->state->BlobType);
  508. if (obj == NULL) {
  509. goto error;
  510. }
  511. obj->connection = (pysqlite_Connection *)Py_NewRef(self);
  512. obj->blob = blob;
  513. obj->offset = 0;
  514. obj->in_weakreflist = NULL;
  515. PyObject_GC_Track(obj);
  516. // Add our blob to connection blobs list
  517. PyObject *weakref = PyWeakref_NewRef((PyObject *)obj, NULL);
  518. if (weakref == NULL) {
  519. goto error;
  520. }
  521. rc = PyList_Append(self->blobs, weakref);
  522. Py_DECREF(weakref);
  523. if (rc < 0) {
  524. goto error;
  525. }
  526. return (PyObject *)obj;
  527. error:
  528. Py_XDECREF(obj);
  529. return NULL;
  530. }
  531. /*[clinic input]
  532. _sqlite3.Connection.close as pysqlite_connection_close
  533. Close the database connection.
  534. Any pending transaction is not committed implicitly.
  535. [clinic start generated code]*/
  536. static PyObject *
  537. pysqlite_connection_close_impl(pysqlite_Connection *self)
  538. /*[clinic end generated code: output=a546a0da212c9b97 input=b3ed5b74f6fefc06]*/
  539. {
  540. if (!pysqlite_check_thread(self)) {
  541. return NULL;
  542. }
  543. if (!self->initialized) {
  544. PyTypeObject *tp = Py_TYPE(self);
  545. pysqlite_state *state = pysqlite_get_state_by_type(tp);
  546. PyErr_SetString(state->ProgrammingError,
  547. "Base Connection.__init__ not called.");
  548. return NULL;
  549. }
  550. pysqlite_close_all_blobs(self);
  551. Py_CLEAR(self->statement_cache);
  552. if (connection_close(self) < 0) {
  553. return NULL;
  554. }
  555. Py_RETURN_NONE;
  556. }
  557. /*
  558. * Checks if a connection object is usable (i. e. not closed).
  559. *
  560. * 0 => error; 1 => ok
  561. */
  562. int pysqlite_check_connection(pysqlite_Connection* con)
  563. {
  564. if (!con->initialized) {
  565. pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(con));
  566. PyErr_SetString(state->ProgrammingError,
  567. "Base Connection.__init__ not called.");
  568. return 0;
  569. }
  570. if (!con->db) {
  571. PyErr_SetString(con->state->ProgrammingError,
  572. "Cannot operate on a closed database.");
  573. return 0;
  574. } else {
  575. return 1;
  576. }
  577. }
  578. /*[clinic input]
  579. _sqlite3.Connection.commit as pysqlite_connection_commit
  580. Commit any pending transaction to the database.
  581. If there is no open transaction, this method is a no-op.
  582. [clinic start generated code]*/
  583. static PyObject *
  584. pysqlite_connection_commit_impl(pysqlite_Connection *self)
  585. /*[clinic end generated code: output=3da45579e89407f2 input=c8793c97c3446065]*/
  586. {
  587. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  588. return NULL;
  589. }
  590. if (self->autocommit == AUTOCOMMIT_LEGACY) {
  591. if (!sqlite3_get_autocommit(self->db)) {
  592. if (connection_exec_stmt(self, "COMMIT") < 0) {
  593. return NULL;
  594. }
  595. }
  596. }
  597. else if (self->autocommit == AUTOCOMMIT_DISABLED) {
  598. if (connection_exec_stmt(self, "COMMIT") < 0) {
  599. return NULL;
  600. }
  601. if (connection_exec_stmt(self, "BEGIN") < 0) {
  602. return NULL;
  603. }
  604. }
  605. Py_RETURN_NONE;
  606. }
  607. /*[clinic input]
  608. _sqlite3.Connection.rollback as pysqlite_connection_rollback
  609. Roll back to the start of any pending transaction.
  610. If there is no open transaction, this method is a no-op.
  611. [clinic start generated code]*/
  612. static PyObject *
  613. pysqlite_connection_rollback_impl(pysqlite_Connection *self)
  614. /*[clinic end generated code: output=b66fa0d43e7ef305 input=7f60a2f1076f16b3]*/
  615. {
  616. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  617. return NULL;
  618. }
  619. if (self->autocommit == AUTOCOMMIT_LEGACY) {
  620. if (!sqlite3_get_autocommit(self->db)) {
  621. if (connection_exec_stmt(self, "ROLLBACK") < 0) {
  622. return NULL;
  623. }
  624. }
  625. }
  626. else if (self->autocommit == AUTOCOMMIT_DISABLED) {
  627. if (connection_exec_stmt(self, "ROLLBACK") < 0) {
  628. return NULL;
  629. }
  630. if (connection_exec_stmt(self, "BEGIN") < 0) {
  631. return NULL;
  632. }
  633. }
  634. Py_RETURN_NONE;
  635. }
  636. static int
  637. _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
  638. {
  639. if (py_val == Py_None) {
  640. sqlite3_result_null(context);
  641. } else if (PyLong_Check(py_val)) {
  642. sqlite_int64 value = _pysqlite_long_as_int64(py_val);
  643. if (value == -1 && PyErr_Occurred())
  644. return -1;
  645. sqlite3_result_int64(context, value);
  646. } else if (PyFloat_Check(py_val)) {
  647. double value = PyFloat_AsDouble(py_val);
  648. if (value == -1 && PyErr_Occurred()) {
  649. return -1;
  650. }
  651. sqlite3_result_double(context, value);
  652. } else if (PyUnicode_Check(py_val)) {
  653. Py_ssize_t sz;
  654. const char *str = PyUnicode_AsUTF8AndSize(py_val, &sz);
  655. if (str == NULL) {
  656. return -1;
  657. }
  658. if (sz > INT_MAX) {
  659. PyErr_SetString(PyExc_OverflowError,
  660. "string is longer than INT_MAX bytes");
  661. return -1;
  662. }
  663. sqlite3_result_text(context, str, (int)sz, SQLITE_TRANSIENT);
  664. } else if (PyObject_CheckBuffer(py_val)) {
  665. Py_buffer view;
  666. if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
  667. return -1;
  668. }
  669. if (view.len > INT_MAX) {
  670. PyErr_SetString(PyExc_OverflowError,
  671. "BLOB longer than INT_MAX bytes");
  672. PyBuffer_Release(&view);
  673. return -1;
  674. }
  675. sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
  676. PyBuffer_Release(&view);
  677. } else {
  678. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  679. PyErr_Format(ctx->state->ProgrammingError,
  680. "User-defined functions cannot return '%s' values to "
  681. "SQLite",
  682. Py_TYPE(py_val)->tp_name);
  683. return -1;
  684. }
  685. return 0;
  686. }
  687. static PyObject *
  688. _pysqlite_build_py_params(sqlite3_context *context, int argc,
  689. sqlite3_value **argv)
  690. {
  691. PyObject* args;
  692. int i;
  693. sqlite3_value* cur_value;
  694. PyObject* cur_py_value;
  695. args = PyTuple_New(argc);
  696. if (!args) {
  697. return NULL;
  698. }
  699. for (i = 0; i < argc; i++) {
  700. cur_value = argv[i];
  701. switch (sqlite3_value_type(argv[i])) {
  702. case SQLITE_INTEGER:
  703. cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
  704. break;
  705. case SQLITE_FLOAT:
  706. cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
  707. break;
  708. case SQLITE_TEXT: {
  709. sqlite3 *db = sqlite3_context_db_handle(context);
  710. const char *text = (const char *)sqlite3_value_text(cur_value);
  711. if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
  712. PyErr_NoMemory();
  713. goto error;
  714. }
  715. Py_ssize_t size = sqlite3_value_bytes(cur_value);
  716. cur_py_value = PyUnicode_FromStringAndSize(text, size);
  717. break;
  718. }
  719. case SQLITE_BLOB: {
  720. sqlite3 *db = sqlite3_context_db_handle(context);
  721. const void *blob = sqlite3_value_blob(cur_value);
  722. if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
  723. PyErr_NoMemory();
  724. goto error;
  725. }
  726. Py_ssize_t size = sqlite3_value_bytes(cur_value);
  727. cur_py_value = PyBytes_FromStringAndSize(blob, size);
  728. break;
  729. }
  730. case SQLITE_NULL:
  731. default:
  732. cur_py_value = Py_NewRef(Py_None);
  733. }
  734. if (!cur_py_value) {
  735. goto error;
  736. }
  737. PyTuple_SET_ITEM(args, i, cur_py_value);
  738. }
  739. return args;
  740. error:
  741. Py_DECREF(args);
  742. return NULL;
  743. }
  744. static void
  745. print_or_clear_traceback(callback_context *ctx)
  746. {
  747. assert(ctx != NULL);
  748. assert(ctx->state != NULL);
  749. if (ctx->state->enable_callback_tracebacks) {
  750. PyErr_WriteUnraisable(ctx->callable);
  751. }
  752. else {
  753. PyErr_Clear();
  754. }
  755. }
  756. // Checks the Python exception and sets the appropriate SQLite error code.
  757. static void
  758. set_sqlite_error(sqlite3_context *context, const char *msg)
  759. {
  760. assert(PyErr_Occurred());
  761. if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
  762. sqlite3_result_error_nomem(context);
  763. }
  764. else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  765. sqlite3_result_error_toobig(context);
  766. }
  767. else {
  768. sqlite3_result_error(context, msg, -1);
  769. }
  770. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  771. print_or_clear_traceback(ctx);
  772. }
  773. static void
  774. func_callback(sqlite3_context *context, int argc, sqlite3_value **argv)
  775. {
  776. PyGILState_STATE threadstate = PyGILState_Ensure();
  777. PyObject* args;
  778. PyObject* py_retval = NULL;
  779. int ok;
  780. args = _pysqlite_build_py_params(context, argc, argv);
  781. if (args) {
  782. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  783. assert(ctx != NULL);
  784. py_retval = PyObject_CallObject(ctx->callable, args);
  785. Py_DECREF(args);
  786. }
  787. ok = 0;
  788. if (py_retval) {
  789. ok = _pysqlite_set_result(context, py_retval) == 0;
  790. Py_DECREF(py_retval);
  791. }
  792. if (!ok) {
  793. set_sqlite_error(context, "user-defined function raised exception");
  794. }
  795. PyGILState_Release(threadstate);
  796. }
  797. static void
  798. step_callback(sqlite3_context *context, int argc, sqlite3_value **params)
  799. {
  800. PyGILState_STATE threadstate = PyGILState_Ensure();
  801. PyObject* args;
  802. PyObject* function_result = NULL;
  803. PyObject** aggregate_instance;
  804. PyObject* stepmethod = NULL;
  805. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  806. assert(ctx != NULL);
  807. aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
  808. if (*aggregate_instance == NULL) {
  809. *aggregate_instance = PyObject_CallNoArgs(ctx->callable);
  810. if (!*aggregate_instance) {
  811. set_sqlite_error(context,
  812. "user-defined aggregate's '__init__' method raised error");
  813. goto error;
  814. }
  815. }
  816. stepmethod = PyObject_GetAttr(*aggregate_instance, ctx->state->str_step);
  817. if (!stepmethod) {
  818. set_sqlite_error(context,
  819. "user-defined aggregate's 'step' method not defined");
  820. goto error;
  821. }
  822. args = _pysqlite_build_py_params(context, argc, params);
  823. if (!args) {
  824. goto error;
  825. }
  826. function_result = PyObject_CallObject(stepmethod, args);
  827. Py_DECREF(args);
  828. if (!function_result) {
  829. set_sqlite_error(context,
  830. "user-defined aggregate's 'step' method raised error");
  831. }
  832. error:
  833. Py_XDECREF(stepmethod);
  834. Py_XDECREF(function_result);
  835. PyGILState_Release(threadstate);
  836. }
  837. static void
  838. final_callback(sqlite3_context *context)
  839. {
  840. PyGILState_STATE threadstate = PyGILState_Ensure();
  841. PyObject* function_result;
  842. PyObject** aggregate_instance;
  843. int ok;
  844. aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
  845. if (aggregate_instance == NULL) {
  846. /* No rows matched the query; the step handler was never called. */
  847. goto error;
  848. }
  849. else if (!*aggregate_instance) {
  850. /* this branch is executed if there was an exception in the aggregate's
  851. * __init__ */
  852. goto error;
  853. }
  854. // Keep the exception (if any) of the last call to step, value, or inverse
  855. PyObject *exc = PyErr_GetRaisedException();
  856. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  857. assert(ctx != NULL);
  858. function_result = PyObject_CallMethodNoArgs(*aggregate_instance,
  859. ctx->state->str_finalize);
  860. Py_DECREF(*aggregate_instance);
  861. ok = 0;
  862. if (function_result) {
  863. ok = _pysqlite_set_result(context, function_result) == 0;
  864. Py_DECREF(function_result);
  865. }
  866. if (!ok) {
  867. int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
  868. _PyErr_ChainExceptions1(exc);
  869. /* Note: contrary to the step, value, and inverse callbacks, SQLite
  870. * does _not_, as of SQLite 3.38.0, propagate errors to sqlite3_step()
  871. * from the finalize callback. This implies that execute*() will not
  872. * raise OperationalError, as it normally would. */
  873. set_sqlite_error(context, attr_err
  874. ? "user-defined aggregate's 'finalize' method not defined"
  875. : "user-defined aggregate's 'finalize' method raised error");
  876. }
  877. else {
  878. PyErr_SetRaisedException(exc);
  879. }
  880. error:
  881. PyGILState_Release(threadstate);
  882. }
  883. static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
  884. {
  885. PyObject* new_list;
  886. PyObject* weakref;
  887. int i;
  888. /* we only need to do this once in a while */
  889. if (self->created_cursors++ < 200) {
  890. return;
  891. }
  892. self->created_cursors = 0;
  893. new_list = PyList_New(0);
  894. if (!new_list) {
  895. return;
  896. }
  897. for (i = 0; i < PyList_Size(self->cursors); i++) {
  898. weakref = PyList_GetItem(self->cursors, i);
  899. if (PyWeakref_GetObject(weakref) != Py_None) {
  900. if (PyList_Append(new_list, weakref) != 0) {
  901. Py_DECREF(new_list);
  902. return;
  903. }
  904. }
  905. }
  906. Py_SETREF(self->cursors, new_list);
  907. }
  908. /* Allocate a UDF/callback context structure. In order to ensure that the state
  909. * pointer always outlives the callback context, we make sure it owns a
  910. * reference to the module itself. create_callback_context() is always called
  911. * from connection methods, so we use the defining class to fetch the module
  912. * pointer.
  913. */
  914. static callback_context *
  915. create_callback_context(PyTypeObject *cls, PyObject *callable)
  916. {
  917. callback_context *ctx = PyMem_Malloc(sizeof(callback_context));
  918. if (ctx != NULL) {
  919. PyObject *module = PyType_GetModule(cls);
  920. ctx->callable = Py_NewRef(callable);
  921. ctx->module = Py_NewRef(module);
  922. ctx->state = pysqlite_get_state(module);
  923. }
  924. return ctx;
  925. }
  926. static void
  927. free_callback_context(callback_context *ctx)
  928. {
  929. assert(ctx != NULL);
  930. Py_XDECREF(ctx->callable);
  931. Py_XDECREF(ctx->module);
  932. PyMem_Free(ctx);
  933. }
  934. static void
  935. set_callback_context(callback_context **ctx_pp, callback_context *ctx)
  936. {
  937. assert(ctx_pp != NULL);
  938. callback_context *tmp = *ctx_pp;
  939. *ctx_pp = ctx;
  940. if (tmp != NULL) {
  941. free_callback_context(tmp);
  942. }
  943. }
  944. static void
  945. destructor_callback(void *ctx)
  946. {
  947. if (ctx != NULL) {
  948. // This function may be called without the GIL held, so we need to
  949. // ensure that we destroy 'ctx' with the GIL held.
  950. PyGILState_STATE gstate = PyGILState_Ensure();
  951. free_callback_context((callback_context *)ctx);
  952. PyGILState_Release(gstate);
  953. }
  954. }
  955. /*[clinic input]
  956. _sqlite3.Connection.create_function as pysqlite_connection_create_function
  957. cls: defining_class
  958. /
  959. name: str
  960. narg: int
  961. func: object
  962. *
  963. deterministic: bool = False
  964. Creates a new function.
  965. [clinic start generated code]*/
  966. static PyObject *
  967. pysqlite_connection_create_function_impl(pysqlite_Connection *self,
  968. PyTypeObject *cls, const char *name,
  969. int narg, PyObject *func,
  970. int deterministic)
  971. /*[clinic end generated code: output=8a811529287ad240 input=b3e8e1d8ddaffbef]*/
  972. {
  973. int rc;
  974. int flags = SQLITE_UTF8;
  975. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  976. return NULL;
  977. }
  978. if (deterministic) {
  979. #if SQLITE_VERSION_NUMBER < 3008003
  980. PyErr_SetString(self->NotSupportedError,
  981. "deterministic=True requires SQLite 3.8.3 or higher");
  982. return NULL;
  983. #else
  984. if (sqlite3_libversion_number() < 3008003) {
  985. PyErr_SetString(self->NotSupportedError,
  986. "deterministic=True requires SQLite 3.8.3 or higher");
  987. return NULL;
  988. }
  989. flags |= SQLITE_DETERMINISTIC;
  990. #endif
  991. }
  992. callback_context *ctx = create_callback_context(cls, func);
  993. if (ctx == NULL) {
  994. return NULL;
  995. }
  996. rc = sqlite3_create_function_v2(self->db, name, narg, flags, ctx,
  997. func_callback,
  998. NULL,
  999. NULL,
  1000. &destructor_callback); // will decref func
  1001. if (rc != SQLITE_OK) {
  1002. /* Workaround for SQLite bug: no error code or string is available here */
  1003. PyErr_SetString(self->OperationalError, "Error creating function");
  1004. return NULL;
  1005. }
  1006. Py_RETURN_NONE;
  1007. }
  1008. #ifdef HAVE_WINDOW_FUNCTIONS
  1009. /*
  1010. * Regarding the 'inverse' aggregate callback:
  1011. * This method is only required by window aggregate functions, not
  1012. * ordinary aggregate function implementations. It is invoked to remove
  1013. * a row from the current window. The function arguments, if any,
  1014. * correspond to the row being removed.
  1015. */
  1016. static void
  1017. inverse_callback(sqlite3_context *context, int argc, sqlite3_value **params)
  1018. {
  1019. PyGILState_STATE gilstate = PyGILState_Ensure();
  1020. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  1021. assert(ctx != NULL);
  1022. int size = sizeof(PyObject *);
  1023. PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
  1024. assert(cls != NULL);
  1025. assert(*cls != NULL);
  1026. PyObject *method = PyObject_GetAttr(*cls, ctx->state->str_inverse);
  1027. if (method == NULL) {
  1028. set_sqlite_error(context,
  1029. "user-defined aggregate's 'inverse' method not defined");
  1030. goto exit;
  1031. }
  1032. PyObject *args = _pysqlite_build_py_params(context, argc, params);
  1033. if (args == NULL) {
  1034. set_sqlite_error(context,
  1035. "unable to build arguments for user-defined aggregate's "
  1036. "'inverse' method");
  1037. goto exit;
  1038. }
  1039. PyObject *res = PyObject_CallObject(method, args);
  1040. Py_DECREF(args);
  1041. if (res == NULL) {
  1042. set_sqlite_error(context,
  1043. "user-defined aggregate's 'inverse' method raised error");
  1044. goto exit;
  1045. }
  1046. Py_DECREF(res);
  1047. exit:
  1048. Py_XDECREF(method);
  1049. PyGILState_Release(gilstate);
  1050. }
  1051. /*
  1052. * Regarding the 'value' aggregate callback:
  1053. * This method is only required by window aggregate functions, not
  1054. * ordinary aggregate function implementations. It is invoked to return
  1055. * the current value of the aggregate.
  1056. */
  1057. static void
  1058. value_callback(sqlite3_context *context)
  1059. {
  1060. PyGILState_STATE gilstate = PyGILState_Ensure();
  1061. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  1062. assert(ctx != NULL);
  1063. int size = sizeof(PyObject *);
  1064. PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
  1065. assert(cls != NULL);
  1066. assert(*cls != NULL);
  1067. PyObject *res = PyObject_CallMethodNoArgs(*cls, ctx->state->str_value);
  1068. if (res == NULL) {
  1069. int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
  1070. set_sqlite_error(context, attr_err
  1071. ? "user-defined aggregate's 'value' method not defined"
  1072. : "user-defined aggregate's 'value' method raised error");
  1073. }
  1074. else {
  1075. int rc = _pysqlite_set_result(context, res);
  1076. Py_DECREF(res);
  1077. if (rc < 0) {
  1078. set_sqlite_error(context,
  1079. "unable to set result from user-defined aggregate's "
  1080. "'value' method");
  1081. }
  1082. }
  1083. PyGILState_Release(gilstate);
  1084. }
  1085. /*[clinic input]
  1086. _sqlite3.Connection.create_window_function as create_window_function
  1087. cls: defining_class
  1088. name: str
  1089. The name of the SQL aggregate window function to be created or
  1090. redefined.
  1091. num_params: int
  1092. The number of arguments the step and inverse methods takes.
  1093. aggregate_class: object
  1094. A class with step(), finalize(), value(), and inverse() methods.
  1095. Set to None to clear the window function.
  1096. /
  1097. Creates or redefines an aggregate window function. Non-standard.
  1098. [clinic start generated code]*/
  1099. static PyObject *
  1100. create_window_function_impl(pysqlite_Connection *self, PyTypeObject *cls,
  1101. const char *name, int num_params,
  1102. PyObject *aggregate_class)
  1103. /*[clinic end generated code: output=5332cd9464522235 input=46d57a54225b5228]*/
  1104. {
  1105. if (sqlite3_libversion_number() < 3025000) {
  1106. PyErr_SetString(self->NotSupportedError,
  1107. "create_window_function() requires "
  1108. "SQLite 3.25.0 or higher");
  1109. return NULL;
  1110. }
  1111. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1112. return NULL;
  1113. }
  1114. int flags = SQLITE_UTF8;
  1115. int rc;
  1116. if (Py_IsNone(aggregate_class)) {
  1117. rc = sqlite3_create_window_function(self->db, name, num_params, flags,
  1118. 0, 0, 0, 0, 0, 0);
  1119. }
  1120. else {
  1121. callback_context *ctx = create_callback_context(cls, aggregate_class);
  1122. if (ctx == NULL) {
  1123. return NULL;
  1124. }
  1125. rc = sqlite3_create_window_function(self->db, name, num_params, flags,
  1126. ctx,
  1127. &step_callback,
  1128. &final_callback,
  1129. &value_callback,
  1130. &inverse_callback,
  1131. &destructor_callback);
  1132. }
  1133. if (rc != SQLITE_OK) {
  1134. // Errors are not set on the database connection, so we cannot
  1135. // use _pysqlite_seterror().
  1136. PyErr_SetString(self->ProgrammingError, sqlite3_errstr(rc));
  1137. return NULL;
  1138. }
  1139. Py_RETURN_NONE;
  1140. }
  1141. #endif
  1142. /*[clinic input]
  1143. _sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
  1144. cls: defining_class
  1145. /
  1146. name: str
  1147. n_arg: int
  1148. aggregate_class: object
  1149. Creates a new aggregate.
  1150. [clinic start generated code]*/
  1151. static PyObject *
  1152. pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
  1153. PyTypeObject *cls,
  1154. const char *name, int n_arg,
  1155. PyObject *aggregate_class)
  1156. /*[clinic end generated code: output=1b02d0f0aec7ff96 input=68a2a26366d4c686]*/
  1157. {
  1158. int rc;
  1159. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1160. return NULL;
  1161. }
  1162. callback_context *ctx = create_callback_context(cls, aggregate_class);
  1163. if (ctx == NULL) {
  1164. return NULL;
  1165. }
  1166. rc = sqlite3_create_function_v2(self->db, name, n_arg, SQLITE_UTF8, ctx,
  1167. 0,
  1168. &step_callback,
  1169. &final_callback,
  1170. &destructor_callback); // will decref func
  1171. if (rc != SQLITE_OK) {
  1172. /* Workaround for SQLite bug: no error code or string is available here */
  1173. PyErr_SetString(self->OperationalError, "Error creating aggregate");
  1174. return NULL;
  1175. }
  1176. Py_RETURN_NONE;
  1177. }
  1178. static int
  1179. authorizer_callback(void *ctx, int action, const char *arg1,
  1180. const char *arg2 , const char *dbname,
  1181. const char *access_attempt_source)
  1182. {
  1183. PyGILState_STATE gilstate = PyGILState_Ensure();
  1184. PyObject *ret;
  1185. int rc = SQLITE_DENY;
  1186. assert(ctx != NULL);
  1187. PyObject *callable = ((callback_context *)ctx)->callable;
  1188. ret = PyObject_CallFunction(callable, "issss", action, arg1, arg2, dbname,
  1189. access_attempt_source);
  1190. if (ret == NULL) {
  1191. print_or_clear_traceback(ctx);
  1192. rc = SQLITE_DENY;
  1193. }
  1194. else {
  1195. if (PyLong_Check(ret)) {
  1196. rc = _PyLong_AsInt(ret);
  1197. if (rc == -1 && PyErr_Occurred()) {
  1198. print_or_clear_traceback(ctx);
  1199. rc = SQLITE_DENY;
  1200. }
  1201. }
  1202. else {
  1203. rc = SQLITE_DENY;
  1204. }
  1205. Py_DECREF(ret);
  1206. }
  1207. PyGILState_Release(gilstate);
  1208. return rc;
  1209. }
  1210. static int
  1211. progress_callback(void *ctx)
  1212. {
  1213. PyGILState_STATE gilstate = PyGILState_Ensure();
  1214. int rc;
  1215. PyObject *ret;
  1216. assert(ctx != NULL);
  1217. PyObject *callable = ((callback_context *)ctx)->callable;
  1218. ret = PyObject_CallNoArgs(callable);
  1219. if (!ret) {
  1220. /* abort query if error occurred */
  1221. rc = -1;
  1222. }
  1223. else {
  1224. rc = PyObject_IsTrue(ret);
  1225. Py_DECREF(ret);
  1226. }
  1227. if (rc < 0) {
  1228. print_or_clear_traceback(ctx);
  1229. }
  1230. PyGILState_Release(gilstate);
  1231. return rc;
  1232. }
  1233. #ifdef HAVE_TRACE_V2
  1234. /*
  1235. * From https://sqlite.org/c3ref/trace_v2.html:
  1236. * The integer return value from the callback is currently ignored, though this
  1237. * may change in future releases. Callback implementations should return zero
  1238. * to ensure future compatibility.
  1239. */
  1240. static int
  1241. trace_callback(unsigned int type, void *ctx, void *stmt, void *sql)
  1242. #else
  1243. static void
  1244. trace_callback(void *ctx, const char *sql)
  1245. #endif
  1246. {
  1247. #ifdef HAVE_TRACE_V2
  1248. if (type != SQLITE_TRACE_STMT) {
  1249. return 0;
  1250. }
  1251. #endif
  1252. PyGILState_STATE gilstate = PyGILState_Ensure();
  1253. assert(ctx != NULL);
  1254. pysqlite_state *state = ((callback_context *)ctx)->state;
  1255. assert(state != NULL);
  1256. PyObject *py_statement = NULL;
  1257. #ifdef HAVE_TRACE_V2
  1258. const char *expanded_sql = sqlite3_expanded_sql((sqlite3_stmt *)stmt);
  1259. if (expanded_sql == NULL) {
  1260. sqlite3 *db = sqlite3_db_handle((sqlite3_stmt *)stmt);
  1261. if (sqlite3_errcode(db) == SQLITE_NOMEM) {
  1262. (void)PyErr_NoMemory();
  1263. goto exit;
  1264. }
  1265. PyErr_SetString(state->DataError,
  1266. "Expanded SQL string exceeds the maximum string length");
  1267. print_or_clear_traceback((callback_context *)ctx);
  1268. // Fall back to unexpanded sql
  1269. py_statement = PyUnicode_FromString((const char *)sql);
  1270. }
  1271. else {
  1272. py_statement = PyUnicode_FromString(expanded_sql);
  1273. sqlite3_free((void *)expanded_sql);
  1274. }
  1275. #else
  1276. if (sql == NULL) {
  1277. PyErr_SetString(state->DataError,
  1278. "Expanded SQL string exceeds the maximum string length");
  1279. print_or_clear_traceback((callback_context *)ctx);
  1280. goto exit;
  1281. }
  1282. py_statement = PyUnicode_FromString(sql);
  1283. #endif
  1284. if (py_statement) {
  1285. PyObject *callable = ((callback_context *)ctx)->callable;
  1286. PyObject *ret = PyObject_CallOneArg(callable, py_statement);
  1287. Py_DECREF(py_statement);
  1288. Py_XDECREF(ret);
  1289. }
  1290. if (PyErr_Occurred()) {
  1291. print_or_clear_traceback((callback_context *)ctx);
  1292. }
  1293. exit:
  1294. PyGILState_Release(gilstate);
  1295. #ifdef HAVE_TRACE_V2
  1296. return 0;
  1297. #endif
  1298. }
  1299. /*[clinic input]
  1300. _sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
  1301. cls: defining_class
  1302. /
  1303. authorizer_callback as callable: object
  1304. Sets authorizer callback.
  1305. [clinic start generated code]*/
  1306. static PyObject *
  1307. pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
  1308. PyTypeObject *cls,
  1309. PyObject *callable)
  1310. /*[clinic end generated code: output=75fa60114fc971c3 input=605d32ba92dd3eca]*/
  1311. {
  1312. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1313. return NULL;
  1314. }
  1315. int rc;
  1316. if (callable == Py_None) {
  1317. rc = sqlite3_set_authorizer(self->db, NULL, NULL);
  1318. set_callback_context(&self->authorizer_ctx, NULL);
  1319. }
  1320. else {
  1321. callback_context *ctx = create_callback_context(cls, callable);
  1322. if (ctx == NULL) {
  1323. return NULL;
  1324. }
  1325. rc = sqlite3_set_authorizer(self->db, authorizer_callback, ctx);
  1326. set_callback_context(&self->authorizer_ctx, ctx);
  1327. }
  1328. if (rc != SQLITE_OK) {
  1329. PyErr_SetString(self->OperationalError,
  1330. "Error setting authorizer callback");
  1331. set_callback_context(&self->authorizer_ctx, NULL);
  1332. return NULL;
  1333. }
  1334. Py_RETURN_NONE;
  1335. }
  1336. /*[clinic input]
  1337. _sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
  1338. cls: defining_class
  1339. /
  1340. progress_handler as callable: object
  1341. n: int
  1342. Sets progress handler callback.
  1343. [clinic start generated code]*/
  1344. static PyObject *
  1345. pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
  1346. PyTypeObject *cls,
  1347. PyObject *callable, int n)
  1348. /*[clinic end generated code: output=0739957fd8034a50 input=f7c1837984bd86db]*/
  1349. {
  1350. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1351. return NULL;
  1352. }
  1353. if (callable == Py_None) {
  1354. /* None clears the progress handler previously set */
  1355. sqlite3_progress_handler(self->db, 0, 0, (void*)0);
  1356. set_callback_context(&self->progress_ctx, NULL);
  1357. }
  1358. else {
  1359. callback_context *ctx = create_callback_context(cls, callable);
  1360. if (ctx == NULL) {
  1361. return NULL;
  1362. }
  1363. sqlite3_progress_handler(self->db, n, progress_callback, ctx);
  1364. set_callback_context(&self->progress_ctx, ctx);
  1365. }
  1366. Py_RETURN_NONE;
  1367. }
  1368. /*[clinic input]
  1369. _sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
  1370. cls: defining_class
  1371. /
  1372. trace_callback as callable: object
  1373. Sets a trace callback called for each SQL statement (passed as unicode).
  1374. [clinic start generated code]*/
  1375. static PyObject *
  1376. pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
  1377. PyTypeObject *cls,
  1378. PyObject *callable)
  1379. /*[clinic end generated code: output=d91048c03bfcee05 input=351a94210c5f81bb]*/
  1380. {
  1381. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1382. return NULL;
  1383. }
  1384. if (callable == Py_None) {
  1385. /*
  1386. * None clears the trace callback previously set
  1387. *
  1388. * Ref.
  1389. * - https://sqlite.org/c3ref/c_trace.html
  1390. * - https://sqlite.org/c3ref/trace_v2.html
  1391. */
  1392. #ifdef HAVE_TRACE_V2
  1393. sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
  1394. #else
  1395. sqlite3_trace(self->db, 0, (void*)0);
  1396. #endif
  1397. set_callback_context(&self->trace_ctx, NULL);
  1398. }
  1399. else {
  1400. callback_context *ctx = create_callback_context(cls, callable);
  1401. if (ctx == NULL) {
  1402. return NULL;
  1403. }
  1404. #ifdef HAVE_TRACE_V2
  1405. sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, trace_callback, ctx);
  1406. #else
  1407. sqlite3_trace(self->db, trace_callback, ctx);
  1408. #endif
  1409. set_callback_context(&self->trace_ctx, ctx);
  1410. }
  1411. Py_RETURN_NONE;
  1412. }
  1413. #ifdef PY_SQLITE_ENABLE_LOAD_EXTENSION
  1414. /*[clinic input]
  1415. _sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
  1416. enable as onoff: bool
  1417. /
  1418. Enable dynamic loading of SQLite extension modules.
  1419. [clinic start generated code]*/
  1420. static PyObject *
  1421. pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
  1422. int onoff)
  1423. /*[clinic end generated code: output=9cac37190d388baf input=2a1e87931486380f]*/
  1424. {
  1425. int rc;
  1426. if (PySys_Audit("sqlite3.enable_load_extension",
  1427. "OO", self, onoff ? Py_True : Py_False) < 0) {
  1428. return NULL;
  1429. }
  1430. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1431. return NULL;
  1432. }
  1433. rc = sqlite3_enable_load_extension(self->db, onoff);
  1434. if (rc != SQLITE_OK) {
  1435. PyErr_SetString(self->OperationalError,
  1436. "Error enabling load extension");
  1437. return NULL;
  1438. } else {
  1439. Py_RETURN_NONE;
  1440. }
  1441. }
  1442. /*[clinic input]
  1443. _sqlite3.Connection.load_extension as pysqlite_connection_load_extension
  1444. name as extension_name: str
  1445. /
  1446. *
  1447. entrypoint: str(accept={str, NoneType}) = None
  1448. Load SQLite extension module.
  1449. [clinic start generated code]*/
  1450. static PyObject *
  1451. pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
  1452. const char *extension_name,
  1453. const char *entrypoint)
  1454. /*[clinic end generated code: output=7e61a7add9de0286 input=c36b14ea702e04f5]*/
  1455. {
  1456. int rc;
  1457. char* errmsg;
  1458. if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
  1459. return NULL;
  1460. }
  1461. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1462. return NULL;
  1463. }
  1464. rc = sqlite3_load_extension(self->db, extension_name, entrypoint, &errmsg);
  1465. if (rc != 0) {
  1466. PyErr_SetString(self->OperationalError, errmsg);
  1467. return NULL;
  1468. } else {
  1469. Py_RETURN_NONE;
  1470. }
  1471. }
  1472. #endif
  1473. int pysqlite_check_thread(pysqlite_Connection* self)
  1474. {
  1475. if (self->check_same_thread) {
  1476. if (PyThread_get_thread_ident() != self->thread_ident) {
  1477. PyErr_Format(self->ProgrammingError,
  1478. "SQLite objects created in a thread can only be used in that same thread. "
  1479. "The object was created in thread id %lu and this is thread id %lu.",
  1480. self->thread_ident, PyThread_get_thread_ident());
  1481. return 0;
  1482. }
  1483. }
  1484. return 1;
  1485. }
  1486. static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
  1487. {
  1488. if (!pysqlite_check_connection(self)) {
  1489. return NULL;
  1490. }
  1491. if (self->isolation_level != NULL) {
  1492. return PyUnicode_FromString(self->isolation_level);
  1493. }
  1494. Py_RETURN_NONE;
  1495. }
  1496. static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
  1497. {
  1498. if (!pysqlite_check_connection(self)) {
  1499. return NULL;
  1500. }
  1501. return PyLong_FromLong(sqlite3_total_changes(self->db));
  1502. }
  1503. static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
  1504. {
  1505. if (!pysqlite_check_connection(self)) {
  1506. return NULL;
  1507. }
  1508. if (!sqlite3_get_autocommit(self->db)) {
  1509. Py_RETURN_TRUE;
  1510. }
  1511. Py_RETURN_FALSE;
  1512. }
  1513. static int
  1514. pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
  1515. {
  1516. if (isolation_level == NULL) {
  1517. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1518. return -1;
  1519. }
  1520. if (Py_IsNone(isolation_level)) {
  1521. self->isolation_level = NULL;
  1522. // Execute a COMMIT to re-enable autocommit mode
  1523. PyObject *res = pysqlite_connection_commit_impl(self);
  1524. if (res == NULL) {
  1525. return -1;
  1526. }
  1527. Py_DECREF(res);
  1528. return 0;
  1529. }
  1530. if (!isolation_level_converter(isolation_level, &self->isolation_level)) {
  1531. return -1;
  1532. }
  1533. return 0;
  1534. }
  1535. static PyObject *
  1536. pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
  1537. PyObject *kwargs)
  1538. {
  1539. PyObject* sql;
  1540. pysqlite_Statement* statement;
  1541. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1542. return NULL;
  1543. }
  1544. if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
  1545. return NULL;
  1546. if (!PyArg_ParseTuple(args, "U", &sql))
  1547. return NULL;
  1548. statement = pysqlite_statement_create(self, sql);
  1549. if (statement == NULL) {
  1550. return NULL;
  1551. }
  1552. return (PyObject*)statement;
  1553. }
  1554. /*[clinic input]
  1555. _sqlite3.Connection.execute as pysqlite_connection_execute
  1556. sql: unicode
  1557. parameters: object = NULL
  1558. /
  1559. Executes an SQL statement.
  1560. [clinic start generated code]*/
  1561. static PyObject *
  1562. pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
  1563. PyObject *parameters)
  1564. /*[clinic end generated code: output=5be05ae01ee17ee4 input=27aa7792681ddba2]*/
  1565. {
  1566. PyObject* result = 0;
  1567. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1568. if (!cursor) {
  1569. goto error;
  1570. }
  1571. result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 0, sql, parameters);
  1572. if (!result) {
  1573. Py_CLEAR(cursor);
  1574. }
  1575. error:
  1576. Py_XDECREF(result);
  1577. return cursor;
  1578. }
  1579. /*[clinic input]
  1580. _sqlite3.Connection.executemany as pysqlite_connection_executemany
  1581. sql: unicode
  1582. parameters: object
  1583. /
  1584. Repeatedly executes an SQL statement.
  1585. [clinic start generated code]*/
  1586. static PyObject *
  1587. pysqlite_connection_executemany_impl(pysqlite_Connection *self,
  1588. PyObject *sql, PyObject *parameters)
  1589. /*[clinic end generated code: output=776cd2fd20bfe71f input=495be76551d525db]*/
  1590. {
  1591. PyObject* result = 0;
  1592. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1593. if (!cursor) {
  1594. goto error;
  1595. }
  1596. result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 1, sql, parameters);
  1597. if (!result) {
  1598. Py_CLEAR(cursor);
  1599. }
  1600. error:
  1601. Py_XDECREF(result);
  1602. return cursor;
  1603. }
  1604. /*[clinic input]
  1605. _sqlite3.Connection.executescript as pysqlite_connection_executescript
  1606. sql_script as script_obj: object
  1607. /
  1608. Executes multiple SQL statements at once.
  1609. [clinic start generated code]*/
  1610. static PyObject *
  1611. pysqlite_connection_executescript(pysqlite_Connection *self,
  1612. PyObject *script_obj)
  1613. /*[clinic end generated code: output=4c4f9d77aa0ae37d input=f6e5f1ccfa313db4]*/
  1614. {
  1615. PyObject* result = 0;
  1616. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1617. if (!cursor) {
  1618. goto error;
  1619. }
  1620. PyObject *meth = self->state->str_executescript; // borrowed ref.
  1621. result = PyObject_CallMethodObjArgs(cursor, meth, script_obj, NULL);
  1622. if (!result) {
  1623. Py_CLEAR(cursor);
  1624. }
  1625. error:
  1626. Py_XDECREF(result);
  1627. return cursor;
  1628. }
  1629. /* ------------------------- COLLATION CODE ------------------------ */
  1630. static int
  1631. collation_callback(void *context, int text1_length, const void *text1_data,
  1632. int text2_length, const void *text2_data)
  1633. {
  1634. PyGILState_STATE gilstate = PyGILState_Ensure();
  1635. PyObject* string1 = 0;
  1636. PyObject* string2 = 0;
  1637. PyObject* retval = NULL;
  1638. long longval;
  1639. int result = 0;
  1640. /* This callback may be executed multiple times per sqlite3_step(). Bail if
  1641. * the previous call failed */
  1642. if (PyErr_Occurred()) {
  1643. goto finally;
  1644. }
  1645. string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
  1646. if (string1 == NULL) {
  1647. goto finally;
  1648. }
  1649. string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
  1650. if (string2 == NULL) {
  1651. goto finally;
  1652. }
  1653. callback_context *ctx = (callback_context *)context;
  1654. assert(ctx != NULL);
  1655. PyObject *args[] = { NULL, string1, string2 }; // Borrowed refs.
  1656. size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
  1657. retval = PyObject_Vectorcall(ctx->callable, args + 1, nargsf, NULL);
  1658. if (retval == NULL) {
  1659. /* execution failed */
  1660. goto finally;
  1661. }
  1662. longval = PyLong_AsLongAndOverflow(retval, &result);
  1663. if (longval == -1 && PyErr_Occurred()) {
  1664. PyErr_Clear();
  1665. result = 0;
  1666. }
  1667. else if (!result) {
  1668. if (longval > 0)
  1669. result = 1;
  1670. else if (longval < 0)
  1671. result = -1;
  1672. }
  1673. finally:
  1674. Py_XDECREF(string1);
  1675. Py_XDECREF(string2);
  1676. Py_XDECREF(retval);
  1677. PyGILState_Release(gilstate);
  1678. return result;
  1679. }
  1680. /*[clinic input]
  1681. _sqlite3.Connection.interrupt as pysqlite_connection_interrupt
  1682. Abort any pending database operation.
  1683. [clinic start generated code]*/
  1684. static PyObject *
  1685. pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
  1686. /*[clinic end generated code: output=f193204bc9e70b47 input=75ad03ade7012859]*/
  1687. {
  1688. PyObject* retval = NULL;
  1689. if (!pysqlite_check_connection(self)) {
  1690. goto finally;
  1691. }
  1692. sqlite3_interrupt(self->db);
  1693. retval = Py_NewRef(Py_None);
  1694. finally:
  1695. return retval;
  1696. }
  1697. /* Function author: Paul Kippes <kippesp@gmail.com>
  1698. * Class method of Connection to call the Python function _iterdump
  1699. * of the sqlite3 module.
  1700. */
  1701. /*[clinic input]
  1702. _sqlite3.Connection.iterdump as pysqlite_connection_iterdump
  1703. Returns iterator to the dump of the database in an SQL text format.
  1704. [clinic start generated code]*/
  1705. static PyObject *
  1706. pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
  1707. /*[clinic end generated code: output=586997aaf9808768 input=1911ca756066da89]*/
  1708. {
  1709. if (!pysqlite_check_connection(self)) {
  1710. return NULL;
  1711. }
  1712. PyObject *iterdump = _PyImport_GetModuleAttrString(MODULE_NAME ".dump", "_iterdump");
  1713. if (!iterdump) {
  1714. if (!PyErr_Occurred()) {
  1715. PyErr_SetString(self->OperationalError,
  1716. "Failed to obtain _iterdump() reference");
  1717. }
  1718. return NULL;
  1719. }
  1720. PyObject *retval = PyObject_CallOneArg(iterdump, (PyObject *)self);
  1721. Py_DECREF(iterdump);
  1722. return retval;
  1723. }
  1724. /*[clinic input]
  1725. _sqlite3.Connection.backup as pysqlite_connection_backup
  1726. target: object(type='pysqlite_Connection *', subclass_of='clinic_state()->ConnectionType')
  1727. *
  1728. pages: int = -1
  1729. progress: object = None
  1730. name: str = "main"
  1731. sleep: double = 0.250
  1732. Makes a backup of the database.
  1733. [clinic start generated code]*/
  1734. static PyObject *
  1735. pysqlite_connection_backup_impl(pysqlite_Connection *self,
  1736. pysqlite_Connection *target, int pages,
  1737. PyObject *progress, const char *name,
  1738. double sleep)
  1739. /*[clinic end generated code: output=306a3e6a38c36334 input=c6519d0f59d0fd7f]*/
  1740. {
  1741. int rc;
  1742. int sleep_ms = (int)(sleep * 1000.0);
  1743. sqlite3 *bck_conn;
  1744. sqlite3_backup *bck_handle;
  1745. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1746. return NULL;
  1747. }
  1748. if (!pysqlite_check_connection(target)) {
  1749. return NULL;
  1750. }
  1751. if (target == self) {
  1752. PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
  1753. return NULL;
  1754. }
  1755. #if SQLITE_VERSION_NUMBER < 3008008
  1756. /* Since 3.8.8 this is already done, per commit
  1757. https://www.sqlite.org/src/info/169b5505498c0a7e */
  1758. if (!sqlite3_get_autocommit(target->db)) {
  1759. PyErr_SetString(self->OperationalError, "target is in transaction");
  1760. return NULL;
  1761. }
  1762. #endif
  1763. if (progress != Py_None && !PyCallable_Check(progress)) {
  1764. PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
  1765. return NULL;
  1766. }
  1767. if (pages == 0) {
  1768. pages = -1;
  1769. }
  1770. bck_conn = target->db;
  1771. Py_BEGIN_ALLOW_THREADS
  1772. bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
  1773. Py_END_ALLOW_THREADS
  1774. if (bck_handle == NULL) {
  1775. _pysqlite_seterror(self->state, bck_conn);
  1776. return NULL;
  1777. }
  1778. do {
  1779. Py_BEGIN_ALLOW_THREADS
  1780. rc = sqlite3_backup_step(bck_handle, pages);
  1781. Py_END_ALLOW_THREADS
  1782. if (progress != Py_None) {
  1783. int remaining = sqlite3_backup_remaining(bck_handle);
  1784. int pagecount = sqlite3_backup_pagecount(bck_handle);
  1785. PyObject *res = PyObject_CallFunction(progress, "iii", rc,
  1786. remaining, pagecount);
  1787. if (res == NULL) {
  1788. /* Callback failed: abort backup and bail. */
  1789. Py_BEGIN_ALLOW_THREADS
  1790. sqlite3_backup_finish(bck_handle);
  1791. Py_END_ALLOW_THREADS
  1792. return NULL;
  1793. }
  1794. Py_DECREF(res);
  1795. }
  1796. /* Sleep for a while if there are still further pages to copy and
  1797. the engine could not make any progress */
  1798. if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
  1799. Py_BEGIN_ALLOW_THREADS
  1800. sqlite3_sleep(sleep_ms);
  1801. Py_END_ALLOW_THREADS
  1802. }
  1803. } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
  1804. Py_BEGIN_ALLOW_THREADS
  1805. rc = sqlite3_backup_finish(bck_handle);
  1806. Py_END_ALLOW_THREADS
  1807. if (rc != SQLITE_OK) {
  1808. _pysqlite_seterror(self->state, bck_conn);
  1809. return NULL;
  1810. }
  1811. Py_RETURN_NONE;
  1812. }
  1813. /*[clinic input]
  1814. _sqlite3.Connection.create_collation as pysqlite_connection_create_collation
  1815. cls: defining_class
  1816. name: str
  1817. callback as callable: object
  1818. /
  1819. Creates a collation function.
  1820. [clinic start generated code]*/
  1821. static PyObject *
  1822. pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
  1823. PyTypeObject *cls,
  1824. const char *name,
  1825. PyObject *callable)
  1826. /*[clinic end generated code: output=32d339e97869c378 input=f67ecd2e31e61ad3]*/
  1827. {
  1828. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1829. return NULL;
  1830. }
  1831. callback_context *ctx = NULL;
  1832. int rc;
  1833. int flags = SQLITE_UTF8;
  1834. if (callable == Py_None) {
  1835. rc = sqlite3_create_collation_v2(self->db, name, flags,
  1836. NULL, NULL, NULL);
  1837. }
  1838. else {
  1839. if (!PyCallable_Check(callable)) {
  1840. PyErr_SetString(PyExc_TypeError, "parameter must be callable");
  1841. return NULL;
  1842. }
  1843. ctx = create_callback_context(cls, callable);
  1844. if (ctx == NULL) {
  1845. return NULL;
  1846. }
  1847. rc = sqlite3_create_collation_v2(self->db, name, flags, ctx,
  1848. &collation_callback,
  1849. &destructor_callback);
  1850. }
  1851. if (rc != SQLITE_OK) {
  1852. /* Unlike other sqlite3_* functions, the destructor callback is _not_
  1853. * called if sqlite3_create_collation_v2() fails, so we have to free
  1854. * the context before returning.
  1855. */
  1856. if (callable != Py_None) {
  1857. free_callback_context(ctx);
  1858. }
  1859. _pysqlite_seterror(self->state, self->db);
  1860. return NULL;
  1861. }
  1862. Py_RETURN_NONE;
  1863. }
  1864. #ifdef PY_SQLITE_HAVE_SERIALIZE
  1865. /*[clinic input]
  1866. _sqlite3.Connection.serialize as serialize
  1867. *
  1868. name: str = "main"
  1869. Which database to serialize.
  1870. Serialize a database into a byte string.
  1871. For an ordinary on-disk database file, the serialization is just a copy of the
  1872. disk file. For an in-memory database or a "temp" database, the serialization is
  1873. the same sequence of bytes which would be written to disk if that database
  1874. were backed up to disk.
  1875. [clinic start generated code]*/
  1876. static PyObject *
  1877. serialize_impl(pysqlite_Connection *self, const char *name)
  1878. /*[clinic end generated code: output=97342b0e55239dd3 input=d2eb5194a65abe2b]*/
  1879. {
  1880. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1881. return NULL;
  1882. }
  1883. /* If SQLite has a contiguous memory representation of the database, we can
  1884. * avoid memory allocations, so we try with the no-copy flag first.
  1885. */
  1886. sqlite3_int64 size;
  1887. unsigned int flags = SQLITE_SERIALIZE_NOCOPY;
  1888. const char *data;
  1889. Py_BEGIN_ALLOW_THREADS
  1890. data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
  1891. if (data == NULL) {
  1892. flags &= ~SQLITE_SERIALIZE_NOCOPY;
  1893. data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
  1894. }
  1895. Py_END_ALLOW_THREADS
  1896. if (data == NULL) {
  1897. PyErr_Format(self->OperationalError, "unable to serialize '%s'",
  1898. name);
  1899. return NULL;
  1900. }
  1901. PyObject *res = PyBytes_FromStringAndSize(data, (Py_ssize_t)size);
  1902. if (!(flags & SQLITE_SERIALIZE_NOCOPY)) {
  1903. sqlite3_free((void *)data);
  1904. }
  1905. return res;
  1906. }
  1907. /*[clinic input]
  1908. _sqlite3.Connection.deserialize as deserialize
  1909. data: Py_buffer(accept={buffer, str})
  1910. The serialized database content.
  1911. /
  1912. *
  1913. name: str = "main"
  1914. Which database to reopen with the deserialization.
  1915. Load a serialized database.
  1916. The deserialize interface causes the database connection to disconnect from the
  1917. target database, and then reopen it as an in-memory database based on the given
  1918. serialized data.
  1919. The deserialize interface will fail with SQLITE_BUSY if the database is
  1920. currently in a read transaction or is involved in a backup operation.
  1921. [clinic start generated code]*/
  1922. static PyObject *
  1923. deserialize_impl(pysqlite_Connection *self, Py_buffer *data,
  1924. const char *name)
  1925. /*[clinic end generated code: output=e394c798b98bad89 input=1be4ca1faacf28f2]*/
  1926. {
  1927. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1928. return NULL;
  1929. }
  1930. /* Transfer ownership of the buffer to SQLite:
  1931. * - Move buffer from Py to SQLite
  1932. * - Tell SQLite to free buffer memory
  1933. * - Tell SQLite that it is permitted to grow the resulting database
  1934. *
  1935. * Make sure we don't overflow sqlite3_deserialize(); it accepts a signed
  1936. * 64-bit int as its data size argument.
  1937. *
  1938. * We can safely use sqlite3_malloc64 here, since it was introduced before
  1939. * the serialize APIs.
  1940. */
  1941. if (data->len > 9223372036854775807) { // (1 << 63) - 1
  1942. PyErr_SetString(PyExc_OverflowError, "'data' is too large");
  1943. return NULL;
  1944. }
  1945. sqlite3_int64 size = (sqlite3_int64)data->len;
  1946. unsigned char *buf = sqlite3_malloc64(size);
  1947. if (buf == NULL) {
  1948. return PyErr_NoMemory();
  1949. }
  1950. const unsigned int flags = SQLITE_DESERIALIZE_FREEONCLOSE |
  1951. SQLITE_DESERIALIZE_RESIZEABLE;
  1952. int rc;
  1953. Py_BEGIN_ALLOW_THREADS
  1954. (void)memcpy(buf, data->buf, data->len);
  1955. rc = sqlite3_deserialize(self->db, name, buf, size, size, flags);
  1956. Py_END_ALLOW_THREADS
  1957. if (rc != SQLITE_OK) {
  1958. (void)_pysqlite_seterror(self->state, self->db);
  1959. return NULL;
  1960. }
  1961. Py_RETURN_NONE;
  1962. }
  1963. #endif // PY_SQLITE_HAVE_SERIALIZE
  1964. /*[clinic input]
  1965. _sqlite3.Connection.__enter__ as pysqlite_connection_enter
  1966. Called when the connection is used as a context manager.
  1967. Returns itself as a convenience to the caller.
  1968. [clinic start generated code]*/
  1969. static PyObject *
  1970. pysqlite_connection_enter_impl(pysqlite_Connection *self)
  1971. /*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
  1972. {
  1973. if (!pysqlite_check_connection(self)) {
  1974. return NULL;
  1975. }
  1976. return Py_NewRef((PyObject *)self);
  1977. }
  1978. /*[clinic input]
  1979. _sqlite3.Connection.__exit__ as pysqlite_connection_exit
  1980. type as exc_type: object
  1981. value as exc_value: object
  1982. traceback as exc_tb: object
  1983. /
  1984. Called when the connection is used as a context manager.
  1985. If there was any exception, a rollback takes place; otherwise we commit.
  1986. [clinic start generated code]*/
  1987. static PyObject *
  1988. pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
  1989. PyObject *exc_value, PyObject *exc_tb)
  1990. /*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
  1991. {
  1992. int commit = 0;
  1993. PyObject* result;
  1994. if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
  1995. commit = 1;
  1996. result = pysqlite_connection_commit_impl(self);
  1997. }
  1998. else {
  1999. result = pysqlite_connection_rollback_impl(self);
  2000. }
  2001. if (result == NULL) {
  2002. if (commit) {
  2003. /* Commit failed; try to rollback in order to unlock the database.
  2004. * If rollback also fails, chain the exceptions. */
  2005. PyObject *exc = PyErr_GetRaisedException();
  2006. result = pysqlite_connection_rollback_impl(self);
  2007. if (result == NULL) {
  2008. _PyErr_ChainExceptions1(exc);
  2009. }
  2010. else {
  2011. Py_DECREF(result);
  2012. PyErr_SetRaisedException(exc);
  2013. }
  2014. }
  2015. return NULL;
  2016. }
  2017. Py_DECREF(result);
  2018. Py_RETURN_FALSE;
  2019. }
  2020. /*[clinic input]
  2021. _sqlite3.Connection.setlimit as setlimit
  2022. category: int
  2023. The limit category to be set.
  2024. limit: int
  2025. The new limit. If the new limit is a negative number, the limit is
  2026. unchanged.
  2027. /
  2028. Set connection run-time limits.
  2029. Attempts to increase a limit above its hard upper bound are silently truncated
  2030. to the hard upper bound. Regardless of whether or not the limit was changed,
  2031. the prior value of the limit is returned.
  2032. [clinic start generated code]*/
  2033. static PyObject *
  2034. setlimit_impl(pysqlite_Connection *self, int category, int limit)
  2035. /*[clinic end generated code: output=0d208213f8d68ccd input=9bd469537e195635]*/
  2036. {
  2037. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2038. return NULL;
  2039. }
  2040. int old_limit = sqlite3_limit(self->db, category, limit);
  2041. if (old_limit < 0) {
  2042. PyErr_SetString(self->ProgrammingError, "'category' is out of bounds");
  2043. return NULL;
  2044. }
  2045. return PyLong_FromLong(old_limit);
  2046. }
  2047. /*[clinic input]
  2048. _sqlite3.Connection.getlimit as getlimit
  2049. category: int
  2050. The limit category to be queried.
  2051. /
  2052. Get connection run-time limits.
  2053. [clinic start generated code]*/
  2054. static PyObject *
  2055. getlimit_impl(pysqlite_Connection *self, int category)
  2056. /*[clinic end generated code: output=7c3f5d11f24cecb1 input=61e0849fb4fb058f]*/
  2057. {
  2058. return setlimit_impl(self, category, -1);
  2059. }
  2060. static inline bool
  2061. is_int_config(const int op)
  2062. {
  2063. switch (op) {
  2064. case SQLITE_DBCONFIG_ENABLE_FKEY:
  2065. case SQLITE_DBCONFIG_ENABLE_TRIGGER:
  2066. #if SQLITE_VERSION_NUMBER >= 3012002
  2067. case SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:
  2068. #endif
  2069. #if SQLITE_VERSION_NUMBER >= 3013000
  2070. case SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:
  2071. #endif
  2072. #if SQLITE_VERSION_NUMBER >= 3016000
  2073. case SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:
  2074. #endif
  2075. #if SQLITE_VERSION_NUMBER >= 3020000
  2076. case SQLITE_DBCONFIG_ENABLE_QPSG:
  2077. #endif
  2078. #if SQLITE_VERSION_NUMBER >= 3022000
  2079. case SQLITE_DBCONFIG_TRIGGER_EQP:
  2080. #endif
  2081. #if SQLITE_VERSION_NUMBER >= 3024000
  2082. case SQLITE_DBCONFIG_RESET_DATABASE:
  2083. #endif
  2084. #if SQLITE_VERSION_NUMBER >= 3026000
  2085. case SQLITE_DBCONFIG_DEFENSIVE:
  2086. #endif
  2087. #if SQLITE_VERSION_NUMBER >= 3028000
  2088. case SQLITE_DBCONFIG_WRITABLE_SCHEMA:
  2089. #endif
  2090. #if SQLITE_VERSION_NUMBER >= 3029000
  2091. case SQLITE_DBCONFIG_DQS_DDL:
  2092. case SQLITE_DBCONFIG_DQS_DML:
  2093. case SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:
  2094. #endif
  2095. #if SQLITE_VERSION_NUMBER >= 3030000
  2096. case SQLITE_DBCONFIG_ENABLE_VIEW:
  2097. #endif
  2098. #if SQLITE_VERSION_NUMBER >= 3031000
  2099. case SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:
  2100. case SQLITE_DBCONFIG_TRUSTED_SCHEMA:
  2101. #endif
  2102. return true;
  2103. default:
  2104. return false;
  2105. }
  2106. }
  2107. /*[clinic input]
  2108. _sqlite3.Connection.setconfig as setconfig
  2109. op: int
  2110. The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes.
  2111. enable: bool = True
  2112. /
  2113. Set a boolean connection configuration option.
  2114. [clinic start generated code]*/
  2115. static PyObject *
  2116. setconfig_impl(pysqlite_Connection *self, int op, int enable)
  2117. /*[clinic end generated code: output=c60b13e618aff873 input=a10f1539c2d7da6b]*/
  2118. {
  2119. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2120. return NULL;
  2121. }
  2122. if (!is_int_config(op)) {
  2123. return PyErr_Format(PyExc_ValueError, "unknown config 'op': %d", op);
  2124. }
  2125. int actual;
  2126. int rc = sqlite3_db_config(self->db, op, enable, &actual);
  2127. if (rc != SQLITE_OK) {
  2128. (void)_pysqlite_seterror(self->state, self->db);
  2129. return NULL;
  2130. }
  2131. if (enable != actual) {
  2132. PyErr_SetString(self->state->OperationalError, "Unable to set config");
  2133. return NULL;
  2134. }
  2135. Py_RETURN_NONE;
  2136. }
  2137. /*[clinic input]
  2138. _sqlite3.Connection.getconfig as getconfig -> bool
  2139. op: int
  2140. The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes.
  2141. /
  2142. Query a boolean connection configuration option.
  2143. [clinic start generated code]*/
  2144. static int
  2145. getconfig_impl(pysqlite_Connection *self, int op)
  2146. /*[clinic end generated code: output=25ac05044c7b78a3 input=b0526d7e432e3f2f]*/
  2147. {
  2148. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2149. return -1;
  2150. }
  2151. if (!is_int_config(op)) {
  2152. PyErr_Format(PyExc_ValueError, "unknown config 'op': %d", op);
  2153. return -1;
  2154. }
  2155. int current;
  2156. int rc = sqlite3_db_config(self->db, op, -1, &current);
  2157. if (rc != SQLITE_OK) {
  2158. (void)_pysqlite_seterror(self->state, self->db);
  2159. return -1;
  2160. }
  2161. return current;
  2162. }
  2163. static PyObject *
  2164. get_autocommit(pysqlite_Connection *self, void *Py_UNUSED(ctx))
  2165. {
  2166. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2167. return NULL;
  2168. }
  2169. if (self->autocommit == AUTOCOMMIT_ENABLED) {
  2170. Py_RETURN_TRUE;
  2171. }
  2172. if (self->autocommit == AUTOCOMMIT_DISABLED) {
  2173. Py_RETURN_FALSE;
  2174. }
  2175. return PyLong_FromLong(LEGACY_TRANSACTION_CONTROL);
  2176. }
  2177. static int
  2178. set_autocommit(pysqlite_Connection *self, PyObject *val, void *Py_UNUSED(ctx))
  2179. {
  2180. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2181. return -1;
  2182. }
  2183. if (!autocommit_converter(val, &self->autocommit)) {
  2184. return -1;
  2185. }
  2186. if (self->autocommit == AUTOCOMMIT_ENABLED) {
  2187. if (!sqlite3_get_autocommit(self->db)) {
  2188. if (connection_exec_stmt(self, "COMMIT") < 0) {
  2189. return -1;
  2190. }
  2191. }
  2192. }
  2193. else if (self->autocommit == AUTOCOMMIT_DISABLED) {
  2194. if (sqlite3_get_autocommit(self->db)) {
  2195. if (connection_exec_stmt(self, "BEGIN") < 0) {
  2196. return -1;
  2197. }
  2198. }
  2199. }
  2200. return 0;
  2201. }
  2202. static const char connection_doc[] =
  2203. PyDoc_STR("SQLite database connection object.");
  2204. static PyGetSetDef connection_getset[] = {
  2205. {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
  2206. {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
  2207. {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
  2208. {"autocommit", (getter)get_autocommit, (setter)set_autocommit},
  2209. {NULL}
  2210. };
  2211. static PyMethodDef connection_methods[] = {
  2212. PYSQLITE_CONNECTION_BACKUP_METHODDEF
  2213. PYSQLITE_CONNECTION_CLOSE_METHODDEF
  2214. PYSQLITE_CONNECTION_COMMIT_METHODDEF
  2215. PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
  2216. PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
  2217. PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
  2218. PYSQLITE_CONNECTION_CURSOR_METHODDEF
  2219. PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
  2220. PYSQLITE_CONNECTION_ENTER_METHODDEF
  2221. PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
  2222. PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
  2223. PYSQLITE_CONNECTION_EXECUTE_METHODDEF
  2224. PYSQLITE_CONNECTION_EXIT_METHODDEF
  2225. PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
  2226. PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
  2227. PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
  2228. PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
  2229. PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
  2230. PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
  2231. PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
  2232. SETLIMIT_METHODDEF
  2233. GETLIMIT_METHODDEF
  2234. SERIALIZE_METHODDEF
  2235. DESERIALIZE_METHODDEF
  2236. CREATE_WINDOW_FUNCTION_METHODDEF
  2237. BLOBOPEN_METHODDEF
  2238. SETCONFIG_METHODDEF
  2239. GETCONFIG_METHODDEF
  2240. {NULL, NULL}
  2241. };
  2242. static struct PyMemberDef connection_members[] =
  2243. {
  2244. {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
  2245. {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
  2246. {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
  2247. {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
  2248. {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
  2249. {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
  2250. {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
  2251. {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
  2252. {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
  2253. {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
  2254. {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
  2255. {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
  2256. {NULL}
  2257. };
  2258. static PyType_Slot connection_slots[] = {
  2259. {Py_tp_finalize, connection_finalize},
  2260. {Py_tp_dealloc, connection_dealloc},
  2261. {Py_tp_doc, (void *)connection_doc},
  2262. {Py_tp_methods, connection_methods},
  2263. {Py_tp_members, connection_members},
  2264. {Py_tp_getset, connection_getset},
  2265. {Py_tp_init, pysqlite_connection_init},
  2266. {Py_tp_call, pysqlite_connection_call},
  2267. {Py_tp_traverse, connection_traverse},
  2268. {Py_tp_clear, connection_clear},
  2269. {0, NULL},
  2270. };
  2271. static PyType_Spec connection_spec = {
  2272. .name = MODULE_NAME ".Connection",
  2273. .basicsize = sizeof(pysqlite_Connection),
  2274. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  2275. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  2276. .slots = connection_slots,
  2277. };
  2278. int
  2279. pysqlite_connection_setup_types(PyObject *module)
  2280. {
  2281. PyObject *type = PyType_FromModuleAndSpec(module, &connection_spec, NULL);
  2282. if (type == NULL) {
  2283. return -1;
  2284. }
  2285. pysqlite_state *state = pysqlite_get_state(module);
  2286. state->ConnectionType = (PyTypeObject *)type;
  2287. return 0;
  2288. }