_mysql.c 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  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 <stdbool.h>
  25. #include "mysql.h"
  26. #include "mysqld_error.h"
  27. #if MYSQL_VERSION_ID >= 80000
  28. // https://github.com/mysql/mysql-server/commit/eb821c023cedc029ca0b06456dfae365106bee84
  29. // my_bool was typedef of char before MySQL 8.0.0.
  30. #define my_bool bool
  31. #endif
  32. #if ((MYSQL_VERSION_ID >= 50555 && MYSQL_VERSION_ID <= 50599) || \
  33. (MYSQL_VERSION_ID >= 50636 && MYSQL_VERSION_ID <= 50699) || \
  34. (MYSQL_VERSION_ID >= 50711 && MYSQL_VERSION_ID <= 50799) || \
  35. (MYSQL_VERSION_ID >= 80000)) && \
  36. !defined(MARIADB_BASE_VERSION) && !defined(MARIADB_VERSION_ID)
  37. #define HAVE_ENUM_MYSQL_OPT_SSL_MODE
  38. #endif
  39. #define PY_SSIZE_T_CLEAN 1
  40. #include "Python.h"
  41. #if PY_MAJOR_VERSION == 2
  42. #error "Python 2 is not supported"
  43. #endif
  44. #include "bytesobject.h"
  45. #include "structmember.h"
  46. #include "errmsg.h"
  47. #define MyAlloc(s,t) (s *) t.tp_alloc(&t,0)
  48. #define MyFree(o) Py_TYPE(o)->tp_free((PyObject*)o)
  49. static PyObject *_mysql_MySQLError;
  50. static PyObject *_mysql_Warning;
  51. static PyObject *_mysql_Error;
  52. static PyObject *_mysql_DatabaseError;
  53. static PyObject *_mysql_InterfaceError;
  54. static PyObject *_mysql_DataError;
  55. static PyObject *_mysql_OperationalError;
  56. static PyObject *_mysql_IntegrityError;
  57. static PyObject *_mysql_InternalError;
  58. static PyObject *_mysql_ProgrammingError;
  59. static PyObject *_mysql_NotSupportedError;
  60. typedef struct {
  61. PyObject_HEAD
  62. MYSQL connection;
  63. bool open;
  64. bool reconnect;
  65. PyObject *converter;
  66. } _mysql_ConnectionObject;
  67. #define check_connection(c) \
  68. if (!(c->open)) { \
  69. return _mysql_Exception(c); \
  70. };
  71. #define result_connection(r) ((_mysql_ConnectionObject *)r->conn)
  72. #define check_result_connection(r) check_connection(result_connection(r))
  73. extern PyTypeObject _mysql_ConnectionObject_Type;
  74. typedef struct {
  75. PyObject_HEAD
  76. PyObject *conn;
  77. MYSQL_RES *result;
  78. int nfields;
  79. int use;
  80. char has_next;
  81. PyObject *converter;
  82. const char *encoding;
  83. } _mysql_ResultObject;
  84. extern PyTypeObject _mysql_ResultObject_Type;
  85. PyObject *
  86. _mysql_Exception(_mysql_ConnectionObject *c)
  87. {
  88. PyObject *t, *e;
  89. int merr;
  90. if (!(t = PyTuple_New(2))) return NULL;
  91. if (!(c->open)) {
  92. /* GH-270: When connection is closed, accessing the c->connection
  93. * object may cause SEGV.
  94. */
  95. merr = CR_SERVER_GONE_ERROR;
  96. }
  97. else {
  98. merr = mysql_errno(&(c->connection));
  99. }
  100. switch (merr) {
  101. case 0:
  102. e = _mysql_InterfaceError;
  103. break;
  104. case CR_COMMANDS_OUT_OF_SYNC:
  105. case ER_DB_CREATE_EXISTS:
  106. case ER_SYNTAX_ERROR:
  107. case ER_PARSE_ERROR:
  108. case ER_NO_SUCH_TABLE:
  109. case ER_WRONG_DB_NAME:
  110. case ER_WRONG_TABLE_NAME:
  111. case ER_FIELD_SPECIFIED_TWICE:
  112. case ER_INVALID_GROUP_FUNC_USE:
  113. case ER_UNSUPPORTED_EXTENSION:
  114. case ER_TABLE_MUST_HAVE_COLUMNS:
  115. #ifdef ER_CANT_DO_THIS_DURING_AN_TRANSACTION
  116. case ER_CANT_DO_THIS_DURING_AN_TRANSACTION:
  117. #endif
  118. e = _mysql_ProgrammingError;
  119. break;
  120. #ifdef WARN_DATA_TRUNCATED
  121. case WARN_DATA_TRUNCATED:
  122. #ifdef WARN_NULL_TO_NOTNULL
  123. case WARN_NULL_TO_NOTNULL:
  124. #endif
  125. #ifdef ER_WARN_DATA_OUT_OF_RANGE
  126. case ER_WARN_DATA_OUT_OF_RANGE:
  127. #endif
  128. #ifdef ER_NO_DEFAULT
  129. case ER_NO_DEFAULT:
  130. #endif
  131. #ifdef ER_PRIMARY_CANT_HAVE_NULL
  132. case ER_PRIMARY_CANT_HAVE_NULL:
  133. #endif
  134. #ifdef ER_DATA_TOO_LONG
  135. case ER_DATA_TOO_LONG:
  136. #endif
  137. #ifdef ER_DATETIME_FUNCTION_OVERFLOW
  138. case ER_DATETIME_FUNCTION_OVERFLOW:
  139. #endif
  140. e = _mysql_DataError;
  141. break;
  142. #endif
  143. case ER_DUP_ENTRY:
  144. #ifdef ER_DUP_UNIQUE
  145. case ER_DUP_UNIQUE:
  146. #endif
  147. #ifdef ER_NO_REFERENCED_ROW
  148. case ER_NO_REFERENCED_ROW:
  149. #endif
  150. #ifdef ER_NO_REFERENCED_ROW_2
  151. case ER_NO_REFERENCED_ROW_2:
  152. #endif
  153. #ifdef ER_ROW_IS_REFERENCED
  154. case ER_ROW_IS_REFERENCED:
  155. #endif
  156. #ifdef ER_ROW_IS_REFERENCED_2
  157. case ER_ROW_IS_REFERENCED_2:
  158. #endif
  159. #ifdef ER_CANNOT_ADD_FOREIGN
  160. case ER_CANNOT_ADD_FOREIGN:
  161. #endif
  162. #ifdef ER_NO_DEFAULT_FOR_FIELD
  163. case ER_NO_DEFAULT_FOR_FIELD:
  164. #endif
  165. case ER_BAD_NULL_ERROR:
  166. e = _mysql_IntegrityError;
  167. break;
  168. #ifdef ER_WARNING_NOT_COMPLETE_ROLLBACK
  169. case ER_WARNING_NOT_COMPLETE_ROLLBACK:
  170. #endif
  171. #ifdef ER_NOT_SUPPORTED_YET
  172. case ER_NOT_SUPPORTED_YET:
  173. #endif
  174. #ifdef ER_FEATURE_DISABLED
  175. case ER_FEATURE_DISABLED:
  176. #endif
  177. #ifdef ER_UNKNOWN_STORAGE_ENGINE
  178. case ER_UNKNOWN_STORAGE_ENGINE:
  179. #endif
  180. e = _mysql_NotSupportedError;
  181. break;
  182. default:
  183. if (merr < 1000)
  184. e = _mysql_InternalError;
  185. else
  186. e = _mysql_OperationalError;
  187. break;
  188. }
  189. PyTuple_SET_ITEM(t, 0, PyLong_FromLong((long)merr));
  190. PyTuple_SET_ITEM(t, 1, PyUnicode_FromString(mysql_error(&(c->connection))));
  191. PyErr_SetObject(e, t);
  192. Py_DECREF(t);
  193. return NULL;
  194. }
  195. static const char *utf8 = "utf8";
  196. static const char*
  197. _get_encoding(MYSQL *mysql)
  198. {
  199. MY_CHARSET_INFO cs;
  200. mysql_get_character_set_info(mysql, &cs);
  201. if (strncmp(utf8, cs.csname, 4) == 0) { // utf8, utf8mb3, utf8mb4
  202. return utf8;
  203. }
  204. else if (strncmp("latin1", cs.csname, 6) == 0) {
  205. return "cp1252";
  206. }
  207. else if (strncmp("koi8r", cs.csname, 5) == 0) {
  208. return "koi8_r";
  209. }
  210. else if (strncmp("koi8u", cs.csname, 5) == 0) {
  211. return "koi8_u";
  212. }
  213. return cs.csname;
  214. }
  215. static char _mysql_ResultObject__doc__[] =
  216. "result(connection, use=0, converter={}) -- Result set from a query.\n\
  217. \n\
  218. Creating instances of this class directly is an excellent way to\n\
  219. shoot yourself in the foot. If using _mysql.connection directly,\n\
  220. use connection.store_result() or connection.use_result() instead.\n\
  221. If using MySQLdb.Connection, this is done by the cursor class.\n\
  222. Just forget you ever saw this. Forget... FOR-GET...";
  223. static int
  224. _mysql_ResultObject_Initialize(
  225. _mysql_ResultObject *self,
  226. PyObject *args,
  227. PyObject *kwargs)
  228. {
  229. static char *kwlist[] = {"connection", "use", "converter", NULL};
  230. MYSQL_RES *result;
  231. _mysql_ConnectionObject *conn=NULL;
  232. int use=0;
  233. PyObject *conv=NULL;
  234. int n, i;
  235. MYSQL_FIELD *fields;
  236. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|iO", kwlist,
  237. &_mysql_ConnectionObject_Type, &conn, &use, &conv))
  238. return -1;
  239. self->conn = (PyObject *) conn;
  240. Py_INCREF(conn);
  241. self->use = use;
  242. Py_BEGIN_ALLOW_THREADS ;
  243. if (use)
  244. result = mysql_use_result(&(conn->connection));
  245. else
  246. result = mysql_store_result(&(conn->connection));
  247. self->result = result;
  248. self->has_next = (char)mysql_more_results(&(conn->connection));
  249. Py_END_ALLOW_THREADS ;
  250. self->encoding = _get_encoding(&(conn->connection));
  251. //fprintf(stderr, "encoding=%s\n", self->encoding);
  252. if (!result) {
  253. if (mysql_errno(&(conn->connection))) {
  254. _mysql_Exception(conn);
  255. return -1;
  256. }
  257. self->converter = PyTuple_New(0);
  258. return 0;
  259. }
  260. n = mysql_num_fields(result);
  261. self->nfields = n;
  262. if (!(self->converter = PyTuple_New(n))) {
  263. return -1;
  264. }
  265. fields = mysql_fetch_fields(result);
  266. for (i=0; i<n; i++) {
  267. PyObject *tmp, *fun;
  268. tmp = PyLong_FromLong((long) fields[i].type);
  269. if (!tmp) {
  270. return -1;
  271. }
  272. fun = conv ? PyObject_GetItem(conv, tmp) : NULL;
  273. Py_DECREF(tmp);
  274. if (!fun) {
  275. if (PyErr_Occurred()) {
  276. if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
  277. return -1;
  278. }
  279. PyErr_Clear();
  280. }
  281. fun = Py_None;
  282. Py_INCREF(Py_None);
  283. }
  284. else if (PySequence_Check(fun)) {
  285. long flags = fields[i].flags;
  286. PyObject *fun2=NULL;
  287. int j, n2=PySequence_Size(fun);
  288. // BINARY_FLAG means ***_bin collation is used.
  289. // To distinguish text and binary, we should use charsetnr==63 (binary).
  290. // But we abuse BINARY_FLAG for historical reason.
  291. if (fields[i].charsetnr == 63) {
  292. flags |= BINARY_FLAG;
  293. } else {
  294. flags &= ~BINARY_FLAG;
  295. }
  296. for (j=0; j<n2; j++) {
  297. PyObject *t = PySequence_GetItem(fun, j);
  298. if (!t) {
  299. Py_DECREF(fun);
  300. return -1;
  301. }
  302. if (PyTuple_Check(t) && PyTuple_GET_SIZE(t) == 2) {
  303. long mask;
  304. PyObject *pmask=NULL;
  305. pmask = PyTuple_GET_ITEM(t, 0);
  306. fun2 = PyTuple_GET_ITEM(t, 1);
  307. Py_XINCREF(fun2);
  308. if (PyLong_Check(pmask)) {
  309. mask = PyLong_AS_LONG(pmask);
  310. if (mask & flags) {
  311. Py_DECREF(t);
  312. break;
  313. }
  314. else {
  315. fun2 = NULL;
  316. }
  317. } else {
  318. Py_DECREF(t);
  319. break;
  320. }
  321. }
  322. Py_DECREF(t);
  323. }
  324. if (!fun2) {
  325. fun2 = Py_None;
  326. Py_INCREF(fun2);
  327. }
  328. Py_DECREF(fun);
  329. fun = fun2;
  330. }
  331. PyTuple_SET_ITEM(self->converter, i, fun);
  332. }
  333. return 0;
  334. }
  335. static int _mysql_ResultObject_traverse(
  336. _mysql_ResultObject *self,
  337. visitproc visit,
  338. void *arg)
  339. {
  340. int r;
  341. if (self->converter) {
  342. if (!(r = visit(self->converter, arg))) return r;
  343. }
  344. if (self->conn)
  345. return visit(self->conn, arg);
  346. return 0;
  347. }
  348. static int _mysql_ResultObject_clear(_mysql_ResultObject *self)
  349. {
  350. Py_CLEAR(self->converter);
  351. Py_CLEAR(self->conn);
  352. return 0;
  353. }
  354. enum {
  355. SSLMODE_DISABLED = 1,
  356. SSLMODE_PREFERRED = 2,
  357. SSLMODE_REQUIRED = 3,
  358. SSLMODE_VERIFY_CA = 4,
  359. SSLMODE_VERIFY_IDENTITY = 5
  360. };
  361. static int
  362. _get_ssl_mode_num(const char *ssl_mode)
  363. {
  364. static const char *ssl_mode_list[] = {
  365. "DISABLED", "PREFERRED", "REQUIRED", "VERIFY_CA", "VERIFY_IDENTITY" };
  366. unsigned int i;
  367. for (i=0; i < sizeof(ssl_mode_list)/sizeof(ssl_mode_list[0]); i++) {
  368. if (strcmp(ssl_mode, ssl_mode_list[i]) == 0) {
  369. // SSL_MODE one-based
  370. return i + 1;
  371. }
  372. }
  373. return -1;
  374. }
  375. static int
  376. _mysql_ConnectionObject_Initialize(
  377. _mysql_ConnectionObject *self,
  378. PyObject *args,
  379. PyObject *kwargs)
  380. {
  381. MYSQL *conn = NULL;
  382. PyObject *conv = NULL;
  383. PyObject *ssl = NULL;
  384. const char *ssl_mode = NULL;
  385. const char *key = NULL, *cert = NULL, *ca = NULL,
  386. *capath = NULL, *cipher = NULL;
  387. PyObject *ssl_keepref[5] = {NULL};
  388. int n_ssl_keepref = 0;
  389. char *host = NULL, *user = NULL, *passwd = NULL,
  390. *db = NULL, *unix_socket = NULL;
  391. unsigned int port = 0;
  392. unsigned int client_flag = 0;
  393. static char *kwlist[] = { "host", "user", "password", "database", "port",
  394. "unix_socket", "conv",
  395. "connect_timeout", "compress",
  396. "named_pipe", "init_command",
  397. "read_default_file", "read_default_group",
  398. "client_flag", "ssl", "ssl_mode",
  399. "local_infile",
  400. "read_timeout", "write_timeout", "charset",
  401. "auth_plugin",
  402. NULL } ;
  403. int connect_timeout = 0;
  404. int read_timeout = 0;
  405. int write_timeout = 0;
  406. int compress = -1, named_pipe = -1, local_infile = -1;
  407. int ssl_mode_num = SSLMODE_PREFERRED;
  408. char *init_command=NULL,
  409. *read_default_file=NULL,
  410. *read_default_group=NULL,
  411. *charset=NULL,
  412. *auth_plugin=NULL;
  413. self->converter = NULL;
  414. self->open = false;
  415. self->reconnect = false;
  416. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  417. "|ssssisOiiisssiOsiiiss:connect",
  418. kwlist,
  419. &host, &user, &passwd, &db,
  420. &port, &unix_socket, &conv,
  421. &connect_timeout,
  422. &compress, &named_pipe,
  423. &init_command, &read_default_file,
  424. &read_default_group,
  425. &client_flag, &ssl, &ssl_mode,
  426. &local_infile,
  427. &read_timeout,
  428. &write_timeout,
  429. &charset,
  430. &auth_plugin
  431. ))
  432. return -1;
  433. #define _stringsuck(d,t,s) {t=PyMapping_GetItemString(s,#d);\
  434. if(t){d=PyUnicode_AsUTF8(t);ssl_keepref[n_ssl_keepref++]=t;}\
  435. PyErr_Clear();}
  436. char ssl_mode_set = 0;
  437. if (ssl) {
  438. if (PyMapping_Check(ssl)) {
  439. PyObject *value = NULL;
  440. _stringsuck(ca, value, ssl);
  441. _stringsuck(capath, value, ssl);
  442. _stringsuck(cert, value, ssl);
  443. _stringsuck(key, value, ssl);
  444. _stringsuck(cipher, value, ssl);
  445. } else if (PyObject_IsTrue(ssl)) {
  446. // Support ssl=True from mysqlclient 2.2.4.
  447. // for compatibility with PyMySQL and mysqlclient==2.2.1&libmariadb.
  448. ssl_mode_num = SSLMODE_REQUIRED;
  449. ssl_mode_set = 1;
  450. } else {
  451. ssl_mode_num = SSLMODE_DISABLED;
  452. ssl_mode_set = 1;
  453. }
  454. }
  455. if (ssl_mode) {
  456. if ((ssl_mode_num = _get_ssl_mode_num(ssl_mode)) <= 0) {
  457. PyErr_SetString(_mysql_NotSupportedError, "Unknown ssl_mode specification");
  458. return -1;
  459. }
  460. ssl_mode_set = 1;
  461. }
  462. conn = mysql_init(&(self->connection));
  463. if (!conn) {
  464. PyErr_SetNone(PyExc_MemoryError);
  465. return -1;
  466. }
  467. self->open = true;
  468. if (connect_timeout) {
  469. unsigned int timeout = connect_timeout;
  470. mysql_options(&(self->connection), MYSQL_OPT_CONNECT_TIMEOUT,
  471. (char *)&timeout);
  472. }
  473. if (read_timeout) {
  474. unsigned int timeout = read_timeout;
  475. mysql_options(&(self->connection), MYSQL_OPT_READ_TIMEOUT,
  476. (char *)&timeout);
  477. }
  478. if (write_timeout) {
  479. unsigned int timeout = write_timeout;
  480. mysql_options(&(self->connection), MYSQL_OPT_WRITE_TIMEOUT,
  481. (char *)&timeout);
  482. }
  483. if (compress != -1) {
  484. mysql_options(&(self->connection), MYSQL_OPT_COMPRESS, 0);
  485. client_flag |= CLIENT_COMPRESS;
  486. }
  487. if (named_pipe != -1)
  488. mysql_options(&(self->connection), MYSQL_OPT_NAMED_PIPE, 0);
  489. if (init_command != NULL)
  490. mysql_options(&(self->connection), MYSQL_INIT_COMMAND, init_command);
  491. if (read_default_file != NULL)
  492. mysql_options(&(self->connection), MYSQL_READ_DEFAULT_FILE, read_default_file);
  493. if (read_default_group != NULL)
  494. mysql_options(&(self->connection), MYSQL_READ_DEFAULT_GROUP, read_default_group);
  495. if (local_infile != -1)
  496. mysql_options(&(self->connection), MYSQL_OPT_LOCAL_INFILE, (char *) &local_infile);
  497. if (ssl) {
  498. mysql_options(&(self->connection), MYSQL_OPT_SSL_KEY, key);
  499. mysql_options(&(self->connection), MYSQL_OPT_SSL_CERT, cert);
  500. mysql_options(&(self->connection), MYSQL_OPT_SSL_CA, ca);
  501. mysql_options(&(self->connection), MYSQL_OPT_SSL_CAPATH, capath);
  502. mysql_options(&(self->connection), MYSQL_OPT_SSL_CIPHER, cipher);
  503. }
  504. if (ssl_mode_set) {
  505. #ifdef HAVE_ENUM_MYSQL_OPT_SSL_MODE
  506. mysql_options(&(self->connection), MYSQL_OPT_SSL_MODE, &ssl_mode_num);
  507. #else
  508. // MariaDB doesn't support MYSQL_OPT_SSL_MODE.
  509. // See https://github.com/PyMySQL/mysqlclient/issues/474
  510. // TODO: Does MariaDB supports PREFERRED and VERIFY_CA?
  511. // We support only two levels for now.
  512. my_bool enforce_tls = 1;
  513. if (ssl_mode_num >= SSLMODE_REQUIRED) {
  514. mysql_optionsv(&(self->connection), MYSQL_OPT_SSL_ENFORCE, (void *)&enforce_tls);
  515. }
  516. if (ssl_mode_num >= SSLMODE_VERIFY_CA) {
  517. mysql_optionsv(&(self->connection), MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (void *)&enforce_tls);
  518. }
  519. #endif
  520. }
  521. if (charset) {
  522. mysql_options(&(self->connection), MYSQL_SET_CHARSET_NAME, charset);
  523. }
  524. if (auth_plugin) {
  525. mysql_options(&(self->connection), MYSQL_DEFAULT_AUTH, auth_plugin);
  526. }
  527. Py_BEGIN_ALLOW_THREADS
  528. conn = mysql_real_connect(&(self->connection), host, user, passwd, db,
  529. port, unix_socket, client_flag);
  530. Py_END_ALLOW_THREADS
  531. if (ssl) {
  532. int i;
  533. for (i=0; i<n_ssl_keepref; i++) {
  534. Py_DECREF(ssl_keepref[i]);
  535. ssl_keepref[i] = NULL;
  536. }
  537. }
  538. if (!conn) {
  539. _mysql_Exception(self);
  540. return -1;
  541. }
  542. /* Internal references to python-land objects */
  543. if (!conv)
  544. conv = PyDict_New();
  545. else
  546. Py_INCREF(conv);
  547. if (!conv)
  548. return -1;
  549. self->converter = conv;
  550. /*
  551. PyType_GenericAlloc() automatically sets up GC allocation and
  552. tracking for GC objects, at least in 2.2.1, so it does not need to
  553. be done here. tp_dealloc still needs to call PyObject_GC_UnTrack(),
  554. however.
  555. */
  556. return 0;
  557. }
  558. static char _mysql_connect__doc__[] =
  559. "Returns a MYSQL connection object. Exclusive use of\n\
  560. keyword parameters strongly recommended. Consult the\n\
  561. MySQL C API documentation for more details.\n\
  562. \n\
  563. host\n\
  564. string, host to connect\n\
  565. \n\
  566. user\n\
  567. string, user to connect as\n\
  568. \n\
  569. password\n\
  570. string, password to use\n\
  571. \n\
  572. database\n\
  573. string, database to use\n\
  574. \n\
  575. port\n\
  576. integer, TCP/IP port to connect to\n\
  577. \n\
  578. unix_socket\n\
  579. string, location of unix_socket (UNIX-ish only)\n\
  580. \n\
  581. conv\n\
  582. mapping, maps MySQL FIELD_TYPE.* to Python functions which\n\
  583. convert a string to the appropriate Python type\n\
  584. \n\
  585. connect_timeout\n\
  586. number of seconds to wait before the connection\n\
  587. attempt fails.\n\
  588. \n\
  589. compress\n\
  590. if set, gzip compression is enabled\n\
  591. \n\
  592. named_pipe\n\
  593. if set, connect to server via named pipe (Windows only)\n\
  594. \n\
  595. init_command\n\
  596. command which is run once the connection is created\n\
  597. \n\
  598. read_default_file\n\
  599. see the MySQL documentation for mysql_options()\n\
  600. \n\
  601. read_default_group\n\
  602. see the MySQL documentation for mysql_options()\n\
  603. \n\
  604. client_flag\n\
  605. client flags from MySQLdb.constants.CLIENT\n\
  606. \n\
  607. load_infile\n\
  608. int, non-zero enables LOAD LOCAL INFILE, zero disables\n\
  609. \n\
  610. ";
  611. static PyObject *
  612. _mysql_connect(
  613. PyObject *self,
  614. PyObject *args,
  615. PyObject *kwargs)
  616. {
  617. _mysql_ConnectionObject *c=NULL;
  618. c = MyAlloc(_mysql_ConnectionObject, _mysql_ConnectionObject_Type);
  619. if (c == NULL) return NULL;
  620. if (_mysql_ConnectionObject_Initialize(c, args, kwargs)) {
  621. Py_DECREF(c);
  622. c = NULL;
  623. }
  624. return (PyObject *) c;
  625. }
  626. static int _mysql_ConnectionObject_traverse(
  627. _mysql_ConnectionObject *self,
  628. visitproc visit,
  629. void *arg)
  630. {
  631. if (self->converter)
  632. return visit(self->converter, arg);
  633. return 0;
  634. }
  635. static int _mysql_ConnectionObject_clear(
  636. _mysql_ConnectionObject *self)
  637. {
  638. Py_XDECREF(self->converter);
  639. self->converter = NULL;
  640. return 0;
  641. }
  642. static char _mysql_ConnectionObject_close__doc__[] =
  643. "Close the connection. No further activity possible.";
  644. static PyObject *
  645. _mysql_ConnectionObject_close(
  646. _mysql_ConnectionObject *self,
  647. PyObject *noargs)
  648. {
  649. check_connection(self);
  650. Py_BEGIN_ALLOW_THREADS
  651. mysql_close(&(self->connection));
  652. Py_END_ALLOW_THREADS
  653. self->open = false;
  654. _mysql_ConnectionObject_clear(self);
  655. Py_RETURN_NONE;
  656. }
  657. static char _mysql_ConnectionObject_affected_rows__doc__ [] =
  658. "Return number of rows affected by the last query.\n\
  659. Non-standard. Use Cursor.rowcount.\n\
  660. ";
  661. static PyObject *
  662. _mysql_ConnectionObject_affected_rows(
  663. _mysql_ConnectionObject *self,
  664. PyObject *noargs)
  665. {
  666. my_ulonglong ret;
  667. check_connection(self);
  668. ret = mysql_affected_rows(&(self->connection));
  669. if (ret == (my_ulonglong)-1)
  670. return PyLong_FromLong(-1);
  671. return PyLong_FromUnsignedLongLong(ret);
  672. }
  673. static char _mysql_debug__doc__[] =
  674. "Does a DBUG_PUSH with the given string.\n\
  675. mysql_debug() uses the Fred Fish debug library.\n\
  676. To use this function, you must compile the client library to\n\
  677. support debugging.\n\
  678. ";
  679. static PyObject *
  680. _mysql_debug(
  681. PyObject *self,
  682. PyObject *args)
  683. {
  684. char *debug;
  685. if (!PyArg_ParseTuple(args, "s", &debug)) return NULL;
  686. mysql_debug(debug);
  687. Py_RETURN_NONE;
  688. }
  689. static char _mysql_ConnectionObject_dump_debug_info__doc__[] =
  690. "Instructs the server to write some debug information to the\n\
  691. log. The connected user must have the process privilege for\n\
  692. this to work. Non-standard.\n\
  693. ";
  694. static PyObject *
  695. _mysql_ConnectionObject_dump_debug_info(
  696. _mysql_ConnectionObject *self,
  697. PyObject *noargs)
  698. {
  699. int err;
  700. check_connection(self);
  701. Py_BEGIN_ALLOW_THREADS
  702. err = mysql_dump_debug_info(&(self->connection));
  703. Py_END_ALLOW_THREADS
  704. if (err) return _mysql_Exception(self);
  705. Py_RETURN_NONE;
  706. }
  707. static char _mysql_ConnectionObject_autocommit__doc__[] =
  708. "Set the autocommit mode. True values enable; False value disable.\n\
  709. ";
  710. static PyObject *
  711. _mysql_ConnectionObject_autocommit(
  712. _mysql_ConnectionObject *self,
  713. PyObject *args)
  714. {
  715. int flag, err;
  716. if (!PyArg_ParseTuple(args, "i", &flag)) return NULL;
  717. check_connection(self);
  718. Py_BEGIN_ALLOW_THREADS
  719. err = mysql_autocommit(&(self->connection), flag);
  720. Py_END_ALLOW_THREADS
  721. if (err) return _mysql_Exception(self);
  722. Py_RETURN_NONE;
  723. }
  724. static char _mysql_ConnectionObject_get_autocommit__doc__[] =
  725. "Get the autocommit mode. True when enable; False when disable.\n";
  726. static PyObject *
  727. _mysql_ConnectionObject_get_autocommit(
  728. _mysql_ConnectionObject *self,
  729. PyObject *args)
  730. {
  731. check_connection(self);
  732. if (self->connection.server_status & SERVER_STATUS_AUTOCOMMIT) {
  733. Py_RETURN_TRUE;
  734. }
  735. Py_RETURN_FALSE;
  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 *noargs)
  744. {
  745. int err;
  746. check_connection(self);
  747. Py_BEGIN_ALLOW_THREADS
  748. err = mysql_commit(&(self->connection));
  749. Py_END_ALLOW_THREADS
  750. if (err) return _mysql_Exception(self);
  751. Py_RETURN_NONE;
  752. }
  753. static char _mysql_ConnectionObject_rollback__doc__[] =
  754. "Rolls back the current transaction\n\
  755. ";
  756. static PyObject *
  757. _mysql_ConnectionObject_rollback(
  758. _mysql_ConnectionObject *self,
  759. PyObject *noargs)
  760. {
  761. int err;
  762. check_connection(self);
  763. Py_BEGIN_ALLOW_THREADS
  764. err = mysql_rollback(&(self->connection));
  765. Py_END_ALLOW_THREADS
  766. if (err) return _mysql_Exception(self);
  767. Py_RETURN_NONE;
  768. }
  769. static char _mysql_ConnectionObject_next_result__doc__[] =
  770. "If more query results exist, next_result() reads the next query\n\
  771. results and returns the status back to application.\n\
  772. \n\
  773. After calling next_result() the state of the connection is as if\n\
  774. you had called query() for the next query. This means that you can\n\
  775. now call store_result(), warning_count(), affected_rows()\n\
  776. , and so forth. \n\
  777. \n\
  778. Returns 0 if there are more results; -1 if there are no more results\n\
  779. \n\
  780. Non-standard.\n\
  781. ";
  782. static PyObject *
  783. _mysql_ConnectionObject_next_result(
  784. _mysql_ConnectionObject *self,
  785. PyObject *noargs)
  786. {
  787. int err;
  788. check_connection(self);
  789. Py_BEGIN_ALLOW_THREADS
  790. err = mysql_next_result(&(self->connection));
  791. Py_END_ALLOW_THREADS
  792. if (err > 0) return _mysql_Exception(self);
  793. return PyLong_FromLong(err);
  794. }
  795. static char _mysql_ConnectionObject_set_server_option__doc__[] =
  796. "set_server_option(option) -- Enables or disables an option\n\
  797. for the connection.\n\
  798. \n\
  799. Non-standard.\n\
  800. ";
  801. static PyObject *
  802. _mysql_ConnectionObject_set_server_option(
  803. _mysql_ConnectionObject *self,
  804. PyObject *args)
  805. {
  806. int err, flags=0;
  807. if (!PyArg_ParseTuple(args, "i", &flags))
  808. return NULL;
  809. check_connection(self);
  810. Py_BEGIN_ALLOW_THREADS
  811. err = mysql_set_server_option(&(self->connection), flags);
  812. Py_END_ALLOW_THREADS
  813. if (err) return _mysql_Exception(self);
  814. return PyLong_FromLong(err);
  815. }
  816. static char _mysql_ConnectionObject_sqlstate__doc__[] =
  817. "Returns a string containing the SQLSTATE error code\n\
  818. for the last error. The error code consists of five characters.\n\
  819. '00000' means \"no error.\" The values are specified by ANSI SQL\n\
  820. and ODBC. For a list of possible values, see section 23\n\
  821. Error Handling in MySQL in the MySQL Manual.\n\
  822. \n\
  823. Note that not all MySQL errors are yet mapped to SQLSTATE's.\n\
  824. The value 'HY000' (general error) is used for unmapped errors.\n\
  825. \n\
  826. Non-standard.\n\
  827. ";
  828. static PyObject *
  829. _mysql_ConnectionObject_sqlstate(
  830. _mysql_ConnectionObject *self,
  831. PyObject *noargs)
  832. {
  833. check_connection(self);
  834. return PyUnicode_FromString(mysql_sqlstate(&(self->connection)));
  835. }
  836. static char _mysql_ConnectionObject_warning_count__doc__[] =
  837. "Returns the number of warnings generated during execution\n\
  838. of the previous SQL statement.\n\
  839. \n\
  840. Non-standard.\n\
  841. ";
  842. static PyObject *
  843. _mysql_ConnectionObject_warning_count(
  844. _mysql_ConnectionObject *self,
  845. PyObject *noargs)
  846. {
  847. check_connection(self);
  848. return PyLong_FromLong(mysql_warning_count(&(self->connection)));
  849. }
  850. static char _mysql_ConnectionObject_errno__doc__[] =
  851. "Returns the error code for the most recently invoked API function\n\
  852. that can succeed or fail. A return value of zero means that no error\n\
  853. occurred.\n\
  854. ";
  855. static PyObject *
  856. _mysql_ConnectionObject_errno(
  857. _mysql_ConnectionObject *self,
  858. PyObject *noargs)
  859. {
  860. check_connection(self);
  861. return PyLong_FromLong((long)mysql_errno(&(self->connection)));
  862. }
  863. static char _mysql_ConnectionObject_error__doc__[] =
  864. "Returns the error message for the most recently invoked API function\n\
  865. that can succeed or fail. An empty string ("") is returned if no error\n\
  866. occurred.\n\
  867. ";
  868. static PyObject *
  869. _mysql_ConnectionObject_error(
  870. _mysql_ConnectionObject *self,
  871. PyObject *noargs)
  872. {
  873. check_connection(self);
  874. return PyUnicode_FromString(mysql_error(&(self->connection)));
  875. }
  876. static char _mysql_escape_string__doc__[] =
  877. "escape_string(s) -- quote any SQL-interpreted characters in string s.\n\
  878. \n\
  879. Use connection.escape_string(s), if you use it at all.\n\
  880. _mysql.escape_string(s) cannot handle character sets. You are\n\
  881. probably better off using connection.escape(o) instead, since\n\
  882. it will escape entire sequences as well as strings.";
  883. static PyObject *
  884. _mysql_escape_string(
  885. _mysql_ConnectionObject *self,
  886. PyObject *args)
  887. {
  888. PyObject *str;
  889. char *in, *out;
  890. unsigned long len;
  891. Py_ssize_t size;
  892. if (!PyArg_ParseTuple(args, "s#:escape_string", &in, &size)) return NULL;
  893. str = PyBytes_FromStringAndSize((char *) NULL, size*2+1);
  894. if (!str) return PyErr_NoMemory();
  895. out = PyBytes_AS_STRING(str);
  896. if (self && PyModule_Check((PyObject*)self))
  897. self = NULL;
  898. if (self && self->open) {
  899. #if MYSQL_VERSION_ID >= 50707 && !defined(MARIADB_BASE_VERSION) && !defined(MARIADB_VERSION_ID)
  900. len = mysql_real_escape_string_quote(&(self->connection), out, in, size, '\'');
  901. #else
  902. len = mysql_real_escape_string(&(self->connection), out, in, size);
  903. #endif
  904. } else {
  905. len = mysql_escape_string(out, in, size);
  906. }
  907. if (_PyBytes_Resize(&str, len) < 0) return NULL;
  908. return (str);
  909. }
  910. static char _mysql_string_literal__doc__[] =
  911. "string_literal(obj) -- converts object obj into a SQL string literal.\n\
  912. This means, any special SQL characters are escaped, and it is enclosed\n\
  913. within single quotes. In other words, it performs:\n\
  914. \n\
  915. \"'%s'\" % escape_string(str(obj))\n\
  916. \n\
  917. Use connection.string_literal(obj), if you use it at all.\n\
  918. _mysql.string_literal(obj) cannot handle character sets.";
  919. static PyObject *
  920. _mysql_string_literal(
  921. _mysql_ConnectionObject *self,
  922. PyObject *o)
  923. {
  924. PyObject *s; // input string or bytes. need to decref.
  925. if (self && PyModule_Check((PyObject*)self))
  926. self = NULL;
  927. if (PyBytes_Check(o)) {
  928. s = o;
  929. Py_INCREF(s);
  930. }
  931. else {
  932. PyObject *t = PyObject_Str(o);
  933. if (!t) return NULL;
  934. const char *encoding = (self && self->open) ?
  935. _get_encoding(&self->connection) : utf8;
  936. if (encoding == utf8) {
  937. s = t;
  938. }
  939. else {
  940. s = PyUnicode_AsEncodedString(t, encoding, "strict");
  941. Py_DECREF(t);
  942. if (!s) return NULL;
  943. }
  944. }
  945. // Prepare input string (in, size)
  946. const char *in;
  947. Py_ssize_t size;
  948. if (PyUnicode_Check(s)) {
  949. in = PyUnicode_AsUTF8AndSize(s, &size);
  950. } else {
  951. assert(PyBytes_Check(s));
  952. in = PyBytes_AsString(s);
  953. size = PyBytes_GET_SIZE(s);
  954. }
  955. // Prepare output buffer (str, out)
  956. PyObject *str = PyBytes_FromStringAndSize((char *) NULL, size*2+3);
  957. if (!str) {
  958. Py_DECREF(s);
  959. return PyErr_NoMemory();
  960. }
  961. char *out = PyBytes_AS_STRING(str);
  962. // escape
  963. unsigned long len;
  964. if (self && self->open) {
  965. #if MYSQL_VERSION_ID >= 50707 && !defined(MARIADB_BASE_VERSION) && !defined(MARIADB_VERSION_ID)
  966. len = mysql_real_escape_string_quote(&(self->connection), out+1, in, size, '\'');
  967. #else
  968. len = mysql_real_escape_string(&(self->connection), out+1, in, size);
  969. #endif
  970. } else {
  971. len = mysql_escape_string(out+1, in, size);
  972. }
  973. Py_DECREF(s);
  974. *out = *(out+len+1) = '\'';
  975. if (_PyBytes_Resize(&str, len+2) < 0) {
  976. Py_DECREF(str);
  977. return NULL;
  978. }
  979. return str;
  980. }
  981. static PyObject *
  982. _escape_item(
  983. PyObject *self,
  984. PyObject *item,
  985. PyObject *d)
  986. {
  987. PyObject *quoted=NULL, *itemtype, *itemconv;
  988. if (!(itemtype = PyObject_Type(item))) {
  989. return NULL;
  990. }
  991. itemconv = PyObject_GetItem(d, itemtype);
  992. Py_DECREF(itemtype);
  993. if (!itemconv) {
  994. PyErr_Clear();
  995. return _mysql_string_literal((_mysql_ConnectionObject*)self, item);
  996. }
  997. Py_INCREF(d);
  998. quoted = PyObject_CallFunction(itemconv, "OO", item, d);
  999. Py_DECREF(d);
  1000. Py_DECREF(itemconv);
  1001. return quoted;
  1002. }
  1003. static char _mysql_escape__doc__[] =
  1004. "escape(obj, dict) -- escape any special characters in object obj\n\
  1005. using mapping dict to provide quoting functions for each type.\n\
  1006. Returns a SQL literal string.";
  1007. static PyObject *
  1008. _mysql_escape(
  1009. PyObject *self,
  1010. PyObject *args)
  1011. {
  1012. PyObject *o=NULL, *d=NULL;
  1013. if (!PyArg_ParseTuple(args, "O|O:escape", &o, &d))
  1014. return NULL;
  1015. if (d) {
  1016. if (!PyMapping_Check(d)) {
  1017. PyErr_SetString(PyExc_TypeError,
  1018. "argument 2 must be a mapping");
  1019. return NULL;
  1020. }
  1021. return _escape_item(self, o, d);
  1022. } else {
  1023. if (!self) {
  1024. PyErr_SetString(PyExc_TypeError,
  1025. "argument 2 must be a mapping");
  1026. return NULL;
  1027. }
  1028. return _escape_item(self, o,
  1029. ((_mysql_ConnectionObject *) self)->converter);
  1030. }
  1031. }
  1032. static char _mysql_ResultObject_describe__doc__[] =
  1033. "Returns the sequence of 7-tuples required by the DB-API for\n\
  1034. the Cursor.description attribute.\n\
  1035. ";
  1036. static PyObject *
  1037. _mysql_ResultObject_describe(
  1038. _mysql_ResultObject *self,
  1039. PyObject *noargs)
  1040. {
  1041. PyObject *d;
  1042. MYSQL_FIELD *fields;
  1043. unsigned int i, n;
  1044. check_result_connection(self);
  1045. n = mysql_num_fields(self->result);
  1046. fields = mysql_fetch_fields(self->result);
  1047. if (!(d = PyTuple_New(n))) return NULL;
  1048. for (i=0; i<n; i++) {
  1049. PyObject *t;
  1050. PyObject *name;
  1051. if (self->encoding == utf8) {
  1052. name = PyUnicode_DecodeUTF8(fields[i].name, fields[i].name_length, "replace");
  1053. } else {
  1054. name = PyUnicode_Decode(fields[i].name, fields[i].name_length, self->encoding, "replace");
  1055. }
  1056. if (name == NULL) {
  1057. goto error;
  1058. }
  1059. t = Py_BuildValue("(Niiiiii)",
  1060. name,
  1061. (long) fields[i].type,
  1062. (long) fields[i].max_length,
  1063. (long) fields[i].length,
  1064. (long) fields[i].length,
  1065. (long) fields[i].decimals,
  1066. (long) !(IS_NOT_NULL(fields[i].flags)));
  1067. if (!t) goto error;
  1068. PyTuple_SET_ITEM(d, i, t);
  1069. }
  1070. return d;
  1071. error:
  1072. Py_XDECREF(d);
  1073. return NULL;
  1074. }
  1075. static char _mysql_ResultObject_field_flags__doc__[] =
  1076. "Returns a tuple of field flags, one for each column in the result.\n\
  1077. " ;
  1078. static PyObject *
  1079. _mysql_ResultObject_field_flags(
  1080. _mysql_ResultObject *self,
  1081. PyObject *noargs)
  1082. {
  1083. PyObject *d;
  1084. MYSQL_FIELD *fields;
  1085. unsigned int i, n;
  1086. check_result_connection(self);
  1087. n = mysql_num_fields(self->result);
  1088. fields = mysql_fetch_fields(self->result);
  1089. if (!(d = PyTuple_New(n))) return NULL;
  1090. for (i=0; i<n; i++) {
  1091. PyObject *f;
  1092. if (!(f = PyLong_FromLong((long)fields[i].flags))) goto error;
  1093. PyTuple_SET_ITEM(d, i, f);
  1094. }
  1095. return d;
  1096. error:
  1097. Py_XDECREF(d);
  1098. return NULL;
  1099. }
  1100. static PyObject *
  1101. _mysql_field_to_python(
  1102. PyObject *converter,
  1103. const char *rowitem,
  1104. Py_ssize_t length,
  1105. MYSQL_FIELD *field,
  1106. const char *encoding)
  1107. {
  1108. if (rowitem == NULL) {
  1109. Py_RETURN_NONE;
  1110. }
  1111. // Fast paths for int, string and binary.
  1112. if (converter == (PyObject*)&PyUnicode_Type) {
  1113. if (encoding == utf8) {
  1114. //fprintf(stderr, "decoding with utf8!\n");
  1115. return PyUnicode_DecodeUTF8(rowitem, length, NULL);
  1116. } else {
  1117. //fprintf(stderr, "decoding with %s\n", encoding);
  1118. return PyUnicode_Decode(rowitem, length, encoding, NULL);
  1119. }
  1120. }
  1121. if (converter == (PyObject*)&PyBytes_Type || converter == Py_None) {
  1122. //fprintf(stderr, "decoding with bytes\n", encoding);
  1123. return PyBytes_FromStringAndSize(rowitem, length);
  1124. }
  1125. if (converter == (PyObject*)&PyLong_Type) {
  1126. //fprintf(stderr, "decoding with int\n", encoding);
  1127. return PyLong_FromString(rowitem, NULL, 10);
  1128. }
  1129. //fprintf(stderr, "decoding with callback\n");
  1130. //PyObject_Print(converter, stderr, 0);
  1131. //fprintf(stderr, "\n");
  1132. int binary;
  1133. switch (field->type) {
  1134. case FIELD_TYPE_DECIMAL:
  1135. case FIELD_TYPE_NEWDECIMAL:
  1136. case FIELD_TYPE_TIMESTAMP:
  1137. case FIELD_TYPE_DATETIME:
  1138. case FIELD_TYPE_TIME:
  1139. case FIELD_TYPE_DATE:
  1140. binary = 0; // pass str, because these converters expect it
  1141. break;
  1142. default: // Default to just passing bytes
  1143. binary = 1;
  1144. }
  1145. return PyObject_CallFunction(converter,
  1146. binary ? "y#" : "s#",
  1147. rowitem, (Py_ssize_t)length);
  1148. }
  1149. static PyObject *
  1150. _mysql_row_to_tuple(
  1151. _mysql_ResultObject *self,
  1152. MYSQL_ROW row,
  1153. PyObject *unused)
  1154. {
  1155. unsigned int n, i;
  1156. unsigned long *length;
  1157. PyObject *r, *c;
  1158. MYSQL_FIELD *fields;
  1159. n = mysql_num_fields(self->result);
  1160. if (!(r = PyTuple_New(n))) return NULL;
  1161. length = mysql_fetch_lengths(self->result);
  1162. fields = mysql_fetch_fields(self->result);
  1163. for (i=0; i<n; i++) {
  1164. PyObject *v;
  1165. c = PyTuple_GET_ITEM(self->converter, i);
  1166. v = _mysql_field_to_python(c, row[i], length[i], &fields[i], self->encoding);
  1167. if (!v) goto error;
  1168. PyTuple_SET_ITEM(r, i, v);
  1169. }
  1170. return r;
  1171. error:
  1172. Py_XDECREF(r);
  1173. return NULL;
  1174. }
  1175. static PyObject *
  1176. _mysql_row_to_dict(
  1177. _mysql_ResultObject *self,
  1178. MYSQL_ROW row,
  1179. PyObject *cache)
  1180. {
  1181. unsigned int n, i;
  1182. unsigned long *length;
  1183. PyObject *r, *c;
  1184. MYSQL_FIELD *fields;
  1185. n = mysql_num_fields(self->result);
  1186. if (!(r = PyDict_New())) return NULL;
  1187. length = mysql_fetch_lengths(self->result);
  1188. fields = mysql_fetch_fields(self->result);
  1189. for (i=0; i<n; i++) {
  1190. PyObject *v;
  1191. c = PyTuple_GET_ITEM(self->converter, i);
  1192. v = _mysql_field_to_python(c, row[i], length[i], &fields[i], self->encoding);
  1193. if (!v) goto error;
  1194. PyObject *pyname = PyUnicode_FromString(fields[i].name);
  1195. if (pyname == NULL) {
  1196. Py_DECREF(v);
  1197. goto error;
  1198. }
  1199. int err = PyDict_Contains(r, pyname);
  1200. if (err < 0) { // error
  1201. Py_DECREF(v);
  1202. goto error;
  1203. }
  1204. if (err) { // duplicate
  1205. Py_DECREF(pyname);
  1206. pyname = PyUnicode_FromFormat("%s.%s", fields[i].table, fields[i].name);
  1207. if (pyname == NULL) {
  1208. Py_DECREF(v);
  1209. goto error;
  1210. }
  1211. }
  1212. err = PyDict_SetItem(r, pyname, v);
  1213. if (cache) {
  1214. PyTuple_SET_ITEM(cache, i, pyname);
  1215. } else {
  1216. Py_DECREF(pyname);
  1217. }
  1218. Py_DECREF(v);
  1219. if (err) {
  1220. goto error;
  1221. }
  1222. }
  1223. return r;
  1224. error:
  1225. Py_DECREF(r);
  1226. return NULL;
  1227. }
  1228. static PyObject *
  1229. _mysql_row_to_dict_old(
  1230. _mysql_ResultObject *self,
  1231. MYSQL_ROW row,
  1232. PyObject *cache)
  1233. {
  1234. unsigned int n, i;
  1235. unsigned long *length;
  1236. PyObject *r, *c;
  1237. MYSQL_FIELD *fields;
  1238. n = mysql_num_fields(self->result);
  1239. if (!(r = PyDict_New())) return NULL;
  1240. length = mysql_fetch_lengths(self->result);
  1241. fields = mysql_fetch_fields(self->result);
  1242. for (i=0; i<n; i++) {
  1243. PyObject *v;
  1244. c = PyTuple_GET_ITEM(self->converter, i);
  1245. v = _mysql_field_to_python(c, row[i], length[i], &fields[i], self->encoding);
  1246. if (!v) {
  1247. goto error;
  1248. }
  1249. PyObject *pyname;
  1250. if (strlen(fields[i].table)) {
  1251. pyname = PyUnicode_FromFormat("%s.%s", fields[i].table, fields[i].name);
  1252. } else {
  1253. pyname = PyUnicode_FromString(fields[i].name);
  1254. }
  1255. int err = PyDict_SetItem(r, pyname, v);
  1256. Py_DECREF(v);
  1257. if (cache) {
  1258. PyTuple_SET_ITEM(cache, i, pyname);
  1259. } else {
  1260. Py_DECREF(pyname);
  1261. }
  1262. if (err) {
  1263. goto error;
  1264. }
  1265. }
  1266. return r;
  1267. error:
  1268. Py_XDECREF(r);
  1269. return NULL;
  1270. }
  1271. static PyObject *
  1272. _mysql_row_to_dict_cached(
  1273. _mysql_ResultObject *self,
  1274. MYSQL_ROW row,
  1275. PyObject *cache)
  1276. {
  1277. PyObject *r = PyDict_New();
  1278. if (!r) {
  1279. return NULL;
  1280. }
  1281. unsigned int n = mysql_num_fields(self->result);
  1282. unsigned long *length = mysql_fetch_lengths(self->result);
  1283. MYSQL_FIELD *fields = mysql_fetch_fields(self->result);
  1284. for (unsigned int i=0; i<n; i++) {
  1285. PyObject *c = PyTuple_GET_ITEM(self->converter, i);
  1286. PyObject *v = _mysql_field_to_python(c, row[i], length[i], &fields[i], self->encoding);
  1287. if (!v) {
  1288. goto error;
  1289. }
  1290. PyObject *pyname = PyTuple_GET_ITEM(cache, i); // borrowed
  1291. int err = PyDict_SetItem(r, pyname, v);
  1292. Py_DECREF(v);
  1293. if (err) {
  1294. goto error;
  1295. }
  1296. }
  1297. return r;
  1298. error:
  1299. Py_XDECREF(r);
  1300. return NULL;
  1301. }
  1302. typedef PyObject *_convertfunc(_mysql_ResultObject *, MYSQL_ROW, PyObject *);
  1303. static _convertfunc * const row_converters[] = {
  1304. _mysql_row_to_tuple,
  1305. _mysql_row_to_dict,
  1306. _mysql_row_to_dict_old
  1307. };
  1308. Py_ssize_t
  1309. _mysql__fetch_row(
  1310. _mysql_ResultObject *self,
  1311. PyObject *r, /* list object */
  1312. Py_ssize_t maxrows,
  1313. int how)
  1314. {
  1315. _convertfunc *convert_row = row_converters[how];
  1316. PyObject *cache = NULL;
  1317. if (maxrows > 0 && how > 0) {
  1318. cache = PyTuple_New(mysql_num_fields(self->result));
  1319. if (!cache) {
  1320. return -1;
  1321. }
  1322. }
  1323. Py_ssize_t i;
  1324. for (i = 0; i < maxrows; i++) {
  1325. MYSQL_ROW row;
  1326. if (!self->use)
  1327. row = mysql_fetch_row(self->result);
  1328. else {
  1329. Py_BEGIN_ALLOW_THREADS
  1330. row = mysql_fetch_row(self->result);
  1331. Py_END_ALLOW_THREADS
  1332. }
  1333. if (!row && mysql_errno(&(((_mysql_ConnectionObject *)(self->conn))->connection))) {
  1334. _mysql_Exception((_mysql_ConnectionObject *)self->conn);
  1335. goto error;
  1336. }
  1337. if (!row) {
  1338. break;
  1339. }
  1340. PyObject *v = convert_row(self, row, cache);
  1341. if (!v) {
  1342. goto error;
  1343. }
  1344. if (cache) {
  1345. convert_row = _mysql_row_to_dict_cached;
  1346. }
  1347. if (PyList_Append(r, v)) {
  1348. Py_DECREF(v);
  1349. goto error;
  1350. }
  1351. Py_DECREF(v);
  1352. }
  1353. Py_XDECREF(cache);
  1354. return i;
  1355. error:
  1356. Py_XDECREF(cache);
  1357. return -1;
  1358. }
  1359. static char _mysql_ResultObject_fetch_row__doc__[] =
  1360. "fetch_row([maxrows, how]) -- Fetches up to maxrows as a tuple.\n\
  1361. The rows are formatted according to how:\n\
  1362. \n\
  1363. 0 -- tuples (default)\n\
  1364. 1 -- dictionaries, key=column or table.column if duplicated\n\
  1365. 2 -- dictionaries, key=table.column\n\
  1366. ";
  1367. static PyObject *
  1368. _mysql_ResultObject_fetch_row(
  1369. _mysql_ResultObject *self,
  1370. PyObject *args,
  1371. PyObject *kwargs)
  1372. {
  1373. static char *kwlist[] = {"maxrows", "how", NULL };
  1374. int maxrows=1, how=0;
  1375. PyObject *r=NULL;
  1376. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:fetch_row", kwlist,
  1377. &maxrows, &how))
  1378. return NULL;
  1379. check_result_connection(self);
  1380. if (how >= (int)(sizeof(row_converters) / sizeof(row_converters[0]))) {
  1381. PyErr_SetString(PyExc_ValueError, "how out of range");
  1382. return NULL;
  1383. }
  1384. if (!maxrows) {
  1385. if (self->use) {
  1386. maxrows = INT_MAX;
  1387. } else {
  1388. // todo: preallocate.
  1389. maxrows = (Py_ssize_t) mysql_num_rows(self->result);
  1390. }
  1391. }
  1392. if (!(r = PyList_New(0))) goto error;
  1393. Py_ssize_t rowsadded = _mysql__fetch_row(self, r, maxrows, how);
  1394. if (rowsadded == -1) goto error;
  1395. /* DB-API allows return rows as list.
  1396. * But we need to return list because Django expecting tuple.
  1397. */
  1398. PyObject *t = PyList_AsTuple(r);
  1399. Py_DECREF(r);
  1400. return t;
  1401. error:
  1402. Py_XDECREF(r);
  1403. return NULL;
  1404. }
  1405. static const char _mysql_ResultObject_discard__doc__[] =
  1406. "discard() -- Discard remaining rows in the resultset.";
  1407. static PyObject *
  1408. _mysql_ResultObject_discard(
  1409. _mysql_ResultObject *self,
  1410. PyObject *noargs)
  1411. {
  1412. check_result_connection(self);
  1413. MYSQL_ROW row;
  1414. Py_BEGIN_ALLOW_THREADS
  1415. while (NULL != (row = mysql_fetch_row(self->result))) {
  1416. // do nothing
  1417. }
  1418. Py_END_ALLOW_THREADS
  1419. _mysql_ConnectionObject *conn = (_mysql_ConnectionObject *)self->conn;
  1420. if (mysql_errno(&conn->connection)) {
  1421. return _mysql_Exception(conn);
  1422. }
  1423. Py_RETURN_NONE;
  1424. }
  1425. static char _mysql_ConnectionObject_change_user__doc__[] =
  1426. "Changes the user and causes the database specified by db to\n\
  1427. become the default (current) database on the connection\n\
  1428. specified by mysql. In subsequent queries, this database is\n\
  1429. the default for table references that do not include an\n\
  1430. explicit database specifier.\n\
  1431. \n\
  1432. This function was introduced in MySQL Version 3.23.3.\n\
  1433. \n\
  1434. Fails unless the connected user can be authenticated or if he\n\
  1435. doesn't have permission to use the database. In this case the\n\
  1436. user and database are not changed.\n\
  1437. \n\
  1438. The db parameter may be set to None if you don't want to have\n\
  1439. a default database.\n\
  1440. ";
  1441. static PyObject *
  1442. _mysql_ConnectionObject_change_user(
  1443. _mysql_ConnectionObject *self,
  1444. PyObject *args,
  1445. PyObject *kwargs)
  1446. {
  1447. char *user, *pwd=NULL, *db=NULL;
  1448. int r;
  1449. static char *kwlist[] = { "user", "passwd", "db", NULL } ;
  1450. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ss:change_user",
  1451. kwlist, &user, &pwd, &db))
  1452. return NULL;
  1453. check_connection(self);
  1454. Py_BEGIN_ALLOW_THREADS
  1455. r = mysql_change_user(&(self->connection), user, pwd, db);
  1456. Py_END_ALLOW_THREADS
  1457. if (r) return _mysql_Exception(self);
  1458. Py_RETURN_NONE;
  1459. }
  1460. static char _mysql_ConnectionObject_character_set_name__doc__[] =
  1461. "Returns the default character set for the current connection.\n\
  1462. Non-standard.\n\
  1463. ";
  1464. static PyObject *
  1465. _mysql_ConnectionObject_character_set_name(
  1466. _mysql_ConnectionObject *self,
  1467. PyObject *noargs)
  1468. {
  1469. const char *s;
  1470. check_connection(self);
  1471. s = mysql_character_set_name(&(self->connection));
  1472. return PyUnicode_FromString(s);
  1473. }
  1474. static char _mysql_ConnectionObject_set_character_set__doc__[] =
  1475. "Sets the default character set for the current connection.\n\
  1476. Non-standard.\n\
  1477. ";
  1478. static PyObject *
  1479. _mysql_ConnectionObject_set_character_set(
  1480. _mysql_ConnectionObject *self,
  1481. PyObject *args)
  1482. {
  1483. const char *s;
  1484. int err;
  1485. if (!PyArg_ParseTuple(args, "s", &s)) return NULL;
  1486. check_connection(self);
  1487. Py_BEGIN_ALLOW_THREADS
  1488. err = mysql_set_character_set(&(self->connection), s);
  1489. Py_END_ALLOW_THREADS
  1490. if (err) return _mysql_Exception(self);
  1491. Py_RETURN_NONE;
  1492. }
  1493. #if MYSQL_VERSION_ID >= 50010
  1494. static char _mysql_ConnectionObject_get_character_set_info__doc__[] =
  1495. "Returns a dict with information about the current character set:\n\
  1496. \n\
  1497. collation\n\
  1498. collation name\n\
  1499. name\n\
  1500. character set name\n\
  1501. comment\n\
  1502. comment or descriptive name\n\
  1503. dir\n\
  1504. character set directory\n\
  1505. mbminlen\n\
  1506. min. length for multibyte string\n\
  1507. mbmaxlen\n\
  1508. max. length for multibyte string\n\
  1509. \n\
  1510. Not all keys may be present, particularly dir.\n\
  1511. \n\
  1512. Non-standard.\n\
  1513. ";
  1514. static PyObject *
  1515. _mysql_ConnectionObject_get_character_set_info(
  1516. _mysql_ConnectionObject *self,
  1517. PyObject *noargs)
  1518. {
  1519. PyObject *result;
  1520. MY_CHARSET_INFO cs;
  1521. check_connection(self);
  1522. mysql_get_character_set_info(&(self->connection), &cs);
  1523. if (!(result = PyDict_New())) return NULL;
  1524. if (cs.csname)
  1525. PyDict_SetItemString(result, "name", PyUnicode_FromString(cs.csname));
  1526. if (cs.name)
  1527. PyDict_SetItemString(result, "collation", PyUnicode_FromString(cs.name));
  1528. if (cs.comment)
  1529. PyDict_SetItemString(result, "comment", PyUnicode_FromString(cs.comment));
  1530. if (cs.dir)
  1531. PyDict_SetItemString(result, "dir", PyUnicode_FromString(cs.dir));
  1532. PyDict_SetItemString(result, "mbminlen", PyLong_FromLong(cs.mbminlen));
  1533. PyDict_SetItemString(result, "mbmaxlen", PyLong_FromLong(cs.mbmaxlen));
  1534. return result;
  1535. }
  1536. #endif
  1537. static char _mysql_ConnectionObject_get_native_connection__doc__[] =
  1538. "Return the internal MYSQL* wrapped in a PyCapsule object.\n\
  1539. NOTE: this is a private API introduced ONLY for XTA integration,\n\
  1540. don't use it for different use cases.\n\
  1541. This method is supported only for XTA integration and support must\n\
  1542. be asked to LIXA project: http://www.tiian.org/lixa/\n\
  1543. Please DO NOT ask support to PyMySQL/mysqlclient-python project.\n\
  1544. ";
  1545. static PyObject *
  1546. _mysql_ConnectionObject_get_native_connection(
  1547. _mysql_ConnectionObject *self,
  1548. PyObject *noargs)
  1549. {
  1550. PyObject *result;
  1551. check_connection(self);
  1552. result = PyCapsule_New(&(self->connection),
  1553. "_mysql.connection.native_connection", NULL);
  1554. return result;
  1555. }
  1556. static char _mysql_get_client_info__doc__[] =
  1557. "get_client_info() -- Returns a string that represents\n\
  1558. the client library version.";
  1559. static PyObject *
  1560. _mysql_get_client_info(
  1561. PyObject *self,
  1562. PyObject *noargs)
  1563. {
  1564. return PyUnicode_FromString(mysql_get_client_info());
  1565. }
  1566. static char _mysql_ConnectionObject_get_host_info__doc__[] =
  1567. "Returns a string that represents the MySQL client library\n\
  1568. version. Non-standard.\n\
  1569. ";
  1570. static PyObject *
  1571. _mysql_ConnectionObject_get_host_info(
  1572. _mysql_ConnectionObject *self,
  1573. PyObject *noargs)
  1574. {
  1575. check_connection(self);
  1576. return PyUnicode_FromString(mysql_get_host_info(&(self->connection)));
  1577. }
  1578. static char _mysql_ConnectionObject_get_proto_info__doc__[] =
  1579. "Returns an unsigned integer representing the protocol version\n\
  1580. used by the current connection. Non-standard.\n\
  1581. ";
  1582. static PyObject *
  1583. _mysql_ConnectionObject_get_proto_info(
  1584. _mysql_ConnectionObject *self,
  1585. PyObject *noargs)
  1586. {
  1587. check_connection(self);
  1588. return PyLong_FromLong((long)mysql_get_proto_info(&(self->connection)));
  1589. }
  1590. static char _mysql_ConnectionObject_get_server_info__doc__[] =
  1591. "Returns a string that represents the server version number.\n\
  1592. Non-standard.\n\
  1593. ";
  1594. static PyObject *
  1595. _mysql_ConnectionObject_get_server_info(
  1596. _mysql_ConnectionObject *self,
  1597. PyObject *noargs)
  1598. {
  1599. check_connection(self);
  1600. return PyUnicode_FromString(mysql_get_server_info(&(self->connection)));
  1601. }
  1602. static char _mysql_ConnectionObject_info__doc__[] =
  1603. "Retrieves a string providing information about the most\n\
  1604. recently executed query. Non-standard. Use messages or\n\
  1605. Cursor.messages.\n\
  1606. ";
  1607. static PyObject *
  1608. _mysql_ConnectionObject_info(
  1609. _mysql_ConnectionObject *self,
  1610. PyObject *noargs)
  1611. {
  1612. const char *s;
  1613. check_connection(self);
  1614. s = mysql_info(&(self->connection));
  1615. if (s) return PyUnicode_FromString(s);
  1616. Py_RETURN_NONE;
  1617. }
  1618. static char _mysql_ConnectionObject_insert_id__doc__[] =
  1619. "Returns the ID generated for an AUTO_INCREMENT column by the previous\n\
  1620. query. Use this function after you have performed an INSERT query into a\n\
  1621. table that contains an AUTO_INCREMENT field.\n\
  1622. \n\
  1623. Note that this returns 0 if the previous query does not\n\
  1624. generate an AUTO_INCREMENT value. If you need to save the value for\n\
  1625. later, be sure to call this immediately after the query\n\
  1626. that generates the value.\n\
  1627. \n\
  1628. The ID is updated after INSERT and UPDATE statements that generate\n\
  1629. an AUTO_INCREMENT value or that set a column value to\n\
  1630. LAST_INSERT_ID(expr). See section 6.3.5.2 Miscellaneous Functions\n\
  1631. in the MySQL documentation.\n\
  1632. \n\
  1633. Also note that the value of the SQL LAST_INSERT_ID() function always\n\
  1634. contains the most recently generated AUTO_INCREMENT value, and is not\n\
  1635. reset between queries because the value of that function is maintained\n\
  1636. in the server.\n\
  1637. " ;
  1638. static PyObject *
  1639. _mysql_ConnectionObject_insert_id(
  1640. _mysql_ConnectionObject *self,
  1641. PyObject *noargs)
  1642. {
  1643. my_ulonglong r;
  1644. check_connection(self);
  1645. r = mysql_insert_id(&(self->connection));
  1646. return PyLong_FromUnsignedLongLong(r);
  1647. }
  1648. static char _mysql_ConnectionObject_kill__doc__[] =
  1649. "Asks the server to kill the thread specified by pid.\n\
  1650. Non-standard. Deprecated.";
  1651. static PyObject *
  1652. _mysql_ConnectionObject_kill(
  1653. _mysql_ConnectionObject *self,
  1654. PyObject *args)
  1655. {
  1656. unsigned long pid;
  1657. int r;
  1658. char query[50];
  1659. if (!PyArg_ParseTuple(args, "k:kill", &pid)) return NULL;
  1660. check_connection(self);
  1661. snprintf(query, 50, "KILL %lu", pid);
  1662. Py_BEGIN_ALLOW_THREADS
  1663. r = mysql_query(&(self->connection), query);
  1664. Py_END_ALLOW_THREADS
  1665. if (r) return _mysql_Exception(self);
  1666. Py_RETURN_NONE;
  1667. }
  1668. static char _mysql_ConnectionObject_field_count__doc__[] =
  1669. "Returns the number of columns for the most recent query on the\n\
  1670. connection. Non-standard. Will probably give you bogus results\n\
  1671. on most cursor classes. Use Cursor.rowcount.\n\
  1672. ";
  1673. static PyObject *
  1674. _mysql_ConnectionObject_field_count(
  1675. _mysql_ConnectionObject *self,
  1676. PyObject *noargs)
  1677. {
  1678. check_connection(self);
  1679. return PyLong_FromLong((long)mysql_field_count(&(self->connection)));
  1680. }
  1681. static char _mysql_ConnectionObject_fileno__doc__[] =
  1682. "Return file descriptor of the underlying libmysqlclient connection.\n\
  1683. This provides raw access to the underlying network connection.\n\
  1684. ";
  1685. static PyObject *
  1686. _mysql_ConnectionObject_fileno(
  1687. _mysql_ConnectionObject *self,
  1688. PyObject *noargs)
  1689. {
  1690. check_connection(self);
  1691. return PyLong_FromLong(self->connection.net.fd);
  1692. }
  1693. static char _mysql_ResultObject_num_fields__doc__[] =
  1694. "Returns the number of fields (column) in the result." ;
  1695. static PyObject *
  1696. _mysql_ResultObject_num_fields(
  1697. _mysql_ResultObject *self,
  1698. PyObject *noargs)
  1699. {
  1700. check_result_connection(self);
  1701. return PyLong_FromLong((long)mysql_num_fields(self->result));
  1702. }
  1703. static char _mysql_ResultObject_num_rows__doc__[] =
  1704. "Returns the number of rows in the result set. Note that if\n\
  1705. use=1, this will not return a valid value until the entire result\n\
  1706. set has been read.\n\
  1707. ";
  1708. static PyObject *
  1709. _mysql_ResultObject_num_rows(
  1710. _mysql_ResultObject *self,
  1711. PyObject *noargs)
  1712. {
  1713. check_result_connection(self);
  1714. return PyLong_FromUnsignedLongLong(mysql_num_rows(self->result));
  1715. }
  1716. static char _mysql_ConnectionObject_ping__doc__[] =
  1717. "Checks whether or not the connection to the server is working.\n\
  1718. \n\
  1719. This function can be used by clients that remain idle for a\n\
  1720. long while, to check whether or not the server has closed the\n\
  1721. connection.\n\
  1722. \n\
  1723. New in 1.2.2: Accepts an optional reconnect parameter. If True,\n\
  1724. then the client will attempt reconnection. Note that this setting\n\
  1725. is persistent. By default, this is on in MySQL<5.0.3, and off\n\
  1726. thereafter.\n\
  1727. MySQL 8.0.33 deprecated the MYSQL_OPT_RECONNECT option so reconnect\n\
  1728. parameter is also deprecated in mysqlclient 2.2.1.\n\
  1729. \n\
  1730. Non-standard. You should assume that ping() performs an\n\
  1731. implicit rollback; use only when starting a new transaction.\n\
  1732. You have been warned.\n\
  1733. ";
  1734. static PyObject *
  1735. _mysql_ConnectionObject_ping(
  1736. _mysql_ConnectionObject *self,
  1737. PyObject *args)
  1738. {
  1739. int reconnect = 0;
  1740. if (!PyArg_ParseTuple(args, "|p", &reconnect)) return NULL;
  1741. check_connection(self);
  1742. if (reconnect != (self->reconnect == true)) {
  1743. // libmysqlclient show warning to stderr when MYSQL_OPT_RECONNECT is used.
  1744. // so we avoid using it as possible for now.
  1745. // TODO: Warn when reconnect is true.
  1746. // MySQL 8.0.33 show warning to stderr already.
  1747. // We will emit Pytohn warning in future.
  1748. my_bool recon = (my_bool)reconnect;
  1749. mysql_options(&self->connection, MYSQL_OPT_RECONNECT, &recon);
  1750. self->reconnect = (bool)reconnect;
  1751. }
  1752. int r;
  1753. Py_BEGIN_ALLOW_THREADS
  1754. r = mysql_ping(&(self->connection));
  1755. Py_END_ALLOW_THREADS
  1756. if (r) return _mysql_Exception(self);
  1757. Py_RETURN_NONE;
  1758. }
  1759. static char _mysql_ConnectionObject_query__doc__[] =
  1760. "Execute a query. store_result() or use_result() will get the\n\
  1761. result set, if any. Non-standard. Use cursor() to create a cursor,\n\
  1762. then cursor.execute().\n\
  1763. " ;
  1764. static PyObject *
  1765. _mysql_ConnectionObject_query(
  1766. _mysql_ConnectionObject *self,
  1767. PyObject *args)
  1768. {
  1769. char *query;
  1770. Py_ssize_t len;
  1771. int r;
  1772. if (!PyArg_ParseTuple(args, "s#:query", &query, &len)) return NULL;
  1773. check_connection(self);
  1774. Py_BEGIN_ALLOW_THREADS
  1775. r = mysql_real_query(&(self->connection), query, len);
  1776. Py_END_ALLOW_THREADS
  1777. if (r) return _mysql_Exception(self);
  1778. Py_RETURN_NONE;
  1779. }
  1780. static char _mysql_ConnectionObject_send_query__doc__[] =
  1781. "Send a query. Same to query() except not wait response.\n\n\
  1782. Use read_query_result() before calling store_result() or use_result()\n";
  1783. static PyObject *
  1784. _mysql_ConnectionObject_send_query(
  1785. _mysql_ConnectionObject *self,
  1786. PyObject *args)
  1787. {
  1788. char *query;
  1789. Py_ssize_t len;
  1790. int r;
  1791. MYSQL *mysql = &(self->connection);
  1792. if (!PyArg_ParseTuple(args, "s#:query", &query, &len)) return NULL;
  1793. check_connection(self);
  1794. Py_BEGIN_ALLOW_THREADS
  1795. r = mysql_send_query(mysql, query, len);
  1796. Py_END_ALLOW_THREADS
  1797. if (r) return _mysql_Exception(self);
  1798. Py_RETURN_NONE;
  1799. }
  1800. static char _mysql_ConnectionObject_read_query_result__doc__[] =
  1801. "Read result of query sent by send_query().\n";
  1802. static PyObject *
  1803. _mysql_ConnectionObject_read_query_result(
  1804. _mysql_ConnectionObject *self,
  1805. PyObject *noargs)
  1806. {
  1807. int r;
  1808. MYSQL *mysql = &(self->connection);
  1809. check_connection(self);
  1810. Py_BEGIN_ALLOW_THREADS
  1811. r = (int)mysql_read_query_result(mysql);
  1812. Py_END_ALLOW_THREADS
  1813. if (r) return _mysql_Exception(self);
  1814. Py_RETURN_NONE;
  1815. }
  1816. static char _mysql_ConnectionObject_select_db__doc__[] =
  1817. "Causes the database specified by db to become the default\n\
  1818. (current) database on the connection specified by mysql. In subsequent\n\
  1819. queries, this database is the default for table references that do not\n\
  1820. include an explicit database specifier.\n\
  1821. \n\
  1822. Fails unless the connected user can be authenticated as having\n\
  1823. permission to use the database.\n\
  1824. \n\
  1825. Non-standard.\n\
  1826. ";
  1827. static PyObject *
  1828. _mysql_ConnectionObject_select_db(
  1829. _mysql_ConnectionObject *self,
  1830. PyObject *args)
  1831. {
  1832. char *db;
  1833. int r;
  1834. if (!PyArg_ParseTuple(args, "s:select_db", &db)) return NULL;
  1835. check_connection(self);
  1836. Py_BEGIN_ALLOW_THREADS
  1837. r = mysql_select_db(&(self->connection), db);
  1838. Py_END_ALLOW_THREADS
  1839. if (r) return _mysql_Exception(self);
  1840. Py_RETURN_NONE;
  1841. }
  1842. static char _mysql_ConnectionObject_shutdown__doc__[] =
  1843. "Asks the database server to shut down. The connected user must\n\
  1844. have shutdown privileges. Non-standard. Deprecated.\n\
  1845. ";
  1846. static PyObject *
  1847. _mysql_ConnectionObject_shutdown(
  1848. _mysql_ConnectionObject *self,
  1849. PyObject *noargs)
  1850. {
  1851. int r;
  1852. check_connection(self);
  1853. Py_BEGIN_ALLOW_THREADS
  1854. r = mysql_query(&(self->connection), "SHUTDOWN");
  1855. Py_END_ALLOW_THREADS
  1856. if (r) return _mysql_Exception(self);
  1857. Py_RETURN_NONE;
  1858. }
  1859. static char _mysql_ConnectionObject_stat__doc__[] =
  1860. "Returns a character string containing information similar to\n\
  1861. that provided by the mysqladmin status command. This includes\n\
  1862. uptime in seconds and the number of running threads,\n\
  1863. questions, reloads, and open tables. Non-standard.\n\
  1864. ";
  1865. static PyObject *
  1866. _mysql_ConnectionObject_stat(
  1867. _mysql_ConnectionObject *self,
  1868. PyObject *noargs)
  1869. {
  1870. const char *s;
  1871. check_connection(self);
  1872. Py_BEGIN_ALLOW_THREADS
  1873. s = mysql_stat(&(self->connection));
  1874. Py_END_ALLOW_THREADS
  1875. if (!s) return _mysql_Exception(self);
  1876. return PyUnicode_FromString(s);
  1877. }
  1878. static char _mysql_ConnectionObject_store_result__doc__[] =
  1879. "Returns a result object acquired by mysql_store_result\n\
  1880. (results stored in the client). If no results are available,\n\
  1881. None is returned. Non-standard.\n\
  1882. ";
  1883. static PyObject *
  1884. _mysql_ConnectionObject_store_result(
  1885. _mysql_ConnectionObject *self,
  1886. PyObject *noargs)
  1887. {
  1888. PyObject *arglist=NULL, *kwarglist=NULL, *result=NULL;
  1889. _mysql_ResultObject *r=NULL;
  1890. check_connection(self);
  1891. arglist = Py_BuildValue("(OiO)", self, 0, self->converter);
  1892. if (!arglist) goto error;
  1893. kwarglist = PyDict_New();
  1894. if (!kwarglist) goto error;
  1895. r = MyAlloc(_mysql_ResultObject, _mysql_ResultObject_Type);
  1896. if (!r) goto error;
  1897. if (_mysql_ResultObject_Initialize(r, arglist, kwarglist)) {
  1898. Py_DECREF(r);
  1899. goto error;
  1900. }
  1901. result = (PyObject *) r;
  1902. if (!(r->result)) {
  1903. Py_DECREF(result);
  1904. Py_INCREF(Py_None);
  1905. result = Py_None;
  1906. }
  1907. error:
  1908. Py_XDECREF(arglist);
  1909. Py_XDECREF(kwarglist);
  1910. return result;
  1911. }
  1912. static char _mysql_ConnectionObject_thread_id__doc__[] =
  1913. "Returns the thread ID of the current connection. This value\n\
  1914. can be used as an argument to kill() to kill the thread.\n\
  1915. \n\
  1916. If the connection is lost and you reconnect with ping(), the\n\
  1917. thread ID will change. This means you should not get the\n\
  1918. thread ID and store it for later. You should get it when you\n\
  1919. need it.\n\
  1920. \n\
  1921. Non-standard.";
  1922. static PyObject *
  1923. _mysql_ConnectionObject_thread_id(
  1924. _mysql_ConnectionObject *self,
  1925. PyObject *noargs)
  1926. {
  1927. unsigned long pid;
  1928. check_connection(self);
  1929. pid = mysql_thread_id(&(self->connection));
  1930. return PyLong_FromLong((long)pid);
  1931. }
  1932. static char _mysql_ConnectionObject_use_result__doc__[] =
  1933. "Returns a result object acquired by mysql_use_result\n\
  1934. (results stored in the server). If no results are available,\n\
  1935. None is returned. Non-standard.\n\
  1936. ";
  1937. static PyObject *
  1938. _mysql_ConnectionObject_use_result(
  1939. _mysql_ConnectionObject *self,
  1940. PyObject *noargs)
  1941. {
  1942. PyObject *arglist=NULL, *kwarglist=NULL, *result=NULL;
  1943. _mysql_ResultObject *r=NULL;
  1944. check_connection(self);
  1945. arglist = Py_BuildValue("(OiO)", self, 1, self->converter);
  1946. if (!arglist) return NULL;
  1947. kwarglist = PyDict_New();
  1948. if (!kwarglist) goto error;
  1949. r = MyAlloc(_mysql_ResultObject, _mysql_ResultObject_Type);
  1950. if (!r) goto error;
  1951. if (_mysql_ResultObject_Initialize(r, arglist, kwarglist)) {
  1952. Py_DECREF(r);
  1953. goto error;
  1954. }
  1955. result = (PyObject *) r;
  1956. if (!(r->result)) {
  1957. Py_DECREF(result);
  1958. Py_INCREF(Py_None);
  1959. result = Py_None;
  1960. }
  1961. error:
  1962. Py_DECREF(arglist);
  1963. Py_XDECREF(kwarglist);
  1964. return result;
  1965. }
  1966. static const char _mysql_ConnectionObject_discard_result__doc__[] =
  1967. "Discard current result set.\n\n"
  1968. "This function can be called instead of use_result() or store_result(). Non-standard.";
  1969. static PyObject *
  1970. _mysql_ConnectionObject_discard_result(
  1971. _mysql_ConnectionObject *self,
  1972. PyObject *noargs)
  1973. {
  1974. check_connection(self);
  1975. MYSQL *conn = &(self->connection);
  1976. Py_BEGIN_ALLOW_THREADS;
  1977. MYSQL_RES *res = mysql_use_result(conn);
  1978. if (res == NULL) {
  1979. Py_BLOCK_THREADS;
  1980. if (mysql_errno(conn) != 0) {
  1981. // fprintf(stderr, "mysql_use_result failed: %s\n", mysql_error(conn));
  1982. return _mysql_Exception(self);
  1983. }
  1984. Py_RETURN_NONE;
  1985. }
  1986. MYSQL_ROW row;
  1987. while (NULL != (row = mysql_fetch_row(res))) {
  1988. // do nothing.
  1989. }
  1990. mysql_free_result(res);
  1991. Py_END_ALLOW_THREADS;
  1992. if (mysql_errno(conn)) {
  1993. // fprintf(stderr, "mysql_free_result failed: %s\n", mysql_error(conn));
  1994. return _mysql_Exception(self);
  1995. }
  1996. Py_RETURN_NONE;
  1997. }
  1998. static void
  1999. _mysql_ConnectionObject_dealloc(
  2000. _mysql_ConnectionObject *self)
  2001. {
  2002. PyObject_GC_UnTrack(self);
  2003. if (self->open) {
  2004. mysql_close(&(self->connection));
  2005. self->open = false;
  2006. }
  2007. Py_CLEAR(self->converter);
  2008. MyFree(self);
  2009. }
  2010. static PyObject *
  2011. _mysql_ConnectionObject_repr(
  2012. _mysql_ConnectionObject *self)
  2013. {
  2014. char buf[300];
  2015. if (self->open)
  2016. snprintf(buf, 300, "<_mysql.connection open to '%.256s' at %p>",
  2017. self->connection.host, self);
  2018. else
  2019. snprintf(buf, 300, "<_mysql.connection closed at %p>", self);
  2020. return PyUnicode_FromString(buf);
  2021. }
  2022. static char _mysql_ResultObject_data_seek__doc__[] =
  2023. "data_seek(n) -- seek to row n of result set";
  2024. static PyObject *
  2025. _mysql_ResultObject_data_seek(
  2026. _mysql_ResultObject *self,
  2027. PyObject *args)
  2028. {
  2029. unsigned int row;
  2030. if (!PyArg_ParseTuple(args, "i:data_seek", &row)) return NULL;
  2031. check_result_connection(self);
  2032. mysql_data_seek(self->result, row);
  2033. Py_RETURN_NONE;
  2034. }
  2035. static void
  2036. _mysql_ResultObject_dealloc(
  2037. _mysql_ResultObject *self)
  2038. {
  2039. PyObject_GC_UnTrack((PyObject *)self);
  2040. mysql_free_result(self->result);
  2041. _mysql_ResultObject_clear(self);
  2042. MyFree(self);
  2043. }
  2044. static PyObject *
  2045. _mysql_ResultObject_repr(
  2046. _mysql_ResultObject *self)
  2047. {
  2048. char buf[300];
  2049. snprintf(buf, 300, "<_mysql.result object at %p>", self);
  2050. return PyUnicode_FromString(buf);
  2051. }
  2052. static PyMethodDef _mysql_ConnectionObject_methods[] = {
  2053. {
  2054. "affected_rows",
  2055. (PyCFunction)_mysql_ConnectionObject_affected_rows,
  2056. METH_NOARGS,
  2057. _mysql_ConnectionObject_affected_rows__doc__
  2058. },
  2059. {
  2060. "autocommit",
  2061. (PyCFunction)_mysql_ConnectionObject_autocommit,
  2062. METH_VARARGS,
  2063. _mysql_ConnectionObject_autocommit__doc__
  2064. },
  2065. {
  2066. "get_autocommit",
  2067. (PyCFunction)_mysql_ConnectionObject_get_autocommit,
  2068. METH_NOARGS,
  2069. _mysql_ConnectionObject_get_autocommit__doc__
  2070. },
  2071. {
  2072. "commit",
  2073. (PyCFunction)_mysql_ConnectionObject_commit,
  2074. METH_NOARGS,
  2075. _mysql_ConnectionObject_commit__doc__
  2076. },
  2077. {
  2078. "rollback",
  2079. (PyCFunction)_mysql_ConnectionObject_rollback,
  2080. METH_NOARGS,
  2081. _mysql_ConnectionObject_rollback__doc__
  2082. },
  2083. {
  2084. "next_result",
  2085. (PyCFunction)_mysql_ConnectionObject_next_result,
  2086. METH_NOARGS,
  2087. _mysql_ConnectionObject_next_result__doc__
  2088. },
  2089. {
  2090. "set_server_option",
  2091. (PyCFunction)_mysql_ConnectionObject_set_server_option,
  2092. METH_VARARGS,
  2093. _mysql_ConnectionObject_set_server_option__doc__
  2094. },
  2095. {
  2096. "sqlstate",
  2097. (PyCFunction)_mysql_ConnectionObject_sqlstate,
  2098. METH_NOARGS,
  2099. _mysql_ConnectionObject_sqlstate__doc__
  2100. },
  2101. {
  2102. "warning_count",
  2103. (PyCFunction)_mysql_ConnectionObject_warning_count,
  2104. METH_NOARGS,
  2105. _mysql_ConnectionObject_warning_count__doc__
  2106. },
  2107. {
  2108. "change_user",
  2109. (PyCFunction)_mysql_ConnectionObject_change_user,
  2110. METH_VARARGS | METH_KEYWORDS,
  2111. _mysql_ConnectionObject_change_user__doc__
  2112. },
  2113. {
  2114. "character_set_name",
  2115. (PyCFunction)_mysql_ConnectionObject_character_set_name,
  2116. METH_NOARGS,
  2117. _mysql_ConnectionObject_character_set_name__doc__
  2118. },
  2119. {
  2120. "set_character_set",
  2121. (PyCFunction)_mysql_ConnectionObject_set_character_set,
  2122. METH_VARARGS,
  2123. _mysql_ConnectionObject_set_character_set__doc__
  2124. },
  2125. #if MYSQL_VERSION_ID >= 50010
  2126. {
  2127. "get_character_set_info",
  2128. (PyCFunction)_mysql_ConnectionObject_get_character_set_info,
  2129. METH_NOARGS,
  2130. _mysql_ConnectionObject_get_character_set_info__doc__
  2131. },
  2132. #endif
  2133. {
  2134. "_get_native_connection",
  2135. (PyCFunction)_mysql_ConnectionObject_get_native_connection,
  2136. METH_NOARGS,
  2137. _mysql_ConnectionObject_get_native_connection__doc__
  2138. },
  2139. {
  2140. "close",
  2141. (PyCFunction)_mysql_ConnectionObject_close,
  2142. METH_NOARGS,
  2143. _mysql_ConnectionObject_close__doc__
  2144. },
  2145. {
  2146. "dump_debug_info",
  2147. (PyCFunction)_mysql_ConnectionObject_dump_debug_info,
  2148. METH_NOARGS,
  2149. _mysql_ConnectionObject_dump_debug_info__doc__
  2150. },
  2151. {
  2152. "escape",
  2153. (PyCFunction)_mysql_escape,
  2154. METH_VARARGS,
  2155. _mysql_escape__doc__
  2156. },
  2157. {
  2158. "escape_string",
  2159. (PyCFunction)_mysql_escape_string,
  2160. METH_VARARGS,
  2161. _mysql_escape_string__doc__
  2162. },
  2163. {
  2164. "error",
  2165. (PyCFunction)_mysql_ConnectionObject_error,
  2166. METH_NOARGS,
  2167. _mysql_ConnectionObject_error__doc__
  2168. },
  2169. {
  2170. "errno",
  2171. (PyCFunction)_mysql_ConnectionObject_errno,
  2172. METH_NOARGS,
  2173. _mysql_ConnectionObject_errno__doc__
  2174. },
  2175. {
  2176. "field_count",
  2177. (PyCFunction)_mysql_ConnectionObject_field_count,
  2178. METH_NOARGS,
  2179. _mysql_ConnectionObject_field_count__doc__
  2180. },
  2181. {
  2182. "fileno",
  2183. (PyCFunction)_mysql_ConnectionObject_fileno,
  2184. METH_NOARGS,
  2185. _mysql_ConnectionObject_fileno__doc__
  2186. },
  2187. {
  2188. "get_host_info",
  2189. (PyCFunction)_mysql_ConnectionObject_get_host_info,
  2190. METH_NOARGS,
  2191. _mysql_ConnectionObject_get_host_info__doc__
  2192. },
  2193. {
  2194. "get_proto_info",
  2195. (PyCFunction)_mysql_ConnectionObject_get_proto_info,
  2196. METH_NOARGS,
  2197. _mysql_ConnectionObject_get_proto_info__doc__
  2198. },
  2199. {
  2200. "get_server_info",
  2201. (PyCFunction)_mysql_ConnectionObject_get_server_info,
  2202. METH_NOARGS,
  2203. _mysql_ConnectionObject_get_server_info__doc__
  2204. },
  2205. {
  2206. "info",
  2207. (PyCFunction)_mysql_ConnectionObject_info,
  2208. METH_NOARGS,
  2209. _mysql_ConnectionObject_info__doc__
  2210. },
  2211. {
  2212. "insert_id",
  2213. (PyCFunction)_mysql_ConnectionObject_insert_id,
  2214. METH_NOARGS,
  2215. _mysql_ConnectionObject_insert_id__doc__
  2216. },
  2217. {
  2218. "kill",
  2219. (PyCFunction)_mysql_ConnectionObject_kill,
  2220. METH_VARARGS,
  2221. _mysql_ConnectionObject_kill__doc__
  2222. },
  2223. {
  2224. "ping",
  2225. (PyCFunction)_mysql_ConnectionObject_ping,
  2226. METH_VARARGS,
  2227. _mysql_ConnectionObject_ping__doc__
  2228. },
  2229. {
  2230. "query",
  2231. (PyCFunction)_mysql_ConnectionObject_query,
  2232. METH_VARARGS,
  2233. _mysql_ConnectionObject_query__doc__
  2234. },
  2235. {
  2236. "send_query",
  2237. (PyCFunction)_mysql_ConnectionObject_send_query,
  2238. METH_VARARGS,
  2239. _mysql_ConnectionObject_send_query__doc__,
  2240. },
  2241. {
  2242. "read_query_result",
  2243. (PyCFunction)_mysql_ConnectionObject_read_query_result,
  2244. METH_NOARGS,
  2245. _mysql_ConnectionObject_read_query_result__doc__,
  2246. },
  2247. {
  2248. "select_db",
  2249. (PyCFunction)_mysql_ConnectionObject_select_db,
  2250. METH_VARARGS,
  2251. _mysql_ConnectionObject_select_db__doc__
  2252. },
  2253. {
  2254. "shutdown",
  2255. (PyCFunction)_mysql_ConnectionObject_shutdown,
  2256. METH_NOARGS,
  2257. _mysql_ConnectionObject_shutdown__doc__
  2258. },
  2259. {
  2260. "stat",
  2261. (PyCFunction)_mysql_ConnectionObject_stat,
  2262. METH_NOARGS,
  2263. _mysql_ConnectionObject_stat__doc__
  2264. },
  2265. {
  2266. "store_result",
  2267. (PyCFunction)_mysql_ConnectionObject_store_result,
  2268. METH_NOARGS,
  2269. _mysql_ConnectionObject_store_result__doc__
  2270. },
  2271. {
  2272. "string_literal",
  2273. (PyCFunction)_mysql_string_literal,
  2274. METH_O,
  2275. _mysql_string_literal__doc__},
  2276. {
  2277. "thread_id",
  2278. (PyCFunction)_mysql_ConnectionObject_thread_id,
  2279. METH_NOARGS,
  2280. _mysql_ConnectionObject_thread_id__doc__
  2281. },
  2282. {
  2283. "use_result",
  2284. (PyCFunction)_mysql_ConnectionObject_use_result,
  2285. METH_NOARGS,
  2286. _mysql_ConnectionObject_use_result__doc__
  2287. },
  2288. {
  2289. "discard_result",
  2290. (PyCFunction)_mysql_ConnectionObject_discard_result,
  2291. METH_NOARGS,
  2292. _mysql_ConnectionObject_discard_result__doc__
  2293. },
  2294. {NULL, NULL} /* sentinel */
  2295. };
  2296. static struct PyMemberDef _mysql_ConnectionObject_memberlist[] = {
  2297. {
  2298. "open",
  2299. T_INT,
  2300. offsetof(_mysql_ConnectionObject,open),
  2301. READONLY,
  2302. "True if connection is open"
  2303. },
  2304. {
  2305. "converter",
  2306. T_OBJECT,
  2307. offsetof(_mysql_ConnectionObject,converter),
  2308. 0,
  2309. "Type conversion mapping"
  2310. },
  2311. {
  2312. "server_capabilities",
  2313. T_ULONG,
  2314. offsetof(_mysql_ConnectionObject,connection.server_capabilities),
  2315. READONLY,
  2316. "Capabilities of server; consult MySQLdb.constants.CLIENT"
  2317. },
  2318. {
  2319. "port",
  2320. T_UINT,
  2321. offsetof(_mysql_ConnectionObject,connection.port),
  2322. READONLY,
  2323. "TCP/IP port of the server connection"
  2324. },
  2325. {
  2326. "client_flag",
  2327. T_ULONG,
  2328. offsetof(_mysql_ConnectionObject,connection.client_flag),
  2329. READONLY,
  2330. "Client flags; refer to MySQLdb.constants.CLIENT"
  2331. },
  2332. {NULL} /* Sentinel */
  2333. };
  2334. static PyMethodDef _mysql_ResultObject_methods[] = {
  2335. {
  2336. "data_seek",
  2337. (PyCFunction)_mysql_ResultObject_data_seek,
  2338. METH_VARARGS,
  2339. _mysql_ResultObject_data_seek__doc__
  2340. },
  2341. {
  2342. "describe",
  2343. (PyCFunction)_mysql_ResultObject_describe,
  2344. METH_NOARGS,
  2345. _mysql_ResultObject_describe__doc__
  2346. },
  2347. {
  2348. "fetch_row",
  2349. (PyCFunction)_mysql_ResultObject_fetch_row,
  2350. METH_VARARGS | METH_KEYWORDS,
  2351. _mysql_ResultObject_fetch_row__doc__
  2352. },
  2353. {
  2354. "discard",
  2355. (PyCFunction)_mysql_ResultObject_discard,
  2356. METH_NOARGS,
  2357. _mysql_ResultObject_discard__doc__
  2358. },
  2359. {
  2360. "field_flags",
  2361. (PyCFunction)_mysql_ResultObject_field_flags,
  2362. METH_NOARGS,
  2363. _mysql_ResultObject_field_flags__doc__
  2364. },
  2365. {
  2366. "num_fields",
  2367. (PyCFunction)_mysql_ResultObject_num_fields,
  2368. METH_NOARGS,
  2369. _mysql_ResultObject_num_fields__doc__
  2370. },
  2371. {
  2372. "num_rows",
  2373. (PyCFunction)_mysql_ResultObject_num_rows,
  2374. METH_NOARGS,
  2375. _mysql_ResultObject_num_rows__doc__
  2376. },
  2377. {NULL, NULL} /* sentinel */
  2378. };
  2379. static struct PyMemberDef _mysql_ResultObject_memberlist[] = {
  2380. {
  2381. "converter",
  2382. T_OBJECT,
  2383. offsetof(_mysql_ResultObject,converter),
  2384. READONLY,
  2385. "Type conversion mapping"
  2386. },
  2387. {
  2388. "has_next",
  2389. T_BOOL,
  2390. offsetof(_mysql_ResultObject, has_next),
  2391. READONLY,
  2392. "Has next result"
  2393. },
  2394. {NULL} /* Sentinel */
  2395. };
  2396. static PyObject *
  2397. _mysql_ConnectionObject_getattro(
  2398. _mysql_ConnectionObject *self,
  2399. PyObject *name)
  2400. {
  2401. const char *cname;
  2402. cname = PyUnicode_AsUTF8(name);
  2403. if (strcmp(cname, "closed") == 0)
  2404. return PyLong_FromLong((long)!(self->open));
  2405. return PyObject_GenericGetAttr((PyObject *)self, name);
  2406. }
  2407. static int
  2408. _mysql_ConnectionObject_setattro(
  2409. _mysql_ConnectionObject *self,
  2410. PyObject *name,
  2411. PyObject *v)
  2412. {
  2413. if (v == NULL) {
  2414. PyErr_SetString(PyExc_AttributeError,
  2415. "can't delete connection attributes");
  2416. return -1;
  2417. }
  2418. return PyObject_GenericSetAttr((PyObject *)self, name, v);
  2419. }
  2420. static int
  2421. _mysql_ResultObject_setattro(
  2422. _mysql_ResultObject *self,
  2423. PyObject *name,
  2424. PyObject *v)
  2425. {
  2426. if (v == NULL) {
  2427. PyErr_SetString(PyExc_AttributeError,
  2428. "can't delete connection attributes");
  2429. return -1;
  2430. }
  2431. return PyObject_GenericSetAttr((PyObject *)self, name, v);
  2432. }
  2433. PyTypeObject _mysql_ConnectionObject_Type = {
  2434. PyVarObject_HEAD_INIT(NULL, 0)
  2435. "_mysql.connection", /* (char *)tp_name For printing */
  2436. sizeof(_mysql_ConnectionObject),
  2437. 0,
  2438. (destructor)_mysql_ConnectionObject_dealloc, /* tp_dealloc */
  2439. 0, /*tp_print*/
  2440. 0, /* tp_getattr */
  2441. 0, /* tp_setattr */
  2442. 0, /*tp_compare*/
  2443. (reprfunc)_mysql_ConnectionObject_repr, /* tp_repr */
  2444. /* Method suites for standard classes */
  2445. 0, /* (PyNumberMethods *) tp_as_number */
  2446. 0, /* (PySequenceMethods *) tp_as_sequence */
  2447. 0, /* (PyMappingMethods *) tp_as_mapping */
  2448. /* More standard operations (here for binary compatibility) */
  2449. 0, /* (hashfunc) tp_hash */
  2450. 0, /* (ternaryfunc) tp_call */
  2451. 0, /* (reprfunc) tp_str */
  2452. (getattrofunc)_mysql_ConnectionObject_getattro, /* tp_getattro */
  2453. (setattrofunc)_mysql_ConnectionObject_setattro, /* tp_setattro */
  2454. /* Functions to access object as input/output buffer */
  2455. 0, /* (PyBufferProcs *) tp_as_buffer */
  2456. /* (tp_flags) Flags to define presence of optional/expanded features */
  2457. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
  2458. _mysql_connect__doc__, /* (char *) tp_doc Documentation string */
  2459. /* call function for all accessible objects */
  2460. (traverseproc) _mysql_ConnectionObject_traverse, /* tp_traverse */
  2461. /* delete references to contained objects */
  2462. (inquiry) _mysql_ConnectionObject_clear, /* tp_clear */
  2463. /* rich comparisons */
  2464. 0, /* (richcmpfunc) tp_richcompare */
  2465. /* weak reference enabler */
  2466. 0, /* (long) tp_weaklistoffset */
  2467. /* Iterators */
  2468. 0, /* (getiterfunc) tp_iter */
  2469. 0, /* (iternextfunc) tp_iternext */
  2470. /* Attribute descriptor and subclassing stuff */
  2471. (struct PyMethodDef *)_mysql_ConnectionObject_methods, /* tp_methods */
  2472. (struct PyMemberDef *)_mysql_ConnectionObject_memberlist, /* tp_members */
  2473. 0, /* (struct getsetlist *) tp_getset; */
  2474. 0, /* (struct _typeobject *) tp_base; */
  2475. 0, /* (PyObject *) tp_dict */
  2476. 0, /* (descrgetfunc) tp_descr_get */
  2477. 0, /* (descrsetfunc) tp_descr_set */
  2478. 0, /* (long) tp_dictoffset */
  2479. (initproc)_mysql_ConnectionObject_Initialize, /* tp_init */
  2480. NULL, /* tp_alloc */
  2481. PyType_GenericNew, /* tp_new */
  2482. NULL, /* tp_free Low-level free-memory routine */
  2483. 0, /* (PyObject *) tp_bases */
  2484. 0, /* (PyObject *) tp_mro method resolution order */
  2485. 0, /* (PyObject *) tp_defined */
  2486. } ;
  2487. PyTypeObject _mysql_ResultObject_Type = {
  2488. PyVarObject_HEAD_INIT(NULL, 0)
  2489. "_mysql.result",
  2490. sizeof(_mysql_ResultObject),
  2491. 0,
  2492. (destructor)_mysql_ResultObject_dealloc, /* tp_dealloc */
  2493. 0, /*tp_print*/
  2494. 0, /* tp_getattr */
  2495. 0, /* tp_setattr */
  2496. 0, /*tp_compare*/
  2497. (reprfunc)_mysql_ResultObject_repr, /* tp_repr */
  2498. /* Method suites for standard classes */
  2499. 0, /* (PyNumberMethods *) tp_as_number */
  2500. 0, /* (PySequenceMethods *) tp_as_sequence */
  2501. 0, /* (PyMappingMethods *) tp_as_mapping */
  2502. /* More standard operations (here for binary compatibility) */
  2503. 0, /* (hashfunc) tp_hash */
  2504. 0, /* (ternaryfunc) tp_call */
  2505. 0, /* (reprfunc) tp_str */
  2506. (getattrofunc)PyObject_GenericGetAttr, /* tp_getattro */
  2507. (setattrofunc)_mysql_ResultObject_setattro, /* tp_setattr */
  2508. /* Functions to access object as input/output buffer */
  2509. 0, /* (PyBufferProcs *) tp_as_buffer */
  2510. /* Flags to define presence of optional/expanded features */
  2511. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
  2512. _mysql_ResultObject__doc__, /* (char *) tp_doc Documentation string */
  2513. /* call function for all accessible objects */
  2514. (traverseproc) _mysql_ResultObject_traverse, /* tp_traverse */
  2515. /* delete references to contained objects */
  2516. (inquiry) _mysql_ResultObject_clear, /* tp_clear */
  2517. /* rich comparisons */
  2518. 0, /* (richcmpfunc) tp_richcompare */
  2519. /* weak reference enabler */
  2520. 0, /* (long) tp_weaklistoffset */
  2521. /* Iterators */
  2522. 0, /* (getiterfunc) tp_iter */
  2523. 0, /* (iternextfunc) tp_iternext */
  2524. /* Attribute descriptor and subclassing stuff */
  2525. (struct PyMethodDef *) _mysql_ResultObject_methods, /* tp_methods */
  2526. (struct PyMemberDef *) _mysql_ResultObject_memberlist, /*tp_members */
  2527. 0, /* (struct getsetlist *) tp_getset; */
  2528. 0, /* (struct _typeobject *) tp_base; */
  2529. 0, /* (PyObject *) tp_dict */
  2530. 0, /* (descrgetfunc) tp_descr_get */
  2531. 0, /* (descrsetfunc) tp_descr_set */
  2532. 0, /* (long) tp_dictoffset */
  2533. (initproc)_mysql_ResultObject_Initialize, /* tp_init */
  2534. NULL, /* tp_alloc */
  2535. PyType_GenericNew, /* tp_new */
  2536. NULL, /* tp_free Low-level free-memory routine */
  2537. 0, /* (PyObject *) tp_bases */
  2538. 0, /* (PyObject *) tp_mro method resolution order */
  2539. 0, /* (PyObject *) tp_defined */
  2540. };
  2541. static PyMethodDef
  2542. _mysql_methods[] = {
  2543. {
  2544. "connect",
  2545. (PyCFunction)_mysql_connect,
  2546. METH_VARARGS | METH_KEYWORDS,
  2547. _mysql_connect__doc__
  2548. },
  2549. {
  2550. "debug",
  2551. (PyCFunction)_mysql_debug,
  2552. METH_VARARGS,
  2553. _mysql_debug__doc__
  2554. },
  2555. {
  2556. "escape",
  2557. (PyCFunction)_mysql_escape,
  2558. METH_VARARGS,
  2559. _mysql_escape__doc__
  2560. },
  2561. {
  2562. "escape_string",
  2563. (PyCFunction)_mysql_escape_string,
  2564. METH_VARARGS,
  2565. _mysql_escape_string__doc__
  2566. },
  2567. {
  2568. "string_literal",
  2569. (PyCFunction)_mysql_string_literal,
  2570. METH_O,
  2571. _mysql_string_literal__doc__
  2572. },
  2573. {
  2574. "get_client_info",
  2575. (PyCFunction)_mysql_get_client_info,
  2576. METH_NOARGS,
  2577. _mysql_get_client_info__doc__
  2578. },
  2579. {NULL, NULL} /* sentinel */
  2580. };
  2581. static PyObject *
  2582. _mysql_NewException(
  2583. PyObject *dict,
  2584. PyObject *edict,
  2585. char *name)
  2586. {
  2587. PyObject *e;
  2588. if (!(e = PyDict_GetItemString(edict, name)))
  2589. return NULL;
  2590. if (PyDict_SetItemString(dict, name, e))
  2591. return NULL;
  2592. Py_INCREF(e);
  2593. return e;
  2594. }
  2595. #define QUOTE(X) _QUOTE(X)
  2596. #define _QUOTE(X) #X
  2597. static char _mysql___doc__[] =
  2598. "an adaptation of the MySQL C API (mostly)\n\
  2599. \n\
  2600. You probably are better off using MySQLdb instead of using this\n\
  2601. module directly.\n\
  2602. \n\
  2603. In general, renaming goes from mysql_* to _mysql.*. _mysql.connect()\n\
  2604. returns a connection object (MYSQL). Functions which expect MYSQL * as\n\
  2605. an argument are now methods of the connection object. A number of things\n\
  2606. return result objects (MYSQL_RES). Functions which expect MYSQL_RES * as\n\
  2607. an argument are now methods of the result object. Deprecated functions\n\
  2608. (as of 3.23) are NOT implemented.\n\
  2609. ";
  2610. static struct PyModuleDef _mysqlmodule = {
  2611. PyModuleDef_HEAD_INIT,
  2612. "_mysql", /* name of module */
  2613. _mysql___doc__, /* module documentation, may be NULL */
  2614. -1, /* size of per-interpreter state of the module,
  2615. or -1 if the module keeps state in global variables. */
  2616. _mysql_methods
  2617. };
  2618. PyMODINIT_FUNC
  2619. PyInit__mysql(void)
  2620. {
  2621. PyObject *dict, *module, *emod, *edict;
  2622. if (mysql_library_init(0, NULL, NULL)) {
  2623. PyErr_SetString(PyExc_ImportError, "_mysql: mysql_library_init failed");
  2624. return NULL;
  2625. }
  2626. if (PyType_Ready(&_mysql_ConnectionObject_Type) < 0)
  2627. return NULL;
  2628. if (PyType_Ready(&_mysql_ResultObject_Type) < 0)
  2629. return NULL;
  2630. module = PyModule_Create(&_mysqlmodule);
  2631. if (!module) return module; /* this really should never happen */
  2632. if (!(dict = PyModule_GetDict(module))) goto error;
  2633. if (PyDict_SetItemString(dict, "version_info",
  2634. PyRun_String(QUOTE(version_info), Py_eval_input,
  2635. dict, dict)))
  2636. goto error;
  2637. if (PyDict_SetItemString(dict, "__version__",
  2638. PyUnicode_FromString(QUOTE(__version__))))
  2639. goto error;
  2640. if (PyDict_SetItemString(dict, "connection",
  2641. (PyObject *)&_mysql_ConnectionObject_Type))
  2642. goto error;
  2643. Py_INCREF(&_mysql_ConnectionObject_Type);
  2644. if (PyDict_SetItemString(dict, "result",
  2645. (PyObject *)&_mysql_ResultObject_Type))
  2646. goto error;
  2647. Py_INCREF(&_mysql_ResultObject_Type);
  2648. if (!(emod = PyImport_ImportModule("MySQLdb._exceptions"))) {
  2649. PyErr_Print();
  2650. goto error;
  2651. }
  2652. if (!(edict = PyModule_GetDict(emod))) goto error;
  2653. if (!(_mysql_MySQLError =
  2654. _mysql_NewException(dict, edict, "MySQLError")))
  2655. goto error;
  2656. if (!(_mysql_Warning =
  2657. _mysql_NewException(dict, edict, "Warning")))
  2658. goto error;
  2659. if (!(_mysql_Error =
  2660. _mysql_NewException(dict, edict, "Error")))
  2661. goto error;
  2662. if (!(_mysql_InterfaceError =
  2663. _mysql_NewException(dict, edict, "InterfaceError")))
  2664. goto error;
  2665. if (!(_mysql_DatabaseError =
  2666. _mysql_NewException(dict, edict, "DatabaseError")))
  2667. goto error;
  2668. if (!(_mysql_DataError =
  2669. _mysql_NewException(dict, edict, "DataError")))
  2670. goto error;
  2671. if (!(_mysql_OperationalError =
  2672. _mysql_NewException(dict, edict, "OperationalError")))
  2673. goto error;
  2674. if (!(_mysql_IntegrityError =
  2675. _mysql_NewException(dict, edict, "IntegrityError")))
  2676. goto error;
  2677. if (!(_mysql_InternalError =
  2678. _mysql_NewException(dict, edict, "InternalError")))
  2679. goto error;
  2680. if (!(_mysql_ProgrammingError =
  2681. _mysql_NewException(dict, edict, "ProgrammingError")))
  2682. goto error;
  2683. if (!(_mysql_NotSupportedError =
  2684. _mysql_NewException(dict, edict, "NotSupportedError")))
  2685. goto error;
  2686. Py_DECREF(emod);
  2687. error:
  2688. if (PyErr_Occurred()) {
  2689. PyErr_SetString(PyExc_ImportError, "_mysql: init failed");
  2690. module = NULL;
  2691. }
  2692. return module;
  2693. }
  2694. /* vim: set ts=4 sts=4 sw=4 expandtab : */