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

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

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


E-mail: