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