Diff for /sql/pgsql/parser3pgsql.C between versions 1.27 and 1.32

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

Removed from v.1.27  
changed lines
  Added in v.1.32


E-mail: