PageRenderTime 56ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/desktop/core/ext-py/MySQL-python-1.2.3c1/_mysql.c

https://github.com/jcrobak/hue
C | 1893 lines | 1728 code | 128 blank | 37 comment | 221 complexity | 9b0aa108cd28ac57e61f900e9e6ebf4c MD5 | raw file
  1. /*
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; either version 2, or (at your option)
  5. any later version. Alternatively, you may use the original license
  6. reproduced below.
  7. Copyright 1999 by Comstar.net, Inc., Atlanta, GA, US.
  8. All Rights Reserved
  9. Permission to use, copy, modify, and distribute this software and its
  10. documentation for any purpose and without fee is hereby granted,
  11. provided that the above copyright notice appear in all copies and that
  12. both that copyright notice and this permission notice appear in
  13. supporting documentation, and that the name of Comstar.net, Inc.
  14. or COMSTAR not be used in advertising or publicity pertaining to
  15. distribution of the software without specific, written prior permission.
  16. COMSTAR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  17. INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
  18. EVENT SHALL COMSTAR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  19. CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  20. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  21. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  22. PERFORMANCE OF THIS SOFTWARE.
  23. */
  24. #include "pymemcompat.h"
  25. #include "structmember.h"
  26. #if defined(MS_WINDOWS)
  27. #include <winsock2.h>
  28. #include <windows.h>
  29. #include <config-win.h>
  30. #else
  31. #include "my_config.h"
  32. #endif
  33. #include "mysql.h"
  34. #include "mysqld_error.h"
  35. #include "errmsg.h"
  36. #if PY_VERSION_HEX < 0x02020000
  37. # define MyTuple_Resize(t,n,d) _PyTuple_Resize(t, n, d)
  38. # define MyMember(a,b,c,d,e) {a,b,c,d}
  39. # define MyMemberlist(x) struct memberlist x
  40. # define MyAlloc(s,t) PyObject_New(s,&t)
  41. # define MyFree(o) PyObject_Del(o)
  42. #else
  43. # define MyTuple_Resize(t,n,d) _PyTuple_Resize(t, n)
  44. # define MyMember(a,b,c,d,e) {a,b,c,d,e}
  45. # define MyMemberlist(x) struct PyMemberDef x
  46. # define MyAlloc(s,t) (s *) t.tp_alloc(&t,0)
  47. # define MyFree(ob) ob->ob_type->tp_free((PyObject *)ob)
  48. #endif
  49. #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
  50. typedef int Py_ssize_t;
  51. #define PY_SSIZE_T_MAX INT_MAX
  52. #define PY_SSIZE_T_MIN INT_MIN
  53. #endif
  54. static PyObject *_mysql_MySQLError;
  55. static PyObject *_mysql_Warning;
  56. static PyObject *_mysql_Error;
  57. static PyObject *_mysql_DatabaseError;
  58. static PyObject *_mysql_InterfaceError;
  59. static PyObject *_mysql_DataError;
  60. static PyObject *_mysql_OperationalError;
  61. static PyObject *_mysql_IntegrityError;
  62. static PyObject *_mysql_InternalError;
  63. static PyObject *_mysql_ProgrammingError;
  64. static PyObject *_mysql_NotSupportedError;
  65. typedef struct {
  66. PyObject_HEAD
  67. MYSQL connection;
  68. int open;
  69. PyObject *converter;
  70. } _mysql_ConnectionObject;
  71. #define check_connection(c) if (!(c->open)) return _mysql_Exception(c)
  72. #define result_connection(r) ((_mysql_ConnectionObject *)r->conn)
  73. #define check_result_connection(r) check_connection(result_connection(r))
  74. extern PyTypeObject _mysql_ConnectionObject_Type;
  75. typedef struct {
  76. PyObject_HEAD
  77. PyObject *conn;
  78. MYSQL_RES *result;
  79. int nfields;
  80. int use;
  81. PyObject *converter;
  82. } _mysql_ResultObject;
  83. extern PyTypeObject _mysql_ResultObject_Type;
  84. static int _mysql_server_init_done = 0;
  85. #if MYSQL_VERSION_ID >= 40000
  86. #define check_server_init(x) if (!_mysql_server_init_done) { if (mysql_server_init(0, NULL, NULL)) { _mysql_Exception(NULL); return x; } else { _mysql_server_init_done = 1;} }
  87. #else
  88. #define check_server_init(x) if (!_mysql_server_init_done) _mysql_server_init_done = 1
  89. #endif
  90. PyObject *
  91. _mysql_Exception(_mysql_ConnectionObject *c)
  92. {
  93. PyObject *t, *e;
  94. int merr;
  95. if (!(t = PyTuple_New(2))) return NULL;
  96. if (!_mysql_server_init_done) {
  97. e = _mysql_InternalError;
  98. PyTuple_SET_ITEM(t, 0, PyInt_FromLong(-1L));
  99. PyTuple_SET_ITEM(t, 1, PyString_FromString("server not initialized"));
  100. PyErr_SetObject(e, t);
  101. Py_DECREF(t);
  102. return NULL;
  103. }
  104. merr = mysql_errno(&(c->connection));
  105. if (!merr)
  106. e = _mysql_InterfaceError;
  107. else if (merr > CR_MAX_ERROR) {
  108. PyTuple_SET_ITEM(t, 0, PyInt_FromLong(-1L));
  109. PyTuple_SET_ITEM(t, 1, PyString_FromString("error totally whack"));
  110. PyErr_SetObject(_mysql_InterfaceError, t);
  111. Py_DECREF(t);
  112. return NULL;
  113. }
  114. else switch (merr) {
  115. case CR_COMMANDS_OUT_OF_SYNC:
  116. case ER_DB_CREATE_EXISTS:
  117. case ER_SYNTAX_ERROR:
  118. case ER_PARSE_ERROR:
  119. case ER_NO_SUCH_TABLE:
  120. case ER_WRONG_DB_NAME:
  121. case ER_WRONG_TABLE_NAME:
  122. case ER_FIELD_SPECIFIED_TWICE:
  123. case ER_INVALID_GROUP_FUNC_USE:
  124. case ER_UNSUPPORTED_EXTENSION:
  125. case ER_TABLE_MUST_HAVE_COLUMNS:
  126. #ifdef ER_CANT_DO_THIS_DURING_AN_TRANSACTION
  127. case ER_CANT_DO_THIS_DURING_AN_TRANSACTION:
  128. #endif
  129. e = _mysql_ProgrammingError;
  130. break;
  131. #ifdef WARN_DATA_TRUNCATED
  132. case WARN_DATA_TRUNCATED:
  133. #ifdef WARN_NULL_TO_NOTNULL
  134. case WARN_NULL_TO_NOTNULL:
  135. #endif
  136. #ifdef ER_WARN_DATA_OUT_OF_RANGE
  137. case ER_WARN_DATA_OUT_OF_RANGE:
  138. #endif
  139. #ifdef ER_NO_DEFAULT
  140. case ER_NO_DEFAULT:
  141. #endif
  142. #ifdef ER_PRIMARY_CANT_HAVE_NULL
  143. case ER_PRIMARY_CANT_HAVE_NULL:
  144. #endif
  145. #ifdef ER_DATA_TOO_LONG
  146. case ER_DATA_TOO_LONG:
  147. #endif
  148. #ifdef ER_DATETIME_FUNCTION_OVERFLOW
  149. case ER_DATETIME_FUNCTION_OVERFLOW:
  150. #endif
  151. e = _mysql_DataError;
  152. break;
  153. #endif
  154. case ER_DUP_ENTRY:
  155. #ifdef ER_DUP_UNIQUE
  156. case ER_DUP_UNIQUE:
  157. #endif
  158. #ifdef ER_NO_REFERENCED_ROW
  159. case ER_NO_REFERENCED_ROW:
  160. #endif
  161. #ifdef ER_NO_REFERENCED_ROW_2
  162. case ER_NO_REFERENCED_ROW_2:
  163. #endif
  164. #ifdef ER_ROW_IS_REFERENCED
  165. case ER_ROW_IS_REFERENCED:
  166. #endif
  167. #ifdef ER_ROW_IS_REFERENCED_2
  168. case ER_ROW_IS_REFERENCED_2:
  169. #endif
  170. #ifdef ER_CANNOT_ADD_FOREIGN
  171. case ER_CANNOT_ADD_FOREIGN:
  172. #endif
  173. e = _mysql_IntegrityError;
  174. break;
  175. #ifdef ER_WARNING_NOT_COMPLETE_ROLLBACK
  176. case ER_WARNING_NOT_COMPLETE_ROLLBACK:
  177. #endif
  178. #ifdef ER_NOT_SUPPORTED_YET
  179. case ER_NOT_SUPPORTED_YET:
  180. #endif
  181. #ifdef ER_FEATURE_DISABLED
  182. case ER_FEATURE_DISABLED:
  183. #endif
  184. #ifdef ER_UNKNOWN_STORAGE_ENGINE
  185. case ER_UNKNOWN_STORAGE_ENGINE:
  186. #endif
  187. e = _mysql_NotSupportedError;
  188. break;
  189. default:
  190. if (merr < 1000)
  191. e = _mysql_InternalError;
  192. else
  193. e = _mysql_OperationalError;
  194. break;
  195. }
  196. PyTuple_SET_ITEM(t, 0, PyInt_FromLong((long)merr));
  197. PyTuple_SET_ITEM(t, 1, PyString_FromString(mysql_error(&(c->connection))));
  198. PyErr_SetObject(e, t);
  199. Py_DECREF(t);
  200. return NULL;
  201. }
  202. static char _mysql_server_init__doc__[] =
  203. "Initialize embedded server. If this client is not linked against\n\
  204. the embedded server library, this function does nothing.\n\
  205. \n\
  206. args -- sequence of command-line arguments\n\
  207. groups -- sequence of groups to use in defaults files\n\
  208. ";
  209. static PyObject *_mysql_server_init(
  210. PyObject *self,
  211. PyObject *args,
  212. PyObject *kwargs) {
  213. static char *kwlist[] = {"args", "groups", NULL};
  214. char **cmd_args_c=NULL, **groups_c=NULL, *s;
  215. int cmd_argc=0, i, groupc;
  216. PyObject *cmd_args=NULL, *groups=NULL, *ret=NULL, *item;
  217. if (_mysql_server_init_done) {
  218. PyErr_SetString(_mysql_ProgrammingError,
  219. "already initialized");
  220. return NULL;
  221. }
  222. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", kwlist,
  223. &cmd_args, &groups))
  224. return NULL;
  225. #if MYSQL_VERSION_ID >= 40000
  226. if (cmd_args) {
  227. if (!PySequence_Check(cmd_args)) {
  228. PyErr_SetString(PyExc_TypeError,
  229. "args must be a sequence");
  230. goto finish;
  231. }
  232. cmd_argc = PySequence_Size(cmd_args);
  233. if (cmd_argc == -1) {
  234. PyErr_SetString(PyExc_TypeError,
  235. "args could not be sized");
  236. goto finish;
  237. }
  238. cmd_args_c = (char **) PyMem_Malloc(cmd_argc*sizeof(char *));
  239. for (i=0; i< cmd_argc; i++) {
  240. item = PySequence_GetItem(cmd_args, i);
  241. s = PyString_AsString(item);
  242. Py_DECREF(item);
  243. if (!s) {
  244. PyErr_SetString(PyExc_TypeError,
  245. "args must contain strings");
  246. goto finish;
  247. }
  248. cmd_args_c[i] = s;
  249. }
  250. }
  251. if (groups) {
  252. if (!PySequence_Check(groups)) {
  253. PyErr_SetString(PyExc_TypeError,
  254. "groups must be a sequence");
  255. goto finish;
  256. }
  257. groupc = PySequence_Size(groups);
  258. if (groupc == -1) {
  259. PyErr_SetString(PyExc_TypeError,
  260. "groups could not be sized");
  261. goto finish;
  262. }
  263. groups_c = (char **) PyMem_Malloc((1+groupc)*sizeof(char *));
  264. for (i=0; i< groupc; i++) {
  265. item = PySequence_GetItem(groups, i);
  266. s = PyString_AsString(item);
  267. Py_DECREF(item);
  268. if (!s) {
  269. PyErr_SetString(PyExc_TypeError,
  270. "groups must contain strings");
  271. goto finish;
  272. }
  273. groups_c[i] = s;
  274. }
  275. groups_c[groupc] = (char *)NULL;
  276. }
  277. /* even though this may block, don't give up the interpreter lock
  278. so that the server can't be initialized multiple times. */
  279. if (mysql_server_init(cmd_argc, cmd_args_c, groups_c)) {
  280. _mysql_Exception(NULL);
  281. goto finish;
  282. }
  283. #endif
  284. ret = Py_None;
  285. Py_INCREF(Py_None);
  286. _mysql_server_init_done = 1;
  287. finish:
  288. PyMem_Free(groups_c);
  289. PyMem_Free(cmd_args_c);
  290. return ret;
  291. }
  292. static char _mysql_server_end__doc__[] =
  293. "Shut down embedded server. If not using an embedded server, this\n\
  294. does nothing.";
  295. static PyObject *_mysql_server_end(
  296. PyObject *self,
  297. PyObject *args) {
  298. if (_mysql_server_init_done) {
  299. #if MYSQL_VERSION_ID >= 40000
  300. mysql_server_end();
  301. #endif
  302. _mysql_server_init_done = 0;
  303. Py_INCREF(Py_None);
  304. return Py_None;
  305. }
  306. return _mysql_Exception(NULL);
  307. }
  308. #if MYSQL_VERSION_ID >= 32314
  309. static char _mysql_thread_safe__doc__[] =
  310. "Indicates whether the client is compiled as thread-safe.";
  311. static PyObject *_mysql_thread_safe(
  312. PyObject *self,
  313. PyObject *args) {
  314. PyObject *flag;
  315. if (!PyArg_ParseTuple(args, "")) return NULL;
  316. check_server_init(NULL);
  317. if (!(flag=PyInt_FromLong((long)mysql_thread_safe()))) return NULL;
  318. return flag;
  319. }
  320. #endif
  321. static char _mysql_ResultObject__doc__[] =
  322. "result(connection, use=0, converter={}) -- Result set from a query.\n\
  323. \n\
  324. Creating instances of this class directly is an excellent way to\n\
  325. shoot yourself in the foot. If using _mysql.connection directly,\n\
  326. use connection.store_result() or connection.use_result() instead.\n\
  327. If using MySQLdb.Connection, this is done by the cursor class.\n\
  328. Just forget you ever saw this. Forget... FOR-GET...";
  329. static int
  330. _mysql_ResultObject_Initialize(
  331. _mysql_ResultObject *self,
  332. PyObject *args,
  333. PyObject *kwargs)
  334. {
  335. static char *kwlist[] = {"connection", "use", "converter", NULL};
  336. MYSQL_RES *result;
  337. _mysql_ConnectionObject *conn=NULL;
  338. int use=0;
  339. PyObject *conv=NULL;
  340. int n, i;
  341. MYSQL_FIELD *fields;
  342. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iO", kwlist,
  343. &conn, &use, &conv))
  344. return -1;
  345. if (!conv) conv = PyDict_New();
  346. if (!conv) return -1;
  347. self->conn = (PyObject *) conn;
  348. Py_INCREF(conn);
  349. self->use = use;
  350. Py_BEGIN_ALLOW_THREADS ;
  351. if (use)
  352. result = mysql_use_result(&(conn->connection));
  353. else
  354. result = mysql_store_result(&(conn->connection));
  355. self->result = result;
  356. Py_END_ALLOW_THREADS ;
  357. if (!result) {
  358. self->converter = PyTuple_New(0);
  359. return 0;
  360. }
  361. n = mysql_num_fields(result);
  362. self->nfields = n;
  363. if (!(self->converter = PyTuple_New(n))) return -1;
  364. fields = mysql_fetch_fields(result);
  365. for (i=0; i<n; i++) {
  366. PyObject *tmp, *fun;
  367. tmp = PyInt_FromLong((long) fields[i].type);
  368. if (!tmp) return -1;
  369. fun = PyObject_GetItem(conv, tmp);
  370. Py_DECREF(tmp);
  371. if (!fun) {
  372. PyErr_Clear();
  373. fun = Py_None;
  374. Py_INCREF(Py_None);
  375. }
  376. if (PySequence_Check(fun)) {
  377. int j, n2=PySequence_Size(fun);
  378. PyObject *fun2=NULL;
  379. for (j=0; j<n2; j++) {
  380. PyObject *t = PySequence_GetItem(fun, j);
  381. if (!t) continue;
  382. if (!PyTuple_Check(t)) goto cleanup;
  383. if (PyTuple_GET_SIZE(t) == 2) {
  384. long mask;
  385. PyObject *pmask=NULL;
  386. pmask = PyTuple_GET_ITEM(t, 0);
  387. fun2 = PyTuple_GET_ITEM(t, 1);
  388. if (PyInt_Check(pmask)) {
  389. mask = PyInt_AS_LONG(pmask);
  390. if (mask & fields[i].flags) {
  391. Py_DECREF(t);
  392. break;
  393. }
  394. else {
  395. goto cleanup;
  396. }
  397. } else {
  398. Py_DECREF(t);
  399. break;
  400. }
  401. }
  402. cleanup:
  403. Py_DECREF(t);
  404. }
  405. if (!fun2) fun2 = Py_None;
  406. Py_INCREF(fun2);
  407. Py_DECREF(fun);
  408. fun = fun2;
  409. }
  410. PyTuple_SET_ITEM(self->converter, i, fun);
  411. }
  412. return 0;
  413. }
  414. #if PY_VERSION_HEX >= 0x02020000
  415. static int _mysql_ResultObject_traverse(
  416. _mysql_ResultObject *self,
  417. visitproc visit,
  418. void *arg)
  419. {
  420. int r;
  421. if (self->converter) {
  422. if (!(r = visit(self->converter, arg))) return r;
  423. }
  424. if (self->conn)
  425. return visit(self->conn, arg);
  426. return 0;
  427. }
  428. #endif
  429. static int _mysql_ResultObject_clear(
  430. _mysql_ResultObject *self)
  431. {
  432. Py_XDECREF(self->converter);
  433. self->converter = NULL;
  434. Py_XDECREF(self->conn);
  435. self->conn = NULL;
  436. return 0;
  437. }
  438. static int
  439. _mysql_ConnectionObject_Initialize(
  440. _mysql_ConnectionObject *self,
  441. PyObject *args,
  442. PyObject *kwargs)
  443. {
  444. MYSQL *conn = NULL;
  445. PyObject *conv = NULL;
  446. PyObject *ssl = NULL;
  447. #if HAVE_OPENSSL
  448. char *key = NULL, *cert = NULL, *ca = NULL,
  449. *capath = NULL, *cipher = NULL;
  450. #endif
  451. char *host = NULL, *user = NULL, *passwd = NULL,
  452. *db = NULL, *unix_socket = NULL;
  453. unsigned int port = 0;
  454. unsigned int client_flag = 0;
  455. static char *kwlist[] = { "host", "user", "passwd", "db", "port",
  456. "unix_socket", "conv",
  457. "connect_timeout", "compress",
  458. "named_pipe", "init_command",
  459. "read_default_file", "read_default_group",
  460. "client_flag", "ssl",
  461. "local_infile",
  462. NULL } ;
  463. int connect_timeout = 0;
  464. int compress = -1, named_pipe = -1, local_infile = -1;
  465. char *init_command=NULL,
  466. *read_default_file=NULL,
  467. *read_default_group=NULL;
  468. self->converter = NULL;
  469. self->open = 0;
  470. check_server_init(-1);
  471. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ssssisOiiisssiOi:connect",
  472. kwlist,
  473. &host, &user, &passwd, &db,
  474. &port, &unix_socket, &conv,
  475. &connect_timeout,
  476. &compress, &named_pipe,
  477. &init_command, &read_default_file,
  478. &read_default_group,
  479. &client_flag, &ssl,
  480. &local_infile /* DO NOT PATCH FOR RECONNECT, IDIOTS
  481. IF YOU DO THIS, I WILL NOT SUPPORT YOUR PACKAGES. */
  482. ))
  483. return -1;
  484. if (!conv)
  485. conv = PyDict_New();
  486. #if PY_VERSION_HEX > 0x02000100
  487. else
  488. Py_INCREF(conv);
  489. #endif
  490. if (!conv)
  491. return -1;
  492. self->converter = conv;
  493. #define _stringsuck(d,t,s) {t=PyMapping_GetItemString(s,#d);\
  494. if(t){d=PyString_AsString(t);Py_DECREF(t);}\
  495. PyErr_Clear();}
  496. if (ssl) {
  497. #if HAVE_OPENSSL
  498. PyObject *value = NULL;
  499. _stringsuck(ca, value, ssl);
  500. _stringsuck(capath, value, ssl);
  501. _stringsuck(cert, value, ssl);
  502. _stringsuck(key, value, ssl);
  503. _stringsuck(cipher, value, ssl);
  504. #else
  505. PyErr_SetString(_mysql_NotSupportedError,
  506. "client library does not have SSL support");
  507. return -1;
  508. #endif
  509. }
  510. Py_BEGIN_ALLOW_THREADS ;
  511. conn = mysql_init(&(self->connection));
  512. if (connect_timeout) {
  513. unsigned int timeout = connect_timeout;
  514. mysql_options(&(self->connection), MYSQL_OPT_CONNECT_TIMEOUT,
  515. (char *)&timeout);
  516. }
  517. if (compress != -1) {
  518. mysql_options(&(self->connection), MYSQL_OPT_COMPRESS, 0);
  519. client_flag |= CLIENT_COMPRESS;
  520. }
  521. if (named_pipe != -1)
  522. mysql_options(&(self->connection), MYSQL_OPT_NAMED_PIPE, 0);
  523. if (init_command != NULL)
  524. mysql_options(&(self->connection), MYSQL_INIT_COMMAND, init_command);
  525. if (read_default_file != NULL)
  526. mysql_options(&(self->connection), MYSQL_READ_DEFAULT_FILE, read_default_file);
  527. if (read_default_group != NULL)
  528. mysql_options(&(self->connection), MYSQL_READ_DEFAULT_GROUP, read_default_group);
  529. if (local_infile != -1)
  530. mysql_options(&(self->connection), MYSQL_OPT_LOCAL_INFILE, (char *) &local_infile);
  531. #if HAVE_OPENSSL
  532. if (ssl)
  533. mysql_ssl_set(&(self->connection),
  534. key, cert, ca, capath, cipher);
  535. #endif
  536. conn = mysql_real_connect(&(self->connection), host, user, passwd, db,
  537. port, unix_socket, client_flag);
  538. Py_END_ALLOW_THREADS ;
  539. if (!conn) {
  540. _mysql_Exception(self);
  541. return -1;
  542. }
  543. /*
  544. PyType_GenericAlloc() automatically sets up GC allocation and
  545. tracking for GC objects, at least in 2.2.1, so it does not need to
  546. be done here. tp_dealloc still needs to call PyObject_GC_UnTrack(),
  547. however.
  548. */
  549. self->open = 1;
  550. return 0;
  551. }
  552. static char _mysql_connect__doc__[] =
  553. "Returns a MYSQL connection object. Exclusive use of\n\
  554. keyword parameters strongly recommended. Consult the\n\
  555. MySQL C API documentation for more details.\n\
  556. \n\
  557. host\n\
  558. string, host to connect\n\
  559. \n\
  560. user\n\
  561. string, user to connect as\n\
  562. \n\
  563. passwd\n\
  564. string, password to use\n\
  565. \n\
  566. db\n\
  567. string, database to use\n\
  568. \n\
  569. port\n\
  570. integer, TCP/IP port to connect to\n\
  571. \n\
  572. unix_socket\n\
  573. string, location of unix_socket (UNIX-ish only)\n\
  574. \n\
  575. conv\n\
  576. mapping, maps MySQL FIELD_TYPE.* to Python functions which\n\
  577. convert a string to the appropriate Python type\n\
  578. \n\
  579. connect_timeout\n\
  580. number of seconds to wait before the connection\n\
  581. attempt fails.\n\
  582. \n\
  583. compress\n\
  584. if set, gzip compression is enabled\n\
  585. \n\
  586. named_pipe\n\
  587. if set, connect to server via named pipe (Windows only)\n\
  588. \n\
  589. init_command\n\
  590. command which is run once the connection is created\n\
  591. \n\
  592. read_default_file\n\
  593. see the MySQL documentation for mysql_options()\n\
  594. \n\
  595. read_default_group\n\
  596. see the MySQL documentation for mysql_options()\n\
  597. \n\
  598. client_flag\n\
  599. client flags from MySQLdb.constants.CLIENT\n\
  600. \n\
  601. load_infile\n\
  602. int, non-zero enables LOAD LOCAL INFILE, zero disables\n\
  603. \n\
  604. ";
  605. static PyObject *
  606. _mysql_connect(
  607. PyObject *self,
  608. PyObject *args,
  609. PyObject *kwargs)
  610. {
  611. _mysql_ConnectionObject *c=NULL;
  612. c = MyAlloc(_mysql_ConnectionObject, _mysql_ConnectionObject_Type);
  613. if (c == NULL) return NULL;
  614. if (_mysql_ConnectionObject_Initialize(c, args, kwargs)) {
  615. Py_DECREF(c);
  616. c = NULL;
  617. }
  618. return (PyObject *) c;
  619. }
  620. #if PY_VERSION_HEX >= 0x02020000
  621. static int _mysql_ConnectionObject_traverse(
  622. _mysql_ConnectionObject *self,
  623. visitproc visit,
  624. void *arg)
  625. {
  626. if (self->converter)
  627. return visit(self->converter, arg);
  628. return 0;
  629. }
  630. #endif
  631. static int _mysql_ConnectionObject_clear(
  632. _mysql_ConnectionObject *self)
  633. {
  634. Py_XDECREF(self->converter);
  635. self->converter = NULL;
  636. return 0;
  637. }
  638. static char _mysql_ConnectionObject_close__doc__[] =
  639. "Close the connection. No further activity possible.";
  640. static PyObject *
  641. _mysql_ConnectionObject_close(
  642. _mysql_ConnectionObject *self,
  643. PyObject *args)
  644. {
  645. if (args) {
  646. if (!PyArg_ParseTuple(args, "")) return NULL;
  647. }
  648. if (self->open) {
  649. Py_BEGIN_ALLOW_THREADS
  650. mysql_close(&(self->connection));
  651. Py_END_ALLOW_THREADS
  652. self->open = 0;
  653. } else {
  654. PyErr_SetString(_mysql_ProgrammingError,
  655. "closing a closed connection");
  656. return NULL;
  657. }
  658. _mysql_ConnectionObject_clear(self);
  659. Py_INCREF(Py_None);
  660. return Py_None;
  661. }
  662. static char _mysql_ConnectionObject_affected_rows__doc__ [] =
  663. "Return number of rows affected by the last query.\n\
  664. Non-standard. Use Cursor.rowcount.\n\
  665. ";
  666. static PyObject *
  667. _mysql_ConnectionObject_affected_rows(
  668. _mysql_ConnectionObject *self,
  669. PyObject *args)
  670. {
  671. if (!PyArg_ParseTuple(args, "")) return NULL;
  672. check_connection(self);
  673. return PyLong_FromUnsignedLongLong(mysql_affected_rows(&(self->connection)));
  674. }
  675. static char _mysql_debug__doc__[] =
  676. "Does a DBUG_PUSH with the given string.\n\
  677. mysql_debug() uses the Fred Fish debug library.\n\
  678. To use this function, you must compile the client library to\n\
  679. support debugging.\n\
  680. ";
  681. static PyObject *
  682. _mysql_debug(
  683. PyObject *self,
  684. PyObject *args)
  685. {
  686. char *debug;
  687. if (!PyArg_ParseTuple(args, "s", &debug)) return NULL;
  688. mysql_debug(debug);
  689. Py_INCREF(Py_None);
  690. return Py_None;
  691. }
  692. static char _mysql_ConnectionObject_dump_debug_info__doc__[] =
  693. "Instructs the server to write some debug information to the\n\
  694. log. The connected user must have the process privilege for\n\
  695. this to work. Non-standard.\n\
  696. ";
  697. static PyObject *
  698. _mysql_ConnectionObject_dump_debug_info(
  699. _mysql_ConnectionObject *self,
  700. PyObject *args)
  701. {
  702. int err;
  703. if (!PyArg_ParseTuple(args, "")) return NULL;
  704. check_connection(self);
  705. Py_BEGIN_ALLOW_THREADS
  706. err = mysql_dump_debug_info(&(self->connection));
  707. Py_END_ALLOW_THREADS
  708. if (err) return _mysql_Exception(self);
  709. Py_INCREF(Py_None);
  710. return Py_None;
  711. }
  712. static char _mysql_ConnectionObject_autocommit__doc__[] =
  713. "Set the autocommit mode. True values enable; False value disable.\n\
  714. ";
  715. static PyObject *
  716. _mysql_ConnectionObject_autocommit(
  717. _mysql_ConnectionObject *self,
  718. PyObject *args)
  719. {
  720. int flag, err;
  721. if (!PyArg_ParseTuple(args, "i", &flag)) return NULL;
  722. Py_BEGIN_ALLOW_THREADS
  723. #if MYSQL_VERSION_ID >= 40100
  724. err = mysql_autocommit(&(self->connection), flag);
  725. #else
  726. {
  727. char query[256];
  728. snprintf(query, 256, "SET AUTOCOMMIT=%d", flag);
  729. err = mysql_query(&(self->connection), query);
  730. }
  731. #endif
  732. Py_END_ALLOW_THREADS
  733. if (err) return _mysql_Exception(self);
  734. Py_INCREF(Py_None);
  735. return Py_None;
  736. }
  737. static char _mysql_ConnectionObject_commit__doc__[] =
  738. "Commits the current transaction\n\
  739. ";
  740. static PyObject *
  741. _mysql_ConnectionObject_commit(
  742. _mysql_ConnectionObject *self,
  743. PyObject *args)
  744. {
  745. int err;
  746. if (!PyArg_ParseTuple(args, "")) return NULL;
  747. Py_BEGIN_ALLOW_THREADS
  748. #if MYSQL_VERSION_ID >= 40100
  749. err = mysql_commit(&(self->connection));
  750. #else
  751. err = mysql_query(&(self->connection), "COMMIT");
  752. #endif
  753. Py_END_ALLOW_THREADS
  754. if (err) return _mysql_Exception(self);
  755. Py_INCREF(Py_None);
  756. return Py_None;
  757. }
  758. static char _mysql_ConnectionObject_rollback__doc__[] =
  759. "Rolls backs the current transaction\n\
  760. ";
  761. static PyObject *
  762. _mysql_ConnectionObject_rollback(
  763. _mysql_ConnectionObject *self,
  764. PyObject *args)
  765. {
  766. int err;
  767. if (!PyArg_ParseTuple(args, "")) return NULL;
  768. Py_BEGIN_ALLOW_THREADS
  769. #if MYSQL_VERSION_ID >= 40100
  770. err = mysql_rollback(&(self->connection));
  771. #else
  772. err = mysql_query(&(self->connection), "ROLLBACK");
  773. #endif
  774. Py_END_ALLOW_THREADS
  775. if (err) return _mysql_Exception(self);
  776. Py_INCREF(Py_None);
  777. return Py_None;
  778. }
  779. static char _mysql_ConnectionObject_next_result__doc__[] =
  780. "If more query results exist, next_result() reads the next query\n\
  781. results and returns the status back to application.\n\
  782. \n\
  783. After calling next_result() the state of the connection is as if\n\
  784. you had called query() for the next query. This means that you can\n\
  785. now call store_result(), warning_count(), affected_rows()\n\
  786. , and so forth. \n\
  787. \n\
  788. Returns 0 if there are more results; -1 if there are no more results\n\
  789. \n\
  790. Non-standard.\n\
  791. ";
  792. static PyObject *
  793. _mysql_ConnectionObject_next_result(
  794. _mysql_ConnectionObject *self,
  795. PyObject *args)
  796. {
  797. int err;
  798. if (!PyArg_ParseTuple(args, "")) return NULL;
  799. Py_BEGIN_ALLOW_THREADS
  800. #if MYSQL_VERSION_ID >= 40100
  801. err = mysql_next_result(&(self->connection));
  802. #else
  803. err = -1;
  804. #endif
  805. Py_END_ALLOW_THREADS
  806. if (err > 0) return _mysql_Exception(self);
  807. return PyInt_FromLong(err);
  808. }
  809. #if MYSQL_VERSION_ID >= 40100
  810. static char _mysql_ConnectionObject_set_server_option__doc__[] =
  811. "set_server_option(option) -- Enables or disables an option\n\
  812. for the connection.\n\
  813. \n\
  814. Non-standard.\n\
  815. ";
  816. static PyObject *
  817. _mysql_ConnectionObject_set_server_option(
  818. _mysql_ConnectionObject *self,
  819. PyObject *args)
  820. {
  821. int err, flags=0;
  822. if (!PyArg_ParseTuple(args, "i", &flags))
  823. return NULL;
  824. Py_BEGIN_ALLOW_THREADS
  825. err = mysql_set_server_option(&(self->connection), flags);
  826. Py_END_ALLOW_THREADS
  827. if (err) return _mysql_Exception(self);
  828. return PyInt_FromLong(err);
  829. }
  830. static char _mysql_ConnectionObject_sqlstate__doc__[] =
  831. "Returns a string containing the SQLSTATE error code\n\
  832. for the last error. The error code consists of five characters.\n\
  833. '00000' means \"no error.\" The values are specified by ANSI SQL\n\
  834. and ODBC. For a list of possible values, see section 23\n\
  835. Error Handling in MySQL in the MySQL Manual.\n\
  836. \n\
  837. Note that not all MySQL errors are yet mapped to SQLSTATE's.\n\
  838. The value 'HY000' (general error) is used for unmapped errors.\n\
  839. \n\
  840. Non-standard.\n\
  841. ";
  842. static PyObject *
  843. _mysql_ConnectionObject_sqlstate(
  844. _mysql_ConnectionObject *self,
  845. PyObject *args)
  846. {
  847. if (!PyArg_ParseTuple(args, "")) return NULL;
  848. return PyString_FromString(mysql_sqlstate(&(self->connection)));
  849. }
  850. static char _mysql_ConnectionObject_warning_count__doc__[] =
  851. "Returns the number of warnings generated during execution\n\
  852. of the previous SQL statement.\n\
  853. \n\
  854. Non-standard.\n\
  855. ";
  856. static PyObject *
  857. _mysql_ConnectionObject_warning_count(
  858. _mysql_ConnectionObject *self,
  859. PyObject *args)
  860. {
  861. if (!PyArg_ParseTuple(args, "")) return NULL;
  862. return PyInt_FromLong(mysql_warning_count(&(self->connection)));
  863. }
  864. #endif
  865. static char _mysql_ConnectionObject_errno__doc__[] =
  866. "Returns the error code for the most recently invoked API function\n\
  867. that can succeed or fail. A return value of zero means that no error\n\
  868. occurred.\n\
  869. ";
  870. static PyObject *
  871. _mysql_ConnectionObject_errno(
  872. _mysql_ConnectionObject *self,
  873. PyObject *args)
  874. {
  875. if (!PyArg_ParseTuple(args, "")) return NULL;
  876. check_connection(self);
  877. return PyInt_FromLong((long)mysql_errno(&(self->connection)));
  878. }
  879. static char _mysql_ConnectionObject_error__doc__[] =
  880. "Returns the error message for the most recently invoked API function\n\
  881. that can succeed or fail. An empty string ("") is returned if no error\n\
  882. occurred.\n\
  883. ";
  884. static PyObject *
  885. _mysql_ConnectionObject_error(
  886. _mysql_ConnectionObject *self,
  887. PyObject *args)
  888. {
  889. if (!PyArg_ParseTuple(args, "")) return NULL;
  890. check_connection(self);
  891. return PyString_FromString(mysql_error(&(self->connection)));
  892. }
  893. static char _mysql_escape_string__doc__[] =
  894. "escape_string(s) -- quote any SQL-interpreted characters in string s.\n\
  895. \n\
  896. Use connection.escape_string(s), if you use it at all.\n\
  897. _mysql.escape_string(s) cannot handle character sets. You are\n\
  898. probably better off using connection.escape(o) instead, since\n\
  899. it will escape entire sequences as well as strings.";
  900. static PyObject *
  901. _mysql_escape_string(
  902. _mysql_ConnectionObject *self,
  903. PyObject *args)
  904. {
  905. PyObject *str;
  906. char *in, *out;
  907. int len, size;
  908. if (!PyArg_ParseTuple(args, "s#:escape_string", &in, &size)) return NULL;
  909. str = PyString_FromStringAndSize((char *) NULL, size*2+1);
  910. if (!str) return PyErr_NoMemory();
  911. out = PyString_AS_STRING(str);
  912. #if MYSQL_VERSION_ID < 32321
  913. len = mysql_escape_string(out, in, size);
  914. #else
  915. check_server_init(NULL);
  916. if (self && self->open)
  917. len = mysql_real_escape_string(&(self->connection), out, in, size);
  918. else
  919. len = mysql_escape_string(out, in, size);
  920. #endif
  921. if (_PyString_Resize(&str, len) < 0) return NULL;
  922. return (str);
  923. }
  924. static char _mysql_string_literal__doc__[] =
  925. "string_literal(obj) -- converts object obj into a SQL string literal.\n\
  926. This means, any special SQL characters are escaped, and it is enclosed\n\
  927. within single quotes. In other words, it performs:\n\
  928. \n\
  929. \"'%s'\" % escape_string(str(obj))\n\
  930. \n\
  931. Use connection.string_literal(obj), if you use it at all.\n\
  932. _mysql.string_literal(obj) cannot handle character sets.";
  933. static PyObject *
  934. _mysql_string_literal(
  935. _mysql_ConnectionObject *self,
  936. PyObject *args)
  937. {
  938. PyObject *str, *s, *o, *d;
  939. char *in, *out;
  940. int len, size;
  941. if (!PyArg_ParseTuple(args, "O|O:string_literal", &o, &d)) return NULL;
  942. s = PyObject_Str(o);
  943. if (!s) return NULL;
  944. in = PyString_AsString(s);
  945. size = PyString_GET_SIZE(s);
  946. str = PyString_FromStringAndSize((char *) NULL, size*2+3);
  947. if (!str) return PyErr_NoMemory();
  948. out = PyString_AS_STRING(str);
  949. #if MYSQL_VERSION_ID < 32321
  950. len = mysql_escape_string(out+1, in, size);
  951. #else
  952. check_server_init(NULL);
  953. if (self && self->open)
  954. len = mysql_real_escape_string(&(self->connection), out+1, in, size);
  955. else
  956. len = mysql_escape_string(out+1, in, size);
  957. #endif
  958. *out = *(out+len+1) = '\'';
  959. if (_PyString_Resize(&str, len+2) < 0) return NULL;
  960. Py_DECREF(s);
  961. return (str);
  962. }
  963. static PyObject *_mysql_NULL;
  964. static PyObject *
  965. _escape_item(
  966. PyObject *item,
  967. PyObject *d)
  968. {
  969. PyObject *quoted=NULL, *itemtype, *itemconv;
  970. if (!(itemtype = PyObject_Type(item)))
  971. goto error;
  972. itemconv = PyObject_GetItem(d, itemtype);
  973. Py_DECREF(itemtype);
  974. if (!itemconv) {
  975. PyErr_Clear();
  976. itemconv = PyObject_GetItem(d,
  977. (PyObject *) &PyString_Type);
  978. }
  979. if (!itemconv) {
  980. PyErr_SetString(PyExc_TypeError,
  981. "no default type converter defined");
  982. goto error;
  983. }
  984. quoted = PyObject_CallFunction(itemconv, "OO", item, d);
  985. Py_DECREF(itemconv);
  986. error:
  987. return quoted;
  988. }
  989. static char _mysql_escape__doc__[] =
  990. "escape(obj, dict) -- escape any special characters in object obj\n\
  991. using mapping dict to provide quoting functions for each type.\n\
  992. Returns a SQL literal string.";
  993. static PyObject *
  994. _mysql_escape(
  995. PyObject *self,
  996. PyObject *args)
  997. {
  998. PyObject *o=NULL, *d=NULL;
  999. if (!PyArg_ParseTuple(args, "O|O:escape", &o, &d))
  1000. return NULL;
  1001. if (d) {
  1002. if (!PyMapping_Check(d)) {
  1003. PyErr_SetString(PyExc_TypeError,
  1004. "argument 2 must be a mapping");
  1005. return NULL;
  1006. }
  1007. return _escape_item(o, d);
  1008. } else {
  1009. if (!self) {
  1010. PyErr_SetString(PyExc_TypeError,
  1011. "argument 2 must be a mapping");
  1012. return NULL;
  1013. }
  1014. return _escape_item(o,
  1015. ((_mysql_ConnectionObject *) self)->converter);
  1016. }
  1017. }
  1018. static char _mysql_escape_sequence__doc__[] =
  1019. "escape_sequence(seq, dict) -- escape any special characters in sequence\n\
  1020. seq using mapping dict to provide quoting functions for each type.\n\
  1021. Returns a tuple of escaped items.";
  1022. static PyObject *
  1023. _mysql_escape_sequence(
  1024. PyObject *self,
  1025. PyObject *args)
  1026. {
  1027. PyObject *o=NULL, *d=NULL, *r=NULL, *item, *quoted;
  1028. int i, n;
  1029. if (!PyArg_ParseTuple(args, "OO:escape_sequence", &o, &d))
  1030. goto error;
  1031. if (!PyMapping_Check(d)) {
  1032. PyErr_SetString(PyExc_TypeError,
  1033. "argument 2 must be a mapping");
  1034. return NULL;
  1035. }
  1036. if ((n = PyObject_Length(o)) == -1) goto error;
  1037. if (!(r = PyTuple_New(n))) goto error;
  1038. for (i=0; i<n; i++) {
  1039. item = PySequence_GetItem(o, i);
  1040. if (!item) goto error;
  1041. quoted = _escape_item(item, d);
  1042. Py_DECREF(item);
  1043. if (!quoted) goto error;
  1044. PyTuple_SET_ITEM(r, i, quoted);
  1045. }
  1046. return r;
  1047. error:
  1048. Py_XDECREF(r);
  1049. return NULL;
  1050. }
  1051. static char _mysql_escape_dict__doc__[] =
  1052. "escape_sequence(d, dict) -- escape any special characters in\n\
  1053. dictionary d using mapping dict to provide quoting functions for each type.\n\
  1054. Returns a dictionary of escaped items.";
  1055. static PyObject *
  1056. _mysql_escape_dict(
  1057. PyObject *self,
  1058. PyObject *args)
  1059. {
  1060. PyObject *o=NULL, *d=NULL, *r=NULL, *item, *quoted, *pkey;
  1061. Py_ssize_t ppos = 0;
  1062. if (!PyArg_ParseTuple(args, "O!O:escape_dict", &PyDict_Type, &o, &d))
  1063. goto error;
  1064. if (!PyMapping_Check(d)) {
  1065. PyErr_SetString(PyExc_TypeError,
  1066. "argument 2 must be a mapping");
  1067. return NULL;
  1068. }
  1069. if (!(r = PyDict_New())) goto error;
  1070. while (PyDict_Next(o, &ppos, &pkey, &item)) {
  1071. quoted = _escape_item(item, d);
  1072. if (!quoted) goto error;
  1073. if (PyDict_SetItem(r, pkey, quoted)==-1) goto error;
  1074. Py_DECREF(quoted);
  1075. }
  1076. return r;
  1077. error:
  1078. Py_XDECREF(r);
  1079. return NULL;
  1080. }
  1081. static char _mysql_ResultObject_describe__doc__[] =
  1082. "Returns the sequence of 7-tuples required by the DB-API for\n\
  1083. the Cursor.description attribute.\n\
  1084. ";
  1085. static PyObject *
  1086. _mysql_ResultObject_describe(
  1087. _mysql_ResultObject *self,
  1088. PyObject *args)
  1089. {
  1090. PyObject *d;
  1091. MYSQL_FIELD *fields;
  1092. unsigned int i, n;
  1093. if (!PyArg_ParseTuple(args, "")) return NULL;
  1094. check_result_connection(self);
  1095. n = mysql_num_fields(self->result);
  1096. fields = mysql_fetch_fields(self->result);
  1097. if (!(d = PyTuple_New(n))) return NULL;
  1098. for (i=0; i<n; i++) {
  1099. PyObject *t;
  1100. t = Py_BuildValue("(siiiiii)",
  1101. fields[i].name,
  1102. (long) fields[i].type,
  1103. (long) fields[i].max_length,
  1104. (long) fields[i].length,
  1105. (long) fields[i].length,
  1106. (long) fields[i].decimals,
  1107. (long) !(IS_NOT_NULL(fields[i].flags)));
  1108. if (!t) goto error;
  1109. PyTuple_SET_ITEM(d, i, t);
  1110. }
  1111. return d;
  1112. error:
  1113. Py_XDECREF(d);
  1114. return NULL;
  1115. }
  1116. static char _mysql_ResultObject_field_flags__doc__[] =
  1117. "Returns a tuple of field flags, one for each column in the result.\n\
  1118. " ;
  1119. static PyObject *
  1120. _mysql_ResultObject_field_flags(
  1121. _mysql_ResultObject *self,
  1122. PyObject *args)
  1123. {
  1124. PyObject *d;
  1125. MYSQL_FIELD *fields;
  1126. unsigned int i, n;
  1127. if (!PyArg_ParseTuple(args, "")) return NULL;
  1128. check_result_connection(self);
  1129. n = mysql_num_fields(self->result);
  1130. fields = mysql_fetch_fields(self->result);
  1131. if (!(d = PyTuple_New(n))) return NULL;
  1132. for (i=0; i<n; i++) {
  1133. PyObject *f;
  1134. if (!(f = PyInt_FromLong((long)fields[i].flags))) goto error;
  1135. PyTuple_SET_ITEM(d, i, f);
  1136. }
  1137. return d;
  1138. error:
  1139. Py_XDECREF(d);
  1140. return NULL;
  1141. }
  1142. static PyObject *
  1143. _mysql_field_to_python(
  1144. PyObject *converter,
  1145. char *rowitem,
  1146. unsigned long length)
  1147. {
  1148. PyObject *v;
  1149. if (rowitem) {
  1150. if (converter != Py_None)
  1151. v = PyObject_CallFunction(converter,
  1152. "s#",
  1153. rowitem,
  1154. (int)length);
  1155. else
  1156. v = PyString_FromStringAndSize(rowitem,
  1157. (int)length);
  1158. if (!v)
  1159. return NULL;
  1160. } else {
  1161. Py_INCREF(Py_None);
  1162. v = Py_None;
  1163. }
  1164. return v;
  1165. }
  1166. static PyObject *
  1167. _mysql_row_to_tuple(
  1168. _mysql_ResultObject *self,
  1169. MYSQL_ROW row)
  1170. {
  1171. unsigned int n, i;
  1172. unsigned long *length;
  1173. PyObject *r, *c;
  1174. n = mysql_num_fields(self->result);
  1175. if (!(r = PyTuple_New(n))) return NULL;
  1176. length = mysql_fetch_lengths(self->result);
  1177. for (i=0; i<n; i++) {
  1178. PyObject *v;
  1179. c = PyTuple_GET_ITEM(self->converter, i);
  1180. v = _mysql_field_to_python(c, row[i], length[i]);
  1181. if (!v) goto error;
  1182. PyTuple_SET_ITEM(r, i, v);
  1183. }
  1184. return r;
  1185. error:
  1186. Py_XDECREF(r);
  1187. return NULL;
  1188. }
  1189. static PyObject *
  1190. _mysql_row_to_dict(
  1191. _mysql_ResultObject *self,
  1192. MYSQL_ROW row)
  1193. {
  1194. unsigned int n, i;
  1195. unsigned long *length;
  1196. PyObject *r, *c;
  1197. MYSQL_FIELD *fields;
  1198. n = mysql_num_fields(self->result);
  1199. if (!(r = PyDict_New())) return NULL;
  1200. length = mysql_fetch_lengths(self->result);
  1201. fields = mysql_fetch_fields(self->result);
  1202. for (i=0; i<n; i++) {
  1203. PyObject *v;
  1204. c = PyTuple_GET_ITEM(self->converter, i);
  1205. v = _mysql_field_to_python(c, row[i], length[i]);
  1206. if (!v) goto error;
  1207. if (!PyMapping_HasKeyString(r, fields[i].name)) {
  1208. PyMapping_SetItemString(r, fields[i].name, v);
  1209. } else {
  1210. int len;
  1211. char buf[256];
  1212. strncpy(buf, fields[i].table, 256);
  1213. len = strlen(buf);
  1214. strncat(buf, ".", 256-len);
  1215. len = strlen(buf);
  1216. strncat(buf, fields[i].name, 256-len);
  1217. PyMapping_SetItemString(r, buf, v);
  1218. }
  1219. Py_DECREF(v);
  1220. }
  1221. return r;
  1222. error:
  1223. Py_XDECREF(r);
  1224. return NULL;
  1225. }
  1226. static PyObject *
  1227. _mysql_row_to_dict_old(
  1228. _mysql_ResultObject *self,
  1229. MYSQL_ROW row)
  1230. {
  1231. unsigned int n, i;
  1232. unsigned long *length;
  1233. PyObject *r, *c;
  1234. MYSQL_FIELD *fields;
  1235. n = mysql_num_fields(self->result);
  1236. if (!(r = PyDict_New())) return NULL;
  1237. length = mysql_fetch_lengths(self->result);
  1238. fields = mysql_fetch_fields(self->result);
  1239. for (i=0; i<n; i++) {
  1240. PyObject *v;
  1241. c = PyTuple_GET_ITEM(self->converter, i);
  1242. v = _mysql_field_to_python(c, row[i], length[i]);
  1243. if (!v) goto error;
  1244. {
  1245. int len=0;
  1246. char buf[256]="";
  1247. if (strlen(fields[i].table)) {
  1248. strncpy(buf, fields[i].table, 256);
  1249. len = strlen(buf);
  1250. strncat(buf, ".", 256-len);
  1251. len = strlen(buf);
  1252. }
  1253. strncat(buf, fields[i].name, 256-len);
  1254. PyMapping_SetItemString(r, buf, v);
  1255. }
  1256. Py_DECREF(v);
  1257. }
  1258. return r;
  1259. error:
  1260. Py_XDECREF(r);
  1261. return NULL;
  1262. }
  1263. typedef PyObject *_PYFUNC(_mysql_ResultObject *, MYSQL_ROW);
  1264. int
  1265. _mysql__fetch_row(
  1266. _mysql_ResultObject *self,
  1267. PyObject **r,
  1268. int skiprows,
  1269. int maxrows,
  1270. _PYFUNC *convert_row)
  1271. {
  1272. unsigned int i;
  1273. MYSQL_ROW row;
  1274. for (i = skiprows; i<(skiprows+maxrows); i++) {
  1275. PyObject *v;
  1276. if (!self->use)
  1277. row = mysql_fetch_row(self->result);
  1278. else {
  1279. Py_BEGIN_ALLOW_THREADS;
  1280. row = mysql_fetch_row(self->result);
  1281. Py_END_ALLOW_THREADS;
  1282. }
  1283. if (!row && mysql_errno(&(((_mysql_ConnectionObject *)(self->conn))->connection))) {
  1284. _mysql_Exception((_mysql_ConnectionObject *)self->conn);
  1285. goto error;
  1286. }
  1287. if (!row) {
  1288. if (MyTuple_Resize(r, i, 0) == -1) goto error;
  1289. break;
  1290. }
  1291. v = convert_row(self, row);
  1292. if (!v) goto error;
  1293. PyTuple_SET_ITEM(*r, i, v);
  1294. }
  1295. return i-skiprows;
  1296. error:
  1297. return -1;
  1298. }
  1299. static char _mysql_ResultObject_fetch_row__doc__[] =
  1300. "fetch_row([maxrows, how]) -- Fetches up to maxrows as a tuple.\n\
  1301. The rows are formatted according to how:\n\
  1302. \n\
  1303. 0 -- tuples (default)\n\
  1304. 1 -- dictionaries, key=column or table.column if duplicated\n\
  1305. 2 -- dictionaries, key=table.column\n\
  1306. ";
  1307. static PyObject *
  1308. _mysql_ResultObject_fetch_row(
  1309. _mysql_ResultObject *self,
  1310. PyObject *args,
  1311. PyObject *kwargs)
  1312. {
  1313. typedef PyObject *_PYFUNC(_mysql_ResultObject *, MYSQL_ROW);
  1314. static char *kwlist[] = { "maxrows", "how", NULL };
  1315. static _PYFUNC *row_converters[] =
  1316. {
  1317. _mysql_row_to_tuple,
  1318. _mysql_row_to_dict,
  1319. _mysql_row_to_dict_old
  1320. };
  1321. _PYFUNC *convert_row;
  1322. unsigned int maxrows=1, how=0, skiprows=0, rowsadded;
  1323. PyObject *r=NULL;
  1324. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:fetch_row", kwlist,
  1325. &maxrows, &how))
  1326. return NULL;
  1327. check_result_connection(self);
  1328. if (how < 0 || how >= sizeof(row_converters)) {
  1329. PyErr_SetString(PyExc_ValueError, "how out of range");
  1330. return NULL;
  1331. }
  1332. convert_row = row_converters[how];
  1333. if (maxrows) {
  1334. if (!(r = PyTuple_New(maxrows))) goto error;
  1335. rowsadded = _mysql__fetch_row(self, &r, skiprows, maxrows,
  1336. convert_row);
  1337. if (rowsadded == -1) goto error;
  1338. } else {
  1339. if (self->use) {
  1340. maxrows = 1000;
  1341. if (!(r = PyTuple_New(maxrows))) goto error;
  1342. while (1) {
  1343. rowsadded = _mysql__fetch_row(self, &r, skiprows,
  1344. maxrows, convert_row);
  1345. if (rowsadded == -1) goto error;
  1346. skiprows += rowsadded;
  1347. if (rowsadded < maxrows) break;
  1348. if (MyTuple_Resize(&r, skiprows+maxrows, 0) == -1)
  1349. goto error;
  1350. }
  1351. } else {
  1352. /* XXX if overflow, maxrows<0? */
  1353. maxrows = (int) mysql_num_rows(self->result);
  1354. if (!(r = PyTuple_New(maxrows))) goto error;
  1355. rowsadded = _mysql__fetch_row(self, &r, 0,
  1356. maxrows, convert_row);
  1357. if (rowsadded == -1) goto error;
  1358. }
  1359. }
  1360. return r;
  1361. error:
  1362. Py_XDECREF(r);
  1363. return NULL;
  1364. }
  1365. #if MYSQL_VERSION_ID >= 32303
  1366. static char _mysql_ConnectionObject_change_user__doc__[] =
  1367. "Changes the user and causes the database specified by db to\n\
  1368. become the default (current) database on the connection\n\
  1369. specified by mysql. In subsequent queries, this database is\n\
  1370. the default for table references that do not include an\n\
  1371. explicit database specifier.\n\
  1372. \n\
  1373. This function was introduced in MySQL Version 3.23.3.\n\
  1374. \n\
  1375. Fails unless the connected user can be authenticated or if he\n\
  1376. doesn't have permission to use the database. In this case the\n\
  1377. user and database are not changed.\n\
  1378. \n\
  1379. The db parameter may be set to None if you don't want to have\n\
  1380. a default database.\n\
  1381. ";
  1382. static PyObject *
  1383. _mysql_ConnectionObject_change_user(
  1384. _mysql_ConnectionObject *self,
  1385. PyObject *args,
  1386. PyObject *kwargs)
  1387. {
  1388. char *user, *pwd=NULL, *db=NULL;
  1389. int r;
  1390. static char *kwlist[] = { "user", "passwd", "db", NULL } ;
  1391. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ss:change_user",
  1392. kwlist, &user, &pwd, &db))
  1393. return NULL;
  1394. check_connection(self);
  1395. Py_BEGIN_ALLOW_THREADS
  1396. r = mysql_change_user(&(self->connection), user, pwd, db);
  1397. Py_END_ALLOW_THREADS
  1398. if (r) return _mysql_Exception(self);
  1399. Py_INCREF(Py_None);
  1400. return Py_None;
  1401. }
  1402. #endif
  1403. static char _mysql_ConnectionObject_character_set_name__doc__[] =
  1404. "Returns the default character set for the current connection.\n\
  1405. Non-standard.\n\
  1406. ";
  1407. static PyObject *
  1408. _mysql_ConnectionObject_character_set_name(
  1409. _mysql_ConnectionObject *self,
  1410. PyObject *args)
  1411. {
  1412. const char *s;
  1413. if (!PyArg_ParseTuple(args, "")) return NULL;
  1414. check_connection(self);
  1415. #if MYSQL_VERSION_ID >= 32321
  1416. s = mysql_character_set_name(&(self->connection));
  1417. #else
  1418. s = "latin1";
  1419. #endif
  1420. return PyString_FromString(s);
  1421. }
  1422. #if MYSQL_VERSION_ID >= 50007
  1423. static char _mysql_ConnectionObject_set_character_set__doc__[] =
  1424. "Sets the default character set for the current connection.\n\
  1425. Non-standard.\n\
  1426. ";
  1427. static PyObject *
  1428. _mysql_ConnectionObject_set_character_set(
  1429. _mysql_ConnectionObject *self,
  1430. PyObject *args)
  1431. {
  1432. const char *s;
  1433. int err;
  1434. if (!PyArg_ParseTuple(args, "s", &s)) return NULL;
  1435. check_connection(self);
  1436. Py_BEGIN_ALLOW_THREADS
  1437. err = mysql_set_character_set(&(self->connection), s);
  1438. Py_END_ALLOW_THREADS
  1439. if (err) return _mysql_Exception(self);
  1440. Py_INCREF(Py_None);
  1441. return Py_None;
  1442. }
  1443. #endif
  1444. #if MYSQL_VERSION_ID >= 50010
  1445. static char _mysql_ConnectionObject_get_character_set_info__doc__[] =
  1446. "Returns a dict with information about the current character set:\n\
  1447. \n\
  1448. collation\n\
  1449. collation name\n\
  1450. name\n\
  1451. character set name\n\
  1452. comment\n\
  1453. comment or descriptive name\n\
  1454. dir\n\
  1455. character set directory\n\
  1456. mbminlen\n\
  1457. min. length for multibyte string\n\
  1458. mbmaxlen\n\
  1459. max. length for multibyte string\n\
  1460. \n\
  1461. Not all keys may be present, particularly dir.\n\
  1462. \n\
  1463. Non-standard.\n\
  1464. ";
  1465. static PyObject *
  1466. _mysql_ConnectionObject_get_character_set_info(
  1467. _mysql_ConnectionObject *self,
  1468. PyObject *args)
  1469. {
  1470. PyObject *result;
  1471. MY_CHARSET_INFO cs;
  1472. if (!PyArg_ParseTuple(args, "")) return NULL;
  1473. check_connection(self);
  1474. mysql_get_character_set_info(&(self->connection), &cs);
  1475. if (!(result = PyDict_New())) return NULL;
  1476. if (cs.csname)
  1477. PyDict_SetItemString(result, "name", PyString_FromString(cs.csname));
  1478. if (cs.name)
  1479. PyDict_SetItemString(result, "collation", PyString_FromString(cs.name));
  1480. if (cs.comment)
  1481. PyDict_SetItemString(result, "comment", PyString_FromString(cs.comment));
  1482. if (cs.dir)
  1483. PyDict_SetItemString(result, "dir", PyString_FromString(cs.dir));
  1484. PyDict_SetItemString(result, "mbminlen", PyInt_FromLong(cs.mbminlen));
  1485. PyDict_SetItemString(result, "mbmaxlen", PyInt_FromLong(cs.mbmaxlen));
  1486. return result;
  1487. }
  1488. #endif
  1489. static char _mysql_get_client_info__doc__[] =
  1490. "get_client_info() -- Returns a string that represents\n\
  1491. the client library version.";
  1492. static PyObject *
  1493. _mysql_get_client_info(
  1494. PyObject *self,
  1495. PyObject *args)
  1496. {
  1497. if (!PyArg_ParseTuple(args, "")) return NULL;
  1498. check_server_init(NULL);
  1499. return PyString_FromString(mysql_get_client_info());
  1500. }
  1501. static char _mysql_ConnectionObject_get_host_info__doc__[] =
  1502. "Returns a string that represents the MySQL client library\n\
  1503. version. Non-standard.\n\
  1504. ";
  1505. static PyObject *
  1506. _mysql_ConnectionObject_get_host_info(
  1507. _mysql_ConnectionObject *self,
  1508. PyObject *args)
  1509. {
  1510. if (!PyArg_ParseTuple(args, "")) return NULL;
  1511. check_connection(self);
  1512. return PyString_FromString(mysql_get_host_info(&(self->connection)));
  1513. }
  1514. static char _mysql_ConnectionObject_get_proto_info__doc__[] =
  1515. "Returns an unsigned integer representing the protocol version\n\
  1516. used by the current connection. Non-standard.\n\
  1517. ";
  1518. static PyObject *
  1519. _mysql_ConnectionObject_get_proto_info(
  1520. _mysql_ConnectionObject *self,
  1521. PyObject *args)
  1522. {
  1523. if (!PyArg_ParseTuple(args, "")) return NULL;
  1524. check_connection(self);
  1525. return PyInt_FromLong((long)mysql_get_proto_info(&(self->connection)));
  1526. }
  1527. static char _mysql_ConnectionObject_get_server_info__doc__[] =
  1528. "Returns a string that represents the server version number.\n\
  1529. Non-standard.\n\
  1530. ";
  1531. static PyObject *
  1532. _mysql_ConnectionObject_get_server_info(
  1533. _mysql_ConnectionObject *self,
  1534. PyObject *args)
  1535. {
  1536. if (!PyArg_ParseTuple(args, "")) return NULL;
  1537. check_connection(self);
  1538. return PyString_FromString(mysql_get_server_info(&(self->connection)));
  1539. }
  1540. static char _mysql_ConnectionObject_info__doc__[] =
  1541. "Retrieves a string providing information about the most\n\
  1542. recently executed query. Non-standard. Use messages or\n\
  1543. Cursor.messages.\n\
  1544. ";
  1545. static PyObject *
  1546. _mysql_ConnectionObject_info(
  1547. _mysql_ConnectionObject *self,
  1548. PyObject *args)
  1549. {
  1550. const char *s;
  1551. if (!PyArg_ParseTuple(args, "")) return NULL;
  1552. check_connection(self);
  1553. s = mysql_info(&(self->connection));
  1554. if (s) return PyString_FromString(s);
  1555. Py_INCREF(Py_None);
  1556. return Py_None;
  1557. }
  1558. static char _mysql_ConnectionObject_insert_id__doc__[] =
  1559. "Returns the ID generated for an AUTO_INCREMENT column by the previous\n\
  1560. query. Use this function after you have performed an INSERT query into a\n\
  1561. table that contains an AUTO_INCREMENT field.\n\
  1562. \n\
  1563. Note that this returns 0 if the previous query does not\n\
  1564. generate an AUTO_INCREMENT value. If you need to save the value for\n\
  1565. later, be sure to call this immediately after the query\n\
  1566. that generates the value.\n\
  1567. \n\
  1568. The ID is updated after INSERT and UPDATE statements that generate\n\
  1569. an AUTO_INCREMENT value or that set a column value to\n\
  1570. LAST_INSERT_ID(expr). See section 6.3.5.2 Miscellaneous Functions\n\
  1571. in the MySQL documentation.\n\
  1572. \n\
  1573. Also note that the value of the SQL LAST_INSERT_ID() function always\n\
  1574. contains the most recently generated AUTO_INCREMENT value, and is not\n\
  1575. reset between queries because the value of that function is maintained\n\
  1576. in the server.\n\
  1577. " ;
  1578. static PyObject *
  1579. _mysql_ConnectionObject_insert_id(
  1580. _mysql_ConnectionObject *self,
  1581. PyObject *args)
  1582. {
  1583. my_ulonglong r;
  1584. if (!PyArg_ParseTuple(args, "")) return NULL;
  1585. check_connection(self);
  1586. Py_BEGIN_ALLOW_THREADS
  1587. r = mysql_insert_id(&(self->connection));
  1588. Py_END_ALLOW_THREADS
  1589. return PyLong_FromUnsignedLongLong(r);
  1590. }
  1591. static char _mysql_ConnectionObject_kill__doc__[] =
  1592. "Asks the server to kill the thread specified by pid.\n\
  1593. Non-standard.";
  1594. static PyObject *
  1595. _mysql_ConnectionObject_kill(
  1596. _mysql_ConnectionObject *self,
  1597. PyObject *args)
  1598. {
  1599. unsigned long pid;
  1600. int r;
  1601. if (!PyArg_ParseTuple(args, "i:kill", &pid)) return NULL;
  1602. check_connection(self);
  1603. Py_BEGIN_ALLOW_THREADS
  1604. r = mysql_kill(&(self->connection), pid);
  1605. Py_END_ALLOW_THREADS
  1606. if (r) return _mysql_Exception(self);
  1607. Py_INCREF(Py_None);
  1608. return Py_None;
  1609. }
  1610. static char _mysql_ConnectionObject_field_count__doc__[] =
  1611. "Returns the number of columns for the most recent query on the\n\
  1612. connection. Non-standard. Will probably give you bogus results\n\
  1613. on most cursor classes. Use Cursor.rowcount.\n\
  1614. ";
  1615. static PyObject *
  1616. _mysql_ConnectionObject_field_count(
  1617. _mysql_ConnectionObject *self,
  1618. PyObject *args)
  1619. {
  1620. if (!PyArg_ParseTuple(args, "")) return NULL;
  1621. check_connection(self);
  1622. #if MYSQL_VERSION_ID < 32224
  1623. return PyInt_FromLong((long)mysql_num_fields(&(self->connection)));
  1624. #else
  1625. return PyInt_FromLong((long)mysql_field_count(&(self->connection)));
  1626. #endif
  1627. }
  1628. static char _mysql_ResultObject_num_fields__doc__[] =
  1629. "Returns the number of fields (column) in the result." ;
  1630. static PyObject *
  1631. _mysql_ResultObject_num_fields(
  1632. _mysql_ResultObject *self,
  1633. PyObject *args)
  1634. {
  1635. if (!PyArg_ParseTuple(args, "")) return NULL;
  1636. check_result_connection(self);
  1637. return PyInt_FromLong((long)mysql_num_fields(self->result));
  1638. }
  1639. static char _mysql_ResultObject_num_rows__doc__[] =
  1640. "Returns the number of rows in the result set. Note that if\n\
  1641. use=1, this will not return a valid value until the entire result\n\
  1642. set has been read.\n\
  1643. ";
  1644. static PyObject *
  1645. _mysql_ResultObject_num_rows(
  1646. _mysql_ResultObject *self,
  1647. PyObject *args)
  1648. {
  1649. if (!PyArg_ParseTuple(args, "")) return NULL;
  1650. check_result_connection(self);
  1651. return PyLong_FromUnsignedLongLong(mysql_num_rows(self->result));
  1652. }
  1653. static char _mysql_ConnectionObject_ping__doc__[] =
  1654. "Checks whether or not the connection to the server is\n\
  1655. working. If it has gone down, an automatic reconnection is\n\
  1656. attempted.\n\
  1657. \n\
  1658. This function can be used by clients that remain idle for a\n\
  1659. long while, to check whether or not the server has closed the\n\
  1660. connection and reconnect if necessary.\n\
  1661. \n\
  1662. New in 1.2.2: Accepts an optional reconnect parameter. If True,\n\
  1663. then the client will attempt reconnection. Note that this setting\n\
  1664. is persistent. By default, this is on in MySQL<5.0.3, and off\n\
  1665. thereafter.\n\
  1666. \n\
  1667. Non-standard. You should assume that ping() performs an\n\
  1668. implicit rollback; use only when starting a new transaction.\n\
  1669. You have been warned.\n\
  1670. ";
  1671. static PyObject *
  1672. _mysql_ConnectionObject_ping(
  1673. _mysql_ConnectionObject *self,
  1674. PyObject *args)
  1675. {
  1676. int r, reconnect = -1;
  1677. if (!PyArg_ParseTuple(args, "|I", &reconnect)) return NULL;
  1678. check_connection(self);
  1679. if ( reconnect != -1 ) self->connection.reconnect = reconnect;
  1680. Py_BEGIN_ALLOW_THREADS
  1681. r = mysql_ping(&(self->connection));
  1682. Py_END_ALLOW_THREADS
  1683. if (r) return _mysql_Exception(self);
  1684. Py_INCREF(Py_None);
  1685. return Py_None;
  1686. }
  1687. static char _mysql_ConnectionObject_query__doc__[] =
  1688. "Execute a query. store_result() or use_result() will get the\n\
  1689. result set, if any. Non-standard. Use cursor() to create a cursor,\n\
  1690. then cursor.execute().\n\
  1691. " ;
  1692. static PyObject *
  1693. _mysql_ConnectionObject_query(
  1694. _mysql_ConnectionObject *self,
  1695. PyObject *args)
  1696. {
  1697. char *query;
  1698. int len, r;
  1699. if (!PyArg_ParseTuple(args, "s#:query", &query, &len)) return NULL;
  1700. check_connection(self);
  1701. Py_BEGIN_ALLOW_THREADS
  1702. r = mysql_real_query(&(self->connection), query, len);
  1703. Py_END_ALLOW_THREADS
  1704. if (r) return _mysql_Exception(self);
  1705. Py_INCREF(Py_None);
  1706. return Py_None;
  1707. }
  1708. static char _mysql_ConnectionObject_select_db__doc__[] =
  1709. "Causes the database specified by db to become the default\n\
  1710. (current) database on the connection specified by mysql. In subsequent\n\
  1711. queries, this database is the default for table references that do not\n\
  1712. include an explicit database specifier.\n\
  1713. \n\
  1714. Fails unless the connected user can be authenticated as having\n\
  1715. permission to use the database.\n\
  1716. \n\
  1717. Non-standard.\n\
  1718. ";
  1719. static PyObject *
  1720. _mysql_ConnectionObject_select_db(
  1721. _mysql_ConnectionObject *self,
  1722. PyObject *args)
  1723. {
  1724. char *db;
  1725. int r;
  1726. if (!PyArg_ParseTuple(args, "s:select_db", &db)) return NULL;
  1727. check_connection(self);
  1728. Py_BEGIN_ALLOW_THREADS
  1729. r = mysql_select_db(&(self->connection), db);
  1730. Py_END_ALLOW_THREADS
  1731. if (r) return _mysql_Exception(self);
  1732. Py_INCREF(Py_None);
  1733. return Py_None;
  1734. }
  1735. static char _mysql_ConnectionObject_shutdown__doc__[] =
  1736. "Asks the database server to shut down. The connected user must\n\
  1737. have shutdown privileges. Non-standard.\n\
  1738. ";
  1739. static PyObject *
  1740. _mysql_ConnectionObject_shutdown(
  1741. _mysql_ConnectionObject *self,
  1742. PyObject *args)
  1743. {
  1744. int r;
  1745. if (!PyArg_ParseTuple(args, "")) return NULL;
  1746. check_connection(self);
  1747. Py_BEGIN_ALLOW_THREADS
  1748. r = mysql_shutdown(&(self->connection)
  1749. #if MYSQL_VERSION_ID >= 40103
  1750. , SHUTDOWN_DEFAULT
  1751. #endif
  1752. );
  1753. Py_END_ALLOW_THREADS
  1754. if (r) return _mysql_Exception(self);
  1755. Py_INCREF(Py_None);
  1756. return Py_None;
  1757. }
  1758. static char _mysql_ConnectionObject_stat__doc__[] =
  1759. "Returns a character string containing information similar to\n\
  1760. that provided by the mysqladmin status command. This includes\n\
  1761. uptime in