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