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

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


E-mail: