sq_postgresql.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. #ifdef WITH_POSTGRESQL
  2. #include "squirrel.h"
  3. #include "libpq-fe.h"
  4. //#include "pg_type.h"
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include "sqstdblobimpl.h"
  9. SQ_OPT_STRING_STRLEN();
  10. #define BOOLOID 16
  11. #define BYTEAOID 17
  12. #define CHAROID 18
  13. #define INT8OID 20
  14. #define INT2OID 21
  15. #define INT4OID 23
  16. #define FLOAT4OID 700
  17. #define FLOAT8OID 701
  18. #define TIMESTAMPOID 1114
  19. #define TIMESTAMPTZOID 1184
  20. #define VARCHAROID 1043
  21. #include "dynamic_library.h"
  22. /*SquiLu
  23. local pgsql_functions = [
  24. ["ConnStatusType", "PQstatus", "const PGconn *conn"],
  25. ["void", "PQfinish", "PGconn *conn"],
  26. ["PGresult *", "PQprepare", @"PGconn *conn,
  27. const char *stmtName,
  28. const char *query,
  29. int nParams,
  30. const Oid *paramTypes"],
  31. ["void", "PQfreemem", "void *ptr"],
  32. ["char *", "PQescapeLiteral", "PGconn *conn, const char *str, size_t length"],
  33. ["char *", "PQescapeIdentifier", "PGconn *conn, const char *str, size_t length"],
  34. ["unsigned char *", "PQescapeByteaConn", "PGconn *conn, const unsigned char *str, size_t length"],
  35. ["unsigned char *", "PQunescapeBytea", "const unsigned char *str, size_t length"],
  36. ["PGresult *", "PQdescribePrepared", "PGconn *conn, const char *stmtName"],
  37. ["int", "PQnparams", "const PGresult *res"],
  38. ["Oid", "PQparamtype", "const PGresult *res, int param_number"],
  39. ["PGresult *", "PQexecPrepared", @"PGconn *conn,
  40. const char *stmtName,
  41. int nParams,
  42. const char * const *paramValues,
  43. const int *paramLengths,
  44. const int *paramFormats,
  45. int resultFormat"],
  46. ["PGresult *", "PQexec", "PGconn *conn, const char *command"],
  47. ["PGresult *", "PQexecParams", @"PGconn *conn,
  48. const char *command,
  49. int nParams,
  50. const Oid *paramTypes,
  51. const char * const *paramValues,
  52. const int *paramLengths,
  53. const int *paramFormats,
  54. int resultFormat"],
  55. ["const char*", "PQgetvalue", @"const PGresult *res,
  56. int row_number,
  57. int column_number"],
  58. ["int", "PQntuples", "const PGresult *res"],
  59. ["char *", "PQcmdTuples", "const PGresult *res"],
  60. ["int", "PQnfields", "const PGresult *res"],
  61. ["int", "PQgetisnull", @"const PGresult *res,
  62. int row_number,
  63. int column_number"],
  64. ["void", "PQclear", "const PGresult *res"],
  65. ["int", "PQfnumber", "const PGresult *res, const char *column_name"],
  66. ["char *", "PQfname", "const PGresult *res, int column_number"],
  67. ["ExecStatusType", "PQresultStatus", "const PGresult *res"],
  68. ["char *", "PQerrorMessage", "const PGconn *conn"],
  69. ["void", "PQreset", "PGconn *conn"],
  70. ["PGresult *", "PQgetResult", "PGconn *conn"],
  71. ["int", "PQsetnonblocking", "PGconn *conn, int arg"],
  72. ["Oid", "PQftype", "const PGresult *res, int column_number"],
  73. ["int", "PQserverVersion", "const PGconn *conn"],
  74. // Large-object access routines
  75. ["int", "lo_open", "PGconn *conn, Oid lobjId, int mode"],
  76. ["int", "lo_close", "PGconn *conn, int fd"],
  77. ["int", "lo_read", "PGconn *conn, int fd, char *buf, size_t len"],
  78. ["int", "lo_write", "PGconn *conn, int fd, const char *buf, size_t len"],
  79. ["int", "lo_lseek", "PGconn *conn, int fd, int offset, int whence"],
  80. ["Oid", "lo_creat", "PGconn *conn, int mode"],
  81. ["Oid", "lo_create", "PGconn *conn, Oid lobjId"],
  82. ["int", "lo_tell", "PGconn *conn, int fd"],
  83. ["int", "lo_truncate", "PGconn *conn, int fd, size_t len"],
  84. ["int", "lo_unlink", "PGconn *conn, Oid lobjId"],
  85. ["Oid", "lo_import", "PGconn *conn, const char *filename"],
  86. ["Oid", "lo_import_with_oid", "PGconn *conn, const char *filename, Oid lobjId"],
  87. ["int", "lo_export", "PGconn *conn, Oid lobjId, const char *filename"],
  88. //next entry should be the last one
  89. //to make valid the test made on load_libpq function
  90. ["PGconn *", "PQconnectdb", "const char *conninfo"],
  91. ];
  92. function write_pgsql_functions_declaration(){
  93. foreach(k,v in pgsql_functions) {
  94. putsnl("typedef " + v[0] + " (*" + v[1] + "_t)(" + v[2] + ");");
  95. putsnl("static " + v[1] + "_t dl" + v[1] + " = 0;");
  96. }
  97. }
  98. function write_pgsql_functions_load(){
  99. foreach(k,v in pgsql_functions){
  100. putsnl("dl" + v[1] + " = (" + v[1] + "_t) libpq.dlsym(\"" + v[1] + "\");");
  101. putsnl("if(!dl" + v[1] + ") return false;");
  102. }
  103. }
  104. SquiLu*/
  105. static DynamicLibrary libpq;
  106. //@write_pgsql_functions_declaration();
  107. // generated-code:begin
  108. typedef ConnStatusType (*PQstatus_t)(const PGconn *conn);
  109. static PQstatus_t dlPQstatus = 0;
  110. typedef void (*PQfinish_t)(PGconn *conn);
  111. static PQfinish_t dlPQfinish = 0;
  112. typedef PGresult * (*PQprepare_t)(PGconn *conn,
  113. const char *stmtName,
  114. const char *query,
  115. int nParams,
  116. const Oid *paramTypes);
  117. static PQprepare_t dlPQprepare = 0;
  118. typedef void (*PQfreemem_t)(void *ptr);
  119. static PQfreemem_t dlPQfreemem = 0;
  120. typedef char * (*PQescapeLiteral_t)(PGconn *conn, const char *str, size_t length);
  121. static PQescapeLiteral_t dlPQescapeLiteral = 0;
  122. typedef char * (*PQescapeIdentifier_t)(PGconn *conn, const char *str, size_t length);
  123. static PQescapeIdentifier_t dlPQescapeIdentifier = 0;
  124. typedef unsigned char * (*PQescapeByteaConn_t)(PGconn *conn, const unsigned char *str, size_t length);
  125. static PQescapeByteaConn_t dlPQescapeByteaConn = 0;
  126. typedef unsigned char * (*PQunescapeBytea_t)(const unsigned char *str, size_t length);
  127. static PQunescapeBytea_t dlPQunescapeBytea = 0;
  128. typedef PGresult * (*PQdescribePrepared_t)(PGconn *conn, const char *stmtName);
  129. static PQdescribePrepared_t dlPQdescribePrepared = 0;
  130. typedef int (*PQnparams_t)(const PGresult *res);
  131. static PQnparams_t dlPQnparams = 0;
  132. typedef Oid (*PQparamtype_t)(const PGresult *res, int param_number);
  133. static PQparamtype_t dlPQparamtype = 0;
  134. typedef PGresult * (*PQexecPrepared_t)(PGconn *conn,
  135. const char *stmtName,
  136. int nParams,
  137. const char * const *paramValues,
  138. const int *paramLengths,
  139. const int *paramFormats,
  140. int resultFormat);
  141. static PQexecPrepared_t dlPQexecPrepared = 0;
  142. typedef PGresult * (*PQexec_t)(PGconn *conn, const char *command);
  143. static PQexec_t dlPQexec = 0;
  144. typedef PGresult * (*PQexecParams_t)(PGconn *conn,
  145. const char *command,
  146. int nParams,
  147. const Oid *paramTypes,
  148. const char * const *paramValues,
  149. const int *paramLengths,
  150. const int *paramFormats,
  151. int resultFormat);
  152. static PQexecParams_t dlPQexecParams = 0;
  153. typedef const char* (*PQgetvalue_t)(const PGresult *res,
  154. int row_number,
  155. int column_number);
  156. static PQgetvalue_t dlPQgetvalue = 0;
  157. typedef int (*PQntuples_t)(const PGresult *res);
  158. static PQntuples_t dlPQntuples = 0;
  159. typedef char * (*PQcmdTuples_t)(const PGresult *res);
  160. static PQcmdTuples_t dlPQcmdTuples = 0;
  161. typedef int (*PQnfields_t)(const PGresult *res);
  162. static PQnfields_t dlPQnfields = 0;
  163. typedef int (*PQgetisnull_t)(const PGresult *res,
  164. int row_number,
  165. int column_number);
  166. static PQgetisnull_t dlPQgetisnull = 0;
  167. typedef void (*PQclear_t)(const PGresult *res);
  168. static PQclear_t dlPQclear = 0;
  169. typedef int (*PQfnumber_t)(const PGresult *res, const char *column_name);
  170. static PQfnumber_t dlPQfnumber = 0;
  171. typedef char * (*PQfname_t)(const PGresult *res, int column_number);
  172. static PQfname_t dlPQfname = 0;
  173. typedef ExecStatusType (*PQresultStatus_t)(const PGresult *res);
  174. static PQresultStatus_t dlPQresultStatus = 0;
  175. typedef char * (*PQerrorMessage_t)(const PGconn *conn);
  176. static PQerrorMessage_t dlPQerrorMessage = 0;
  177. typedef void (*PQreset_t)(PGconn *conn);
  178. static PQreset_t dlPQreset = 0;
  179. typedef PGresult * (*PQgetResult_t)(PGconn *conn);
  180. static PQgetResult_t dlPQgetResult = 0;
  181. typedef int (*PQsetnonblocking_t)(PGconn *conn, int arg);
  182. static PQsetnonblocking_t dlPQsetnonblocking = 0;
  183. typedef Oid (*PQftype_t)(const PGresult *res, int column_number);
  184. static PQftype_t dlPQftype = 0;
  185. typedef int (*PQserverVersion_t)(const PGconn *conn);
  186. static PQserverVersion_t dlPQserverVersion = 0;
  187. typedef int (*lo_open_t)(PGconn *conn, Oid lobjId, int mode);
  188. static lo_open_t dllo_open = 0;
  189. typedef int (*lo_close_t)(PGconn *conn, int fd);
  190. static lo_close_t dllo_close = 0;
  191. typedef int (*lo_read_t)(PGconn *conn, int fd, char *buf, size_t len);
  192. static lo_read_t dllo_read = 0;
  193. typedef int (*lo_write_t)(PGconn *conn, int fd, const char *buf, size_t len);
  194. static lo_write_t dllo_write = 0;
  195. typedef int (*lo_lseek_t)(PGconn *conn, int fd, int offset, int whence);
  196. static lo_lseek_t dllo_lseek = 0;
  197. typedef Oid (*lo_creat_t)(PGconn *conn, int mode);
  198. static lo_creat_t dllo_creat = 0;
  199. typedef Oid (*lo_create_t)(PGconn *conn, Oid lobjId);
  200. static lo_create_t dllo_create = 0;
  201. typedef int (*lo_tell_t)(PGconn *conn, int fd);
  202. static lo_tell_t dllo_tell = 0;
  203. typedef int (*lo_truncate_t)(PGconn *conn, int fd, size_t len);
  204. static lo_truncate_t dllo_truncate = 0;
  205. typedef int (*lo_unlink_t)(PGconn *conn, Oid lobjId);
  206. static lo_unlink_t dllo_unlink = 0;
  207. typedef Oid (*lo_import_t)(PGconn *conn, const char *filename);
  208. static lo_import_t dllo_import = 0;
  209. typedef Oid (*lo_import_with_oid_t)(PGconn *conn, const char *filename, Oid lobjId);
  210. static lo_import_with_oid_t dllo_import_with_oid = 0;
  211. typedef int (*lo_export_t)(PGconn *conn, Oid lobjId, const char *filename);
  212. static lo_export_t dllo_export = 0;
  213. typedef PGconn * (*PQconnectdb_t)(const char *conninfo);
  214. static PQconnectdb_t dlPQconnectdb = 0;
  215. // generated-code:end
  216. static const char *dynamicLibName = DYNLIB_FOR_OS(libpq);
  217. static bool load_libpq(const char *libname)
  218. {
  219. if(dlPQconnectdb) return true;
  220. if(libpq.open(libname))
  221. {
  222. //@write_pgsql_functions_load();
  223. // generated-code:begin
  224. dlPQstatus = (PQstatus_t) libpq.dlsym("PQstatus");
  225. if(!dlPQstatus) return false;
  226. dlPQfinish = (PQfinish_t) libpq.dlsym("PQfinish");
  227. if(!dlPQfinish) return false;
  228. dlPQprepare = (PQprepare_t) libpq.dlsym("PQprepare");
  229. if(!dlPQprepare) return false;
  230. dlPQfreemem = (PQfreemem_t) libpq.dlsym("PQfreemem");
  231. if(!dlPQfreemem) return false;
  232. dlPQescapeLiteral = (PQescapeLiteral_t) libpq.dlsym("PQescapeLiteral");
  233. if(!dlPQescapeLiteral) return false;
  234. dlPQescapeIdentifier = (PQescapeIdentifier_t) libpq.dlsym("PQescapeIdentifier");
  235. if(!dlPQescapeIdentifier) return false;
  236. dlPQescapeByteaConn = (PQescapeByteaConn_t) libpq.dlsym("PQescapeByteaConn");
  237. if(!dlPQescapeByteaConn) return false;
  238. dlPQunescapeBytea = (PQunescapeBytea_t) libpq.dlsym("PQunescapeBytea");
  239. if(!dlPQunescapeBytea) return false;
  240. dlPQdescribePrepared = (PQdescribePrepared_t) libpq.dlsym("PQdescribePrepared");
  241. if(!dlPQdescribePrepared) return false;
  242. dlPQnparams = (PQnparams_t) libpq.dlsym("PQnparams");
  243. if(!dlPQnparams) return false;
  244. dlPQparamtype = (PQparamtype_t) libpq.dlsym("PQparamtype");
  245. if(!dlPQparamtype) return false;
  246. dlPQexecPrepared = (PQexecPrepared_t) libpq.dlsym("PQexecPrepared");
  247. if(!dlPQexecPrepared) return false;
  248. dlPQexec = (PQexec_t) libpq.dlsym("PQexec");
  249. if(!dlPQexec) return false;
  250. dlPQexecParams = (PQexecParams_t) libpq.dlsym("PQexecParams");
  251. if(!dlPQexecParams) return false;
  252. dlPQgetvalue = (PQgetvalue_t) libpq.dlsym("PQgetvalue");
  253. if(!dlPQgetvalue) return false;
  254. dlPQntuples = (PQntuples_t) libpq.dlsym("PQntuples");
  255. if(!dlPQntuples) return false;
  256. dlPQcmdTuples = (PQcmdTuples_t) libpq.dlsym("PQcmdTuples");
  257. if(!dlPQcmdTuples) return false;
  258. dlPQnfields = (PQnfields_t) libpq.dlsym("PQnfields");
  259. if(!dlPQnfields) return false;
  260. dlPQgetisnull = (PQgetisnull_t) libpq.dlsym("PQgetisnull");
  261. if(!dlPQgetisnull) return false;
  262. dlPQclear = (PQclear_t) libpq.dlsym("PQclear");
  263. if(!dlPQclear) return false;
  264. dlPQfnumber = (PQfnumber_t) libpq.dlsym("PQfnumber");
  265. if(!dlPQfnumber) return false;
  266. dlPQfname = (PQfname_t) libpq.dlsym("PQfname");
  267. if(!dlPQfname) return false;
  268. dlPQresultStatus = (PQresultStatus_t) libpq.dlsym("PQresultStatus");
  269. if(!dlPQresultStatus) return false;
  270. dlPQerrorMessage = (PQerrorMessage_t) libpq.dlsym("PQerrorMessage");
  271. if(!dlPQerrorMessage) return false;
  272. dlPQreset = (PQreset_t) libpq.dlsym("PQreset");
  273. if(!dlPQreset) return false;
  274. dlPQgetResult = (PQgetResult_t) libpq.dlsym("PQgetResult");
  275. if(!dlPQgetResult) return false;
  276. dlPQsetnonblocking = (PQsetnonblocking_t) libpq.dlsym("PQsetnonblocking");
  277. if(!dlPQsetnonblocking) return false;
  278. dlPQftype = (PQftype_t) libpq.dlsym("PQftype");
  279. if(!dlPQftype) return false;
  280. dlPQserverVersion = (PQserverVersion_t) libpq.dlsym("PQserverVersion");
  281. if(!dlPQserverVersion) return false;
  282. dllo_open = (lo_open_t) libpq.dlsym("lo_open");
  283. if(!dllo_open) return false;
  284. dllo_close = (lo_close_t) libpq.dlsym("lo_close");
  285. if(!dllo_close) return false;
  286. dllo_read = (lo_read_t) libpq.dlsym("lo_read");
  287. if(!dllo_read) return false;
  288. dllo_write = (lo_write_t) libpq.dlsym("lo_write");
  289. if(!dllo_write) return false;
  290. dllo_lseek = (lo_lseek_t) libpq.dlsym("lo_lseek");
  291. if(!dllo_lseek) return false;
  292. dllo_creat = (lo_creat_t) libpq.dlsym("lo_creat");
  293. if(!dllo_creat) return false;
  294. dllo_create = (lo_create_t) libpq.dlsym("lo_create");
  295. if(!dllo_create) return false;
  296. dllo_tell = (lo_tell_t) libpq.dlsym("lo_tell");
  297. if(!dllo_tell) return false;
  298. dllo_truncate = (lo_truncate_t) libpq.dlsym("lo_truncate");
  299. if(!dllo_truncate) return false;
  300. dllo_unlink = (lo_unlink_t) libpq.dlsym("lo_unlink");
  301. if(!dllo_unlink) return false;
  302. dllo_import = (lo_import_t) libpq.dlsym("lo_import");
  303. if(!dllo_import) return false;
  304. dllo_import_with_oid = (lo_import_with_oid_t) libpq.dlsym("lo_import_with_oid");
  305. if(!dllo_import_with_oid) return false;
  306. dllo_export = (lo_export_t) libpq.dlsym("lo_export");
  307. if(!dllo_export) return false;
  308. dlPQconnectdb = (PQconnectdb_t) libpq.dlsym("PQconnectdb");
  309. if(!dlPQconnectdb) return false;
  310. // generated-code:end
  311. return true;
  312. }
  313. return false;
  314. }
  315. ////////////////////////////////////////////////////////////////////////////////
  316. static const SQChar *PostgreSQL_TAG = _SC("PostgreSQL");
  317. static SQRESULT get_pgsql_instance(HSQUIRRELVM v, SQInteger idx, PGconn **self){
  318. SQRESULT _rc_;
  319. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)self,(void*)PostgreSQL_TAG,SQFalse)) < 0) return _rc_;
  320. if(!*self) return sq_throwerror(v, _SC("database is closed"));
  321. return _rc_;
  322. }
  323. #define GET_pgsql_INSTANCE_AT(idx) \
  324. PGconn *self=NULL; \
  325. if((_rc_ = get_pgsql_instance(v,idx,&self)) < 0) return _rc_;
  326. #define GET_pgsql_INSTANCE() GET_pgsql_INSTANCE_AT(1)
  327. static const SQChar *PostgreSQL_Result_TAG = _SC("PostgreSQL_Result");
  328. static const SQChar *_curr_row_key = _SC("_curr_row");
  329. static SQRESULT get_pgsql_result_instance(HSQUIRRELVM v, SQInteger idx, PGresult **self){
  330. SQRESULT _rc_;
  331. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)self,(void*)PostgreSQL_Result_TAG,SQFalse)) < 0) return _rc_;
  332. if(!*self) return sq_throwerror(v, _SC("PGresult is closed"));
  333. return _rc_;
  334. }
  335. #define GET_pgsql_result_INSTANCE_AT(idx) \
  336. PGresult *self=NULL; \
  337. if((_rc_ = get_pgsql_result_instance(v,idx,&self)) < 0) return _rc_;
  338. #define GET_pgsql_result_INSTANCE() GET_pgsql_result_INSTANCE_AT(1)
  339. static SQRESULT sq_pgsql_result_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  340. {
  341. PGresult *self = ((PGresult *)p);
  342. if (self) dlPQclear(self);
  343. return 0;
  344. }
  345. static SQRESULT sq_pgsql_result_close(HSQUIRRELVM v){
  346. SQ_FUNC_VARS_NO_TOP(v);
  347. GET_pgsql_result_INSTANCE();
  348. dlPQclear(self);
  349. sq_setinstanceup(v, 1, 0); //next calls will fail with "Pgresult is closed"
  350. return 0;
  351. }
  352. static SQRESULT sq_pgsql_result_col_count(HSQUIRRELVM v){
  353. SQ_FUNC_VARS_NO_TOP(v);
  354. GET_pgsql_result_INSTANCE();
  355. sq_pushinteger(v, dlPQnfields(self));
  356. return 1;
  357. }
  358. static SQRESULT sq_pgsql_result_row_count(HSQUIRRELVM v){
  359. SQ_FUNC_VARS_NO_TOP(v);
  360. GET_pgsql_result_INSTANCE();
  361. sq_pushinteger(v, dlPQntuples(self));
  362. return 1;
  363. }
  364. static SQRESULT sq_pgsql_result_col_name(HSQUIRRELVM v){
  365. SQ_FUNC_VARS_NO_TOP(v);
  366. GET_pgsql_result_INSTANCE();
  367. SQ_GET_INTEGER(v, 2, col);
  368. sq_pushstring(v, dlPQfname(self, col), -1);
  369. return 1;
  370. }
  371. static SQRESULT sq_pgsql_result_col_type(HSQUIRRELVM v){
  372. SQ_FUNC_VARS_NO_TOP(v);
  373. GET_pgsql_result_INSTANCE();
  374. SQ_GET_INTEGER(v, 2, col);
  375. sq_pushinteger(v, dlPQftype(self, col));
  376. return 1;
  377. }
  378. static SQRESULT sq_pgsql_result_col_index(HSQUIRRELVM v){
  379. SQ_FUNC_VARS_NO_TOP(v);
  380. GET_pgsql_result_INSTANCE();
  381. SQ_GET_STRING(v, 2, name);
  382. sq_pushinteger(v, dlPQfnumber(self, name));
  383. return 1;
  384. }
  385. static SQRESULT sq_pgsql_result_eof(HSQUIRRELVM v){
  386. SQ_FUNC_VARS_NO_TOP(v);
  387. GET_pgsql_result_INSTANCE();
  388. sq_pushstring(v, _curr_row_key, -1);
  389. if(sq_get(v, 1) == SQ_OK){
  390. SQ_GET_INTEGER(v, -1, curr_row);
  391. sq_pushbool(v, curr_row < dlPQntuples(self));
  392. }
  393. else sq_pushbool(v, SQTrue);
  394. return 1;
  395. }
  396. static SQRESULT sq_pgsql_result_next_row(HSQUIRRELVM v){
  397. SQ_FUNC_VARS_NO_TOP(v);
  398. GET_pgsql_result_INSTANCE();
  399. sq_pushstring(v, _curr_row_key, -1);
  400. sq_push(v, -1); //make a copy
  401. if(sq_get(v, 1) == SQ_OK){
  402. SQ_GET_INTEGER(v, -1, curr_row);
  403. if(++curr_row < dlPQntuples(self)){
  404. sq_poptop(v);
  405. sq_pushinteger(v, curr_row);
  406. sq_set(v, 1);
  407. sq_pushbool(v, SQTrue);
  408. return 1;
  409. }
  410. }
  411. sq_pushbool(v, SQFalse);
  412. return 1;
  413. }
  414. static SQRESULT sq_pgsql_result_col_value(HSQUIRRELVM v){
  415. SQ_FUNC_VARS_NO_TOP(v);
  416. GET_pgsql_result_INSTANCE();
  417. SQObjectType ptype = sq_gettype(v, 2);
  418. int col = -1;
  419. if(ptype == OT_STRING){
  420. SQ_GET_STRING(v, 2, col_name);
  421. col = dlPQfnumber(self, col_name);
  422. }
  423. else
  424. {
  425. SQ_GET_INTEGER(v, 2, idx);
  426. col = idx;
  427. }
  428. if(col < 0) return sq_throwerror(v, _SC("invalid col index/name"));
  429. sq_pushstring(v, _curr_row_key, -1);
  430. if(sq_get(v, 1) == SQ_OK){
  431. SQ_GET_INTEGER(v, -1, curr_row);
  432. if(curr_row < dlPQntuples(self)){
  433. sq_pushstring(v, dlPQgetvalue(self, curr_row, col), -1);
  434. return 1;
  435. }
  436. }
  437. return SQ_ERROR;
  438. }
  439. static SQRESULT sq_pgsql_result_row_as_array(HSQUIRRELVM v){
  440. SQ_FUNC_VARS(v);
  441. GET_pgsql_result_INSTANCE();
  442. SQ_OPT_INTEGER(v, 2, row, -1);
  443. if(row < 0){
  444. sq_pushstring(v, _curr_row_key, -1);
  445. if(sq_get(v, 1) == SQ_OK){
  446. sq_getinteger(v, -1, &row);
  447. }
  448. }
  449. int row_count = dlPQntuples(self);
  450. if(row < 0 || row >= row_count) return sq_throwerror(v, _SC("invalid row (" _PRINT_INT_FMT ")"), row);
  451. int col_count = dlPQnfields(self);
  452. sq_newarray(v, col_count);
  453. for(int i=0; i < col_count; ++i){
  454. sq_pushinteger(v, i);
  455. sq_pushstring(v, dlPQgetvalue(self, row, i), -1);
  456. sq_rawset(v, -3);
  457. }
  458. return 1;
  459. }
  460. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_pgsql_result_##name,nparams,tycheck}
  461. static SQRegFunction sq_pgsql_result_methods[] =
  462. {
  463. _DECL_FUNC(close, 1, _SC("x")),
  464. _DECL_FUNC(eof, 1, _SC("x")),
  465. _DECL_FUNC(next_row, 1, _SC("x")),
  466. _DECL_FUNC(col_count, 1, _SC("x")),
  467. _DECL_FUNC(row_count, 1, _SC("x")),
  468. _DECL_FUNC(col_name, 2, _SC("xi")),
  469. _DECL_FUNC(col_index, 2, _SC("xs")),
  470. _DECL_FUNC(col_value, 2, _SC("x i|s")),
  471. _DECL_FUNC(col_type, 2, _SC("x i|s")),
  472. _DECL_FUNC(row_as_array, -1, _SC("xi")),
  473. {0,0}
  474. };
  475. #undef _DECL_FUNC
  476. struct PgSqlStatement {
  477. PGconn *db;
  478. char name[64];
  479. int param_count;
  480. int isGetPrepared;
  481. void **param_values;
  482. int *param_sizes;
  483. int *param_types;
  484. };
  485. static const SQChar *PostgreSQL_Statement_TAG = _SC("PostgreSQL_Statement");
  486. static SQRESULT get_pgsql_statement_instance(HSQUIRRELVM v, SQInteger idx, PgSqlStatement **self){
  487. SQRESULT _rc_;
  488. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)self,(void*)PostgreSQL_Statement_TAG,SQFalse)) < 0) return _rc_;
  489. if(!*self) return sq_throwerror(v, _SC("PGstatement is closed"));
  490. return _rc_;
  491. }
  492. #define GET_pgsql_statement_INSTANCE_AT(idx) \
  493. PgSqlStatement *self=NULL; \
  494. if((_rc_ = get_pgsql_statement_instance(v,idx,&self)) < 0) return _rc_;
  495. #define GET_pgsql_statement_INSTANCE() GET_pgsql_statement_INSTANCE_AT(1)
  496. static SQRESULT sq_pgsql_statement_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  497. {
  498. PgSqlStatement *self = ((PgSqlStatement *)p);
  499. if (self){
  500. if(!self->isGetPrepared)
  501. {
  502. char sql[128];
  503. snprintf(sql, sizeof(sql), "DEALLOCATE %s", self->name);
  504. PGresult *qres = dlPQexec(self->db, sql);
  505. dlPQclear(qres);
  506. }
  507. if(self->param_count)
  508. {
  509. SQUnsignedInteger the_size;
  510. if(self->param_values)
  511. {
  512. the_size = self->param_count * sizeof(self->param_values);
  513. sq_free(self->param_values, the_size);
  514. }
  515. if(self->param_sizes)
  516. {
  517. the_size = self->param_count * sizeof(self->param_sizes);
  518. sq_free(self->param_sizes, the_size);
  519. }
  520. if(self->param_types)
  521. {
  522. the_size = self->param_count * sizeof(self->param_types);
  523. sq_free(self->param_types, the_size);
  524. }
  525. }
  526. sq_free(self, sizeof(PgSqlStatement));
  527. }
  528. return 0;
  529. }
  530. static SQRESULT sq_pgsql_statement_close(HSQUIRRELVM v){
  531. SQ_FUNC_VARS_NO_TOP(v);
  532. GET_pgsql_statement_INSTANCE();
  533. sq_pgsql_statement_releasehook(self, 0, v);
  534. sq_setinstanceup(v, 1, 0); //next calls will fail with "Pgstatement is closed"
  535. return 0;
  536. }
  537. /*
  538. static SQRESULT sq_pgsql_statement_exec(HSQUIRRELVM v){
  539. SQ_FUNC_VARS(v);
  540. GET_pgsql_statement_INSTANCE();
  541. SQ_OPT_INTEGER(v, 3, result_type, 0);
  542. SQInteger psize = sq_getsize(v, 2);
  543. void **param_values;
  544. int *param_sizes;
  545. int *param_types;
  546. bool bresult = false;
  547. SQBool bval;
  548. PGresult *qres;
  549. SQUnsignedInteger param_values_size = psize * sizeof(param_values);
  550. SQUnsignedInteger param_sizes_size = psize * sizeof(param_sizes);
  551. if(self->result)
  552. {
  553. dlPQclear(self->result);
  554. self->result = NULL;
  555. }
  556. param_values = (void **)sq_malloc(param_values_size);
  557. memset(param_values, 0, param_values_size);
  558. param_sizes = (int *)sq_malloc(param_sizes_size);
  559. memset(param_sizes, 0, param_sizes_size);
  560. param_types = (int *)sq_malloc(param_sizes_size);
  561. memset(param_types, 0, param_sizes_size);
  562. for(SQInteger i=0; i < psize; ++i)
  563. {
  564. sq_pushinteger(v, i);
  565. if(sq_get(v, 2) == SQ_OK)
  566. {
  567. switch(sq_gettype(v, -1))
  568. {
  569. case OT_NULL:
  570. param_values[i] = NULL;
  571. param_sizes[i] = 0;
  572. param_types[i] = 0;
  573. sq_poptop(v);
  574. break;
  575. case OT_BOOL:
  576. sq_getbool(v, -1, &bval);
  577. param_values[i] = (void*)(bval == SQTrue ? "1" : "0");
  578. param_sizes[i] = 1;
  579. param_types[i] = BOOLOID;
  580. sq_poptop(v);
  581. break;
  582. case OT_INTEGER:
  583. param_values[i] = (void*)sq_tostring(v, -1);
  584. param_sizes[i] = (int)sq_getsize(v, -1);
  585. param_types[i] = INT4OID;
  586. break;
  587. case OT_FLOAT:
  588. param_values[i] = (void*)sq_tostring(v, -1);
  589. param_sizes[i] = (int)sq_getsize(v, -1);
  590. param_types[i] = FLOAT8OID;
  591. break;
  592. case OT_STRING:
  593. param_values[i] = (void*)sq_tostring(v, -1);
  594. param_sizes[i] = (int)sq_getsize(v, -1);
  595. param_types[i] = VARCHAROID;
  596. break;
  597. default:
  598. goto cleanup;
  599. }
  600. }
  601. }
  602. qres = dlPQexecPrepared(self->db, self->name, psize, (const char**)param_values, param_sizes, NULL, result_type);
  603. bresult = dlPQresultStatus(qres) == PGRES_COMMAND_OK;
  604. if(bresult) self->result = qres;
  605. else dlPQclear(qres);
  606. cleanup:
  607. sq_free(param_values, param_values_size);
  608. sq_free(param_sizes, param_sizes_size);
  609. sq_settop(v, _top_);
  610. sq_pushbool(v, bresult);
  611. return 1;
  612. }
  613. */
  614. #define SQ_EXEC_DML 1
  615. #define SQ_EXEC_SCALAR 2
  616. #define SQ_EXEC_QUERY 3
  617. /*
  618. static SQRESULT sq_pgsql_statement_exec(HSQUIRRELVM v, int exec_type){
  619. SQ_FUNC_VARS(v);
  620. GET_pgsql_statement_INSTANCE();
  621. SQ_OPT_INTEGER(v, 3, result_type, 0);
  622. SQInteger psize = sq_getsize(v, 2);
  623. if(psize != self->param_count)
  624. {
  625. return sq_throwerror(v, _SC("Wrong number of paramters, exptexted %d"), self->param_count);
  626. }
  627. int result = SQ_ERROR;
  628. SQBool bval;
  629. const SQChar *str_val;
  630. SQInteger *int_val_ptr;
  631. SQFloat *float_val_ptr;
  632. PGresult *qres;
  633. SQUnsignedInteger param_values_size = psize * sizeof(self->param_values);
  634. SQUnsignedInteger param_sizes_size = psize * sizeof(self->param_sizes);
  635. SQUnsignedInteger param_types_size = psize * sizeof(self->param_types);
  636. if(!self->param_values)
  637. {
  638. //only allocate once
  639. self->param_values = (void **)sq_malloc(param_values_size);
  640. self->param_sizes = (int *)sq_malloc(param_sizes_size);
  641. self->param_types = (int *)sq_malloc(param_types_size);
  642. }
  643. memset(self->param_values, 0, param_values_size);
  644. memset(self->param_sizes, 0, param_sizes_size);
  645. memset(self->param_types, 0, param_types_size);
  646. sq_reservestack(v, psize*2);
  647. for(SQInteger i=0; i < psize; ++i)
  648. {
  649. sq_pushinteger(v, i);
  650. if(sq_get(v, 2) == SQ_OK)
  651. {
  652. switch(sq_gettype(v, -1))
  653. {
  654. case OT_NULL:
  655. self->param_values[i] = NULL;
  656. self->param_sizes[i] = 0;
  657. self->param_types[i] = 0;
  658. sq_poptop(v);
  659. break;
  660. case OT_BOOL:
  661. sq_getbool(v, -1, &bval);
  662. self->param_values[i] = (void*)(bval == SQTrue ? "1" : "0");
  663. self->param_sizes[i] = 1;
  664. param_types[i] = BOOLOID;
  665. sq_poptop(v);
  666. break;
  667. case OT_INTEGER:
  668. sq_getinteger_ptr(v, -1, &int_val_ptr);
  669. self->param_values[i] = (void*)int_val_ptr;
  670. self->param_sizes[i] = (int)sizeof(SQInteger);
  671. param_types[i] = INT8OID;
  672. break;
  673. case OT_FLOAT:
  674. sq_getfloat_ptr(v, -1, &float_val_ptr);
  675. self->param_values[i] = (void*)float_val_ptr;
  676. self->param_sizes[i] = (int)sizeof(SQFloat);
  677. param_types[i] = FLOAT8OID;
  678. break;
  679. case OT_STRING:
  680. //sq_tostring(v, -1);
  681. sq_getstring(v, -1, &str_val);
  682. self->param_values[i] = (void*)str_val;
  683. self->param_sizes[i] = (int)sq_getsize(v, -1);
  684. self->param_types[i] = VARCHAROID;
  685. break;
  686. default:
  687. result = sq_throwerror(v, _SC("Unknow parameter type at pos %d"), i);
  688. goto cleanup;
  689. }
  690. }
  691. }
  692. */
  693. static SQRESULT sq_pgsql_statement_exec(HSQUIRRELVM v, int exec_type){
  694. SQ_FUNC_VARS(v);
  695. GET_pgsql_statement_INSTANCE();
  696. SQ_OPT_INTEGER(v, 3, result_type, 0);
  697. SQInteger psize = sq_getsize(v, 2);
  698. if(psize != self->param_count)
  699. {
  700. return sq_throwerror(v, _SC("Wrong number of paramters, exptexted %d"), self->param_count);
  701. }
  702. int result = SQ_ERROR;
  703. SQBool bval;
  704. const SQChar *str_val;
  705. PGresult *qres;
  706. SQUnsignedInteger param_values_size = psize * sizeof(self->param_values);
  707. SQUnsignedInteger param_sizes_size = psize * sizeof(self->param_sizes);
  708. if(!self->param_values)
  709. {
  710. //only allocate once
  711. self->param_values = (void **)sq_malloc(param_values_size);
  712. self->param_sizes = (int *)sq_malloc(param_sizes_size);
  713. }
  714. memset(self->param_values, 0, param_values_size);
  715. memset(self->param_sizes, 0, param_sizes_size);
  716. sq_reservestack(v, psize*2);
  717. for(SQInteger i=0; i < psize; ++i)
  718. {
  719. sq_pushinteger(v, i);
  720. if(sq_get(v, 2) == SQ_OK)
  721. {
  722. switch(sq_gettype(v, -1))
  723. {
  724. case OT_NULL:
  725. sq_poptop(v);
  726. break;
  727. case OT_BOOL:
  728. sq_getbool(v, -1, &bval);
  729. self->param_values[i] = (void*)(bval == SQTrue ? "1" : "0");
  730. self->param_sizes[i] = 1;
  731. sq_poptop(v);
  732. break;
  733. case OT_INTEGER:
  734. case OT_FLOAT:
  735. case OT_STRING:
  736. sq_tostring(v, -1);
  737. sq_getstring(v, -1, &str_val);
  738. self->param_values[i] = (void*)str_val;
  739. self->param_sizes[i] = (int)sq_getsize(v, -1);
  740. break;
  741. default:
  742. result = sq_throwerror(v, _SC("Unknow parameter type at pos %d"), (int)i);
  743. goto cleanup;
  744. }
  745. }
  746. }
  747. qres = dlPQexecPrepared(self->db, self->name, psize,
  748. (const char**)self->param_values, self->param_sizes, NULL, result_type);
  749. result = dlPQresultStatus(qres);
  750. if(result == PGRES_COMMAND_OK || result == PGRES_TUPLES_OK)
  751. {
  752. if(exec_type == SQ_EXEC_DML)
  753. {
  754. sq_pushinteger(v, atoi(dlPQcmdTuples(qres)));
  755. dlPQclear(qres);
  756. }
  757. else if(exec_type == SQ_EXEC_SCALAR)
  758. {
  759. int ntuples = dlPQntuples(qres);
  760. int nfields = dlPQnfields(qres);
  761. if(exec_type == SQ_EXEC_SCALAR && (ntuples == 1) && (nfields > 0))
  762. {
  763. result = atoi(dlPQgetvalue(qres, 0, 0));
  764. sq_pushinteger(v, result);
  765. dlPQclear(qres);
  766. }
  767. else
  768. {
  769. sq_pushnull(v);
  770. }
  771. }
  772. else if(exec_type == SQ_EXEC_QUERY)
  773. {
  774. sq_pushroottable(v);
  775. sq_pushstring(v, PostgreSQL_Result_TAG, -1);
  776. if(sq_get(v, -2) == SQ_OK){
  777. if(sq_createinstance(v, -1) == SQ_OK){
  778. sq_setinstanceup(v, -1, qres);
  779. sq_setreleasehook(v, -1, sq_pgsql_result_releasehook);
  780. sq_pushstring(v, _curr_row_key, -1);
  781. sq_pushinteger(v, -1);
  782. sq_set(v, -3);
  783. }
  784. }
  785. }
  786. result = 1;
  787. }
  788. else
  789. {
  790. dlPQclear(qres);
  791. //sq_settop(v, _top_);
  792. result = sq_throwerror(v, _SC("%s"), dlPQerrorMessage(self->db));
  793. }
  794. cleanup:
  795. return result;
  796. }
  797. static SQRESULT sq_pgsql_statement_exec_query(HSQUIRRELVM v){
  798. return sq_pgsql_statement_exec(v, SQ_EXEC_QUERY);
  799. }
  800. static SQRESULT sq_pgsql_statement_exec_scalar(HSQUIRRELVM v){
  801. return sq_pgsql_statement_exec(v, SQ_EXEC_SCALAR);
  802. }
  803. static SQRESULT sq_pgsql_statement_exec_dml(HSQUIRRELVM v){
  804. return sq_pgsql_statement_exec(v, SQ_EXEC_DML);
  805. }
  806. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_pgsql_statement_##name,nparams,tycheck}
  807. static SQRegFunction sq_pgsql_statement_methods[] =
  808. {
  809. _DECL_FUNC(exec_query, -2, _SC("xai")),
  810. _DECL_FUNC(exec_scalar, 2, _SC("xa")),
  811. _DECL_FUNC(exec_dml, 2, _SC("xa")),
  812. _DECL_FUNC(close, 1, _SC("x")),
  813. {0,0}
  814. };
  815. #undef _DECL_FUNC
  816. static SQRESULT sq_pgsql_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  817. {
  818. PGconn *self = ((PGconn *)p);
  819. if (self) dlPQfinish(self);
  820. return 0;
  821. }
  822. static SQRESULT sq_pgsql_constructor(HSQUIRRELVM v)
  823. {
  824. SQ_FUNC_VARS_NO_TOP(v);
  825. SQ_GET_STRING(v, 2, szConnInfo);
  826. PGconn *self=0;
  827. if(load_libpq(dynamicLibName))
  828. {
  829. self = dlPQconnectdb(szConnInfo);
  830. if (dlPQstatus(self) == CONNECTION_BAD) return sq_throwerror(v, _SC("Failed to connect ot database !"));
  831. }
  832. else return sq_throwerror(v, _SC("Failed to load libpq !"));
  833. sq_setinstanceup(v, 1, self);
  834. sq_setreleasehook(v,1, sq_pgsql_releasehook);
  835. //save a weakref to allow statement return it's db
  836. sq_pushuserpointer(v, self);
  837. sq_weakref(v, 1);
  838. sq_setonregistrytable(v);
  839. return 1;
  840. }
  841. static SQRESULT sq_pgsql_close(HSQUIRRELVM v){
  842. SQ_FUNC_VARS_NO_TOP(v);
  843. GET_pgsql_INSTANCE();
  844. dlPQfinish(self);
  845. sq_setinstanceup(v, 1, 0); //next calls will fail with "database is closed"
  846. return 0;
  847. }
  848. #if 0
  849. static PGresult *sq_pgsql_exec_params(HSQUIRRELVM v) {
  850. SQ_FUNC_VARS(v);
  851. GET_pgsql_INSTANCE();
  852. SQ_GET_STRING(v, 2, szSQL);
  853. int nParams = _top_ - 2; /* subtract connection and command */
  854. if(nParams)
  855. {
  856. if (nParams > 65535) return null;
  857. sq_reservestack(v, 4);
  858. Oid *paramTypes = sq_newuserdata(v, nParams * sizeof(Oid));
  859. char **paramValues = sq_newuserdata(v, nParams * sizeof(char*));
  860. int *paramLengths = sq_newuserdata(v, nParams * sizeof(int));
  861. int *paramFormats = sq_newuserdata(v, nParams * sizeof(int));
  862. for (int n = 0; n < nParams; n++)
  863. {
  864. //get_param(v, 3 + n, n, paramTypes, paramValues, paramLengths, paramFormats);
  865. }
  866. return dlPQexecParams(self. szSQL, nParams, paramTypes,
  867. (const char * const*)paramValues, paramLengths, paramFormats, 0);
  868. }
  869. return dlPQexec(self, szSQL);
  870. }
  871. #endif
  872. static SQRESULT sq_pgsql_exec_dml(HSQUIRRELVM v){
  873. SQ_FUNC_VARS_NO_TOP(v);
  874. GET_pgsql_INSTANCE();
  875. SQ_GET_STRING(v, 2, szSQL);
  876. int result = 0;
  877. PGresult *qres = dlPQexec(self, szSQL);
  878. bool is_ok = dlPQresultStatus(qres) == PGRES_COMMAND_OK;
  879. if (is_ok) result = atoi(dlPQcmdTuples(qres));
  880. dlPQclear(qres);
  881. if (!is_ok) return sq_throwerror(v, _SC("%s"), dlPQerrorMessage(self));
  882. sq_pushinteger(v, result);
  883. return 1;
  884. }
  885. static SQRESULT sq_pgsql_exec_scalar(HSQUIRRELVM v){
  886. SQ_FUNC_VARS_NO_TOP(v);
  887. GET_pgsql_INSTANCE();
  888. SQ_GET_STRING(v, 2, szSQL);
  889. int result = 0;
  890. PGresult *qres = dlPQexec(self, szSQL);
  891. bool is_ok = (dlPQresultStatus(qres) == PGRES_TUPLES_OK) &&
  892. (dlPQntuples(qres) == 1) && (dlPQnfields(qres) > 0);
  893. if (is_ok) result = atoi(dlPQgetvalue(qres, 0, 0));
  894. dlPQclear(qres);
  895. if (!is_ok) return sq_throwerror(v, _SC("%s"), dlPQerrorMessage(self));
  896. sq_pushinteger(v, result);
  897. return 1;
  898. }
  899. static SQRESULT sq_pgsql_exec_query(HSQUIRRELVM v){
  900. SQ_FUNC_VARS_NO_TOP(v);
  901. GET_pgsql_INSTANCE();
  902. SQ_GET_STRING(v, 2, szSQL);
  903. PGresult *qres = dlPQexec(self, szSQL);
  904. if(dlPQresultStatus(qres) == PGRES_TUPLES_OK){
  905. sq_pushroottable(v);
  906. sq_pushstring(v, PostgreSQL_Result_TAG, -1);
  907. if(sq_get(v, -2) == SQ_OK){
  908. if(sq_createinstance(v, -1) == SQ_OK){
  909. sq_setinstanceup(v, -1, qres);
  910. sq_setreleasehook(v, -1, sq_pgsql_result_releasehook);
  911. sq_pushstring(v, _curr_row_key, -1);
  912. sq_pushinteger(v, -1);
  913. sq_set(v, -3);
  914. return 1;
  915. }
  916. }
  917. }
  918. return sq_throwerror(v, _SC("%s"), dlPQerrorMessage(self));
  919. }
  920. static SQRESULT sq_pgsql_do_prepare(HSQUIRRELVM v, int isGetPrepared){
  921. SQ_FUNC_VARS_NO_TOP(v);
  922. GET_pgsql_INSTANCE();
  923. SQ_GET_STRING(v, 2, szSQL);
  924. PGresult *qres;
  925. bool bresult;
  926. PgSqlStatement *stmt = (PgSqlStatement*)sq_malloc(sizeof(PgSqlStatement));
  927. memset(stmt, 0, sizeof(PgSqlStatement));
  928. stmt->db = self;
  929. stmt->isGetPrepared = isGetPrepared;
  930. if(isGetPrepared)
  931. {
  932. snprintf(stmt->name, sizeof(stmt->name), "%s", szSQL);
  933. qres = dlPQdescribePrepared(self, stmt->name);
  934. bresult = dlPQresultStatus(qres) == PGRES_COMMAND_OK;
  935. if(bresult) stmt->param_count = dlPQnparams(qres);
  936. dlPQclear(qres);
  937. }
  938. else
  939. {
  940. snprintf(stmt->name, sizeof(stmt->name), "sq_stmt_%p_%p", self, stmt);
  941. qres = dlPQprepare(self, stmt->name, szSQL, 0, NULL);
  942. bresult = dlPQresultStatus(qres) == PGRES_COMMAND_OK;
  943. dlPQclear(qres);
  944. }
  945. if(bresult){
  946. if(!isGetPrepared)
  947. {
  948. qres = dlPQdescribePrepared(self, stmt->name);
  949. stmt->param_count = dlPQnparams(qres);
  950. dlPQclear(qres);
  951. }
  952. sq_pushroottable(v);
  953. sq_pushstring(v, PostgreSQL_Statement_TAG, -1);
  954. if(sq_get(v, -2) == SQ_OK){
  955. if(sq_createinstance(v, -1) == SQ_OK){
  956. sq_setinstanceup(v, -1, stmt);
  957. sq_setreleasehook(v, -1, sq_pgsql_statement_releasehook);
  958. return 1;
  959. }
  960. }
  961. }
  962. sq_free(stmt, sizeof(PgSqlStatement));
  963. return sq_throwerror(v, _SC("%s"), dlPQerrorMessage(self));
  964. }
  965. static SQRESULT sq_pgsql_prepare(HSQUIRRELVM v){
  966. return sq_pgsql_do_prepare(v, 0);
  967. }
  968. static SQRESULT sq_pgsql_get_prepared(HSQUIRRELVM v){
  969. return sq_pgsql_do_prepare(v, 1);
  970. }
  971. static SQRESULT sq_pgsql_error_message(HSQUIRRELVM v){
  972. SQ_FUNC_VARS_NO_TOP(v);
  973. GET_pgsql_INSTANCE();
  974. sq_pushstring(v, dlPQerrorMessage(self), -1);
  975. return 1;
  976. }
  977. static SQRESULT sq_pgsql_version(HSQUIRRELVM v){
  978. SQ_FUNC_VARS_NO_TOP(v);
  979. GET_pgsql_INSTANCE();
  980. sq_pushinteger(v, dlPQserverVersion(self));
  981. return 1;
  982. }
  983. static int
  984. inv_read = 0x40000,
  985. inv_write = 0x20000,
  986. //invalidoid = 0,
  987. inv_seek_set = 0,
  988. //inv_seek_curr = 1,
  989. inv_seek_end = 2;
  990. static SQRESULT sq_pgsql_get_blob_field(HSQUIRRELVM v){
  991. SQ_FUNC_VARS_NO_TOP(v);
  992. GET_pgsql_INSTANCE();
  993. SQ_GET_INTEGER(v, 2, oid);
  994. //begin_recursive_transaction();
  995. char *result = 0;
  996. int ofd = dllo_open(self, oid, inv_read);
  997. if(ofd >= 0){
  998. int blobSize = dllo_lseek(self, ofd, 0, inv_seek_end);
  999. dllo_lseek(self, ofd, 0, inv_seek_set);
  1000. SQBlob blob(blobSize);
  1001. result = (char*)blob.GetBuf();
  1002. int numRead = 0;
  1003. while(blobSize > 0){
  1004. int i = dllo_read(self, ofd, result+numRead, blobSize);
  1005. numRead += i;
  1006. blobSize -= i;
  1007. }
  1008. dllo_close(self, oid);
  1009. sq_pushstring(v, (const SQChar*)blob.GetBuf(), blob.Len());
  1010. }
  1011. //commit_recursive_transaction();
  1012. if(!result) sq_pushnull(v);
  1013. return 1;
  1014. }
  1015. static SQRESULT sq_pgsql_insert_blob_field(HSQUIRRELVM v){
  1016. SQ_FUNC_VARS_NO_TOP(v);
  1017. GET_pgsql_INSTANCE();
  1018. int result = 0;
  1019. SQ_GET_STRING(v, 2, blob);
  1020. SQ_GET_BOOL(v, 3, isFileName);
  1021. if(isFileName){
  1022. result = dllo_import(self, blob);
  1023. } else {
  1024. result = dllo_creat(self, inv_write);
  1025. if(result){
  1026. int ofd = dllo_open(self, result, inv_write);
  1027. if (ofd >= 0){
  1028. int i = blob_size;
  1029. const char *blopPtr = (const char *)blob;
  1030. int numWriten = 0;
  1031. while(i > 0){
  1032. int i2 = dllo_write(self, ofd, blopPtr+numWriten, i);
  1033. numWriten += i2;
  1034. i -= i2;
  1035. }
  1036. dllo_close(self, ofd);
  1037. }
  1038. else return sq_throwerror(v, _SC("Failed to insert blob !"));
  1039. }
  1040. }
  1041. if(!result) sq_pushnull(v);
  1042. return 1;
  1043. }
  1044. static SQRESULT sq_pgsql_update_blob_field(HSQUIRRELVM v){
  1045. SQ_FUNC_VARS_NO_TOP(v);
  1046. GET_pgsql_INSTANCE();
  1047. SQ_GET_INTEGER(v, 2, oid);
  1048. SQ_GET_STRING(v, 3, blob);
  1049. SQ_GET_BOOL(v, 4, isFileName);
  1050. int result_oid = 0;
  1051. int result_error = SQ_OK;
  1052. int loid = dllo_creat(self, inv_write);
  1053. int ofd = dllo_open(self, loid, inv_write);
  1054. if(ofd >= 0){
  1055. dllo_unlink(self, oid);
  1056. result_oid = loid;
  1057. if(isFileName)
  1058. {
  1059. char buf[2048];
  1060. FILE *fp = fopen(blob, "rb");
  1061. if(!fp) {
  1062. sq_throwerror(v, _SC("Failed to update blob from file !"));
  1063. result_error = SQ_ERROR;
  1064. }
  1065. else
  1066. {
  1067. char *charPtr = buf;
  1068. int numRead;
  1069. do{
  1070. numRead = fread(buf, 1, sizeof(buf), fp);
  1071. int numWriten = dllo_write(self, ofd, charPtr, numRead);
  1072. if (numWriten != numRead) {
  1073. sq_throwerror(v, _SC("Failed to update blob from file !"));
  1074. result_error = SQ_ERROR;
  1075. break;
  1076. }
  1077. } while (numRead == 0);
  1078. fclose(fp);
  1079. }
  1080. }else{
  1081. int i = blob_size;
  1082. const char *blopPtr = (const char *)blob;
  1083. int numWriten = 0;
  1084. while(i > 0){
  1085. int i2 = dllo_write(self, ofd, blopPtr+numWriten, i);
  1086. numWriten += i2;
  1087. i -= i2;
  1088. }
  1089. }
  1090. dllo_close(self, ofd);
  1091. }
  1092. if(result_error == SQ_ERROR) return result_error;
  1093. sq_pushinteger(v, result_oid);
  1094. return 1;
  1095. }
  1096. static SQRESULT sq_pgsql_delete_blob_field(HSQUIRRELVM v){
  1097. SQ_FUNC_VARS_NO_TOP(v);
  1098. GET_pgsql_INSTANCE();
  1099. SQ_GET_INTEGER(v, 2, oid);
  1100. sq_pushinteger(v, dllo_unlink(self, oid));
  1101. return 1;
  1102. }
  1103. static SQRESULT sq_pgsql_escape_string(HSQUIRRELVM v){
  1104. SQ_FUNC_VARS_NO_TOP(v);
  1105. GET_pgsql_INSTANCE();
  1106. SQ_GET_STRING(v, 2, str);
  1107. char *escaped_str = dlPQescapeLiteral(self, str, str_size);
  1108. if(escaped_str) {
  1109. sq_pushstring(v, escaped_str, -1);
  1110. dlPQfreemem(escaped_str);
  1111. return 1;
  1112. }
  1113. return sq_throwerror(v, _SC("could not allocate escaped string"));
  1114. }
  1115. static SQRESULT sq_pgsql_escape_bytea(HSQUIRRELVM v){
  1116. SQ_FUNC_VARS_NO_TOP(v);
  1117. GET_pgsql_INSTANCE();
  1118. SQ_GET_STRING(v, 2, str);
  1119. char *escaped_str = (char*)dlPQescapeByteaConn(self, (const unsigned char*)str, str_size);
  1120. if(escaped_str) {
  1121. sq_pushstring(v, escaped_str, -1);
  1122. dlPQfreemem(escaped_str);
  1123. return 1;
  1124. }
  1125. return sq_throwerror(v, _SC("could not allocate escaped bytea"));
  1126. }
  1127. static SQRESULT sq_pgsql_unescape_bytea(HSQUIRRELVM v){
  1128. SQ_FUNC_VARS_NO_TOP(v);
  1129. GET_pgsql_INSTANCE();
  1130. SQ_GET_STRING(v, 2, str);
  1131. char *escaped_str = (char*)dlPQunescapeBytea((const unsigned char*)str, str_size);
  1132. if(escaped_str) {
  1133. sq_pushstring(v, escaped_str, -1);
  1134. dlPQfreemem(escaped_str);
  1135. return 1;
  1136. }
  1137. return sq_throwerror(v, _SC("could not allocate unescaped bytea"));
  1138. }
  1139. static SQRESULT sq_pgsql_loadlib(HSQUIRRELVM v)
  1140. {
  1141. SQ_FUNC_VARS(v);
  1142. SQ_OPT_STRING(v, 2, libname, dynamicLibName);
  1143. sq_pushbool(v, load_libpq(libname));
  1144. return 1;
  1145. }
  1146. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_pgsql_##name,nparams,tycheck}
  1147. static SQRegFunction sq_pgsql_methods[] =
  1148. {
  1149. _DECL_FUNC(constructor, 2, _SC("xs")),
  1150. _DECL_FUNC(close, 1, _SC("x")),
  1151. _DECL_FUNC(exec_dml, 2, _SC("xs")),
  1152. //_DECL_FUNC(exec_one_dml, -2, _SC("xs")),
  1153. _DECL_FUNC(exec_scalar, 2, _SC("xs")),
  1154. _DECL_FUNC(exec_query, 2, _SC("xs")),
  1155. _DECL_FUNC(prepare, 2, _SC("xs")),
  1156. _DECL_FUNC(get_prepared, 2, _SC("xs")),
  1157. _DECL_FUNC(error_message, 1, _SC("x")),
  1158. _DECL_FUNC(version, 1, _SC("x")),
  1159. _DECL_FUNC(get_blob_field, 2, _SC("xi")),
  1160. _DECL_FUNC(insert_blob_field, 3, _SC("xsb")),
  1161. _DECL_FUNC(update_blob_field, 3, _SC("xisb")),
  1162. _DECL_FUNC(delete_blob_field, 2, _SC("xi")),
  1163. _DECL_FUNC(escape_string, 2, _SC("xs")),
  1164. _DECL_FUNC(escape_bytea, 2, _SC("xs")),
  1165. _DECL_FUNC(unescape_bytea, 2, _SC("xs")),
  1166. _DECL_FUNC(loadlib,-1,_SC(".s")),
  1167. {0,0}
  1168. };
  1169. #undef _DECL_FUNC
  1170. #ifdef __cplusplus
  1171. extern "C" {
  1172. #endif
  1173. SQRESULT sqext_register_PostgreSQL(HSQUIRRELVM v)
  1174. {
  1175. sq_pushstring(v,PostgreSQL_TAG,-1);
  1176. sq_newclass(v,SQFalse);
  1177. sq_settypetag(v,-1,(void*)PostgreSQL_TAG);
  1178. sq_insert_reg_funcs(v, sq_pgsql_methods);
  1179. sq_newslot(v,-3,SQTrue);
  1180. sq_pushstring(v,PostgreSQL_Statement_TAG,-1);
  1181. sq_newclass(v,SQFalse);
  1182. sq_settypetag(v,-1,(void*)PostgreSQL_Statement_TAG);
  1183. sq_insert_reg_funcs(v, sq_pgsql_statement_methods);
  1184. sq_newslot(v,-3,SQTrue);
  1185. sq_pushstring(v,PostgreSQL_Result_TAG,-1);
  1186. sq_newclass(v,SQFalse);
  1187. sq_settypetag(v,-1,(void*)PostgreSQL_Result_TAG);
  1188. sq_insert_reg_funcs(v, sq_pgsql_result_methods);
  1189. sq_pushstring(v, _curr_row_key, -1);
  1190. sq_pushnull(v);
  1191. sq_newslot(v, -3, SQFalse);
  1192. sq_newslot(v,-3,SQTrue);
  1193. return 0;
  1194. }
  1195. #ifdef __cplusplus
  1196. }
  1197. #endif
  1198. #endif // WITH_POSTGRESQL