|
|
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.22 ! paf 10: static const char *RCSId="$Id: parser3pgsql.C,v 1.21 2004/05/25 07:07:48 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;
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) {
1.20 paf 136: toupper_str(value, value, strlen(value));
1.18 paf 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.22 ! paf 231: const char *astatement,
! 232: size_t placeholders_count, Placeholder* placeholders,
! 233: unsigned long offset, unsigned long limit,
1.1 parser 234: SQL_Driver_query_event_handlers& handlers) {
235: // _asm int 3;
1.16 paf 236: Connection& connection=*static_cast<Connection*>(aconnection);
1.19 paf 237: const char* cstrClientCharset=connection.cstrClientCharset;
1.16 paf 238: SQL_Driver_services& services=*connection.services;
239: PGconn *conn=connection.conn;
1.22 ! paf 240:
! 241: if(placeholders_count>0)
! 242: services._throw("bind variables not supported (yet)");
1.1 parser 243:
1.18 paf 244: // transcode from $request:charset to connect-string?client_charset
1.19 paf 245: if(cstrClientCharset) {
1.18 paf 246: size_t transcoded_statement_size;
247: services.transcode(astatement, strlen(astatement),
248: astatement, transcoded_statement_size,
249: services.request_charset(),
250: cstrClientCharset);
251: }
252:
1.16 paf 253: const char *statement=preprocess_statement(connection,
1.1 parser 254: astatement, offset, limit);
255:
256: PGresult *res=PQexec(conn, statement);
257: if(!res)
258: throwPQerror;
259:
260: switch(PQresultStatus(res)) {
261: case PGRES_EMPTY_QUERY:
262: PQclear_throw("no query");
263: break;
264: case PGRES_COMMAND_OK:
265: // empty result: insert|delete|update|...
266: PQclear(res);
267: return;
268: case PGRES_TUPLES_OK:
269: break;
270: default:
271: PQclear_throwPQerror;
272: break;
273: }
274:
275: int column_count=PQnfields(res);
276: if(!column_count)
277: PQclear_throw("result contains no columns");
278:
1.9 paf 279: bool failed=false;
280: SQL_Error sql_error;
281: #define CHECK(afailed) \
282: if(afailed) { \
283: failed=true; \
284: goto cleanup; \
285: }
286:
1.1 parser 287: for(int i=0; i<column_count; i++){
288: char *name=PQfname(res, i);
1.18 paf 289: size_t length=strlen(name);
1.19 paf 290: char* strm=(char*)services.malloc(length+1);
291: memcpy(strm, name, length+1);
292: const char* str=strm;
1.18 paf 293:
294: // transcode to $request:charset from connect-string?client_charset
1.19 paf 295: if(cstrClientCharset)
1.18 paf 296: services.transcode(str, length,
297: str, length,
298: cstrClientCharset,
299: services.request_charset());
300:
301: CHECK(handlers.add_column(sql_error, str, length));
1.1 parser 302: }
303:
1.9 paf 304: CHECK(handlers.before_rows(sql_error));
1.1 parser 305:
306: if(unsigned long row_count=(unsigned long)PQntuples(res))
307: for(unsigned long r=0; r<row_count; r++) {
1.9 paf 308: CHECK(handlers.add_row(sql_error));
1.1 parser 309: for(int i=0; i<column_count; i++){
310: const char *cell=PQgetvalue(res, r, i);
1.18 paf 311: size_t length;
1.19 paf 312: const char* str;
1.1 parser 313: if(PQftype(res, i)==OIDOID) {
314: // ObjectID column, read object bytes
315:
316: char *error_pos=0;
317: Oid oid=cell?atoi(cell):0;
318: int fd=lo_open(conn, oid, INV_READ);
319: if(fd>=0) {
320: // seek to end
321: if(lo_lseek(conn, fd, 0, SEEK_END)<0)
322: PQclear_throwPQerror;
1.18 paf 323: // get length
1.1 parser 324: int size_tell=lo_tell(conn, fd);
325: if(size_tell<0)
326: PQclear_throwPQerror;
327: // seek to begin
328: if(lo_lseek(conn, fd, 0, SEEK_SET)<0)
329: PQclear_throwPQerror;
1.18 paf 330: length=(size_t)size_tell;
331: if(length) {
1.1 parser 332: // read
1.19 paf 333: char* strm=(char*)services.malloc(length+1);
334: if(!lo_read_ex(conn, fd, strm, size_tell))
1.1 parser 335: PQclear_throw("lo_read can not read all bytes of object");
1.19 paf 336: strm[length]=0;
337: str=strm;
1.1 parser 338: } else
1.13 paf 339: str=0;
1.1 parser 340: if(lo_close(conn, fd)<0)
341: PQclear_throwPQerror;
342: } else
343: PQclear_throwPQerror;
344: } else {
345: // normal column, read it normally
1.18 paf 346: length=(size_t)PQgetlength(res, r, i);
347: if(length) {
1.19 paf 348: char* strm=(char*)services.malloc(length+1);
349: memcpy(strm, cell, length+1);
350: str=strm;
1.1 parser 351: } else
1.13 paf 352: str=0;
1.1 parser 353: }
1.18 paf 354:
355: if(str && length) {
356: // transcode to $request:charset from connect-string?client_charset
1.19 paf 357: if(cstrClientCharset)
1.18 paf 358: services.transcode(str, length,
359: str, length,
360: cstrClientCharset,
361: services.request_charset());
362: }
363:
364: CHECK(handlers.add_row_cell(sql_error, str, length));
1.1 parser 365: }
366: }
1.9 paf 367: cleanup:
1.1 parser 368: PQclear(res);
1.9 paf 369: if(failed)
370: services._throw(sql_error);
1.1 parser 371: }
372:
373: private: // private funcs
374:
1.16 paf 375: void begin_transaction(Connection& connection) {
376: if(PGresult *res=PQexec(connection.conn, "BEGIN"))
1.1 parser 377: PQclear(res);
378: else
379: throwPQerror;
380: }
381:
1.16 paf 382: const char *preprocess_statement(Connection& connection,
1.1 parser 383: const char *astatement, unsigned long offset, unsigned long limit) {
1.16 paf 384: PGconn *conn=connection.conn;
385:
1.1 parser 386: size_t statement_size=strlen(astatement);
387:
1.16 paf 388: char *result=(char *)connection.services->malloc(statement_size
1.1 parser 389: +MAX_NUMBER*2+15 // limit # offset #
390: +MAX_STRING // in case of short 'strings'
391: +1);
392: // offset & limit -> suffixes
393: const char *o;
394: if(offset || limit) {
395: char *cur=result;
396: memcpy(cur, astatement, statement_size); cur+=statement_size;
397: if(limit)
398: cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit);
399: if(offset)
400: cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset);
401: o=result;
402: } else
403: o=astatement;
404:
405: // /**xxx**/'literal' -> oid
406: char *n=result;
407: while(*o) {
408: if(
409: o[0]=='/' &&
410: o[1]=='*' &&
411: o[2]=='*') { // name start
1.15 paf 412: const char* saved_o=o;
1.1 parser 413: o+=3;
414: while(*o)
415: if(
416: o[0]=='*' &&
417: o[1]=='*' &&
418: o[2]=='/' &&
419: o[3]=='\'') { // name end
1.15 paf 420: saved_o=0; // found, marking that
1.1 parser 421: o+=4;
422: Oid oid=lo_creat(conn, INV_READ|INV_WRITE);
423: if(oid==InvalidOid)
424: throwPQerror;
425: int fd=lo_open(conn, oid, INV_WRITE);
426: if(fd>=0) {
427: const char *start=o;
428: bool escaped=false;
429: while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) {
430: escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\'');
431: if(escaped) {
432: // write pending, skip "\" or "'"
433: if(!lo_write_ex(conn, fd, start, o-start))
1.16 paf 434: connection.services->_throw("lo_write could not write all bytes of object (1)");
1.1 parser 435: start=++o;
436: } else
437: o++;
438: }
439: if(!lo_write_ex(conn, fd, start, o-start))
1.16 paf 440: connection.services->_throw("lo_write can not write all bytes of object (2)");
1.1 parser 441: if(lo_close(conn, fd)<0)
442: throwPQerror;
443: } else
444: throwPQerror;
445: if(*o)
446: o++; // skip "'"
447:
448: n+=snprintf(n, MAX_NUMBER, "%u", oid);
449: break;
450: } else
451: o++; // /**skip**/'xxx'
1.15 paf 452: if(saved_o) {
453: o=saved_o;
454: *n++=*o++;
455: }
1.1 parser 456: } else
457: *n++=*o++;
458: }
459: *n=0;
460:
461: return result;
462: }
463:
464: private: // lo_read/write exchancements
465:
466: bool lo_read_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
467: int size_read;
468: while(len && (size_read=lo_read(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
469: buf+=size_read;
470: len-=size_read;
471: }
472: return len==0;
473: }
474:
475: bool lo_write_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
476: int size_written;
477: while(len && (size_written=lo_write(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
478: buf+=size_written;
479: len-=size_written;
480: }
481: return len==0;
482: }
483:
484: private: // conn client library funcs
485:
486: typedef PGconn* (*t_PQsetdbLogin)(
487: const char *pghost,
488: const char *pgport,
489: const char *pgoptions,
490: const char *pgtty,
491: const char *dbName,
492: const char *login,
493: const char *pwd); t_PQsetdbLogin PQsetdbLogin;
494: typedef void (*t_PQfinish)(PGconn *conn); t_PQfinish PQfinish;
495: typedef char *(*t_PQerrorMessage)(const PGconn* conn); t_PQerrorMessage PQerrorMessage;
496: typedef ConnStatusType (*t_PQstatus)(const PGconn *conn); t_PQstatus PQstatus;
497: typedef PGresult *(*t_PQexec)(PGconn *conn,
498: const char *query); t_PQexec PQexec;
499: typedef ExecStatusType (*t_PQresultStatus)(const PGresult *res); t_PQresultStatus PQresultStatus;
500: typedef int (*t_PQgetlength)(const PGresult *res,
501: int tup_num,
502: int field_num); t_PQgetlength PQgetlength;
503: typedef char* (*t_PQgetvalue)(const PGresult *res,
504: int tup_num,
505: int field_num); t_PQgetvalue PQgetvalue;
506: typedef int (*t_PQntuples)(const PGresult *res); t_PQntuples PQntuples;
507: typedef char *(*t_PQfname)(const PGresult *res,
508: int field_index); t_PQfname PQfname;
509: typedef int (*t_PQnfields)(const PGresult *res); t_PQnfields PQnfields;
510: typedef void (*t_PQclear)(PGresult *res); t_PQclear PQclear;
511:
512: typedef Oid (*t_PQftype)(const PGresult *res, int field_num); t_PQftype PQftype;
513:
514: typedef int (*t_lo_open)(PGconn *conn, Oid lobjId, int mode); t_lo_open lo_open;
515: typedef int (*t_lo_close)(PGconn *conn, int fd); t_lo_close lo_close;
516: typedef int (*t_lo_read)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_read lo_read;
517: typedef int (*t_lo_write)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_write lo_write;
518: typedef int (*t_lo_lseek)(PGconn *conn, int fd, int offset, int whence); t_lo_lseek lo_lseek;
519: typedef Oid (*t_lo_creat)(PGconn *conn, int mode); t_lo_creat lo_creat;
520: typedef int (*t_lo_tell)(PGconn *conn, int fd); t_lo_tell lo_tell;
521: typedef int (*t_lo_unlink)(PGconn *conn, Oid lobjId); t_lo_unlink lo_unlink;
522: typedef Oid (*t_lo_import)(PGconn *conn, const char *filename); t_lo_import lo_import;
523: typedef int (*t_lo_export)(PGconn *conn, Oid lobjId, const char *filename); t_lo_export lo_export;
524:
525: private: // conn client library funcs linking
526:
527: const char *dlink(const char *dlopen_file_spec) {
1.11 paf 528: if(lt_dlinit())
529: return lt_dlerror();
1.1 parser 530: lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
531: if(!handle)
532: return "can not open the dynamic link module";
533:
534: #define DSLINK(name, action) \
535: name=(t_##name)lt_dlsym(handle, #name); \
536: if(!name) \
537: action;
538:
539: #define DLINK(name) DSLINK(name, return "function " #name " was not found")
540:
541: DLINK(PQsetdbLogin);
542: DLINK(PQerrorMessage);
543: DLINK(PQstatus);
544: DLINK(PQfinish);
545: DLINK(PQgetvalue);
546: DLINK(PQgetlength);
547: DLINK(PQntuples);
548: DLINK(PQfname);
549: DLINK(PQnfields);
550: DLINK(PQclear);
551: DLINK(PQresultStatus);
552: DLINK(PQexec);
553: DLINK(PQftype);
554: DLINK(lo_open); DLINK(lo_close);
555: DLINK(lo_read); DLINK(lo_write);
556: DLINK(lo_lseek); DLINK(lo_creat);
557: DLINK(lo_tell); DLINK(lo_unlink);
558: DLINK(lo_import); DLINK(lo_export);
559:
560: return 0;
561: }
562:
563: };
564:
565: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
566: return new PgSQL_Driver();
1.2 paf 567: }