You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1137 lines
35 KiB

20 years ago
  1. /* cursor.c - the cursor type
  2. *
  3. * Copyright (C) 2004-2010 Gerhard Hring <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 "cursor.h"
  24. #include "module.h"
  25. #include "util.h"
  26. #include "sqlitecompat.h"
  27. /* used to decide wether to call PyInt_FromLong or PyLong_FromLongLong */
  28. #ifndef INT32_MIN
  29. #define INT32_MIN (-2147483647 - 1)
  30. #endif
  31. #ifndef INT32_MAX
  32. #define INT32_MAX 2147483647
  33. #endif
  34. PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self);
  35. static char* errmsg_fetch_across_rollback = "Cursor needed to be reset because of commit/rollback and can no longer be fetched from.";
  36. static pysqlite_StatementKind detect_statement_type(char* statement)
  37. {
  38. char buf[20];
  39. char* src;
  40. char* dst;
  41. src = statement;
  42. /* skip over whitepace */
  43. while (*src == '\r' || *src == '\n' || *src == ' ' || *src == '\t') {
  44. src++;
  45. }
  46. if (*src == 0)
  47. return STATEMENT_INVALID;
  48. dst = buf;
  49. *dst = 0;
  50. while (Py_ISALPHA(*src) && dst - buf < sizeof(buf) - 2) {
  51. *dst++ = Py_TOLOWER(*src++);
  52. }
  53. *dst = 0;
  54. if (!strcmp(buf, "select")) {
  55. return STATEMENT_SELECT;
  56. } else if (!strcmp(buf, "insert")) {
  57. return STATEMENT_INSERT;
  58. } else if (!strcmp(buf, "update")) {
  59. return STATEMENT_UPDATE;
  60. } else if (!strcmp(buf, "delete")) {
  61. return STATEMENT_DELETE;
  62. } else if (!strcmp(buf, "replace")) {
  63. return STATEMENT_REPLACE;
  64. } else {
  65. return STATEMENT_OTHER;
  66. }
  67. }
  68. static int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
  69. {
  70. pysqlite_Connection* connection;
  71. if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection))
  72. {
  73. return -1;
  74. }
  75. Py_INCREF(connection);
  76. self->connection = connection;
  77. self->statement = NULL;
  78. self->next_row = NULL;
  79. self->in_weakreflist = NULL;
  80. self->row_cast_map = PyList_New(0);
  81. if (!self->row_cast_map) {
  82. return -1;
  83. }
  84. Py_INCREF(Py_None);
  85. self->description = Py_None;
  86. Py_INCREF(Py_None);
  87. self->lastrowid= Py_None;
  88. self->arraysize = 1;
  89. self->closed = 0;
  90. self->reset = 0;
  91. self->rowcount = -1L;
  92. Py_INCREF(Py_None);
  93. self->row_factory = Py_None;
  94. if (!pysqlite_check_thread(self->connection)) {
  95. return -1;
  96. }
  97. if (!pysqlite_connection_register_cursor(connection, (PyObject*)self)) {
  98. return -1;
  99. }
  100. self->initialized = 1;
  101. return 0;
  102. }
  103. static void pysqlite_cursor_dealloc(pysqlite_Cursor* self)
  104. {
  105. int rc;
  106. /* Reset the statement if the user has not closed the cursor */
  107. if (self->statement) {
  108. rc = pysqlite_statement_reset(self->statement);
  109. Py_DECREF(self->statement);
  110. }
  111. Py_XDECREF(self->connection);
  112. Py_XDECREF(self->row_cast_map);
  113. Py_XDECREF(self->description);
  114. Py_XDECREF(self->lastrowid);
  115. Py_XDECREF(self->row_factory);
  116. Py_XDECREF(self->next_row);
  117. if (self->in_weakreflist != NULL) {
  118. PyObject_ClearWeakRefs((PyObject*)self);
  119. }
  120. self->ob_type->tp_free((PyObject*)self);
  121. }
  122. PyObject* _pysqlite_get_converter(PyObject* key)
  123. {
  124. PyObject* upcase_key;
  125. PyObject* retval;
  126. upcase_key = PyObject_CallMethod(key, "upper", "");
  127. if (!upcase_key) {
  128. return NULL;
  129. }
  130. retval = PyDict_GetItem(converters, upcase_key);
  131. Py_DECREF(upcase_key);
  132. return retval;
  133. }
  134. int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
  135. {
  136. int i;
  137. const char* type_start = (const char*)-1;
  138. const char* pos;
  139. const char* colname;
  140. const char* decltype;
  141. PyObject* py_decltype;
  142. PyObject* converter;
  143. PyObject* key;
  144. if (!self->connection->detect_types) {
  145. return 0;
  146. }
  147. Py_XDECREF(self->row_cast_map);
  148. self->row_cast_map = PyList_New(0);
  149. for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
  150. converter = NULL;
  151. if (self->connection->detect_types & PARSE_COLNAMES) {
  152. colname = sqlite3_column_name(self->statement->st, i);
  153. if (colname) {
  154. for (pos = colname; *pos != 0; pos++) {
  155. if (*pos == '[') {
  156. type_start = pos + 1;
  157. } else if (*pos == ']' && type_start != (const char*)-1) {
  158. key = PyString_FromStringAndSize(type_start, pos - type_start);
  159. if (!key) {
  160. /* creating a string failed, but it is too complicated
  161. * to propagate the error here, we just assume there is
  162. * no converter and proceed */
  163. break;
  164. }
  165. converter = _pysqlite_get_converter(key);
  166. Py_DECREF(key);
  167. break;
  168. }
  169. }
  170. }
  171. }
  172. if (!converter && self->connection->detect_types & PARSE_DECLTYPES) {
  173. decltype = sqlite3_column_decltype(self->statement->st, i);
  174. if (decltype) {
  175. for (pos = decltype;;pos++) {
  176. /* Converter names are split at '(' and blanks.
  177. * This allows 'INTEGER NOT NULL' to be treated as 'INTEGER' and
  178. * 'NUMBER(10)' to be treated as 'NUMBER', for example.
  179. * In other words, it will work as people expect it to work.*/
  180. if (*pos == ' ' || *pos == '(' || *pos == 0) {
  181. py_decltype = PyString_FromStringAndSize(decltype, pos - decltype);
  182. if (!py_decltype) {
  183. return -1;
  184. }
  185. break;
  186. }
  187. }
  188. converter = _pysqlite_get_converter(py_decltype);
  189. Py_DECREF(py_decltype);
  190. }
  191. }
  192. if (!converter) {
  193. converter = Py_None;
  194. }
  195. if (PyList_Append(self->row_cast_map, converter) != 0) {
  196. if (converter != Py_None) {
  197. Py_DECREF(converter);
  198. }
  199. Py_XDECREF(self->row_cast_map);
  200. self->row_cast_map = NULL;
  201. return -1;
  202. }
  203. }
  204. return 0;
  205. }
  206. PyObject* _pysqlite_build_column_name(const char* colname)
  207. {
  208. const char* pos;
  209. if (!colname) {
  210. Py_INCREF(Py_None);
  211. return Py_None;
  212. }
  213. for (pos = colname;; pos++) {
  214. if (*pos == 0 || *pos == '[') {
  215. if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
  216. pos--;
  217. }
  218. return PyString_FromStringAndSize(colname, pos - colname);
  219. }
  220. }
  221. }
  222. PyObject* pysqlite_unicode_from_string(const char* val_str, Py_ssize_t size, int optimize)
  223. {
  224. const char* check;
  225. Py_ssize_t pos;
  226. int is_ascii = 0;
  227. if (optimize) {
  228. is_ascii = 1;
  229. check = val_str;
  230. for (pos = 0; pos < size; pos++) {
  231. if (*check & 0x80) {
  232. is_ascii = 0;
  233. break;
  234. }
  235. check++;
  236. }
  237. }
  238. if (is_ascii) {
  239. return PyString_FromStringAndSize(val_str, size);
  240. } else {
  241. return PyUnicode_DecodeUTF8(val_str, size, NULL);
  242. }
  243. }
  244. /*
  245. * Returns a row from the currently active SQLite statement
  246. *
  247. * Precondidition:
  248. * - sqlite3_step() has been called before and it returned SQLITE_ROW.
  249. */
  250. PyObject* _pysqlite_fetch_one_row(pysqlite_Cursor* self)
  251. {
  252. int i, numcols;
  253. PyObject* row;
  254. PyObject* item = NULL;
  255. int coltype;
  256. PY_LONG_LONG intval;
  257. PyObject* converter;
  258. PyObject* converted;
  259. Py_ssize_t nbytes;
  260. PyObject* buffer;
  261. void* raw_buffer;
  262. const char* val_str;
  263. char buf[200];
  264. const char* colname;
  265. if (self->reset) {
  266. PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
  267. return NULL;
  268. }
  269. Py_BEGIN_ALLOW_THREADS
  270. numcols = sqlite3_data_count(self->statement->st);
  271. Py_END_ALLOW_THREADS
  272. row = PyTuple_New(numcols);
  273. if (!row) {
  274. return NULL;
  275. }
  276. for (i = 0; i < numcols; i++) {
  277. if (self->connection->detect_types) {
  278. converter = PyList_GetItem(self->row_cast_map, i);
  279. if (!converter) {
  280. converter = Py_None;
  281. }
  282. } else {
  283. converter = Py_None;
  284. }
  285. if (converter != Py_None) {
  286. nbytes = sqlite3_column_bytes(self->statement->st, i);
  287. val_str = (const char*)sqlite3_column_blob(self->statement->st, i);
  288. if (!val_str) {
  289. Py_INCREF(Py_None);
  290. converted = Py_None;
  291. } else {
  292. item = PyString_FromStringAndSize(val_str, nbytes);
  293. if (!item) {
  294. return NULL;
  295. }
  296. converted = PyObject_CallFunction(converter, "O", item);
  297. Py_DECREF(item);
  298. if (!converted) {
  299. break;
  300. }
  301. }
  302. } else {
  303. Py_BEGIN_ALLOW_THREADS
  304. coltype = sqlite3_column_type(self->statement->st, i);
  305. Py_END_ALLOW_THREADS
  306. if (coltype == SQLITE_NULL) {
  307. Py_INCREF(Py_None);
  308. converted = Py_None;
  309. } else if (coltype == SQLITE_INTEGER) {
  310. intval = sqlite3_column_int64(self->statement->st, i);
  311. if (intval < INT32_MIN || intval > INT32_MAX) {
  312. converted = PyLong_FromLongLong(intval);
  313. } else {
  314. converted = PyInt_FromLong((long)intval);
  315. }
  316. } else if (coltype == SQLITE_FLOAT) {
  317. converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i));
  318. } else if (coltype == SQLITE_TEXT) {
  319. val_str = (const char*)sqlite3_column_text(self->statement->st, i);
  320. nbytes = sqlite3_column_bytes(self->statement->st, i);
  321. if ((self->connection->text_factory == (PyObject*)&PyUnicode_Type)
  322. || (self->connection->text_factory == pysqlite_OptimizedUnicode)) {
  323. converted = pysqlite_unicode_from_string(val_str, nbytes,
  324. self->connection->text_factory == pysqlite_OptimizedUnicode ? 1 : 0);
  325. if (!converted) {
  326. colname = sqlite3_column_name(self->statement->st, i);
  327. if (!colname) {
  328. colname = "<unknown column name>";
  329. }
  330. PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
  331. colname , val_str);
  332. PyErr_SetString(pysqlite_OperationalError, buf);
  333. }
  334. } else if (self->connection->text_factory == (PyObject*)&PyString_Type) {
  335. converted = PyString_FromStringAndSize(val_str, nbytes);
  336. } else {
  337. converted = PyObject_CallFunction(self->connection->text_factory, "s#", val_str, nbytes);
  338. }
  339. } else {
  340. /* coltype == SQLITE_BLOB */
  341. nbytes = sqlite3_column_bytes(self->statement->st, i);
  342. buffer = PyBuffer_New(nbytes);
  343. if (!buffer) {
  344. break;
  345. }
  346. if (PyObject_AsWriteBuffer(buffer, &raw_buffer, &nbytes)) {
  347. break;
  348. }
  349. memcpy(raw_buffer, sqlite3_column_blob(self->statement->st, i), nbytes);
  350. converted = buffer;
  351. }
  352. }
  353. if (converted) {
  354. PyTuple_SetItem(row, i, converted);
  355. } else {
  356. Py_INCREF(Py_None);
  357. PyTuple_SetItem(row, i, Py_None);
  358. }
  359. }
  360. if (PyErr_Occurred()) {
  361. Py_DECREF(row);
  362. row = NULL;
  363. }
  364. return row;
  365. }
  366. /*
  367. * Checks if a cursor object is usable.
  368. *
  369. * 0 => error; 1 => ok
  370. */
  371. static int check_cursor(pysqlite_Cursor* cur)
  372. {
  373. if (!cur->initialized) {
  374. PyErr_SetString(pysqlite_ProgrammingError, "Base Cursor.__init__ not called.");
  375. return 0;
  376. }
  377. if (cur->closed) {
  378. PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed cursor.");
  379. return 0;
  380. }
  381. if (cur->locked) {
  382. PyErr_SetString(pysqlite_ProgrammingError, "Recursive use of cursors not allowed.");
  383. return 0;
  384. }
  385. return pysqlite_check_thread(cur->connection) && pysqlite_check_connection(cur->connection);
  386. }
  387. PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args)
  388. {
  389. PyObject* operation;
  390. PyObject* operation_bytestr = NULL;
  391. char* operation_cstr;
  392. PyObject* parameters_list = NULL;
  393. PyObject* parameters_iter = NULL;
  394. PyObject* parameters = NULL;
  395. int i;
  396. int rc;
  397. PyObject* func_args;
  398. PyObject* result;
  399. int numcols;
  400. PY_LONG_LONG lastrowid;
  401. int statement_type;
  402. PyObject* descriptor;
  403. PyObject* second_argument = NULL;
  404. int allow_8bit_chars;
  405. if (!check_cursor(self)) {
  406. goto error;
  407. }
  408. self->locked = 1;
  409. self->reset = 0;
  410. /* Make shooting yourself in the foot with not utf-8 decodable 8-bit-strings harder */
  411. allow_8bit_chars = ((self->connection->text_factory != (PyObject*)&PyUnicode_Type) &&
  412. (self->connection->text_factory != pysqlite_OptimizedUnicode));
  413. Py_XDECREF(self->next_row);
  414. self->next_row = NULL;
  415. if (multiple) {
  416. /* executemany() */
  417. if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) {
  418. goto error;
  419. }
  420. if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
  421. PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
  422. goto error;
  423. }
  424. if (PyIter_Check(second_argument)) {
  425. /* iterator */
  426. Py_INCREF(second_argument);
  427. parameters_iter = second_argument;
  428. } else {
  429. /* sequence */
  430. parameters_iter = PyObject_GetIter(second_argument);
  431. if (!parameters_iter) {
  432. goto error;
  433. }
  434. }
  435. } else {
  436. /* execute() */
  437. if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) {
  438. goto error;
  439. }
  440. if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
  441. PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
  442. goto error;
  443. }
  444. parameters_list = PyList_New(0);
  445. if (!parameters_list) {
  446. goto error;
  447. }
  448. if (second_argument == NULL) {
  449. second_argument = PyTuple_New(0);
  450. if (!second_argument) {
  451. goto error;
  452. }
  453. } else {
  454. Py_INCREF(second_argument);
  455. }
  456. if (PyList_Append(parameters_list, second_argument) != 0) {
  457. Py_DECREF(second_argument);
  458. goto error;
  459. }
  460. Py_DECREF(second_argument);
  461. parameters_iter = PyObject_GetIter(parameters_list);
  462. if (!parameters_iter) {
  463. goto error;
  464. }
  465. }
  466. if (self->statement != NULL) {
  467. /* There is an active statement */
  468. rc = pysqlite_statement_reset(self->statement);
  469. }
  470. if (PyString_Check(operation)) {
  471. operation_cstr = PyString_AsString(operation);
  472. } else {
  473. operation_bytestr = PyUnicode_AsUTF8String(operation);
  474. if (!operation_bytestr) {
  475. goto error;
  476. }
  477. operation_cstr = PyString_AsString(operation_bytestr);
  478. }
  479. /* reset description and rowcount */
  480. Py_DECREF(self->description);
  481. Py_INCREF(Py_None);
  482. self->description = Py_None;
  483. self->rowcount = -1L;
  484. func_args = PyTuple_New(1);
  485. if (!func_args) {
  486. goto error;
  487. }
  488. Py_INCREF(operation);
  489. if (PyTuple_SetItem(func_args, 0, operation) != 0) {
  490. goto error;
  491. }
  492. if (self->statement) {
  493. (void)pysqlite_statement_reset(self->statement);
  494. Py_DECREF(self->statement);
  495. }
  496. self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args);
  497. Py_DECREF(func_args);
  498. if (!self->statement) {
  499. goto error;
  500. }
  501. if (self->statement->in_use) {
  502. Py_DECREF(self->statement);
  503. self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
  504. if (!self->statement) {
  505. goto error;
  506. }
  507. rc = pysqlite_statement_create(self->statement, self->connection, operation);
  508. if (rc != SQLITE_OK) {
  509. Py_CLEAR(self->statement);
  510. goto error;
  511. }
  512. }
  513. pysqlite_statement_reset(self->statement);
  514. pysqlite_statement_mark_dirty(self->statement);
  515. statement_type = detect_statement_type(operation_cstr);
  516. if (self->connection->begin_statement) {
  517. switch (statement_type) {
  518. case STATEMENT_UPDATE:
  519. case STATEMENT_DELETE:
  520. case STATEMENT_INSERT:
  521. case STATEMENT_REPLACE:
  522. if (!self->connection->inTransaction) {
  523. result = _pysqlite_connection_begin(self->connection);
  524. if (!result) {
  525. goto error;
  526. }
  527. Py_DECREF(result);
  528. }
  529. break;
  530. case STATEMENT_OTHER:
  531. /* it's a DDL statement or something similar
  532. - we better COMMIT first so it works for all cases */
  533. if (self->connection->inTransaction) {
  534. result = pysqlite_connection_commit(self->connection, NULL);
  535. if (!result) {
  536. goto error;
  537. }
  538. Py_DECREF(result);
  539. }
  540. break;
  541. case STATEMENT_SELECT:
  542. if (multiple) {
  543. PyErr_SetString(pysqlite_ProgrammingError,
  544. "You cannot execute SELECT statements in executemany().");
  545. goto error;
  546. }
  547. break;
  548. }
  549. }
  550. while (1) {
  551. parameters = PyIter_Next(parameters_iter);
  552. if (!parameters) {
  553. break;
  554. }
  555. pysqlite_statement_mark_dirty(self->statement);
  556. pysqlite_statement_bind_parameters(self->statement, parameters, allow_8bit_chars);
  557. if (PyErr_Occurred()) {
  558. goto error;
  559. }
  560. /* Keep trying the SQL statement until the schema stops changing. */
  561. while (1) {
  562. /* Actually execute the SQL statement. */
  563. rc = pysqlite_step(self->statement->st, self->connection);
  564. if (rc == SQLITE_DONE || rc == SQLITE_ROW) {
  565. /* If it worked, let's get out of the loop */
  566. break;
  567. }
  568. /* Something went wrong. Re-set the statement and try again. */
  569. rc = pysqlite_statement_reset(self->statement);
  570. if (rc == SQLITE_SCHEMA) {
  571. /* If this was a result of the schema changing, let's try
  572. again. */
  573. rc = pysqlite_statement_recompile(self->statement, parameters);
  574. if (rc == SQLITE_OK) {
  575. continue;
  576. } else {
  577. /* If the database gave us an error, promote it to Python. */
  578. (void)pysqlite_statement_reset(self->statement);
  579. _pysqlite_seterror(self->connection->db, NULL);
  580. goto error;
  581. }
  582. } else {
  583. if (PyErr_Occurred()) {
  584. /* there was an error that occurred in a user-defined callback */
  585. if (_enable_callback_tracebacks) {
  586. PyErr_Print();
  587. } else {
  588. PyErr_Clear();
  589. }
  590. }
  591. (void)pysqlite_statement_reset(self->statement);
  592. _pysqlite_seterror(self->connection->db, NULL);
  593. goto error;
  594. }
  595. }
  596. if (pysqlite_build_row_cast_map(self) != 0) {
  597. PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map");
  598. goto error;
  599. }
  600. if (rc == SQLITE_ROW || (rc == SQLITE_DONE && statement_type == STATEMENT_SELECT)) {
  601. if (self->description == Py_None) {
  602. Py_BEGIN_ALLOW_THREADS
  603. numcols = sqlite3_column_count(self->statement->st);
  604. Py_END_ALLOW_THREADS
  605. Py_DECREF(self->description);
  606. self->description = PyTuple_New(numcols);
  607. if (!self->description) {
  608. goto error;
  609. }
  610. for (i = 0; i < numcols; i++) {
  611. descriptor = PyTuple_New(7);
  612. if (!descriptor) {
  613. goto error;
  614. }
  615. PyTuple_SetItem(descriptor, 0, _pysqlite_build_column_name(sqlite3_column_name(self->statement->st, i)));
  616. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
  617. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
  618. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
  619. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 4, Py_None);
  620. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 5, Py_None);
  621. Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 6, Py_None);
  622. PyTuple_SetItem(self->description, i, descriptor);
  623. }
  624. }
  625. }
  626. if (rc == SQLITE_ROW) {
  627. if (multiple) {
  628. PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements.");
  629. goto error;
  630. }
  631. self->next_row = _pysqlite_fetch_one_row(self);
  632. } else if (rc == SQLITE_DONE && !multiple) {
  633. pysqlite_statement_reset(self->statement);
  634. Py_CLEAR(self->statement);
  635. }
  636. switch (statement_type) {
  637. case STATEMENT_UPDATE:
  638. case STATEMENT_DELETE:
  639. case STATEMENT_INSERT:
  640. case STATEMENT_REPLACE:
  641. if (self->rowcount == -1L) {
  642. self->rowcount = 0L;
  643. }
  644. self->rowcount += (long)sqlite3_changes(self->connection->db);
  645. }
  646. Py_DECREF(self->lastrowid);
  647. if (!multiple && statement_type == STATEMENT_INSERT) {
  648. Py_BEGIN_ALLOW_THREADS
  649. lastrowid = sqlite3_last_insert_rowid(self->connection->db);
  650. Py_END_ALLOW_THREADS
  651. self->lastrowid = PyInt_FromLong((long)lastrowid);
  652. } else {
  653. Py_INCREF(Py_None);
  654. self->lastrowid = Py_None;
  655. }
  656. if (multiple) {
  657. rc = pysqlite_statement_reset(self->statement);
  658. }
  659. Py_XDECREF(parameters);
  660. }
  661. error:
  662. /* just to be sure (implicit ROLLBACKs with ON CONFLICT ROLLBACK/OR
  663. * ROLLBACK could have happened */
  664. #ifdef SQLITE_VERSION_NUMBER
  665. #if SQLITE_VERSION_NUMBER >= 3002002
  666. if (self->connection && self->connection->db)
  667. self->connection->inTransaction = !sqlite3_get_autocommit(self->connection->db);
  668. #endif
  669. #endif
  670. Py_XDECREF(operation_bytestr);
  671. Py_XDECREF(parameters);
  672. Py_XDECREF(parameters_iter);
  673. Py_XDECREF(parameters_list);
  674. self->locked = 0;
  675. if (PyErr_Occurred()) {
  676. self->rowcount = -1L;
  677. return NULL;
  678. } else {
  679. Py_INCREF(self);
  680. return (PyObject*)self;
  681. }
  682. }
  683. PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args)
  684. {
  685. return _pysqlite_query_execute(self, 0, args);
  686. }
  687. PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args)
  688. {
  689. return _pysqlite_query_execute(self, 1, args);
  690. }
  691. PyObject* pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args)
  692. {
  693. PyObject* script_obj;
  694. PyObject* script_str = NULL;
  695. const char* script_cstr;
  696. sqlite3_stmt* statement;
  697. int rc;
  698. PyObject* result;
  699. if (!PyArg_ParseTuple(args, "O", &script_obj)) {
  700. return NULL;
  701. }
  702. if (!check_cursor(self)) {
  703. return NULL;
  704. }
  705. self->reset = 0;
  706. if (PyString_Check(script_obj)) {
  707. script_cstr = PyString_AsString(script_obj);
  708. } else if (PyUnicode_Check(script_obj)) {
  709. script_str = PyUnicode_AsUTF8String(script_obj);
  710. if (!script_str) {
  711. return NULL;
  712. }
  713. script_cstr = PyString_AsString(script_str);
  714. } else {
  715. PyErr_SetString(PyExc_ValueError, "script argument must be unicode or string.");
  716. return NULL;
  717. }
  718. /* commit first */
  719. result = pysqlite_connection_commit(self->connection, NULL);
  720. if (!result) {
  721. goto error;
  722. }
  723. Py_DECREF(result);
  724. while (1) {
  725. Py_BEGIN_ALLOW_THREADS
  726. rc = sqlite3_prepare(self->connection->db,
  727. script_cstr,
  728. -1,
  729. &statement,
  730. &script_cstr);
  731. Py_END_ALLOW_THREADS
  732. if (rc != SQLITE_OK) {
  733. _pysqlite_seterror(self->connection->db, NULL);
  734. goto error;
  735. }
  736. /* execute statement, and ignore results of SELECT statements */
  737. rc = SQLITE_ROW;
  738. while (rc == SQLITE_ROW) {
  739. rc = pysqlite_step(statement, self->connection);
  740. /* TODO: we probably need more error handling here */
  741. }
  742. if (rc != SQLITE_DONE) {
  743. (void)sqlite3_finalize(statement);
  744. _pysqlite_seterror(self->connection->db, NULL);
  745. goto error;
  746. }
  747. rc = sqlite3_finalize(statement);
  748. if (rc != SQLITE_OK) {
  749. _pysqlite_seterror(self->connection->db, NULL);
  750. goto error;
  751. }
  752. if (*script_cstr == (char)0) {
  753. break;
  754. }
  755. }
  756. error:
  757. Py_XDECREF(script_str);
  758. if (PyErr_Occurred()) {
  759. return NULL;
  760. } else {
  761. Py_INCREF(self);
  762. return (PyObject*)self;
  763. }
  764. }
  765. PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self)
  766. {
  767. Py_INCREF(self);
  768. return (PyObject*)self;
  769. }
  770. PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self)
  771. {
  772. PyObject* next_row_tuple;
  773. PyObject* next_row;
  774. int rc;
  775. if (!check_cursor(self)) {
  776. return NULL;
  777. }
  778. if (self->reset) {
  779. PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
  780. return NULL;
  781. }
  782. if (!self->next_row) {
  783. if (self->statement) {
  784. (void)pysqlite_statement_reset(self->statement);
  785. Py_DECREF(self->statement);
  786. self->statement = NULL;
  787. }
  788. return NULL;
  789. }
  790. next_row_tuple = self->next_row;
  791. self->next_row = NULL;
  792. if (self->row_factory != Py_None) {
  793. next_row = PyObject_CallFunction(self->row_factory, "OO", self, next_row_tuple);
  794. Py_DECREF(next_row_tuple);
  795. } else {
  796. next_row = next_row_tuple;
  797. }
  798. if (self->statement) {
  799. rc = pysqlite_step(self->statement->st, self->connection);
  800. if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
  801. (void)pysqlite_statement_reset(self->statement);
  802. Py_DECREF(next_row);
  803. _pysqlite_seterror(self->connection->db, NULL);
  804. return NULL;
  805. }
  806. if (rc == SQLITE_ROW) {
  807. self->next_row = _pysqlite_fetch_one_row(self);
  808. }
  809. }
  810. return next_row;
  811. }
  812. PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args)
  813. {
  814. PyObject* row;
  815. row = pysqlite_cursor_iternext(self);
  816. if (!row && !PyErr_Occurred()) {
  817. Py_INCREF(Py_None);
  818. return Py_None;
  819. }
  820. return row;
  821. }
  822. PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
  823. {
  824. static char *kwlist[] = {"size", NULL, NULL};
  825. PyObject* row;
  826. PyObject* list;
  827. int maxrows = self->arraysize;
  828. int counter = 0;
  829. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:fetchmany", kwlist, &maxrows)) {
  830. return NULL;
  831. }
  832. list = PyList_New(0);
  833. if (!list) {
  834. return NULL;
  835. }
  836. /* just make sure we enter the loop */
  837. row = Py_None;
  838. while (row) {
  839. row = pysqlite_cursor_iternext(self);
  840. if (row) {
  841. PyList_Append(list, row);
  842. Py_DECREF(row);
  843. } else {
  844. break;
  845. }
  846. if (++counter == maxrows) {
  847. break;
  848. }
  849. }
  850. if (PyErr_Occurred()) {
  851. Py_DECREF(list);
  852. return NULL;
  853. } else {
  854. return list;
  855. }
  856. }
  857. PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args)
  858. {
  859. PyObject* row;
  860. PyObject* list;
  861. list = PyList_New(0);
  862. if (!list) {
  863. return NULL;
  864. }
  865. /* just make sure we enter the loop */
  866. row = (PyObject*)Py_None;
  867. while (row) {
  868. row = pysqlite_cursor_iternext(self);
  869. if (row) {
  870. PyList_Append(list, row);
  871. Py_DECREF(row);
  872. }
  873. }
  874. if (PyErr_Occurred()) {
  875. Py_DECREF(list);
  876. return NULL;
  877. } else {
  878. return list;
  879. }
  880. }
  881. PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args)
  882. {
  883. /* don't care, return None */
  884. Py_INCREF(Py_None);
  885. return Py_None;
  886. }
  887. PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args)
  888. {
  889. if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
  890. return NULL;
  891. }
  892. if (self->statement) {
  893. (void)pysqlite_statement_reset(self->statement);
  894. Py_CLEAR(self->statement);
  895. }
  896. self->closed = 1;
  897. Py_INCREF(Py_None);
  898. return Py_None;
  899. }
  900. static PyMethodDef cursor_methods[] = {
  901. {"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS,
  902. PyDoc_STR("Executes a SQL statement.")},
  903. {"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS,
  904. PyDoc_STR("Repeatedly executes a SQL statement.")},
  905. {"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS,
  906. PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
  907. {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS,
  908. PyDoc_STR("Fetches one row from the resultset.")},
  909. {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS|METH_KEYWORDS,
  910. PyDoc_STR("Fetches several rows from the resultset.")},
  911. {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS,
  912. PyDoc_STR("Fetches all rows from the resultset.")},
  913. {"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS,
  914. PyDoc_STR("Closes the cursor.")},
  915. {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
  916. PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
  917. {"setoutputsize", (PyCFunction)pysqlite_noop, METH_VARARGS,
  918. PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
  919. {NULL, NULL}
  920. };
  921. static struct PyMemberDef cursor_members[] =
  922. {
  923. {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), RO},
  924. {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), RO},
  925. {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
  926. {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), RO},
  927. {"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), RO},
  928. {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
  929. {NULL}
  930. };
  931. static char cursor_doc[] =
  932. PyDoc_STR("SQLite database cursor class.");
  933. PyTypeObject pysqlite_CursorType = {
  934. PyVarObject_HEAD_INIT(NULL, 0)
  935. MODULE_NAME ".Cursor", /* tp_name */
  936. sizeof(pysqlite_Cursor), /* tp_basicsize */
  937. 0, /* tp_itemsize */
  938. (destructor)pysqlite_cursor_dealloc, /* tp_dealloc */
  939. 0, /* tp_print */
  940. 0, /* tp_getattr */
  941. 0, /* tp_setattr */
  942. 0, /* tp_compare */
  943. 0, /* tp_repr */
  944. 0, /* tp_as_number */
  945. 0, /* tp_as_sequence */
  946. 0, /* tp_as_mapping */
  947. 0, /* tp_hash */
  948. 0, /* tp_call */
  949. 0, /* tp_str */
  950. 0, /* tp_getattro */
  951. 0, /* tp_setattro */
  952. 0, /* tp_as_buffer */
  953. Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_ITER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
  954. cursor_doc, /* tp_doc */
  955. 0, /* tp_traverse */
  956. 0, /* tp_clear */
  957. 0, /* tp_richcompare */
  958. offsetof(pysqlite_Cursor, in_weakreflist), /* tp_weaklistoffset */
  959. (getiterfunc)pysqlite_cursor_getiter, /* tp_iter */
  960. (iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */
  961. cursor_methods, /* tp_methods */
  962. cursor_members, /* tp_members */
  963. 0, /* tp_getset */
  964. 0, /* tp_base */
  965. 0, /* tp_dict */
  966. 0, /* tp_descr_get */
  967. 0, /* tp_descr_set */
  968. 0, /* tp_dictoffset */
  969. (initproc)pysqlite_cursor_init, /* tp_init */
  970. 0, /* tp_alloc */
  971. 0, /* tp_new */
  972. 0 /* tp_free */
  973. };
  974. extern int pysqlite_cursor_setup_types(void)
  975. {
  976. pysqlite_CursorType.tp_new = PyType_GenericNew;
  977. return PyType_Ready(&pysqlite_CursorType);
  978. }