|
|
1.1 parser 1: /** @file
2: Parser PgSQL driver.
3:
1.12 paf 4: Copyright(c) 2001, 2003 ArtLebedev Group (http://www.artlebedev.com)
1.1 parser 5:
1.6 paf 6: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.1 parser 7:
8: 2001.07.30 using PgSQL 7.1.2
9: */
1.25 ! paf 10: static const char *RCSId="$Id: parser3pgsql.C,v 1.24 2004/12/23 16:18:21 paf Exp $";
1.1 parser 11:
12: #include "config_includes.h"
13:
14: #include "pa_sql_driver.h"
15:
16: #include <libpq-fe.h>
17: #include <libpq/libpq-fs.h>
18:
19: // OIDOID from catalog/pg_type.h
20: #define OIDOID 26
21: // LO_BUFSIZE from interfaces\libpq\fe-lobj.c = 8192 (0x2000)
22: // actually writing chunks of that size failed, reduced it twice
23: #define LO_BUFSIZE 0x1000
24: // from postgres_ext.h
25: #define InvalidOid ((Oid) 0)
26:
27:
28: #include "ltdl.h"
29:
30: #define MAX_STRING 0x400
31: #define MAX_NUMBER 20
32:
33: #if _MSC_VER
34: # define snprintf _snprintf
35: # define strcasecmp _stricmp
36: #endif
37:
38: #ifndef max
39: inline int max(int a,int b) { return a>b?a:b; }
40: inline int min(int a,int b){ return a<b?a:b; }
41: #endif
42:
43: static char *lsplit(char *string, char delim) {
44: if(string) {
45: char *v=strchr(string, delim);
46: if(v) {
47: *v=0;
48: return v+1;
49: }
50: }
51: return 0;
52: }
53:
1.8 paf 54: static char *lsplit(char **string_ref, char delim) {
55: char *result=*string_ref;
56: char *next=lsplit(*string_ref, delim);
57: *string_ref=next;
58: return result;
59: }
60:
1.25 ! paf 61: static char* rsplit(char* string, char delim) {
! 62: if(string) {
! 63: char* v=strrchr(string, delim);
! 64: if(v) {
! 65: *v=0;
! 66: return v+1;
! 67: }
! 68: }
! 69: return NULL;
! 70: }
! 71:
1.20 paf 72: static void toupper_str(char *out, const char *in, size_t size) {
1.18 paf 73: while(size--)
74: *out++=(char)toupper(*in++);
75: }
76:
1.16 paf 77: struct Connection {
78: SQL_Driver_services* services;
79:
80: PGconn *conn;
1.18 paf 81: const char* cstrClientCharset;
1.16 paf 82: };
83:
1.1 parser 84: /**
85: PgSQL server driver
86: */
87: class PgSQL_Driver : public SQL_Driver {
88: public:
89:
90: PgSQL_Driver() : SQL_Driver() {
91: }
92:
93: /// get api version
94: int api_version() { return SQL_DRIVER_API_VERSION; }
95: /// initialize driver by loading sql dynamic link library
1.3 paf 96: const char *initialize(char *dlopen_file_spec) {
1.1 parser 97: return dlopen_file_spec?
98: dlink(dlopen_file_spec):"client library column is empty";
99: }
100:
1.16 paf 101: #define throwPQerror connection.services->_throw(PQerrorMessage(connection.conn))
1.8 paf 102: #define PQclear_throw(msg) { \
103: PQclear(res); \
1.16 paf 104: connection.services->_throw(msg); \
1.8 paf 105: }
1.16 paf 106: #define PQclear_throwPQerror PQclear_throw(PQerrorMessage(connection.conn))
1.1 parser 107:
108: /** connect
1.21 paf 109: @param url
1.1 parser 110: format: @b user:pass@host[:port]|[local]/database
111: */
112: void connect(
1.21 paf 113: char *url,
1.1 parser 114: SQL_Driver_services& services,
1.16 paf 115: void **connection_ref ///< output: Connection*
1.1 parser 116: ) {
1.21 paf 117: char *user=url;
1.25 ! paf 118: char *host=rsplit(user, '@');
1.1 parser 119: char *db=lsplit(host, '/');
120: char *pwd=lsplit(user, ':');
121: char *port=lsplit(host, ':');
122:
1.8 paf 123: char *options=lsplit(db, '?');
124:
1.18 paf 125: char *cstrBackwardCompAskServerToTranscode=0;
126:
1.17 paf 127: Connection& connection=*(Connection *)services.malloc(sizeof(Connection));
1.16 paf 128: *connection_ref=&connection;
129: connection.services=&services;
1.18 paf 130: connection.cstrClientCharset=0;
1.16 paf 131: connection.conn=PQsetdbLogin(
1.7 paf 132: (host&&strcasecmp(host, "local")==0)?NULL/* local Unix domain socket */:host, port,
1.1 parser 133: NULL, NULL, db, user, pwd);
1.16 paf 134: if(!connection.conn)
1.1 parser 135: services._throw("PQsetdbLogin failed");
1.16 paf 136: if(PQstatus(connection.conn)!=CONNECTION_OK)
1.1 parser 137: throwPQerror;
138:
1.8 paf 139: char *charset=0;
140: char *datestyle=0;
1.23 paf 141: isDefaultTransaction = true;
1.8 paf 142:
143: while(options) {
144: if(char *key=lsplit(&options, '&')) {
145: if(*key) {
146: if(char *value=lsplit(key, '=')) {
1.18 paf 147: if(strcmp(key, "ClientCharset" ) == 0) {
1.20 paf 148: toupper_str(value, value, strlen(value));
1.18 paf 149: connection.cstrClientCharset=value;
150: } else if(strcasecmp(key, "charset")==0) { // left for backward compatibility, consider using ClientCharset
151: cstrBackwardCompAskServerToTranscode=value;
1.8 paf 152: } else if(strcasecmp(key, "datestyle")==0) {
153: datestyle=value;
1.23 paf 154: } else if(strcmp(key, "WithoutDefaultTransaction")==0) {
155: isDefaultTransaction = false;
1.8 paf 156: } else
157: services._throw("unknown connect option" /*key*/);
158: } else
159: services._throw("connect option without =value" /*key*/);
160: }
161: }
162: }
163:
1.18 paf 164: if(connection.cstrClientCharset && cstrBackwardCompAskServerToTranscode)
165: services._throw("use 'ClientCharset' option only, "
166: "'charset' option is obsolete and should not be used with new 'ClientCharset' option");
167:
168: if(cstrBackwardCompAskServerToTranscode) {
1.8 paf 169: // set CLIENT_ENCODING
170: char statement[MAX_STRING]="set CLIENT_ENCODING="; // win
1.18 paf 171: strncat(statement, cstrBackwardCompAskServerToTranscode, MAX_STRING);
1.8 paf 172:
1.16 paf 173: PGresult *res=PQexec(connection.conn, statement);
1.8 paf 174: if(!res)
175: throwPQerror;
176: PQclear(res); // throw out the result [don't need but must call]
177: }
178:
179: if(datestyle) {
180: // set DATESTYLE
181: char statement[MAX_STRING]="set DATESTYLE="; // ISO,SQL,Postgres,European,NonEuropean=US,German,DEFAULT=ISO
182: strncat(statement, charset, MAX_STRING);
183:
1.16 paf 184: PGresult *res=PQexec(connection.conn, statement);
1.8 paf 185: if(!res)
186: throwPQerror;
187: PQclear(res); // throw out the result [don't need but must call]
188: }
189:
1.16 paf 190: begin_transaction(connection);
1.1 parser 191: }
1.16 paf 192: void disconnect(void *aconnection) {
193: Connection& connection=*static_cast<Connection*>(aconnection);
194:
195: PQfinish(connection.conn);
196: connection.conn=0;
1.1 parser 197: }
1.16 paf 198: void commit(void *aconnection) {
1.23 paf 199: if(isDefaultTransaction)
200: {
201: Connection& connection=*static_cast<Connection*>(aconnection);
202:
203: if(PGresult *res=PQexec(connection.conn, "COMMIT"))
204: PQclear(res);
205: else
206: throwPQerror;
207: begin_transaction(connection);
208: }
1.1 parser 209: }
1.16 paf 210: void rollback(void *aconnection) {
1.23 paf 211: if(isDefaultTransaction)
212: {
213: Connection& connection=*static_cast<Connection*>(aconnection);
214:
215: if(PGresult *res=PQexec(connection.conn, "ROLLBACK"))
216: PQclear(res);
217: else
218: throwPQerror;
219: begin_transaction(connection);
220: }
1.1 parser 221: }
222:
1.16 paf 223: bool ping(void *aconnection) {
224: Connection& connection=*static_cast<Connection*>(aconnection);
225:
226: return PQstatus(connection.conn)==CONNECTION_OK;
1.1 parser 227: }
228:
1.13 paf 229: const char* quote(
1.16 paf 230: void *aconnection,
1.13 paf 231: const char *from, unsigned int length) {
1.16 paf 232: Connection& connection=*static_cast<Connection*>(aconnection);
233:
234: char *result=(char*)connection.services->malloc_atomic(length*2+1);
1.13 paf 235: char *to=result;
236: while(length--) {
237: switch(*from) {
238: case '\'': // "'" -> "''"
1.14 paf 239: *to++='\'';
1.13 paf 240: break;
241: case '\\': // "\" -> "\\"
1.14 paf 242: *to++='\\';
1.13 paf 243: break;
1.1 parser 244: }
1.13 paf 245: *to++=*from++;
246: }
247: *to=0;
248: return result;
249: }
1.16 paf 250: void query(void *aconnection,
1.22 paf 251: const char *astatement,
252: size_t placeholders_count, Placeholder* placeholders,
253: unsigned long offset, unsigned long limit,
1.1 parser 254: SQL_Driver_query_event_handlers& handlers) {
255: // _asm int 3;
1.16 paf 256: Connection& connection=*static_cast<Connection*>(aconnection);
1.19 paf 257: const char* cstrClientCharset=connection.cstrClientCharset;
1.16 paf 258: SQL_Driver_services& services=*connection.services;
259: PGconn *conn=connection.conn;
1.22 paf 260:
261: if(placeholders_count>0)
262: services._throw("bind variables not supported (yet)");
1.1 parser 263:
1.18 paf 264: // transcode from $request:charset to connect-string?client_charset
1.19 paf 265: if(cstrClientCharset) {
1.18 paf 266: size_t transcoded_statement_size;
267: services.transcode(astatement, strlen(astatement),
268: astatement, transcoded_statement_size,
269: services.request_charset(),
270: cstrClientCharset);
271: }
272:
1.16 paf 273: const char *statement=preprocess_statement(connection,
1.1 parser 274: astatement, offset, limit);
275:
276: PGresult *res=PQexec(conn, statement);
277: if(!res)
278: throwPQerror;
279:
280: switch(PQresultStatus(res)) {
281: case PGRES_EMPTY_QUERY:
282: PQclear_throw("no query");
283: break;
284: case PGRES_COMMAND_OK:
285: // empty result: insert|delete|update|...
286: PQclear(res);
287: return;
288: case PGRES_TUPLES_OK:
289: break;
290: default:
291: PQclear_throwPQerror;
292: break;
293: }
294:
295: int column_count=PQnfields(res);
296: if(!column_count)
297: PQclear_throw("result contains no columns");
298:
1.9 paf 299: bool failed=false;
300: SQL_Error sql_error;
301: #define CHECK(afailed) \
302: if(afailed) { \
303: failed=true; \
304: goto cleanup; \
305: }
306:
1.1 parser 307: for(int i=0; i<column_count; i++){
308: char *name=PQfname(res, i);
1.18 paf 309: size_t length=strlen(name);
1.19 paf 310: char* strm=(char*)services.malloc(length+1);
311: memcpy(strm, name, length+1);
312: const char* str=strm;
1.18 paf 313:
314: // transcode to $request:charset from connect-string?client_charset
1.19 paf 315: if(cstrClientCharset)
1.18 paf 316: services.transcode(str, length,
317: str, length,
318: cstrClientCharset,
319: services.request_charset());
320:
321: CHECK(handlers.add_column(sql_error, str, length));
1.1 parser 322: }
323:
1.9 paf 324: CHECK(handlers.before_rows(sql_error));
1.1 parser 325:
326: if(unsigned long row_count=(unsigned long)PQntuples(res))
327: for(unsigned long r=0; r<row_count; r++) {
1.9 paf 328: CHECK(handlers.add_row(sql_error));
1.1 parser 329: for(int i=0; i<column_count; i++){
330: const char *cell=PQgetvalue(res, r, i);
1.18 paf 331: size_t length;
1.19 paf 332: const char* str;
1.1 parser 333: if(PQftype(res, i)==OIDOID) {
334: // ObjectID column, read object bytes
335:
336: char *error_pos=0;
337: Oid oid=cell?atoi(cell):0;
338: int fd=lo_open(conn, oid, INV_READ);
339: if(fd>=0) {
340: // seek to end
341: if(lo_lseek(conn, fd, 0, SEEK_END)<0)
342: PQclear_throwPQerror;
1.18 paf 343: // get length
1.1 parser 344: int size_tell=lo_tell(conn, fd);
345: if(size_tell<0)
346: PQclear_throwPQerror;
347: // seek to begin
348: if(lo_lseek(conn, fd, 0, SEEK_SET)<0)
349: PQclear_throwPQerror;
1.18 paf 350: length=(size_t)size_tell;
351: if(length) {
1.1 parser 352: // read
1.19 paf 353: char* strm=(char*)services.malloc(length+1);
354: if(!lo_read_ex(conn, fd, strm, size_tell))
1.1 parser 355: PQclear_throw("lo_read can not read all bytes of object");
1.19 paf 356: strm[length]=0;
357: str=strm;
1.1 parser 358: } else
1.13 paf 359: str=0;
1.1 parser 360: if(lo_close(conn, fd)<0)
361: PQclear_throwPQerror;
362: } else
363: PQclear_throwPQerror;
364: } else {
365: // normal column, read it normally
1.18 paf 366: length=(size_t)PQgetlength(res, r, i);
367: if(length) {
1.19 paf 368: char* strm=(char*)services.malloc(length+1);
369: memcpy(strm, cell, length+1);
370: str=strm;
1.1 parser 371: } else
1.13 paf 372: str=0;
1.1 parser 373: }
1.18 paf 374:
375: if(str && length) {
376: // transcode to $request:charset from connect-string?client_charset
1.19 paf 377: if(cstrClientCharset)
1.18 paf 378: services.transcode(str, length,
379: str, length,
380: cstrClientCharset,
381: services.request_charset());
382: }
383:
384: CHECK(handlers.add_row_cell(sql_error, str, length));
1.1 parser 385: }
386: }
1.9 paf 387: cleanup:
1.1 parser 388: PQclear(res);
1.9 paf 389: if(failed)
390: services._throw(sql_error);
1.1 parser 391: }
392:
393: private: // private funcs
394:
1.16 paf 395: void begin_transaction(Connection& connection) {
1.23 paf 396: if(isDefaultTransaction)
397: {
398: if(PGresult *res=PQexec(connection.conn, "BEGIN"))
399: PQclear(res);
400: else
401: throwPQerror;
402: }
1.1 parser 403: }
404:
1.16 paf 405: const char *preprocess_statement(Connection& connection,
1.1 parser 406: const char *astatement, unsigned long offset, unsigned long limit) {
1.16 paf 407: PGconn *conn=connection.conn;
408:
1.1 parser 409: size_t statement_size=strlen(astatement);
410:
1.16 paf 411: char *result=(char *)connection.services->malloc(statement_size
1.1 parser 412: +MAX_NUMBER*2+15 // limit # offset #
413: +MAX_STRING // in case of short 'strings'
414: +1);
415: // offset & limit -> suffixes
416: const char *o;
417: if(offset || limit) {
418: char *cur=result;
419: memcpy(cur, astatement, statement_size); cur+=statement_size;
420: if(limit)
421: cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit);
422: if(offset)
423: cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset);
424: o=result;
425: } else
426: o=astatement;
427:
428: // /**xxx**/'literal' -> oid
429: char *n=result;
430: while(*o) {
431: if(
432: o[0]=='/' &&
433: o[1]=='*' &&
434: o[2]=='*') { // name start
1.15 paf 435: const char* saved_o=o;
1.1 parser 436: o+=3;
437: while(*o)
438: if(
439: o[0]=='*' &&
440: o[1]=='*' &&
441: o[2]=='/' &&
442: o[3]=='\'') { // name end
1.15 paf 443: saved_o=0; // found, marking that
1.1 parser 444: o+=4;
445: Oid oid=lo_creat(conn, INV_READ|INV_WRITE);
446: if(oid==InvalidOid)
447: throwPQerror;
448: int fd=lo_open(conn, oid, INV_WRITE);
449: if(fd>=0) {
450: const char *start=o;
451: bool escaped=false;
452: while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) {
453: escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\'');
454: if(escaped) {
455: // write pending, skip "\" or "'"
456: if(!lo_write_ex(conn, fd, start, o-start))
1.16 paf 457: connection.services->_throw("lo_write could not write all bytes of object (1)");
1.1 parser 458: start=++o;
459: } else
460: o++;
461: }
462: if(!lo_write_ex(conn, fd, start, o-start))
1.16 paf 463: connection.services->_throw("lo_write can not write all bytes of object (2)");
1.1 parser 464: if(lo_close(conn, fd)<0)
465: throwPQerror;
466: } else
467: throwPQerror;
468: if(*o)
469: o++; // skip "'"
470:
471: n+=snprintf(n, MAX_NUMBER, "%u", oid);
472: break;
473: } else
474: o++; // /**skip**/'xxx'
1.15 paf 475: if(saved_o) {
476: o=saved_o;
477: *n++=*o++;
478: }
1.1 parser 479: } else
480: *n++=*o++;
481: }
482: *n=0;
483:
484: return result;
485: }
486:
487: private: // lo_read/write exchancements
488:
489: bool lo_read_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
490: int size_read;
491: while(len && (size_read=lo_read(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
492: buf+=size_read;
493: len-=size_read;
494: }
495: return len==0;
496: }
497:
498: bool lo_write_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
499: int size_written;
500: while(len && (size_written=lo_write(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
501: buf+=size_written;
502: len-=size_written;
503: }
504: return len==0;
505: }
506:
507: private: // conn client library funcs
508:
509: typedef PGconn* (*t_PQsetdbLogin)(
510: const char *pghost,
511: const char *pgport,
512: const char *pgoptions,
513: const char *pgtty,
514: const char *dbName,
515: const char *login,
516: const char *pwd); t_PQsetdbLogin PQsetdbLogin;
517: typedef void (*t_PQfinish)(PGconn *conn); t_PQfinish PQfinish;
518: typedef char *(*t_PQerrorMessage)(const PGconn* conn); t_PQerrorMessage PQerrorMessage;
519: typedef ConnStatusType (*t_PQstatus)(const PGconn *conn); t_PQstatus PQstatus;
520: typedef PGresult *(*t_PQexec)(PGconn *conn,
521: const char *query); t_PQexec PQexec;
522: typedef ExecStatusType (*t_PQresultStatus)(const PGresult *res); t_PQresultStatus PQresultStatus;
523: typedef int (*t_PQgetlength)(const PGresult *res,
524: int tup_num,
525: int field_num); t_PQgetlength PQgetlength;
526: typedef char* (*t_PQgetvalue)(const PGresult *res,
527: int tup_num,
528: int field_num); t_PQgetvalue PQgetvalue;
529: typedef int (*t_PQntuples)(const PGresult *res); t_PQntuples PQntuples;
530: typedef char *(*t_PQfname)(const PGresult *res,
531: int field_index); t_PQfname PQfname;
532: typedef int (*t_PQnfields)(const PGresult *res); t_PQnfields PQnfields;
533: typedef void (*t_PQclear)(PGresult *res); t_PQclear PQclear;
534:
535: typedef Oid (*t_PQftype)(const PGresult *res, int field_num); t_PQftype PQftype;
536:
537: typedef int (*t_lo_open)(PGconn *conn, Oid lobjId, int mode); t_lo_open lo_open;
538: typedef int (*t_lo_close)(PGconn *conn, int fd); t_lo_close lo_close;
539: typedef int (*t_lo_read)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_read lo_read;
540: typedef int (*t_lo_write)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_write lo_write;
541: typedef int (*t_lo_lseek)(PGconn *conn, int fd, int offset, int whence); t_lo_lseek lo_lseek;
542: typedef Oid (*t_lo_creat)(PGconn *conn, int mode); t_lo_creat lo_creat;
543: typedef int (*t_lo_tell)(PGconn *conn, int fd); t_lo_tell lo_tell;
544: typedef int (*t_lo_unlink)(PGconn *conn, Oid lobjId); t_lo_unlink lo_unlink;
545: typedef Oid (*t_lo_import)(PGconn *conn, const char *filename); t_lo_import lo_import;
546: typedef int (*t_lo_export)(PGconn *conn, Oid lobjId, const char *filename); t_lo_export lo_export;
547:
548: private: // conn client library funcs linking
549:
550: const char *dlink(const char *dlopen_file_spec) {
1.11 paf 551: if(lt_dlinit())
552: return lt_dlerror();
1.1 parser 553: lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
554: if(!handle)
555: return "can not open the dynamic link module";
556:
557: #define DSLINK(name, action) \
558: name=(t_##name)lt_dlsym(handle, #name); \
559: if(!name) \
560: action;
561:
562: #define DLINK(name) DSLINK(name, return "function " #name " was not found")
563:
564: DLINK(PQsetdbLogin);
565: DLINK(PQerrorMessage);
566: DLINK(PQstatus);
567: DLINK(PQfinish);
568: DLINK(PQgetvalue);
569: DLINK(PQgetlength);
570: DLINK(PQntuples);
571: DLINK(PQfname);
572: DLINK(PQnfields);
573: DLINK(PQclear);
574: DLINK(PQresultStatus);
575: DLINK(PQexec);
576: DLINK(PQftype);
577: DLINK(lo_open); DLINK(lo_close);
578: DLINK(lo_read); DLINK(lo_write);
579: DLINK(lo_lseek); DLINK(lo_creat);
580: DLINK(lo_tell); DLINK(lo_unlink);
581: DLINK(lo_import); DLINK(lo_export);
582:
583: return 0;
584: }
585:
1.23 paf 586: bool isDefaultTransaction;
1.1 parser 587: };
588:
589: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
590: return new PgSQL_Driver();
1.2 paf 591: }