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