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

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


E-mail: