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