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