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