connection.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664
  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. (void)PyErr_NoMemory();
  810. set_sqlite_error(context, "unable to allocate SQLite aggregate context");
  811. goto error;
  812. }
  813. if (*aggregate_instance == NULL) {
  814. *aggregate_instance = PyObject_CallNoArgs(ctx->callable);
  815. if (!*aggregate_instance) {
  816. set_sqlite_error(context,
  817. "user-defined aggregate's '__init__' method raised error");
  818. goto error;
  819. }
  820. }
  821. stepmethod = PyObject_GetAttr(*aggregate_instance, ctx->state->str_step);
  822. if (!stepmethod) {
  823. set_sqlite_error(context,
  824. "user-defined aggregate's 'step' method not defined");
  825. goto error;
  826. }
  827. args = _pysqlite_build_py_params(context, argc, params);
  828. if (!args) {
  829. goto error;
  830. }
  831. function_result = PyObject_CallObject(stepmethod, args);
  832. Py_DECREF(args);
  833. if (!function_result) {
  834. set_sqlite_error(context,
  835. "user-defined aggregate's 'step' method raised error");
  836. }
  837. error:
  838. Py_XDECREF(stepmethod);
  839. Py_XDECREF(function_result);
  840. PyGILState_Release(threadstate);
  841. }
  842. static void
  843. final_callback(sqlite3_context *context)
  844. {
  845. PyGILState_STATE threadstate = PyGILState_Ensure();
  846. PyObject* function_result;
  847. PyObject** aggregate_instance;
  848. int ok;
  849. aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
  850. if (aggregate_instance == NULL) {
  851. /* No rows matched the query; the step handler was never called. */
  852. goto error;
  853. }
  854. else if (!*aggregate_instance) {
  855. /* this branch is executed if there was an exception in the aggregate's
  856. * __init__ */
  857. goto error;
  858. }
  859. // Keep the exception (if any) of the last call to step, value, or inverse
  860. PyObject *exc = PyErr_GetRaisedException();
  861. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  862. assert(ctx != NULL);
  863. function_result = PyObject_CallMethodNoArgs(*aggregate_instance,
  864. ctx->state->str_finalize);
  865. Py_DECREF(*aggregate_instance);
  866. ok = 0;
  867. if (function_result) {
  868. ok = _pysqlite_set_result(context, function_result) == 0;
  869. Py_DECREF(function_result);
  870. }
  871. if (!ok) {
  872. int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
  873. _PyErr_ChainExceptions1(exc);
  874. /* Note: contrary to the step, value, and inverse callbacks, SQLite
  875. * does _not_, as of SQLite 3.38.0, propagate errors to sqlite3_step()
  876. * from the finalize callback. This implies that execute*() will not
  877. * raise OperationalError, as it normally would. */
  878. set_sqlite_error(context, attr_err
  879. ? "user-defined aggregate's 'finalize' method not defined"
  880. : "user-defined aggregate's 'finalize' method raised error");
  881. }
  882. else {
  883. PyErr_SetRaisedException(exc);
  884. }
  885. error:
  886. PyGILState_Release(threadstate);
  887. }
  888. static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
  889. {
  890. PyObject* new_list;
  891. PyObject* weakref;
  892. int i;
  893. /* we only need to do this once in a while */
  894. if (self->created_cursors++ < 200) {
  895. return;
  896. }
  897. self->created_cursors = 0;
  898. new_list = PyList_New(0);
  899. if (!new_list) {
  900. return;
  901. }
  902. for (i = 0; i < PyList_Size(self->cursors); i++) {
  903. weakref = PyList_GetItem(self->cursors, i);
  904. if (PyWeakref_GetObject(weakref) != Py_None) {
  905. if (PyList_Append(new_list, weakref) != 0) {
  906. Py_DECREF(new_list);
  907. return;
  908. }
  909. }
  910. }
  911. Py_SETREF(self->cursors, new_list);
  912. }
  913. /* Allocate a UDF/callback context structure. In order to ensure that the state
  914. * pointer always outlives the callback context, we make sure it owns a
  915. * reference to the module itself. create_callback_context() is always called
  916. * from connection methods, so we use the defining class to fetch the module
  917. * pointer.
  918. */
  919. static callback_context *
  920. create_callback_context(PyTypeObject *cls, PyObject *callable)
  921. {
  922. callback_context *ctx = PyMem_Malloc(sizeof(callback_context));
  923. if (ctx != NULL) {
  924. PyObject *module = PyType_GetModule(cls);
  925. ctx->callable = Py_NewRef(callable);
  926. ctx->module = Py_NewRef(module);
  927. ctx->state = pysqlite_get_state(module);
  928. }
  929. return ctx;
  930. }
  931. static void
  932. free_callback_context(callback_context *ctx)
  933. {
  934. assert(ctx != NULL);
  935. Py_XDECREF(ctx->callable);
  936. Py_XDECREF(ctx->module);
  937. PyMem_Free(ctx);
  938. }
  939. static void
  940. set_callback_context(callback_context **ctx_pp, callback_context *ctx)
  941. {
  942. assert(ctx_pp != NULL);
  943. callback_context *tmp = *ctx_pp;
  944. *ctx_pp = ctx;
  945. if (tmp != NULL) {
  946. free_callback_context(tmp);
  947. }
  948. }
  949. static void
  950. destructor_callback(void *ctx)
  951. {
  952. if (ctx != NULL) {
  953. // This function may be called without the GIL held, so we need to
  954. // ensure that we destroy 'ctx' with the GIL held.
  955. PyGILState_STATE gstate = PyGILState_Ensure();
  956. free_callback_context((callback_context *)ctx);
  957. PyGILState_Release(gstate);
  958. }
  959. }
  960. /*[clinic input]
  961. _sqlite3.Connection.create_function as pysqlite_connection_create_function
  962. cls: defining_class
  963. /
  964. name: str
  965. narg: int
  966. func: object
  967. *
  968. deterministic: bool = False
  969. Creates a new function.
  970. [clinic start generated code]*/
  971. static PyObject *
  972. pysqlite_connection_create_function_impl(pysqlite_Connection *self,
  973. PyTypeObject *cls, const char *name,
  974. int narg, PyObject *func,
  975. int deterministic)
  976. /*[clinic end generated code: output=8a811529287ad240 input=b3e8e1d8ddaffbef]*/
  977. {
  978. int rc;
  979. int flags = SQLITE_UTF8;
  980. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  981. return NULL;
  982. }
  983. if (deterministic) {
  984. #if SQLITE_VERSION_NUMBER < 3008003
  985. PyErr_SetString(self->NotSupportedError,
  986. "deterministic=True requires SQLite 3.8.3 or higher");
  987. return NULL;
  988. #else
  989. if (sqlite3_libversion_number() < 3008003) {
  990. PyErr_SetString(self->NotSupportedError,
  991. "deterministic=True requires SQLite 3.8.3 or higher");
  992. return NULL;
  993. }
  994. flags |= SQLITE_DETERMINISTIC;
  995. #endif
  996. }
  997. callback_context *ctx = create_callback_context(cls, func);
  998. if (ctx == NULL) {
  999. return NULL;
  1000. }
  1001. rc = sqlite3_create_function_v2(self->db, name, narg, flags, ctx,
  1002. func_callback,
  1003. NULL,
  1004. NULL,
  1005. &destructor_callback); // will decref func
  1006. if (rc != SQLITE_OK) {
  1007. /* Workaround for SQLite bug: no error code or string is available here */
  1008. PyErr_SetString(self->OperationalError, "Error creating function");
  1009. return NULL;
  1010. }
  1011. Py_RETURN_NONE;
  1012. }
  1013. #ifdef HAVE_WINDOW_FUNCTIONS
  1014. /*
  1015. * Regarding the 'inverse' aggregate callback:
  1016. * This method is only required by window aggregate functions, not
  1017. * ordinary aggregate function implementations. It is invoked to remove
  1018. * a row from the current window. The function arguments, if any,
  1019. * correspond to the row being removed.
  1020. */
  1021. static void
  1022. inverse_callback(sqlite3_context *context, int argc, sqlite3_value **params)
  1023. {
  1024. PyGILState_STATE gilstate = PyGILState_Ensure();
  1025. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  1026. assert(ctx != NULL);
  1027. int size = sizeof(PyObject *);
  1028. PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
  1029. assert(cls != NULL);
  1030. assert(*cls != NULL);
  1031. PyObject *method = PyObject_GetAttr(*cls, ctx->state->str_inverse);
  1032. if (method == NULL) {
  1033. set_sqlite_error(context,
  1034. "user-defined aggregate's 'inverse' method not defined");
  1035. goto exit;
  1036. }
  1037. PyObject *args = _pysqlite_build_py_params(context, argc, params);
  1038. if (args == NULL) {
  1039. set_sqlite_error(context,
  1040. "unable to build arguments for user-defined aggregate's "
  1041. "'inverse' method");
  1042. goto exit;
  1043. }
  1044. PyObject *res = PyObject_CallObject(method, args);
  1045. Py_DECREF(args);
  1046. if (res == NULL) {
  1047. set_sqlite_error(context,
  1048. "user-defined aggregate's 'inverse' method raised error");
  1049. goto exit;
  1050. }
  1051. Py_DECREF(res);
  1052. exit:
  1053. Py_XDECREF(method);
  1054. PyGILState_Release(gilstate);
  1055. }
  1056. /*
  1057. * Regarding the 'value' aggregate callback:
  1058. * This method is only required by window aggregate functions, not
  1059. * ordinary aggregate function implementations. It is invoked to return
  1060. * the current value of the aggregate.
  1061. */
  1062. static void
  1063. value_callback(sqlite3_context *context)
  1064. {
  1065. PyGILState_STATE gilstate = PyGILState_Ensure();
  1066. callback_context *ctx = (callback_context *)sqlite3_user_data(context);
  1067. assert(ctx != NULL);
  1068. int size = sizeof(PyObject *);
  1069. PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
  1070. assert(cls != NULL);
  1071. assert(*cls != NULL);
  1072. PyObject *res = PyObject_CallMethodNoArgs(*cls, ctx->state->str_value);
  1073. if (res == NULL) {
  1074. int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
  1075. set_sqlite_error(context, attr_err
  1076. ? "user-defined aggregate's 'value' method not defined"
  1077. : "user-defined aggregate's 'value' method raised error");
  1078. }
  1079. else {
  1080. int rc = _pysqlite_set_result(context, res);
  1081. Py_DECREF(res);
  1082. if (rc < 0) {
  1083. set_sqlite_error(context,
  1084. "unable to set result from user-defined aggregate's "
  1085. "'value' method");
  1086. }
  1087. }
  1088. PyGILState_Release(gilstate);
  1089. }
  1090. /*[clinic input]
  1091. _sqlite3.Connection.create_window_function as create_window_function
  1092. cls: defining_class
  1093. name: str
  1094. The name of the SQL aggregate window function to be created or
  1095. redefined.
  1096. num_params: int
  1097. The number of arguments the step and inverse methods takes.
  1098. aggregate_class: object
  1099. A class with step(), finalize(), value(), and inverse() methods.
  1100. Set to None to clear the window function.
  1101. /
  1102. Creates or redefines an aggregate window function. Non-standard.
  1103. [clinic start generated code]*/
  1104. static PyObject *
  1105. create_window_function_impl(pysqlite_Connection *self, PyTypeObject *cls,
  1106. const char *name, int num_params,
  1107. PyObject *aggregate_class)
  1108. /*[clinic end generated code: output=5332cd9464522235 input=46d57a54225b5228]*/
  1109. {
  1110. if (sqlite3_libversion_number() < 3025000) {
  1111. PyErr_SetString(self->NotSupportedError,
  1112. "create_window_function() requires "
  1113. "SQLite 3.25.0 or higher");
  1114. return NULL;
  1115. }
  1116. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1117. return NULL;
  1118. }
  1119. int flags = SQLITE_UTF8;
  1120. int rc;
  1121. if (Py_IsNone(aggregate_class)) {
  1122. rc = sqlite3_create_window_function(self->db, name, num_params, flags,
  1123. 0, 0, 0, 0, 0, 0);
  1124. }
  1125. else {
  1126. callback_context *ctx = create_callback_context(cls, aggregate_class);
  1127. if (ctx == NULL) {
  1128. return NULL;
  1129. }
  1130. rc = sqlite3_create_window_function(self->db, name, num_params, flags,
  1131. ctx,
  1132. &step_callback,
  1133. &final_callback,
  1134. &value_callback,
  1135. &inverse_callback,
  1136. &destructor_callback);
  1137. }
  1138. if (rc != SQLITE_OK) {
  1139. // Errors are not set on the database connection, so we cannot
  1140. // use _pysqlite_seterror().
  1141. PyErr_SetString(self->ProgrammingError, sqlite3_errstr(rc));
  1142. return NULL;
  1143. }
  1144. Py_RETURN_NONE;
  1145. }
  1146. #endif
  1147. /*[clinic input]
  1148. _sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
  1149. cls: defining_class
  1150. /
  1151. name: str
  1152. n_arg: int
  1153. aggregate_class: object
  1154. Creates a new aggregate.
  1155. [clinic start generated code]*/
  1156. static PyObject *
  1157. pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
  1158. PyTypeObject *cls,
  1159. const char *name, int n_arg,
  1160. PyObject *aggregate_class)
  1161. /*[clinic end generated code: output=1b02d0f0aec7ff96 input=68a2a26366d4c686]*/
  1162. {
  1163. int rc;
  1164. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1165. return NULL;
  1166. }
  1167. callback_context *ctx = create_callback_context(cls, aggregate_class);
  1168. if (ctx == NULL) {
  1169. return NULL;
  1170. }
  1171. rc = sqlite3_create_function_v2(self->db, name, n_arg, SQLITE_UTF8, ctx,
  1172. 0,
  1173. &step_callback,
  1174. &final_callback,
  1175. &destructor_callback); // will decref func
  1176. if (rc != SQLITE_OK) {
  1177. /* Workaround for SQLite bug: no error code or string is available here */
  1178. PyErr_SetString(self->OperationalError, "Error creating aggregate");
  1179. return NULL;
  1180. }
  1181. Py_RETURN_NONE;
  1182. }
  1183. static int
  1184. authorizer_callback(void *ctx, int action, const char *arg1,
  1185. const char *arg2 , const char *dbname,
  1186. const char *access_attempt_source)
  1187. {
  1188. PyGILState_STATE gilstate = PyGILState_Ensure();
  1189. PyObject *ret;
  1190. int rc = SQLITE_DENY;
  1191. assert(ctx != NULL);
  1192. PyObject *callable = ((callback_context *)ctx)->callable;
  1193. ret = PyObject_CallFunction(callable, "issss", action, arg1, arg2, dbname,
  1194. access_attempt_source);
  1195. if (ret == NULL) {
  1196. print_or_clear_traceback(ctx);
  1197. rc = SQLITE_DENY;
  1198. }
  1199. else {
  1200. if (PyLong_Check(ret)) {
  1201. rc = _PyLong_AsInt(ret);
  1202. if (rc == -1 && PyErr_Occurred()) {
  1203. print_or_clear_traceback(ctx);
  1204. rc = SQLITE_DENY;
  1205. }
  1206. }
  1207. else {
  1208. rc = SQLITE_DENY;
  1209. }
  1210. Py_DECREF(ret);
  1211. }
  1212. PyGILState_Release(gilstate);
  1213. return rc;
  1214. }
  1215. static int
  1216. progress_callback(void *ctx)
  1217. {
  1218. PyGILState_STATE gilstate = PyGILState_Ensure();
  1219. int rc;
  1220. PyObject *ret;
  1221. assert(ctx != NULL);
  1222. PyObject *callable = ((callback_context *)ctx)->callable;
  1223. ret = PyObject_CallNoArgs(callable);
  1224. if (!ret) {
  1225. /* abort query if error occurred */
  1226. rc = -1;
  1227. }
  1228. else {
  1229. rc = PyObject_IsTrue(ret);
  1230. Py_DECREF(ret);
  1231. }
  1232. if (rc < 0) {
  1233. print_or_clear_traceback(ctx);
  1234. }
  1235. PyGILState_Release(gilstate);
  1236. return rc;
  1237. }
  1238. #ifdef HAVE_TRACE_V2
  1239. /*
  1240. * From https://sqlite.org/c3ref/trace_v2.html:
  1241. * The integer return value from the callback is currently ignored, though this
  1242. * may change in future releases. Callback implementations should return zero
  1243. * to ensure future compatibility.
  1244. */
  1245. static int
  1246. trace_callback(unsigned int type, void *ctx, void *stmt, void *sql)
  1247. #else
  1248. static void
  1249. trace_callback(void *ctx, const char *sql)
  1250. #endif
  1251. {
  1252. #ifdef HAVE_TRACE_V2
  1253. if (type != SQLITE_TRACE_STMT) {
  1254. return 0;
  1255. }
  1256. #endif
  1257. PyGILState_STATE gilstate = PyGILState_Ensure();
  1258. assert(ctx != NULL);
  1259. pysqlite_state *state = ((callback_context *)ctx)->state;
  1260. assert(state != NULL);
  1261. PyObject *py_statement = NULL;
  1262. #ifdef HAVE_TRACE_V2
  1263. const char *expanded_sql = sqlite3_expanded_sql((sqlite3_stmt *)stmt);
  1264. if (expanded_sql == NULL) {
  1265. sqlite3 *db = sqlite3_db_handle((sqlite3_stmt *)stmt);
  1266. if (sqlite3_errcode(db) == SQLITE_NOMEM) {
  1267. (void)PyErr_NoMemory();
  1268. goto exit;
  1269. }
  1270. PyErr_SetString(state->DataError,
  1271. "Expanded SQL string exceeds the maximum string length");
  1272. print_or_clear_traceback((callback_context *)ctx);
  1273. // Fall back to unexpanded sql
  1274. py_statement = PyUnicode_FromString((const char *)sql);
  1275. }
  1276. else {
  1277. py_statement = PyUnicode_FromString(expanded_sql);
  1278. sqlite3_free((void *)expanded_sql);
  1279. }
  1280. #else
  1281. if (sql == NULL) {
  1282. PyErr_SetString(state->DataError,
  1283. "Expanded SQL string exceeds the maximum string length");
  1284. print_or_clear_traceback((callback_context *)ctx);
  1285. goto exit;
  1286. }
  1287. py_statement = PyUnicode_FromString(sql);
  1288. #endif
  1289. if (py_statement) {
  1290. PyObject *callable = ((callback_context *)ctx)->callable;
  1291. PyObject *ret = PyObject_CallOneArg(callable, py_statement);
  1292. Py_DECREF(py_statement);
  1293. Py_XDECREF(ret);
  1294. }
  1295. if (PyErr_Occurred()) {
  1296. print_or_clear_traceback((callback_context *)ctx);
  1297. }
  1298. exit:
  1299. PyGILState_Release(gilstate);
  1300. #ifdef HAVE_TRACE_V2
  1301. return 0;
  1302. #endif
  1303. }
  1304. /*[clinic input]
  1305. _sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
  1306. cls: defining_class
  1307. /
  1308. authorizer_callback as callable: object
  1309. Sets authorizer callback.
  1310. [clinic start generated code]*/
  1311. static PyObject *
  1312. pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
  1313. PyTypeObject *cls,
  1314. PyObject *callable)
  1315. /*[clinic end generated code: output=75fa60114fc971c3 input=605d32ba92dd3eca]*/
  1316. {
  1317. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1318. return NULL;
  1319. }
  1320. int rc;
  1321. if (callable == Py_None) {
  1322. rc = sqlite3_set_authorizer(self->db, NULL, NULL);
  1323. set_callback_context(&self->authorizer_ctx, NULL);
  1324. }
  1325. else {
  1326. callback_context *ctx = create_callback_context(cls, callable);
  1327. if (ctx == NULL) {
  1328. return NULL;
  1329. }
  1330. rc = sqlite3_set_authorizer(self->db, authorizer_callback, ctx);
  1331. set_callback_context(&self->authorizer_ctx, ctx);
  1332. }
  1333. if (rc != SQLITE_OK) {
  1334. PyErr_SetString(self->OperationalError,
  1335. "Error setting authorizer callback");
  1336. set_callback_context(&self->authorizer_ctx, NULL);
  1337. return NULL;
  1338. }
  1339. Py_RETURN_NONE;
  1340. }
  1341. /*[clinic input]
  1342. _sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
  1343. cls: defining_class
  1344. /
  1345. progress_handler as callable: object
  1346. n: int
  1347. Sets progress handler callback.
  1348. [clinic start generated code]*/
  1349. static PyObject *
  1350. pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
  1351. PyTypeObject *cls,
  1352. PyObject *callable, int n)
  1353. /*[clinic end generated code: output=0739957fd8034a50 input=f7c1837984bd86db]*/
  1354. {
  1355. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1356. return NULL;
  1357. }
  1358. if (callable == Py_None) {
  1359. /* None clears the progress handler previously set */
  1360. sqlite3_progress_handler(self->db, 0, 0, (void*)0);
  1361. set_callback_context(&self->progress_ctx, NULL);
  1362. }
  1363. else {
  1364. callback_context *ctx = create_callback_context(cls, callable);
  1365. if (ctx == NULL) {
  1366. return NULL;
  1367. }
  1368. sqlite3_progress_handler(self->db, n, progress_callback, ctx);
  1369. set_callback_context(&self->progress_ctx, ctx);
  1370. }
  1371. Py_RETURN_NONE;
  1372. }
  1373. /*[clinic input]
  1374. _sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
  1375. cls: defining_class
  1376. /
  1377. trace_callback as callable: object
  1378. Sets a trace callback called for each SQL statement (passed as unicode).
  1379. [clinic start generated code]*/
  1380. static PyObject *
  1381. pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
  1382. PyTypeObject *cls,
  1383. PyObject *callable)
  1384. /*[clinic end generated code: output=d91048c03bfcee05 input=351a94210c5f81bb]*/
  1385. {
  1386. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1387. return NULL;
  1388. }
  1389. if (callable == Py_None) {
  1390. /*
  1391. * None clears the trace callback previously set
  1392. *
  1393. * Ref.
  1394. * - https://sqlite.org/c3ref/c_trace.html
  1395. * - https://sqlite.org/c3ref/trace_v2.html
  1396. */
  1397. #ifdef HAVE_TRACE_V2
  1398. sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
  1399. #else
  1400. sqlite3_trace(self->db, 0, (void*)0);
  1401. #endif
  1402. set_callback_context(&self->trace_ctx, NULL);
  1403. }
  1404. else {
  1405. callback_context *ctx = create_callback_context(cls, callable);
  1406. if (ctx == NULL) {
  1407. return NULL;
  1408. }
  1409. #ifdef HAVE_TRACE_V2
  1410. sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, trace_callback, ctx);
  1411. #else
  1412. sqlite3_trace(self->db, trace_callback, ctx);
  1413. #endif
  1414. set_callback_context(&self->trace_ctx, ctx);
  1415. }
  1416. Py_RETURN_NONE;
  1417. }
  1418. #ifdef PY_SQLITE_ENABLE_LOAD_EXTENSION
  1419. /*[clinic input]
  1420. _sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
  1421. enable as onoff: bool
  1422. /
  1423. Enable dynamic loading of SQLite extension modules.
  1424. [clinic start generated code]*/
  1425. static PyObject *
  1426. pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
  1427. int onoff)
  1428. /*[clinic end generated code: output=9cac37190d388baf input=2a1e87931486380f]*/
  1429. {
  1430. int rc;
  1431. if (PySys_Audit("sqlite3.enable_load_extension",
  1432. "OO", self, onoff ? Py_True : Py_False) < 0) {
  1433. return NULL;
  1434. }
  1435. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1436. return NULL;
  1437. }
  1438. rc = sqlite3_enable_load_extension(self->db, onoff);
  1439. if (rc != SQLITE_OK) {
  1440. PyErr_SetString(self->OperationalError,
  1441. "Error enabling load extension");
  1442. return NULL;
  1443. } else {
  1444. Py_RETURN_NONE;
  1445. }
  1446. }
  1447. /*[clinic input]
  1448. _sqlite3.Connection.load_extension as pysqlite_connection_load_extension
  1449. name as extension_name: str
  1450. /
  1451. *
  1452. entrypoint: str(accept={str, NoneType}) = None
  1453. Load SQLite extension module.
  1454. [clinic start generated code]*/
  1455. static PyObject *
  1456. pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
  1457. const char *extension_name,
  1458. const char *entrypoint)
  1459. /*[clinic end generated code: output=7e61a7add9de0286 input=c36b14ea702e04f5]*/
  1460. {
  1461. int rc;
  1462. char* errmsg;
  1463. if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
  1464. return NULL;
  1465. }
  1466. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1467. return NULL;
  1468. }
  1469. rc = sqlite3_load_extension(self->db, extension_name, entrypoint, &errmsg);
  1470. if (rc != 0) {
  1471. PyErr_SetString(self->OperationalError, errmsg);
  1472. return NULL;
  1473. } else {
  1474. Py_RETURN_NONE;
  1475. }
  1476. }
  1477. #endif
  1478. int pysqlite_check_thread(pysqlite_Connection* self)
  1479. {
  1480. if (self->check_same_thread) {
  1481. if (PyThread_get_thread_ident() != self->thread_ident) {
  1482. PyErr_Format(self->ProgrammingError,
  1483. "SQLite objects created in a thread can only be used in that same thread. "
  1484. "The object was created in thread id %lu and this is thread id %lu.",
  1485. self->thread_ident, PyThread_get_thread_ident());
  1486. return 0;
  1487. }
  1488. }
  1489. return 1;
  1490. }
  1491. static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
  1492. {
  1493. if (!pysqlite_check_connection(self)) {
  1494. return NULL;
  1495. }
  1496. if (self->isolation_level != NULL) {
  1497. return PyUnicode_FromString(self->isolation_level);
  1498. }
  1499. Py_RETURN_NONE;
  1500. }
  1501. static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
  1502. {
  1503. if (!pysqlite_check_connection(self)) {
  1504. return NULL;
  1505. }
  1506. return PyLong_FromLong(sqlite3_total_changes(self->db));
  1507. }
  1508. static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
  1509. {
  1510. if (!pysqlite_check_connection(self)) {
  1511. return NULL;
  1512. }
  1513. if (!sqlite3_get_autocommit(self->db)) {
  1514. Py_RETURN_TRUE;
  1515. }
  1516. Py_RETURN_FALSE;
  1517. }
  1518. static int
  1519. pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
  1520. {
  1521. if (isolation_level == NULL) {
  1522. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1523. return -1;
  1524. }
  1525. if (Py_IsNone(isolation_level)) {
  1526. self->isolation_level = NULL;
  1527. // Execute a COMMIT to re-enable autocommit mode
  1528. PyObject *res = pysqlite_connection_commit_impl(self);
  1529. if (res == NULL) {
  1530. return -1;
  1531. }
  1532. Py_DECREF(res);
  1533. return 0;
  1534. }
  1535. if (!isolation_level_converter(isolation_level, &self->isolation_level)) {
  1536. return -1;
  1537. }
  1538. return 0;
  1539. }
  1540. static PyObject *
  1541. pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
  1542. PyObject *kwargs)
  1543. {
  1544. PyObject* sql;
  1545. pysqlite_Statement* statement;
  1546. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1547. return NULL;
  1548. }
  1549. if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
  1550. return NULL;
  1551. if (!PyArg_ParseTuple(args, "U", &sql))
  1552. return NULL;
  1553. statement = pysqlite_statement_create(self, sql);
  1554. if (statement == NULL) {
  1555. return NULL;
  1556. }
  1557. return (PyObject*)statement;
  1558. }
  1559. /*[clinic input]
  1560. _sqlite3.Connection.execute as pysqlite_connection_execute
  1561. sql: unicode
  1562. parameters: object = NULL
  1563. /
  1564. Executes an SQL statement.
  1565. [clinic start generated code]*/
  1566. static PyObject *
  1567. pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
  1568. PyObject *parameters)
  1569. /*[clinic end generated code: output=5be05ae01ee17ee4 input=27aa7792681ddba2]*/
  1570. {
  1571. PyObject* result = 0;
  1572. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1573. if (!cursor) {
  1574. goto error;
  1575. }
  1576. result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 0, sql, parameters);
  1577. if (!result) {
  1578. Py_CLEAR(cursor);
  1579. }
  1580. error:
  1581. Py_XDECREF(result);
  1582. return cursor;
  1583. }
  1584. /*[clinic input]
  1585. _sqlite3.Connection.executemany as pysqlite_connection_executemany
  1586. sql: unicode
  1587. parameters: object
  1588. /
  1589. Repeatedly executes an SQL statement.
  1590. [clinic start generated code]*/
  1591. static PyObject *
  1592. pysqlite_connection_executemany_impl(pysqlite_Connection *self,
  1593. PyObject *sql, PyObject *parameters)
  1594. /*[clinic end generated code: output=776cd2fd20bfe71f input=495be76551d525db]*/
  1595. {
  1596. PyObject* result = 0;
  1597. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1598. if (!cursor) {
  1599. goto error;
  1600. }
  1601. result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 1, sql, parameters);
  1602. if (!result) {
  1603. Py_CLEAR(cursor);
  1604. }
  1605. error:
  1606. Py_XDECREF(result);
  1607. return cursor;
  1608. }
  1609. /*[clinic input]
  1610. _sqlite3.Connection.executescript as pysqlite_connection_executescript
  1611. sql_script as script_obj: object
  1612. /
  1613. Executes multiple SQL statements at once.
  1614. [clinic start generated code]*/
  1615. static PyObject *
  1616. pysqlite_connection_executescript(pysqlite_Connection *self,
  1617. PyObject *script_obj)
  1618. /*[clinic end generated code: output=4c4f9d77aa0ae37d input=f6e5f1ccfa313db4]*/
  1619. {
  1620. PyObject* result = 0;
  1621. PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
  1622. if (!cursor) {
  1623. goto error;
  1624. }
  1625. PyObject *meth = self->state->str_executescript; // borrowed ref.
  1626. result = PyObject_CallMethodObjArgs(cursor, meth, script_obj, NULL);
  1627. if (!result) {
  1628. Py_CLEAR(cursor);
  1629. }
  1630. error:
  1631. Py_XDECREF(result);
  1632. return cursor;
  1633. }
  1634. /* ------------------------- COLLATION CODE ------------------------ */
  1635. static int
  1636. collation_callback(void *context, int text1_length, const void *text1_data,
  1637. int text2_length, const void *text2_data)
  1638. {
  1639. PyGILState_STATE gilstate = PyGILState_Ensure();
  1640. PyObject* string1 = 0;
  1641. PyObject* string2 = 0;
  1642. PyObject* retval = NULL;
  1643. long longval;
  1644. int result = 0;
  1645. /* This callback may be executed multiple times per sqlite3_step(). Bail if
  1646. * the previous call failed */
  1647. if (PyErr_Occurred()) {
  1648. goto finally;
  1649. }
  1650. string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
  1651. if (string1 == NULL) {
  1652. goto finally;
  1653. }
  1654. string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
  1655. if (string2 == NULL) {
  1656. goto finally;
  1657. }
  1658. callback_context *ctx = (callback_context *)context;
  1659. assert(ctx != NULL);
  1660. PyObject *args[] = { NULL, string1, string2 }; // Borrowed refs.
  1661. size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
  1662. retval = PyObject_Vectorcall(ctx->callable, args + 1, nargsf, NULL);
  1663. if (retval == NULL) {
  1664. /* execution failed */
  1665. goto finally;
  1666. }
  1667. longval = PyLong_AsLongAndOverflow(retval, &result);
  1668. if (longval == -1 && PyErr_Occurred()) {
  1669. PyErr_Clear();
  1670. result = 0;
  1671. }
  1672. else if (!result) {
  1673. if (longval > 0)
  1674. result = 1;
  1675. else if (longval < 0)
  1676. result = -1;
  1677. }
  1678. finally:
  1679. Py_XDECREF(string1);
  1680. Py_XDECREF(string2);
  1681. Py_XDECREF(retval);
  1682. PyGILState_Release(gilstate);
  1683. return result;
  1684. }
  1685. /*[clinic input]
  1686. _sqlite3.Connection.interrupt as pysqlite_connection_interrupt
  1687. Abort any pending database operation.
  1688. [clinic start generated code]*/
  1689. static PyObject *
  1690. pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
  1691. /*[clinic end generated code: output=f193204bc9e70b47 input=75ad03ade7012859]*/
  1692. {
  1693. PyObject* retval = NULL;
  1694. if (!pysqlite_check_connection(self)) {
  1695. goto finally;
  1696. }
  1697. sqlite3_interrupt(self->db);
  1698. retval = Py_NewRef(Py_None);
  1699. finally:
  1700. return retval;
  1701. }
  1702. /* Function author: Paul Kippes <kippesp@gmail.com>
  1703. * Class method of Connection to call the Python function _iterdump
  1704. * of the sqlite3 module.
  1705. */
  1706. /*[clinic input]
  1707. _sqlite3.Connection.iterdump as pysqlite_connection_iterdump
  1708. Returns iterator to the dump of the database in an SQL text format.
  1709. [clinic start generated code]*/
  1710. static PyObject *
  1711. pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
  1712. /*[clinic end generated code: output=586997aaf9808768 input=1911ca756066da89]*/
  1713. {
  1714. if (!pysqlite_check_connection(self)) {
  1715. return NULL;
  1716. }
  1717. PyObject *iterdump = _PyImport_GetModuleAttrString(MODULE_NAME ".dump", "_iterdump");
  1718. if (!iterdump) {
  1719. if (!PyErr_Occurred()) {
  1720. PyErr_SetString(self->OperationalError,
  1721. "Failed to obtain _iterdump() reference");
  1722. }
  1723. return NULL;
  1724. }
  1725. PyObject *retval = PyObject_CallOneArg(iterdump, (PyObject *)self);
  1726. Py_DECREF(iterdump);
  1727. return retval;
  1728. }
  1729. /*[clinic input]
  1730. _sqlite3.Connection.backup as pysqlite_connection_backup
  1731. target: object(type='pysqlite_Connection *', subclass_of='clinic_state()->ConnectionType')
  1732. *
  1733. pages: int = -1
  1734. progress: object = None
  1735. name: str = "main"
  1736. sleep: double = 0.250
  1737. Makes a backup of the database.
  1738. [clinic start generated code]*/
  1739. static PyObject *
  1740. pysqlite_connection_backup_impl(pysqlite_Connection *self,
  1741. pysqlite_Connection *target, int pages,
  1742. PyObject *progress, const char *name,
  1743. double sleep)
  1744. /*[clinic end generated code: output=306a3e6a38c36334 input=c6519d0f59d0fd7f]*/
  1745. {
  1746. int rc;
  1747. int sleep_ms = (int)(sleep * 1000.0);
  1748. sqlite3 *bck_conn;
  1749. sqlite3_backup *bck_handle;
  1750. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1751. return NULL;
  1752. }
  1753. if (!pysqlite_check_connection(target)) {
  1754. return NULL;
  1755. }
  1756. if (target == self) {
  1757. PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
  1758. return NULL;
  1759. }
  1760. #if SQLITE_VERSION_NUMBER < 3008008
  1761. /* Since 3.8.8 this is already done, per commit
  1762. https://www.sqlite.org/src/info/169b5505498c0a7e */
  1763. if (!sqlite3_get_autocommit(target->db)) {
  1764. PyErr_SetString(self->OperationalError, "target is in transaction");
  1765. return NULL;
  1766. }
  1767. #endif
  1768. if (progress != Py_None && !PyCallable_Check(progress)) {
  1769. PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
  1770. return NULL;
  1771. }
  1772. if (pages == 0) {
  1773. pages = -1;
  1774. }
  1775. bck_conn = target->db;
  1776. Py_BEGIN_ALLOW_THREADS
  1777. bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
  1778. Py_END_ALLOW_THREADS
  1779. if (bck_handle == NULL) {
  1780. _pysqlite_seterror(self->state, bck_conn);
  1781. return NULL;
  1782. }
  1783. do {
  1784. Py_BEGIN_ALLOW_THREADS
  1785. rc = sqlite3_backup_step(bck_handle, pages);
  1786. Py_END_ALLOW_THREADS
  1787. if (progress != Py_None) {
  1788. int remaining = sqlite3_backup_remaining(bck_handle);
  1789. int pagecount = sqlite3_backup_pagecount(bck_handle);
  1790. PyObject *res = PyObject_CallFunction(progress, "iii", rc,
  1791. remaining, pagecount);
  1792. if (res == NULL) {
  1793. /* Callback failed: abort backup and bail. */
  1794. Py_BEGIN_ALLOW_THREADS
  1795. sqlite3_backup_finish(bck_handle);
  1796. Py_END_ALLOW_THREADS
  1797. return NULL;
  1798. }
  1799. Py_DECREF(res);
  1800. }
  1801. /* Sleep for a while if there are still further pages to copy and
  1802. the engine could not make any progress */
  1803. if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
  1804. Py_BEGIN_ALLOW_THREADS
  1805. sqlite3_sleep(sleep_ms);
  1806. Py_END_ALLOW_THREADS
  1807. }
  1808. } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
  1809. Py_BEGIN_ALLOW_THREADS
  1810. rc = sqlite3_backup_finish(bck_handle);
  1811. Py_END_ALLOW_THREADS
  1812. if (rc != SQLITE_OK) {
  1813. _pysqlite_seterror(self->state, bck_conn);
  1814. return NULL;
  1815. }
  1816. Py_RETURN_NONE;
  1817. }
  1818. /*[clinic input]
  1819. _sqlite3.Connection.create_collation as pysqlite_connection_create_collation
  1820. cls: defining_class
  1821. name: str
  1822. callback as callable: object
  1823. /
  1824. Creates a collation function.
  1825. [clinic start generated code]*/
  1826. static PyObject *
  1827. pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
  1828. PyTypeObject *cls,
  1829. const char *name,
  1830. PyObject *callable)
  1831. /*[clinic end generated code: output=32d339e97869c378 input=f67ecd2e31e61ad3]*/
  1832. {
  1833. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1834. return NULL;
  1835. }
  1836. callback_context *ctx = NULL;
  1837. int rc;
  1838. int flags = SQLITE_UTF8;
  1839. if (callable == Py_None) {
  1840. rc = sqlite3_create_collation_v2(self->db, name, flags,
  1841. NULL, NULL, NULL);
  1842. }
  1843. else {
  1844. if (!PyCallable_Check(callable)) {
  1845. PyErr_SetString(PyExc_TypeError, "parameter must be callable");
  1846. return NULL;
  1847. }
  1848. ctx = create_callback_context(cls, callable);
  1849. if (ctx == NULL) {
  1850. return NULL;
  1851. }
  1852. rc = sqlite3_create_collation_v2(self->db, name, flags, ctx,
  1853. &collation_callback,
  1854. &destructor_callback);
  1855. }
  1856. if (rc != SQLITE_OK) {
  1857. /* Unlike other sqlite3_* functions, the destructor callback is _not_
  1858. * called if sqlite3_create_collation_v2() fails, so we have to free
  1859. * the context before returning.
  1860. */
  1861. if (callable != Py_None) {
  1862. free_callback_context(ctx);
  1863. }
  1864. _pysqlite_seterror(self->state, self->db);
  1865. return NULL;
  1866. }
  1867. Py_RETURN_NONE;
  1868. }
  1869. #ifdef PY_SQLITE_HAVE_SERIALIZE
  1870. /*[clinic input]
  1871. _sqlite3.Connection.serialize as serialize
  1872. *
  1873. name: str = "main"
  1874. Which database to serialize.
  1875. Serialize a database into a byte string.
  1876. For an ordinary on-disk database file, the serialization is just a copy of the
  1877. disk file. For an in-memory database or a "temp" database, the serialization is
  1878. the same sequence of bytes which would be written to disk if that database
  1879. were backed up to disk.
  1880. [clinic start generated code]*/
  1881. static PyObject *
  1882. serialize_impl(pysqlite_Connection *self, const char *name)
  1883. /*[clinic end generated code: output=97342b0e55239dd3 input=d2eb5194a65abe2b]*/
  1884. {
  1885. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1886. return NULL;
  1887. }
  1888. /* If SQLite has a contiguous memory representation of the database, we can
  1889. * avoid memory allocations, so we try with the no-copy flag first.
  1890. */
  1891. sqlite3_int64 size;
  1892. unsigned int flags = SQLITE_SERIALIZE_NOCOPY;
  1893. const char *data;
  1894. Py_BEGIN_ALLOW_THREADS
  1895. data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
  1896. if (data == NULL) {
  1897. flags &= ~SQLITE_SERIALIZE_NOCOPY;
  1898. data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
  1899. }
  1900. Py_END_ALLOW_THREADS
  1901. if (data == NULL) {
  1902. PyErr_Format(self->OperationalError, "unable to serialize '%s'",
  1903. name);
  1904. return NULL;
  1905. }
  1906. PyObject *res = PyBytes_FromStringAndSize(data, (Py_ssize_t)size);
  1907. if (!(flags & SQLITE_SERIALIZE_NOCOPY)) {
  1908. sqlite3_free((void *)data);
  1909. }
  1910. return res;
  1911. }
  1912. /*[clinic input]
  1913. _sqlite3.Connection.deserialize as deserialize
  1914. data: Py_buffer(accept={buffer, str})
  1915. The serialized database content.
  1916. /
  1917. *
  1918. name: str = "main"
  1919. Which database to reopen with the deserialization.
  1920. Load a serialized database.
  1921. The deserialize interface causes the database connection to disconnect from the
  1922. target database, and then reopen it as an in-memory database based on the given
  1923. serialized data.
  1924. The deserialize interface will fail with SQLITE_BUSY if the database is
  1925. currently in a read transaction or is involved in a backup operation.
  1926. [clinic start generated code]*/
  1927. static PyObject *
  1928. deserialize_impl(pysqlite_Connection *self, Py_buffer *data,
  1929. const char *name)
  1930. /*[clinic end generated code: output=e394c798b98bad89 input=1be4ca1faacf28f2]*/
  1931. {
  1932. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  1933. return NULL;
  1934. }
  1935. /* Transfer ownership of the buffer to SQLite:
  1936. * - Move buffer from Py to SQLite
  1937. * - Tell SQLite to free buffer memory
  1938. * - Tell SQLite that it is permitted to grow the resulting database
  1939. *
  1940. * Make sure we don't overflow sqlite3_deserialize(); it accepts a signed
  1941. * 64-bit int as its data size argument.
  1942. *
  1943. * We can safely use sqlite3_malloc64 here, since it was introduced before
  1944. * the serialize APIs.
  1945. */
  1946. if (data->len > 9223372036854775807) { // (1 << 63) - 1
  1947. PyErr_SetString(PyExc_OverflowError, "'data' is too large");
  1948. return NULL;
  1949. }
  1950. sqlite3_int64 size = (sqlite3_int64)data->len;
  1951. unsigned char *buf = sqlite3_malloc64(size);
  1952. if (buf == NULL) {
  1953. return PyErr_NoMemory();
  1954. }
  1955. const unsigned int flags = SQLITE_DESERIALIZE_FREEONCLOSE |
  1956. SQLITE_DESERIALIZE_RESIZEABLE;
  1957. int rc;
  1958. Py_BEGIN_ALLOW_THREADS
  1959. (void)memcpy(buf, data->buf, data->len);
  1960. rc = sqlite3_deserialize(self->db, name, buf, size, size, flags);
  1961. Py_END_ALLOW_THREADS
  1962. if (rc != SQLITE_OK) {
  1963. (void)_pysqlite_seterror(self->state, self->db);
  1964. return NULL;
  1965. }
  1966. Py_RETURN_NONE;
  1967. }
  1968. #endif // PY_SQLITE_HAVE_SERIALIZE
  1969. /*[clinic input]
  1970. _sqlite3.Connection.__enter__ as pysqlite_connection_enter
  1971. Called when the connection is used as a context manager.
  1972. Returns itself as a convenience to the caller.
  1973. [clinic start generated code]*/
  1974. static PyObject *
  1975. pysqlite_connection_enter_impl(pysqlite_Connection *self)
  1976. /*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
  1977. {
  1978. if (!pysqlite_check_connection(self)) {
  1979. return NULL;
  1980. }
  1981. return Py_NewRef((PyObject *)self);
  1982. }
  1983. /*[clinic input]
  1984. _sqlite3.Connection.__exit__ as pysqlite_connection_exit
  1985. type as exc_type: object
  1986. value as exc_value: object
  1987. traceback as exc_tb: object
  1988. /
  1989. Called when the connection is used as a context manager.
  1990. If there was any exception, a rollback takes place; otherwise we commit.
  1991. [clinic start generated code]*/
  1992. static PyObject *
  1993. pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
  1994. PyObject *exc_value, PyObject *exc_tb)
  1995. /*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
  1996. {
  1997. int commit = 0;
  1998. PyObject* result;
  1999. if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
  2000. commit = 1;
  2001. result = pysqlite_connection_commit_impl(self);
  2002. }
  2003. else {
  2004. result = pysqlite_connection_rollback_impl(self);
  2005. }
  2006. if (result == NULL) {
  2007. if (commit) {
  2008. /* Commit failed; try to rollback in order to unlock the database.
  2009. * If rollback also fails, chain the exceptions. */
  2010. PyObject *exc = PyErr_GetRaisedException();
  2011. result = pysqlite_connection_rollback_impl(self);
  2012. if (result == NULL) {
  2013. _PyErr_ChainExceptions1(exc);
  2014. }
  2015. else {
  2016. Py_DECREF(result);
  2017. PyErr_SetRaisedException(exc);
  2018. }
  2019. }
  2020. return NULL;
  2021. }
  2022. Py_DECREF(result);
  2023. Py_RETURN_FALSE;
  2024. }
  2025. /*[clinic input]
  2026. _sqlite3.Connection.setlimit as setlimit
  2027. category: int
  2028. The limit category to be set.
  2029. limit: int
  2030. The new limit. If the new limit is a negative number, the limit is
  2031. unchanged.
  2032. /
  2033. Set connection run-time limits.
  2034. Attempts to increase a limit above its hard upper bound are silently truncated
  2035. to the hard upper bound. Regardless of whether or not the limit was changed,
  2036. the prior value of the limit is returned.
  2037. [clinic start generated code]*/
  2038. static PyObject *
  2039. setlimit_impl(pysqlite_Connection *self, int category, int limit)
  2040. /*[clinic end generated code: output=0d208213f8d68ccd input=9bd469537e195635]*/
  2041. {
  2042. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2043. return NULL;
  2044. }
  2045. int old_limit = sqlite3_limit(self->db, category, limit);
  2046. if (old_limit < 0) {
  2047. PyErr_SetString(self->ProgrammingError, "'category' is out of bounds");
  2048. return NULL;
  2049. }
  2050. return PyLong_FromLong(old_limit);
  2051. }
  2052. /*[clinic input]
  2053. _sqlite3.Connection.getlimit as getlimit
  2054. category: int
  2055. The limit category to be queried.
  2056. /
  2057. Get connection run-time limits.
  2058. [clinic start generated code]*/
  2059. static PyObject *
  2060. getlimit_impl(pysqlite_Connection *self, int category)
  2061. /*[clinic end generated code: output=7c3f5d11f24cecb1 input=61e0849fb4fb058f]*/
  2062. {
  2063. return setlimit_impl(self, category, -1);
  2064. }
  2065. static inline bool
  2066. is_int_config(const int op)
  2067. {
  2068. switch (op) {
  2069. case SQLITE_DBCONFIG_ENABLE_FKEY:
  2070. case SQLITE_DBCONFIG_ENABLE_TRIGGER:
  2071. #if SQLITE_VERSION_NUMBER >= 3012002
  2072. case SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:
  2073. #endif
  2074. #if SQLITE_VERSION_NUMBER >= 3013000
  2075. case SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:
  2076. #endif
  2077. #if SQLITE_VERSION_NUMBER >= 3016000
  2078. case SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:
  2079. #endif
  2080. #if SQLITE_VERSION_NUMBER >= 3020000
  2081. case SQLITE_DBCONFIG_ENABLE_QPSG:
  2082. #endif
  2083. #if SQLITE_VERSION_NUMBER >= 3022000
  2084. case SQLITE_DBCONFIG_TRIGGER_EQP:
  2085. #endif
  2086. #if SQLITE_VERSION_NUMBER >= 3024000
  2087. case SQLITE_DBCONFIG_RESET_DATABASE:
  2088. #endif
  2089. #if SQLITE_VERSION_NUMBER >= 3026000
  2090. case SQLITE_DBCONFIG_DEFENSIVE:
  2091. #endif
  2092. #if SQLITE_VERSION_NUMBER >= 3028000
  2093. case SQLITE_DBCONFIG_WRITABLE_SCHEMA:
  2094. #endif
  2095. #if SQLITE_VERSION_NUMBER >= 3029000
  2096. case SQLITE_DBCONFIG_DQS_DDL:
  2097. case SQLITE_DBCONFIG_DQS_DML:
  2098. case SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:
  2099. #endif
  2100. #if SQLITE_VERSION_NUMBER >= 3030000
  2101. case SQLITE_DBCONFIG_ENABLE_VIEW:
  2102. #endif
  2103. #if SQLITE_VERSION_NUMBER >= 3031000
  2104. case SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:
  2105. case SQLITE_DBCONFIG_TRUSTED_SCHEMA:
  2106. #endif
  2107. return true;
  2108. default:
  2109. return false;
  2110. }
  2111. }
  2112. /*[clinic input]
  2113. _sqlite3.Connection.setconfig as setconfig
  2114. op: int
  2115. The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes.
  2116. enable: bool = True
  2117. /
  2118. Set a boolean connection configuration option.
  2119. [clinic start generated code]*/
  2120. static PyObject *
  2121. setconfig_impl(pysqlite_Connection *self, int op, int enable)
  2122. /*[clinic end generated code: output=c60b13e618aff873 input=a10f1539c2d7da6b]*/
  2123. {
  2124. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2125. return NULL;
  2126. }
  2127. if (!is_int_config(op)) {
  2128. return PyErr_Format(PyExc_ValueError, "unknown config 'op': %d", op);
  2129. }
  2130. int actual;
  2131. int rc = sqlite3_db_config(self->db, op, enable, &actual);
  2132. if (rc != SQLITE_OK) {
  2133. (void)_pysqlite_seterror(self->state, self->db);
  2134. return NULL;
  2135. }
  2136. if (enable != actual) {
  2137. PyErr_SetString(self->state->OperationalError, "Unable to set config");
  2138. return NULL;
  2139. }
  2140. Py_RETURN_NONE;
  2141. }
  2142. /*[clinic input]
  2143. _sqlite3.Connection.getconfig as getconfig -> bool
  2144. op: int
  2145. The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes.
  2146. /
  2147. Query a boolean connection configuration option.
  2148. [clinic start generated code]*/
  2149. static int
  2150. getconfig_impl(pysqlite_Connection *self, int op)
  2151. /*[clinic end generated code: output=25ac05044c7b78a3 input=b0526d7e432e3f2f]*/
  2152. {
  2153. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2154. return -1;
  2155. }
  2156. if (!is_int_config(op)) {
  2157. PyErr_Format(PyExc_ValueError, "unknown config 'op': %d", op);
  2158. return -1;
  2159. }
  2160. int current;
  2161. int rc = sqlite3_db_config(self->db, op, -1, &current);
  2162. if (rc != SQLITE_OK) {
  2163. (void)_pysqlite_seterror(self->state, self->db);
  2164. return -1;
  2165. }
  2166. return current;
  2167. }
  2168. static PyObject *
  2169. get_autocommit(pysqlite_Connection *self, void *Py_UNUSED(ctx))
  2170. {
  2171. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2172. return NULL;
  2173. }
  2174. if (self->autocommit == AUTOCOMMIT_ENABLED) {
  2175. Py_RETURN_TRUE;
  2176. }
  2177. if (self->autocommit == AUTOCOMMIT_DISABLED) {
  2178. Py_RETURN_FALSE;
  2179. }
  2180. return PyLong_FromLong(LEGACY_TRANSACTION_CONTROL);
  2181. }
  2182. static int
  2183. set_autocommit(pysqlite_Connection *self, PyObject *val, void *Py_UNUSED(ctx))
  2184. {
  2185. if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
  2186. return -1;
  2187. }
  2188. if (!autocommit_converter(val, &self->autocommit)) {
  2189. return -1;
  2190. }
  2191. if (self->autocommit == AUTOCOMMIT_ENABLED) {
  2192. if (!sqlite3_get_autocommit(self->db)) {
  2193. if (connection_exec_stmt(self, "COMMIT") < 0) {
  2194. return -1;
  2195. }
  2196. }
  2197. }
  2198. else if (self->autocommit == AUTOCOMMIT_DISABLED) {
  2199. if (sqlite3_get_autocommit(self->db)) {
  2200. if (connection_exec_stmt(self, "BEGIN") < 0) {
  2201. return -1;
  2202. }
  2203. }
  2204. }
  2205. return 0;
  2206. }
  2207. static const char connection_doc[] =
  2208. PyDoc_STR("SQLite database connection object.");
  2209. static PyGetSetDef connection_getset[] = {
  2210. {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
  2211. {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
  2212. {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
  2213. {"autocommit", (getter)get_autocommit, (setter)set_autocommit},
  2214. {NULL}
  2215. };
  2216. static PyMethodDef connection_methods[] = {
  2217. PYSQLITE_CONNECTION_BACKUP_METHODDEF
  2218. PYSQLITE_CONNECTION_CLOSE_METHODDEF
  2219. PYSQLITE_CONNECTION_COMMIT_METHODDEF
  2220. PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
  2221. PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
  2222. PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
  2223. PYSQLITE_CONNECTION_CURSOR_METHODDEF
  2224. PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
  2225. PYSQLITE_CONNECTION_ENTER_METHODDEF
  2226. PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
  2227. PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
  2228. PYSQLITE_CONNECTION_EXECUTE_METHODDEF
  2229. PYSQLITE_CONNECTION_EXIT_METHODDEF
  2230. PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
  2231. PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
  2232. PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
  2233. PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
  2234. PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
  2235. PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
  2236. PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
  2237. SETLIMIT_METHODDEF
  2238. GETLIMIT_METHODDEF
  2239. SERIALIZE_METHODDEF
  2240. DESERIALIZE_METHODDEF
  2241. CREATE_WINDOW_FUNCTION_METHODDEF
  2242. BLOBOPEN_METHODDEF
  2243. SETCONFIG_METHODDEF
  2244. GETCONFIG_METHODDEF
  2245. {NULL, NULL}
  2246. };
  2247. static struct PyMemberDef connection_members[] =
  2248. {
  2249. {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
  2250. {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
  2251. {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
  2252. {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
  2253. {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
  2254. {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
  2255. {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
  2256. {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
  2257. {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
  2258. {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
  2259. {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
  2260. {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
  2261. {NULL}
  2262. };
  2263. static PyType_Slot connection_slots[] = {
  2264. {Py_tp_finalize, connection_finalize},
  2265. {Py_tp_dealloc, connection_dealloc},
  2266. {Py_tp_doc, (void *)connection_doc},
  2267. {Py_tp_methods, connection_methods},
  2268. {Py_tp_members, connection_members},
  2269. {Py_tp_getset, connection_getset},
  2270. {Py_tp_init, pysqlite_connection_init},
  2271. {Py_tp_call, pysqlite_connection_call},
  2272. {Py_tp_traverse, connection_traverse},
  2273. {Py_tp_clear, connection_clear},
  2274. {0, NULL},
  2275. };
  2276. static PyType_Spec connection_spec = {
  2277. .name = MODULE_NAME ".Connection",
  2278. .basicsize = sizeof(pysqlite_Connection),
  2279. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  2280. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  2281. .slots = connection_slots,
  2282. };
  2283. int
  2284. pysqlite_connection_setup_types(PyObject *module)
  2285. {
  2286. PyObject *type = PyType_FromModuleAndSpec(module, &connection_spec, NULL);
  2287. if (type == NULL) {
  2288. return -1;
  2289. }
  2290. pysqlite_state *state = pysqlite_get_state(module);
  2291. state->ConnectionType = (PyTypeObject *)type;
  2292. return 0;
  2293. }