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