|
|
| version 1.29, 2008/06/24 17:43:48 | version 1.32, 2008/12/18 01:45:03 |
|---|---|
| Line 1 | Line 1 |
| /** @file | /** @file |
| Parser PgSQL driver. | Parser PgSQL driver. |
| Copyright(c) 2001, 2003 ArtLebedev Group (http://www.artlebedev.com) | Copyright(c) 2001, 2003 ArtLebedev Group (http://www.artlebedev.com) |
| Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru) | Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru) |
| 2007.10.25 using PgSQL 8.1.5 | 2007.10.25 using PgSQL 8.1.5 |
| */ | */ |
| static const char *RCSId="$Id$"; | static const char *RCSId="$Id$"; |
| #include "config_includes.h" | #include "config_includes.h" |
| #include "pa_sql_driver.h" | #include "pa_sql_driver.h" |
| #include <libpq-fe.h> | #include <libpq-fe.h> |
| #include <libpq/libpq-fs.h> | #include <libpq/libpq-fs.h> |
| // OIDOID from catalog/pg_type.h | // from catalog/pg_type.h |
| #define OIDOID 26 | #define BOOLOID 16 |
| // LO_BUFSIZE from interfaces\libpq\fe-lobj.c = 8192 (0x2000) | #define INT8OID 20 |
| // actually writing chunks of that size failed, reduced it twice | #define INT2OID 21 |
| #define LO_BUFSIZE 0x1000 | #define INT4OID 23 |
| // from postgres_ext.h | #define OIDOID 26 |
| //#define InvalidOid ((Oid) 0) | #define FLOAT4OID 700 |
| #define FLOAT8OID 701 | |
| #define DATEOID 1082 | |
| #include "ltdl.h" | #define TIMEOID 1083 |
| #define TIMESTAMPOID 1114 | |
| #define MAX_STRING 0x400 | #define TIMESTAMPTZOID 1184 |
| #define MAX_NUMBER 20 | #define TIMETZOID 1266 |
| #define NUMERICOID 1700 | |
| #if _MSC_VER | |
| # define snprintf _snprintf | // LO_BUFSIZE from interfaces\libpq\fe-lobj.c = 8192 (0x2000) |
| # define strcasecmp _stricmp | // actually writing chunks of that size failed, reduced it twice |
| #endif | #define LO_BUFSIZE 0x1000 |
| #ifndef max | |
| inline int max(int a,int b) { return a>b?a:b; } | #include "ltdl.h" |
| inline int min(int a,int b){ return a<b?a:b; } | |
| #endif | #define MAX_COLS 500 |
| static char *lsplit(char *string, char delim) { | #define MAX_STRING 0x400 |
| if(string) { | #define MAX_NUMBER 20 |
| char *v=strchr(string, delim); | |
| if(v) { | #if _MSC_VER |
| *v=0; | # define snprintf _snprintf |
| return v+1; | # define strcasecmp _stricmp |
| } | #endif |
| } | |
| return 0; | #ifndef max |
| } | inline int max(int a,int b){ return a>b?a:b; } |
| inline int min(int a,int b){ return a<b?a:b; } | |
| static char *lsplit(char **string_ref, char delim) { | #endif |
| char *result=*string_ref; | |
| char *next=lsplit(*string_ref, delim); | static char *lsplit(char *string, char delim){ |
| *string_ref=next; | if(string){ |
| return result; | if(char *v=strchr(string, delim)){ |
| } | *v=0; |
| return v+1; | |
| static char* rsplit(char* string, char delim) { | } |
| if(string) { | } |
| char* v=strrchr(string, delim); | return 0; |
| if(v) { | } |
| *v=0; | |
| return v+1; | static char *lsplit(char **string_ref, char delim){ |
| } | char *result=*string_ref; |
| } | char *next=lsplit(*string_ref, delim); |
| return NULL; | *string_ref=next; |
| } | return result; |
| } | |
| static void toupper_str(char *out, const char *in, size_t size) { | |
| while(size--) | static char* rsplit(char* string, char delim){ |
| *out++=(char)toupper(*in++); | if(string){ |
| } | if(char* v=strrchr(string, delim)){ |
| *v=0; | |
| struct Connection { | return v+1; |
| SQL_Driver_services* services; | } |
| } | |
| PGconn *conn; | return NULL; |
| const char* cstrClientCharset; | } |
| bool autocommit; | |
| }; | static void toupper_str(char *out, const char *in, size_t size){ |
| while(size--) | |
| /** | *out++=(char)toupper(*in++); |
| PgSQL server driver | } |
| */ | |
| class PgSQL_Driver : public SQL_Driver { | struct Connection { |
| public: | SQL_Driver_services* services; |
| PgSQL_Driver() : SQL_Driver() { | PGconn *conn; |
| } | const char* client_charset; |
| bool autocommit; | |
| /// get api version | bool without_default_transactions; |
| int api_version() { return SQL_DRIVER_API_VERSION; } | }; |
| /// initialize driver by loading sql dynamic link library | /** |
| const char *initialize(char *dlopen_file_spec) { | PgSQL server driver |
| return dlopen_file_spec? | */ |
| dlink(dlopen_file_spec):"client library column is empty"; | class PgSQL_Driver : public SQL_Driver { |
| } | public: |
| #define throwPQerror connection.services->_throw(PQerrorMessage(connection.conn)) | PgSQL_Driver() : SQL_Driver() { |
| #define PQclear_throw(msg) { \ | } |
| PQclear(res); \ | |
| connection.services->_throw(msg); \ | /// get api version |
| } | int api_version(){ return SQL_DRIVER_API_VERSION; } |
| #define PQclear_throwPQerror PQclear_throw(PQerrorMessage(connection.conn)) | |
| /// initialize driver by loading sql dynamic link library | |
| /** connect | const char *initialize(char *dlopen_file_spec){ |
| @param url | return dlopen_file_spec? |
| format: @b user:pass@host[:port]|[local]/database? | dlink(dlopen_file_spec):"client library column is empty"; |
| ClientCharset=xyz& // transcode by parser | } |
| charset=xyz& // transcode by server with 'set CLIENT_ENCODING=xyz' | |
| datestyle=xyz& // set DATESTYLE=xyz | #define throwPQerror connection.services->_throw(PQerrorMessage(connection.conn)) |
| autocommit=1& | #define PQclear_throw(msg) { \ |
| WithoutDefaultTransaction=1 // == autocommit=0 | PQclear(res); \ |
| */ | connection.services->_throw(msg); \ |
| void connect( | } |
| char *url, | #define PQclear_throwPQerror PQclear_throw(PQerrorMessage(connection.conn)) |
| SQL_Driver_services& services, | |
| void **connection_ref ///< output: Connection* | /** connect |
| ) { | @param url |
| char *user=url; | format: @b user:pass@host[:port]|[local]/database? |
| char *host=rsplit(user, '@'); | ClientCharset=charset& // transcode by parser |
| char *db=lsplit(host, '/'); | charset=value& // transcode by server with 'SET CLIENT_ENCODING=value' |
| char *pwd=lsplit(user, ':'); | datestyle=value& // 'SET DATESTYLE=value' available values are: ISO|SQL|Postgres|European|US|German [default=ISO] |
| char *port=lsplit(host, ':'); | autocommit=1& // each transaction is commited automatically (default) |
| WithoutDefaultTransaction=0 // 1 -- disable auto commit, 'BEGIN TRAN' at connection start and COMMIT/ROLLBACK at the end [can't be used together with autocommit option] | |
| char *options=lsplit(db, '?'); | */ |
| void connect( | |
| char *cstrBackwardCompAskServerToTranscode=0; | char* url, |
| char* datestyle=0; | SQL_Driver_services& services, |
| void** connection_ref ///< output: Connection* | |
| Connection& connection=*(Connection *)services.malloc(sizeof(Connection)); | ){ |
| *connection_ref=&connection; | char* user=url; |
| connection.services=&services; | char* host=rsplit(user, '@'); |
| connection.cstrClientCharset=0; | char* db=lsplit(host, '/'); |
| connection.autocommit=true; | char* pwd=lsplit(user, ':'); |
| connection.conn=PQsetdbLogin( | char* port=lsplit(host, ':'); |
| (host&&strcasecmp(host, "local")==0)?NULL/* local Unix domain socket */:host, port, | |
| NULL, NULL, db, user, pwd); | char *options=lsplit(db, '?'); |
| if(!connection.conn) | char* charset=0; |
| services._throw("PQsetdbLogin failed"); | char* datestyle=0; |
| if(PQstatus(connection.conn)!=CONNECTION_OK) | Connection& connection=*(Connection *)services.malloc(sizeof(Connection)); |
| throwPQerror; | *connection_ref=&connection; |
| connection.services=&services; | |
| while(options){ | connection.client_charset=0; |
| if(char *key=lsplit(&options, '&')){ | connection.autocommit=true; |
| if(*key){ | connection.without_default_transactions=false; |
| if(char *value=lsplit(key, '=')){ | |
| if(strcmp(key, "ClientCharset")==0) { // transcoding with parser | connection.conn=PQsetdbLogin( |
| toupper_str(value, value, strlen(value)); | (host&&strcasecmp(host, "local")==0)?NULL/* local Unix domain socket */:host, port, |
| connection.cstrClientCharset=value; | NULL, NULL, db, user, pwd); |
| } else if(strcasecmp(key, "charset")==0){ // transcoding with server | |
| cstrBackwardCompAskServerToTranscode=value; | if(!connection.conn) |
| } else if(strcasecmp(key, "datestyle")==0) { | services._throw("PQsetdbLogin failed"); |
| datestyle=value; | |
| } else if(strcasecmp(key, "autocommit")==0){ | if(PQstatus(connection.conn)!=CONNECTION_OK) |
| if(atoi(value)==0) | throwPQerror; |
| connection.autocommit=false; | |
| } else if(strcmp(key, "WithoutDefaultTransaction")==0){ // backward, use autocommit=0 | while(options){ |
| if(atoi(value)==1) | if(char *key=lsplit(&options, '&')){ |
| connection.autocommit=false; | if(*key){ |
| } else | if(char *value=lsplit(key, '=')){ |
| services._throw("unknown connect option" /*key*/); | if(strcmp(key, "ClientCharset")==0){ |
| } else | toupper_str(value, value, strlen(value)); |
| services._throw("connect option without =value" /*key*/); | connection.client_charset=value; |
| } | } else if(strcasecmp(key, "charset")==0){ |
| } | charset=value; |
| } | } else if(strcasecmp(key, "datestyle")==0){ |
| datestyle=value; | |
| if(cstrBackwardCompAskServerToTranscode){ | } else if(strcasecmp(key, "autocommit")==0){ |
| char statement[MAX_STRING]="set CLIENT_ENCODING="; | if(connection.without_default_transactions) |
| strncat(statement, cstrBackwardCompAskServerToTranscode, MAX_STRING); | services._throw("options WithoutDefaultTransaction and autocommit can't be used together"); |
| if(atoi(value)==0) | |
| execute_resultless(connection, statement); | connection.autocommit=false; |
| } | } else if(strcmp(key, "WithoutDefaultTransaction")==0){ |
| if(!connection.autocommit) | |
| if(datestyle){ | services._throw("options WithoutDefaultTransaction and autocommit can't be used together"); |
| char statement[MAX_STRING]="set DATESTYLE="; // ISO,SQL,Postgres,European,NonEuropean=US,German,DEFAULT=ISO | if(atoi(value)==1){ |
| strncat(statement, datestyle, MAX_STRING); | connection.without_default_transactions=true; |
| connection.autocommit=false; | |
| execute_resultless(connection, statement); | } |
| } | } else |
| services._throw("unknown connect option" /*key*/); | |
| begin_transaction(connection); | } else |
| } | services._throw("connect option without =value" /*key*/); |
| } | |
| void disconnect(void *aconnection) { | } |
| Connection& connection=*static_cast<Connection*>(aconnection); | } |
| PQfinish(connection.conn); | if(charset){ |
| connection.conn=0; | char statement[MAX_STRING]="SET CLIENT_ENCODING="; |
| } | strncat(statement, charset, MAX_STRING); |
| void commit(void *aconnection) { | _execute_cmd(connection, statement); |
| execute_transaction_cmd(aconnection, "COMMIT"); | } |
| } | |
| if(datestyle){ | |
| void rollback(void *aconnection) { | char statement[MAX_STRING]="SET DATESTYLE="; |
| execute_transaction_cmd(aconnection, "ROLLBACK"); | strncat(statement, datestyle, MAX_STRING); |
| } | |
| _execute_cmd(connection, statement); | |
| bool ping(void *aconnection) { | } |
| Connection& connection=*static_cast<Connection*>(aconnection); | |
| _begin_transaction(connection); | |
| return PQstatus(connection.conn)==CONNECTION_OK; | } |
| } | |
| void disconnect(void *aconnection){ | |
| const char* quote( | Connection& connection=*static_cast<Connection*>(aconnection); |
| void *aconnection, | PQfinish(connection.conn); |
| const char *from, unsigned int length) { | connection.conn=0; |
| Connection& connection=*static_cast<Connection*>(aconnection); | } |
| char *result=(char*)connection.services->malloc_atomic(length*2+1); | void commit(void *aconnection){ |
| int err=0; | Connection& connection=*static_cast<Connection*>(aconnection); |
| PQescapeStringConn (connection.conn, | if(!connection.without_default_transactions){ |
| result, from, length, | _execute_cmd(connection, "COMMIT"); |
| &err); | } |
| return result; | _begin_transaction(connection); |
| } | } |
| void query(void *aconnection, | void rollback(void *aconnection){ |
| const char *astatement, | Connection& connection=*static_cast<Connection*>(aconnection); |
| size_t placeholders_count, Placeholder* placeholders, | if(!connection.without_default_transactions){ |
| unsigned long offset, unsigned long limit, | _execute_cmd(connection, "ROLLBACK"); |
| SQL_Driver_query_event_handlers& handlers) { | } |
| // _asm int 3; | _begin_transaction(connection); |
| Connection& connection=*static_cast<Connection*>(aconnection); | } |
| const char* cstrClientCharset=connection.cstrClientCharset; | |
| SQL_Driver_services& services=*connection.services; | bool ping(void *aconnection) { |
| PGconn *conn=connection.conn; | Connection& connection=*static_cast<Connection*>(aconnection); |
| return PQstatus(connection.conn)==CONNECTION_OK; | |
| const char** paramValues; | } |
| if(placeholders_count>0){ | |
| //services._throw("bind variables not supported (yet)"); | const char* quote(void *aconnection, const char *from, unsigned int length){ |
| int binds_size=sizeof(char) * placeholders_count; | Connection& connection=*static_cast<Connection*>(aconnection); |
| paramValues = static_cast<const char**>(services.malloc_atomic(binds_size)); | |
| bind_parameters(placeholders_count, placeholders, paramValues, connection); | char *result=(char*)connection.services->malloc_atomic(length*2+1); |
| } | int err=0; |
| PQescapeStringConn(connection.conn, result, from, length, &err); | |
| // transcode from $request:charset to ?ClientCharset | return result; |
| if(cstrClientCharset) { | } |
| size_t transcoded_statement_size; | |
| services.transcode(astatement, strlen(astatement), | void query(void *aconnection, |
| astatement, transcoded_statement_size, | const char *astatement, |
| services.request_charset(), | size_t placeholders_count, Placeholder* placeholders, |
| cstrClientCharset); | unsigned long offset, unsigned long limit, |
| } | SQL_Driver_query_event_handlers& handlers |
| ){ | |
| const char *statement=preprocess_statement(connection, | Connection& connection=*static_cast<Connection*>(aconnection); |
| astatement, offset, limit); | SQL_Driver_services& services=*connection.services; |
| PGconn *conn=connection.conn; | |
| PGresult *res; | |
| if(placeholders_count>0){ | const char* client_charset=connection.client_charset; |
| res=PQexecParams(conn, statement, placeholders_count, NULL, paramValues, NULL, NULL, 0); | const char* request_charset=services.request_charset(); |
| } else { | bool transcode_needed=client_charset && strcmp(client_charset, request_charset)!=0; |
| res=PQexec(conn, statement); | |
| } | const char** paramValues; |
| if(!res) | if(placeholders_count>0){ |
| throwPQerror; | int binds_size=sizeof(char)*placeholders_count; |
| paramValues = static_cast<const char**>(services.malloc_atomic(binds_size)); | |
| switch(PQresultStatus(res)) { | _bind_parameters(placeholders_count, placeholders, paramValues, connection, transcode_needed); |
| case PGRES_EMPTY_QUERY: | } |
| PQclear_throw("no query"); | |
| break; | if(transcode_needed){ |
| case PGRES_COMMAND_OK: | // transcode query from $request:charset to ?ClientCharset |
| // empty result: insert|delete|update|... | size_t length=strlen(astatement); |
| PQclear(res); | services.transcode(astatement, length, |
| return; | astatement, length, |
| case PGRES_TUPLES_OK: | request_charset, |
| break; | client_charset); |
| default: | } |
| PQclear_throwPQerror; | |
| break; | const char *statement=_preprocess_statement(connection, astatement, offset, limit); |
| } | // error after prepare? |
| int column_count=PQnfields(res); | PGresult *res; |
| if(!column_count) | if(placeholders_count>0){ |
| PQclear_throw("result contains no columns"); | res=PQexecParams(conn, statement, placeholders_count, NULL, paramValues, NULL, NULL, 0); |
| } else { | |
| bool failed=false; | res=PQexec(conn, statement); |
| SQL_Error sql_error; | } |
| #define CHECK(afailed) \ | if(!res) |
| if(afailed) { \ | throwPQerror; |
| failed=true; \ | |
| goto cleanup; \ | switch(PQresultStatus(res)) { |
| } | case PGRES_EMPTY_QUERY: |
| PQclear_throw("no query"); | |
| for(int i=0; i<column_count; i++){ | break; |
| char *name=PQfname(res, i); | case PGRES_COMMAND_OK: // empty result: insert|delete|update|... |
| size_t length=strlen(name); | PQclear(res); |
| char* strm=(char*)services.malloc(length+1); | return; |
| memcpy(strm, name, length+1); | case PGRES_TUPLES_OK: |
| const char* str=strm; | break; |
| default: | |
| // transcode from ?ClientCharset to $request:charset | PQclear_throwPQerror; |
| if(cstrClientCharset) | break; |
| services.transcode(str, length, | } |
| str, length, | |
| cstrClientCharset, | int column_count=PQnfields(res); |
| services.request_charset()); | if(!column_count) |
| PQclear_throw("result contains no columns"); | |
| CHECK(handlers.add_column(sql_error, str, length)); | |
| } | bool failed=false; |
| SQL_Error sql_error; | |
| CHECK(handlers.before_rows(sql_error)); | #define CHECK(afailed) \ |
| if(afailed) { \ | |
| if(unsigned long row_count=(unsigned long)PQntuples(res)) | failed=true; \ |
| for(unsigned long r=0; r<row_count; r++) { | goto cleanup; \ |
| CHECK(handlers.add_row(sql_error)); | } |
| for(int i=0; i<column_count; i++){ | |
| const char *cell=PQgetvalue(res, r, i); | if(column_count>MAX_COLS) |
| size_t length; | column_count=MAX_COLS; |
| const char* str; | |
| if(PQftype(res, i)==OIDOID) { | unsigned int column_types[MAX_COLS]; |
| // ObjectID column, read object bytes | bool transcode_column[MAX_COLS]; |
| char *error_pos=0; | for(int i=0; i<column_count; i++){ |
| Oid oid=cell?atoi(cell):0; | char *name=PQfname(res, i); |
| int fd=lo_open(conn, oid, INV_READ); | size_t length=strlen(name); |
| if(fd>=0) { | column_types[i]=PQftype(res, i); |
| // seek to end | switch(column_types[i]){ |
| if(lo_lseek(conn, fd, 0, SEEK_END)<0) | case BOOLOID: |
| PQclear_throwPQerror; | case INT8OID: |
| // get length | case INT2OID: |
| int size_tell=lo_tell(conn, fd); | case INT4OID: |
| if(size_tell<0) | case FLOAT4OID: |
| PQclear_throwPQerror; | case FLOAT8OID: |
| // seek to begin | case DATEOID: |
| if(lo_lseek(conn, fd, 0, SEEK_SET)<0) | case TIMEOID: |
| PQclear_throwPQerror; | case TIMESTAMPOID: |
| length=(size_t)size_tell; | case TIMESTAMPTZOID: |
| if(length) { | case TIMETZOID: |
| // read | case NUMERICOID: |
| char* strm=(char*)services.malloc(length+1); | transcode_column[i]=false; |
| if(!lo_read_ex(conn, fd, strm, size_tell)) | break; |
| PQclear_throw("lo_read can not read all bytes of object"); | default: |
| strm[length]=0; | transcode_column[i]=transcode_needed; |
| str=strm; | break; |
| } else | } |
| str=0; | char* strm=(char*)services.malloc(length+1); |
| if(lo_close(conn, fd)<0) | memcpy(strm, name, length+1); |
| PQclear_throwPQerror; | const char* str=strm; |
| } else | |
| PQclear_throwPQerror; | if(transcode_needed) |
| } else { | // transcode column name from ?ClientCharset to $request:charset |
| // normal column, read it normally | services.transcode(str, length, |
| length=(size_t)PQgetlength(res, r, i); | str, length, |
| if(length) { | client_charset, |
| char* strm=(char*)services.malloc(length+1); | request_charset); |
| memcpy(strm, cell, length+1); | |
| str=strm; | CHECK(handlers.add_column(sql_error, str, length)); |
| } else | } |
| str=0; | |
| } | CHECK(handlers.before_rows(sql_error)); |
| if(str && length) { | if(unsigned long row_count=(unsigned long)PQntuples(res)) |
| // transcode from ?ClientCharset to $request:charset | for(unsigned long r=0; r<row_count; r++) { |
| if(cstrClientCharset) | CHECK(handlers.add_row(sql_error)); |
| services.transcode(str, length, | for(int i=0; i<column_count; i++){ |
| str, length, | const char *cell=PQgetvalue(res, r, i); |
| cstrClientCharset, | size_t length; |
| services.request_charset()); | const char* str; |
| } | |
| switch(column_types[i]){ | |
| CHECK(handlers.add_row_cell(sql_error, str, length)); | case OIDOID: |
| } | { |
| } | char *error_pos=0; |
| cleanup: | Oid oid=cell?atoi(cell):0; |
| PQclear(res); | int fd=lo_open(conn, oid, INV_READ); |
| if(failed) | if(fd>=0){ |
| services._throw(sql_error); | // seek to end |
| } | if(lo_lseek(conn, fd, 0, SEEK_END)<0) |
| PQclear_throwPQerror; | |
| private: // private funcs | // get length |
| int size_tell=lo_tell(conn, fd); | |
| void bind_parameters( | if(size_tell<0) |
| size_t placeholders_count, | PQclear_throwPQerror; |
| Placeholder* placeholders, | // seek to begin |
| const char** paramValues, | if(lo_lseek(conn, fd, 0, SEEK_SET)<0) |
| Connection& connection | PQclear_throwPQerror; |
| ) { | length=(size_t)size_tell; |
| for(size_t i=0; i<placeholders_count; i++) { | if(length){ |
| Placeholder& ph=placeholders[i]; | // read |
| size_t value_length; | char* strm=(char*)services.malloc(length+1); |
| if(connection.cstrClientCharset) { | if(!lo_read_ex(conn, fd, strm, size_tell)) |
| size_t name_length; | PQclear_throw("lo_read can not read all bytes of object"); |
| connection.services->transcode(ph.name, strlen(ph.name), | strm[length]=0; |
| ph.name, name_length, | str=strm; |
| connection.services->request_charset(), | } else |
| connection.cstrClientCharset); | str=0; |
| if(lo_close(conn, fd)<0) | |
| if(ph.value) { | PQclear_throwPQerror; |
| connection.services->transcode(ph.value, strlen(ph.value), | } else |
| ph.value, value_length, | PQclear_throwPQerror; |
| connection.services->request_charset(), | } |
| connection.cstrClientCharset); | default: |
| } | // normal column, read it normally |
| } | length=(size_t)PQgetlength(res, r, i); |
| if( atoi(ph.name) <= 0 || atoi(ph.name) > placeholders_count) { | if(length){ |
| connection.services->_throw("bad bind parameter key"); | char* strm=(char*)services.malloc(length+1); |
| } | memcpy(strm, cell, length+1); |
| paramValues[atoi(ph.name)-1] = ph.value; | str=strm; |
| } | } else |
| } | str=0; |
| } | |
| void execute_transaction_cmd(void *aconnection, const char *query) { | if(str && length && transcode_column[i]){ |
| Connection& connection=*static_cast<Connection*>(aconnection); | //services._throw("tr"); |
| // transcode cell value from ?ClientCharset to $request:charset | |
| if(connection.autocommit){ | services.transcode(str, length, |
| Connection& connection=*static_cast<Connection*>(aconnection); | str, length, |
| execute_resultless(connection, query); | client_charset, |
| } | request_charset); |
| } | |
| begin_transaction(connection); | |
| } | CHECK(handlers.add_row_cell(sql_error, str, length)); |
| } | |
| /** | } |
| Executes a query and throws the result. | cleanup: |
| */ | PQclear(res); |
| void execute_resultless(const Connection& connection, const char *query) { | if(failed) |
| if(PGresult *res=PQexec(connection.conn, query)) | services._throw(sql_error); |
| PQclear(res); // throw out the result [don't need but must call] | |
| else | if(connection.autocommit) |
| throwPQerror; | commit(aconnection); |
| } | } |
| void begin_transaction(Connection& connection) { | private: |
| if(connection.autocommit){ | void _bind_parameters( |
| execute_resultless(connection, "BEGIN"); | size_t placeholders_count, |
| } | Placeholder* placeholders, |
| } | const char** paramValues, |
| Connection& connection, | |
| const char *preprocess_statement(Connection& connection, | bool transcode_needed |
| const char *astatement, unsigned long offset, unsigned long limit) { | ){ |
| PGconn *conn=connection.conn; | for(size_t i=0; i<placeholders_count; i++){ |
| Placeholder& ph=placeholders[i]; | |
| size_t statement_size=strlen(astatement); | if(transcode_needed){ |
| size_t name_length; | |
| char *result=(char *)connection.services->malloc(statement_size | size_t value_length; |
| +MAX_NUMBER*2+15 // limit # offset # | connection.services->transcode(ph.name, strlen(ph.name), |
| +MAX_STRING // in case of short 'strings' | ph.name, name_length, |
| +1); | connection.services->request_charset(), |
| // offset & limit -> suffixes | connection.client_charset); |
| const char *o; | |
| if(offset || limit) { | if(ph.value) { |
| char *cur=result; | connection.services->transcode(ph.value, strlen(ph.value), |
| memcpy(cur, astatement, statement_size); cur+=statement_size; | ph.value, value_length, |
| if(limit) | connection.services->request_charset(), |
| cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit); | connection.client_charset); |
| if(offset) | } |
| cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset); | } |
| o=result; | int name_numner=atoi(ph.name); |
| } else | if(name_numner <= 0 || name_numner > placeholders_count) |
| o=astatement; | connection.services->_throw("bad bind parameter key"); |
| // /**xxx**/'literal' -> oid | paramValues[name_numner-1]=ph.value; |
| char *n=result; | } |
| while(*o) { | } |
| if( | |
| o[0]=='/' && | |
| o[1]=='*' && | /** |
| o[2]=='*') { // name start | Executes a query and throw away the result. |
| const char* saved_o=o; | */ |
| o+=3; | void _execute_cmd(const Connection& connection, const char *query){ |
| while(*o) | if(PGresult *res=PQexec(connection.conn, query)) |
| if( | PQclear(res); // throw out the result [don't need but must call] |
| o[0]=='*' && | else |
| o[1]=='*' && | throwPQerror; |
| o[2]=='/' && | } |
| o[3]=='\'') { // name end | |
| saved_o=0; // found, marking that | void _begin_transaction(Connection& connection){ |
| o+=4; | if(!connection.without_default_transactions) |
| Oid oid=lo_creat(conn, INV_READ|INV_WRITE); | _execute_cmd(connection, "BEGIN"); |
| if(oid==InvalidOid) | } |
| throwPQerror; | |
| int fd=lo_open(conn, oid, INV_WRITE); | const char *_preprocess_statement( |
| if(fd>=0) { | Connection& connection, |
| const char *start=o; | const char *astatement, |
| bool escaped=false; | unsigned long offset, |
| while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) { | unsigned long limit |
| escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\''); | ){ |
| if(escaped) { | PGconn *conn=connection.conn; |
| // write pending, skip "\" or "'" | |
| if(!lo_write_ex(conn, fd, start, o-start)) | size_t statement_size=strlen(astatement); |
| connection.services->_throw("lo_write could not write all bytes of object (1)"); | |
| start=++o; | char *result=(char *)connection.services->malloc(statement_size |
| } else | +MAX_NUMBER*2+15 // limit # offset # |
| o++; | +MAX_STRING // in case of short 'strings' |
| } | +1); |
| if(!lo_write_ex(conn, fd, start, o-start)) | // offset & limit -> suffixes |
| connection.services->_throw("lo_write can not write all bytes of object (2)"); | const char *o; |
| if(lo_close(conn, fd)<0) | if(offset || limit!=SQL_NO_LIMIT){ |
| throwPQerror; | char *cur=result; |
| } else | memcpy(cur, astatement, statement_size); cur+=statement_size; |
| throwPQerror; | if(limit!=SQL_NO_LIMIT) |
| if(*o) | cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit); |
| o++; // skip "'" | if(offset) |
| cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset); | |
| n+=snprintf(n, MAX_NUMBER, "%u", oid); | o=result; |
| break; | } else |
| } else | o=astatement; |
| o++; // /**skip**/'xxx' | |
| if(saved_o) { | // /**xxx**/'literal' -> oid |
| o=saved_o; | char *n=result; |
| *n++=*o++; | while(*o) { |
| } | if( |
| } else | o[0]=='/' && |
| *n++=*o++; | o[1]=='*' && |
| } | o[2]=='*') { // name start |
| *n=0; | const char* saved_o=o; |
| o+=3; | |
| return result; | while(*o) |
| } | if( |
| o[0]=='*' && | |
| private: // lo_read/write exchancements | o[1]=='*' && |
| o[2]=='/' && | |
| bool lo_read_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) { | o[3]=='\'') { // name end |
| return lo_rw_method (conn, fd, buf, len, lo_read); | saved_o=0; // found, marking that |
| } | o+=4; |
| Oid oid=lo_creat(conn, INV_READ|INV_WRITE); | |
| bool lo_write_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) { | if(oid==InvalidOid) |
| return lo_rw_method (conn, fd, buf, len, lo_write); | throwPQerror; |
| } | int fd=lo_open(conn, oid, INV_WRITE); |
| if(fd>=0) { | |
| bool lo_rw_method(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len, int (*lo_func)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len)) { | const char *start=o; |
| int size_op; | bool escaped=false; |
| while(len && (size_op=lo_func(conn, fd, buf, min(LO_BUFSIZE, len)))>0) { | while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) { |
| buf+=size_op; | escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\''); |
| len-=size_op; | if(escaped) { |
| } | // write pending, skip "\" or "'" |
| return len==0; | if(!lo_write_ex(conn, fd, start, o-start)) |
| } | connection.services->_throw("lo_write could not write all bytes of object (1)"); |
| start=++o; | |
| private: // conn client library funcs | } else |
| o++; | |
| typedef PGconn* (*t_PQsetdbLogin)( | } |
| const char *pghost, | if(!lo_write_ex(conn, fd, start, o-start)) |
| const char *pgport, | connection.services->_throw("lo_write can not write all bytes of object (2)"); |
| const char *pgoptions, | if(lo_close(conn, fd)<0) |
| const char *pgtty, | throwPQerror; |
| const char *dbName, | } else |
| const char *login, | throwPQerror; |
| const char *pwd); t_PQsetdbLogin PQsetdbLogin; | if(*o) |
| typedef void (*t_PQfinish)(PGconn *conn); t_PQfinish PQfinish; | o++; // skip "'" |
| typedef char *(*t_PQerrorMessage)(const PGconn* conn); t_PQerrorMessage PQerrorMessage; | |
| typedef ConnStatusType (*t_PQstatus)(const PGconn *conn); t_PQstatus PQstatus; | n+=snprintf(n, MAX_NUMBER, "%u", oid); |
| typedef PGresult *(*t_PQexec)(PGconn *conn, | break; |
| const char *query); t_PQexec PQexec; | } else |
| typedef PGresult *(*t_PQexecParams)( | o++; // /**skip**/'xxx' |
| PGconn *conn, | if(saved_o) { |
| const char *query, | o=saved_o; |
| int nParams, | *n++=*o++; |
| const Oid *paramTypes, | } |
| const char * const *paramValues, | } else |
| const int *paramLengths, | *n++=*o++; |
| const int *paramFormats, | } |
| int resultFormat); t_PQexecParams PQexecParams; | *n=0; |
| typedef ExecStatusType (*t_PQresultStatus)(const PGresult *res); t_PQresultStatus PQresultStatus; | return result; |
| typedef int (*t_PQgetlength)(const PGresult *res, | } |
| int tup_num, | |
| int field_num); t_PQgetlength PQgetlength; | private: // lo_read/write exchancements |
| typedef char* (*t_PQgetvalue)(const PGresult *res, | |
| int tup_num, | bool lo_read_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) { |
| int field_num); t_PQgetvalue PQgetvalue; | return lo_rw_method (conn, fd, buf, len, lo_read); |
| typedef int (*t_PQntuples)(const PGresult *res); t_PQntuples PQntuples; | } |
| typedef char *(*t_PQfname)(const PGresult *res, | |
| int field_index); t_PQfname PQfname; | bool lo_write_ex(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len) { |
| typedef int (*t_PQnfields)(const PGresult *res); t_PQnfields PQnfields; | return lo_rw_method (conn, fd, buf, len, lo_write); |
| typedef void (*t_PQclear)(PGresult *res); t_PQclear PQclear; | } |
| typedef Oid (*t_PQftype)(const PGresult *res, int field_num); t_PQftype PQftype; | bool lo_rw_method(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len, int (*lo_func)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len)) { |
| int size_op; | |
| typedef size_t (*t_PQescapeStringConn)(PGconn *conn, | while(len && (size_op=lo_func(conn, fd, buf, min(LO_BUFSIZE, len)))>0) { |
| char *to, const char *from, size_t length, | buf+=size_op; |
| int *error); t_PQescapeStringConn PQescapeStringConn; | len-=size_op; |
| } | |
| typedef int (*t_lo_open)(PGconn *conn, Oid lobjId, int mode); t_lo_open lo_open; | return len==0; |
| typedef int (*t_lo_close)(PGconn *conn, int fd); t_lo_close lo_close; | } |
| typedef int (*t_lo_read)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_read lo_read; | |
| typedef int (*t_lo_write)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_write lo_write; | private: // conn client library funcs |
| typedef int (*t_lo_lseek)(PGconn *conn, int fd, int offset, int whence); t_lo_lseek lo_lseek; | |
| typedef Oid (*t_lo_creat)(PGconn *conn, int mode); t_lo_creat lo_creat; | typedef PGconn* (*t_PQsetdbLogin)( |
| typedef int (*t_lo_tell)(PGconn *conn, int fd); t_lo_tell lo_tell; | const char *pghost, |
| typedef int (*t_lo_unlink)(PGconn *conn, Oid lobjId); t_lo_unlink lo_unlink; | const char *pgport, |
| typedef Oid (*t_lo_import)(PGconn *conn, const char *filename); t_lo_import lo_import; | const char *pgoptions, |
| typedef int (*t_lo_export)(PGconn *conn, Oid lobjId, const char *filename); t_lo_export lo_export; | const char *pgtty, |
| const char *dbName, | |
| private: // conn client library funcs linking | const char *login, |
| const char *pwd); t_PQsetdbLogin PQsetdbLogin; | |
| const char *dlink(const char *dlopen_file_spec) { | typedef void (*t_PQfinish)(PGconn *conn); t_PQfinish PQfinish; |
| if(lt_dlinit()) | typedef char *(*t_PQerrorMessage)(const PGconn* conn); t_PQerrorMessage PQerrorMessage; |
| return lt_dlerror(); | typedef ConnStatusType (*t_PQstatus)(const PGconn *conn); t_PQstatus PQstatus; |
| lt_dlhandle handle=lt_dlopen(dlopen_file_spec); | typedef PGresult *(*t_PQexec)(PGconn *conn, |
| if(!handle) | const char *query); t_PQexec PQexec; |
| return "can not open the dynamic link module"; | typedef PGresult *(*t_PQexecParams)( |
| PGconn *conn, | |
| #define DSLINK(name, action) \ | const char *query, |
| name=(t_##name)lt_dlsym(handle, #name); \ | int nParams, |
| if(!name) \ | const Oid *paramTypes, |
| action; | const char * const *paramValues, |
| const int *paramLengths, | |
| #define DLINK(name) DSLINK(name, return "function " #name " was not found") | const int *paramFormats, |
| int resultFormat); t_PQexecParams PQexecParams; | |
| DLINK(PQsetdbLogin); | |
| DLINK(PQerrorMessage); | typedef ExecStatusType (*t_PQresultStatus)(const PGresult *res); t_PQresultStatus PQresultStatus; |
| DLINK(PQstatus); | typedef int (*t_PQgetlength)(const PGresult *res, |
| DLINK(PQfinish); | int tup_num, |
| DLINK(PQgetvalue); | int field_num); t_PQgetlength PQgetlength; |
| DLINK(PQgetlength); | typedef char* (*t_PQgetvalue)(const PGresult *res, |
| DLINK(PQntuples); | int tup_num, |
| DLINK(PQfname); | int field_num); t_PQgetvalue PQgetvalue; |
| DLINK(PQnfields); | typedef int (*t_PQntuples)(const PGresult *res); t_PQntuples PQntuples; |
| DLINK(PQclear); | typedef char *(*t_PQfname)(const PGresult *res, |
| DLINK(PQresultStatus); | int field_index); t_PQfname PQfname; |
| DLINK(PQexec); | typedef int (*t_PQnfields)(const PGresult *res); t_PQnfields PQnfields; |
| DLINK(PQexecParams); | typedef void (*t_PQclear)(PGresult *res); t_PQclear PQclear; |
| DLINK(PQftype); | |
| DLINK(PQescapeStringConn); | typedef Oid (*t_PQftype)(const PGresult *res, int field_num); t_PQftype PQftype; |
| DLINK(lo_open); DLINK(lo_close); | |
| DLINK(lo_read); DLINK(lo_write); | typedef size_t (*t_PQescapeStringConn)(PGconn *conn, |
| DLINK(lo_lseek); DLINK(lo_creat); | char *to, const char *from, size_t length, |
| DLINK(lo_tell); DLINK(lo_unlink); | int *error); t_PQescapeStringConn PQescapeStringConn; |
| DLINK(lo_import); DLINK(lo_export); | |
| typedef int (*t_lo_open)(PGconn *conn, Oid lobjId, int mode); t_lo_open lo_open; | |
| return 0; | typedef int (*t_lo_close)(PGconn *conn, int fd); t_lo_close lo_close; |
| } | typedef int (*t_lo_read)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_read lo_read; |
| }; | typedef int (*t_lo_write)(PGconn *conn, int fd, const/*paf*/ char *buf, size_t len); t_lo_write lo_write; |
| typedef int (*t_lo_lseek)(PGconn *conn, int fd, int offset, int whence); t_lo_lseek lo_lseek; | |
| extern "C" SQL_Driver *SQL_DRIVER_CREATE() { | typedef Oid (*t_lo_creat)(PGconn *conn, int mode); t_lo_creat lo_creat; |
| return new PgSQL_Driver(); | typedef int (*t_lo_tell)(PGconn *conn, int fd); t_lo_tell lo_tell; |
| } | typedef int (*t_lo_unlink)(PGconn *conn, Oid lobjId); t_lo_unlink lo_unlink; |
| typedef Oid (*t_lo_import)(PGconn *conn, const char *filename); t_lo_import lo_import; | |
| typedef int (*t_lo_export)(PGconn *conn, Oid lobjId, const char *filename); t_lo_export lo_export; | |
| private: // conn client library funcs linking | |
| const char *dlink(const char *dlopen_file_spec) { | |
| if(lt_dlinit()) | |
| return lt_dlerror(); | |
| lt_dlhandle handle=lt_dlopen(dlopen_file_spec); | |
| if(!handle) | |
| return "can not open the dynamic link module"; | |
| #define DSLINK(name, action) \ | |
| name=(t_##name)lt_dlsym(handle, #name); \ | |
| if(!name) \ | |
| action; | |
| #define DLINK(name) DSLINK(name, return "function " #name " was not found") | |
| DLINK(PQsetdbLogin); | |
| DLINK(PQerrorMessage); | |
| DLINK(PQstatus); | |
| DLINK(PQfinish); | |
| DLINK(PQgetvalue); | |
| DLINK(PQgetlength); | |
| DLINK(PQntuples); | |
| DLINK(PQfname); | |
| DLINK(PQnfields); | |
| DLINK(PQclear); | |
| DLINK(PQresultStatus); | |
| DLINK(PQexec); | |
| DLINK(PQexecParams); | |
| DLINK(PQftype); | |
| DLINK(PQescapeStringConn); | |
| DLINK(lo_open); DLINK(lo_close); | |
| DLINK(lo_read); DLINK(lo_write); | |
| DLINK(lo_lseek); DLINK(lo_creat); | |
| DLINK(lo_tell); DLINK(lo_unlink); | |
| DLINK(lo_import); DLINK(lo_export); | |
| return 0; | |
| } | |
| }; | |
| extern "C" SQL_Driver *SQL_DRIVER_CREATE() { | |
| return new PgSQL_Driver(); | |
| } |