|
|
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.8 ! paf 10: static const char *RCSId="$Id: parser3pgsql.C,v 1.7 2002/03/22 15:50:25 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 '\\': // "\" -> "\\"
189: *to++='\''; result++;
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:
232: for(int i=0; i<column_count; i++){
233: char *name=PQfname(res, i);
234: size_t size=strlen(name);
235: void *ptr=services.malloc(size);
236: memcpy(ptr, name, size);
237: handlers.add_column(ptr, size);
238: }
239:
240: handlers.before_rows();
241:
242: if(unsigned long row_count=(unsigned long)PQntuples(res))
243: for(unsigned long r=0; r<row_count; r++) {
244: handlers.add_row();
245: for(int i=0; i<column_count; i++){
246: const char *cell=PQgetvalue(res, r, i);
247: size_t size;
248: void *ptr;
249: if(PQftype(res, i)==OIDOID) {
250: // ObjectID column, read object bytes
251:
252: char *error_pos=0;
253: Oid oid=cell?atoi(cell):0;
254: int fd=lo_open(conn, oid, INV_READ);
255: if(fd>=0) {
256: // seek to end
257: if(lo_lseek(conn, fd, 0, SEEK_END)<0)
258: PQclear_throwPQerror;
259: // get size
260: int size_tell=lo_tell(conn, fd);
261: if(size_tell<0)
262: PQclear_throwPQerror;
263: // seek to begin
264: if(lo_lseek(conn, fd, 0, SEEK_SET)<0)
265: PQclear_throwPQerror;
266: size=(size_t)size_tell;
267: if(size) {
268: // read
269: ptr=services.malloc(size);
270: if(!lo_read_ex(conn, fd, (const char *)ptr, size_tell))
271: PQclear_throw("lo_read can not read all bytes of object");
272: } else
273: ptr=0;
274: if(lo_close(conn, fd)<0)
275: PQclear_throwPQerror;
276: } else
277: PQclear_throwPQerror;
278: } else {
279: // normal column, read it normally
280: size=(size_t)PQgetlength(res, r, i);
281: if(size) {
282: ptr=services.malloc(size);
283: memcpy(ptr, cell, size);
284: } else
285: ptr=0;
286: }
287: handlers.add_row_cell(ptr, size);
288: }
289: }
290:
291: PQclear(res);
292: }
293:
294: private: // private funcs
295:
296: void begin_transaction(SQL_Driver_services& services, PGconn *conn) {
297: if(PGresult *res=PQexec(conn, "BEGIN"))
298: PQclear(res);
299: else
300: throwPQerror;
301: }
302:
303: const char *preprocess_statement(SQL_Driver_services& services, PGconn *conn,
304: const char *astatement, unsigned long offset, unsigned long limit) {
305: size_t statement_size=strlen(astatement);
306:
307: char *result=(char *)services.malloc(statement_size
308: +MAX_NUMBER*2+15 // limit # offset #
309: +MAX_STRING // in case of short 'strings'
310: +1);
311: // offset & limit -> suffixes
312: const char *o;
313: if(offset || limit) {
314: char *cur=result;
315: memcpy(cur, astatement, statement_size); cur+=statement_size;
316: if(limit)
317: cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit);
318: if(offset)
319: cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset);
320: o=result;
321: } else
322: o=astatement;
323:
324: // /**xxx**/'literal' -> oid
325: char *n=result;
326: while(*o) {
327: if(
328: o[0]=='/' &&
329: o[1]=='*' &&
330: o[2]=='*') { // name start
331: o+=3;
332: while(*o)
333: if(
334: o[0]=='*' &&
335: o[1]=='*' &&
336: o[2]=='/' &&
337: o[3]=='\'') { // name end
338: o+=4;
339: Oid oid=lo_creat(conn, INV_READ|INV_WRITE);
340: if(oid==InvalidOid)
341: throwPQerror;
342: int fd=lo_open(conn, oid, INV_WRITE);
343: if(fd>=0) {
344: const char *start=o;
345: bool escaped=false;
346: while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) {
347: escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\'');
348: if(escaped) {
349: // write pending, skip "\" or "'"
350: if(!lo_write_ex(conn, fd, start, o-start))
351: services._throw("lo_write could not write all bytes of object (1)");
352: start=++o;
353: } else
354: o++;
355: }
356: if(!lo_write_ex(conn, fd, start, o-start))
357: services._throw("lo_write can not write all bytes of object (2)");
358: if(lo_close(conn, fd)<0)
359: throwPQerror;
360: } else
361: throwPQerror;
362: if(*o)
363: o++; // skip "'"
364:
365: n+=snprintf(n, MAX_NUMBER, "%u", oid);
366: break;
367: } else
368: o++; // /**skip**/'xxx'
369: } else
370: *n++=*o++;
371: }
372: *n=0;
373:
374: return result;
375: }
376:
377: private: // lo_read/write exchancements
378:
379: bool lo_read_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
380: int size_read;
381: while(len && (size_read=lo_read(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
382: buf+=size_read;
383: len-=size_read;
384: }
385: return len==0;
386: }
387:
388: bool lo_write_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) {
389: int size_written;
390: while(len && (size_written=lo_write(conn, fd, buf, min(LO_BUFSIZE, len)))>0) {
391: buf+=size_written;
392: len-=size_written;
393: }
394: return len==0;
395: }
396:
397: private: // conn client library funcs
398:
399: typedef PGconn* (*t_PQsetdbLogin)(
400: const char *pghost,
401: const char *pgport,
402: const char *pgoptions,
403: const char *pgtty,
404: const char *dbName,
405: const char *login,
406: const char *pwd); t_PQsetdbLogin PQsetdbLogin;
407: typedef void (*t_PQfinish)(PGconn *conn); t_PQfinish PQfinish;
408: typedef char *(*t_PQerrorMessage)(const PGconn* conn); t_PQerrorMessage PQerrorMessage;
409: typedef ConnStatusType (*t_PQstatus)(const PGconn *conn); t_PQstatus PQstatus;
410: typedef PGresult *(*t_PQexec)(PGconn *conn,
411: const char *query); t_PQexec PQexec;
412: typedef ExecStatusType (*t_PQresultStatus)(const PGresult *res); t_PQresultStatus PQresultStatus;
413: typedef int (*t_PQgetlength)(const PGresult *res,
414: int tup_num,
415: int field_num); t_PQgetlength PQgetlength;
416: typedef char* (*t_PQgetvalue)(const PGresult *res,
417: int tup_num,
418: int field_num); t_PQgetvalue PQgetvalue;
419: typedef int (*t_PQntuples)(const PGresult *res); t_PQntuples PQntuples;
420: typedef char *(*t_PQfname)(const PGresult *res,
421: int field_index); t_PQfname PQfname;
422: typedef int (*t_PQnfields)(const PGresult *res); t_PQnfields PQnfields;
423: typedef void (*t_PQclear)(PGresult *res); t_PQclear PQclear;
424:
425: typedef Oid (*t_PQftype)(const PGresult *res, int field_num); t_PQftype PQftype;
426:
427: typedef int (*t_lo_open)(PGconn *conn, Oid lobjId, int mode); t_lo_open lo_open;
428: typedef int (*t_lo_close)(PGconn *conn, int fd); t_lo_close lo_close;
429: typedef int (*t_lo_read)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_read lo_read;
430: typedef int (*t_lo_write)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_write lo_write;
431: typedef int (*t_lo_lseek)(PGconn *conn, int fd, int offset, int whence); t_lo_lseek lo_lseek;
432: typedef Oid (*t_lo_creat)(PGconn *conn, int mode); t_lo_creat lo_creat;
433: typedef int (*t_lo_tell)(PGconn *conn, int fd); t_lo_tell lo_tell;
434: typedef int (*t_lo_unlink)(PGconn *conn, Oid lobjId); t_lo_unlink lo_unlink;
435: typedef Oid (*t_lo_import)(PGconn *conn, const char *filename); t_lo_import lo_import;
436: typedef int (*t_lo_export)(PGconn *conn, Oid lobjId, const char *filename); t_lo_export lo_export;
437:
438: private: // conn client library funcs linking
439:
440: const char *dlink(const char *dlopen_file_spec) {
441: lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
442: if(!handle)
443: return "can not open the dynamic link module";
444:
445: #define DSLINK(name, action) \
446: name=(t_##name)lt_dlsym(handle, #name); \
447: if(!name) \
448: action;
449:
450: #define DLINK(name) DSLINK(name, return "function " #name " was not found")
451:
452: DLINK(PQsetdbLogin);
453: DLINK(PQerrorMessage);
454: DLINK(PQstatus);
455: DLINK(PQfinish);
456: DLINK(PQgetvalue);
457: DLINK(PQgetlength);
458: DLINK(PQntuples);
459: DLINK(PQfname);
460: DLINK(PQnfields);
461: DLINK(PQclear);
462: DLINK(PQresultStatus);
463: DLINK(PQexec);
464: DLINK(PQftype);
465: DLINK(lo_open); DLINK(lo_close);
466: DLINK(lo_read); DLINK(lo_write);
467: DLINK(lo_lseek); DLINK(lo_creat);
468: DLINK(lo_tell); DLINK(lo_unlink);
469: DLINK(lo_import); DLINK(lo_export);
470:
471: return 0;
472: }
473:
474: };
475:
476: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
477: return new PgSQL_Driver();
1.2 paf 478: }