|
|
| version 1.32, 2008/12/18 01:45:03 | version 1.38, 2012/04/18 09:39:15 |
|---|---|
| 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 auto commit, 'BEGIN TRAN' at connection start and COMMIT/ROLLBACK at the end [can't be used together 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); |
| } | |
| _begin_transaction(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); | |
| if(!connection.without_default_transactions){ | void disconnect(void *aconnection){ |
| _execute_cmd(connection, "COMMIT"); | Connection& connection=*static_cast<Connection*>(aconnection); |
| } | PQfinish(connection.conn); |
| _begin_transaction(connection); | connection.conn=0; |
| } | } |
| void rollback(void *aconnection){ | void commit(void *aconnection){ |
| Connection& connection=*static_cast<Connection*>(aconnection); | Connection& connection=*static_cast<Connection*>(aconnection); |
| if(!connection.without_default_transactions){ | _transaction_commit(connection); |
| _execute_cmd(connection, "ROLLBACK"); | _transaction_begin(connection); |
| } | } |
| _begin_transaction(connection); | |
| } | void rollback(void *aconnection){ |
| Connection& connection=*static_cast<Connection*>(aconnection); | |
| bool ping(void *aconnection) { | _transaction_rollback(connection); |
| Connection& connection=*static_cast<Connection*>(aconnection); | _transaction_begin(connection); |
| return PQstatus(connection.conn)==CONNECTION_OK; | } |
| } | |
| bool ping(void *aconnection) { | |
| const char* quote(void *aconnection, const char *from, unsigned int length){ | Connection& connection=*static_cast<Connection*>(aconnection); |
| Connection& connection=*static_cast<Connection*>(aconnection); | return PQstatus(connection.conn)==CONNECTION_OK; |
| } | |
| char *result=(char*)connection.services->malloc_atomic(length*2+1); | |
| int err=0; | // charset here is services.request_charset(), not connection.client_charset |
| PQescapeStringConn(connection.conn, result, from, length, &err); | // thus we can't use the sql server quoting support |
| return result; | const char* quote(void *aconnection, const char *str, unsigned int length) |
| } | { |
| const char* from; | |
| void query(void *aconnection, | const char* from_end=str+length; |
| const char *astatement, | |
| size_t placeholders_count, Placeholder* placeholders, | size_t quoted=0; |
| unsigned long offset, unsigned long limit, | |
| SQL_Driver_query_event_handlers& handlers | for(from=str; from<from_end; from++){ |
| ){ | switch (*from) { |
| Connection& connection=*static_cast<Connection*>(aconnection); | case '\'': |
| SQL_Driver_services& services=*connection.services; | case '\\': |
| PGconn *conn=connection.conn; | quoted++; |
| } | |
| const char* client_charset=connection.client_charset; | } |
| const char* request_charset=services.request_charset(); | |
| bool transcode_needed=client_charset && strcmp(client_charset, request_charset)!=0; | if(!quoted) |
| return str; | |
| const char** paramValues; | |
| if(placeholders_count>0){ | Connection& connection=*static_cast<Connection*>(aconnection); |
| int binds_size=sizeof(char)*placeholders_count; | char *result=(char*)connection.services->malloc_atomic(length + quoted + 1); |
| paramValues = static_cast<const char**>(services.malloc_atomic(binds_size)); | char *to = result; |
| _bind_parameters(placeholders_count, placeholders, paramValues, connection, transcode_needed); | |
| } | for(from=str; from<from_end; from++){ |
| switch (*from) { | |
| if(transcode_needed){ | case '\'': // "'" -> "''" |
| // transcode query from $request:charset to ?ClientCharset | *to++='\''; |
| size_t length=strlen(astatement); | break; |
| services.transcode(astatement, length, | case '\\': // "\" -> "\\" |
| astatement, length, | *to++='\\'; |
| request_charset, | break; |
| client_charset); | } |
| } | *to++=*from; |
| } | |
| const char *statement=_preprocess_statement(connection, astatement, offset, limit); | |
| // error after prepare? | *to=0; |
| return result; | |
| PGresult *res; | } |
| if(placeholders_count>0){ | |
| res=PQexecParams(conn, statement, placeholders_count, NULL, paramValues, NULL, NULL, 0); | void query(void *aconnection, |
| } else { | const char *astatement, |
| res=PQexec(conn, statement); | size_t placeholders_count, Placeholder* placeholders, |
| } | unsigned long offset, unsigned long limit, |
| if(!res) | SQL_Driver_query_event_handlers& handlers |
| throwPQerror; | ){ |
| Connection& connection=*static_cast<Connection*>(aconnection); | |
| switch(PQresultStatus(res)) { | SQL_Driver_services& services=*connection.services; |
| case PGRES_EMPTY_QUERY: | PGconn *conn=connection.conn; |
| PQclear_throw("no query"); | |
| break; | const char* client_charset=connection.client_charset; |
| case PGRES_COMMAND_OK: // empty result: insert|delete|update|... | const char* request_charset=services.request_charset(); |
| PQclear(res); | bool transcode_needed=client_charset && strcmp(client_charset, request_charset)!=0; |
| return; | |
| case PGRES_TUPLES_OK: | const char** paramValues; |
| break; | if(placeholders_count>0){ |
| default: | int binds_size=sizeof(char)*placeholders_count; |
| PQclear_throwPQerror; | paramValues = static_cast<const char**>(services.malloc_atomic(binds_size)); |
| break; | _bind_parameters(placeholders_count, placeholders, paramValues, connection, transcode_needed); |
| } | } |
| int column_count=PQnfields(res); | size_t statement_size=0; |
| if(!column_count) | if(transcode_needed){ |
| PQclear_throw("result contains no columns"); | // transcode query from $request:charset to ?ClientCharset |
| statement_size=strlen(astatement); | |
| bool failed=false; | services.transcode(astatement, statement_size, |
| SQL_Error sql_error; | astatement, statement_size, |
| #define CHECK(afailed) \ | request_charset, |
| if(afailed) { \ | client_charset); |
| failed=true; \ | } |
| goto cleanup; \ | |
| } | const char *statement=_preprocess_statement(connection, astatement, statement_size, offset, limit); |
| // error after prepare? | |
| if(column_count>MAX_COLS) | |
| column_count=MAX_COLS; | PGresult *res; |
| if(placeholders_count>0){ | |
| unsigned int column_types[MAX_COLS]; | res=PQexecParams(conn, statement, placeholders_count, NULL, paramValues, NULL, NULL, 0); |
| bool transcode_column[MAX_COLS]; | } else { |
| res=PQexec(conn, statement); | |
| for(int i=0; i<column_count; i++){ | } |
| char *name=PQfname(res, i); | if(!res) |
| size_t length=strlen(name); | throwPQerror; |
| column_types[i]=PQftype(res, i); | |
| switch(column_types[i]){ | bool failed=false; |
| case BOOLOID: | SQL_Error sql_error; |
| case INT8OID: | |
| case INT2OID: | switch(PQresultStatus(res)) { |
| case INT4OID: | case PGRES_EMPTY_QUERY: |
| case FLOAT4OID: | PQclear_throw("no query"); |
| case FLOAT8OID: | break; |
| case DATEOID: | case PGRES_COMMAND_OK: // empty result: insert|delete|update|... |
| case TIMEOID: | PQclear(res); |
| case TIMESTAMPOID: | if(connection.autocommit) |
| case TIMESTAMPTZOID: | commit(aconnection); |
| case TIMETZOID: | return; |
| case NUMERICOID: | case PGRES_TUPLES_OK: |
| transcode_column[i]=false; | break; |
| break; | default: |
| default: | PQclear_throwPQerror; |
| transcode_column[i]=transcode_needed; | break; |
| break; | } |
| } | |
| char* strm=(char*)services.malloc(length+1); | #define CHECK(afailed) \ |
| memcpy(strm, name, length+1); | if(afailed) { \ |
| const char* str=strm; | failed=true; \ |
| goto cleanup; \ | |
| if(transcode_needed) | } |
| // transcode column name from ?ClientCharset to $request:charset | |
| services.transcode(str, length, | size_t column_count=PQnfields(res); |
| str, length, | if(!column_count) |
| client_charset, | PQclear_throw("result contains no columns"); |
| request_charset); | |
| if(column_count>MAX_COLS) | |
| CHECK(handlers.add_column(sql_error, str, length)); | column_count=MAX_COLS; |
| } | |
| unsigned int column_types[MAX_COLS]; | |
| CHECK(handlers.before_rows(sql_error)); | |
| for(size_t i=0; i<column_count; i++){ | |
| if(unsigned long row_count=(unsigned long)PQntuples(res)) | column_types[i]=PQftype(res, i); |
| for(unsigned long r=0; r<row_count; r++) { | |
| CHECK(handlers.add_row(sql_error)); | char *name=PQfname(res, i); |
| for(int i=0; i<column_count; i++){ | size_t length=strlen(name); |
| const char *cell=PQgetvalue(res, r, i); | const char* str=strdup(services, name, length); |
| size_t length; | |
| const char* str; | if(transcode_needed) |
| // transcode column name from ?ClientCharset to $request:charset | |
| switch(column_types[i]){ | services.transcode(str, length, |
| case OIDOID: | str, length, |
| { | client_charset, |
| char *error_pos=0; | request_charset); |
| Oid oid=cell?atoi(cell):0; | |
| int fd=lo_open(conn, oid, INV_READ); | CHECK(handlers.add_column(sql_error, str, length)); |
| if(fd>=0){ | } |
| // seek to end | |
| if(lo_lseek(conn, fd, 0, SEEK_END)<0) | CHECK(handlers.before_rows(sql_error)); |
| PQclear_throwPQerror; | |
| // get length | if(unsigned long row_count=(unsigned long)PQntuples(res)) |
| int size_tell=lo_tell(conn, fd); | for(unsigned long r=0; r<row_count; r++) { |
| if(size_tell<0) | CHECK(handlers.add_row(sql_error)); |
| PQclear_throwPQerror; | for(size_t i=0; i<column_count; i++){ |
| // seek to begin | char *cell=PQgetvalue(res, r, i); |
| if(lo_lseek(conn, fd, 0, SEEK_SET)<0) | |
| PQclear_throwPQerror; | size_t length=0; |
| length=(size_t)size_tell; | const char* str; |
| if(length){ | |
| // read | switch(column_types[i]){ |
| char* strm=(char*)services.malloc(length+1); | case BOOLOID: |
| if(!lo_read_ex(conn, fd, strm, size_tell)) | case INT8OID: |
| PQclear_throw("lo_read can not read all bytes of object"); | case INT2OID: |
| strm[length]=0; | case INT4OID: |
| str=strm; | case FLOAT4OID: |
| } else | case FLOAT8OID: |
| str=0; | case DATEOID: |
| if(lo_close(conn, fd)<0) | case TIMEOID: |
| PQclear_throwPQerror; | case TIMESTAMPOID: |
| } else | case TIMESTAMPTZOID: |
| PQclear_throwPQerror; | case TIMETZOID: |
| } | case NUMERICOID: |
| default: | length=(size_t)PQgetlength(res, r, i); |
| // normal column, read it normally | str=length ? strdup(services, cell, length) : 0; |
| length=(size_t)PQgetlength(res, r, i); | // transcode is never required for these types |
| if(length){ | break; |
| char* strm=(char*)services.malloc(length+1); | case OIDOID: |
| memcpy(strm, cell, length+1); | { |
| str=strm; | Oid oid=cell?atoi(cell):0; |
| } else | int fd=lo_open(conn, oid, INV_READ); |
| str=0; | if(fd>=0){ |
| } | // seek to end |
| if(lo_lseek(conn, fd, 0, SEEK_END)<0) | |
| if(str && length && transcode_column[i]){ | PQclear_throwPQerror; |
| //services._throw("tr"); | // get length |
| // transcode cell value from ?ClientCharset to $request:charset | int size_tell=lo_tell(conn, fd); |
| services.transcode(str, length, | if(size_tell<0) |
| str, length, | PQclear_throwPQerror; |
| client_charset, | // seek to begin |
| request_charset); | if(lo_lseek(conn, fd, 0, SEEK_SET)<0) |
| } | PQclear_throwPQerror; |
| length=(size_t)size_tell; | |
| CHECK(handlers.add_row_cell(sql_error, str, length)); | if(length){ |
| } | // read |
| } | char* strm=(char*)services.malloc(length+1); |
| cleanup: | if(!lo_read_ex(conn, fd, strm, size_tell)) |
| PQclear(res); | PQclear_throw("lo_read can not read all bytes of object"); |
| if(failed) | strm[length]=0; |
| services._throw(sql_error); | str=strm; |
| if(transcode_needed) { | |
| if(connection.autocommit) | // transcode cell value from ?ClientCharset to $request:charset |
| commit(aconnection); | services.transcode(str, length, |
| } | str, length, |
| client_charset, | |
| private: | request_charset); |
| void _bind_parameters( | } |
| size_t placeholders_count, | } else |
| Placeholder* placeholders, | str=0; |
| const char** paramValues, | if(lo_close(conn, fd)<0) |
| Connection& connection, | PQclear_throwPQerror; |
| bool transcode_needed | } else |
| ){ | PQclear_throwPQerror; |
| for(size_t i=0; i<placeholders_count; i++){ | break; |
| Placeholder& ph=placeholders[i]; | } |
| if(transcode_needed){ | default: |
| size_t name_length; | // normal column, read it normally |
| size_t value_length; | length=(size_t)PQgetlength(res, r, i); |
| connection.services->transcode(ph.name, strlen(ph.name), | str=length ? strdup(services, cell, length) : 0; |
| ph.name, name_length, | if(transcode_needed) { |
| connection.services->request_charset(), | // transcode cell value from ?ClientCharset to $request:charset |
| connection.client_charset); | services.transcode(str, length, |
| str, length, | |
| if(ph.value) { | client_charset, |
| connection.services->transcode(ph.value, strlen(ph.value), | request_charset); |
| ph.value, value_length, | } |
| connection.services->request_charset(), | break; |
| connection.client_charset); | } |
| } | CHECK(handlers.add_row_cell(sql_error, str, length)); |
| } | } |
| int name_numner=atoi(ph.name); | } |
| if(name_numner <= 0 || name_numner > placeholders_count) | cleanup: |
| connection.services->_throw("bad bind parameter key"); | PQclear(res); |
| if(failed) | |
| paramValues[name_numner-1]=ph.value; | services._throw(sql_error); |
| } | |
| } | if(connection.autocommit) |
| commit(aconnection); | |
| } | |
| /** | |
| Executes a query and throw away the result. | private: |
| */ | void _bind_parameters( |
| void _execute_cmd(const Connection& connection, const char *query){ | size_t placeholders_count, |
| if(PGresult *res=PQexec(connection.conn, query)) | Placeholder* placeholders, |
| PQclear(res); // throw out the result [don't need but must call] | const char** paramValues, |
| else | Connection& connection, |
| throwPQerror; | bool transcode_needed |
| } | ){ |
| for(size_t i=0; i<placeholders_count; i++){ | |
| void _begin_transaction(Connection& connection){ | Placeholder& ph=placeholders[i]; |
| if(!connection.without_default_transactions) | if(transcode_needed){ |
| _execute_cmd(connection, "BEGIN"); | size_t name_length; |
| } | connection.services->transcode(ph.name, strlen(ph.name), |
| ph.name, name_length, | |
| const char *_preprocess_statement( | connection.services->request_charset(), |
| Connection& connection, | connection.client_charset); |
| const char *astatement, | |
| unsigned long offset, | if(ph.value) { |
| unsigned long limit | size_t value_length; |
| ){ | connection.services->transcode(ph.value, strlen(ph.value), |
| PGconn *conn=connection.conn; | ph.value, value_length, |
| connection.services->request_charset(), | |
| size_t statement_size=strlen(astatement); | connection.client_charset); |
| } | |
| char *result=(char *)connection.services->malloc(statement_size | } |
| +MAX_NUMBER*2+15 // limit # offset # | int name_number=atoi(ph.name); |
| +MAX_STRING // in case of short 'strings' | if(name_number <= 0 || (size_t)name_number > placeholders_count) |
| +1); | connection.services->_throw("bad bind parameter key"); |
| // offset & limit -> suffixes | |
| const char *o; | paramValues[name_number-1]=ph.value; |
| if(offset || limit!=SQL_NO_LIMIT){ | } |
| char *cur=result; | } |
| memcpy(cur, astatement, statement_size); cur+=statement_size; | |
| if(limit!=SQL_NO_LIMIT) | |
| cur+=snprintf(cur, 7+MAX_NUMBER, " limit %u", limit); | void _transaction_begin(Connection& connection){ |
| if(offset) | _execute_transactions_cmd(connection, "BEGIN"); |
| cur+=snprintf(cur, 8+MAX_NUMBER, " offset %u", offset); | } |
| o=result; | |
| } else | void _transaction_commit(Connection& connection){ |
| o=astatement; | _execute_transactions_cmd(connection, "COMMIT"); |
| } | |
| // /**xxx**/'literal' -> oid | |
| char *n=result; | void _transaction_rollback(Connection& connection){ |
| while(*o) { | _execute_transactions_cmd(connection, "ROLLBACK"); |
| if( | } |
| o[0]=='/' && | |
| o[1]=='*' && | void _execute_transactions_cmd(const Connection& connection, const char *query){ |
| o[2]=='*') { // name start | if(!connection.without_default_transactions) // with option ?WithoutDefaultTransaction=1 user must execute BEGIN/COMMIT/ROLLBACK by himself |
| const char* saved_o=o; | _execute_cmd(connection, query); |
| o+=3; | } |
| while(*o) | |
| if( | // executes a query and throw away the result. |
| o[0]=='*' && | void _execute_cmd(const Connection& connection, const char *query){ |
| o[1]=='*' && | if(PGresult *res=PQexec(connection.conn, query)) |
| o[2]=='/' && | PQclear(res); // throw away the result [don't need but must call] |
| o[3]=='\'') { // name end | else |
| saved_o=0; // found, marking that | throwPQerror; |
| o+=4; | } |
| Oid oid=lo_creat(conn, INV_READ|INV_WRITE); | |
| if(oid==InvalidOid) | const char *_preprocess_statement( |
| throwPQerror; | Connection& connection, |
| int fd=lo_open(conn, oid, INV_WRITE); | const char *astatement, |
| if(fd>=0) { | size_t statement_size, |
| const char *start=o; | unsigned long offset, |
| bool escaped=false; | unsigned long limit |
| while(*o && !(o[0]=='\'' && o[1]!='\'' && !escaped)) { | ){ |
| escaped=*o=='\\' || (o[0]=='\'' && o[1]=='\''); | PGconn *conn=connection.conn; |
| if(escaped) { | |
| // write pending, skip "\" or "'" | if(!statement_size) |
| if(!lo_write_ex(conn, fd, start, o-start)) | 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(); | |
| } |