LCOV - code coverage report
Current view: top level - src/dblib - dblib.c (source / functions) Hit Total Coverage
Test: FreeTDS coverage Lines: 1417 2611 54.3 %
Date: 2026-03-10 20:29:39 Functions: 98 161 60.9 %

          Line data    Source code
       1             : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005  Brian Bruns
       3             :  * Copyright (C) 2006-2015  Frediano Ziglio
       4             :  *
       5             :  * This library is free software; you can redistribute it and/or
       6             :  * modify it under the terms of the GNU Library General Public
       7             :  * License as published by the Free Software Foundation; either
       8             :  * version 2 of the License, or (at your option) any later version.
       9             :  *
      10             :  * This library is distributed in the hope that it will be useful,
      11             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      13             :  * Library General Public License for more details.
      14             :  *
      15             :  * You should have received a copy of the GNU Library General Public
      16             :  * License along with this library; if not, write to the
      17             :  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
      18             :  * Boston, MA 02111-1307, USA.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : 
      23             : #include <stdarg.h>
      24             : 
      25             : #include <freetds/time.h>
      26             : 
      27             : #include <assert.h>
      28             : #include <stdio.h>
      29             : 
      30             : #if HAVE_STDLIB_H
      31             : #include <stdlib.h>
      32             : #endif /* HAVE_STDLIB_H */
      33             : 
      34             : #if HAVE_STRING_H
      35             : #include <string.h>
      36             : #endif /* HAVE_STRING_H */
      37             : 
      38             : #if HAVE_UNISTD_H
      39             : #include <unistd.h>
      40             : #endif /* HAVE_UNISTD_H */
      41             : 
      42             : #if HAVE_ERRNO_H
      43             : # include <errno.h>
      44             : #endif /* HAVE_ERRNO_H */
      45             : 
      46             : /** 
      47             :  * \ingroup dblib_core
      48             :  * \remarks Either SYBDBLIB or MSDBLIB (not both) must be defined. 
      49             :  *      This affects how certain application-addressable 
      50             :  *      strucures are defined.  
      51             :  */
      52             : #include <freetds/tds.h>
      53             : #include <freetds/thread.h>
      54             : #include <freetds/tds/convert.h>
      55             : #include <freetds/utils/string.h>
      56             : #include <freetds/tds/data.h>
      57             : #include <freetds/replacements.h>
      58             : #include <sybfront.h>
      59             : #include <sybdb.h>
      60             : #include <syberror.h>
      61             : #include <dblib.h>
      62             : 
      63             : static RETCODE _dbresults(DBPROCESS * dbproc);
      64             : static BYTE *_dbcoldata(TDSCOLUMN *colinfo);
      65             : static int _get_printable_size(TDSCOLUMN * colinfo);
      66             : static char *_dbprdate(char *timestr);
      67             : static int _dbnullable(DBPROCESS * dbproc, int column);
      68             : static const char *tds_prdatatype(int datatype_token);
      69             : 
      70             : static int default_err_handler(DBPROCESS * dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr);
      71             : 
      72             : void copy_data_to_host_var(DBPROCESS *, TDS_SERVER_TYPE, const BYTE *, int, BYTE *, DBINT, int, DBINT *);
      73             : RETCODE dbgetnull(DBPROCESS *dbproc, int bindtype, int varlen, BYTE* varaddr);
      74             : 
      75             : /**
      76             :  * \file dblib.c
      77             :  * Main implementation file for \c db-lib.
      78             :  */
      79             : /**
      80             :  * \file bcp.c
      81             :  * Implementation of \c db-lib bulk copy functions.
      82             :  */
      83             : /**
      84             :  * \defgroup dblib_api The db-lib API
      85             :  * Functions callable by \c db-lib client programs
      86             :  *
      87             :  * The \c db_lib interface is implemented by both Sybase and Microsoft.  FreeTDS seeks to implement 
      88             :  * first the intersection of the functions defined by the vendors.  
      89             :  */
      90             :  
      91             : /**
      92             :  * \ingroup dblib_api
      93             :  * \defgroup dblib_core Primary functions
      94             :  * Core functions needed by most db-lib programs.  
      95             : */
      96             : /**
      97             :  * \ingroup dblib_api
      98             :  * \defgroup dblib_rpc Remote Procedure functions
      99             :  * Functions used with stored procedures.  
     100             :  * Especially useful for OUTPUT parameters, because modern Microsoft servers do not 
     101             :  * return output parameter data to the client unless the procedure was invoked
     102             :  * with dbrpcsend().  
     103             :  */
     104             : /**
     105             :  * \ingroup dblib_api
     106             :  * \defgroup dblib_bcp Bulk copy functions
     107             :  * Functions to bulk-copy (a/k/a \em bcp) data to/from the database.  
     108             :  */
     109             : /**
     110             :  * \ingroup dblib_bcp
     111             :  * \defgroup dblib_bcp_internal Internal bcp functions
     112             :  * Static functions internal to the bcp library.  
     113             :  */
     114             : /**
     115             :  * \ingroup dblib_api
     116             :  * \defgroup dblib_money Money functions 
     117             :  * Functions to manipulate the MONEY datatype.  
     118             :  */
     119             : /**
     120             :  * \ingroup dblib_api
     121             :  * \defgroup dblib_datetime Datetime functions 
     122             :  * Functions to manipulate DBDATETIME structures.  Defined by Sybase only.  
     123             :  * These are not implemented:
     124             :  *      - dbdate4cmp()
     125             :  *      - dbdate4zero()
     126             :  *      - dbdatechar()
     127             :  *      - dbdatename()
     128             :  *      - dbdateorder()
     129             :  *      - dbdatepart()
     130             :  *      - dbdatezero()
     131             :  *      - dbdayname()
     132             :  */
     133             : /**
     134             :  * \ingroup dblib_api
     135             :  * \defgroup dblib_internal Internals
     136             :  * Functions called within \c db-lib for self-help.  
     137             :  * These functions are of interest only to people hacking on the FreeTDS db-lib implementation.  
     138             :  */
     139             : /**
     140             :  * \ingroup dblib_api
     141             :  * \defgroup dblib_unimplemented Unimplemented
     142             :  * Functions thus far not implemented in the FreeTDS db-lib implementation.  
     143             :  * While some of these are simply awaiting someone with time and skill (and inclination)
     144             :  * it might be noted here that the old browse functions (e.g. dbcolbrowse()) 
     145             :  * are on the never-to-do list.  
     146             :  * They were defined by Sybase and were superseded long ago, although they're still
     147             :  * present in Microsoft's implementation.  
     148             :  * They were never popular and today better alternatives are available.  
     149             :  * For completeness, they are:
     150             :  *      - dbcolbrowse()
     151             :  *      - dbcolsource()
     152             :  *      - dbfreequal()
     153             :  *      - dbqual()
     154             :  *      - dbtabbrowse()
     155             :  *      - dbtabcount()
     156             :  *      - dbtabname()
     157             :  *      - dbtabsource()
     158             :  *      - dbtsnewlen()
     159             :  *      - dbtsnewval()
     160             :  *      - dbtsput()
     161             :  */
     162             : 
     163             : /* info/err message handler functions (or rather pointers to them) */
     164             : MHANDLEFUNC _dblib_msg_handler = NULL;
     165             : EHANDLEFUNC _dblib_err_handler = default_err_handler;
     166             : 
     167             : /** \internal
     168             :  * \dblib_internal
     169             :  * \remarks A db-lib connection has an implicit TDS context. 
     170             :  */
     171             : typedef struct dblib_context
     172             : {
     173             :         /** reference count, time dbinit called */
     174             :         int ref_count;
     175             : 
     176             :         /** libTDS context */
     177             :         TDSCONTEXT *tds_ctx;
     178             :         /** libTDS context reference counter */
     179             :         int tds_ctx_ref_count;
     180             : 
     181             :         /* save all connection in a list */
     182             :         TDSSOCKET **connection_list;
     183             :         int connection_list_size;
     184             :         int connection_list_size_represented;
     185             :         char *recftos_filename;
     186             :         int recftos_filenum;
     187             :         int login_timeout;      /**< not used unless positive */
     188             :         int query_timeout;      /**< not used unless positive */
     189             : }
     190             : DBLIBCONTEXT;
     191             : 
     192             : static DBLIBCONTEXT g_dblib_ctx;
     193             : static tds_mutex dblib_mutex = TDS_MUTEX_INITIALIZER;
     194             : 
     195             : static int g_dblib_version =
     196             : #if TDS50
     197             :         DBVERSION_100;
     198             : #elif TDS71
     199             :         DBVERSION_71;
     200             : #elif TDS72
     201             :         DBVERSION_72;
     202             : #elif TDS73
     203             :         DBVERSION_73;
     204             : #elif TDS74
     205             :         DBVERSION_74;
     206             : #else
     207             :         DBVERSION_UNKNOWN;
     208             : #endif
     209             : 
     210             : 
     211             : static int
     212         864 : dblib_add_connection(DBLIBCONTEXT * ctx, TDSSOCKET * tds)
     213             : {
     214         864 :         int i = 0;
     215         864 :         const int list_size = ctx->connection_list_size_represented;
     216             : 
     217         864 :         tdsdump_log(TDS_DBG_FUNC, "dblib_add_connection(%p, %p)\n", ctx, tds);
     218             : 
     219        1466 :         while (i < list_size && ctx->connection_list[i])
     220         602 :                 i++;
     221         864 :         if (i == list_size) {
     222             :                 return 1;
     223             :         } else {
     224         854 :                 ctx->connection_list[i] = tds;
     225         854 :                 return 0;
     226             :         }
     227             : }
     228             : 
     229             : static void
     230         456 : dblib_del_connection(DBLIBCONTEXT * ctx, TDSSOCKET * tds)
     231             : {
     232         456 :         int i = 0;
     233         456 :         const int list_size = ctx->connection_list_size;
     234             : 
     235         456 :         tdsdump_log(TDS_DBG_FUNC, "dblib_del_connection(%p, %p)\n", ctx, tds);
     236             : 
     237       41966 :         while (i < list_size && ctx->connection_list[i] != tds)
     238       41510 :                 i++;
     239         456 :         if (i == list_size) {
     240             :                 /* connection wasn't on the free list...now what */
     241             :         } else {
     242             :                 /* remove it */
     243         446 :                 ctx->connection_list[i] = NULL;
     244             :         }
     245         456 : }
     246             : 
     247             : /**
     248             :  * Get global dblib TDS context.
     249             :  * dblib_mutex should be locked.
     250             :  */
     251             : static TDSCONTEXT *
     252        1366 : dblib_get_tds_ctx(void)
     253             : {
     254        1366 :         tdsdump_log(TDS_DBG_FUNC, "dblib_get_tds_ctx(void)\n");
     255             : 
     256        1366 :         ++g_dblib_ctx.tds_ctx_ref_count;
     257        1366 :         if (g_dblib_ctx.tds_ctx == NULL) {
     258         502 :                 TDSCONTEXT *tds_ctx = tds_alloc_context(&g_dblib_ctx);
     259             : 
     260         502 :                 if (!tds_ctx)
     261             :                         return NULL;
     262             : 
     263             :                 /*
     264             :                  * Set the functions in the TDS layer to point to the correct handler functions
     265             :                  */
     266         502 :                 tds_ctx->msg_handler = _dblib_handle_info_message;
     267         502 :                 tds_ctx->err_handler = _dblib_handle_err_message;
     268         502 :                 tds_ctx->int_handler = _dblib_check_and_handle_interrupt;
     269             : 
     270         502 :                 if (tds_ctx->locale && !tds_ctx->locale->datetime_fmt) {
     271             :                         /* set default in case there's no locale file */
     272             :                         static const char datetime_format[] = "%b %e %Y %l:%M:%S:%z%p";
     273           0 :                         tds_ctx->locale->datetime_fmt = strdup(datetime_format);
     274           0 :                         if (!tds_ctx->locale->datetime_fmt) {
     275           0 :                                 tds_free_context(tds_ctx);
     276           0 :                                 return NULL;
     277             :                         }
     278             :                 }
     279         502 :                 g_dblib_ctx.tds_ctx = tds_ctx;
     280             :         }
     281        1366 :         return g_dblib_ctx.tds_ctx;
     282             : }
     283             : 
     284             : /**
     285             :  * Decrease global dblib TDS context.
     286             :  * dblib_mutex should be locked.
     287             :  *
     288             :  * @param count number of references to decrease.
     289             :  */
     290             : static void
     291         928 : dblib_release_tds_ctx(int count)
     292             : {
     293         928 :         tdsdump_log(TDS_DBG_FUNC, "dblib_release_tds_ctx(%d)\n", count);
     294             : 
     295         928 :         g_dblib_ctx.tds_ctx_ref_count -= count;
     296         928 :         if (g_dblib_ctx.tds_ctx_ref_count <= 0) {
     297         472 :                 tds_free_context(g_dblib_ctx.tds_ctx);
     298         472 :                 g_dblib_ctx.tds_ctx = NULL;
     299             :         }
     300         928 : }
     301             : 
     302             : #include "buffering.h"
     303             : 
     304             : static void
     305        3198 : db_env_chg(TDSSOCKET * tds, int type, char *oldval, char *newval)
     306             : {
     307             :         DBPROCESS *dbproc;
     308             : 
     309        3198 :         assert(oldval != NULL && newval != NULL);
     310        3198 :         if (strlen(oldval) == 1 && *oldval == 1)
     311           0 :                 oldval = "(0x1)";
     312             :                 
     313        3198 :         tdsdump_log(TDS_DBG_FUNC, "db_env_chg(%p, %d, %s, %s)\n", tds, type, oldval, newval);
     314             : 
     315        3198 :         if (!tds || !(dbproc = (DBPROCESS *) tds_get_parent(tds)))
     316             :                 return;
     317             : 
     318        3198 :         dbproc->envchange_rcv |= (1 << (type - 1));
     319        3198 :         switch (type) {
     320        1664 :         case TDS_ENV_DATABASE:
     321        1664 :                 strlcpy(dbproc->dbcurdb, newval, sizeof(dbproc->dbcurdb));
     322        1664 :                 break;
     323           0 :         case TDS_ENV_CHARSET:
     324           0 :                 strlcpy(dbproc->servcharset, newval, sizeof(dbproc->servcharset));
     325           0 :                 break;
     326             :         default:
     327             :                 break;
     328             :         }
     329             :         return;
     330             : }
     331             : 
     332             : /** \internal
     333             :  * \ingroup dblib_internal
     334             :  * \brief Sanity checks for column-oriented functions.  
     335             :  * 
     336             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
     337             :  * \param pcolinfo address of pointer to a TDSCOLUMN structure.
     338             :  * \remarks Makes sure dbproc and the requested column are valid.  
     339             :  *      Calls dbperror() if not.  
     340             :  * \returns appropriate error or SUCCEED
     341             :  */
     342             : static TDSCOLUMN*
     343       11736 : dbcolptr(DBPROCESS* dbproc, int column)
     344             : {
     345             :         TDSSOCKET *tds;
     346             :         TDSRESULTINFO *info;
     347             : 
     348       11736 :         if (!dbproc) {
     349           0 :                 dbperror(dbproc, SYBENULL, 0);
     350           0 :                 return NULL;
     351             :         }
     352       11736 :         tds = dbproc->tds_socket;
     353       11736 :         if (IS_TDSDEAD(tds)) {
     354           0 :                 dbperror(dbproc, SYBEDDNE, 0);
     355           0 :                 return NULL;
     356             :         }
     357       11736 :         info = tds->res_info;
     358       11736 :         if (!info)
     359             :                 return NULL;
     360       11476 :         if (column < 1 || column > info->num_cols) {
     361           0 :                 dbperror(dbproc, SYBECNOR, 0);
     362           0 :                 return NULL;
     363             :         } 
     364             :         
     365       11476 :         return info->columns[column - 1];
     366             : }
     367             : 
     368             : static TDSCOLUMN*
     369          64 : dbacolptr(DBPROCESS* dbproc, int computeid, int column, bool is_bind)
     370             : {
     371             :         unsigned int i;
     372             :         TDSSOCKET *tds;
     373             :         TDSCOMPUTEINFO *info;
     374             : 
     375          64 :         if (!dbproc) {
     376           0 :                 dbperror(dbproc, SYBENULL, 0);
     377           0 :                 return NULL;
     378             :         }
     379          64 :         tds = dbproc->tds_socket;
     380          64 :         if (IS_TDSDEAD(tds)) {
     381           0 :                 dbperror(dbproc, SYBEDDNE, 0);
     382           0 :                 return NULL;
     383             :         }
     384          32 :         for (i = 0;; ++i) {
     385         128 :                 if (i >= tds->num_comp_info) {
     386             :                         /* Attempt to bind user variable to a non-existent compute row */
     387           0 :                         if (is_bind)
     388           0 :                                 dbperror(dbproc, SYBEBNCR, 0);
     389             :                         return NULL;
     390             :                 }
     391          96 :                 info = tds->comp_info[i];
     392          96 :                 if (info->computeid == computeid)
     393             :                         break;
     394             :         }
     395             :         /* Fail if either the compute id or the column number is invalid. */
     396          64 :         if (column < 1 || column > info->num_cols) {
     397           0 :                 dbperror(dbproc, is_bind ? SYBEABNC : SYBECNOR, 0);
     398           0 :                 return NULL;
     399             :         }
     400             : 
     401          64 :         return info->columns[column - 1];
     402             : }
     403             : 
     404             : /*
     405             :  * Default null substitution values
     406             :  * Binding Type         Null Substitution Value
     407             :  * TINYBIND             0
     408             :  * SMALLBIND            0
     409             :  * INTBIND              0
     410             :  * CHARBIND             Empty string (padded with blanks)
     411             :  * STRINGBIND           Empty string (padded with blanks, null-terminated)
     412             :  * NTBSTRINGBIND        Empty string (null-terminated)
     413             :  * VARYCHARBIND         Empty string
     414             :  * BINARYBIND           Empty array (padded with zeros)
     415             :  * VARYBINBIND          Empty array
     416             :  * DATETIMEBIND         8 bytes of zeros
     417             :  * SMALLDATETIMEBIND    8 bytes of zeros
     418             :  * MONEYBIND            $0.00
     419             :  * SMALLMONEYBIND       $0.00
     420             :  * FLT8BIND             0.0
     421             :  * REALBIND             0.0
     422             :  * DECIMALBIND          0.0 (with default scale and precision)
     423             :  * NUMERICBIND          0.0 (with default scale and precision)
     424             :  * BOUNDARYBIND         Empty string (null-terminated)
     425             :  * SENSITIVITYBIND      Empty string (null-terminated)
     426             :  */
     427             : 
     428             : static const DBBIT              null_BIT = 0;
     429             : static const DBTINYINT          null_TINYINT = 0;
     430             : static const DBSMALLINT         null_SMALLINT = 0;
     431             : static const DBINT              null_INT = 0;
     432             : static const DBBIGINT           null_BIGINT = 0;
     433             : static const DBFLT8             null_FLT8 = 0;
     434             : static const DBREAL             null_REAL = 0;
     435             : 
     436             : static const DBCHAR             null_CHAR = '\0';
     437             : static const DBVARYCHAR         null_VARYCHAR = { 0, {0} };
     438             : 
     439             : static const DBDATETIME         null_DATETIME = { 0, 0 };
     440             : static const DBDATETIME4        null_SMALLDATETIME = { 0, 0 };
     441             : static const DBMONEY            null_MONEY = { 0, 0 };
     442             : static const DBMONEY4           null_SMALLMONEY = {0};
     443             : static const DBNUMERIC          null_NUMERIC = { 0, 0, {0} };
     444             : static const TDS_DATETIMEALL    null_DATETIMEALL = { 0, 0, 0, 0 };
     445             : 
     446             : static NULLREP default_null_representations[MAXBINDTYPES] = {
     447             :         /* CHARBIND          0  */        {         NULL, 0 }
     448             :         /* STRINGBIND        1  */      , {         NULL, 0 }
     449             :         /* NTBSTRINGBIND     2  */      , { (BYTE*) &null_CHAR, sizeof(null_CHAR) }
     450             :         /* VARYCHARBIND      3  */      , { (BYTE*) &null_VARYCHAR, sizeof(null_VARYCHAR) }
     451             :         /* VARYBINBIND       4  */      , { (BYTE*) &null_VARYCHAR, sizeof(null_VARYCHAR) }
     452             :         /* no such bind      5  */      , {         NULL, 0 }                   
     453             :         /* TINYBIND          6  */      , {         &null_TINYINT, sizeof(null_TINYINT) }
     454             :         /* SMALLBIND         7  */      , { (BYTE*) &null_SMALLINT, sizeof(null_SMALLINT) }
     455             :         /* INTBIND           8  */      , { (BYTE*) &null_INT, sizeof(null_INT) }
     456             :         /* FLT8BIND          9  */      , { (BYTE*) &null_FLT8, sizeof(null_FLT8) }
     457             :         /* REALBIND          10 */      , { (BYTE*) &null_REAL, sizeof(null_REAL) }
     458             :         /* DATETIMEBIND      11 */      , { (BYTE*) &null_DATETIME, sizeof(null_DATETIME) }
     459             :         /* SMALLDATETIMEBIND 12 */      , { (BYTE*) &null_SMALLDATETIME, sizeof(null_SMALLDATETIME) }
     460             :         /* MONEYBIND         13 */      , { (BYTE*) &null_MONEY, sizeof(null_MONEY) }
     461             :         /* SMALLMONEYBIND    14 */      , { (BYTE*) &null_SMALLMONEY, sizeof(null_SMALLMONEY) }
     462             :         /* BINARYBIND        15 */      , {         NULL, 0 }               
     463             :         /* BITBIND           16 */      , {         &null_BIT, sizeof(null_BIT) }
     464             :         /* NUMERICBIND       17 */      , { (BYTE*) &null_NUMERIC, sizeof(null_NUMERIC) }
     465             :         /* DECIMALBIND       18 */      , { (BYTE*) &null_NUMERIC, sizeof(null_NUMERIC) }
     466             :         /* SRCNUMERICBIND    19 */      , { (BYTE*) &null_NUMERIC, sizeof(null_NUMERIC) }
     467             :         /* SRCDECIMALBIND    20 */      , { (BYTE*) &null_NUMERIC, sizeof(null_NUMERIC) }
     468             :         /* DATEBIND          21 */      , { (BYTE*) &null_INT, sizeof(null_INT) }
     469             :         /* TIMEBIND          22 */      , { (BYTE*) &null_INT, sizeof(null_INT) }
     470             :         /* BIGDATETIMEBIND   23 */      , { (BYTE*) &null_BIGINT, sizeof(null_BIGINT) }
     471             :         /* BIGTIMEBIND       24 */      , { (BYTE*) &null_BIGINT, sizeof(null_BIGINT) }
     472             :         /*                   25 */      , {         NULL, 0 }
     473             :         /*                   26 */      , {         NULL, 0 }
     474             :         /*                   27 */      , {         NULL, 0 }
     475             :         /*                   28 */      , {         NULL, 0 }
     476             :         /*                   29 */      , {         NULL, 0 }
     477             :         /* BIGINTBIND        30 */      , { (BYTE*) &null_BIGINT, sizeof(null_BIGINT) }
     478             :         /* DATETIME2BIND     31 */      , { (BYTE*) &null_DATETIMEALL, sizeof(null_DATETIMEALL) }
     479             :         /* MAXBINDTYPES      32 */
     480             : };
     481             : 
     482             : static int
     483         122 : dbbindtype(int datatype)
     484             : {
     485         122 :         switch (datatype) {
     486             :         case SYBIMAGE:
     487             :         case SYBVARBINARY:
     488             :         case SYBBINARY:         return BINARYBIND;
     489             :         
     490           0 :         case SYBBIT:            return BITBIND;
     491             : 
     492          22 :         case SYBLONGCHAR:
     493             :         case SYBTEXT:
     494             :         case SYBVARCHAR:
     495          22 :         case SYBCHAR:           return NTBSTRINGBIND;
     496             :         
     497           0 :         case SYBDATETIME:       return DATETIMEBIND;
     498           0 :         case SYBDATETIME4:      return SMALLDATETIMEBIND;
     499             : 
     500           0 :         case SYBDATE:           return DATEBIND;
     501           0 :         case SYBTIME:           return TIMEBIND;
     502             : 
     503           0 :         case SYB5BIGDATETIME:   return BIGDATETIMEBIND;
     504           0 :         case SYB5BIGTIME:       return BIGTIMEBIND;
     505             : 
     506           0 :         case SYBDECIMAL:        return DECIMALBIND;
     507           0 :         case SYBNUMERIC:        return NUMERICBIND;
     508             :         
     509           0 :         case SYBFLT8:           return FLT8BIND;
     510           0 :         case SYBREAL:           return REALBIND;
     511             : 
     512           0 :         case SYBINT1:           return TINYBIND;
     513           0 :         case SYBINT2:           return SMALLBIND;
     514           0 :         case SYBINT4:           return INTBIND;
     515           0 :         case SYBINT8:           return BIGINTBIND;
     516             : 
     517           0 :         case SYBMONEY:          return MONEYBIND;
     518           0 :         case SYBMONEY4:         return SMALLMONEYBIND;
     519             : 
     520           0 :         case SYBMSDATE:
     521             :         case SYBMSTIME:
     522             :         case SYBMSDATETIME2:
     523             :         case SYBMSDATETIMEOFFSET:
     524           0 :                                 return DATETIME2BIND;
     525             : 
     526             :         default:
     527           0 :                 assert(0 == "no such datatype");
     528             :         }
     529             :         
     530             :         return 0;
     531             : }
     532             : 
     533             : /** \internal
     534             :  * dbbind() says: "Note that if varlen is 0, no padding takes place"
     535             :  * dbgetnull() will not pad varaddr unless varlen is positive.  
     536             :  * Vartype              Program Type    Padding         Terminator
     537             :  * -------------------  --------------  --------------  ----------
     538             :  * CHARBIND             DBCHAR          blanks          none
     539             :  * STRINGBIND           DBCHAR          blanks          \0
     540             :  * NTBSTRINGBIND        DBCHAR          none            \0
     541             :  * VARYCHARBIND         DBVARYCHAR      none            none
     542             :  * BOUNDARYBIND         DBCHAR          none            \0
     543             :  * SENSITIVITYBIND      DBCHAR          none            \0
     544             :  */
     545             : RETCODE
     546         420 : dbgetnull(DBPROCESS *dbproc, int bindtype, int varlen, BYTE* varaddr)
     547             : {
     548         420 :         NULLREP *pnullrep = default_null_representations + bindtype;
     549             : 
     550         420 :         tdsdump_log(TDS_DBG_FUNC, "dbgetnull(%p, %d, %d, %p)\n", dbproc, bindtype, varlen, varaddr);
     551             : 
     552         420 :         CHECK_PARAMETER(varaddr, SYBENULL, FAIL);
     553         420 :         CHECK_PARAMETER(0 <= bindtype && bindtype < MAXBINDTYPES, SYBEBTYP, FAIL);
     554             : 
     555             :         /* dbproc can be NULL */
     556         420 :         if (NULL != dbproc) {
     557         320 :                 assert(dbproc->nullreps);
     558         320 :                 pnullrep = dbproc->nullreps + bindtype;
     559             :         }
     560             :         
     561             :         /* 
     562             :          * Fixed types: ignore varlen
     563             :          * Other types: ignore varlen if <= 0, else varlen must be >= pnullrep->len.
     564             :          */
     565             :         switch (bindtype) {
     566          10 :         case DATETIMEBIND:
     567             :         case DATETIME2BIND:
     568             :         case DECIMALBIND:
     569             :         case SRCDECIMALBIND:
     570             :         case FLT8BIND:
     571             :         case INTBIND:
     572             :         case MONEYBIND:
     573             :         case NUMERICBIND:
     574             :         case SRCNUMERICBIND:
     575             :         case REALBIND:
     576             :         case SMALLBIND:
     577             :         case SMALLDATETIMEBIND:
     578             :         case SMALLMONEYBIND:
     579             :         case TINYBIND:
     580             :         case BIGINTBIND:
     581             :         case BITBIND:
     582             :         case TIMEBIND:
     583             :         case DATEBIND:
     584             :         case BIGDATETIMEBIND:
     585             :         case BIGTIMEBIND:
     586          10 :                 memcpy(varaddr, pnullrep->bindval, pnullrep->len);
     587          10 :                 return SUCCEED;
     588         410 :         case CHARBIND:
     589             :         case STRINGBIND:
     590             :         case NTBSTRINGBIND:
     591             :         case BINARYBIND:
     592             :         case VARYCHARBIND:
     593             :         case VARYBINBIND:
     594         410 :                 if (pnullrep->bindval && (varlen <= 0 || (size_t)varlen >= pnullrep->len)) {
     595         232 :                         memcpy(varaddr, pnullrep->bindval, pnullrep->len);
     596             :                 }
     597             :                 break;
     598           0 :         default:
     599           0 :                 dbperror(dbproc, SYBEBTYP, 0);
     600           0 :                 return FAIL;
     601             :         }
     602             : 
     603             :         /* 
     604             :          * For variable-length types, nonpositive varlen indicates 
     605             :          * buffer is "big enough" but also not to pad.
     606             :          * Apply terminator (if applicable) and go home.  
     607             :          */
     608         410 :         if (varlen <= 0) {
     609         258 :                 varlen = pnullrep->len;
     610         258 :                 switch (bindtype) {
     611         188 :                 case STRINGBIND:
     612             :                 case NTBSTRINGBIND:
     613         188 :                         ++varlen;
     614         188 :                         break;
     615             : #if 0
     616             :                 case BOUNDARYBIND:
     617             :                 case SENSITIVITYBIND:
     618             : #endif
     619             :                 }
     620             :         }
     621             :         
     622         410 :         if (varlen < (long)pnullrep->len) {
     623           0 :                 tdsdump_log(TDS_DBG_FUNC, "dbgetnull: error: not setting varaddr(%p) because %d < %lu\n",
     624             :                                         varaddr, varlen, (unsigned long int) pnullrep->len);
     625             :                 return FAIL;
     626             :         } 
     627             :                 
     628         410 :         tdsdump_log(TDS_DBG_FUNC, "varaddr(%p) varlen %d < %lu?\n",
     629             :                                 varaddr, varlen, (unsigned long int) pnullrep->len);
     630             : 
     631         410 :         assert(varlen >= 0);
     632             : 
     633             :         /*
     634             :          * CHARBIND             Empty string (padded with blanks)
     635             :          * STRINGBIND           Empty string (padded with blanks, null-terminated)
     636             :          * NTBSTRINGBIND        Empty string (unpadded, null-terminated)
     637             :          * BINARYBIND           Empty array (padded with zeros)
     638             :          */
     639         410 :         varaddr += pnullrep->len;
     640         410 :         varlen  -= (int)pnullrep->len;
     641         410 :         if (varlen > 0) {
     642         326 :                 switch (bindtype) {
     643          48 :                 case CHARBIND:
     644          48 :                         memset(varaddr, ' ', varlen);
     645          48 :                         break;
     646          40 :                 case STRINGBIND:
     647          40 :                         memset(varaddr, ' ', varlen);
     648          40 :                         varaddr[varlen-1] = '\0';
     649          40 :                         break;
     650         148 :                 case NTBSTRINGBIND:
     651         148 :                         varaddr[0] = '\0';
     652         148 :                         break;
     653          90 :                 case BINARYBIND:
     654          90 :                         memset(varaddr, 0, varlen);
     655          90 :                         break;
     656             :                 case VARYCHARBIND:
     657             :                 case VARYBINBIND:
     658             :                         break;
     659             :                 default:
     660           0 :                         assert(!"unknown bindtype");
     661             :                 }
     662             :         }       
     663             :         return SUCCEED;
     664             : }
     665             : 
     666             : /**
     667             :  * \ingroup dblib_core
     668             :  * \brief Initialize db-lib.  
     669             :  *
     670             :  * \remarks Call this function before trying to use db-lib in any way.  
     671             :  * Allocates various internal structures and reads \c locales.conf (if any) to determine the default
     672             :  * date format.  
     673             :  * \retval SUCCEED normal.  
     674             :  * \retval FAIL cannot allocate an array of \c TDS_MAX_CONN \c TDSSOCKET pointers.  
     675             :  */
     676             : RETCODE
     677         502 : dbinit(void)
     678             : {
     679         502 :         _dblib_err_handler = default_err_handler;
     680             : 
     681         502 :         tds_mutex_lock(&dblib_mutex);
     682             : 
     683         502 :         tdsdump_log(TDS_DBG_FUNC, "dbinit(void)\n");
     684             : 
     685         502 :         if (++g_dblib_ctx.ref_count != 1) {
     686           0 :                 tds_mutex_unlock(&dblib_mutex);
     687           0 :                 return SUCCEED;
     688             :         }
     689             : 
     690         502 :         if (dblib_get_tds_ctx() == NULL) {
     691           0 :                 tdsdump_log(TDS_DBG_FUNC, "dbinit: out of memory\n");
     692           0 :                 tds_mutex_unlock(&dblib_mutex);
     693           0 :                 return FAIL;
     694             :         }
     695             : 
     696             :         /* 
     697             :          * DBLIBCONTEXT stores a list of current connections so they may be closed with dbexit() 
     698             :          */
     699             : 
     700         502 :         g_dblib_ctx.connection_list = tds_new0(TDSSOCKET *, TDS_MAX_CONN);
     701         502 :         if (g_dblib_ctx.connection_list == NULL) {
     702           0 :                 tdsdump_log(TDS_DBG_FUNC, "dbinit: out of memory\n");
     703           0 :                 dblib_release_tds_ctx(1);
     704           0 :                 tds_mutex_unlock(&dblib_mutex);
     705           0 :                 return FAIL;
     706             :         }
     707         502 :         g_dblib_ctx.connection_list_size = TDS_MAX_CONN;
     708         502 :         g_dblib_ctx.connection_list_size_represented = TDS_MAX_CONN;
     709             : 
     710         502 :         g_dblib_ctx.login_timeout = -1;
     711         502 :         g_dblib_ctx.query_timeout = -1;
     712             : 
     713         502 :         tds_mutex_unlock(&dblib_mutex);
     714             : 
     715         502 :         return SUCCEED;
     716             : }
     717             : 
     718             : /**
     719             :  * \ingroup dblib_core
     720             :  * \brief Allocate a \c LOGINREC structure.  
     721             :  *
     722             :  * \remarks A \c LOGINREC structure is passed to \c dbopen() to create a connection to the database. 
     723             :  *      Does not communicate to the server; interacts strictly with library.  
     724             :  * \retval NULL the \c LOGINREC cannot be allocated.
     725             :  * \retval LOGINREC* to valid memory, otherwise.  
     726             :  */
     727             : LOGINREC *
     728         832 : dblogin(void)
     729             : {
     730             :         LOGINREC *loginrec;
     731             : 
     732         832 :         tdsdump_log(TDS_DBG_FUNC, "dblogin(void)\n");
     733             : 
     734         832 :         if ((loginrec = tds_new0(LOGINREC, 1)) == NULL) {
     735           0 :                 dbperror(NULL, SYBEMEM, errno);
     736           0 :                 return NULL;
     737             :         }
     738         832 :         if ((loginrec->tds_login = tds_alloc_login(true)) == NULL) {
     739           0 :                 dbperror(NULL, SYBEMEM, errno);
     740           0 :                 free(loginrec);
     741           0 :                 return NULL;
     742             :         }
     743             : 
     744             :         /* set default values for loginrec */
     745         832 :         if (!tds_set_library(loginrec->tds_login, "DB-Library")) {
     746           0 :                 dbperror(NULL, SYBEMEM, errno);
     747           0 :                 tds_free_login(loginrec->tds_login);
     748           0 :                 free(loginrec);
     749           0 :                 return NULL;
     750             :         }
     751             : 
     752             :         return loginrec;
     753             : }
     754             : 
     755             : /**
     756             :  * \ingroup dblib_core
     757             :  * \brief free the \c LOGINREC
     758             :  *
     759             :  */
     760             : void
     761         802 : dbloginfree(LOGINREC * login)
     762             : {
     763         802 :         tdsdump_log(TDS_DBG_FUNC, "dbloginfree(%p)\n", login);
     764             : 
     765         802 :         if (login) {
     766         802 :                 tds_free_login(login->tds_login);
     767         802 :                 free(login);
     768             :         }
     769         802 : }
     770             : 
     771             : /** \internal
     772             :  * \ingroup dblib_internal 
     773             :  * \brief Set the value of a string in a \c LOGINREC structure.  
     774             :  *
     775             :  * Called by various macros to populate \a login.  
     776             :  * \param login the \c LOGINREC* to modify.
     777             :  * \param value the value to set it to.  
     778             :  * \param which the field to set.  
     779             :  * \retval SUCCEED the value was set.
     780             :  * \retval FAIL \c DBSETHID or other invalid \a which was tried.  
     781             :  */
     782             : RETCODE
     783        2836 : dbsetlname(LOGINREC * login, const char *value, int which)
     784             : {
     785             :         bool copy_ret;
     786        2836 :         const char *value_nonull = value ? value : "";
     787             : 
     788        2836 :         tdsdump_log(TDS_DBG_FUNC, "dbsetlname(%p, %s, %d)\n", login, value, which);
     789             : 
     790        2836 :         if (login == NULL) {
     791           0 :                 dbperror(NULL, SYBEASNL, 0);
     792           0 :                 return FAIL;
     793             :         }
     794             : 
     795        2836 :         if (TDS_MAX_LOGIN_STR_SZ < strlen(value_nonull)) {
     796           0 :                 dbperror(NULL, SYBENTLL, 0);
     797           0 :                 return FAIL;
     798             :         }
     799             : 
     800        2836 :         switch (which) {
     801         330 :         case DBSETHOST:
     802         330 :                 copy_ret = tds_set_host(login->tds_login, value_nonull);
     803         330 :                 break;
     804         822 :         case DBSETUSER:
     805         822 :                 copy_ret = tds_set_user(login->tds_login, value_nonull);
     806         822 :                 break;
     807         822 :         case DBSETPWD:
     808         822 :                 copy_ret = tds_set_passwd(login->tds_login, value_nonull);
     809         822 :                 break;
     810         822 :         case DBSETAPP:
     811         822 :                 copy_ret = tds_set_app(login->tds_login, value_nonull);
     812         822 :                 break;
     813          10 :         case DBSETCHARSET:
     814             :                 /* TODO NULL == no conversion desired */
     815          10 :                 copy_ret = tds_set_client_charset(login->tds_login, value_nonull);
     816          10 :                 break;
     817           0 :         case DBSETNATLANG:
     818           0 :                 copy_ret = tds_set_language(login->tds_login, value_nonull);
     819           0 :                 break;
     820          30 :         case DBSETDBNAME:
     821          30 :                 copy_ret = !!tds_dstr_copy(&login->tds_login->database, value_nonull);
     822          30 :                 break;
     823           0 :         case DBSETSERVERPRINCIPAL:
     824           0 :                 copy_ret = !!tds_dstr_copy(&login->tds_login->server_spn, value_nonull);
     825           0 :                 break;
     826           0 :         case DBSETENCRYPTION:
     827           0 :                 copy_ret = tds_parse_conf_section(TDS_STR_ENCRYPTION, value_nonull, login->tds_login);
     828           0 :                 break;
     829           0 :         default:
     830           0 :                 dbperror(NULL, SYBEASUL, 0); /* Attempt to set unknown LOGINREC field */
     831           0 :                 return FAIL;
     832             :                 break;
     833             :         }
     834             : 
     835        2836 :         if (!copy_ret)
     836             :                 return FAIL;
     837        2836 :         return SUCCEED;
     838             : }
     839             : 
     840             : /** \internal
     841             :  * \ingroup dblib_internal
     842             :  * \brief Set an integer value in a \c LOGINREC structure.  
     843             :  *
     844             :  * Called by various macros to populate \a login.  
     845             :  * \param login the \c LOGINREC* to modify.
     846             :  * \param value the value to set it to.  
     847             :  * \param which the field to set.  
     848             :  * \retval SUCCEED the value was set.
     849             :  * \retval FAIL anything other than \c DBSETPACKET was passed for \a which.  
     850             :  */
     851             : RETCODE
     852          10 : dbsetllong(LOGINREC * login, long value, int which)
     853             : {
     854          10 :         tdsdump_log(TDS_DBG_FUNC, "dbsetllong(%p, %ld, %d)\n", login, value, which);
     855             : 
     856          10 :         if( login == NULL ) {
     857           0 :                 dbperror(NULL, SYBEASNL, 0);
     858           0 :                 return FAIL;
     859             :         }
     860             : 
     861          10 :         switch (which) {
     862          10 :         case DBSETPACKET:
     863          10 :                 if (0 <= value && value <= 999999) { 
     864           0 :                         tds_set_packet(login->tds_login, (int) value);
     865           0 :                         return SUCCEED;
     866             :                 }
     867          10 :                 dbperror(0, SYBEBADPK, 0, (int) value, (int) login->tds_login->block_size);
     868          10 :                 return FAIL;
     869             :                 break;
     870           0 :         default:
     871           0 :                 tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetllong() which = %d\n", which);
     872             :                 return FAIL;
     873             :                 break;
     874             :         }
     875             : }
     876             : 
     877             : /** \internal
     878             :  * \ingroup dblib_internal
     879             :  * \brief Set an integer value in a \c LOGINREC structure.  
     880             :  *
     881             :  * Called by various macros to populate \a login.  
     882             :  * \param login the \c LOGINREC* to modify.
     883             :  * \param value the value to set it to.  
     884             :  * \param which the field to set.  
     885             :  * \retval SUCCEED the value was set.
     886             :  * \retval FAIL if invalid field in \a which or invalid \a value.  
     887             :  */
     888             : RETCODE
     889           0 : dbsetlshort(LOGINREC * login, int value, int which)
     890             : {
     891           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsetlshort(%p, %d, %d)\n", login, value, which);
     892             : 
     893           0 :         if( login == NULL ) {
     894           0 :                 dbperror(NULL, SYBEASNL, 0);
     895           0 :                 return FAIL;
     896             :         }
     897             : 
     898           0 :         switch (which) {
     899           0 :         case DBSETPORT:
     900           0 :                 tds_set_port(login->tds_login, value);
     901           0 :                 return SUCCEED;
     902             :         /* case DBSETHIER: */
     903           0 :         default:
     904           0 :                 tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetlshort() which = %d\n", which);
     905             :                 return FAIL;
     906             :                 break;
     907             :         }
     908             : }
     909             : 
     910             : /** \internal
     911             :  * \ingroup dblib_internal
     912             :  * \brief Set a boolean value in a \c LOGINREC structure.  
     913             :  *
     914             :  * Called by various macros to populate \a login.  
     915             :  * \param login the \c LOGINREC* to modify.
     916             :  * \param value the value to set it to.  
     917             :  * \param which the field to set. 
     918             :  * \remark Only DBSETBCP is implemented.  
     919             :  * \retval SUCCEED the value was set.
     920             :  * \retval FAIL invalid value passed for \a which.  
     921             :  * \todo DBSETNOSHORT, DBSETENCRYPT, DBSETLABELED
     922             :  */
     923             : RETCODE
     924          50 : dbsetlbool(LOGINREC * login, int value, int which)
     925             : {
     926             :         bool b_value;
     927             : 
     928          50 :         tdsdump_log(TDS_DBG_FUNC, "dbsetlbool(%p, %d, %d)\n", login, value, which);
     929             : 
     930          50 :         if (login == NULL) {
     931           0 :                 dbperror(NULL, SYBEASNL, 0);
     932           0 :                 return FAIL;
     933             :         }
     934             : 
     935          50 :         b_value = (value != 0);
     936             : 
     937          50 :         switch (which) {
     938          50 :         case DBSETBCP:
     939          50 :                 tds_set_bulk(login->tds_login, b_value);
     940          50 :                 return SUCCEED;
     941           0 :         case DBSETUTF16:
     942           0 :                 login->tds_login->use_utf16 = b_value;
     943           0 :                 return SUCCEED;
     944           0 :         case DBSETNTLMV2:
     945           0 :                 login->tds_login->use_ntlmv2 = b_value;
     946           0 :                 login->tds_login->use_ntlmv2_specified = 1;
     947           0 :                 return SUCCEED;
     948           0 :         case DBSETREADONLY:
     949           0 :                 login->tds_login->readonly_intent = b_value;
     950           0 :                 return SUCCEED;
     951           0 :         case DBSETNETWORKAUTH:
     952           0 :                 login->network_auth = b_value;
     953           0 :                 return SUCCEED;
     954           0 :         case DBSETMUTUALAUTH:
     955           0 :                 login->tds_login->mutual_authentication = b_value;
     956           0 :                 return SUCCEED;
     957           0 :         case DBSETDELEGATION:
     958           0 :                 login->tds_login->gssapi_use_delegation = b_value;
     959           0 :                 return SUCCEED;
     960           0 :         case DBSETENCRYPT:
     961             :         case DBSETLABELED:
     962             :         default:
     963           0 :                 tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetlbool() which = %d\n", which);
     964             :                 return FAIL;
     965             :                 break;
     966             :         }
     967             : }
     968             : 
     969             : /**
     970             :  * \ingroup dblib_core
     971             :  * \brief Set TDS version for future connections
     972             :  *
     973             :  */
     974             : RETCODE 
     975           0 : dbsetlversion(LOGINREC * login, BYTE version)
     976             : {
     977           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsetlversion(%p, %x)\n", login, version);
     978             : 
     979           0 :         if( login == NULL ) {
     980           0 :                 dbperror(NULL, SYBEASNL, 0);
     981           0 :                 return FAIL;
     982             :         }
     983             : 
     984           0 :         assert(login->tds_login != NULL);
     985             : 
     986           0 :         switch (version) {
     987           0 :         case DBVERSION_UNKNOWN:
     988           0 :                 tds_set_version(login->tds_login, 0, 0);
     989           0 :                 return SUCCEED;
     990           0 :         case DBVERSION_42:
     991           0 :                 tds_set_version(login->tds_login, 4, 2);
     992           0 :                 return SUCCEED;
     993           0 :         case DBVERSION_100:
     994           0 :                 tds_set_version(login->tds_login, 5, 0);
     995           0 :                 return SUCCEED;
     996           0 :         case DBVERSION_70:
     997           0 :                 tds_set_version(login->tds_login, 7, 0);
     998           0 :                 return SUCCEED;
     999           0 :         case DBVERSION_71:
    1000           0 :                 tds_set_version(login->tds_login, 7, 1);
    1001           0 :                 return SUCCEED;
    1002           0 :         case DBVERSION_72:
    1003           0 :                 tds_set_version(login->tds_login, 7, 2);
    1004           0 :                 return SUCCEED;
    1005           0 :         case DBVERSION_73:
    1006           0 :                 tds_set_version(login->tds_login, 7, 3);
    1007           0 :                 return SUCCEED;
    1008           0 :         case DBVERSION_74:
    1009           0 :                 tds_set_version(login->tds_login, 7, 4);
    1010           0 :                 return SUCCEED;
    1011             :         }
    1012             : 
    1013             :         return FAIL;
    1014             : }
    1015             : 
    1016             : static void
    1017       36072 : dbstring_free(DBSTRING ** dbstrp)
    1018             : {
    1019             :         DBSTRING *curr, *next;
    1020             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_free(%p)\n", dbstrp); */
    1021             : 
    1022       36072 :         if (!dbstrp)
    1023             :                 return;
    1024             : 
    1025       36072 :         curr = *dbstrp;
    1026       36072 :         *dbstrp = NULL;
    1027       77178 :         for (; curr; ) {
    1028        5034 :                 next = curr->strnext;
    1029        5034 :                 free(curr->strtext);
    1030        5034 :                 free(curr);
    1031        5034 :                 curr = next;
    1032             :         }
    1033             : }
    1034             : 
    1035             : static RETCODE
    1036        5214 : dbstring_concat(DBSTRING ** dbstrp, const char *p)
    1037             : {
    1038        5214 :         DBSTRING **strp = dbstrp;
    1039             : 
    1040             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_concat(%p, %s)\n", *dbstrp, p); */
    1041             : 
    1042       10428 :         while (*strp != NULL) {
    1043           0 :                 strp = &((*strp)->strnext);
    1044             :         }
    1045        5214 :         if ((*strp = tds_new(DBSTRING, 1)) == NULL) {
    1046           0 :                 dbperror(NULL, SYBEMEM, errno);
    1047           0 :                 return FAIL;
    1048             :         }
    1049        5214 :         (*strp)->strtotlen = (DBINT)strlen(p);
    1050        5214 :         if (((*strp)->strtext = tds_new(BYTE, (*strp)->strtotlen)) == NULL) {
    1051           0 :                 TDS_ZERO_FREE(*strp);
    1052           0 :                 dbperror(NULL, SYBEMEM, errno);
    1053           0 :                 return FAIL;
    1054             :         }
    1055        5214 :         memcpy((*strp)->strtext, p, (*strp)->strtotlen);
    1056        5214 :         (*strp)->strnext = NULL;
    1057        5214 :         return SUCCEED;
    1058             : }
    1059             : 
    1060             : static RETCODE
    1061             : dbstring_assign(DBSTRING ** dbstrp, const char *p)
    1062             : {
    1063             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_assign(%p, %s)\n", *dbstrp, p); */
    1064             : 
    1065        5214 :         dbstring_free(dbstrp);
    1066        5214 :         return dbstring_concat(dbstrp, p);
    1067             : }
    1068             : 
    1069             : static DBINT
    1070             : dbstring_length(DBSTRING * dbstr)
    1071             : {
    1072           0 :         DBINT len = 0;
    1073             :         DBSTRING *next;
    1074             : 
    1075             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_length(%p)\n", dbstr); */
    1076             : 
    1077           0 :         for (next = dbstr; next != NULL; next = next->strnext) {
    1078           0 :                 len += next->strtotlen;
    1079             :         }
    1080             :         return len;
    1081             : }
    1082             : 
    1083             : static int
    1084             : dbstring_getchar(DBSTRING * dbstr, ptrdiff_t i)
    1085             : {
    1086             : 
    1087             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_getchar(%p, %d)\n", dbstr, i); */
    1088             : 
    1089        6160 :         if (dbstr == NULL) {
    1090             :                 return -1;
    1091             :         }
    1092        4600 :         if (i < 0) {
    1093             :                 return -1;
    1094             :         }
    1095        4600 :         if (i < dbstr->strtotlen) {
    1096        3040 :                 return dbstr->strtext[i];
    1097             :         }
    1098        1560 :         return dbstring_getchar(dbstr->strnext, i - dbstr->strtotlen);
    1099             : }
    1100             : 
    1101             : static char *
    1102           0 : dbstring_get(DBSTRING * dbstr)
    1103             : {
    1104             :         DBSTRING *next;
    1105             :         int len;
    1106             :         char *ret;
    1107             :         char *cp;
    1108             : 
    1109             :         /* tdsdump_log(TDS_DBG_FUNC, "dbstring_get(%p)\n", dbstr); */
    1110             : 
    1111           0 :         if (dbstr == NULL) {
    1112             :                 return NULL;
    1113             :         }
    1114           0 :         len = dbstring_length(dbstr);
    1115           0 :         if ((ret = tds_new(char, len + 1)) == NULL) {
    1116           0 :                 dbperror(NULL, SYBEMEM, errno);
    1117           0 :                 return NULL;
    1118             :         }
    1119             :         cp = ret;
    1120           0 :         for (next = dbstr; next != NULL; next = next->strnext) {
    1121           0 :                 memcpy(cp, next->strtext, next->strtotlen);
    1122           0 :                 cp += next->strtotlen;
    1123             :         }
    1124           0 :         *cp = '\0';
    1125           0 :         return ret;
    1126             : }
    1127             : 
    1128             : static const char *const opttext[DBNUMOPTIONS] = {
    1129             :         "parseonly",
    1130             :         "estimate",
    1131             :         "showplan",
    1132             :         "noexec",
    1133             :         "arithignore",
    1134             :         "nocount",
    1135             :         "arithabort",
    1136             :         "textlimit",
    1137             :         "browse",
    1138             :         "offsets",
    1139             :         "statistics",
    1140             :         "errlvl",
    1141             :         "confirm",
    1142             :         "spid",
    1143             :         "buffer",
    1144             :         "noautofree",
    1145             :         "rowcount",
    1146             :         "textsize",
    1147             :         "language",
    1148             :         "dateformat",
    1149             :         "prpad",
    1150             :         "prcolsep",
    1151             :         "prlinelen",
    1152             :         "prlinesep",
    1153             :         "lfconvert",
    1154             :         "datefirst",
    1155             :         "chained",
    1156             :         "fipsflagger",
    1157             :         "transaction isolation level",
    1158             :         "auth",
    1159             :         "identity_insert",
    1160             :         "no_identity_column",
    1161             :         "cnv_date2char_short",
    1162             :         "client cursors",
    1163             :         "set time",
    1164             :         "quoted_identifier"
    1165             : };
    1166             : 
    1167             : static DBOPTION *
    1168         864 : init_dboptions(void)
    1169             : {
    1170             :         DBOPTION *dbopts;
    1171             :         int i;
    1172             : 
    1173         864 :         if ((dbopts = tds_new0(DBOPTION, DBNUMOPTIONS)) == NULL) {
    1174           0 :                 dbperror(NULL, SYBEMEM, errno);
    1175           0 :                 return NULL;
    1176             :         }
    1177       31104 :         for (i = 0; i < DBNUMOPTIONS; i++) {
    1178       31104 :                 dbopts[i].text = opttext[i];
    1179       31104 :                 dbopts[i].param = NULL;
    1180       31104 :                 dbopts[i].factive = FALSE;
    1181             :         }
    1182        1728 :         dbstring_assign(&(dbopts[DBPRPAD].param), " ");
    1183        1728 :         dbstring_assign(&(dbopts[DBPRCOLSEP].param), " ");
    1184        1728 :         dbstring_assign(&(dbopts[DBPRLINELEN].param), "80");
    1185        1728 :         dbstring_assign(&(dbopts[DBPRLINESEP].param), "\n");
    1186        1728 :         dbstring_assign(&(dbopts[DBCLIENTCURSORS].param), " ");
    1187        1728 :         dbstring_assign(&(dbopts[DBSETTIME].param), " ");
    1188         864 :         return dbopts;
    1189             : }
    1190             : 
    1191             : /** \internal
    1192             :  * \ingroup dblib_internal
    1193             :  * \brief Form a connection with the server.
    1194             :  *   
    1195             :  * Called by the \c dbopen() macro, normally.  If FreeTDS was configured with \c --enable-msdblib, this
    1196             :  * function is called by (exported) \c dbopen() function.  \c tdsdbopen is so-named to avoid
    1197             :  * namespace conflicts with other database libraries that use the same function name.  
    1198             :  * \param login \c LOGINREC* carrying the account information.
    1199             :  * \param server name of the dataserver to connect to.  
    1200             :  * \return valid pointer on successful login.  
    1201             :  * \retval NULL insufficient memory, unable to connect for any reason.
    1202             :  * \sa dbopen()
    1203             :  * \todo use \c asprintf() to avoid buffer overflow.
    1204             :  * \todo separate error messages for \em no-such-server and \em no-such-user. 
    1205             :  */
    1206             : DBPROCESS *
    1207         864 : tdsdbopen(LOGINREC * login, const char *server, int msdblib)
    1208             : {
    1209         864 :         DBPROCESS *dbproc = NULL;
    1210         864 :         TDSCONTEXT *tds_ctx = NULL;
    1211             :         TDSLOGIN *connection;
    1212             :         int add_connection_res;
    1213             : 
    1214         864 :         tds_dir_char *tdsdump = tds_dir_getenv(TDS_DIR("TDSDUMP"));
    1215         864 :         if (tdsdump && *tdsdump) {
    1216           0 :                 tdsdump_topen(tdsdump);
    1217           0 :                 tdsdump_log(TDS_DBG_FUNC, "tdsdbopen(%p, %s, [%s])\n", login, server? server : "0x0", msdblib? "microsoft" : "sybase");
    1218             :         }
    1219             : 
    1220             :         /*
    1221             :          * Sybase supports the DSQUERY environment variable and falls back to "SYBASE" if server is NULL. 
    1222             :          * Microsoft uses a NULL or "" server to indicate a local server.  
    1223             :          * FIXME: support local server for win32.  
    1224             :          */
    1225         864 :         if (!server && !msdblib) {
    1226           0 :                 if ((server = getenv("TDSQUERY")) == NULL)
    1227           0 :                         if ((server = getenv("DSQUERY")) == NULL)
    1228           0 :                                 server = "SYBASE";
    1229           0 :                 tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: servername set to %s\n", server);
    1230             :         }
    1231             : 
    1232         864 :         if ((dbproc = tds_new0(DBPROCESS, 1)) == NULL)
    1233             :                 goto memory_error;
    1234         864 :         dbproc->msdblib = msdblib;
    1235             : 
    1236         864 :         dbproc->dbopts = init_dboptions();
    1237         864 :         if (dbproc->dbopts == NULL)
    1238             :                 goto cleanup;
    1239         864 :         tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: dbproc->dbopts = %p\n", dbproc->dbopts);
    1240             : 
    1241         864 :         dbproc->dboptcmd = NULL;
    1242         864 :         dbproc->avail_flag = TRUE;
    1243         864 :         dbproc->command_state = DBCMDNONE;
    1244             : 
    1245         864 :         if (!tds_set_server(login->tds_login, server))
    1246             :                 goto memory_error;
    1247         864 :         tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: tds_set_server(%p, \"%s\")\n", login->tds_login, server);
    1248             : 
    1249         864 :         tds_mutex_lock(&dblib_mutex);
    1250         864 :         tds_ctx = dblib_get_tds_ctx();
    1251         864 :         tds_mutex_unlock(&dblib_mutex);
    1252         864 :         if (!tds_ctx)
    1253             :                 goto memory_error;
    1254             : 
    1255         864 :         dbproc->tds_socket = tds_alloc_socket(tds_ctx, 512);
    1256         864 :         if (dbproc->tds_socket == NULL)
    1257             :                 goto memory_error;
    1258         864 :         tds_ctx = NULL;
    1259             : 
    1260         864 :         tds_set_parent(dbproc->tds_socket, dbproc);
    1261             : 
    1262         864 :         dbproc->tds_socket->env_chg_func = db_env_chg;
    1263         864 :         dbproc->envchange_rcv = 0;
    1264             : 
    1265         864 :         dbproc->dbcurdb[0] = '\0';
    1266         864 :         dbproc->servcharset[0] = '\0';
    1267             : 
    1268         864 :         tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: About to call tds_read_config_info...\n");
    1269             : 
    1270         864 :         tds_mutex_lock(&dblib_mutex);
    1271         864 :         add_connection_res = dblib_add_connection(&g_dblib_ctx, dbproc->tds_socket);
    1272         864 :         tds_mutex_unlock(&dblib_mutex);
    1273         864 :         if (add_connection_res) {
    1274          10 :                 dbperror(dbproc, SYBEDBPS, 0);
    1275          10 :                 dbclose(dbproc);
    1276          10 :                 return NULL;
    1277             :         }
    1278             : 
    1279         854 :         connection = tds_read_config_info(dbproc->tds_socket, login->tds_login, g_dblib_ctx.tds_ctx->locale);
    1280         854 :         if (!connection) {
    1281           0 :                 dbclose(dbproc);
    1282           0 :                 return NULL;
    1283             :         }
    1284         854 :         connection->option_flag2 &= ~TDS_ODBC_ON;        /* we're not an ODBC driver */
    1285         854 :         tds_fix_login(connection);              /* initialize from Environment variables */
    1286             : 
    1287         854 :         dbproc->chkintr = NULL;
    1288         854 :         dbproc->hndlintr = NULL;
    1289             : 
    1290         854 :         tds_mutex_lock(&dblib_mutex);
    1291             : 
    1292             :         /* override connection timeout if dbsetlogintime() was called */
    1293         854 :         if (g_dblib_ctx.login_timeout > 0) {
    1294          20 :                 connection->connect_timeout = g_dblib_ctx.login_timeout;
    1295             :         }
    1296             : 
    1297             :         /* override query timeout if dbsettime() was called */
    1298         854 :         if (g_dblib_ctx.query_timeout > 0) {
    1299          10 :                 connection->query_timeout = g_dblib_ctx.query_timeout;
    1300             :         }
    1301             : 
    1302         854 :         tds_mutex_unlock(&dblib_mutex);
    1303             : 
    1304         854 :         tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: Calling tds_connect_and_login(%p, %p)\n",
    1305             :                 dbproc->tds_socket, connection);
    1306             : 
    1307         854 :         if (login->network_auth) {
    1308           0 :                 tds_dstr_empty(&connection->user_name);
    1309           0 :                 tds_dstr_empty(&connection->password);
    1310             :         }
    1311             : 
    1312         854 :         if (TDS_FAILED(tds_connect_and_login(dbproc->tds_socket, connection))) {
    1313           0 :                 tdsdump_log(TDS_DBG_ERROR, "tdsdbopen: tds_connect_and_login failed for \"%s\"!\n",
    1314             :                         tds_dstr_cstr(&connection->server_name));
    1315           0 :                 tds_free_login(connection);
    1316           0 :                 dbclose(dbproc);
    1317           0 :                 return NULL;
    1318             :         }
    1319         854 :         tds_free_login(connection);
    1320             : 
    1321         854 :         dbproc->dbbuf = NULL;
    1322         854 :         dbproc->dbbufsz = 0;
    1323             : 
    1324             :         /* set the DBBUFFER capacity to nil */
    1325         854 :         buffer_set_capacity(dbproc, 0);
    1326             : 
    1327         854 :         memcpy(dbproc->nullreps, default_null_representations, sizeof(default_null_representations));
    1328             : 
    1329         854 :         tds_mutex_lock(&dblib_mutex);
    1330             : 
    1331         854 :         if (g_dblib_ctx.recftos_filename != NULL) {
    1332           0 :                 char *temp_filename = NULL;
    1333           0 :                 const int len = asprintf(&temp_filename, "%s.%d", 
    1334             :                                          g_dblib_ctx.recftos_filename, g_dblib_ctx.recftos_filenum);
    1335           0 :                 if (len >= 0) {
    1336           0 :                         dbproc->ftos = fopen(temp_filename, "w");
    1337           0 :                         free(temp_filename);
    1338           0 :                         if (dbproc->ftos != NULL) {
    1339             :                                 char timestr[256];
    1340           0 :                                 fprintf(dbproc->ftos, "/* dbopen() at %s */\n", _dbprdate(timestr));
    1341           0 :                                 fflush(dbproc->ftos);
    1342           0 :                                 g_dblib_ctx.recftos_filenum++;
    1343             :                         }
    1344             :                 }
    1345             :         }
    1346             :         
    1347         854 :         tds_mutex_unlock(&dblib_mutex);
    1348             : 
    1349         854 :         tdsdump_log(TDS_DBG_FUNC, "tdsdbopen: Returning dbproc = %p\n", dbproc);
    1350             : 
    1351             :         return dbproc;
    1352             : 
    1353           0 :       memory_error:
    1354           0 :         dbperror(NULL, SYBEMEM, errno);
    1355             : 
    1356           0 :       cleanup:
    1357           0 :         if (tds_ctx) {
    1358           0 :                 tds_mutex_lock(&dblib_mutex);
    1359           0 :                 dblib_release_tds_ctx(1);
    1360           0 :                 tds_mutex_unlock(&dblib_mutex);
    1361             :         }
    1362           0 :         if (dbproc) {
    1363           0 :                 free(dbproc->dbopts);
    1364           0 :                 free(dbproc);
    1365             :         }
    1366             :         return NULL;
    1367             : }
    1368             : 
    1369             : /**
    1370             :  * \ingroup dblib_core
    1371             :  * \brief \c printf-like way to form SQL to send to the server.  
    1372             :  *
    1373             :  * Forms a command string and writes to the command buffer with dbcmd().  
    1374             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1375             :  * \param fmt <tt> man vasprintf</tt> for details.  
    1376             :  * \retval SUCCEED success.
    1377             :  * \retval FAIL insufficient memory, or dbcmd() failed.
    1378             :  * \sa dbcmd(), dbfreebuf(), dbgetchar(), dbopen(), dbstrcpy(), dbstrlen().
    1379             :  */
    1380             : RETCODE
    1381         860 : dbfcmd(DBPROCESS * dbproc, const char *fmt, ...)
    1382             : {
    1383             :         va_list ap;
    1384             :         char *s;
    1385             :         int len;
    1386             :         RETCODE ret;
    1387             : 
    1388         860 :         tdsdump_log(TDS_DBG_FUNC, "dbfcmd(%p, %s, ...)\n", dbproc, fmt);
    1389         860 :         CHECK_CONN(FAIL);
    1390         860 :         CHECK_NULP(fmt, "dbfcmd", 2, FAIL);
    1391             :         
    1392         860 :         va_start(ap, fmt);
    1393         860 :         len = vasprintf(&s, fmt, ap);
    1394         860 :         va_end(ap);
    1395             : 
    1396         860 :         if (len < 0) {
    1397           0 :                 dbperror(dbproc, SYBEMEM, errno);
    1398           0 :                 return FAIL;
    1399             :         }
    1400             : 
    1401         860 :         ret = dbcmd(dbproc, s);
    1402         860 :         free(s);
    1403             : 
    1404         860 :         return ret;
    1405             : }
    1406             : 
    1407             : /**
    1408             :  * \ingroup dblib_core
    1409             :  * \brief \c Append SQL to the command buffer.  
    1410             :  *
    1411             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1412             :  * \param cmdstring SQL to append to the command buffer.  
    1413             :  * \retval SUCCEED success.
    1414             :  * \retval FAIL insufficient memory.  
    1415             :  * \remarks set command state to \c  DBCMDPEND unless the command state is DBCMDSENT, in which case 
    1416             :  * it frees the command buffer.  This latter may or may not be the Right Thing to do.  
    1417             :  * \sa dbfcmd(), dbfreebuf(), dbgetchar(), dbopen(), dbstrcpy(), dbstrlen().
    1418             :  */
    1419             : RETCODE
    1420       25248 : dbcmd(DBPROCESS * dbproc, const char cmdstring[])
    1421             : {
    1422             :         size_t cmd_len, buf_len, newsz;
    1423             : 
    1424       25248 :         tdsdump_log(TDS_DBG_FUNC, "dbcmd(%p, %s)\n", dbproc, cmdstring);
    1425       25248 :         CHECK_CONN(FAIL);
    1426       25248 :         CHECK_NULP(cmdstring, "dbcmd", 2, FAIL);
    1427             : 
    1428       25248 :         dbproc->avail_flag = FALSE;
    1429             : 
    1430       25248 :         tdsdump_log(TDS_DBG_FUNC, "dbcmd() bufsz = %d\n", dbproc->dbbufsz);
    1431             : 
    1432       25248 :         if (dbproc->command_state == DBCMDSENT) {
    1433       19890 :                 if (!dbproc->noautofree) {
    1434       19890 :                         dbfreebuf(dbproc);
    1435             :                 }
    1436             :         }
    1437             : 
    1438       25248 :         buf_len = (dbproc->dbbufsz == 0) ? 0 : dbproc->dbbufsz - 1;
    1439       25248 :         cmd_len = strlen(cmdstring);
    1440       25248 :         newsz = buf_len + cmd_len + 1;
    1441       25248 :         if (newsz > 0x7fffffffu || !TDS_RESIZE(dbproc->dbbuf, newsz)) {
    1442           0 :                 dbperror(dbproc, SYBEMEM, errno);
    1443           0 :                 return FAIL;
    1444             :         }
    1445       25248 :         memcpy(dbproc->dbbuf + buf_len, cmdstring, cmd_len);
    1446       25248 :         dbproc->dbbuf[newsz - 1] = 0;
    1447       25248 :         dbproc->dbbufsz = (int) newsz;
    1448             : 
    1449       25248 :         dbproc->command_state = DBCMDPEND;
    1450             : 
    1451       25248 :         return SUCCEED;
    1452             : }
    1453             : 
    1454             : /**
    1455             :  * \ingroup dblib_core
    1456             :  * \brief send the SQL command to the server and wait for an answer.  
    1457             :  * 
    1458             :  * Please be patient.  This function waits for the server to respond.   \c dbsqlexec is equivalent
    1459             :  * to dbsqlsend() followed by dbsqlok(). 
    1460             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1461             :  * \retval SUCCEED query was processed without errors.
    1462             :  * \retval FAIL was returned by dbsqlsend() or dbsqlok().
    1463             :  * \sa dbcmd(), dbfcmd(), dbnextrow(), dbresults(), dbretstatus(), dbsettime(), dbsqlok(), dbsqlsend()
    1464             :  */
    1465             : RETCODE
    1466       20434 : dbsqlexec(DBPROCESS * dbproc)
    1467             : {
    1468       20434 :         RETCODE rc = FAIL;
    1469             : 
    1470       20434 :         tdsdump_log(TDS_DBG_FUNC, "dbsqlexec(%p)\n", dbproc);
    1471       20434 :         CHECK_CONN(FAIL);
    1472             : 
    1473       20434 :         if (SUCCEED == (rc = dbsqlsend(dbproc))) {
    1474       20354 :                 rc = dbsqlok(dbproc);
    1475             :         }
    1476             :         return rc;
    1477             : }
    1478             : 
    1479             : /**
    1480             :  * \ingroup dblib_core
    1481             :  * \brief Change current database. 
    1482             :  * 
    1483             :  * Analagous to the unix command \c cd, dbuse() makes \a name the default database.  Waits for an answer
    1484             :  * from the server.  
    1485             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1486             :  * \param name database to use.
    1487             :  * \retval SUCCEED query was processed without errors.
    1488             :  * \retval FAIL query was not processed
    1489             :  * \sa dbchange(), dbname().
    1490             :  */
    1491             : RETCODE
    1492         804 : dbuse(DBPROCESS * dbproc, const char *name)
    1493             : {
    1494             :         RETCODE rc;
    1495             :         char *query;
    1496             : 
    1497         804 :         tdsdump_log(TDS_DBG_FUNC, "dbuse(%p, %s)\n", dbproc, name);
    1498         804 :         CHECK_CONN(FAIL);
    1499         804 :         CHECK_NULP(name, "dbuse", 2, FAIL);
    1500             : 
    1501             :         /* quote name */
    1502         804 :         query = tds_new(char, tds_quote_id(dbproc->tds_socket, NULL, name, -1) + 6);
    1503         804 :         if (!query) {
    1504           0 :                 dbperror(dbproc, SYBEMEM, errno);
    1505           0 :                 return FAIL;
    1506             :         }
    1507         804 :         strcpy(query, "use ");
    1508             :         /* TODO PHP suggest to quote by yourself with []... what should I do ?? quote or not ?? */
    1509         804 :         if (name[0] == '[' && name[strlen(name)-1] == ']')
    1510           0 :                 strcat(query, name);
    1511             :         else
    1512         804 :                 tds_quote_id(dbproc->tds_socket, query + 4, name, -1);
    1513             : 
    1514         804 :         rc = SUCCEED;
    1515         804 :         if ((dbcmd(dbproc, query) == FAIL)
    1516         804 :             || (dbsqlexec(dbproc) == FAIL)
    1517         804 :             || (dbresults(dbproc) == FAIL)
    1518         804 :             || (dbcanquery(dbproc) == FAIL))
    1519             :                 rc = FAIL;
    1520         804 :         free(query);
    1521         804 :         return rc;
    1522             : }
    1523             : 
    1524             : /**
    1525             :  * \ingroup dblib_core
    1526             :  * \brief Close a connection to the server and free associated resources.  
    1527             :  * 
    1528             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1529             :  * \sa dbexit(), dbopen().
    1530             :  */
    1531             : void
    1532         834 : dbclose(DBPROCESS * dbproc)
    1533             : {
    1534             :         TDSSOCKET *tds;
    1535             :         int i;
    1536             :         char timestr[256];
    1537             : 
    1538         834 :         tdsdump_log(TDS_DBG_FUNC, "dbclose(%p)\n", dbproc);   
    1539         834 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    1540             : 
    1541         834 :         tds = dbproc->tds_socket;
    1542         834 :         if (tds) {
    1543             :                 /* 
    1544             :                  * this MUST be done before socket destruction
    1545             :                  * it is possible that a TDSSOCKET is allocated on same position
    1546             :                  */
    1547         456 :                 tds_mutex_lock(&dblib_mutex);
    1548         456 :                 dblib_del_connection(&g_dblib_ctx, dbproc->tds_socket);
    1549         456 :                 tds_mutex_unlock(&dblib_mutex);
    1550             : 
    1551         456 :                 tds_close_socket(tds);
    1552         456 :                 tds_free_socket(tds);
    1553             : 
    1554         456 :                 tds_mutex_lock(&dblib_mutex);
    1555         456 :                 dblib_release_tds_ctx(1);
    1556         456 :                 tds_mutex_unlock(&dblib_mutex);
    1557             :         }
    1558         834 :         buffer_free(&(dbproc->row_buf));
    1559             : 
    1560         834 :         if (dbproc->ftos != NULL) {
    1561           0 :                 fprintf(dbproc->ftos, "/* dbclose() at %s */\n", _dbprdate(timestr));
    1562           0 :                 fclose(dbproc->ftos);
    1563             :         }
    1564             : 
    1565         834 :         tds_free_bcpinfo(dbproc->bcpinfo);
    1566         834 :         if (dbproc->hostfileinfo) {
    1567           0 :                 free(dbproc->hostfileinfo->hostfile);
    1568           0 :                 free(dbproc->hostfileinfo->errorfile);
    1569           0 :                 if (dbproc->hostfileinfo->host_columns) {
    1570           0 :                         for (i = 0; i < dbproc->hostfileinfo->host_colcount; i++) {
    1571           0 :                                 free(dbproc->hostfileinfo->host_columns[i]->terminator);
    1572           0 :                                 free(dbproc->hostfileinfo->host_columns[i]);
    1573             :                         }
    1574           0 :                         free(dbproc->hostfileinfo->host_columns);
    1575             :                 }
    1576             :         }
    1577             : 
    1578       30024 :         for (i = 0; i < DBNUMOPTIONS; i++) {
    1579       30024 :                 dbstring_free(&(dbproc->dbopts[i].param));
    1580             :         }
    1581         834 :         free(dbproc->dbopts);
    1582             : 
    1583         834 :         dbstring_free(&(dbproc->dboptcmd));
    1584             : 
    1585       27522 :         for (i=0; i < MAXBINDTYPES; i++) {
    1586       26688 :                 if (dbproc->nullreps[i].bindval != default_null_representations[i].bindval)
    1587         250 :                         free((BYTE*)dbproc->nullreps[i].bindval);
    1588             :         }
    1589             : 
    1590         834 :         dbfreebuf(dbproc);
    1591         834 :         free(dbproc);
    1592             : }
    1593             : 
    1594             : /**
    1595             :  * \ingroup dblib_core
    1596             :  * \brief Close server connections and free all related structures.  
    1597             :  * 
    1598             :  * \sa dbclose(), dbinit(), dbopen().
    1599             :  * \todo breaks if ctlib/dblib used in same process.
    1600             :  */
    1601             : void
    1602         472 : dbexit(void)
    1603             : {
    1604             :         TDSSOCKET *tds;
    1605             :         DBPROCESS *dbproc;
    1606         472 :         int i, list_size, count = 1;
    1607             : 
    1608         472 :         tdsdump_log(TDS_DBG_FUNC, "dbexit(void)\n");
    1609             : 
    1610         472 :         tds_mutex_lock(&dblib_mutex);
    1611             : 
    1612         472 :         if (--g_dblib_ctx.ref_count != 0) {
    1613           0 :                 tds_mutex_unlock(&dblib_mutex);
    1614           0 :                 return;
    1615             :         }
    1616             : 
    1617         472 :         list_size = g_dblib_ctx.connection_list_size;
    1618             : 
    1619     1933784 :         for (i = 0; i < list_size; i++) {
    1620     1933312 :                 tds = g_dblib_ctx.connection_list[i];
    1621     1933312 :                 g_dblib_ctx.connection_list[i] = NULL;
    1622     1933312 :                 if (tds) {
    1623         378 :                         ++count;
    1624         378 :                         dbproc = (DBPROCESS *) tds_get_parent(tds);
    1625         378 :                         tds_close_socket(tds);
    1626         378 :                         tds_free_socket(tds);
    1627         378 :                         if (dbproc) {
    1628             :                                 /* avoid locking in dbclose */
    1629         378 :                                 dbproc->tds_socket = NULL;
    1630         378 :                                 dbclose(dbproc);
    1631             :                         }
    1632             :                 }
    1633             :         }
    1634         472 :         if (g_dblib_ctx.connection_list) {
    1635         472 :                 TDS_ZERO_FREE(g_dblib_ctx.connection_list);
    1636         472 :                 g_dblib_ctx.connection_list_size = 0;
    1637         472 :                 g_dblib_ctx.connection_list_size_represented = 0;
    1638             :         }
    1639             : 
    1640         472 :         dblib_release_tds_ctx(count);
    1641             : 
    1642         472 :         tds_mutex_unlock(&dblib_mutex);
    1643             : }
    1644             : 
    1645             : static const char *
    1646             : prdbresults_state(int retcode)
    1647             : {
    1648           0 :         switch(retcode) {
    1649             :         case _DB_RES_INIT:              return "_DB_RES_INIT";
    1650           0 :         case _DB_RES_RESULTSET_EMPTY:   return "_DB_RES_RESULTSET_EMPTY";
    1651           0 :         case _DB_RES_RESULTSET_ROWS:    return "_DB_RES_RESULTSET_ROWS";
    1652           0 :         case _DB_RES_NEXT_RESULT:       return "_DB_RES_NEXT_RESULT";
    1653           0 :         case _DB_RES_NO_MORE_RESULTS:   return "_DB_RES_NO_MORE_RESULTS";
    1654           0 :         case _DB_RES_SUCCEED:           return "_DB_RES_SUCCEED";
    1655             :         default: break;
    1656             :         }
    1657             :         return "??";
    1658             : }
    1659             : 
    1660             : static const char *
    1661             : prdbretcode(RETCODE retcode)
    1662             : {
    1663           0 :         switch(retcode) {
    1664             :         case REG_ROW:           return "REG_ROW/MORE_ROWS";
    1665           0 :         case NO_MORE_ROWS:      return "NO_MORE_ROWS";
    1666           0 :         case BUF_FULL:          return "BUF_FULL";
    1667           0 :         case NO_MORE_RESULTS:   return "NO_MORE_RESULTS";
    1668           0 :         case SUCCEED:           return "SUCCEED";
    1669           0 :         case FAIL:              return "FAIL";
    1670             :         default: break;
    1671             :         }
    1672             :         return "??";
    1673             : }
    1674             : 
    1675             : static const char *
    1676             : prretcode(int retcode)
    1677             : {
    1678           0 :         switch(retcode) {
    1679             :         case TDS_SUCCESS:               return "TDS_SUCCESS";
    1680           0 :         case TDS_FAIL:                  return "TDS_FAIL";
    1681           0 :         case TDS_NO_MORE_RESULTS:       return "TDS_NO_MORE_RESULTS";
    1682           0 :         case TDS_CANCELLED:             return "TDS_CANCELLED";
    1683             :         default: break;
    1684             :         }
    1685             :         return "??";
    1686             : }
    1687             : 
    1688             : static const char *
    1689           0 : prresult_type(int result_type)
    1690             : {
    1691           0 :         switch(result_type) {
    1692             :         case TDS_ROW_RESULT:            return "TDS_ROW_RESULT";
    1693           0 :         case TDS_PARAM_RESULT:          return "TDS_PARAM_RESULT";
    1694           0 :         case TDS_STATUS_RESULT:         return "TDS_STATUS_RESULT";
    1695           0 :         case TDS_MSG_RESULT:            return "TDS_MSG_RESULT";
    1696           0 :         case TDS_COMPUTE_RESULT:        return "TDS_COMPUTE_RESULT";
    1697           0 :         case TDS_CMD_DONE:              return "TDS_CMD_DONE";
    1698           0 :         case TDS_CMD_SUCCEED:           return "TDS_CMD_SUCCEED";
    1699           0 :         case TDS_CMD_FAIL:              return "TDS_CMD_FAIL";
    1700           0 :         case TDS_ROWFMT_RESULT:         return "TDS_ROWFMT_RESULT";
    1701           0 :         case TDS_COMPUTEFMT_RESULT:     return "TDS_COMPUTEFMT_RESULT";
    1702           0 :         case TDS_DESCRIBE_RESULT:       return "TDS_DESCRIBE_RESULT";
    1703           0 :         case TDS_DONE_RESULT:           return "TDS_DONE_RESULT";
    1704           0 :         case TDS_DONEPROC_RESULT:       return "TDS_DONEPROC_RESULT";
    1705           0 :         case TDS_DONEINPROC_RESULT:     return "TDS_DONEINPROC_RESULT";
    1706           0 :         case TDS_OTHERS_RESULT:         return "TDS_OTHERS_RESULT";
    1707             :         default: break;
    1708             :         }
    1709           0 :         return "??";
    1710             : }
    1711             : 
    1712             : /**
    1713             :  * \ingroup dblib_core
    1714             :  * \brief Set up query results.  
    1715             :  *
    1716             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1717             :  * \retval SUCCEED Some results are available.
    1718             :  * \retval FAIL query was not processed successfully by the server
    1719             :  * \retval NO_MORE_RESULTS query produced no results. 
    1720             :  *
    1721             :  * \remarks Call dbresults() after calling dbsqlexec() or dbsqlok(), or dbrpcsend() returns SUCCEED.  Unless
    1722             :  *      one of them fails, dbresults will return either SUCCEED or NO_MORE_RESULTS.  
    1723             :  *
    1724             :  *      The meaning of \em results is very specific and not very intuitive.  Results are created by either
    1725             :  *      - a SELECT statement
    1726             :  *      - a stored procedure
    1727             :  *
    1728             :  *      When dbresults returns SUCCEED, therefore, it indicates the server processed the query successfully and 
    1729             :  *      that one or more of these is present:
    1730             :  *      - metadata -- dbnumcols() returns 1 or more
    1731             :  *      - data -- dbnextrow() returns SUCCEED
    1732             :  *      - return status -- dbhasretstat() returns TRUE
    1733             :  *      - output parameters -- dbnumrets() returns 1 or more
    1734             :  *
    1735             :  *      If none of the above are present, dbresults() returns NO_MORE_RESULTS.  
    1736             :  *      
    1737             :  *      SUCCEED does not imply that DBROWS() will return TRUE or even that dbnumcols() will return nonzero.  
    1738             :  *      A general algorithm for reading results will call dbresults() until it return NO_MORE_RESULTS (or FAIL).  
    1739             :  *      An application should check for all the above kinds of results within the dbresults() loop.  
    1740             :  * 
    1741             :  * \sa dbsqlexec(), dbsqlok(), dbrpcsend(), dbcancel(), DBROWS(), dbnextrow(), dbnumcols(), dbhasretstat(), dbretstatus(), dbnumrets()
    1742             :  */
    1743             : RETCODE
    1744       29835 : dbresults(DBPROCESS * dbproc)
    1745             : {
    1746       29835 :         RETCODE erc = _dbresults(dbproc);
    1747             : 
    1748       29835 :         tdsdump_log(TDS_DBG_FUNC, "dbresults returning %d (%s)\n", erc, prdbretcode(erc));
    1749       29835 :         return erc;
    1750             : }
    1751             : 
    1752             : static RETCODE
    1753       29835 : _dbresults(DBPROCESS * dbproc)
    1754             : {
    1755             :         TDSSOCKET *tds;
    1756       29835 :         int result_type = 0, done_flags;
    1757             : 
    1758       29835 :         tdsdump_log(TDS_DBG_FUNC, "dbresults(%p)\n", dbproc);
    1759       29835 :         CHECK_CONN(FAIL);
    1760             : 
    1761       29835 :         tds = dbproc->tds_socket;
    1762             : 
    1763       29835 :         tdsdump_log(TDS_DBG_FUNC, "dbresults: dbresults_state is %d (%s)\n", 
    1764             :                                         dbproc->dbresults_state, prdbresults_state(dbproc->dbresults_state));
    1765       29835 :         switch ( dbproc->dbresults_state ) {
    1766        8170 :         case _DB_RES_SUCCEED:
    1767        8170 :                 dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    1768        8170 :                 return SUCCEED;
    1769             :                 break;
    1770           0 :         case _DB_RES_RESULTSET_ROWS:
    1771           0 :                 dbperror(dbproc, SYBERPND, 0); /* dbresults called while rows outstanding.... */
    1772           0 :                 return FAIL;
    1773             :                 break;
    1774             :         case _DB_RES_NO_MORE_RESULTS:
    1775             :                 return NO_MORE_RESULTS;
    1776             :                 break;
    1777             :         default:
    1778             :                 break;
    1779             :         }
    1780             : 
    1781             :         for (;;) {
    1782       31271 :                 TDSRET retcode = tds_process_tokens(tds, &result_type, &done_flags, TDS_TOKEN_RESULTS);
    1783             : 
    1784       31271 :                 tdsdump_log(TDS_DBG_FUNC, "dbresults() tds_process_tokens returned %d (%s),\n\t\t\tresult_type %d (%s)\n",
    1785             :                                                 retcode, prretcode(retcode), result_type, prresult_type(result_type));
    1786             : 
    1787       31271 :                 switch (retcode) {
    1788             : 
    1789       22863 :                 case TDS_SUCCESS:
    1790             : 
    1791       22863 :                         switch (result_type) {
    1792             :         
    1793         298 :                         case TDS_ROWFMT_RESULT:
    1794         298 :                                 buffer_free(&dbproc->row_buf);
    1795         298 :                                 buffer_alloc(dbproc);
    1796         298 :                                 dbproc->dbresults_state = _DB_RES_RESULTSET_EMPTY;
    1797         298 :                                 break;
    1798             :         
    1799             :                         case TDS_COMPUTEFMT_RESULT:
    1800             :                                 break;
    1801             :         
    1802       12080 :                         case TDS_ROW_RESULT:
    1803             :                         case TDS_COMPUTE_RESULT:
    1804             :         
    1805       12080 :                                 dbproc->dbresults_state = _DB_RES_RESULTSET_ROWS;
    1806       12080 :                                 return SUCCEED;
    1807             :                                 break;
    1808             :         
    1809        1177 :                         case TDS_DONE_RESULT:
    1810             :                         case TDS_DONEPROC_RESULT:
    1811        1177 :                                 tdsdump_log(TDS_DBG_FUNC, "dbresults(): dbresults_state is %d (%s)\n", 
    1812             :                                                 dbproc->dbresults_state, prdbresults_state(dbproc->dbresults_state));
    1813             : 
    1814             :                                 /* A done token signifies the end of a logical command.
    1815             :                                  * There are three possibilities:
    1816             :                                  * 1. Simple command with no result set, i.e. update, delete, insert
    1817             :                                  * 2. Command with result set but no rows
    1818             :                                  * 3. Command with result set and rows
    1819             :                                  */
    1820        1177 :                                 switch (dbproc->dbresults_state) {
    1821             : 
    1822         807 :                                 case _DB_RES_INIT:
    1823             :                                 case _DB_RES_NEXT_RESULT:
    1824         807 :                                         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    1825         807 :                                         if (done_flags & TDS_DONE_ERROR)
    1826             :                                                 return FAIL;
    1827         791 :                                         if (result_type == TDS_DONE_RESULT) {
    1828         685 :                                                 tds_free_all_results(tds);
    1829         685 :                                                 return SUCCEED;
    1830             :                                         }
    1831             :                                         break;
    1832             : 
    1833         370 :                                 case _DB_RES_RESULTSET_EMPTY:
    1834             :                                 case _DB_RES_RESULTSET_ROWS:
    1835         370 :                                         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    1836         370 :                                         return SUCCEED;
    1837             :                                         break;
    1838             :                                 default:
    1839           0 :                                         assert(0);
    1840             :                                         break;
    1841             :                                 }
    1842             :                                 break;
    1843             : 
    1844        9253 :                         case TDS_DONEINPROC_RESULT:
    1845             :                                 /* 
    1846             :                                  * Return SUCCEED on a command within a stored procedure
    1847             :                                  * only if the command returned a result set. 
    1848             :                                  */
    1849        9253 :                                 switch (dbproc->dbresults_state) {
    1850        9241 :                                 case _DB_RES_INIT:  
    1851             :                                 case _DB_RES_NEXT_RESULT: 
    1852        9241 :                                         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    1853        9241 :                                         break;
    1854          12 :                                 case _DB_RES_RESULTSET_EMPTY :
    1855             :                                 case _DB_RES_RESULTSET_ROWS : 
    1856          12 :                                         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    1857          12 :                                         return SUCCEED;
    1858             :                                         break;
    1859             :                                 case _DB_RES_NO_MORE_RESULTS:
    1860             :                                 case _DB_RES_SUCCEED:
    1861             :                                         break;
    1862             :                                 }
    1863             :                                 break;
    1864             : 
    1865             :                         case TDS_STATUS_RESULT:
    1866             :                         case TDS_MSG_RESULT:
    1867             :                         case TDS_DESCRIBE_RESULT:
    1868             :                         case TDS_PARAM_RESULT:
    1869             :                         default:
    1870             :                                 break;
    1871             :                         }
    1872             : 
    1873             :                         break;
    1874             : 
    1875        8408 :                 case TDS_NO_MORE_RESULTS:
    1876        8408 :                         dbproc->dbresults_state = _DB_RES_NO_MORE_RESULTS;
    1877        8408 :                         return NO_MORE_RESULTS;
    1878             :                         break;
    1879             : 
    1880           0 :                 default:
    1881           0 :                         assert(TDS_FAILED(retcode));
    1882           0 :                         dbproc->dbresults_state = _DB_RES_INIT;
    1883           0 :                         return FAIL;
    1884             :                         break;
    1885             :                 }
    1886             :         }
    1887             : }
    1888             : 
    1889             : 
    1890             : /**
    1891             :  * \ingroup dblib_core
    1892             :  * \brief Return number of regular columns in a result set.  
    1893             :  * 
    1894             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1895             :  * \sa dbcollen(), dbcolname(), dbnumalts().
    1896             :  */
    1897             : int
    1898        4014 : dbnumcols(DBPROCESS * dbproc)
    1899             : {
    1900        4014 :         tdsdump_log(TDS_DBG_FUNC, "dbnumcols(%p)\n", dbproc);
    1901        4014 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    1902             : 
    1903        4014 :         if (dbproc && dbproc->tds_socket && dbproc->tds_socket->res_info)
    1904        3754 :                 return dbproc->tds_socket->res_info->num_cols;
    1905             :         return 0;
    1906             : }
    1907             : 
    1908             : /**
    1909             :  * \ingroup dblib_core
    1910             :  * \brief Return name of a regular result column.
    1911             :  * 
    1912             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1913             :  * \param column Nth in the result set, starting with 1.  
    1914             :  * \return pointer to ASCII null-terminated string, the name of the column. 
    1915             :  * \retval NULL \a column is not in range.
    1916             :  * \sa dbcollen(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols().
    1917             :  * \bug Relies on ASCII column names, post iconv conversion.  
    1918             :  *      Will not work as described for UTF-8 or UCS-2 clients.  
    1919             :  *      But maybe it shouldn't.  
    1920             :  */
    1921             : char *
    1922        2858 : dbcolname(DBPROCESS * dbproc, int column)
    1923             : {
    1924             :         TDSCOLUMN *colinfo;
    1925             :         
    1926        2858 :         tdsdump_log(TDS_DBG_FUNC, "dbcolname(%p, %d)\n", dbproc, column);
    1927             : 
    1928        2858 :         colinfo = dbcolptr(dbproc, column);
    1929        2858 :         if (!colinfo)
    1930             :                 return NULL;
    1931             :                 
    1932        5716 :         return tds_dstr_buf(&colinfo->column_name);
    1933             : }
    1934             : 
    1935             : /**
    1936             :  * \ingroup dblib_core
    1937             :  * \brief Return name of a computed result column.
    1938             :  *
    1939             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1940             :  * \param computeid identifies which one of potientially many compute rows is meant. The first compute
    1941             :  * clause has \a computeid == 1.
    1942             :  * \param column Nth in the result set, starting with 1.
    1943             :  * \return pointer to ASCII null-terminated string, the name of the column.
    1944             :  * \retval NULL \a column is not in range.
    1945             :  * \sa dbcollen(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols().
    1946             :  */
    1947             : const char *
    1948           0 : dbacolname(DBPROCESS * dbproc, int computeid, int column)
    1949             : {
    1950             :         TDSCOLUMN *colinfo;
    1951             : 
    1952           0 :         tdsdump_log(TDS_DBG_FUNC, "dbacolname(%p, %d, %d)\n", dbproc, computeid, column);
    1953             : 
    1954           0 :         colinfo = dbacolptr(dbproc, computeid, column, true);
    1955           0 :         if (!colinfo)
    1956             :                 return NULL;
    1957             : 
    1958           0 :         return tds_dstr_cstr(&colinfo->column_name);
    1959             : }
    1960             : 
    1961             : /**
    1962             :  * \ingroup dblib_core
    1963             :  * \brief Read a row from the row buffer.
    1964             :  * 
    1965             :  * When row buffering is enabled (DBBUFFER option is on), the client can use dbgetrow() to re-read a row previously fetched 
    1966             :  * with dbnextrow().  The effect is to move the row pointer -- analogous to fseek() -- back to \a row.  
    1967             :  * Calls to dbnextrow() read from \a row + 1 until the buffer is exhausted, at which point it resumes
    1968             :  * its normal behavior, except that as each row is fetched from the server, it is added to the row
    1969             :  * buffer (in addition to being returned to the client).  When the buffer is filled, dbnextrow()  returns 
    1970             :  * \c FAIL until the buffer is at least partially emptied with dbclrbuf().
    1971             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    1972             :  * \param row Nth row to read, starting with 1.
    1973             :  * \retval REG_ROW returned row is a regular row.
    1974             :  * \returns computeid when returned row is a compute row.
    1975             :  * \retval NO_MORE_ROWS no such row in the row buffer.  Current row is unchanged.
    1976             :  * \retval FAIL unsuccessful; row buffer may be full.  
    1977             :  * \sa dbaltbind(), dbbind(), dbclrbuf(), DBCURROW(), DBFIRSTROW(), DBLASTROW(), dbnextrow(), dbsetrow().
    1978             :  */
    1979             : RETCODE
    1980          60 : dbgetrow(DBPROCESS * dbproc, DBINT row)
    1981             : {
    1982          60 :         RETCODE result = FAIL;
    1983          60 :         const int idx = buffer_row2idx(&dbproc->row_buf, row);
    1984             : 
    1985          60 :         tdsdump_log(TDS_DBG_FUNC, "dbgetrow(%p, %d)\n", dbproc, row);
    1986          60 :         CHECK_CONN(FAIL);
    1987             : 
    1988          60 :         if (-1 == idx)
    1989             :                 return NO_MORE_ROWS;
    1990             : 
    1991          40 :         dbproc->row_buf.current = idx;
    1992          40 :         buffer_transfer_bound_data(&dbproc->row_buf, TDS_ROW_RESULT, 0, dbproc, idx);
    1993          40 :         result = REG_ROW;
    1994             : 
    1995          40 :         return result;
    1996             : }
    1997             : 
    1998             : /**
    1999             :  * \ingroup dblib_core
    2000             :  * \brief Define substitution values to be used when binding null values.
    2001             :  * 
    2002             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2003             :  * \param bindtype      type of binding to which the substitute value will apply. 
    2004             :  * \param bindlen       size of the substitute value you are supplying, in bytes. 
    2005             :  *                      Ignored except for CHARBIND and BINARYBIND. 
    2006             :  * \param bindval       pointer to a buffer containing the substitute value.
    2007             :  * \retval SUCCEED query was processed without errors.
    2008             :  * \retval FAIL query was not processed
    2009             :  * \sa dbaltbind(), dbbind(), dbconvert(), dbnullbind().
    2010             :  */
    2011             : RETCODE
    2012         400 : dbsetnull(DBPROCESS * dbproc, int bindtype, int bindlen, BYTE *bindval)
    2013             : {
    2014             :         BYTE *pval;
    2015             :         
    2016         400 :         tdsdump_log(TDS_DBG_FUNC, "dbsetnull(%p, %d, %d, %p)\n", dbproc, bindtype, bindlen, bindval);
    2017             :         
    2018         400 :         CHECK_CONN(FAIL);
    2019         400 :         CHECK_PARAMETER(bindval, SYBENBVP, FAIL);
    2020             :         
    2021         400 :         switch (bindtype) {
    2022         330 :         case DATETIMEBIND:
    2023             :         case DECIMALBIND:
    2024             :         case SRCDECIMALBIND:
    2025             :         case FLT8BIND:
    2026             :         case INTBIND:
    2027             :         case MONEYBIND:
    2028             :         case NUMERICBIND:
    2029             :         case SRCNUMERICBIND:
    2030             :         case REALBIND:
    2031             :         case SMALLBIND:
    2032             :         case SMALLDATETIMEBIND:
    2033             :         case SMALLMONEYBIND:
    2034             :         case TINYBIND:
    2035             :         case BIGINTBIND:
    2036             :         case DATEBIND:
    2037             :         case TIMEBIND:
    2038             :         case BIGDATETIMEBIND:
    2039             :         case BIGTIMEBIND:
    2040         330 :                 bindlen = (int)default_null_representations[bindtype].len;
    2041         330 :                 break;
    2042             : 
    2043          70 :         case CHARBIND:
    2044             :         case BINARYBIND:
    2045          70 :                 CHECK_PARAMETER(bindlen >= 0, SYBEBBL, FAIL);
    2046             :                 break;
    2047             :                 
    2048           0 :         case NTBSTRINGBIND:     bindlen = (int)strlen((char *) bindval);
    2049           0 :                 break;
    2050           0 :         case STRINGBIND:        bindlen = (int)strlen((char *) bindval);
    2051           0 :                 break;
    2052           0 :         case VARYBINBIND:       bindlen = ((DBVARYBIN*) bindval)->len;
    2053           0 :                 break;
    2054           0 :         case VARYCHARBIND:      bindlen = ((DBVARYCHAR*) bindval)->len;
    2055           0 :                 break;
    2056             : 
    2057             : #if 0
    2058             :         case SENSITIVITYBIND:
    2059             :         case BOUNDARYBIND:
    2060             : #endif
    2061           0 :         default:
    2062           0 :                 dbperror(dbproc, SYBEBTYP, 0);
    2063           0 :                 return FAIL;
    2064             :         }
    2065             : 
    2066         400 :         if ((pval = tds_new(BYTE, bindlen)) == NULL) {
    2067           0 :                 dbperror(dbproc, SYBEMEM, errno);
    2068           0 :                 return FAIL;
    2069             :         }
    2070             :         
    2071             :         /* free any prior allocation */
    2072         400 :         if (dbproc->nullreps[bindtype].bindval != default_null_representations[bindtype].bindval)
    2073         380 :                 free((BYTE*)dbproc->nullreps[bindtype].bindval);
    2074             : 
    2075         400 :         memcpy(pval, bindval, bindlen);
    2076             :         
    2077         400 :         dbproc->nullreps[bindtype].bindval = pval;
    2078         400 :         dbproc->nullreps[bindtype].len = bindlen;
    2079             : 
    2080         400 :         tdsdump_dump_buf(TDS_DBG_NETWORK, "null representation set ", pval,  bindlen);
    2081             :         return SUCCEED;
    2082             : }
    2083             : 
    2084             : /**
    2085             :  * \ingroup dblib_core
    2086             :  * \brief Make a buffered row "current" without fetching it into bound variables.  
    2087             :  * 
    2088             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2089             :  * \retval MORE_ROWS row found
    2090             :  * \retval NO_MORE_ROWS row not found
    2091             :  * \retval FAIL \a dbproc is dead or not enabled
    2092             :  * \sa dbaltbind(), dbbind(), dbcanquery(), dbclrbuf(), dbgetrow(), dbnextrow(), dbprrow().
    2093             :  */
    2094             : STATUS
    2095           0 : dbsetrow(DBPROCESS * dbproc, DBINT row)
    2096             : {
    2097           0 :         const int idx = buffer_row2idx(&dbproc->row_buf, row);
    2098             : 
    2099           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsetrow(%p, %d)\n", dbproc, row);
    2100           0 :         CHECK_CONN(FAIL);
    2101             : 
    2102           0 :         if (-1 == idx)
    2103             :                 return NO_MORE_ROWS;
    2104             :                 
    2105           0 :         dbproc->row_buf.current = idx;
    2106             :                 
    2107             :         /* FIXME: should determine REG_ROW or compute_id; */
    2108           0 :         return REG_ROW; 
    2109             : }
    2110             : 
    2111             : /**
    2112             :  * \ingroup dblib_core
    2113             :  * \brief Read result row into the row buffer and into any bound host variables.
    2114             :  * 
    2115             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2116             :  * \retval REG_ROW regular row has been read.
    2117             :  * \returns computeid when a compute row is read. 
    2118             :  * \retval BUF_FULL reading next row would cause the buffer to be exceeded (and buffering is turned on).
    2119             :  * No row was read from the server
    2120             :  * \sa dbaltbind(), dbbind(), dbcanquery(), dbclrbuf(), dbgetrow(), dbprrow(), dbsetrow().
    2121             :  */
    2122             : struct pivot_t;
    2123             : STATUS
    2124      220548 : dbnextrow(DBPROCESS * dbproc)
    2125             : {
    2126             :         TDSRESULTINFO *resinfo;
    2127             :         TDSSOCKET *tds;
    2128      220548 :         STATUS result = FAIL;
    2129             :         TDS_INT res_type;
    2130             :         TDS_INT computeid;
    2131             :         int idx; /* row buffer index.  Unless DBUFFER is on, idx will always be 0. */
    2132             :         struct pivot_t *pivot;
    2133             : 
    2134      220548 :         tdsdump_log(TDS_DBG_FUNC, "dbnextrow(%p)\n", dbproc);
    2135      220548 :         CHECK_CONN(FAIL);
    2136             : 
    2137      220548 :         tds = dbproc->tds_socket;
    2138      220548 :         resinfo = tds->res_info;
    2139             : 
    2140      220548 :         tdsdump_log(TDS_DBG_FUNC, "dbnextrow() dbresults_state = %d (%s)\n", 
    2141             :                                         dbproc->dbresults_state, prdbresults_state(dbproc->dbresults_state));
    2142             : 
    2143      220548 :         if (!resinfo || dbproc->dbresults_state != _DB_RES_RESULTSET_ROWS) {
    2144             :                 /* no result set or result set empty (no rows) */
    2145         820 :                 tdsdump_log(TDS_DBG_FUNC, "leaving dbnextrow() returning %d (NO_MORE_ROWS)\n", NO_MORE_ROWS);
    2146         820 :                 return dbproc->row_type = NO_MORE_ROWS;
    2147             :         }
    2148             : 
    2149             :         /*
    2150             :          * Try to get the dbproc->row_buf.current item from the buffered rows, if any.  
    2151             :          * Else read from the stream, unless the buffer is exhausted.  
    2152             :          * If no rows are read, DBROWTYPE() will report NO_MORE_ROWS. 
    2153             :          */
    2154      219728 :         dbproc->row_type = NO_MORE_ROWS; 
    2155      219728 :         computeid = REG_ROW;
    2156      219728 :         if (-1 != (idx = buffer_current_index(dbproc))) {                       
    2157             :                 /*
    2158             :                  * Cool, the item we want is already there
    2159             :                  */
    2160          10 :                 result = dbproc->row_type = REG_ROW;
    2161          10 :                 res_type = TDS_ROW_RESULT;
    2162             :                 
    2163      219718 :         } else if (buffer_is_full(&dbproc->row_buf)) {
    2164             :                 
    2165         120 :                 result = BUF_FULL;
    2166         120 :                 res_type = TDS_ROWFMT_RESULT;
    2167             :         
    2168      219598 :         } else if ((pivot = dbrows_pivoted(dbproc)) != NULL) {
    2169             :         
    2170           0 :                 tdsdump_log(TDS_DBG_FUNC, "returning pivoted row\n");
    2171           0 :                 return dbnextrow_pivoted(dbproc, pivot);
    2172             : 
    2173             :         } else {
    2174      219598 :                 const int mask = TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW|TDS_RETURN_COMPUTE;
    2175      219598 :                 TDS_INT8 row_count = TDS_NO_COUNT;
    2176      219598 :                 bool rows_set = false;
    2177      219598 :                 buffer_save_row(dbproc);
    2178             : 
    2179             :                 /* Get the row from the TDS stream.  */
    2180         718 : again:
    2181      220316 :                 switch (tds_process_tokens(tds, &res_type, NULL, mask)) {
    2182      220286 :                 case TDS_SUCCESS:
    2183      220286 :                         if (res_type == TDS_ROW_RESULT || res_type == TDS_COMPUTE_RESULT) {
    2184      207698 :                                 if (res_type == TDS_COMPUTE_RESULT)
    2185          32 :                                         computeid = tds->current_results->computeid;
    2186             :                                 /* Add the row to the row buffer, whose capacity is always at least 1 */
    2187      207698 :                                 resinfo = tds->current_results;
    2188      207698 :                                 idx = buffer_add_row(dbproc, resinfo);
    2189      207698 :                                 assert(idx != -1);
    2190      207698 :                                 result = dbproc->row_type = (res_type == TDS_ROW_RESULT)? REG_ROW : computeid;
    2191             : #if 0 /* TODO */
    2192             :                                 tds_process_tokens(tds, &res_type, NULL, TDS_TOKEN_TRAILING);
    2193             : #endif
    2194      207698 :                                 break;
    2195             :                         }
    2196             :                         /* allows to process trailing tokens */
    2197       12588 :                         if (res_type == TDS_DONEINPROC_RESULT) {
    2198         718 :                                 if (!rows_set)
    2199         462 :                                         row_count = tds->rows_affected;
    2200             :                                 rows_set = true;
    2201             :                                 goto again;
    2202             :                         }
    2203             :                         /* fall through */
    2204             :                 case TDS_NO_MORE_RESULTS:
    2205       11900 :                         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    2206       11900 :                         result = NO_MORE_ROWS;
    2207       11900 :                         break;
    2208           0 :                 default:
    2209           0 :                         tdsdump_log(TDS_DBG_FUNC, "unexpected: leaving dbnextrow() returning FAIL\n");
    2210             :                         return FAIL;
    2211             :                         break;
    2212             :                 }
    2213      219598 :                 if (rows_set)
    2214         462 :                         tds->rows_affected = row_count;
    2215             :         }
    2216             : 
    2217      219728 :         if (res_type == TDS_ROW_RESULT || res_type == TDS_COMPUTE_RESULT) {
    2218             :                 /*
    2219             :                  * Transfer the data from the row buffer to the bound variables.  
    2220             :                  */
    2221      207708 :                 buffer_transfer_bound_data(&dbproc->row_buf, res_type, computeid, dbproc, idx);
    2222             :         }
    2223             :         
    2224      219728 :         if (res_type == TDS_COMPUTE_RESULT) {
    2225          32 :                 tdsdump_log(TDS_DBG_FUNC, "leaving dbnextrow() returning compute_id %d\n", result);
    2226             :         } else {
    2227      219696 :                 tdsdump_log(TDS_DBG_FUNC, "leaving dbnextrow() returning %d (%s)\n", result, prdbretcode(result));
    2228             :         }
    2229             :         return result;
    2230             : } /* dbnextrow()  */
    2231             : 
    2232             : static TDS_SERVER_TYPE
    2233             : dblib_bound_type(int bindtype)
    2234             : {
    2235             :         switch (bindtype) {
    2236             :         case CHARBIND:
    2237             :         case STRINGBIND:
    2238             :         case NTBSTRINGBIND:
    2239             :                 return SYBCHAR;
    2240             :                 break;
    2241             :         case FLT8BIND:
    2242             :                 return SYBFLT8;
    2243             :                 break;
    2244             :         case REALBIND:
    2245             :                 return SYBREAL;
    2246             :                 break;
    2247             :         case INTBIND:
    2248             :                 return SYBINT4;
    2249             :                 break;
    2250             :         case SMALLBIND:
    2251             :                 return SYBINT2;
    2252             :                 break;
    2253             :         case TINYBIND:
    2254             :                 return SYBINT1;
    2255             :                 break;
    2256             :         case BIGINTBIND:
    2257             :                 return SYBINT8;
    2258             :                 break;
    2259             :         case DATETIMEBIND:
    2260             :                 return SYBDATETIME;
    2261             :                 break;
    2262             :         case SMALLDATETIMEBIND:
    2263             :                 return SYBDATETIME4;
    2264             :                 break;
    2265             :         case DATEBIND:
    2266             :                 return SYBDATE;
    2267             :                 break;
    2268             :         case TIMEBIND:
    2269             :                 return SYBTIME;
    2270             :                 break;
    2271             :         case BIGDATETIMEBIND:
    2272             :                 return SYB5BIGDATETIME;
    2273             :                 break;
    2274             :         case BIGTIMEBIND:
    2275             :                 return SYB5BIGTIME;
    2276             :                 break;
    2277             :         case MONEYBIND:
    2278             :                 return SYBMONEY;
    2279             :                 break;
    2280             :         case SMALLMONEYBIND:
    2281             :                 return SYBMONEY4;
    2282             :                 break;
    2283             :         case BINARYBIND:
    2284             :                 return SYBBINARY;
    2285             :                 break;
    2286             :         case VARYBINBIND:
    2287             :                 return SYBVARBINARY;
    2288             :                 break;
    2289             :         case VARYCHARBIND:
    2290             :                 return SYBVARCHAR;
    2291             :                 break;
    2292             :         case BITBIND:
    2293             :                 return SYBBIT;
    2294             :                 break;
    2295             :         case NUMERICBIND:
    2296             :         case SRCNUMERICBIND:
    2297             :         case DECIMALBIND:
    2298             :         case SRCDECIMALBIND:
    2299             :                 return SYBNUMERIC;
    2300             :                 break;
    2301             :         case DATETIME2BIND:
    2302             :                 return SYBMSDATETIMEOFFSET;
    2303             :                 break;
    2304             :         default:
    2305             :                 return TDS_INVALID_TYPE;
    2306             :         }
    2307             : }
    2308             : 
    2309             : /**
    2310             :  * \ingroup dblib_core
    2311             :  * \brief Convert one datatype to another.
    2312             :  *
    2313             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2314             :  * \param srctype datatype of the data to convert. 
    2315             :  * \param src buffer to convert
    2316             :  * \param srclen length of \a src
    2317             :  * \param desttype target datatype
    2318             :  * \param dest output buffer
    2319             :  * \param destlen size of \a dest
    2320             :  * \returns     On success, the count of output bytes in \a dest, else -1. On failure, it will call any user-supplied error handler. 
    2321             :  * \remarks      Causes of failure: 
    2322             :  *              - No such conversion unavailable. 
    2323             :  *              - Character data output was truncated, or numerical data overflowed or lost precision. 
    2324             :  *              - In converting character data to one of the numeric types, the string could not be interpreted as a number.  
    2325             :  *              
    2326             :  * Conversion functions are handled in the TDS layer.
    2327             :  * 
    2328             :  * The main reason for this is that \c ct-lib and \c ODBC (and presumably \c DBI) need
    2329             :  * to be able to do conversions between datatypes. This is possible because
    2330             :  * the format of complex data (dates, money, numeric, decimal) is defined by
    2331             :  * its representation on the wire; thus what we call \c DBMONEY is exactly its
    2332             :  * format on the wire. CLIs that need a different representation (ODBC?) 
    2333             :  * need to convert from this format anyway, so the code would already be in
    2334             :  * place.
    2335             :  * 
    2336             :  * Each datatype is also defined by its Server-type so all CLIs should be 
    2337             :  * able to map native types to server types as well.
    2338             :  *
    2339             :  * tds_convert() copies from src to dest and returns the output data length,
    2340             :  * period.  All padding and termination is the responsibility of the API library
    2341             :  * and is done post-conversion.  The peculiar rule in dbconvert() is that
    2342             :  * a \a destlen of -1 and a \a desttype of \c SYBCHAR means the output buffer
    2343             :  * should be null-terminated.
    2344             :  *  
    2345             :  * \sa dbaltbind(), dbaltbind_ps(), dbbind(), dbbind_ps(), dbconvert_ps(), dberrhandle(), dbsetnull(), dbsetversion(), dbwillconvert().
    2346             :  * \todo What happens if client does not reset values? 
    2347             :  * \todo Microsoft and Sybase define this function differently.  
    2348             :  */
    2349             : DBINT
    2350        2318 : dbconvert_ps(DBPROCESS * dbproc, int db_srctype, const BYTE * src, DBINT srclen,
    2351             :              int db_desttype, BYTE * dest, DBINT destlen, DBTYPEINFO * typeinfo)
    2352             : {
    2353             :         CONV_RESULT dres;
    2354             :         DBINT ret;
    2355             :         int i;
    2356             :         int len;
    2357             :         TDS_SERVER_TYPE srctype, desttype;
    2358             : 
    2359        2318 :         tdsdump_log(TDS_DBG_FUNC, "dbconvert_ps(%p, %s, %p, %d, %s, %p, %d, %p)\n",
    2360             :                     dbproc, tds_prdatatype(db_srctype), src, srclen,
    2361             :                     tds_prdatatype(db_desttype), dest, destlen, typeinfo);
    2362             :         /* dbproc and src can be NULLs */
    2363        2318 :         CHECK_PARAMETER(dest, SYBEACNV, -1);
    2364             : 
    2365        2318 :         DBPERROR_RETURN(!is_tds_type_valid(db_srctype), SYBEUDTY);
    2366        2318 :         srctype = (TDS_SERVER_TYPE) db_srctype;
    2367        2318 :         DBPERROR_RETURN(!is_tds_type_valid(db_desttype), SYBEUDTY);
    2368        2318 :         desttype = (TDS_SERVER_TYPE) db_desttype;
    2369             : 
    2370        2318 :         if (is_numeric_type(desttype)) {
    2371         480 :                 TDS_NUMERIC *d = &dres.n;
    2372             : 
    2373         480 :                 if (typeinfo == NULL) {
    2374           0 :                         if (is_numeric_type(srctype)) {
    2375           0 :                                 DBNUMERIC *s = (DBNUMERIC *) src;
    2376           0 :                                 d->precision = s->precision;
    2377           0 :                                 d->scale = s->scale;
    2378             :                         } else {
    2379           0 :                                 d->precision = 18;
    2380           0 :                                 d->scale = 0;
    2381             :                         }
    2382             :                 } else {
    2383         480 :                         d->precision = typeinfo->precision;
    2384         480 :                         d->scale = typeinfo->scale;
    2385             :                 }
    2386             :         }
    2387             : 
    2388        2318 :         if (0 == destlen) 
    2389             :                 return 0; 
    2390             : 
    2391        2318 :         if (src == NULL || srclen == 0) {
    2392         122 :                 int bind = dbbindtype(desttype);
    2393         122 :                 int size = tds_get_size_by_type(desttype);
    2394             : 
    2395         122 :                 if (bind == NTBSTRINGBIND) {
    2396          22 :                         if (destlen > 0) {
    2397             :                                 size = destlen;
    2398             :                                 bind = CHARBIND;
    2399             :                         } else { 
    2400          14 :                                 size = 1;
    2401          14 :                                 bind = NTBSTRINGBIND;
    2402             :                         }
    2403         100 :                 } else if (bind == BINARYBIND) {
    2404         100 :                         if (destlen > 0)
    2405             :                                 size = destlen;
    2406             :                         else
    2407          10 :                                 size = 0;
    2408             :                 }
    2409             : 
    2410         122 :                 dbgetnull(dbproc, bind, size, dest);
    2411         122 :                 return size;
    2412             :         }
    2413             : 
    2414             :         /* srclen of -1 means the source data is definitely NULL terminated */
    2415        2196 :         if (srclen == -1)
    2416         480 :                 srclen = (int)strlen((const char *) src);
    2417             : 
    2418             :         /* often times we are asked to convert a data type to itself */
    2419        2196 :         if (srctype == desttype && !is_numeric_type(desttype)) {
    2420         150 :                 ret = -2;  /* to make sure we always set it */
    2421         150 :                 tdsdump_log(TDS_DBG_INFO1, "dbconvert_ps() srctype == desttype\n");
    2422         150 :                 switch (desttype) {
    2423             : 
    2424          10 :                 case SYBBINARY:
    2425             :                 case SYBVARBINARY:
    2426             :                 case SYBIMAGE:
    2427          10 :                         if (srclen > destlen && destlen >= 0) {
    2428           0 :                                 dbperror(dbproc, SYBECOFL, 0);
    2429           0 :                                 ret = -1;
    2430             :                         } else {
    2431          10 :                                 memcpy(dest, src, srclen);
    2432          10 :                                 if (srclen < destlen)
    2433           0 :                                         memset(dest + srclen, 0, destlen - srclen);
    2434             :                                 ret = srclen;
    2435             :                         }
    2436             :                         break;
    2437             : 
    2438         140 :                 case SYBCHAR:
    2439             :                 case SYBVARCHAR:
    2440             :                 case SYBTEXT:
    2441             :                         /* srclen of -1 means the source data is definitely NULL terminated */
    2442         140 :                         if (srclen == -1)
    2443           0 :                                 srclen = (int)strlen((const char *) src);
    2444             : 
    2445         140 :                         switch (destlen) {
    2446             :                         case  0:        /* nothing to copy */
    2447             :                                 ret = 0;
    2448             :                                 break;
    2449             :                         case -1:        /* rtrim and null terminate */
    2450          80 :                                 while (srclen && src[srclen - 1] == ' ') {
    2451          20 :                                         --srclen;
    2452             :                                 }
    2453             :                                 /* fall thru */
    2454             :                         case -2:        /* just null terminate */
    2455          80 :                                 memcpy(dest, src, srclen);
    2456          80 :                                 dest[srclen] = '\0';
    2457          80 :                                 ret = srclen;
    2458          80 :                                 break;
    2459          60 :                         default:
    2460          60 :                                 assert(destlen > 0);
    2461          60 :                                 if (destlen < 0 || srclen > destlen) {
    2462          20 :                                         dbperror(dbproc, SYBECOFL, 0);
    2463          20 :                                         ret = -1;
    2464             :                                 } else {
    2465          40 :                                         memcpy(dest, src, srclen);
    2466          40 :                                         if (srclen < destlen)
    2467          20 :                                                 memset(dest + srclen, ' ', destlen - srclen);
    2468             :                                         ret = srclen;
    2469             :                                 }
    2470             :                                 break;
    2471             :                         }
    2472             :                         break;
    2473           0 :                 case SYBINT1:
    2474             :                 case SYBINT2:
    2475             :                 case SYBINT4:
    2476             :                 case SYBINT8:
    2477             :                 case SYBFLT8:
    2478             :                 case SYBREAL:
    2479             :                 case SYBBIT:
    2480             :                 case SYBBITN:
    2481             :                 case SYBMONEY:
    2482             :                 case SYBMONEY4:
    2483             :                 case SYBDATETIME:
    2484             :                 case SYBDATETIME4:
    2485             :                 case SYBDATE:
    2486             :                 case SYBTIME:
    2487             :                 case SYB5BIGDATETIME:
    2488             :                 case SYB5BIGTIME:
    2489             :                 case SYBUNIQUE:
    2490           0 :                         ret = tds_get_size_by_type(desttype);
    2491           0 :                         memcpy(dest, src, ret);
    2492           0 :                         break;
    2493             : 
    2494           0 :                 case SYBMSDATE:
    2495             :                 case SYBMSTIME:
    2496             :                 case SYBMSDATETIME2:
    2497             :                 case SYBMSDATETIMEOFFSET:
    2498           0 :                         ret = sizeof(TDS_DATETIMEALL);
    2499           0 :                         memcpy(dest, src, ret);
    2500             :                         break;
    2501             : 
    2502             :                 default:
    2503             :                         ret = -1;
    2504             :                         break;
    2505             :                 }
    2506         130 :                 assert(ret > -2);
    2507             :                 return ret;
    2508             :         }
    2509             :         /* end srctype == desttype */
    2510             : 
    2511             :         /*
    2512             :          * Character types need no conversion.  Just move the data.
    2513             :          */
    2514        2046 :         if (is_similar_type(srctype, desttype)) {
    2515         662 :                 if (src && dest && srclen > 0 && destlen >= srclen) {
    2516         662 :                         memcpy(dest, src, srclen);
    2517         662 :                         return srclen;
    2518             :                 }
    2519             :         }
    2520             : 
    2521        1384 :         tdsdump_log(TDS_DBG_INFO1, "dbconvert_ps() calling tds_convert\n");
    2522             : 
    2523        1384 :         len = tds_convert(g_dblib_ctx.tds_ctx, srctype, src, srclen, desttype, &dres);
    2524        1384 :         tdsdump_log(TDS_DBG_INFO1, "dbconvert_ps() called tds_convert returned %d\n", len);
    2525             : 
    2526        1384 :         if (len < 0) {
    2527           0 :                 _dblib_convert_err(dbproc, len);
    2528           0 :                 return -1;
    2529             :         }
    2530             : 
    2531        1384 :         switch (desttype) {
    2532          30 :         case SYBBINARY:
    2533             :         case SYBVARBINARY:
    2534             :         case SYBIMAGE:
    2535          30 :                 if (len > destlen && destlen >= 0) {
    2536           0 :                         dbperror(dbproc, SYBECOFL, 0);
    2537           0 :                         ret = -1;
    2538             :                 } else {
    2539          30 :                         memcpy(dest, dres.ib, len);
    2540          30 :                         if (len < destlen)
    2541          30 :                                 memset(dest + len, 0, destlen - len);
    2542             :                         ret = len;
    2543             :                 }
    2544          30 :                 free(dres.ib);
    2545          30 :                 break;
    2546         480 :         case SYBINT1:
    2547             :         case SYBINT2:
    2548             :         case SYBINT4:
    2549             :         case SYBINT8:
    2550             :         case SYBFLT8:
    2551             :         case SYBREAL:
    2552             :         case SYBBIT:
    2553             :         case SYBBITN:
    2554             :         case SYBMONEY:
    2555             :         case SYBMONEY4:
    2556             :         case SYBDATETIME:
    2557             :         case SYBDATETIME4:
    2558             :         case SYBTIME:
    2559             :         case SYBDATE:
    2560             :         case SYB5BIGDATETIME:
    2561             :         case SYB5BIGTIME:
    2562             :         case SYBUNIQUE:
    2563             :         case SYBMSDATE:
    2564             :         case SYBMSTIME:
    2565             :         case SYBMSDATETIME2:
    2566             :         case SYBMSDATETIMEOFFSET:
    2567             :         case SYBNUMERIC:
    2568             :         case SYBDECIMAL:
    2569         480 :                 memcpy(dest, &(dres.ti), len);
    2570         480 :                 ret = len;
    2571         480 :                 break;
    2572         874 :         case SYBCHAR:
    2573             :         case SYBVARCHAR:
    2574             :         case SYBTEXT:
    2575         874 :                 tdsdump_log(TDS_DBG_INFO1, "dbconvert_ps() outputting %d bytes character data destlen = %d \n", len, destlen);
    2576             : 
    2577         874 :                 if (destlen < -2)
    2578             :                         destlen = 0;    /* failure condition */
    2579             : 
    2580         874 :                 switch (destlen) {
    2581             :                 case 0:
    2582             :                         ret = -1;
    2583             :                         break;
    2584         204 :                 case -1:        /* rtrim and null terminate */
    2585         204 :                         for (i = len - 1; i >= 0 && dres.c[i] == ' '; --i) {
    2586           0 :                                 len = i;
    2587             :                         }
    2588         204 :                         memcpy(dest, dres.c, len);
    2589         204 :                         dest[len] = '\0';
    2590         204 :                         ret = len;
    2591         204 :                         break;
    2592           0 :                 case -2:        /* just null terminate */
    2593           0 :                         memcpy(dest, dres.c, len);
    2594           0 :                         dest[len] = 0;
    2595           0 :                         ret = len;
    2596           0 :                         break;
    2597         670 :                 default:
    2598         670 :                         assert(destlen > 0);
    2599         670 :                         if (destlen < 0 || len > destlen) {
    2600           0 :                                 dbperror(dbproc, SYBECOFL, 0);
    2601           0 :                                 ret = -1;
    2602           0 :                                 tdsdump_log(TDS_DBG_INFO1, "%d bytes type %d -> %d, destlen %d < %d required\n",
    2603             :                                             srclen, srctype, desttype, destlen, len);
    2604             :                                 break;
    2605             :                         }
    2606             :                         /* else pad with blanks */
    2607         670 :                         memcpy(dest, dres.c, len);
    2608         670 :                         if (len < destlen)
    2609         670 :                                 memset(dest + len, ' ', destlen - len);
    2610             :                         ret = len;
    2611             : 
    2612             :                         break;
    2613             :                 }
    2614             : 
    2615         874 :                 free(dres.c);
    2616             : 
    2617         874 :                 break;
    2618           0 :         default:
    2619           0 :                 tdsdump_log(TDS_DBG_INFO1, "error: dbconvert_ps(): unrecognized desttype %d \n", desttype);
    2620             :                 ret = -1;
    2621             :                 break;
    2622             : 
    2623             :         }
    2624             :         return (ret);
    2625             : }
    2626             : 
    2627             : /**
    2628             :  * \ingroup dblib_core
    2629             :  * \brief cf. dbconvert_ps(), above
    2630             :  * 
    2631             :  * \em Sybase: Convert numeric types.
    2632             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2633             :  * \param srctype datatype of the data to convert. 
    2634             :  * \param src buffer to convert
    2635             :  * \param srclen length of \a src
    2636             :  * \param desttype target datatype
    2637             :  * \param dest output buffer
    2638             :  * \param destlen size of \a dest
    2639             :  * \param typeinfo address of a \c DBTYPEINFO structure that governs the precision & scale of the output, may be \c NULL.
    2640             :  * \sa dbaltbind(), dbaltbind_ps(), dbbind(), dbbind_ps(), dbconvert_ps(), dberrhandle(), dbsetnull(), dbsetversion(), dbwillconvert().
    2641             :  */
    2642             : DBINT
    2643        1838 : dbconvert(DBPROCESS * dbproc,
    2644             :           int srctype, const BYTE * src, DBINT srclen, int desttype, BYTE * dest, DBINT destlen)
    2645             : {
    2646        1838 :         DBTYPEINFO ti, *pti = NULL;
    2647             : 
    2648        1838 :         tdsdump_log(TDS_DBG_FUNC, "dbconvert(%p)\n", dbproc);
    2649             :         /* dbproc can be NULL*/
    2650             : 
    2651        1838 :         DBPERROR_RETURN(!is_tds_type_valid(desttype), SYBEUDTY);
    2652             : 
    2653        1838 :         if (is_numeric_type(desttype)) {
    2654             :                 DBNUMERIC *num;
    2655             : 
    2656             :                 /* FIXME what happen if client do not reset values ??? */
    2657           0 :                 if (dbproc->msdblib) {
    2658           0 :                         num = (DBNUMERIC *) dest;
    2659           0 :                         ti.precision = num->precision;
    2660           0 :                         ti.scale = num->scale;
    2661           0 :                         pti = &ti;
    2662             :                 } else {
    2663             :                         /* for Sybase passing NULL as DBTYPEINFO is fine */
    2664             :                 }
    2665             :         }
    2666             : 
    2667        1838 :         return dbconvert_ps(dbproc, srctype, src, srclen, desttype, dest, destlen, pti);
    2668             : }
    2669             : 
    2670             : /**
    2671             :  * \ingroup dblib_core
    2672             :  * \brief Tie a host variable to a resultset column.
    2673             :  * 
    2674             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2675             :  * \param column Nth column, starting at 1.
    2676             :  * \param vartype datatype of the host variable that will receive the data
    2677             :  * \param varlen size of host variable pointed to \a varaddr
    2678             :  * \param varaddr address of host variable
    2679             :  * \retval SUCCEED everything worked.
    2680             :  * \retval FAIL no such \a column or no such conversion possible, or target buffer too small.
    2681             :  * \sa 
    2682             :  */
    2683             : RETCODE
    2684       21718 : dbbind(DBPROCESS * dbproc, int column, int vartype, DBINT varlen, BYTE * varaddr)
    2685             : {
    2686       21718 :         TDSCOLUMN *colinfo = NULL;
    2687             :         TDSRESULTINFO* results;
    2688             :         TDS_SERVER_TYPE srctype, desttype;
    2689             : 
    2690       21718 :         tdsdump_log(TDS_DBG_FUNC, "dbbind(%p, %d, %d, %d, %p)\n", dbproc, column, vartype, varlen, varaddr);
    2691       21718 :         CHECK_CONN(FAIL);
    2692       21718 :         CHECK_PARAMETER(varaddr, SYBEABNV, FAIL);
    2693             :         
    2694       21718 :         results = dbproc->tds_socket->res_info;
    2695             :         
    2696       21718 :         if (results == NULL || results->num_cols < column || column < 1) {
    2697           0 :                 dbperror(dbproc, SYBEABNC, 0);
    2698           0 :                 return FAIL;
    2699             :         }
    2700             :         
    2701       21718 :         if (varlen < 0) {
    2702         154 :                 switch (vartype) {
    2703          90 :                 case CHARBIND:
    2704             :                 case STRINGBIND:
    2705             :                 case NTBSTRINGBIND:
    2706             :                 case VARYCHARBIND:
    2707             :                 case VARYBINBIND:
    2708             :                         /* 
    2709             :                          * No message for this error.  Documentation doesn't define varlen < 0, but 
    2710             :                          * experimentation with Sybase db-lib shows it's accepted as if zero. 
    2711             :                          */
    2712          90 :                         tdsdump_log(TDS_DBG_FUNC, "dbbind: setting varlen (%d) to 0\n", varlen);
    2713             :                         varlen = 0;
    2714             :                         break;
    2715             :                 }
    2716             :         }
    2717             : 
    2718       21628 :         if (0 == varlen) {              /* "Note that if varlen is 0, no padding takes place." */
    2719       21354 :                 switch (vartype) {
    2720       10906 :                 case CHARBIND:
    2721             :                 case STRINGBIND:
    2722             :                 case NTBSTRINGBIND:
    2723       10906 :                         varlen = -1;
    2724       10906 :                         break;
    2725             :                 default:
    2726             :                         break;          /* dbconvert: "The destlen is ignored for all fixed-length, non-NULL data types." */
    2727             :                 }
    2728         364 :         }
    2729             : 
    2730       21718 :         dbproc->avail_flag = FALSE;
    2731             : 
    2732       21718 :         colinfo = dbproc->tds_socket->res_info->columns[column - 1];
    2733       21718 :         srctype = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    2734       21718 :         desttype = dblib_bound_type(vartype);
    2735       21718 :         if (desttype == TDS_INVALID_TYPE) {
    2736           0 :                 dbperror(dbproc, SYBEBTYP, 0);
    2737           0 :                 return FAIL;
    2738             :         }
    2739             : 
    2740       21718 :         if (!dbwillconvert(srctype, desttype)) {
    2741           0 :                 dbperror(dbproc, SYBEABMT, 0);
    2742           0 :                 return FAIL;
    2743             :         }
    2744             : 
    2745       21718 :         colinfo->column_varaddr = (char *) varaddr;
    2746       21718 :         colinfo->column_bindtype = vartype;
    2747       21718 :         colinfo->column_bindlen = varlen;
    2748             : 
    2749       21718 :         return SUCCEED;
    2750             : }                               /* dbbind()  */
    2751             : 
    2752             : /**
    2753             :  * \ingroup dblib_core
    2754             :  * \brief set name and location of the \c interfaces file FreeTDS should use to look up a servername.
    2755             :  * 
    2756             :  * Does not affect lookups or location of \c freetds.conf.  
    2757             :  * \param filename name of \c interfaces. It can be NULL (reset to default)
    2758             :  * \sa dbopen()
    2759             :  */
    2760             : void
    2761           0 : dbsetifile(char *filename)
    2762             : {
    2763           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsetifile(%s)\n", filename? filename : "0x00");
    2764             : 
    2765           0 :         tds_set_interfaces_file_loc(filename);
    2766           0 : }
    2767             : 
    2768             : /**
    2769             :  * \ingroup dblib_core
    2770             :  * \brief Tie a null-indicator to a regular result column.
    2771             :  * 
    2772             :  * 
    2773             :  * When a row is fetched, the indicator variable tells the state of the column's data.  
    2774             :  * 
    2775             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2776             :  * \param column Nth column in the result set, starting with 1.
    2777             :  * \param indicator address of host variable.
    2778             :  * \retval SUCCEED variable accepted.
    2779             :  * \retval FAIL \a indicator is NULL or \a column is out of range. 
    2780             :  * \remarks Contents of \a indicator are set with \c dbnextrow().  Possible values are:
    2781             :  * -  0 \a column bound successfully
    2782             :  * - -1 \a column is NULL.
    2783             :  * - >0 true length of data, had \a column not been truncated due to insufficient space in the columns bound host variable .  
    2784             :  * \sa dbanullbind(), dbbind(), dbdata(), dbdatlen(), dbnextrow().
    2785             :  */
    2786             : RETCODE
    2787         240 : dbnullbind(DBPROCESS * dbproc, int column, DBINT * indicator)
    2788             : {
    2789             :         TDSCOLUMN *colinfo;
    2790             : 
    2791         240 :         tdsdump_log(TDS_DBG_FUNC, "dbnullbind(%p, %d, %p)\n", dbproc, column, indicator);
    2792             : 
    2793         240 :         colinfo = dbcolptr(dbproc, column);
    2794         240 :         if (!colinfo)
    2795             :                 return FAIL; /* dbcolptr sent SYBECNOR, Column number out of range */
    2796             : 
    2797         240 :         colinfo->column_nullbind = (TDS_SMALLINT *)indicator;
    2798         240 :         return SUCCEED;
    2799             : }
    2800             : 
    2801             : /**
    2802             :  * \ingroup dblib_core
    2803             :  * \brief Tie a null-indicator to a compute result column.
    2804             :  * 
    2805             :  * 
    2806             :  * When a row is fetched, the indicator variable tells the state of the column's data.  
    2807             :  * 
    2808             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2809             :  * \param computeid identifies which one of potientially many compute rows is meant. The first compute
    2810             :  * clause has \a computeid == 1.  
    2811             :  * \param column Nth column in the result set, starting with 1.
    2812             :  * \param indicator address of host variable.
    2813             :  * \retval SUCCEED variable accepted.
    2814             :  * \retval FAIL \a indicator is NULL or \a column is out of range. 
    2815             :  * \remarks Contents of \a indicator are set with \c dbnextrow().  Possible values are:
    2816             :  * -  0 \a column bound successfully
    2817             :  * - -1 \a column is NULL.
    2818             :  * - >0 true length of data, had \a column not been truncated due to insufficient space in the columns bound host variable .  
    2819             :  * \sa dbadata(), dbadlen(), dbaltbind(), dbnextrow(), dbnullbind().
    2820             :  * \todo Never fails, but only because failure conditions aren't checked.  
    2821             :  */
    2822             : RETCODE
    2823           0 : dbanullbind(DBPROCESS * dbproc, int computeid, int column, DBINT * indicator)
    2824             : {
    2825             :         TDSCOLUMN *curcol;
    2826             : 
    2827           0 :         tdsdump_log(TDS_DBG_FUNC, "dbanullbind(%p, %d, %d, %p)\n", dbproc, computeid, column, indicator);
    2828             : 
    2829           0 :         curcol = dbacolptr(dbproc, computeid, column, true);
    2830           0 :         if (!curcol)
    2831             :                 return FAIL;
    2832             : 
    2833             :         /*
    2834             :          *  XXX Need to check for possibly problems before assuming
    2835             :          *  everything is okay
    2836             :          */
    2837           0 :         curcol->column_nullbind = (TDS_SMALLINT *)indicator;
    2838             : 
    2839           0 :         return SUCCEED;
    2840             : }
    2841             : 
    2842             : /**
    2843             :  * \ingroup dblib_core
    2844             :  * \brief Indicates whether or not the count returned by dbcount is real (Microsoft-compatibility feature).
    2845             :  * 
    2846             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2847             :  * \returns TRUE if the count returned by dbcount is real or FALSE if the count returned by dbcount is not real.
    2848             :  * \sa DBCOUNT(), dbcount().
    2849             :  */
    2850             : BOOL
    2851           0 : dbiscount(DBPROCESS * dbproc)
    2852             : {
    2853           0 :         tdsdump_log(TDS_DBG_FUNC, "dbiscount(%p)\n", dbproc);
    2854           0 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    2855             : 
    2856           0 :         return dbproc->tds_socket && dbproc->tds_socket->rows_affected != TDS_NO_COUNT;
    2857             : }
    2858             : 
    2859             : /**
    2860             :  * \ingroup dblib_core
    2861             :  * \brief Get count of rows processed
    2862             :  *
    2863             :  *
    2864             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    2865             :  * \returns
    2866             :  *      - for insert/update/delete, count of rows affected.
    2867             :  *      - for select, count of rows returned, after all rows have been fetched.
    2868             :  * \sa DBCOUNT(), dbnextrow(), dbresults().
    2869             :  */
    2870             : DBINT
    2871        1294 : dbcount(DBPROCESS * dbproc)
    2872             : {
    2873        1294 :         tdsdump_log(TDS_DBG_FUNC, "dbcount(%p)\n", dbproc);
    2874        1294 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    2875             : 
    2876        1294 :         if (!dbproc->tds_socket || dbproc->tds_socket->rows_affected == TDS_NO_COUNT)
    2877             :                 return -1;
    2878         796 :         return (DBINT)dbproc->tds_socket->rows_affected;
    2879             : }
    2880             : 
    2881             : /**
    2882             :  * \ingroup dblib_core
    2883             :  * \brief Clear \a n rows from the row buffer.
    2884             :  * 
    2885             :  * 
    2886             :  * \param dbproc contains all information needed by db-lib to manage communications with the server. 
    2887             :  * \param n number of rows to remove, >= 0.
    2888             :  * \sa dbgetrow(), dbnextrow(), dbsetopt().
    2889             :  */
    2890             : void
    2891         200 : dbclrbuf(DBPROCESS * dbproc, DBINT n)
    2892             : {
    2893         200 :         tdsdump_log(TDS_DBG_FUNC, "dbclrbuf(%p, %d)\n", dbproc, n);
    2894         200 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    2895             : 
    2896         200 :         if (n <= 0)
    2897             :                 return;
    2898             : 
    2899         200 :         if (dbproc->dbopts[DBBUFFER].factive) {
    2900         160 :                 DBPROC_ROWBUF * buf = &(dbproc->row_buf);
    2901         160 :                 int count = buffer_count(buf);
    2902         160 :                 if (n >= count)
    2903         140 :                         n = count - 1;
    2904         160 :                 buffer_delete_rows(&(dbproc->row_buf), n);
    2905             :         }
    2906             : }
    2907             : 
    2908             : /**
    2909             :  * \ingroup dblib_core
    2910             :  * \brief Test whether or not a datatype can be converted to another datatype
    2911             :  * 
    2912             :  * \param srctype type converting from
    2913             :  * \param desttype type converting to
    2914             :  * \remarks dbwillconvert() lies sometimes.  Some datatypes \em should be convertible but aren't yet in our implementation.  
    2915             :  *          Legal unimplemented conversions return \em TRUE.  
    2916             :  * \retval TRUE convertible, or should be.
    2917             :  * \retval FAIL not convertible.  
    2918             :  * \sa dbaltbind(), dbbind(), dbconvert(), dbconvert_ps(), \c src/dblib/unittests/convert().c().
    2919             :  */
    2920             : DBBOOL
    2921       22594 : dbwillconvert(int srctype, int desttype)
    2922             : {
    2923       22594 :         tdsdump_log(TDS_DBG_FUNC, "dbwillconvert(%s, %s)\n", tds_prdatatype(srctype), tds_prdatatype(desttype));
    2924       22594 :         return tds_willconvert(srctype, desttype) ? TRUE : FALSE;
    2925             : }
    2926             : 
    2927             : static int
    2928        1448 : dblib_coltype(TDSCOLUMN *colinfo)
    2929             : {
    2930        1448 :         switch (colinfo->column_type) {
    2931             :         case SYBVARCHAR:
    2932             :                 return SYBCHAR;
    2933           0 :         case SYBVARBINARY:
    2934             :                 return SYBBINARY;
    2935           0 :         case SYBLONGCHAR:
    2936             :         case SYBUNITEXT:
    2937             :         case SYBMSXML:
    2938             :                 return SYBTEXT;
    2939             :         /* these types are handled by tds_get_conversion_type */
    2940             :         case SYBBITN:
    2941             :         case SYBDATEN:
    2942             :         case SYBDATETIMN:
    2943             :         case SYBFLTN:
    2944             :         case SYBINTN:
    2945             :         case SYBMONEYN:
    2946             :         case SYBTIMEN:
    2947             :         case SYBUINTN:
    2948             :         case SYBMSTABLE:
    2949             :                 break;
    2950             :         /* these types are supported */
    2951             :         case SYBCHAR:
    2952             :         case SYBINT1:
    2953             :         case SYBINT2:
    2954             :         case SYBINT4:
    2955             :         case SYBINT8:
    2956             :         case SYBFLT8:
    2957             :         case SYBDATETIME:
    2958             :         case SYBBIT:
    2959             :         case SYBTEXT:
    2960             :         case SYBNTEXT:
    2961             :         case SYBIMAGE:
    2962             :         case SYBMONEY4:
    2963             :         case SYBMONEY:
    2964             :         case SYBDATETIME4:
    2965             :         case SYBREAL:
    2966             :         case SYBBINARY:
    2967             :         case SYBVOID:
    2968             :         case SYBNUMERIC:
    2969             :         case SYBDECIMAL:
    2970             :         case SYBNVARCHAR:
    2971             :         case SYBDATE:
    2972             :         case SYBTIME:
    2973             :         case SYB5BIGDATETIME:
    2974             :         case SYB5BIGTIME:
    2975             :         case SYBMSDATE:
    2976             :         case SYBMSTIME:
    2977             :         case SYBMSDATETIME2:
    2978             :         case SYBMSDATETIMEOFFSET:
    2979             :                 break;
    2980             :         /* exclude cardinal types */
    2981             :         case XSYBVARBINARY:
    2982             :         case XSYBBINARY:
    2983             :         case XSYBNVARCHAR:
    2984             :         case XSYBVARCHAR:
    2985             :         case XSYBNCHAR:
    2986             :         case SYB5INT8:
    2987             :                 break;
    2988             : #if !ENABLE_EXTRA_CHECKS
    2989             :         /* TODO these should be handled in some ways */
    2990             :         case SYBUNIQUE: /* or SYBBLOB */
    2991             :         case SYBVARIANT:
    2992             :         case SYBMSUDT:
    2993             :         case SYBLONGBINARY:
    2994             :         case SYBUINT1:
    2995             :         case SYBUINT2:
    2996             :         case SYBUINT4:
    2997             :         case SYBUINT8:
    2998             :         case SYBINTERVAL:
    2999             :         case SYBSINT1:
    3000             :         case SYBXML:
    3001             :                 break;
    3002             : #endif
    3003             :         }
    3004         328 :         return tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    3005             : }
    3006             : 
    3007             : /**
    3008             :  * \ingroup dblib_core
    3009             :  * \brief Get the datatype of a regular result set column. 
    3010             :  * 
    3011             :  * 
    3012             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3013             :  * \param column Nth in the result set, starting from 1.
    3014             :  * \returns \c SYB* datetype token value, or zero if \a column out of range
    3015             :  * \sa dbcollen(), dbcolname(), dbdata(), dbdatlen(), dbnumcols(), dbprtype(), dbvarylen().
    3016             :  */
    3017             : int
    3018        1562 : dbcoltype(DBPROCESS * dbproc, int column)
    3019             : {
    3020             :         TDSCOLUMN *colinfo;
    3021             : 
    3022        1562 :         tdsdump_log(TDS_DBG_FUNC, "dbcoltype(%p, %d)\n", dbproc, column);
    3023             : 
    3024        1562 :         colinfo = dbcolptr(dbproc, column);
    3025        1562 :         if (!colinfo)
    3026             :                 return -1;
    3027             : 
    3028        1432 :         return dblib_coltype(colinfo);
    3029             : }
    3030             : 
    3031             : /**
    3032             :  * \ingroup dblib_core
    3033             :  * \brief Get user-defined datatype of a regular result column.
    3034             :  * 
    3035             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3036             :  * \param column Nth in the result set, starting from 1.
    3037             :  * \returns \c SYB* datetype token value, or -1 if \a column out of range
    3038             :  * \sa dbaltutype(), dbcoltype().
    3039             :  */
    3040             : int
    3041           0 : dbcolutype(DBPROCESS * dbproc, int column)
    3042             : {
    3043             :         TDSCOLUMN *colinfo;
    3044             : 
    3045           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcolutype(%p, %d)\n", dbproc, column);
    3046             : 
    3047           0 :         colinfo = dbcolptr(dbproc, column);
    3048           0 :         if (!colinfo)
    3049             :                 return -1;
    3050             : 
    3051           0 :         return colinfo->column_usertype;
    3052             : }
    3053             : 
    3054             : /**
    3055             :  * \ingroup dblib_core
    3056             :  * \brief Get precision and scale information for a regular result column.
    3057             :  * 
    3058             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3059             :  * \param column Nth in the result set, starting from 1.
    3060             :  * \return Pointer to a DBTYPEINFO structure .  NULL \a column is out of range.
    3061             :  * \sa dbcollen(), dbcolname(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols(), dbprtype(), dbvarylen().
    3062             :  */
    3063             : DBTYPEINFO *
    3064           0 : dbcoltypeinfo(DBPROCESS * dbproc, int column)
    3065             : {
    3066             :         /* moved typeinfo from static into dbproc structure to make thread safe.  (mlilback 11/7/01) */
    3067             :         TDSCOLUMN *colinfo;
    3068             : 
    3069           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcoltypeinfo(%p, %d)\n", dbproc, column);
    3070             : 
    3071           0 :         colinfo = dbcolptr(dbproc, column);
    3072           0 :         if (!colinfo)
    3073             :                 return NULL;
    3074             : 
    3075           0 :         dbproc->typeinfo.precision = colinfo->column_prec;
    3076           0 :         dbproc->typeinfo.scale = colinfo->column_scale;
    3077           0 :         return &dbproc->typeinfo;
    3078             : }
    3079             : 
    3080             : /**
    3081             :  * \brief Get a bunch of column attributes with a single call (Microsoft-compatibility feature).  
    3082             :  * 
    3083             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3084             :  * \param type must be CI_REGULAR or CI_ALTERNATE (CI_CURSOR is defined by the vendor, but is not yet implemented).
    3085             :  * \param column Nth in the result set, starting from 1.
    3086             :  * \param computeid (ignored)
    3087             :  * \param pdbcol address of structure to be populated by this function.  
    3088             :  * \return SUCCEED or FAIL. 
    3089             :  * \sa dbcolbrowse(), dbqual(), dbtabbrowse(), dbtabcount(), dbtabname(), dbtabsource(), dbtsnewlen(), dbtsnewval(), dbtsput().
    3090             :  * \todo Support cursor rows. 
    3091             :  */
    3092             : RETCODE
    3093           0 : dbcolinfo(DBPROCESS *dbproc, CI_TYPE type, DBINT column, DBINT computeid, DBCOL *pdbcol)
    3094             : {
    3095             :         DBTYPEINFO *ps;
    3096             :         TDSCOMPUTEINFO *info;
    3097             :         TDSCOLUMN *colinfo;
    3098             :         unsigned int i;
    3099             : 
    3100           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcolinfo(%p, %d, %d, %d, %p)\n", dbproc, type, column, computeid, pdbcol);
    3101             : 
    3102           0 :         colinfo = dbcolptr(dbproc, column);
    3103           0 :         if (!colinfo)
    3104             :                 return FAIL;
    3105             :                 
    3106           0 :         CHECK_NULP(pdbcol, "dbcolinfo", 5, FAIL);
    3107             : 
    3108           0 :         if (type == CI_REGULAR) {
    3109             : 
    3110           0 :                 strlcpy(pdbcol->Name, dbcolname(dbproc, column), sizeof(pdbcol->Name));
    3111           0 :                 strlcpy(pdbcol->ActualName, dbcolname(dbproc, column), sizeof(pdbcol->ActualName));
    3112           0 :                 strlcpy(pdbcol->TableName, tds_dstr_cstr(&colinfo->table_name), sizeof(pdbcol->TableName));
    3113             : 
    3114           0 :                 pdbcol->Type = dbcoltype(dbproc, column);
    3115           0 :                 pdbcol->UserType = dbcolutype(dbproc, column);
    3116           0 :                 pdbcol->MaxLength = dbcollen(dbproc, column);
    3117           0 :                 pdbcol->Null = _dbnullable(dbproc, column);
    3118           0 :                 pdbcol->VarLength = dbvarylen(dbproc, column);
    3119             : 
    3120           0 :                 ps = dbcoltypeinfo(dbproc, column);
    3121             : 
    3122           0 :                 if( ps ) {
    3123           0 :                         pdbcol->Precision = ps->precision;
    3124           0 :                         pdbcol->Scale = ps->scale;
    3125             :                 }
    3126             : 
    3127           0 :                 pdbcol->Updatable = colinfo->column_writeable ? TRUE : FALSE;
    3128           0 :                 pdbcol->Identity = colinfo->column_identity ? TRUE : FALSE;
    3129             : 
    3130           0 :                 return SUCCEED;
    3131             :         }
    3132             :   
    3133           0 :         if (type == CI_ALTERNATE) {
    3134             : 
    3135           0 :                 if (computeid == 0)
    3136             :                         return FAIL;
    3137             : 
    3138           0 :                 for (i = 0;; ++i) {
    3139           0 :                         if (i >= dbproc->tds_socket->num_comp_info)
    3140             :                                 return FAIL;
    3141           0 :                         info = dbproc->tds_socket->comp_info[i];
    3142           0 :                         if (info->computeid == computeid)
    3143             :                                 break;
    3144             :                 }
    3145             : 
    3146             :                 /* if either the compute id or the column number are invalid, return -1 */
    3147           0 :                 if (column < 1 || column > info->num_cols)
    3148             :                         return FAIL;
    3149             : 
    3150           0 :                 colinfo = info->columns[column - 1];
    3151             : 
    3152           0 :                 strlcpy(pdbcol->Name, tds_dstr_cstr(&colinfo->column_name), sizeof(pdbcol->Name));
    3153           0 :                 strlcpy(pdbcol->ActualName, tds_dstr_cstr(&colinfo->column_name), sizeof(pdbcol->ActualName));
    3154           0 :                 strlcpy(pdbcol->TableName, tds_dstr_cstr(&colinfo->table_name), sizeof(pdbcol->TableName));
    3155             : 
    3156           0 :                 pdbcol->Type = dbalttype(dbproc, computeid, column);
    3157           0 :                 pdbcol->UserType = dbaltutype(dbproc, computeid, column);
    3158           0 :                 pdbcol->MaxLength = dbaltlen(dbproc, computeid, column);
    3159           0 :                 if (colinfo->column_nullable) 
    3160           0 :                         pdbcol->Null = TRUE;
    3161             :                 else
    3162           0 :                         pdbcol->Null = FALSE;
    3163             : 
    3164           0 :                 pdbcol->VarLength = FALSE;
    3165             : 
    3166           0 :                 if (colinfo->column_nullable
    3167           0 :                     || is_nullable_type(colinfo->column_type))
    3168           0 :                         pdbcol->VarLength = TRUE;
    3169             : 
    3170           0 :                 pdbcol->Precision = colinfo->column_prec;
    3171           0 :                 pdbcol->Scale = colinfo->column_scale;
    3172             :   
    3173           0 :                 pdbcol->Updatable = colinfo->column_writeable ? TRUE : FALSE ;
    3174           0 :                 pdbcol->Identity = colinfo->column_identity ? TRUE : FALSE ;
    3175             : 
    3176           0 :                 return SUCCEED;
    3177             :         }
    3178             : 
    3179             :         return FAIL;
    3180             : }
    3181             :  
    3182             : /**
    3183             :  * \ingroup dblib_core
    3184             :  * \brief Get base database column name for a result set column.  
    3185             :  * 
    3186             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3187             :  * \param column Nth in the result set, starting from 1.
    3188             :  * \return pointer to ASCII null-terminated string, the name of the column. On error, NULL.
    3189             :  * \sa dbcolbrowse(), dbqual(), dbtabbrowse(), dbtabcount(), dbtabname(), dbtabsource(), dbtsnewlen(), dbtsnewval(), dbtsput().
    3190             :  */
    3191             : char *
    3192           0 : dbcolsource(DBPROCESS * dbproc, int column)
    3193             : {
    3194             :         TDSCOLUMN *colinfo;
    3195             : 
    3196           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcolsource(%p, %d)\n", dbproc, column);
    3197             : 
    3198           0 :         colinfo = dbcolptr(dbproc, column);
    3199           0 :         if (!colinfo)
    3200             :                 return NULL;
    3201             : 
    3202           0 :         return tds_dstr_buf(tds_dstr_isempty(&colinfo->table_column_name) ?
    3203             :                 &colinfo->column_name :
    3204             :                 &colinfo->table_column_name);
    3205             : }
    3206             : 
    3207             : /**
    3208             :  * \ingroup dblib_core
    3209             :  * \brief Get size of a regular result column.
    3210             :  * 
    3211             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3212             :  * \param column Nth in the result set, starting from 1.
    3213             :  * \return size of the column (not of data in any particular row).  On error, -1.
    3214             :  * \sa dbcolname(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols().
    3215             :  */
    3216             : DBINT
    3217           0 : dbcollen(DBPROCESS * dbproc, int column)
    3218             : {
    3219             :         TDSCOLUMN *colinfo;
    3220             : 
    3221           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcollen(%p, %d)\n", dbproc, column);
    3222             : 
    3223           0 :         colinfo = dbcolptr(dbproc, column);
    3224           0 :         if (!colinfo)
    3225             :                 return -1;
    3226             : 
    3227           0 :         return colinfo->column_size;
    3228             : }
    3229             : 
    3230             : /**
    3231             :  * \ingroup dblib_core
    3232             :  * \brief Get size of a result column needed to print column.
    3233             :  *
    3234             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3235             :  * \param column Nth in the result set, starting from 1.
    3236             :  * \return size of the column in characters (not of data in any particular row).  On error, -1.
    3237             :  * \sa dbcolname(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols().
    3238             :  */
    3239             : DBINT
    3240           0 : dbprcollen(DBPROCESS * dbproc, int column)
    3241             : {
    3242             :         TDSCOLUMN *colinfo;
    3243             : 
    3244           0 :         tdsdump_log(TDS_DBG_FUNC, "dbprcollen(%p, %d)\n", dbproc, column);
    3245             : 
    3246           0 :         colinfo = dbcolptr(dbproc, column);
    3247           0 :         if (!colinfo)
    3248             :                 return 0;
    3249             : 
    3250           0 :         return _get_printable_size(colinfo);
    3251             : }
    3252             : 
    3253             : 
    3254             : /* dbvarylen(), pkleef@openlinksw.com 01/21/02 */
    3255             : /**
    3256             :  * \ingroup dblib_core
    3257             :  * \brief Determine whether a column can vary in size.
    3258             :  * 
    3259             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3260             :  * \param column Nth in the result set, starting from 1.
    3261             :  * \retval TRUE datatype of column can vary in size, or is nullable. 
    3262             :  * \retval FALSE datatype of column is fixed and is not nullable. 
    3263             :  * \sa dbcollen(), dbcolname(), dbcoltype(), dbdata(), dbdatlen(), dbnumcols(), dbprtype().
    3264             :  */
    3265             : DBINT
    3266        1588 : dbvarylen(DBPROCESS * dbproc, int column)
    3267             : {
    3268             :         TDSCOLUMN *colinfo;
    3269             : 
    3270        1588 :         tdsdump_log(TDS_DBG_FUNC, "dbvarylen(%p, %d)\n", dbproc, column);
    3271             : 
    3272        1588 :         colinfo = dbcolptr(dbproc, column);
    3273        1588 :         if (!colinfo)
    3274             :                 return FALSE;
    3275             : 
    3276        1588 :         if (colinfo->column_nullable)
    3277             :                 return TRUE;
    3278             : 
    3279        1248 :         switch (colinfo->column_type) {
    3280             :                 /* variable length fields */
    3281             :         case SYBNVARCHAR:
    3282             :         case SYBVARBINARY:
    3283             :         case SYBVARCHAR:
    3284             :         case XSYBVARCHAR:
    3285             :         case XSYBNVARCHAR:
    3286             :         case XSYBVARBINARY:
    3287             :                 return TRUE;
    3288             : 
    3289             :                 /* types that can be null */
    3290             :         case SYBBITN:
    3291             :         case SYBDATETIMN:
    3292             :         case SYBDECIMAL:
    3293             :         case SYBFLTN:
    3294             :         case SYBINTN:
    3295             :         case SYBMONEYN:
    3296             :         case SYBNUMERIC:
    3297             :         case SYBDATEN:
    3298             :         case SYBTIMEN:
    3299             :         case SYBUINTN:
    3300             :         case SYB5BIGDATETIME:
    3301             :         case SYB5BIGTIME:
    3302             :         case SYBMSDATE:
    3303             :         case SYBMSTIME:
    3304             :         case SYBMSDATETIME2:
    3305             :         case SYBMSDATETIMEOFFSET:
    3306             :         case SYBVARIANT:
    3307             :         case SYBUNIQUE:
    3308             :                 return TRUE;
    3309             : 
    3310             :                 /* blob types */
    3311             :         case SYBIMAGE:
    3312             :         case SYBNTEXT:
    3313             :         case SYBTEXT:
    3314             :         case SYBLONGBINARY:
    3315             :         /* case SYBBLOB: */ /* same as SYBUNIQUE */
    3316             :         case SYB5INT8:
    3317             :         case SYBUNITEXT:
    3318             :         case SYBXML:
    3319             :         case SYBMSUDT:
    3320             :         case SYBMSXML:
    3321             :                 return TRUE;
    3322             :         case SYBMSTABLE:
    3323             :                 return TRUE;
    3324             : 
    3325           0 :         case SYBLONGCHAR:
    3326             :         /* case XSYBCHAR: */ /* same as SYBLONGCHAR */
    3327           0 :                 if (colinfo->column_varint_size >= 4)
    3328             :                         return TRUE;
    3329             :                 break;
    3330             : 
    3331             :                 /* with defined size*/
    3332             :         case SYBCHAR:
    3333             :         case SYBBINARY:
    3334             :         case XSYBNCHAR:
    3335             :         case XSYBBINARY:
    3336             :                 break;
    3337             : 
    3338             :                 /* fixed */
    3339             :         case SYBINT1:
    3340             :         case SYBINT2:
    3341             :         case SYBINT4:
    3342             :         case SYBFLT8:
    3343             :         case SYBDATETIME:
    3344             :         case SYBBIT:
    3345             :         case SYBMONEY4:
    3346             :         case SYBMONEY:
    3347             :         case SYBDATETIME4:
    3348             :         case SYBREAL:
    3349             :         case SYBINT8:
    3350             :         case SYBUINT1:
    3351             :         case SYBUINT2:
    3352             :         case SYBUINT4:
    3353             :         case SYBUINT8:
    3354             :         case SYBSINT1:
    3355             :         case SYBTIME:
    3356             :         case SYBDATE:
    3357             :         case SYBVOID:
    3358             :         case SYBINTERVAL:
    3359             :                 break;
    3360             :         }
    3361         680 :         return FALSE;
    3362             : }
    3363             : 
    3364             : /**
    3365             :  * \ingroup dblib_core
    3366             :  * \brief   Get size of current row's data in a regular result column.  
    3367             :  * 
    3368             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3369             :  * \param column Nth in the result set, starting from 1.
    3370             :  * \return size of the data, in bytes.
    3371             :  * \sa dbcollen(), dbcolname(), dbcoltype(), dbdata(), dbnumcols().
    3372             :  */
    3373             : DBINT
    3374        2344 : dbdatlen(DBPROCESS * dbproc, int column)
    3375             : {
    3376             :         DBINT len;
    3377             :         TDSCOLUMN *colinfo;
    3378             : 
    3379        2344 :         tdsdump_log(TDS_DBG_FUNC, "dbdatlen(%p, %d)\n", dbproc, column);
    3380             : 
    3381        2344 :         colinfo = dbcolptr(dbproc, column);
    3382        2344 :         if (!colinfo)
    3383             :                 return -1;      
    3384             : 
    3385        2344 :         len = TDS_MAX(colinfo->column_cur_size, 0);
    3386             : 
    3387        2344 :         tdsdump_log(TDS_DBG_FUNC, "dbdatlen() type = %d, len= %d\n", colinfo->column_type, len);
    3388             : 
    3389             :         return len;
    3390             : }
    3391             : 
    3392             : /**
    3393             :  * \ingroup dblib_core
    3394             :  * \brief Get address of data in a regular result column.
    3395             :  * 
    3396             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3397             :  * \param column Nth in the result set, starting from 1.
    3398             :  * \return pointer the data, or NULL if data are NULL, or if \a column is out of range.  
    3399             :  * \sa dbbind(), dbcollen(), dbcolname(), dbcoltype(), dbdatlen(), dbnumcols().
    3400             :  */
    3401             : BYTE *
    3402        3002 : dbdata(DBPROCESS * dbproc, int column)
    3403             : {
    3404        3002 :         tdsdump_log(TDS_DBG_FUNC, "dbdata(%p, %d)\n", dbproc, column);
    3405             : 
    3406        6004 :         return _dbcoldata(dbcolptr(dbproc, column));
    3407             : }
    3408             : 
    3409             : /** \internal
    3410             :  * \ingroup dblib_internal
    3411             :  * \brief Return data from a column
    3412             :  *
    3413             :  * \param colinfo contains information on a result column.
    3414             :  * \return pointer to the data, or NULL if data are NULL
    3415             :  * \sa dbdata(), dbretdata()
    3416             :  */
    3417             : static BYTE *
    3418             : _dbcoldata(TDSCOLUMN *colinfo)
    3419             : {
    3420             :         BYTE *res;
    3421             :         static const BYTE empty[1] = { 0 };
    3422             : 
    3423        3072 :         if (!colinfo || colinfo->column_cur_size < 0)
    3424             :                 return NULL;
    3425             : 
    3426        2528 :         res = colinfo->column_data;
    3427        2528 :         if (is_blob_col(colinfo))
    3428         274 :                 res = (BYTE *) ((TDSBLOB *) res)->textvalue;
    3429        2528 :         if (!res)
    3430             :                 return (BYTE *) empty;
    3431             :         return res;
    3432             : }
    3433             : 
    3434             : /**
    3435             :  * \ingroup dblib_core
    3436             :  * \brief Cancel the current command batch.
    3437             :  * 
    3438             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3439             :  * \retval SUCCEED always.
    3440             :  * \sa dbcanquery(), dbnextrow(), dbresults(), dbsetinterrupt(), dbsqlexec(), dbsqlok(), dbsqlsend().
    3441             :  * \todo Check for failure and return accordingly.
    3442             :  */
    3443             : RETCODE
    3444       10320 : dbcancel(DBPROCESS * dbproc)
    3445             : {
    3446             :         TDSSOCKET *tds;
    3447             : 
    3448       10320 :         tdsdump_log(TDS_DBG_FUNC, "dbcancel(%p)\n", dbproc);
    3449       10320 :         CHECK_CONN(FAIL);
    3450             : 
    3451       10320 :         tds = dbproc->tds_socket;
    3452             : 
    3453       10320 :         tds_send_cancel(tds);
    3454       10320 :         tds_process_cancel(tds);
    3455             : 
    3456       10320 :         return SUCCEED;
    3457             : }
    3458             : 
    3459             : /**
    3460             :  * \ingroup dblib_core
    3461             :  * \brief Determine size buffer required to hold the results returned by dbsprhead(), dbsprline(), and  dbspr1row().
    3462             :  * 
    3463             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3464             :  * \return size of buffer requirement, in bytes.  
    3465             :  * \remarks An esoteric function.
    3466             :  * \sa dbprhead(), dbprrow(), dbspr1row(), dbsprhead(), dbsprline().
    3467             :  */
    3468             : DBINT
    3469           0 : dbspr1rowlen(DBPROCESS * dbproc)
    3470             : {
    3471             :         TDSSOCKET *tds;
    3472           0 :         int col, len = 0;
    3473             : 
    3474           0 :         tdsdump_log(TDS_DBG_FUNC, "dbspr1rowlen(%p)\n", dbproc);
    3475           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    3476           0 :         CHECK_PARAMETER(dbproc->tds_socket, SYBEDDNE, 0);
    3477             : 
    3478             :         tds = dbproc->tds_socket;
    3479             :         
    3480           0 :         for (col = 0; col < tds->res_info->num_cols; col++) {
    3481           0 :                 TDSCOLUMN *colinfo = tds->res_info->columns[col];
    3482           0 :                 int collen = _get_printable_size(colinfo);
    3483           0 :                 int namlen = (int) tds_dstr_len(&colinfo->column_name);
    3484             : 
    3485           0 :                 len += TDS_MAX(collen, namlen);
    3486             : 
    3487           0 :                 if (col > 0)         /* allow for the space between columns */
    3488           0 :                         len += dbstring_length(dbproc->dbopts[DBPRCOLSEP].param);
    3489             :         }
    3490             :         
    3491           0 :         return ++len;   /* allow for the nul */
    3492             : }
    3493             : 
    3494             : /**
    3495             :  * \ingroup dblib_core
    3496             :  * \brief Print a regular result row to a buffer.  
    3497             :  * 
    3498             :  * Fills a buffer with one data row, represented as a null-terminated ASCII string.  Helpful for debugging.  
    3499             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3500             :  * \param buffer \em output: Address of a buffer to hold ASCII null-terminated string.
    3501             :  * \param buf_len size of \a buffer, in bytes. 
    3502             :  * \retval SUCCEED on success.
    3503             :  * \retval FAIL trouble encountered.  
    3504             :  * \sa dbclropt(), dbisopt(), dbprhead(), dbprrow(), dbspr1rowlen(), dbsprhead(), dbsprline().
    3505             :  */
    3506             : RETCODE
    3507           0 : dbspr1row(DBPROCESS * dbproc, char *buffer, DBINT buf_len)
    3508             : {
    3509             :         TDSSOCKET *tds;
    3510             :         TDSDATEREC when;
    3511             :         int i, c, col;
    3512             :         DBINT len;
    3513             : 
    3514           0 :         tdsdump_log(TDS_DBG_FUNC, "dbspr1row(%p, %s, %d)\n", dbproc, buffer, buf_len);
    3515           0 :         CHECK_CONN(FAIL);
    3516           0 :         CHECK_NULP(buffer, "dbspr1row", 2, FAIL);
    3517             : 
    3518             :         if (!dbproc->tds_socket)
    3519             :                 return FAIL;
    3520             : 
    3521             :         tds = dbproc->tds_socket;
    3522             : 
    3523           0 :         for (col = 0; col < tds->res_info->num_cols; col++) {
    3524             :                 size_t padlen, collen, namlen;
    3525           0 :                 TDSCOLUMN *colinfo = tds->res_info->columns[col];
    3526           0 :                 if (colinfo->column_cur_size < 0) {
    3527           0 :                         len = 4;
    3528           0 :                         if (buf_len <= len) {
    3529             :                                 return FAIL;
    3530             :                         }
    3531           0 :                         strcpy(buffer, "NULL");
    3532             :                 } else {
    3533             :                         TDS_SERVER_TYPE desttype, srctype;
    3534             : 
    3535           0 :                         desttype = dblib_bound_type(STRINGBIND);
    3536           0 :                         srctype = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    3537           0 :                         if (is_datetime_type(srctype)) {
    3538           0 :                                 tds_datecrack(srctype, dbdata(dbproc, col + 1), &when);
    3539           0 :                                 len = (int)tds_strftime(buffer, buf_len, STD_DATETIME_FMT, &when, 3);
    3540             :                         } else {
    3541           0 :                                 len = dbconvert(dbproc, srctype, dbdata(dbproc, col + 1), dbdatlen(dbproc, col + 1), 
    3542             :                                                 desttype, (BYTE *) buffer, buf_len);
    3543             :                         }
    3544           0 :                         if (len == -1) {
    3545             :                                 return FAIL;
    3546             :                         }
    3547             :                 }
    3548           0 :                 buffer += len;
    3549           0 :                 buf_len -= len;
    3550           0 :                 collen = _get_printable_size(colinfo);
    3551           0 :                 namlen = tds_dstr_len(&colinfo->column_name);
    3552           0 :                 padlen = TDS_MAX(collen, namlen) - len;
    3553           0 :                 if ((c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0)) == -1) {
    3554           0 :                         c = ' ';
    3555             :                 }
    3556           0 :                 for (; padlen > 0; padlen--) {
    3557           0 :                         if (buf_len < 1) {
    3558             :                                 return FAIL;
    3559             :                         }
    3560           0 :                         *buffer++ = c;
    3561           0 :                         buf_len--;
    3562             :                 }
    3563           0 :                 if ((col + 1) < tds->res_info->num_cols) {
    3564             :                         i = 0;
    3565           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i)) != -1) {
    3566           0 :                                 if (buf_len < 1) {
    3567             :                                         return FAIL;
    3568             :                                 }
    3569           0 :                                 *buffer++ = c;
    3570           0 :                                 buf_len--;
    3571           0 :                                 i++;
    3572             :                         }
    3573             :                 }
    3574             :         }
    3575           0 :         if (buf_len < 1) {
    3576             :                 return FAIL;
    3577             :         }
    3578           0 :         *buffer = '\0';
    3579           0 :         return SUCCEED;
    3580             : }
    3581             : 
    3582             : /**
    3583             :  * \ingroup dblib_core
    3584             :  * \brief Print a result set to stdout. 
    3585             :  * 
    3586             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3587             :  * \sa dbbind(), dbnextrow(), dbprhead(), dbresults(), dbspr1row(), dbsprhead(), dbsprline(). 
    3588             :  */
    3589             : RETCODE
    3590          60 : dbprrow(DBPROCESS * dbproc)
    3591             : {
    3592             :         TDSCOLUMN *colinfo;
    3593             :         TDSRESULTINFO *resinfo;
    3594             :         TDSSOCKET *tds;
    3595             :         int i, col;
    3596             :         size_t collen, namlen, len;
    3597             :         char dest[8192];
    3598             :         int desttype, srctype;
    3599             :         TDSDATEREC when;
    3600             :         STATUS status;
    3601             :         ptrdiff_t padlen;
    3602             :         int c;
    3603             :         int selcol;
    3604             :         int linechar;
    3605             :         int op;
    3606             :         const char *opname, *p;
    3607             : 
    3608             :         /* these are for compute rows */
    3609             :         DBINT computeid, num_cols, colid;
    3610          60 :         TDS_SMALLINT *col_printlens = NULL;
    3611             : 
    3612          60 :         tdsdump_log(TDS_DBG_FUNC, "dbprrow(%p)\n", dbproc);
    3613          60 :         CHECK_CONN(FAIL);
    3614             : 
    3615             :         tds = dbproc->tds_socket;
    3616             : 
    3617         410 :         while ((status = dbnextrow(dbproc)) != NO_MORE_ROWS) {
    3618             : 
    3619         350 :                 if (status == FAIL) {
    3620           0 :                         free(col_printlens);
    3621           0 :                         return FAIL;
    3622             :                 }
    3623             : 
    3624         350 :                 if (status == REG_ROW) {
    3625             : 
    3626         350 :                         resinfo = tds->res_info;
    3627             : 
    3628         350 :                         if (col_printlens == NULL) {
    3629          20 :                                 if ((col_printlens = tds_new0(TDS_SMALLINT, resinfo->num_cols)) == NULL) {
    3630           0 :                                         dbperror(dbproc, SYBEMEM, errno);
    3631           0 :                                         return FAIL;
    3632             :                                 }
    3633             :                         }
    3634             : 
    3635        1750 :                         for (col = 0; col < resinfo->num_cols; col++) {
    3636        1400 :                                 colinfo = resinfo->columns[col];
    3637        1400 :                                 if (colinfo->column_cur_size < 0) {
    3638          60 :                                         len = 4;
    3639          60 :                                         strcpy(dest, "NULL");
    3640             :                                 } else {
    3641        1340 :                                         desttype = dblib_bound_type(STRINGBIND);
    3642        1340 :                                         srctype = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    3643        1340 :                                         if (is_datetime_type(srctype)) {
    3644           0 :                                                 tds_datecrack(srctype, dbdata(dbproc, col + 1), &when);
    3645           0 :                                                 len = (int)tds_strftime(dest, sizeof(dest), STD_DATETIME_FMT, &when, 3);
    3646             :                                         } else {
    3647        1340 :                                                 len = dbconvert(dbproc, srctype, dbdata(dbproc, col + 1), dbdatlen(dbproc, col + 1),
    3648             :                                                                 desttype, (BYTE *) dest, sizeof(dest));
    3649             :                                         }
    3650             :                                 }
    3651             : 
    3652        1400 :                                 p = memchr(dest, '\0', len);
    3653        1400 :                                 fwrite(dest, 1, p == NULL ? len : (p - dest), stdout);
    3654        1400 :                                 collen = _get_printable_size(colinfo);
    3655        2800 :                                 namlen = tds_dstr_len(&colinfo->column_name);
    3656        1400 :                                 padlen = TDS_MAX(collen, namlen) - len;
    3657             : 
    3658        2800 :                                 c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0);
    3659       10618 :                                 for (; c > -1 && padlen > 0; padlen--) {
    3660        9218 :                                         putchar(c);
    3661             :                                 }
    3662             : 
    3663        1400 :                                 if ((col + 1) < resinfo->num_cols) {
    3664             :                                         i = 0;
    3665        4200 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3666             :                                                 putchar(c);
    3667             :                                         }
    3668             :                                 }
    3669        1400 :                                 col_printlens[col] = collen;
    3670             :                         }
    3671             :                         i = 0;
    3672        1400 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i++)) != -1) {
    3673             :                                 putchar(c);
    3674             :                         }
    3675             : 
    3676           0 :                 } else if (col_printlens == NULL) {
    3677             :                         return FAIL;
    3678             :                 } else {
    3679             : 
    3680             :                         computeid = status;
    3681             : 
    3682           0 :                         for (i = 0;; ++i) {
    3683           0 :                                 if ((TDS_UINT) i >= tds->num_comp_info) {
    3684           0 :                                         free(col_printlens);
    3685           0 :                                         return FAIL;
    3686             :                                 }
    3687           0 :                                 resinfo = tds->comp_info[i];
    3688           0 :                                 if (resinfo->computeid == computeid)
    3689             :                                         break;
    3690             :                         }
    3691             : 
    3692           0 :                         num_cols = dbnumalts(dbproc, computeid);
    3693           0 :                         tdsdump_log(TDS_DBG_FUNC, "dbprrow num compute cols = %d\n", num_cols);
    3694             : 
    3695             :                         i = 0;
    3696           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i++)) != -1) {
    3697             :                                 putchar(c);
    3698             :                         }
    3699           0 :                         for (selcol = col = 1; col <= num_cols; col++) {
    3700           0 :                                 tdsdump_log(TDS_DBG_FUNC, "dbprrow calling dbaltcolid(%d,%d)\n", computeid, col);
    3701           0 :                                 colid = dbaltcolid(dbproc, computeid, col);
    3702             :                                 /*
    3703             :                                  * The pad character is pointed to by dbopts[DBPRPAD].param.  If that pointer 
    3704             :                                  * is NULL -- meaning padding is turned off -- dbstring_getchar returns -1. 
    3705             :                                  */
    3706           0 :                                 while (selcol < colid) {
    3707           0 :                                         for (i = 0; i < col_printlens[selcol - 1]; i++) {
    3708           0 :                                                 if ((c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0)) >= 0)
    3709             :                                                         putchar(c); 
    3710             :                                         }
    3711           0 :                                         selcol++;
    3712           0 :                                         i = 0;
    3713           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3714             :                                                 putchar(c);
    3715             :                                         }
    3716             :                                 }
    3717           0 :                                 op = dbaltop(dbproc, computeid, col);
    3718           0 :                                 opname = dbprtype(op);
    3719           0 :                                 printf("%s", opname);
    3720           0 :                                 for (i = 0; i < (col_printlens[selcol - 1] - (int) strlen(opname)); i++) {
    3721           0 :                                         if ((c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0)) >= 0)
    3722             :                                                 putchar(c); 
    3723             :                                 }
    3724           0 :                                 selcol++;
    3725           0 :                                 if ((colid + 1) < num_cols) {
    3726             :                                         i = 0;
    3727           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3728             :                                                 putchar(c);
    3729             :                                         }
    3730             :                                 }
    3731             :                         }
    3732             :                         i = 0;
    3733           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i++)) != -1) {
    3734             :                                 putchar(c);
    3735             :                         }
    3736             : 
    3737           0 :                         for (selcol = col = 1; col <= num_cols; col++) {
    3738           0 :                                 tdsdump_log(TDS_DBG_FUNC, "dbprrow calling dbaltcolid(%d,%d)\n", computeid, col);
    3739           0 :                                 colid = dbaltcolid(dbproc, computeid, col);
    3740           0 :                                 while (selcol < colid) {
    3741           0 :                                         for (i = 0; i < col_printlens[selcol - 1]; i++) {
    3742           0 :                                                 putchar(' ');
    3743             :                                         }
    3744           0 :                                         selcol++;
    3745           0 :                                         i = 0;
    3746           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3747             :                                                 putchar(c);
    3748             :                                         }
    3749             :                                 }
    3750           0 :                                 if (resinfo->by_cols > 0) {
    3751             :                                         linechar = '-';
    3752             :                                 } else {
    3753           0 :                                         linechar = '=';
    3754             :                                 }
    3755           0 :                                 for (i = 0; i < col_printlens[colid - 1]; i++)
    3756           0 :                                         putchar(linechar);
    3757           0 :                                 selcol++;
    3758           0 :                                 if ((colid + 1) < num_cols) {
    3759             :                                         i = 0;
    3760           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3761             :                                                 putchar(c);
    3762             :                                         }
    3763             :                                 }
    3764             :                         }
    3765             :                         i = 0;
    3766           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i++)) != -1) {
    3767             :                                 putchar(c);
    3768             :                         }
    3769             : 
    3770           0 :                         for (selcol = col = 1; col <= num_cols; col++) {
    3771           0 :                                 colinfo = resinfo->columns[col - 1];
    3772             : 
    3773           0 :                                 desttype = dblib_bound_type(STRINGBIND);
    3774           0 :                                 srctype = dbalttype(dbproc, computeid, col);
    3775             : 
    3776           0 :                                 if (is_datetime_type(srctype)) {
    3777           0 :                                         tds_datecrack(srctype, dbadata(dbproc, computeid, col), &when);
    3778           0 :                                         len = (int)tds_strftime(dest, sizeof(dest), STD_DATETIME_FMT, &when, 3);
    3779             :                                 } else {
    3780           0 :                                         len = dbconvert(dbproc, srctype, dbadata(dbproc, computeid, col), -1, desttype,
    3781             :                                                         (BYTE *) dest, sizeof(dest));
    3782             :                                 }
    3783             : 
    3784           0 :                                 tdsdump_log(TDS_DBG_FUNC, "dbprrow calling dbaltcolid(%d,%d)\n", computeid, col);
    3785           0 :                                 colid = dbaltcolid(dbproc, computeid, col);
    3786           0 :                                 tdsdump_log(TDS_DBG_FUNC, "dbprrow select column = %d\n", colid);
    3787             : 
    3788           0 :                                 while (selcol < colid) {
    3789           0 :                                         for (i = 0; i < col_printlens[selcol - 1]; i++) {
    3790           0 :                                                 putchar(' ');
    3791             :                                         }
    3792           0 :                                         selcol++;
    3793           0 :                                         i = 0;
    3794           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3795             :                                                 putchar(c);
    3796             :                                         }
    3797             :                                 }
    3798           0 :                                 p = memchr(dest, '\0', len);
    3799           0 :                                 fwrite(dest, 1, p == NULL ? len : (p - dest), stdout);
    3800           0 :                                 collen = _get_printable_size(colinfo);
    3801           0 :                                 namlen = tds_dstr_len(&colinfo->column_name);
    3802           0 :                                 padlen = TDS_MAX(collen, namlen) - len;
    3803           0 :                                 if ((c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0)) == -1) {
    3804           0 :                                         c = ' ';
    3805             :                                 }
    3806           0 :                                 for (; padlen > 0; padlen--) {
    3807           0 :                                         putchar(c);
    3808             :                                 }
    3809           0 :                                 selcol++;
    3810           0 :                                 if ((colid + 1) < num_cols) {
    3811             :                                         i = 0;
    3812           0 :                                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i++)) != -1) {
    3813             :                                                 putchar(c);
    3814             :                                         }
    3815             :                                 }
    3816             :                         }
    3817             :                         i = 0;
    3818           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i++)) != -1) {
    3819             :                                 putchar(c);
    3820             :                         }
    3821             :                 }
    3822             :         }
    3823             : 
    3824          60 :         free(col_printlens);
    3825             : 
    3826          60 :         return SUCCEED;
    3827             : }
    3828             : 
    3829             : static int
    3830        1560 : _get_printable_size(TDSCOLUMN * colinfo)
    3831             : {
    3832        1560 :         switch (tds_get_conversion_type(colinfo->column_type, colinfo->column_size)) {
    3833             :         case SYBUINT1:
    3834             :         case SYBINT1:
    3835             :                 return 3;
    3836           0 :         case SYBSINT1:
    3837           0 :                 return 4;
    3838           0 :         case SYBUINT2:
    3839           0 :                 return 5;
    3840         522 :         case SYBINT2:
    3841         522 :                 return 6;
    3842           0 :         case SYBUINT4:
    3843           0 :                 return 10;
    3844         258 :         case SYBINT4:
    3845         258 :                 return 11;
    3846           0 :         case SYBUINT8:
    3847           0 :                 return 20;
    3848           0 :         case SYBINT8:
    3849           0 :                 return 21;
    3850         780 :         case SYBVARCHAR:
    3851             :         case SYBCHAR:
    3852             :         case SYBTEXT:
    3853             :         case SYBNTEXT:
    3854             :         case SYBUNITEXT:
    3855             :         case SYBNVARCHAR:
    3856             :         case SYBLONGCHAR:
    3857         780 :                 return colinfo->column_size;
    3858           0 :         case SYBBINARY:
    3859             :         case SYBIMAGE:
    3860             :         case SYBLONGBINARY:
    3861             :         case SYBVARBINARY:
    3862           0 :                 return colinfo->column_size * 2u;
    3863           0 :         case SYBREAL:
    3864           0 :                 return 14;      /* FIX ME -- we do not track precision */
    3865           0 :         case SYBFLT8:
    3866           0 :                 return 24;      /* FIX ME -- we do not track precision */
    3867           0 :         case SYBMONEY4:
    3868           0 :                 return 12;
    3869           0 :         case SYBMONEY:
    3870           0 :                 return 22;
    3871           0 :         case SYB5BIGDATETIME:
    3872             :         case SYBDATETIME:
    3873             :         case SYBDATETIME4:
    3874           0 :                 return 26;
    3875           0 :         case SYBTIME:
    3876             :         case SYB5BIGTIME:
    3877           0 :                 return 15;
    3878           0 :         case SYBMSTIME:
    3879           0 :                 return 16;
    3880           0 :         case SYBDATE:
    3881             :         case SYBMSDATE:
    3882           0 :                 return 10;
    3883           0 :         case SYBMSDATETIME2:
    3884           0 :                 return 27;
    3885           0 :         case SYBMSDATETIMEOFFSET:
    3886           0 :                 return 33;
    3887           0 :         case SYBUNIQUE:
    3888           0 :                 return 36;
    3889           0 :         case SYBBIT:
    3890           0 :                 return 1;
    3891           0 :         case SYBNUMERIC:
    3892             :         case SYBDECIMAL:
    3893           0 :                 return colinfo->column_prec + 2;
    3894             :                 /* FIX ME -- not all types present */
    3895           0 :         case SYBVOID: /* or 4 bytes for "null" ? */
    3896             :         default:
    3897           0 :                 return 0;
    3898             :         }
    3899             : }
    3900             : 
    3901             : /**
    3902             :  * \ingroup dblib_core
    3903             :  * \brief Get formatted string for underlining dbsprhead() column names.  
    3904             :  * 
    3905             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3906             :  * \param buffer output buffer
    3907             :  * \param buf_len size of \a buffer
    3908             :  * \param line_char character to use to represent underlining.
    3909             :  * \retval SUCCEED \a buffer filled.
    3910             :  * \retval FAIL insufficient space in \a buffer, usually.
    3911             :  * \sa dbprhead(), dbprrow(), dbspr1row(), dbspr1rowlen(), dbsprhead(). 
    3912             :  */
    3913             : RETCODE
    3914           0 : dbsprline(DBPROCESS * dbproc, char *buffer, DBINT buf_len, DBCHAR line_char)
    3915             : {
    3916             :         TDSCOLUMN *colinfo;
    3917             :         TDSRESULTINFO *resinfo;
    3918             :         TDSSOCKET *tds;
    3919             :         size_t i, col, len, collen, namlen;
    3920             :         int c;
    3921             : 
    3922           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsprline(%p, %s, %d, '%c')\n", dbproc, buffer, buf_len, line_char);
    3923           0 :         CHECK_CONN(FAIL);
    3924           0 :         CHECK_NULP(buffer, "dbsprline", 2, FAIL);
    3925             : 
    3926           0 :         tds = dbproc->tds_socket;
    3927           0 :         resinfo = tds->res_info;
    3928             : 
    3929           0 :         for (col = 0; col < resinfo->num_cols; col++) {
    3930           0 :                 colinfo = resinfo->columns[col];
    3931           0 :                 collen = _get_printable_size(colinfo);
    3932           0 :                 namlen = tds_dstr_len(&colinfo->column_name);
    3933           0 :                 len = TDS_MAX(collen, namlen);
    3934           0 :                 for (i = 0; i < len; i++) {
    3935           0 :                         if (buf_len < 1) {
    3936             :                                 return FAIL;
    3937             :                         }
    3938           0 :                         *buffer++ = line_char;
    3939           0 :                         buf_len--;
    3940             :                 }
    3941           0 :                 if ((col + 1) < resinfo->num_cols) {
    3942             :                         i = 0;
    3943           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i)) != -1) {
    3944           0 :                                 if (buf_len < 1) {
    3945             :                                         return FAIL;
    3946             :                                 }
    3947           0 :                                 *buffer++ = c;
    3948           0 :                                 buf_len--;
    3949           0 :                                 i++;
    3950             :                         }
    3951             :                 }
    3952             :         }
    3953           0 :         if (buf_len < 1) {
    3954             :                 return FAIL;
    3955             :         }
    3956           0 :         *buffer = '\0';
    3957           0 :         return SUCCEED;
    3958             : }
    3959             : 
    3960             : /**
    3961             :  * \ingroup dblib_core
    3962             :  * \brief Print result set headings to a buffer.
    3963             :  * 
    3964             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    3965             :  * \param buffer output buffer
    3966             :  * \param buf_len size of \a buffer
    3967             :  * \retval SUCCEED \a buffer filled.
    3968             :  * \retval FAIL insufficient space in \a buffer, usually.
    3969             :  * \sa dbprhead(), dbprrow(), dbsetopt(), dbspr1row(), dbspr1rowlen(), dbsprline().
    3970             :  */
    3971             : RETCODE
    3972           0 : dbsprhead(DBPROCESS * dbproc, char *buffer, DBINT buf_len)
    3973             : {
    3974             :         TDSCOLUMN *colinfo;
    3975             :         TDSRESULTINFO *resinfo;
    3976             :         TDSSOCKET *tds;
    3977             :         int i, collen, namlen;
    3978             :         TDS_USMALLINT col;
    3979             :         int padlen;
    3980             :         int c;
    3981             : 
    3982           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsprhead(%p, %p, %d)\n", dbproc, buffer, buf_len);
    3983           0 :         CHECK_CONN(FAIL);
    3984           0 :         CHECK_NULP(buffer, "dbsprhead", 2, FAIL);
    3985             : 
    3986           0 :         tds = dbproc->tds_socket;
    3987           0 :         resinfo = tds->res_info;
    3988             : 
    3989           0 :         for (col = 0; col < resinfo->num_cols; col++) {
    3990           0 :                 colinfo = resinfo->columns[col];
    3991           0 :                 collen = _get_printable_size(colinfo);
    3992           0 :                 namlen = (int) tds_dstr_len(&colinfo->column_name);
    3993           0 :                 padlen = TDS_MAX(collen, namlen) - namlen;
    3994           0 :                 if (buf_len < namlen) {
    3995             :                         return FAIL;
    3996             :                 }
    3997           0 :                 memcpy(buffer, tds_dstr_cstr(&colinfo->column_name), namlen);
    3998           0 :                 buffer += namlen;
    3999           0 :                 buf_len -= namlen;
    4000           0 :                 if ((c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0)) == -1) {
    4001           0 :                         c = ' ';
    4002             :                 }
    4003           0 :                 for (; padlen > 0; padlen--) {
    4004           0 :                         if (buf_len < 1) {
    4005             :                                 return FAIL;
    4006             :                         }
    4007           0 :                         *buffer++ = c;
    4008           0 :                         buf_len--;
    4009             :                 }
    4010           0 :                 if ((col + 1) < resinfo->num_cols) {
    4011             :                         i = 0;
    4012           0 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i)) != -1) {
    4013           0 :                                 if (buf_len < 1) {
    4014             :                                         return FAIL;
    4015             :                                 }
    4016           0 :                                 *buffer++ = c;
    4017           0 :                                 buf_len--;
    4018           0 :                                 i++;
    4019             :                         }
    4020             :                 }
    4021             :         }
    4022           0 :         if (buf_len < 1) {
    4023             :                 return FAIL;
    4024             :         }
    4025           0 :         *buffer = '\0';
    4026           0 :         return SUCCEED;
    4027             : }
    4028             : 
    4029             : /**
    4030             :  * \ingroup dblib_core
    4031             :  * \brief Print result set headings to stdout.
    4032             :  * 
    4033             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4034             :  * \sa 
    4035             :  */
    4036             : void
    4037          60 : dbprhead(DBPROCESS * dbproc)
    4038             : {
    4039             :         TDSCOLUMN *colinfo;
    4040             :         TDSRESULTINFO *resinfo;
    4041             :         TDSSOCKET *tds;
    4042             :         size_t i, col, len, collen, namlen;
    4043             :         size_t padlen;
    4044             :         int c;
    4045             : 
    4046          60 :         tdsdump_log(TDS_DBG_FUNC, "dbprhead(%p)\n", dbproc);
    4047          60 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    4048             : 
    4049          60 :         tds = dbproc->tds_socket;
    4050          60 :         resinfo = tds->res_info;
    4051          60 :         if (resinfo == NULL) {
    4052             :                 return;
    4053             :         }
    4054         100 :         for (col = 0; col < resinfo->num_cols; col++) {
    4055          80 :                 colinfo = resinfo->columns[col];
    4056          80 :                 collen = _get_printable_size(colinfo);
    4057         160 :                 namlen = tds_dstr_len(&colinfo->column_name);
    4058          80 :                 padlen = TDS_MAX(collen, namlen) - namlen;
    4059         160 :                 printf("%s", tds_dstr_cstr(&colinfo->column_name));
    4060             : 
    4061         160 :                 c = dbstring_getchar(dbproc->dbopts[DBPRPAD].param, 0);
    4062          80 :                 if (c == -1) {
    4063           0 :                         c = ' ';
    4064             :                 }
    4065         600 :                 for (; padlen > 0; padlen--) {
    4066         600 :                         putchar(c);
    4067             :                 }
    4068             : 
    4069          80 :                 if ((col + 1) < resinfo->num_cols) {
    4070             :                         i = 0;
    4071         240 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i)) != -1) {
    4072          60 :                                 putchar(c);
    4073          60 :                                 i++;
    4074             :                         }
    4075             :                 }
    4076             :         }
    4077             :         i = 0;
    4078          80 :         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i)) != -1) {
    4079          20 :                 putchar(c);
    4080          20 :                 i++;
    4081             :         }
    4082         100 :         for (col = 0; col < resinfo->num_cols; col++) {
    4083          80 :                 colinfo = resinfo->columns[col];
    4084          80 :                 collen = _get_printable_size(colinfo);
    4085         160 :                 namlen = tds_dstr_len(&colinfo->column_name);
    4086          80 :                 len = TDS_MAX(collen, namlen);
    4087        1040 :                 for (i = 0; i < len; i++)
    4088         960 :                         putchar('-');
    4089          80 :                 if ((col + 1) < resinfo->num_cols) {
    4090             :                         i = 0;
    4091         240 :                         while ((c = dbstring_getchar(dbproc->dbopts[DBPRCOLSEP].param, i)) != -1) {
    4092          60 :                                 putchar(c);
    4093          60 :                                 i++;
    4094             :                         }
    4095             :                 }
    4096             :         }
    4097             :         i = 0;
    4098          80 :         while ((c = dbstring_getchar(dbproc->dbopts[DBPRLINESEP].param, i)) != -1) {
    4099          20 :                 putchar(c);
    4100          20 :                 i++;
    4101             :         }
    4102             : }
    4103             : 
    4104             : /** \internal
    4105             :  * \ingroup dblib_internal
    4106             :  * \brief Indicate whether a query returned rows.
    4107             :  * 
    4108             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4109             :  * \sa DBROWS(), DBCMDROW(), dbnextrow(), dbresults(), DBROWTYPE().
    4110             :  */
    4111             : RETCODE
    4112         522 : dbrows(DBPROCESS * dbproc)
    4113             : {
    4114             :         TDSSOCKET *tds;
    4115             : 
    4116         522 :         tdsdump_log(TDS_DBG_FUNC, "dbrows(%p)\n", dbproc);
    4117         522 :         CHECK_CONN(FAIL);
    4118             : 
    4119         522 :         if (!(tds=dbproc->tds_socket))
    4120             :                 return FAIL;
    4121             : 
    4122         522 :         return (tds->res_info && tds->res_info->rows_exist)? SUCCEED : FAIL;
    4123             : }
    4124             : 
    4125             : #if defined(DBLIB_UNIMPLEMENTED)
    4126             : /**
    4127             :  * \ingroup dblib_core
    4128             :  * \brief Set the default character set for an application.
    4129             :  * 
    4130             :  * \param language ASCII null-terminated string.  
    4131             :  * \sa dbsetdeflang(), dbsetdefcharset(), dblogin(), dbopen().
    4132             :  * \retval SUCCEED Always.  
    4133             :  * \todo Unimplemented.
    4134             :  */
    4135             : RETCODE
    4136             : dbsetdeflang(char *language)
    4137             : {
    4138             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetdeflang(%s)\n", language);
    4139             :         CHECK_PARAMETER_NOPROC(language, SYBENULP);
    4140             :         return SUCCEED;
    4141             : }
    4142             : #endif
    4143             : 
    4144             : /**
    4145             :  * \ingroup dblib_core
    4146             :  * \brief Get TDS packet size for the connection.
    4147             :  * 
    4148             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4149             :  * \return TDS packet size, in bytes.  
    4150             :  * \sa DBSETLPACKET()
    4151             :  */
    4152             : int
    4153           0 : dbgetpacket(DBPROCESS * dbproc)
    4154             : {
    4155             :         TDSSOCKET *tds;
    4156             : 
    4157           0 :         tdsdump_log(TDS_DBG_FUNC, "dbgetpacket(%p)\n", dbproc);
    4158           0 :         CHECK_PARAMETER(dbproc, SYBENULL, TDS_DEF_BLKSZ);
    4159             : 
    4160           0 :         tds = dbproc->tds_socket;
    4161           0 :         if (!tds) {
    4162             :                 return TDS_DEF_BLKSZ;
    4163             :         } else {
    4164           0 :                 return tds->conn->env.block_size;
    4165             :         }
    4166             : }
    4167             : 
    4168             : /**
    4169             :  * \ingroup dblib_core
    4170             :  * \brief Set maximum simultaneous connections db-lib will open to the server.
    4171             :  * 
    4172             :  * \param maxprocs Limit for process.
    4173             :  * \retval SUCCEED Always.  
    4174             :  * \sa dbgetmaxprocs(), dbopen()
    4175             :  */
    4176             : RETCODE
    4177         250 : dbsetmaxprocs(int maxprocs)
    4178             : {
    4179             :         int i, j;
    4180             :         TDSSOCKET **old_list;
    4181             : 
    4182         250 :         tdsdump_log(TDS_DBG_FUNC, "UNTESTED dbsetmaxprocs(%d)\n", maxprocs);
    4183             : 
    4184             :         /* not too few elements */
    4185         250 :         if (maxprocs <= 0)
    4186             :                 return FAIL;
    4187             : 
    4188         250 :         tds_mutex_lock(&dblib_mutex);
    4189             : 
    4190         250 :         old_list = g_dblib_ctx.connection_list;
    4191             : 
    4192             :         /* "compress" array */
    4193     1024250 :         for (i = 0, j = 0; i < g_dblib_ctx.connection_list_size; ++i) {
    4194     1024000 :                 if (!old_list[i])
    4195     1024000 :                         continue;
    4196           0 :                 if (i != j) {
    4197           0 :                         old_list[j] = old_list[i];
    4198           0 :                         old_list[i] = NULL;
    4199             :                 }
    4200           0 :                 ++j;
    4201             :         }
    4202             :         /* do not restrict too much, j here contains minimun size */
    4203         250 :         if (maxprocs < j)
    4204           0 :                 maxprocs = j;
    4205             : 
    4206             :         /*
    4207             :          * Don't reallocate less memory.  
    4208             :          * If maxprocs is less than was initially allocated, just reduce the represented list size.  
    4209             :          * If larger, reallocate and copy.
    4210             :          * We probably should check for valid connections beyond the new max.
    4211             :          */
    4212         250 :         if (maxprocs <= g_dblib_ctx.connection_list_size) {
    4213         250 :                 g_dblib_ctx.connection_list_size_represented = maxprocs;
    4214         250 :                 tds_mutex_unlock(&dblib_mutex);
    4215         250 :                 return SUCCEED;
    4216             :         }
    4217             : 
    4218           0 :         g_dblib_ctx.connection_list = tds_new0(TDSSOCKET *, maxprocs);
    4219             : 
    4220           0 :         if (g_dblib_ctx.connection_list == NULL) {
    4221           0 :                 g_dblib_ctx.connection_list = old_list;
    4222           0 :                 tds_mutex_unlock(&dblib_mutex);
    4223           0 :                 dbperror(NULL, SYBEMEM, errno);
    4224           0 :                 return FAIL;
    4225             :         }
    4226             : 
    4227           0 :         for (i = 0; i < g_dblib_ctx.connection_list_size; i++) {
    4228           0 :                 g_dblib_ctx.connection_list[i] = old_list[i];
    4229             :         }
    4230             : 
    4231           0 :         g_dblib_ctx.connection_list_size = maxprocs;
    4232           0 :         g_dblib_ctx.connection_list_size_represented = maxprocs;
    4233             : 
    4234           0 :         tds_mutex_unlock(&dblib_mutex);
    4235             : 
    4236           0 :         free(old_list);
    4237             : 
    4238           0 :         return SUCCEED;
    4239             : }
    4240             : 
    4241             : /**
    4242             :  * \ingroup dblib_core
    4243             :  * \brief get maximum simultaneous connections db-lib will open to the server.
    4244             :  * 
    4245             :  * \return Current maximum.  
    4246             :  * \sa dbsetmaxprocs(), dbopen()
    4247             :  */
    4248             : int
    4249           0 : dbgetmaxprocs(void)
    4250             : {
    4251             :         int r;
    4252             : 
    4253           0 :         tdsdump_log(TDS_DBG_FUNC, "dbgetmaxprocs(void)\n");
    4254             : 
    4255           0 :         tds_mutex_lock(&dblib_mutex);
    4256           0 :         r = g_dblib_ctx.connection_list_size_represented;
    4257           0 :         tds_mutex_unlock(&dblib_mutex);
    4258           0 :         return r;
    4259             : }
    4260             : 
    4261             : /**
    4262             :  * \ingroup dblib_core
    4263             :  * \brief Set maximum seconds db-lib waits for a server response to query.  
    4264             :  * 
    4265             :  * \param seconds New limit for application.  
    4266             :  * \retval SUCCEED Always.  
    4267             :  * \sa dberrhandle(), DBGETTIME(), dbsetlogintime(), dbsqlexec(), dbsqlok(), dbsqlsend().
    4268             :  */
    4269             : RETCODE
    4270          70 : dbsettime(int seconds)
    4271             : {
    4272             :         TDSSOCKET **tds;
    4273             :         int i;
    4274             :         DBPROCESS *dbproc;
    4275          70 :         tdsdump_log(TDS_DBG_FUNC, "dbsettime(%d)\n", seconds);
    4276             : 
    4277          70 :         tds_mutex_lock(&dblib_mutex);
    4278          70 :         g_dblib_ctx.query_timeout = seconds;
    4279             :         
    4280          70 :         tds = g_dblib_ctx.connection_list;
    4281      286790 :         for (i = 0; i <  TDS_MAX_CONN; i++) {
    4282      286720 :                 if (tds[i]) {
    4283         100 :                         dbproc = (DBPROCESS *) tds_get_parent(tds[i]);
    4284         100 :                         if (!dbisopt(dbproc, DBSETTIME, 0))
    4285          80 :                                 tds[i]->query_timeout = seconds;
    4286             :                 }
    4287             :         }
    4288             :         
    4289          70 :         tds_mutex_unlock(&dblib_mutex);
    4290          70 :         return SUCCEED;
    4291             : }
    4292             : 
    4293             : /**
    4294             :  * \ingroup dblib_core
    4295             :  * \brief Get maximum seconds db-lib waits for a server response to query.  
    4296             :  * 
    4297             :  * \retval query timeout limit, in seconds
    4298             :  * \sa dberrhandle(), DBSETTIME(), dbsetlogintime(), dbsqlexec(), dbsqlok(), dbsqlsend().
    4299             :  */
    4300             : int
    4301           0 : dbgettime(void)
    4302             : {
    4303           0 :         tdsdump_log(TDS_DBG_FUNC, "dbgettime()\n");
    4304             : 
    4305           0 :         return g_dblib_ctx.query_timeout;
    4306             : }
    4307             : 
    4308             : /**
    4309             :  * \ingroup dblib_core
    4310             :  * \brief Set maximum seconds db-lib waits for a server response to a login attempt.  
    4311             :  * 
    4312             :  * \param seconds New limit for application.  
    4313             :  * \retval SUCCEED Always.  
    4314             :  * \sa dberrhandle(), dbsettime()
    4315             :  */
    4316             : RETCODE
    4317          20 : dbsetlogintime(int seconds)
    4318             : {
    4319          20 :         tdsdump_log(TDS_DBG_FUNC, "dbsetlogintime(%d)\n", seconds);
    4320             : 
    4321          20 :         tds_mutex_lock(&dblib_mutex);
    4322          20 :         g_dblib_ctx.login_timeout = seconds;
    4323          20 :         tds_mutex_unlock(&dblib_mutex);
    4324          20 :         return SUCCEED;
    4325             : }
    4326             : 
    4327             : /** \internal
    4328             :  * \ingroup dblib_internal
    4329             :  * \brief See if the current command can return rows.
    4330             :  * 
    4331             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4332             :  * \retval SUCCEED Yes, it can.  
    4333             :  * \retval FAIL No, it can't.
    4334             :  * \remarks Use   DBCMDROW() macro instead.  
    4335             :  * \sa DBCMDROW(), dbnextrow(), dbresults(), DBROWS(), DBROWTYPE().
    4336             :  */
    4337             : RETCODE
    4338           0 : dbcmdrow(DBPROCESS * dbproc)
    4339             : {
    4340             :         TDSSOCKET *tds;
    4341             : 
    4342           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcmdrow(%p)\n", dbproc);
    4343           0 :         CHECK_CONN(FAIL);
    4344             : 
    4345           0 :         tds = dbproc->tds_socket;
    4346           0 :         if (tds->res_info)
    4347             :                 return SUCCEED;
    4348           0 :         return FAIL;
    4349             : }
    4350             : 
    4351             : /**
    4352             :  * \ingroup dblib_core
    4353             :  * \brief Get column ID of a compute column.
    4354             :  * 
    4355             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4356             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4357             :  * \param column Nth column in \a computeid, starting from 1.
    4358             :  * \return Nth column in the base result set, on which \a column was computed.  
    4359             :  * \sa dbadata(), dbadlen(), dbaltlen(), dbgetrow(), dbnextrow(), dbnumalts(), dbprtype(). 
    4360             :  */
    4361             : int
    4362          16 : dbaltcolid(DBPROCESS * dbproc, int computeid, int column)
    4363             : {
    4364             :         TDSCOLUMN *curcol;
    4365             : 
    4366          16 :         tdsdump_log(TDS_DBG_FUNC, "dbaltcolid(%p, %d, %d)\n", dbproc, computeid, column);
    4367             : 
    4368          16 :         curcol = dbacolptr(dbproc, computeid, column, false);
    4369          16 :         if (!curcol)
    4370             :                 return -1;
    4371             : 
    4372          16 :         return curcol->column_operand;
    4373             : }
    4374             : 
    4375             : /**
    4376             :  * \ingroup dblib_core
    4377             :  * \brief Get size of data in a compute column.
    4378             :  * 
    4379             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4380             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4381             :  * \param column Nth column in \a computeid, starting from 1.
    4382             :  * \return size of the data, in bytes.
    4383             :  * \retval -1 no such \a column or \a computeid. 
    4384             :  * \retval 0 data are NULL.
    4385             :  * \sa dbadata(), dbaltlen(), dbalttype(), dbgetrow(), dbnextrow(), dbnumalts().
    4386             :  */
    4387             : DBINT
    4388           0 : dbadlen(DBPROCESS * dbproc, int computeid, int column)
    4389             : {
    4390             :         TDSCOLUMN *colinfo;
    4391             :         DBINT len;
    4392             : 
    4393           0 :         tdsdump_log(TDS_DBG_FUNC, "dbadlen(%p, %d, %d)\n", dbproc, computeid, column);
    4394             : 
    4395           0 :         colinfo = dbacolptr(dbproc, computeid, column, false);
    4396           0 :         if (!colinfo)
    4397             :                 return -1;
    4398             : 
    4399           0 :         len = TDS_MAX(colinfo->column_cur_size, 0);
    4400             : 
    4401           0 :         tdsdump_log(TDS_DBG_FUNC, "leaving dbadlen() type = %d, returning %d\n", colinfo->column_type, len);
    4402             : 
    4403             :         return len;
    4404             : }
    4405             : 
    4406             : /**
    4407             :  * \ingroup dblib_core
    4408             :  * \brief Get datatype for a compute column.
    4409             :  * 
    4410             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4411             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4412             :  * \param column Nth column in \a computeid, starting from 1.
    4413             :  * \return \c SYB* dataype token.
    4414             :  * \retval -1 no such \a column or \a computeid. 
    4415             :  * \sa dbadata(), dbadlen(), dbaltlen(), dbnextrow(), dbnumalts(), dbprtype().
    4416             :  */
    4417             : int
    4418          16 : dbalttype(DBPROCESS * dbproc, int computeid, int column)
    4419             : {
    4420             :         TDSCOLUMN *colinfo;
    4421             : 
    4422          16 :         tdsdump_log(TDS_DBG_FUNC, "dbalttype(%p, %d, %d)\n", dbproc, computeid, column);
    4423             : 
    4424          16 :         colinfo = dbacolptr(dbproc, computeid, column, false);
    4425          16 :         if (!colinfo)
    4426             :                 return -1;
    4427             : 
    4428          16 :         return dblib_coltype(colinfo);
    4429             : }
    4430             : 
    4431             : /**
    4432             :  * \ingroup dblib_core
    4433             :  * \brief Bind a compute column to a program variable.
    4434             :  * 
    4435             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4436             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4437             :  * \param column Nth column in \a computeid, starting from 1.
    4438             :  * \param vartype datatype of the host variable that will receive the data
    4439             :  * \param varlen size of host variable pointed to \a varaddr
    4440             :  * \param varaddr address of host variable
    4441             :  * \retval SUCCEED everything worked.
    4442             :  * \retval FAIL no such \a computeid or \a column, or no such conversion possible, or target buffer too small.
    4443             :  * \sa dbadata(), dbaltbind_ps(), dbanullbind(), dbbind(), dbbind_ps(), dbconvert(),
    4444             :  *      dbconvert_ps(), dbnullbind(), dbsetnull(), dbsetversion(), dbwillconvert().
    4445             :  */
    4446             : RETCODE
    4447          16 : dbaltbind(DBPROCESS * dbproc, int computeid, int column, int vartype, DBINT varlen, BYTE * varaddr)
    4448             : {
    4449             :         TDS_SERVER_TYPE srctype, desttype;
    4450          16 :         TDSCOLUMN *colinfo = NULL;
    4451             : 
    4452          16 :         tdsdump_log(TDS_DBG_FUNC, "dbaltbind(%p, %d, %d, %d, %d, %p)\n", dbproc, computeid, column, vartype, varlen, varaddr);
    4453             : 
    4454          16 :         colinfo = dbacolptr(dbproc, computeid, column, true);
    4455          16 :         if (!colinfo)
    4456             :                 return FAIL;
    4457          16 :         CHECK_PARAMETER(varaddr, SYBEABNV, FAIL);
    4458             : 
    4459          16 :         dbproc->avail_flag = FALSE;
    4460             : 
    4461          16 :         srctype = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    4462          16 :         desttype = dblib_bound_type(vartype);
    4463          16 :         if (desttype == TDS_INVALID_TYPE) {
    4464           0 :                 dbperror(dbproc, SYBEBTYP, 0);
    4465           0 :                 return FAIL;
    4466             :         }
    4467             : 
    4468          16 :         if (!dbwillconvert(srctype, desttype)) {
    4469           0 :                 dbperror(dbproc, SYBEAAMT, 0);
    4470           0 :                 return FAIL;
    4471             :         }
    4472             : 
    4473          16 :         colinfo->column_varaddr = (char *) varaddr;
    4474          16 :         colinfo->column_bindtype = vartype;
    4475          16 :         colinfo->column_bindlen = varlen;
    4476             : 
    4477          16 :         return SUCCEED;
    4478             : }
    4479             : 
    4480             : 
    4481             : /**
    4482             :  * \ingroup dblib_core
    4483             :  * \brief Get address of compute column data.  
    4484             :  * 
    4485             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4486             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4487             :  * \param column Nth column in \a computeid, starting from 1.
    4488             :  * \return pointer to columns's data buffer.  
    4489             :  * \retval NULL no such \a computeid or \a column.  
    4490             :  * \sa dbadlen(), dbaltbind(), dbaltlen(), dbalttype(), dbgetrow(), dbnextrow(), dbnumalts().
    4491             :  */
    4492             : BYTE *
    4493           0 : dbadata(DBPROCESS * dbproc, int computeid, int column)
    4494             : {
    4495             :         TDSCOLUMN *colinfo;
    4496             : 
    4497           0 :         tdsdump_log(TDS_DBG_FUNC, "dbadata(%p, %d, %d)\n", dbproc, computeid, column);
    4498             : 
    4499           0 :         colinfo = dbacolptr(dbproc, computeid, column, false);
    4500           0 :         if (!colinfo)
    4501             :                 return NULL;
    4502             : 
    4503           0 :         if (is_blob_col(colinfo)) {
    4504           0 :                 return (BYTE *) ((TDSBLOB *) colinfo->column_data)->textvalue;
    4505             :         }
    4506             : 
    4507           0 :         return (BYTE *) colinfo->column_data;
    4508             : }
    4509             : 
    4510             : /**
    4511             :  * \ingroup dblib_core
    4512             :  * \brief Get aggregation operator for a compute column.
    4513             :  * 
    4514             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4515             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    4516             :  * \param column Nth column in \a computeid, starting from 1.
    4517             :  * \return token value for the type of the compute column's aggregation operator.
    4518             :  * \retval -1 no such \a computeid or \a column.  
    4519             :  * \sa dbadata(), dbadlen(), dbaltlen(), dbnextrow(), dbnumalts(), dbprtype().
    4520             :  */
    4521             : int
    4522          16 : dbaltop(DBPROCESS * dbproc, int computeid, int column)
    4523             : {
    4524             :         TDSCOLUMN *curcol;
    4525             : 
    4526          16 :         tdsdump_log(TDS_DBG_FUNC, "dbaltop(%p, %d, %d)\n", dbproc, computeid, column);
    4527             : 
    4528          16 :         if ((curcol=dbacolptr(dbproc, computeid, column, false)) == NULL)
    4529             :                 return -1;
    4530             : 
    4531          16 :         return curcol->column_operator;
    4532             : }
    4533             : 
    4534             : /**
    4535             :  * \ingroup dblib_core
    4536             :  * \brief Set db-lib or server option.
    4537             :  * 
    4538             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4539             :  * \param option option to set.  
    4540             :  * \param char_param value to set \a option to, if it wants a null-teminated ASCII string.  
    4541             :  * \param int_param  value to set \a option to, if it wants an integer value.  
    4542             :  * \retval SUCCEED everything worked.
    4543             :  * \retval FAIL no such \a option, or insufficient memory, or unimplemented.  
    4544             :  * \remarks Many are unimplemented.
    4545             :  * \sa dbclropt(), dbisopt().
    4546             :  * \todo Implement more options.  
    4547             :  */
    4548             : RETCODE
    4549          90 : dbsetopt(DBPROCESS * dbproc, int option, const char *char_param, int int_param)
    4550             : {
    4551             :         char *cmd;
    4552             :         RETCODE rc;
    4553             :         int i;
    4554             : 
    4555          90 :         tdsdump_log(TDS_DBG_FUNC, "dbsetopt(%p, %d, %s, %d)\n", dbproc, option, char_param, int_param);
    4556          90 :         CHECK_CONN(FAIL);
    4557          90 :         CHECK_NULP(char_param, "dbsetopt", 3, FAIL);
    4558             : 
    4559          90 :         if ((option < 0) || (option >= DBNUMOPTIONS)) {
    4560           0 :                 dbperror(dbproc, SYBEUNOP, 0);
    4561           0 :                 return FAIL;
    4562             :         }
    4563             : 
    4564          90 :         rc = FAIL;
    4565          90 :         switch (option) {
    4566           0 :         case DBARITHABORT:
    4567             :         case DBARITHIGNORE:
    4568             :         case DBCHAINXACTS:
    4569             :         case DBFIPSFLAG:
    4570             :         case DBISOLATION:
    4571             :         case DBNOCOUNT:
    4572             :         case DBNOEXEC:
    4573             :         case DBPARSEONLY:
    4574             :         case DBSHOWPLAN:
    4575             :         case DBSTORPROCID:
    4576             :         case DBQUOTEDIDENT:
    4577             :                 /* server options (on/off) */
    4578           0 :                 if (asprintf(&cmd, "set %s on\n", dbproc->dbopts[option].text) < 0) {
    4579             :                         return FAIL;
    4580             :                 }
    4581           0 :                 rc = dbstring_concat(&(dbproc->dboptcmd), cmd);
    4582           0 :                 free(cmd);
    4583           0 :                 break;
    4584           0 :         case DBNATLANG:
    4585             :         case DBDATEFIRST:
    4586             :         case DBDATEFORMAT:
    4587             :                 /* server options (char_param) */
    4588           0 :                 if (asprintf(&cmd, "set %s %s\n", dbproc->dbopts[option].text, char_param) < 0) {
    4589             :                         return FAIL;
    4590             :                 }
    4591           0 :                 rc = dbstring_concat(&(dbproc->dboptcmd), cmd);
    4592           0 :                 free(cmd);
    4593           0 :                 break;
    4594             :         case DBOFFSET:
    4595             :                 /* server option */
    4596             :                 /* requires param
    4597             :                  * "select", "from", "table", "order", "compute",
    4598             :                  * "statement", "procedure", "execute", or "param"
    4599             :                  */
    4600             :                 rc = SUCCEED;
    4601             :                 break;
    4602             :         case DBROWCOUNT:
    4603             :                 /* server option */
    4604             :                 /* requires param "0" to "2147483647" */
    4605             :                 rc = SUCCEED;
    4606             :                 break;
    4607             :         case DBSTAT:
    4608             :                 /* server option */
    4609             :                 /* requires param "io" or "time" */
    4610             :                 rc = SUCCEED;
    4611             :                 break;
    4612             :         case DBTEXTLIMIT:
    4613             :                 /* dblib option */
    4614             :                 /* requires param "0" to "2147483647" */
    4615             :                 /* dblib do not return more than this length from text/image */
    4616             :                 /* TODO required for PHP */
    4617             :                 rc = SUCCEED;
    4618             :                 break;
    4619             :         case DBTEXTSIZE:
    4620             :                 /* server option */
    4621             :                 /* requires param "0" to "2147483647" */
    4622             :                 /* limit text/image from network */
    4623             :                 if (!char_param)
    4624             :                         char_param = "0";
    4625           0 :                 i = atoi(char_param);
    4626           0 :                 if (i < 0 || i > 2147483647)
    4627             :                         return FAIL;
    4628           0 :                 if (asprintf(&cmd, "set textsize %d\n", i) < 0)
    4629             :                         return FAIL;
    4630           0 :                 rc = dbstring_concat(&(dbproc->dboptcmd), cmd);
    4631           0 :                 free(cmd);
    4632           0 :                 break;
    4633             :         case DBAUTH:
    4634             :                 /* ??? */
    4635             :                 rc = SUCCEED;
    4636             :                 break;
    4637             :         case DBNOAUTOFREE:
    4638             :                 /* dblib option */
    4639             :                 rc = SUCCEED;
    4640             :                 break;
    4641             :         case DBBUFFER:
    4642             :                 /* 
    4643             :                  * Requires param "2" to "2147483647" 
    4644             :                  * (0 or 1 is an error, < 0 yields the default 100) 
    4645             :                  */
    4646             :                 {
    4647             :                         int nrows; 
    4648             :                         
    4649             :                         /* 100 is the default, according to Microsoft */
    4650             :                         if( !char_param )
    4651             :                                 char_param = "100";
    4652             : 
    4653          60 :                         nrows = atoi(char_param);
    4654             : 
    4655          60 :                         nrows = (nrows < 0 )? 100 : nrows;
    4656             : 
    4657          60 :                         if( 1 < nrows && nrows <= 2147483647 ) {
    4658          60 :                                 buffer_set_capacity(dbproc, nrows);
    4659          60 :                                 rc = SUCCEED;
    4660             :                         }
    4661             :                 }
    4662             :                 break;
    4663           0 :         case DBPRCOLSEP:
    4664             :         case DBPRLINELEN:
    4665             :         case DBPRLINESEP:
    4666           0 :                 rc = dbstring_assign(&(dbproc->dbopts[option].param), char_param);
    4667           0 :                 break;
    4668           0 :         case DBPRPAD:
    4669             :                 /*
    4670             :                  * "If the character is not specified, the ASCII space character is used." 
    4671             :                  * A NULL pointer to the pad character signifies that padding is turned off. 
    4672             :                  */
    4673           0 :                 if (int_param) {
    4674           0 :                         rc = dbstring_assign(&(dbproc->dbopts[option].param), char_param? char_param : " ");
    4675             :                 } else {
    4676           0 :                         rc = dbstring_assign(&(dbproc->dbopts[option].param), NULL);
    4677             :                 }
    4678             :                 break;
    4679             :         case DBSETTIME:
    4680             :                 if (char_param) {
    4681          30 :                         i = atoi(char_param);
    4682          30 :                         if (0 < i) {
    4683          60 :                                 rc = dbstring_assign(&(dbproc->dbopts[option].param), char_param);
    4684          30 :                                 if (rc == SUCCEED) {
    4685          30 :                                         dbproc->tds_socket->query_timeout = i;
    4686             :                                 }
    4687             :                         }
    4688             :                 }
    4689             :                 break;
    4690           0 :         default:
    4691           0 :                 tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetopt(option = %d)\n", option);
    4692             :                 return FAIL;
    4693             :         }
    4694          30 :         if (rc == SUCCEED)
    4695          90 :                 dbproc->dbopts[option].factive = 1;
    4696             :         return rc;
    4697             : }
    4698             : 
    4699             : /**
    4700             :  * \ingroup dblib_core
    4701             :  * \brief Set interrupt handler for db-lib to use while blocked against a read from the server.
    4702             :  * 
    4703             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4704             :  * \param chkintr
    4705             :  * \param hndlintr
    4706             :  * \sa dbcancel(), dbgetuserdata(), dbsetuserdata(), dbsetbusy(), dbsetidle().
    4707             :  */
    4708             : void
    4709          20 : dbsetinterrupt(DBPROCESS * dbproc, DB_DBCHKINTR_FUNC chkintr, DB_DBHNDLINTR_FUNC hndlintr)
    4710             : {
    4711          20 :         tdsdump_log(TDS_DBG_FUNC, "dbsetinterrupt(%p, %p, %p)\n", dbproc, chkintr, hndlintr);
    4712          20 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    4713             : 
    4714          20 :         dbproc->chkintr = chkintr;
    4715          20 :         dbproc->hndlintr = hndlintr;
    4716             : }
    4717             : 
    4718             : /**
    4719             :  * \ingroup dblib_rpc
    4720             :  * \brief Determine if query generated a return status number.
    4721             :  * 
    4722             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4723             :  * \retval TRUE fetch return status with dbretstatus().  
    4724             :  * \retval FALSE no return status.  
    4725             :  * \sa dbnextrow(), dbresults(), dbretdata(), dbretstatus(), dbrpcinit(), dbrpcparam(), dbrpcsend().
    4726             :  */
    4727             : DBBOOL
    4728          62 : dbhasretstat(DBPROCESS * dbproc)
    4729             : {
    4730             :         TDSSOCKET *tds;
    4731             : 
    4732          62 :         tdsdump_log(TDS_DBG_FUNC, "dbhasretstat(%p)\n", dbproc);
    4733          62 :         CHECK_PARAMETER(dbproc, SYBENULL, FALSE);
    4734             : 
    4735          62 :         tds = dbproc->tds_socket;
    4736          62 :         if (tds->has_status) {
    4737             :                 return TRUE;
    4738             :         } else {
    4739          30 :                 return FALSE;
    4740             :         }
    4741             : }
    4742             : 
    4743             : /**
    4744             :  * \ingroup dblib_rpc
    4745             :  * \brief Fetch status value returned by query or remote procedure call.
    4746             :  * 
    4747             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4748             :  * \return return value 
    4749             :  * \sa dbhasretstat(), dbnextrow(), dbresults(), dbretdata(), dbrpcinit(), dbrpcparam(), dbrpcsend().
    4750             :  */
    4751             : DBINT
    4752         518 : dbretstatus(DBPROCESS * dbproc)
    4753             : {
    4754         518 :         tdsdump_log(TDS_DBG_FUNC, "dbretstatus(%p)\n", dbproc);
    4755         518 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    4756             : 
    4757         518 :         return dbproc->tds_socket->ret_status;
    4758             : }
    4759             : 
    4760             : /**
    4761             :  * \ingroup dblib_rpc
    4762             :  * \brief Get count of output parameters filled by a stored procedure.
    4763             :  * 
    4764             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4765             :  * \return How many, possibly zero.  
    4766             :  * \remarks This name sounds funny.  
    4767             :  * \sa 
    4768             :  */
    4769             : int
    4770         806 : dbnumrets(DBPROCESS * dbproc)
    4771             : {
    4772             :         TDSSOCKET *tds;
    4773             :         TDS_INT result_type;
    4774             : 
    4775         806 :         tdsdump_log(TDS_DBG_FUNC, "dbnumrets(%p)\n", dbproc);
    4776         806 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    4777             : 
    4778         806 :         tds = dbproc->tds_socket;
    4779             : 
    4780         806 :         tdsdump_log(TDS_DBG_FUNC, "dbnumrets() finds %d columns\n", (tds->param_info? tds->param_info->num_cols : 0));
    4781             : 
    4782             :         /* try to fetch output parameters and return status, if we have not already done so */
    4783         806 :         if (!tds->param_info) 
    4784         508 :                 tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_TRAILING);
    4785             :                 
    4786         806 :         if (!tds->param_info)
    4787             :                 return 0;
    4788             : 
    4789         300 :         return tds->param_info->num_cols;
    4790             : }
    4791             : 
    4792             : /**
    4793             :  * \ingroup dblib_rpc
    4794             :  * \brief Get name of an output parameter filled by a stored procedure.
    4795             :  * 
    4796             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4797             :  * \param retnum Nth parameter between \c 1 and the return value from \c dbnumrets().
    4798             :  * \returns ASCII null-terminated string, \c NULL if no such \a retnum.  
    4799             :  * \sa dbnextrow(), dbnumrets(), dbresults(), dbretdata(), dbretlen(), dbrettype(), dbrpcinit(), dbrpcparam().
    4800             :  */
    4801             : char *
    4802          66 : dbretname(DBPROCESS * dbproc, int retnum)
    4803             : {
    4804             :         TDSPARAMINFO *param_info;
    4805             : 
    4806          66 :         tdsdump_log(TDS_DBG_FUNC, "dbretname(%p, %d)\n", dbproc, retnum);
    4807          66 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    4808             : 
    4809          66 :         if (!dbproc->tds_socket)
    4810             :                 return NULL;
    4811             : 
    4812          66 :         dbnumrets(dbproc);
    4813             : 
    4814          66 :         param_info = dbproc->tds_socket->param_info;
    4815          66 :         if (!param_info || !param_info->columns || retnum < 1 || retnum > param_info->num_cols)
    4816             :                 return NULL;
    4817         132 :         return tds_dstr_buf(&param_info->columns[retnum - 1]->column_name);
    4818             : }
    4819             : 
    4820             : /**
    4821             :  * \ingroup dblib_rpc
    4822             :  * \brief Get value of an output parameter filled by a stored procedure.
    4823             :  * 
    4824             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4825             :  * \param retnum Nth parameter between \c 1 and the return value from \c dbnumrets().
    4826             :  * \returns Address of a return parameter value, or \c NULL if no such \a retnum.  
    4827             :  * \sa dbnextrow(), dbnumrets(), dbresults(), dbretlen(), dbretname(), dbrettype(), dbrpcinit(), dbrpcparam().
    4828             :  * \todo Handle blobs.
    4829             :  */
    4830             : BYTE *
    4831          70 : dbretdata(DBPROCESS * dbproc, int retnum)
    4832             : {
    4833             :         TDSPARAMINFO *param_info;
    4834             : 
    4835          70 :         tdsdump_log(TDS_DBG_FUNC, "dbretdata(%p, %d)\n", dbproc, retnum);
    4836          70 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    4837             : 
    4838          70 :         dbnumrets(dbproc);
    4839             : 
    4840          70 :         param_info = dbproc->tds_socket->param_info;
    4841          70 :         if (!param_info || !param_info->columns || retnum < 1 || retnum > param_info->num_cols)
    4842             :                 return NULL;
    4843             : 
    4844          70 :         return _dbcoldata(param_info->columns[retnum - 1]);
    4845             : }
    4846             : 
    4847             : /**
    4848             :  * \ingroup dblib_rpc
    4849             :  * \brief Get size of an output parameter filled by a stored procedure.
    4850             :  * 
    4851             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4852             :  * \param retnum Nth parameter between \c 1 and the return value from \c dbnumrets().
    4853             :  * \returns Size of a return parameter value, or \c NULL if no such \a retnum.  
    4854             :  * \sa dbnextrow(), dbnumrets(), dbresults(), dbretdata(), dbretname(), dbrettype(), dbrpcinit(), dbrpcparam().
    4855             :  */
    4856             : int
    4857          66 : dbretlen(DBPROCESS * dbproc, int retnum)
    4858             : {
    4859             :         TDSCOLUMN *column;
    4860             :         TDSPARAMINFO *param_info;
    4861             :         TDSSOCKET *tds;
    4862             : 
    4863          66 :         tdsdump_log(TDS_DBG_FUNC, "dbretlen(%p, %d)\n", dbproc, retnum);
    4864          66 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    4865             : 
    4866          66 :         dbnumrets(dbproc);
    4867             : 
    4868          66 :         tds = dbproc->tds_socket;
    4869          66 :         param_info = tds->param_info;
    4870          66 :         if (!param_info || !param_info->columns || retnum < 1 || retnum > param_info->num_cols)
    4871             :                 return -1;
    4872             : 
    4873          66 :         column = param_info->columns[retnum - 1];
    4874          66 :         if (column->column_cur_size < 0)
    4875             :                 return 0;
    4876             : 
    4877          52 :         return column->column_cur_size;
    4878             : }
    4879             : 
    4880             : /**
    4881             :  * \ingroup dblib_core
    4882             :  * \brief Wait for results of a query from the server.  
    4883             :  * 
    4884             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    4885             :  * \retval SUCCEED everything worked, fetch results with \c dbnextresults().
    4886             :  * \retval FAIL SQL syntax error, typically.  
    4887             :  * \sa dbcmd(), dbfcmd(), DBIORDESC(), DBIOWDESC(), dbmoretext(), dbnextrow(),
    4888             :         dbpoll(), DBRBUF(), dbresults(), dbretstatus(), dbrpcsend(), dbsettime(), dbsqlexec(),
    4889             :         dbsqlsend(), dbwritetext().
    4890             :  */
    4891             : RETCODE
    4892       20708 : dbsqlok(DBPROCESS * dbproc)
    4893             : {
    4894             :         TDSSOCKET *tds;
    4895             :         TDS_INT result_type;
    4896       20708 :         RETCODE return_code = SUCCEED;
    4897             : 
    4898       20708 :         tdsdump_log(TDS_DBG_FUNC, "dbsqlok(%p)\n", dbproc);
    4899       20708 :         CHECK_CONN(FAIL);
    4900             : 
    4901       20708 :         tds = dbproc->tds_socket;
    4902             : 
    4903             :         /*
    4904             :          * dbsqlok has been called after dbmoretext()
    4905             :          * This is the trigger to send the text data.
    4906             :          */
    4907             : 
    4908       20708 :         if (dbproc->text_sent) {
    4909           0 :                 tds_flush_packet(tds);
    4910           0 :                 dbproc->text_sent = 0;
    4911             :         }
    4912             : 
    4913             :         /* 
    4914             :          * See what the next packet from the server is.
    4915             :          * We want to skip any messages which are not processable. 
    4916             :          * We're looking for a result token or a done token.
    4917             :          */
    4918         289 :         for (;;) {
    4919             :                 TDSRET tds_code;
    4920       20997 :                 int done_flags = 0;
    4921             : 
    4922             :                 /* 
    4923             :                  * If we hit an end token -- e.g. if the command
    4924             :                  * submitted returned no data (like an insert) -- then
    4925             :                  * we process the end token to extract the status code. 
    4926             :                  */
    4927       20997 :                 tdsdump_log(TDS_DBG_FUNC, "dbsqlok() not done, calling tds_process_tokens()\n");
    4928             : 
    4929       20997 :                 tds_code = tds_process_tokens(tds, &result_type, &done_flags, TDS_TOKEN_RESULTS);
    4930             : 
    4931             :                 /* 
    4932             :                  * The error flag may be set for any intervening DONEINPROC packet, in particular
    4933             :                  * by a RAISERROR statement.  Microsoft db-lib returns FAIL in that case. 
    4934             :                  */
    4935       20997 :                 if (done_flags & TDS_DONE_ERROR) {
    4936          78 :                         return_code = FAIL;
    4937             :                 }
    4938             :                 
    4939       20997 :                 switch (tds_code) {
    4940             :                 case TDS_NO_MORE_RESULTS:
    4941       20708 :                         return SUCCEED;
    4942             :                         break;
    4943             : 
    4944       20939 :                 case TDS_SUCCESS:
    4945       20939 :                         switch (result_type) {
    4946       12190 :                         case TDS_ROWFMT_RESULT:
    4947       12190 :                                 buffer_free(&dbproc->row_buf);
    4948       12190 :                                 buffer_alloc(dbproc);
    4949       12190 :                         case TDS_COMPUTEFMT_RESULT:
    4950       12190 :                                 dbproc->dbresults_state = _DB_RES_RESULTSET_EMPTY;
    4951       12190 :                         case TDS_COMPUTE_RESULT:
    4952             :                         case TDS_ROW_RESULT:
    4953       12190 :                                 tdsdump_log(TDS_DBG_FUNC, "dbsqlok() found result token\n");
    4954             :                                 return SUCCEED;
    4955             :                                 break;
    4956             :                         case TDS_DONEINPROC_RESULT:
    4957             :                                 break;
    4958        8460 :                         case TDS_DONE_RESULT:
    4959             :                         case TDS_DONEPROC_RESULT:
    4960        8460 :                                 tdsdump_log(TDS_DBG_FUNC, "dbsqlok() end status is %d (%s)\n", return_code, prdbretcode(return_code));
    4961             : #if 1
    4962        8460 :                                 if (done_flags & TDS_DONE_ERROR) {
    4963             : 
    4964          78 :                                         if (done_flags & TDS_DONE_MORE_RESULTS) {
    4965           0 :                                                 dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    4966             :                                         } else {
    4967          78 :                                                 dbproc->dbresults_state = _DB_RES_NO_MORE_RESULTS;
    4968             :                                         }
    4969             : 
    4970             :                                 } else {
    4971        8382 :                                         tdsdump_log(TDS_DBG_FUNC, "dbsqlok() end status was success\n");
    4972             : 
    4973        8382 :                                         dbproc->dbresults_state = _DB_RES_SUCCEED;
    4974             :                                 }
    4975             : 
    4976             :                                 return return_code;
    4977             :                                 break;
    4978             : #else
    4979             :                                 int retcode = (done_flags & TDS_DONE_ERROR)? FAIL : SUCCEED;
    4980             :                                 dbproc->dbresults_state = (done_flags & TDS_DONE_MORE_RESULTS)?
    4981             :                                         _DB_RES_NEXT_RESULT : _DB_RES_NO_MORE_RESULTS;
    4982             : 
    4983             :                                 tdsdump_log(TDS_DBG_FUNC, "dbsqlok: returning %s with %s (%#x)\n", 
    4984             :                                                 prdbretcode(retcode), prdbresults_state(dbproc->dbresults_state), done_flags);
    4985             :                                                 
    4986             :                                 if (retcode == SUCCEED && (done_flags & TDS_DONE_MORE_RESULTS))
    4987             :                                         continue;
    4988             :                                          
    4989             :                                 return retcode;
    4990             : #endif
    4991          39 :                         default:
    4992          39 :                                 tdsdump_log(TDS_DBG_FUNC, "%s %d: logic error: tds_process_tokens result_type %d\n", 
    4993             :                                                 __FILE__, __LINE__, result_type);
    4994             :                                 break;
    4995             :                         }
    4996             :                         break;
    4997             : 
    4998          40 :                 default:
    4999          40 :                         assert(TDS_FAILED(tds_code));
    5000             :                         return FAIL;
    5001             :                         break;
    5002             :                 }
    5003             :         }
    5004             : 
    5005             :         return SUCCEED;
    5006             : }
    5007             : 
    5008             : /**
    5009             :  * \ingroup dblib_core
    5010             :  * \brief Get count of columns in a compute row.
    5011             :  * 
    5012             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5013             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    5014             :  * \return number of columns, else -1 if no such \a computeid.  
    5015             :  * \sa dbadata(), dbadlen(), dbaltlen(), dbalttype(), dbgetrow(), dbnextrow(), dbnumcols(). 
    5016             :  */
    5017             : int
    5018          16 : dbnumalts(DBPROCESS * dbproc, int computeid)
    5019             : {
    5020             :         TDSSOCKET *tds;
    5021             :         TDSCOMPUTEINFO *info;
    5022             :         TDS_SMALLINT compute_id;
    5023             :         TDS_UINT i;
    5024             : 
    5025          16 :         tdsdump_log(TDS_DBG_FUNC, "dbnumalts(%p, %d)\n", dbproc, computeid);
    5026          16 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    5027             : 
    5028          16 :         tds = dbproc->tds_socket;
    5029          16 :         compute_id = computeid;
    5030             : 
    5031          24 :         for (i = 0;; ++i) {
    5032          32 :                 if (i >= tds->num_comp_info)
    5033             :                         return -1;
    5034          24 :                 info = tds->comp_info[i];
    5035          24 :                 if (info->computeid == compute_id)
    5036             :                         break;
    5037             :         }
    5038             : 
    5039          16 :         return info->num_cols;
    5040             : }
    5041             : 
    5042             : /**
    5043             :  * \ingroup dblib_core
    5044             :  * \brief Get count of \c COMPUTE clauses for a result set.
    5045             :  * 
    5046             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5047             :  * \return number of compute clauses for the current query, possibly zero.  
    5048             :  * \sa dbnumalts(), dbresults().
    5049             :  */
    5050             : int
    5051           0 : dbnumcompute(DBPROCESS * dbproc)
    5052             : {
    5053             :         TDSSOCKET *tds;
    5054             : 
    5055           0 :         tdsdump_log(TDS_DBG_FUNC, "dbnumcompute(%p)\n", dbproc);
    5056           0 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    5057             : 
    5058           0 :         tds = dbproc->tds_socket;
    5059             : 
    5060           0 :         return tds->num_comp_info;
    5061             : }
    5062             : 
    5063             : 
    5064             : /**
    5065             :  * \ingroup dblib_core
    5066             :  * \brief Get \c bylist for a compute row.
    5067             :  * 
    5068             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5069             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    5070             :  * \param size \em output: size of \c bylist buffer whose address is returned, possibly zero.  
    5071             :  * \return address of \c bylist for \a computeid.  
    5072             :  * \retval NULL no such \a computeid.
    5073             :  * \remarks Do not free returned pointer.  
    5074             :  * \sa dbadata(), dbadlen(), dbaltlen(), dbalttype(), dbcolname(), dbgetrow(), dbnextrow().
    5075             :  */
    5076             : BYTE *
    5077           0 : dbbylist(DBPROCESS * dbproc, int computeid, int *size)
    5078             : {
    5079             :         TDSSOCKET *tds;
    5080             :         TDSCOMPUTEINFO *info;
    5081             :         TDS_UINT i;
    5082           0 :         const TDS_SMALLINT byte_flag = -0x8000;
    5083             : 
    5084           0 :         tdsdump_log(TDS_DBG_FUNC, "dbbylist(%p, %d, %p)\n", dbproc, computeid, size);
    5085           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    5086             : 
    5087           0 :         tds = dbproc->tds_socket;
    5088             : 
    5089           0 :         for (i = 0;; ++i) {
    5090           0 :                 if (i >= tds->num_comp_info) {
    5091           0 :                         if (size)
    5092           0 :                                 *size = 0;
    5093             :                         return NULL;
    5094             :                 }
    5095           0 :                 info = tds->comp_info[i];
    5096           0 :                 if (info->computeid == computeid)
    5097             :                         break;
    5098             :         }
    5099             : 
    5100           0 :         if (size)
    5101           0 :                 *size = info->by_cols;
    5102             : 
    5103             :         /*
    5104             :          * libtds stores this information using TDS_SMALLINT so we 
    5105             :          * have to convert it. We can do this because libtds just
    5106             :          * stores these data.
    5107             :          */
    5108           0 :         if (info->by_cols > 0 && info->bycolumns[0] != byte_flag) {
    5109             :                 int n;
    5110           0 :                 TDS_TINYINT *p = (TDS_TINYINT*) malloc(sizeof(info->bycolumns[0]) + info->by_cols);
    5111           0 :                 if (!p) {
    5112           0 :                         dbperror(dbproc, SYBEMEM, errno);
    5113           0 :                         return NULL;
    5114             :                 }
    5115           0 :                 for (n = 0; n < info->by_cols; ++n)
    5116           0 :                         p[sizeof(info->bycolumns[0]) + n] = TDS_MIN(info->bycolumns[n], 255);
    5117           0 :                 *((TDS_SMALLINT *)p) = byte_flag;
    5118           0 :                 free(info->bycolumns);
    5119           0 :                 info->bycolumns = (TDS_SMALLINT *) p;
    5120             :         }
    5121           0 :         return (BYTE *) (&info->bycolumns[1]);
    5122             : }
    5123             : 
    5124             : /** \internal
    5125             :  * \ingroup dblib_internal
    5126             :  * \brief Check if \a dbproc is an ex-parrot.  
    5127             :  * 
    5128             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5129             :  * \retval TRUE process has been marked \em dead.
    5130             :  * \retval FALSE process is OK.  
    5131             :  * \remarks dbdead() does not communicate with the server.  
    5132             :  *      Unless a previously db-lib marked \a dbproc \em dead, dbdead() returns \c FALSE.  
    5133             :  * \sa dberrhandle().
    5134             :  */
    5135             : DBBOOL
    5136          10 : dbdead(DBPROCESS * dbproc)
    5137             : {
    5138          10 :         tdsdump_log(TDS_DBG_FUNC, "dbdead(%p) [%s]\n", dbproc, dbproc? IS_TDSDEAD(dbproc->tds_socket)? "dead":"alive" : "quite dead");
    5139             : 
    5140          10 :         if( NULL == dbproc ) 
    5141             :                 return TRUE;
    5142             : 
    5143          10 :         if (IS_TDSDEAD(dbproc->tds_socket))
    5144             :                 return TRUE;
    5145             : 
    5146          10 :         return FALSE;
    5147             : }
    5148             : 
    5149             : /** \internal
    5150             :  * \ingroup dblib_internal
    5151             :  * \brief default error handler for db-lib (handles library-generated errors)
    5152             :  * 
    5153             :  * The default error handler doesn't print anything.  If you want to see your messages printed, 
    5154             :  * install an error handler.  If you think that should be an optional compile- or run-time default, 
    5155             :  * submit a patch.  It could be done.  
    5156             :  * 
    5157             :  * \sa DBDEAD(), dberrhandle().
    5158             :  */
    5159             : /* Thus saith Sybase:
    5160             :  *     "If the user does not supply an error handler (or passes a NULL pointer to 
    5161             :  *      dberrhandle), DB-Library will exhibit its default error-handling 
    5162             :  *      behavior: It will abort the program if the error has made the affected 
    5163             :  *      DBPROCESS unusable (the user can call DBDEAD to determine whether 
    5164             :  *      or not a DBPROCESS has become unusable). If the error has not made the 
    5165             :  *      DBPROCESS unusable, DB-Library will simply return an error code to its caller." 
    5166             :  *
    5167             :  * It is not the error handler, however, that aborts anything.  It is db-lib, cf. dbperror().  
    5168             :  */ 
    5169             : static int
    5170          10 : default_err_handler(DBPROCESS * dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
    5171             : {
    5172          10 :         tdsdump_log(TDS_DBG_FUNC, "default_err_handler %p, %d, %d, %d, %p, %p", dbproc, severity, dberr, oserr, dberrstr, oserrstr);
    5173             : 
    5174          10 :         if (DBDEAD(dbproc) && (!dbproc || !dbproc->msdblib)) {
    5175             :                 return INT_EXIT;
    5176             :         }
    5177             :         
    5178          10 :         if (!dbproc || !dbproc->msdblib) {   /* i.e. Sybase behavior */
    5179          10 :                 switch(dberr) {
    5180             :                 case SYBETIME:
    5181             :                         return INT_EXIT;
    5182             :                 default: 
    5183             :                         break;
    5184             :                 }
    5185           0 :         }
    5186          10 :         return INT_CANCEL;
    5187             : }
    5188             : 
    5189             : /**
    5190             :  * \ingroup dblib_core
    5191             :  * \brief Set an error handler, for messages from db-lib.
    5192             :  * 
    5193             :  * \param handler pointer to callback function that will handle errors.
    5194             :  *        Pass NULL to restore the default handler.  
    5195             :  * \return address of prior handler, or NULL if none was previously installed. 
    5196             :  * \sa DBDEAD(), dbmsghandle().
    5197             :  */
    5198             : EHANDLEFUNC
    5199        1152 : dberrhandle(EHANDLEFUNC handler)
    5200             : {
    5201        1152 :         EHANDLEFUNC old_handler = _dblib_err_handler;
    5202             : 
    5203        1152 :         tdsdump_log(TDS_DBG_FUNC, "dberrhandle(%p)\n", handler);
    5204             : 
    5205        1152 :         _dblib_err_handler = handler? handler : default_err_handler;
    5206             :         
    5207        1152 :         return (old_handler == default_err_handler)? NULL : old_handler;
    5208             : }
    5209             : 
    5210             : /**
    5211             :  * \ingroup dblib_core
    5212             :  * \brief Set a message handler, for messages from the server.
    5213             :  * 
    5214             :  * \param handler address of the function that will process the messages.
    5215             :  * \sa DBDEAD(), dberrhandle().
    5216             :  */
    5217             : MHANDLEFUNC
    5218        1172 : dbmsghandle(MHANDLEFUNC handler)
    5219             : {
    5220        1172 :         MHANDLEFUNC retFun = _dblib_msg_handler;
    5221             : 
    5222        1172 :         tdsdump_log(TDS_DBG_FUNC, "dbmsghandle(%p)\n", handler);
    5223             : 
    5224        1172 :         _dblib_msg_handler = handler;
    5225        1172 :         return retFun;
    5226             : }
    5227             : 
    5228             : #if defined(DBLIB_UNIMPLEMENTED)
    5229             : /**
    5230             :  * \ingroup dblib_money
    5231             :  * \brief Add two DBMONEY values.
    5232             :  * 
    5233             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5234             :  * \param m1 first operand.
    5235             :  * \param m2 other operand. 
    5236             :  * \param sum \em output: result of computation.  
    5237             :  * \retval SUCCEED Always.  
    5238             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5239             :  * \todo Unimplemented.
    5240             :  */
    5241             : RETCODE
    5242             : dbmnyadd(DBPROCESS * dbproc, DBMONEY * m1, DBMONEY * m2, DBMONEY * sum)
    5243             : {
    5244             :         tdsdump_log(TDS_DBG_FUNC, "dbmnyadd(%p, %p, %p, %p)\n", dbproc, m1, m2, sum);
    5245             :         CHECK_CONN(FAIL);
    5246             :         CHECK_NULP(m1,  "dbmnyadd", 2, FAIL);
    5247             :         CHECK_NULP(m2,  "dbmnyadd", 3, FAIL);
    5248             :         CHECK_NULP(sum, "dbmnyadd", 4, FAIL);
    5249             : 
    5250             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnyadd()\n");
    5251             :         return SUCCEED;
    5252             : }
    5253             : 
    5254             : 
    5255             : /**
    5256             :  * \ingroup dblib_money
    5257             :  * \brief Subtract two DBMONEY values.
    5258             :  * 
    5259             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5260             :  * \param m1 first operand.
    5261             :  * \param m2 other operand, subtracted from \a m1. 
    5262             :  * \param difference \em output: result of computation.  
    5263             :  * \retval SUCCEED Always.  
    5264             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5265             :  * \todo Unimplemented.
    5266             :  */
    5267             : RETCODE
    5268             : dbmnysub(DBPROCESS * dbproc, DBMONEY * m1, DBMONEY * m2, DBMONEY * difference)
    5269             : {
    5270             :         tdsdump_log(TDS_DBG_FUNC, "dbmnysub(%p, %p, %p, %p)\n", dbproc, m1, m2, difference);
    5271             :         CHECK_CONN(FAIL);
    5272             :         CHECK_NULP(m1, "dbmnysub", 2, FAIL);
    5273             :         CHECK_NULP(m2, "dbmnysub", 3, FAIL);
    5274             :         CHECK_NULP(difference, "dbmnysub", 4, FAIL);
    5275             : 
    5276             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnysyb()\n");
    5277             :         return SUCCEED;
    5278             : }
    5279             : 
    5280             : /**
    5281             :  * \ingroup dblib_money
    5282             :  * \brief Multiply two DBMONEY values.
    5283             :  * 
    5284             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5285             :  * \param m1 first operand.
    5286             :  * \param m2 other operand. 
    5287             :  * \param prod \em output: result of computation.  
    5288             :  * \retval SUCCEED Always.  
    5289             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5290             :  * \todo Unimplemented.
    5291             :  */
    5292             : RETCODE
    5293             : dbmnymul(DBPROCESS * dbproc, DBMONEY * m1, DBMONEY * m2, DBMONEY * prod)
    5294             : {
    5295             :         tdsdump_log(TDS_DBG_FUNC, "dbmnymul(%p, %p, %p, %p)\n", dbproc, m1, m2, prod);
    5296             :         CHECK_CONN(FAIL);
    5297             :         CHECK_NULP(m1, "dbmnymul", 2, FAIL);
    5298             :         CHECK_NULP(m2, "dbmnymul", 3, FAIL);
    5299             :         CHECK_NULP(prod, "dbmnymul", 4, FAIL);
    5300             : 
    5301             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnymul()\n");
    5302             :         return SUCCEED;
    5303             : }
    5304             : 
    5305             : /**
    5306             :  * \ingroup dblib_money
    5307             :  * \brief Divide two DBMONEY values.
    5308             :  * 
    5309             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5310             :  * \param m1 dividend.
    5311             :  * \param m2 divisor. 
    5312             :  * \param quotient \em output: result of computation.  
    5313             :  * \retval SUCCEED Always.  
    5314             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5315             :  * \todo Unimplemented.
    5316             :  */
    5317             : RETCODE
    5318             : dbmnydivide(DBPROCESS * dbproc, DBMONEY * m1, DBMONEY * m2, DBMONEY * quotient)
    5319             : {
    5320             :         tdsdump_log(TDS_DBG_FUNC, "dbmnydivide(%p, %p, %p, %p)\n", dbproc, m1, m2, quotient);
    5321             :         CHECK_CONN(FAIL);
    5322             :         CHECK_NULP(m1, "dbmnydivide", 2, FAIL);
    5323             :         CHECK_NULP(m2, "dbmnydivide", 3, FAIL);
    5324             :         CHECK_NULP(quotient, "dbmnydivide", 4, FAIL);
    5325             : 
    5326             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnydivide()\n");
    5327             :         return SUCCEED;
    5328             : }
    5329             : #endif
    5330             : 
    5331             : /**
    5332             :  * \ingroup dblib_money
    5333             :  * \brief Compare two DBMONEY values.
    5334             :  * 
    5335             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5336             :  * \param m1 some money.
    5337             :  * \param m2 some other money. 
    5338             :  * \retval 0 m1 == m2. 
    5339             :  * \retval -1 m1 < m2.
    5340             :  * \retval  1 m1 > m2.
    5341             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5342             :  */
    5343             : int
    5344           0 : dbmnycmp(DBPROCESS * dbproc, DBMONEY * m1, DBMONEY * m2)
    5345             : {
    5346           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnycmp(%p, %p, %p)\n", dbproc, m1, m2);
    5347           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    5348           0 :         CHECK_NULP(m1, "dbmnycmp", 2, 0);
    5349           0 :         CHECK_NULP(m2, "dbmnycmp", 3, 0);
    5350             : 
    5351           0 :         if (m1->mnyhigh < m2->mnyhigh) {
    5352             :                 return -1;
    5353             :         }
    5354           0 :         if (m1->mnyhigh > m2->mnyhigh) {
    5355             :                 return 1;
    5356             :         }
    5357           0 :         if (m1->mnylow < m2->mnylow) {
    5358             :                 return -1;
    5359             :         }
    5360           0 :         if (m1->mnylow > m2->mnylow) {
    5361             :                 return 1;
    5362             :         }
    5363           0 :         return 0;
    5364             : }
    5365             : 
    5366             : #if defined(DBLIB_UNIMPLEMENTED)
    5367             : /**
    5368             :  * \ingroup dblib_money
    5369             :  * \brief Multiply a DBMONEY value by a positive integer, and add an amount. 
    5370             :  * 
    5371             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5372             :  * \param amount starting amount of money, also holds output.
    5373             :  * \param multiplier amount to multiply \a amount by. 
    5374             :  * \param addend amount to add to \a amount, after multiplying by \a multiplier. 
    5375             :  * \retval SUCCEED Always.  
    5376             :  * \remarks This function is goofy.  
    5377             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5378             :  * \todo Unimplemented.
    5379             :  */
    5380             : RETCODE
    5381             : dbmnyscale(DBPROCESS * dbproc, DBMONEY * amount, int multiplier, int addend)
    5382             : {
    5383             :         tdsdump_log(TDS_DBG_FUNC, "dbmnyscale(%p, %p, %d, %d)\n", dbproc, amount, multiplier, addend);
    5384             :         CHECK_CONN(FAIL);
    5385             :         CHECK_NULP(amount, "dbmnyscale", 2, FAIL);
    5386             : 
    5387             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnyscale()\n");
    5388             :         return SUCCEED;
    5389             : }
    5390             : #endif
    5391             : 
    5392             : /**
    5393             :  * \ingroup dblib_money
    5394             :  * \brief Set a DBMONEY value to zero.
    5395             :  * 
    5396             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5397             :  * \param dest address of a DBMONEY structure.  
    5398             :  * \retval SUCCEED unless \a amount is NULL.  
    5399             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5400             :  */
    5401             : RETCODE
    5402           0 : dbmnyzero(DBPROCESS * dbproc, DBMONEY * dest)
    5403             : {
    5404           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnyzero(%p, %p)\n", dbproc, dest);
    5405           0 :         CHECK_CONN(FAIL);
    5406           0 :         CHECK_NULP(dest, "dbmnyzero", 2, FAIL);
    5407             : 
    5408           0 :         dest->mnylow = 0;
    5409           0 :         dest->mnyhigh = 0;
    5410           0 :         return SUCCEED;
    5411             : }
    5412             : 
    5413             : /**
    5414             :  * \ingroup dblib_money
    5415             :  * \brief Get maximum positive DBMONEY value supported.
    5416             :  * 
    5417             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5418             :  * \param amount address of a DBMONEY structure.  
    5419             :  * \retval SUCCEED Always.  
    5420             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5421             :  */
    5422             : RETCODE
    5423           0 : dbmnymaxpos(DBPROCESS * dbproc, DBMONEY * amount)
    5424             : {
    5425           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnymaxpos(%p, %p)\n", dbproc, amount);
    5426           0 :         CHECK_CONN(FAIL);
    5427           0 :         CHECK_NULP(amount, "dbmnymaxpos", 2, FAIL);
    5428             : 
    5429           0 :         amount->mnylow = 0xFFFFFFFFlu;
    5430           0 :         amount->mnyhigh = 0x7FFFFFFFl;
    5431           0 :         return SUCCEED;
    5432             : }
    5433             : 
    5434             : /**
    5435             :  * \ingroup dblib_money
    5436             :  * \brief Get maximum negative DBMONEY value supported.
    5437             :  * 
    5438             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5439             :  * \param amount address of a DBMONEY structure.  
    5440             :  * \retval SUCCEED Always.  
    5441             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5442             :  */
    5443             : RETCODE
    5444           0 : dbmnymaxneg(DBPROCESS * dbproc, DBMONEY * amount)
    5445             : {
    5446           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnymaxneg(%p, %p)\n", dbproc, amount);
    5447           0 :         CHECK_CONN(FAIL);
    5448           0 :         CHECK_NULP(amount, "dbmnymaxneg", 2, FAIL);
    5449             : 
    5450           0 :         amount->mnylow = 0;
    5451           0 :         amount->mnyhigh = -0x7FFFFFFFL - 1;
    5452           0 :         return SUCCEED;
    5453             : }
    5454             : 
    5455             : #if defined(DBLIB_UNIMPLEMENTED)
    5456             : /**
    5457             :  * \ingroup dblib_money
    5458             :  * \brief Get the least significant digit of a DBMONEY value, represented as a character.
    5459             :  * 
    5460             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5461             :  * \param mnyptr \em input the money amount, \em and \em output: \a mnyptr divided by 10.  
    5462             :  * \param digit the character value (between '0' and '9') of the rightmost digit in \a mnyptr.  
    5463             :  * \param zero \em output: \c TRUE if \a mnyptr is zero on output, else \c FALSE.  
    5464             :  * \retval SUCCEED Always.  
    5465             :  * \sa dbconvert(), dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5466             :  * \remarks Unimplemented and likely to remain so.  We'd be amused to learn anyone wants this function.  
    5467             :  * \todo Unimplemented.
    5468             :  */
    5469             : RETCODE
    5470             : dbmnyndigit(DBPROCESS * dbproc, DBMONEY * mnyptr, DBCHAR * digit, DBBOOL * zero)
    5471             : {
    5472             :         tdsdump_log(TDS_DBG_FUNC, "dbmnyndigit(%p, %p, %s, %p)\n", dbproc, mnyptr, digit, zero);
    5473             :         CHECK_CONN(FAIL);
    5474             :         CHECK_NULP(mnyptr, "dbmnyndigit", 2, FAIL);
    5475             :         CHECK_NULP(digit, "dbmnyndigit", 3, FAIL);
    5476             :         CHECK_NULP(zero, "dbmnyndigit", 4, FAIL);
    5477             : 
    5478             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnyndigit()\n");
    5479             :         return SUCCEED;
    5480             : }
    5481             : 
    5482             : /**
    5483             :  * \ingroup dblib_money
    5484             :  * \brief Prepare a DBMONEY value for use with dbmnyndigit().
    5485             :  * 
    5486             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5487             :  * \param amount address of a DBMONEY structure.  
    5488             :  * \param trim number of digits to trim from \a amount.
    5489             :  * \param negative \em output: \c TRUE if \a amount < 0.  
    5490             :  * \retval SUCCEED Always.  
    5491             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5492             :  * \todo Unimplemented.
    5493             :  */
    5494             : RETCODE
    5495             : dbmnyinit(DBPROCESS * dbproc, DBMONEY * amount, int trim, DBBOOL * negative)
    5496             : {
    5497             :         tdsdump_log(TDS_DBG_FUNC, "dbmnyinit(%p, %p, %d, %p)\n", dbproc, amount, trim, negative);
    5498             :         CHECK_CONN(FAIL);
    5499             :         CHECK_NULP(amount, "dbmnyinit", 2, FAIL);
    5500             :         CHECK_NULP(negative, "dbmnyinit", 4, FAIL);
    5501             : 
    5502             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnyinit()\n");
    5503             :         return SUCCEED;
    5504             : }
    5505             : 
    5506             : 
    5507             : /**
    5508             :  * \ingroup dblib_money
    5509             :  * \brief Divide a DBMONEY value by a positive integer.
    5510             :  * 
    5511             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5512             :  * \param amount address of a DBMONEY structure.  
    5513             :  * \param divisor of \a amount.
    5514             :  * \param remainder \em output: modulo of integer division.
    5515             :  * \retval SUCCEED Always.  
    5516             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5517             :  * \todo Unimplemented.
    5518             :  */
    5519             : RETCODE
    5520             : dbmnydown(DBPROCESS * dbproc, DBMONEY * amount, int divisor, int *remainder)
    5521             : {
    5522             :         tdsdump_log(TDS_DBG_FUNC, "dbmnydown(%p, %p, %d, %p)\n", dbproc, amount, divisor, remainder);
    5523             :         CHECK_CONN(FAIL);
    5524             :         CHECK_NULP(amount, "dbmnydown", 2, FAIL);
    5525             :         CHECK_NULP(remainder, "dbmnydown", 4, FAIL);
    5526             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmnydown()\n");
    5527             :         return SUCCEED;
    5528             : }
    5529             : #endif
    5530             : 
    5531             : /**
    5532             :  * \ingroup dblib_money
    5533             :  * \brief Add $0.0001 to a DBMONEY value.
    5534             :  * 
    5535             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5536             :  * \param amount address of a DBMONEY structure.  
    5537             :  * \retval SUCCEED or FAIL if overflow or amount NULL.  
    5538             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5539             :  */
    5540             : RETCODE
    5541           0 : dbmnyinc(DBPROCESS * dbproc, DBMONEY * amount)
    5542             : {
    5543           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnyinc(%p, %p)\n", dbproc, amount);
    5544           0 :         CHECK_CONN(FAIL);
    5545           0 :         CHECK_NULP(amount, "dbmnyinc", 2, FAIL);
    5546             : 
    5547           0 :         if (amount->mnylow != 0xFFFFFFFFlu) {
    5548           0 :                 ++amount->mnylow;
    5549           0 :                 return SUCCEED;
    5550             :         }
    5551           0 :         if (amount->mnyhigh == 0x7FFFFFFFl)
    5552             :                 return FAIL;
    5553           0 :         amount->mnylow = 0;
    5554           0 :         ++amount->mnyhigh;
    5555           0 :         return SUCCEED;
    5556             : }
    5557             : 
    5558             : 
    5559             : /**
    5560             :  * \ingroup dblib_money
    5561             :  * \brief Subtract $0.0001 from a DBMONEY value.
    5562             :  *
    5563             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5564             :  * \param amount address of a DBMONEY structure.  
    5565             :  * \retval SUCCEED or FAIL if overflow or amount NULL.  
    5566             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5567             :  */
    5568             : RETCODE
    5569           0 : dbmnydec(DBPROCESS * dbproc, DBMONEY * amount)
    5570             : {
    5571           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnydec(%p, %p)\n", dbproc, amount);
    5572           0 :         CHECK_CONN(FAIL);
    5573           0 :         CHECK_NULP(amount, "dbmnydec", 2, FAIL);
    5574             : 
    5575           0 :         if (amount->mnylow != 0) {
    5576           0 :                 --amount->mnylow;
    5577           0 :                 return SUCCEED;
    5578             :         }
    5579           0 :         if (amount->mnyhigh == -0x7FFFFFFFL - 1)
    5580             :                 return FAIL;
    5581           0 :         amount->mnylow = 0xFFFFFFFFlu;
    5582           0 :         --amount->mnyhigh;
    5583           0 :         return SUCCEED;
    5584             : }
    5585             : 
    5586             : /**
    5587             :  * \ingroup dblib_money
    5588             :  * \brief Negate a DBMONEY value.
    5589             :  * 
    5590             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5591             :  * \param src address of a DBMONEY structure.  
    5592             :  * \param dest \em output: result of negation. 
    5593             :  * \retval SUCCEED or FAIL if overflow or src/dest NULL.
    5594             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5595             :  */
    5596             : RETCODE
    5597           0 : dbmnyminus(DBPROCESS * dbproc, DBMONEY * src, DBMONEY * dest)
    5598             : {
    5599           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnyminus(%p, %p, %p)\n", dbproc, src, dest);
    5600           0 :         CHECK_CONN(FAIL);
    5601           0 :         CHECK_NULP(src, "dbmnyminus", 2, FAIL);
    5602           0 :         CHECK_NULP(dest, "dbmnyminus", 3, FAIL);
    5603             : 
    5604           0 :         if (src->mnyhigh == -0x7FFFFFFFL - 1  &&  src->mnylow == 0)
    5605             :                 return FAIL;
    5606           0 :         dest->mnyhigh = -src->mnyhigh;
    5607           0 :         dest->mnylow = (~src->mnylow) + 1u;
    5608           0 :         return SUCCEED;
    5609             : }
    5610             : 
    5611             : 
    5612             : /**
    5613             :  * \ingroup dblib_money
    5614             :  * \brief Negate a DBMONEY4 value.
    5615             :  * 
    5616             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5617             :  * \param src address of a DBMONEY4 structure.  
    5618             :  * \param dest \em output: result of negation. 
    5619             :  * \retval SUCCEED usually.  
    5620             :  * \retval FAIL  on overflow.  
    5621             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5622             :  */
    5623             : RETCODE
    5624           0 : dbmny4minus(DBPROCESS * dbproc, DBMONEY4 * src, DBMONEY4 * dest)
    5625             : {
    5626             :         DBMONEY4 zero;
    5627             : 
    5628           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4minus(%p, %p, %p)\n", dbproc, src, dest);
    5629           0 :         CHECK_CONN(FAIL);
    5630           0 :         CHECK_NULP(src, "dbmny4minus", 2, FAIL);
    5631           0 :         CHECK_NULP(dest, "dbmny4minus", 3, FAIL);
    5632             : 
    5633           0 :         dbmny4zero(dbproc, &zero);
    5634           0 :         return (dbmny4sub(dbproc, &zero, src, dest));
    5635             : }
    5636             : 
    5637             : /**
    5638             :  * \ingroup dblib_money
    5639             :  * \brief Zero a DBMONEY4 value.
    5640             :  * 
    5641             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5642             :  * \param dest address of a DBMONEY structure.  
    5643             :  * \retval SUCCEED usually.  
    5644             :  * \retval FAIL  \a dest is NULL.  
    5645             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5646             :  */
    5647             : RETCODE
    5648           0 : dbmny4zero(DBPROCESS * dbproc, DBMONEY4 * dest)
    5649             : {
    5650           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4zero(%p, %p)\n", dbproc, dest);
    5651           0 :         CHECK_CONN(FAIL);
    5652           0 :         CHECK_NULP(dest, "dbmny4zero", 2, FAIL);
    5653             : 
    5654           0 :         dest->mny4 = 0;
    5655           0 :         return SUCCEED;
    5656             : }
    5657             : 
    5658             : /**
    5659             :  * \ingroup dblib_money
    5660             :  * \brief Add two DBMONEY4 values.
    5661             :  * 
    5662             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5663             :  * \param m1 first operand.
    5664             :  * \param m2 other operand. 
    5665             :  * \param sum \em output: result of computation.  
    5666             :  * \retval SUCCEED usually.  
    5667             :  * \retval FAIL  on overflow.  
    5668             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5669             :  */
    5670             : RETCODE
    5671           0 : dbmny4add(DBPROCESS * dbproc, DBMONEY4 * m1, DBMONEY4 * m2, DBMONEY4 * sum)
    5672             : {
    5673           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4add(%p, %p, %p, %p)\n", dbproc, m1, m2, sum);
    5674           0 :         CHECK_CONN(FAIL);
    5675           0 :         CHECK_NULP(m1, "dbmny4add", 2, FAIL);
    5676           0 :         CHECK_NULP(m2, "dbmny4add", 3, FAIL);
    5677           0 :         CHECK_NULP(sum, "dbmny4add", 4, FAIL);
    5678             : 
    5679           0 :         sum->mny4 = m1->mny4 + m2->mny4;
    5680           0 :         if (((m1->mny4 < 0) && (m2->mny4 < 0) && (sum->mny4 >= 0))
    5681           0 :             || ((m1->mny4 > 0) && (m2->mny4 > 0) && (sum->mny4 <= 0))) {
    5682             :                 /* overflow */
    5683           0 :                 sum->mny4 = 0;
    5684           0 :                 return FAIL;
    5685             :         }
    5686             :         return SUCCEED;
    5687             : }
    5688             : 
    5689             : /**
    5690             :  * \ingroup dblib_money
    5691             :  * \brief Subtract two DBMONEY4 values.
    5692             :  * 
    5693             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5694             :  * \param m1 first operand.
    5695             :  * \param m2 other operand, subtracted from \a m1. 
    5696             :  * \param diff \em output: result of computation.  
    5697             :  * \retval SUCCEED usually.  
    5698             :  * \retval FAIL  on overflow.  
    5699             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5700             :  */
    5701             : RETCODE
    5702           0 : dbmny4sub(DBPROCESS * dbproc, DBMONEY4 * m1, DBMONEY4 * m2, DBMONEY4 * diff)
    5703             : {
    5704             : 
    5705           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4sub(%p, %p, %p, %p)\n", dbproc, m1, m2, diff);
    5706           0 :         CHECK_CONN(FAIL);
    5707           0 :         CHECK_NULP(m1, "dbmny4sub", 2, FAIL);
    5708           0 :         CHECK_NULP(m2, "dbmny4sub", 3, FAIL);
    5709           0 :         CHECK_NULP(diff, "dbmny4sub", 4, FAIL);
    5710             : 
    5711           0 :         diff->mny4 = m1->mny4 - m2->mny4;
    5712           0 :         if (((m1->mny4 <= 0) && (m2->mny4 > 0) && (diff->mny4 > 0))
    5713           0 :             || ((m1->mny4 >= 0) && (m2->mny4 < 0) && (diff->mny4 < 0))) {
    5714             :                 /* overflow */
    5715           0 :                 diff->mny4 = 0;
    5716           0 :                 return FAIL;
    5717             :         }
    5718             :         return SUCCEED;
    5719             : }
    5720             : 
    5721             : #if defined(DBLIB_UNIMPLEMENTED)
    5722             : /**
    5723             :  * \ingroup dblib_money
    5724             :  * \brief Multiply two DBMONEY4 values.
    5725             :  * 
    5726             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5727             :  * \param m1 first operand.
    5728             :  * \param m2 other operand. 
    5729             :  * \param prod \em output: result of computation.  
    5730             :  * \retval SUCCEED usually.  
    5731             :  * \retval FAIL a parameter is NULL.  
    5732             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5733             :  * \todo Unimplemented.
    5734             :  */
    5735             : RETCODE
    5736             : dbmny4mul(DBPROCESS * dbproc, DBMONEY4 * m1, DBMONEY4 * m2, DBMONEY4 * prod)
    5737             : {
    5738             : 
    5739             :         tdsdump_log(TDS_DBG_FUNC, "dbmny4mul(%p, %p, %p, %p)\n", dbproc, m1, m2, prod);
    5740             :         CHECK_CONN(FAIL);
    5741             :         CHECK_NULP(m1, "dbmny4mul", 2, FAIL);
    5742             :         CHECK_NULP(m2, "dbmny4mul", 3, FAIL);
    5743             :         CHECK_NULP(prod, "dbmny4mul", 4, FAIL);
    5744             : 
    5745             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmny4mul()\n");
    5746             :         return FAIL;
    5747             : }
    5748             : 
    5749             : /**
    5750             :  * \ingroup dblib_money
    5751             :  * \brief Divide two DBMONEY4 values.
    5752             :  * 
    5753             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5754             :  * \param m1 dividend.
    5755             :  * \param m2 divisor. 
    5756             :  * \param quotient \em output: result of computation.  
    5757             :  * \retval SUCCEED usually.  
    5758             :  * \retval FAIL a parameter is NULL.  
    5759             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5760             :  * \todo Unimplemented.
    5761             :  */
    5762             : RETCODE
    5763             : dbmny4divide(DBPROCESS * dbproc, DBMONEY4 * m1, DBMONEY4 * m2, DBMONEY4 * quotient)
    5764             : {
    5765             : 
    5766             :         tdsdump_log(TDS_DBG_FUNC, "dbmny4divide(%p, %p, %p, %p)\n", dbproc, m1, m2, quotient);
    5767             :         CHECK_CONN(FAIL);
    5768             :         CHECK_NULP(m1, "dbmny4divide", 2, FAIL);
    5769             :         CHECK_NULP(m2, "dbmny4divide", 3, FAIL);
    5770             :         CHECK_NULP(quotient, "dbmny4divide", 4, FAIL);
    5771             : 
    5772             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbmny4divide()\n");
    5773             :         return FAIL;
    5774             : }
    5775             : #endif
    5776             : 
    5777             : /**
    5778             :  * \ingroup dblib_money
    5779             :  * \brief Compare two DBMONEY4 values.
    5780             :  * 
    5781             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5782             :  * \param m1 some money.
    5783             :  * \param m2 some other money. 
    5784             :  * \retval 0 m1 == m2. 
    5785             :  * \retval -1 m1 < m2.
    5786             :  * \retval  1 m1 > m2.
    5787             :  * \sa dbmnyadd(), dbmnysub(), dbmnymul(), dbmnydivide(), dbmnyminus(), dbmny4add(), dbmny4sub(), dbmny4mul(), dbmny4divide(), dbmny4minus().
    5788             :  */
    5789             : int
    5790           0 : dbmny4cmp(DBPROCESS * dbproc, DBMONEY4 * m1, DBMONEY4 * m2)
    5791             : {
    5792             : 
    5793           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4cmp(%p, %p, %p)\n", dbproc, m1, m2);
    5794           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    5795           0 :         CHECK_NULP(m1, "dbmny4cmp", 2, 0);
    5796           0 :         CHECK_NULP(m2, "dbmny4cmp", 3, 0);
    5797             : 
    5798           0 :         if (m1->mny4 < m2->mny4) {
    5799             :                 return -1;
    5800             :         }
    5801           0 :         if (m1->mny4 > m2->mny4) {
    5802             :                 return 1;
    5803             :         }
    5804           0 :         return 0;
    5805             : }
    5806             : 
    5807             : /**
    5808             :  * \ingroup dblib_money
    5809             :  * \brief Copy a DBMONEY4 value.
    5810             :  * 
    5811             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5812             :  * \param src address of a DBMONEY4 structure.  
    5813             :  * \param dest \em output: new money. 
    5814             :  * \retval SUCCEED or FAIL if src/dest NULL.
    5815             :  * \sa dbmnycopy(), dbmnyminus(), dbmny4minus(). 
    5816             :  */
    5817             : RETCODE
    5818           0 : dbmny4copy(DBPROCESS * dbproc, DBMONEY4 * src, DBMONEY4 * dest)
    5819             : {
    5820             : 
    5821           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmny4copy(%p, %p, %p)\n", dbproc, src, dest);
    5822           0 :         CHECK_CONN(FAIL);
    5823           0 :         CHECK_NULP(src, "dbmny4copy", 2, FAIL);
    5824           0 :         CHECK_NULP(dest, "dbmny4copy", 3, FAIL);
    5825             : 
    5826           0 :         dest->mny4 = src->mny4;
    5827           0 :         return SUCCEED;
    5828             : }
    5829             : 
    5830             : /**
    5831             :  * \ingroup dblib_datetime
    5832             :  * \brief Compare DBDATETIME values, similar to strcmp(3).
    5833             :  * 
    5834             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5835             :  * \param d1 a \c DBDATETIME structure address
    5836             :  * \param d2 another \c DBDATETIME structure address
    5837             :  * \retval   0 d1 = d2.
    5838             :  * \retval  -1 d1 < d2.
    5839             :  * \retval   1 d1 > d2.
    5840             :  * \sa dbdate4cmp(), dbmnycmp(), dbmny4cmp().
    5841             :  */
    5842             : int
    5843           0 : dbdatecmp(DBPROCESS * dbproc, DBDATETIME * d1, DBDATETIME * d2)
    5844             : {
    5845           0 :         tdsdump_log(TDS_DBG_FUNC, "dbdatecmp(%p, %p, %p)\n", dbproc, d1, d2);
    5846           0 :         CHECK_CONN(FAIL);
    5847           0 :         CHECK_NULP(d1, "dbdatecmp", 2, 0);
    5848           0 :         CHECK_NULP(d2, "dbdatecmp", 3, 0);
    5849             : 
    5850           0 :         if (d1->dtdays == d2->dtdays) {
    5851           0 :                 if (d1->dttime == d2->dttime)
    5852             :                         return 0;
    5853           0 :                 return d1->dttime > d2->dttime ? 1 : -1;
    5854             :         }
    5855             : 
    5856             :         /* date 1 is before 1900 */
    5857           0 :         if (d1->dtdays > 2958463) {
    5858             : 
    5859           0 :                 if (d2->dtdays > 2958463) /* date 2 is before 1900 */
    5860           0 :                         return d1->dtdays > d2->dtdays ? 1 : -1;
    5861             :                 return -1;
    5862             :         }
    5863             : 
    5864             :         /* date 1 is after 1900 */
    5865           0 :         if (d2->dtdays < 2958463) /* date 2 is after 1900 */
    5866           0 :                 return d1->dtdays > d2->dtdays ? 1 : -1;
    5867             :         return 1;
    5868             : }
    5869             : 
    5870             : static RETCODE
    5871          24 : dblib_datecrack(DBPROCESS * dbproc, BOOL nano_precision, DBDATEREC * output, int type, const void * data)
    5872             : {
    5873             :         TDSDATEREC dr;
    5874          24 :         struct tds_sybase_dbdaterec *di = (struct tds_sybase_dbdaterec*) output;
    5875             : 
    5876          24 :         tdsdump_log(TDS_DBG_FUNC, "dblib_datecrack(%p, %d, %p, %d, %p)\n", dbproc, nano_precision, output, type, data);
    5877          24 :         CHECK_NULP(output, "dbdatecrack", 2, FAIL);
    5878          24 :         CHECK_PARAMETER(data, SYBENDTP, FAIL);
    5879             : 
    5880          24 :         if (TDS_FAILED(tds_datecrack(type, data, &dr)))
    5881             :                 return FAIL;
    5882             : 
    5883          24 :         di->dateyear = dr.year;
    5884          24 :         di->quarter = dr.quarter;
    5885          24 :         di->datemonth = dr.month;
    5886          24 :         di->datedmonth = dr.day;
    5887          24 :         di->datedyear = dr.dayofyear;
    5888          24 :         di->datedweek = dr.weekday;
    5889          24 :         di->datehour = dr.hour;
    5890          24 :         di->dateminute = dr.minute;
    5891          24 :         di->datesecond = dr.second;
    5892          24 :         di->datetzone = dr.timezone;
    5893          24 :         if (nano_precision)
    5894             :                 /* here we are writing to nanosecond field */
    5895           4 :                 di->datemsecond = dr.decimicrosecond * 100u;
    5896             :         else
    5897          20 :                 di->datemsecond = dr.decimicrosecond / 10000u;
    5898             :         /* Revert to compiled-in default if dbproc can't be used to find the runtime override. */
    5899          24 :         if (dbproc ? dbproc->msdblib : dblib_msdblib) {
    5900           0 :                 ++di->quarter;
    5901           0 :                 ++di->datemonth;
    5902           0 :                 ++di->datedweek;
    5903             :         }
    5904             :         return SUCCEED;
    5905             : }
    5906             : 
    5907             : /**
    5908             :  * \ingroup dblib_core
    5909             :  * \brief Break a DBDATETIME value into useful pieces.
    5910             :  *
    5911             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5912             :  * \param di \em output: structure to contain the exploded parts of \a datetime.
    5913             :  * \param datetime \em input: \c DBDATETIME to be converted.
    5914             :  * \retval SUCCEED always.
    5915             :  * \remarks The members of \a di have different names, depending on whether \c --with-msdblib was configured.
    5916             :  *
    5917             :  * If DBPROCESS is NULL, dbdatecrack() uses the compiled in default
    5918             :  * value of MSDBLIB as of when libsybdb was compiled, irrespective of its value when the
    5919             :  * application is compiled.  This can lead to incorrect results because Sybase and Microsoft use different
    5920             :  * ranges -- [0,11] vs. [1,12] -- for the month.
    5921             :  *
    5922             :  * \sa dbconvert(), dbdata(), dbdatechar(), dbdatename(), dbdatepart(), tdsdbopen().
    5923             :  */
    5924             : RETCODE
    5925          20 : dbdatecrack(DBPROCESS * dbproc, DBDATEREC * di, DBDATETIME * datetime)
    5926             : {
    5927          20 :         return dblib_datecrack(dbproc, FALSE, di, SYBDATETIME, datetime);
    5928             : }
    5929             : 
    5930             : /**
    5931             :  * \ingroup dblib_core
    5932             :  * \brief Break any kind of date or time value into useful pieces.
    5933             :  *
    5934             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5935             :  * \param di \em output: structure to contain the exploded parts of \a datetime.
    5936             :  * \param type \em input: \c type of date/time value returned by dbcoltype().
    5937             :  * \param data \em input: \c date/time value to be converted.
    5938             :  * \retval SUCCEED always.
    5939             :  * \remarks The members of \a di have different names, depending on whether \c --with-msdblib was configured.
    5940             :  *
    5941             :  * This is an extension to dbdatecrack(), see it for more information.
    5942             :  *
    5943             :  * \sa dbdatecrack(), dbconvert(), dbdata(), dbdatechar(), dbdatename(), dbdatepart(), tdsdbopen().
    5944             :  */
    5945             : RETCODE
    5946           4 : dbanydatecrack(DBPROCESS * dbproc, DBDATEREC2 * di, int type, const void *data)
    5947             : {
    5948           4 :         return dblib_datecrack(dbproc, TRUE, (DBDATEREC *) di, type, data);
    5949             : }
    5950             : 
    5951             : #if defined(DBLIB_UNIMPLEMENTED)
    5952             : /**
    5953             :  * \ingroup dblib_core
    5954             :  * \brief Clear remote passwords from the LOGINREC structure.
    5955             :  * 
    5956             :  * \param login structure to pass to dbopen().
    5957             :  * \sa dblogin(), dbopen(), dbrpwset(), DBSETLAPP(), DBSETLHOST(), DBSETLPWD(), DBSETLUSER().  
    5958             :  * \remarks Useful for remote stored procedure calls, but not in high demand from FreeTDS.  
    5959             :  * \todo Unimplemented.
    5960             :  */
    5961             : void
    5962             : dbrpwclr(LOGINREC * login)
    5963             : {
    5964             :         tdsdump_log(TDS_DBG_FUNC, "dbrpwclr(%p)\n", login);
    5965             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbrpwclr()\n");
    5966             : }
    5967             : 
    5968             : /**
    5969             :  * \ingroup dblib_core
    5970             :  * \brief Add a remote password to the LOGINREC structure.
    5971             :  * 
    5972             :  * \param login structure to pass to dbopen().
    5973             :  * \param srvname server for which \a password should be used.  
    5974             :  * \param password you guessed it, let's hope no else does.  
    5975             :  * \param pwlen count of \a password, in bytes.
    5976             :  * \remarks Useful for remote stored procedure calls, but not in high demand from FreeTDS.  
    5977             :  * \sa dblogin(), dbopen(), dbrpwclr(), DBSETLAPP(), DBSETLHOST(), DBSETLPWD(), DBSETLUSER().  
    5978             :  * \todo Unimplemented.
    5979             :  */
    5980             : RETCODE
    5981             : dbrpwset(LOGINREC * login, char *srvname, char *password, int pwlen)
    5982             : {
    5983             :         tdsdump_log(TDS_DBG_FUNC, "dbrpwset(%p, %s, %s, %d)\n", login, srvname, password, pwlen);
    5984             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbrpwset()\n");
    5985             :         return SUCCEED;
    5986             : }
    5987             : #endif
    5988             : 
    5989             : /**
    5990             :  * \ingroup dblib_core
    5991             :  * \brief Get server process ID for a \c DBPROCESS.
    5992             :  * 
    5993             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    5994             :  * \return \em "spid", the server's process ID.  
    5995             :  * \sa dbopen().  
    5996             :  */
    5997             : int
    5998          10 : dbspid(DBPROCESS * dbproc)
    5999             : {
    6000          10 :         tdsdump_log(TDS_DBG_FUNC, "dbspid(%p)\n", dbproc);
    6001          10 :         CHECK_CONN(-1);
    6002             : 
    6003          10 :         return dbproc->tds_socket->conn->spid;
    6004             : }
    6005             : 
    6006             : /**
    6007             :  * \ingroup dblib_core
    6008             :  * \brief Associate client-allocated (and defined) data with a \c DBPROCESS.   
    6009             :  * 
    6010             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6011             :  * \param ptr address of client-defined data.
    6012             :  * \remarks \a ptr is the location of user data that \c db-lib will associate with \a dbproc. 
    6013             :  * The client allocates the buffer addressed by \a ptr.  \c db-lib never examines or uses the information; 
    6014             :  * it just stashes the pointer for later retrieval by the application with \c dbgetuserdata().  
    6015             :  * \sa dbgetuserdata().  
    6016             :  */
    6017             : void
    6018         262 : dbsetuserdata(DBPROCESS * dbproc, BYTE * ptr)
    6019             : {
    6020         262 :         tdsdump_log(TDS_DBG_FUNC, "dbsetuserdata(%p, %p)\n", dbproc, ptr);
    6021         262 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    6022             : 
    6023         262 :         dbproc->user_data = ptr;
    6024             : }
    6025             : 
    6026             : /**
    6027             :  * \ingroup dblib_core
    6028             :  * \brief Get address of user-allocated data from a \c DBPROCESS.   
    6029             :  * 
    6030             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6031             :  * \return address of user-defined data that \c db-lib associated with \a dbproc when the client called  dbsetuserdata(). 
    6032             :  * \retval undefined (probably \c NULL) dbsetuserdata() was not previously called.  
    6033             :  * \sa dbsetuserdata().  
    6034             :  */
    6035             : BYTE *
    6036         194 : dbgetuserdata(DBPROCESS * dbproc)
    6037             : {
    6038         194 :         tdsdump_log(TDS_DBG_FUNC, "dbgetuserdata(%p)\n", dbproc);
    6039         194 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    6040             : 
    6041         194 :         return dbproc->user_data;
    6042             : }
    6043             : 
    6044             : /**
    6045             :  * \ingroup dblib_core
    6046             :  * \brief Specify a db-lib version level.
    6047             :  * 
    6048             :  * \param version anything, really. 
    6049             :  * \retval SUCCEED Always.  
    6050             :  * \remarks No effect on behavior of \c db-lib in \c FreeTDS.  
    6051             :  * \sa 
    6052             :  */
    6053             : RETCODE
    6054          40 : dbsetversion(DBINT version)
    6055             : {
    6056          40 :         tdsdump_log(TDS_DBG_FUNC, "dbsetversion(%d)\n", version);
    6057             : 
    6058          40 :         switch (version) {
    6059          40 :         case DBVERSION_42:
    6060             :         case DBVERSION_46:
    6061             :         case DBVERSION_100:
    6062             :         case DBVERSION_70:
    6063             :         case DBVERSION_71:
    6064             :         case DBVERSION_72:
    6065             :         case DBVERSION_73:
    6066             :         case DBVERSION_74:
    6067          40 :                 g_dblib_version = version;
    6068          40 :                 return SUCCEED;
    6069             :         default:
    6070             :                 break;
    6071             :         }
    6072             :         
    6073           0 :         dbperror(NULL, SYBEIVERS, 0);
    6074           0 :         return FAIL;
    6075             : }
    6076             : 
    6077             : /**
    6078             :  * \ingroup dblib_money
    6079             :  * \brief Copy a DBMONEY value.
    6080             :  * 
    6081             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6082             :  * \param src address of a DBMONEY structure.  
    6083             :  * \param dest \em output: new money. 
    6084             :  * \retval SUCCEED always, unless \a src or \a dest is \c NULL.  
    6085             :  * \sa 
    6086             :  */
    6087             : RETCODE
    6088           0 : dbmnycopy(DBPROCESS * dbproc, DBMONEY * src, DBMONEY * dest)
    6089             : {
    6090           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmnycopy(%p, %p, %p)\n", dbproc, src, dest);
    6091           0 :         CHECK_CONN(FAIL);
    6092           0 :         CHECK_NULP(src, "dbmnycopy", 2, FAIL);
    6093           0 :         CHECK_NULP(dest, "dbmnycopy", 3, FAIL);
    6094             : 
    6095           0 :         dest->mnylow = src->mnylow;
    6096           0 :         dest->mnyhigh = src->mnyhigh;
    6097           0 :         return SUCCEED;
    6098             : }
    6099             : 
    6100             : 
    6101             : /**
    6102             :  * \ingroup dblib_core
    6103             :  * \brief Cancel the query currently being retrieved, discarding all pending rows.  
    6104             :  * 
    6105             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6106             :  * \sa 
    6107             :  */
    6108             : RETCODE
    6109         814 : dbcanquery(DBPROCESS * dbproc)
    6110             : {
    6111             :         TDSRET rc;
    6112             :         TDS_INT result_type;
    6113             : 
    6114         814 :         tdsdump_log(TDS_DBG_FUNC, "dbcanquery(%p)\n", dbproc);
    6115         814 :         CHECK_CONN(FAIL);
    6116             : 
    6117             :         /* Just throw away all pending rows from the last query */
    6118             : 
    6119         814 :         rc = tds_process_tokens(dbproc->tds_socket, &result_type, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE);
    6120             : 
    6121         814 :         if (TDS_FAILED(rc))
    6122             :                 return FAIL;
    6123             : 
    6124         814 :         dbproc->dbresults_state = _DB_RES_NEXT_RESULT;
    6125             : 
    6126         814 :         return SUCCEED;
    6127             : }
    6128             : 
    6129             : /**
    6130             :  * \ingroup dblib_core
    6131             :  * \brief Erase the command buffer, in case \c DBNOAUTOFREE was set with dbsetopt(). 
    6132             :  * 
    6133             :  * 
    6134             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6135             :  * \sa dbcmd(), dbfcmd(), dbgetchar(), dbsqlexec(), dbsqlsend(), dbsetopt(), dbstrcpy(), dbstrlen().  
    6136             :  */
    6137             : void
    6138       20724 : dbfreebuf(DBPROCESS * dbproc)
    6139             : {
    6140       20724 :         tdsdump_log(TDS_DBG_FUNC, "dbfreebuf(%p)\n", dbproc);
    6141       20724 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    6142             : 
    6143       20724 :         if (dbproc->dbbuf)
    6144       20704 :                 TDS_ZERO_FREE(dbproc->dbbuf);
    6145       20724 :         dbproc->dbbufsz = 0;
    6146             : }
    6147             : 
    6148             : /**
    6149             :  * \ingroup dblib_core
    6150             :  * \brief Reset an option.
    6151             :  * 
    6152             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6153             :  * \param option to be turned off.
    6154             :  * \param param clearing some options requires a parameter, believe it or not.  
    6155             :  * \retval SUCCEED \a option and \a parameter seem sane.
    6156             :  * \retval FAIL no such \a option.
    6157             :  * \remarks Only the following options are recognized:
    6158             :         - DBARITHABORT
    6159             :         - DBARITHIGNORE
    6160             :         - DBCHAINXACTS
    6161             :         - DBFIPSFLAG
    6162             :         - DBISOLATION
    6163             :         - DBNOCOUNT
    6164             :         - DBNOEXEC
    6165             :         - DBPARSEONLY
    6166             :         - DBSHOWPLAN
    6167             :         - DBSTORPROCID
    6168             :         - DBQUOTEDIDENT
    6169             :         - DBSETTIME
    6170             :  * \sa dbisopt(), dbsetopt().
    6171             :  */
    6172             : RETCODE
    6173          20 : dbclropt(DBPROCESS * dbproc, int option, const char param[])
    6174             : {
    6175             :         char *cmd;
    6176             : 
    6177          20 :         tdsdump_log(TDS_DBG_FUNC, "dbclropt(%p, %d, %s)\n", dbproc, option, param);
    6178          20 :         CHECK_CONN(FAIL);
    6179          20 :         if (option != DBSETTIME) {
    6180           0 :                 CHECK_NULP(param, "dbclropt", 3, FAIL);
    6181             :         }
    6182             : 
    6183          20 :         if ((option < 0) || (option >= DBNUMOPTIONS)) {
    6184             :                 return FAIL;
    6185             :         }
    6186          20 :         dbproc->dbopts[option].factive = 0;
    6187             :         switch (option) {
    6188           0 :         case DBARITHABORT:
    6189             :         case DBARITHIGNORE:
    6190             :         case DBCHAINXACTS:
    6191             :         case DBFIPSFLAG:
    6192             :         case DBISOLATION:
    6193             :         case DBNOCOUNT:
    6194             :         case DBNOEXEC:
    6195             :         case DBPARSEONLY:
    6196             :         case DBSHOWPLAN:
    6197             :         case DBSTORPROCID:
    6198             :         case DBQUOTEDIDENT:
    6199             :                 /* server options (on/off) */
    6200           0 :                 if (asprintf(&cmd, "set %s off\n", dbproc->dbopts[option].text) < 0) {
    6201             :                         return FAIL;
    6202             :                 }
    6203           0 :                 dbstring_concat(&(dbproc->dboptcmd), cmd);
    6204           0 :                 free(cmd);
    6205           0 :                 break;
    6206           0 :         case DBBUFFER:
    6207           0 :                 buffer_set_capacity(dbproc, 1); /* frees row_buf->rows */
    6208           0 :                 return SUCCEED;
    6209             :                 break;
    6210          20 :         case DBSETTIME:
    6211          20 :                 tds_mutex_lock(&dblib_mutex);
    6212             :                 /*
    6213             :                  * Use global value of query timeout set by dbsettime() if any,
    6214             :                  * otherwise set it to zero just like tds_init_socket() does.
    6215             :                  */
    6216          20 :                 if (g_dblib_ctx.query_timeout > 0) {
    6217          10 :                         dbproc->tds_socket->query_timeout = g_dblib_ctx.query_timeout;
    6218             :                 } else {
    6219          10 :                         dbproc->tds_socket->query_timeout = 0;
    6220             :                 }
    6221          20 :                 tds_mutex_unlock(&dblib_mutex);
    6222          20 :                 return SUCCEED;
    6223             :                 break;
    6224             :         default:
    6225             :                 break;
    6226             :         }
    6227           0 :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbclropt(option = %d)\n", option);
    6228             :         return FAIL;
    6229             : }
    6230             : 
    6231             : /**
    6232             :  * \ingroup dblib_core
    6233             :  * \brief Get value of an option
    6234             :  * 
    6235             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6236             :  * \param option the option
    6237             :  * \param param a parameter to \a option. 
    6238             :  * \sa dbclropt(), dbsetopt().
    6239             :  */
    6240             : DBBOOL
    6241         180 : dbisopt(DBPROCESS * dbproc, int option, const char param[])
    6242             : {
    6243         180 :         tdsdump_log(TDS_DBG_FUNC, "dbisopt(%p, %d, %s)\n", dbproc, option, param);
    6244         180 :         CHECK_PARAMETER(dbproc, SYBENULL, FALSE);
    6245             :         /* sometimes param can be NULL */
    6246             :         
    6247         180 :         if ((option < 0) || (option >= DBNUMOPTIONS)) {
    6248             :                 return FALSE;
    6249             :         }
    6250         180 :         return dbproc->dbopts[option].factive;
    6251             : }
    6252             : 
    6253             : /** \internal
    6254             :  * \ingroup dblib_internal
    6255             :  * \brief Get number of the row currently being read.
    6256             :  * 
    6257             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6258             :  * \return ostensibly the row number, or 0 if no rows have been read yet.  
    6259             :  * \retval 0 Always.  
    6260             :  * \sa DBCURROW(), dbclrbuf(), DBFIRSTROW(), dbgetrow(), DBLASTROW(), dbnextrow(), dbsetopt(),.  
    6261             :  * \todo Unimplemented.
    6262             :  */
    6263             : DBINT
    6264           0 : dbcurrow(DBPROCESS * dbproc)
    6265             : {
    6266           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcurrow(%p)\n", dbproc);
    6267           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    6268           0 :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbcurrow()\n");
    6269             :         return 0;
    6270             : }
    6271             : 
    6272             : 
    6273             : /** \internal
    6274             :  * \ingroup dblib_internal
    6275             :  * \brief Get returned row's type.
    6276             :  * 
    6277             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6278             :  * \sa DBROWTYPE().  
    6279             :  */
    6280             : STATUS
    6281           0 : dbrowtype(DBPROCESS * dbproc)
    6282             : {
    6283           0 :         tdsdump_log(TDS_DBG_FUNC, "dbrowtype(%p)\n", dbproc);
    6284           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NO_MORE_ROWS);
    6285           0 :         return dbproc->row_type;
    6286             : }
    6287             : 
    6288             : 
    6289             : /** \internal
    6290             :  * \ingroup dblib_internal
    6291             :  * \brief Get number of the row just returned.
    6292             :  * 
    6293             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6294             :  * \sa DBCURROW().
    6295             :  * \todo Unimplemented.
    6296             :  */
    6297             : int
    6298           0 : dbcurcmd(DBPROCESS * dbproc)
    6299             : {
    6300           0 :         tdsdump_log(TDS_DBG_FUNC, "dbcurcmd(%p)\n", dbproc);
    6301           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    6302           0 :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbcurcmd()\n");
    6303             :         return 0;
    6304             : }
    6305             : 
    6306             : 
    6307             : /** 
    6308             :  * \ingroup dblib_core
    6309             :  * \brief See if more commands are to be processed.
    6310             :  * 
    6311             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6312             :  * \sa DBMORECMDS(). DBCMDROW(), dbresults(), DBROWS(), DBROWTYPE().  
    6313             :  */
    6314             : RETCODE
    6315          30 : dbmorecmds(DBPROCESS * dbproc)
    6316             : {
    6317          30 :         tdsdump_log(TDS_DBG_FUNC, "dbmorecmds(%p)\n", dbproc);
    6318          30 :         CHECK_CONN(FAIL);
    6319             : 
    6320          30 :         if (dbproc->tds_socket->res_info == NULL) {
    6321             :                 return FAIL;
    6322             :         }
    6323             : 
    6324          30 :         if (!dbproc->tds_socket->res_info->more_results) {
    6325          20 :                 tdsdump_log(TDS_DBG_FUNC, "more_results is false; returns FAIL\n");
    6326             :                 return FAIL;
    6327             :         }
    6328             :         
    6329          10 :         tdsdump_log(TDS_DBG_FUNC, "more_results is true; returns SUCCEED\n");
    6330             :         
    6331             :         return SUCCEED;
    6332             : }
    6333             : 
    6334             : /**
    6335             :  * \ingroup dblib_rpc
    6336             :  * \brief Get datatype of a stored procedure's return parameter.
    6337             :  * 
    6338             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6339             :  * \param retnum Nth return parameter, between 1 and \c dbnumrets().  
    6340             :  * \return SYB* datatype token, or -1 if \a retnum is out of range. 
    6341             :  * \sa dbnextrow(), dbnumrets(), dbprtype(), dbresults(), dbretdata(), dbretlen(), dbretname(), dbrpcinit(), dbrpcparam(). 
    6342             :  */
    6343             : int
    6344          66 : dbrettype(DBPROCESS * dbproc, int retnum)
    6345             : {
    6346             :         TDSCOLUMN *colinfo;
    6347             : 
    6348          66 :         tdsdump_log(TDS_DBG_FUNC, "dbrettype(%p, %d)\n", dbproc, retnum);
    6349          66 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    6350          66 :         assert(dbproc->tds_socket);
    6351          66 :         assert(dbproc->tds_socket->param_info);
    6352             : 
    6353          66 :         if (retnum < 1 || retnum > dbproc->tds_socket->param_info->num_cols)
    6354             :                 return -1;
    6355             : 
    6356          66 :         colinfo = dbproc->tds_socket->param_info->columns[retnum - 1];
    6357             : 
    6358          66 :         return tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    6359             : }
    6360             : 
    6361             : /**
    6362             :  * \ingroup dblib_core
    6363             :  * \brief Get size of the command buffer, in bytes. 
    6364             :  * 
    6365             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6366             :  * \sa dbcmd(), dbfcmd(), dbfreebuf(), dbgetchar(), dbstrcpy(). 
    6367             :  */
    6368             : int
    6369           0 : dbstrlen(DBPROCESS * dbproc)
    6370             : {
    6371           0 :         tdsdump_log(TDS_DBG_FUNC, "dbstrlen(%p)\n", dbproc);
    6372           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    6373             :         
    6374           0 :         return dbproc->dbbufsz;
    6375             : }
    6376             : 
    6377             : 
    6378             : /**
    6379             :  * \ingroup dblib_core
    6380             :  * \brief Get address of a position in the command buffer.
    6381             :  * 
    6382             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6383             :  * \param pos offset within the command buffer, starting at \em 0.   
    6384             :  * \remarks A bit overspecialized, this one.  
    6385             :  * \sa dbcmd(), dbfcmd(), dbfreebuf(), dbstrcpy(), dbstrlen(),
    6386             :  */
    6387             : char *
    6388         490 : dbgetchar(DBPROCESS * dbproc, int pos)
    6389             : {
    6390         490 :         tdsdump_log(TDS_DBG_FUNC, "dbgetchar(%p, %d)\n", dbproc, pos);
    6391         490 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    6392         490 :         tdsdump_log(TDS_DBG_FUNC, "dbgetchar() bufsz = %d, pos = %d\n", dbproc->dbbufsz, pos);
    6393             : 
    6394         490 :         if (dbproc->dbbufsz > 0) {
    6395         490 :                 if (pos >= 0 && pos < (dbproc->dbbufsz - 1))
    6396         480 :                         return (char *) &dbproc->dbbuf[pos];
    6397             :                 return NULL;
    6398             :         }
    6399             :         return NULL;
    6400             : }
    6401             : 
    6402             : /**
    6403             :  * \ingroup dblib_core
    6404             :  * \brief Get a copy of a chunk of the command buffer.
    6405             :  * 
    6406             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6407             :  * \param start position in the command buffer to start copying from, starting from \em 0.  
    6408             :  *      If start is past the end of the command buffer, dbstrcpy() inserts a null terminator at dest[0].
    6409             :  * \param numbytes number of bytes to copy. 
    6410             :         - If -1, dbstrcpy() copies the whole command buffer.  
    6411             :         - If  0 dbstrcpy() writes a \c NULL to dest[0]. 
    6412             :         - If the command buffer contains fewer than \a numbytes (taking \a start into account) dbstrcpy() 
    6413             :         copies the rest of it.  
    6414             :  * \param dest \em output: the buffer to write to.  Make sure it's big enough.  
    6415             :  * \retval SUCCEED the inputs were valid and \a dest was affected.  
    6416             :  * \retval FAIL \a start < 0 or \a numbytes < -1.  
    6417             :  * \sa dbcmd(), dbfcmd(), dbfreebuf(), dbgetchar(), dbstrlen().  
    6418             :  */
    6419             : RETCODE
    6420           0 : dbstrcpy(DBPROCESS * dbproc, int start, int numbytes, char *dest)
    6421             : {
    6422           0 :         tdsdump_log(TDS_DBG_FUNC, "dbstrcpy(%p, %d, %d, %s)\n", dbproc, start, numbytes, dest);
    6423           0 :         CHECK_CONN(FAIL);
    6424           0 :         CHECK_NULP(dest, "dbstrcpy", 4, FAIL);
    6425             : 
    6426           0 :         if (start < 0) {
    6427           0 :                 dbperror(dbproc, SYBENSIP, 0);
    6428           0 :                 return FAIL;
    6429             :         }
    6430           0 :         if (numbytes < -1) {
    6431           0 :                 dbperror(dbproc, SYBEBNUM, 0);
    6432           0 :                 return FAIL;
    6433             :         }
    6434           0 :         dest[0] = 0;            /* start with empty string being returned */
    6435           0 :         if (dbproc->dbbufsz > 0 && start < dbproc->dbbufsz) {
    6436           0 :                 if (numbytes == -1)
    6437           0 :                         numbytes = dbproc->dbbufsz - start;
    6438           0 :                 if (start + numbytes > dbproc->dbbufsz)
    6439           0 :                         numbytes = dbproc->dbbufsz - start;
    6440           0 :                 memcpy(dest, (char *) &dbproc->dbbuf[start], numbytes);
    6441           0 :                 dest[numbytes] = '\0';
    6442             :         }
    6443             :         return SUCCEED;
    6444             : }
    6445             : 
    6446             : /**
    6447             :  * \ingroup dblib_core
    6448             :  * \brief safely quotes character values in SQL text.  
    6449             :  * 
    6450             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6451             :  * \param src input string.
    6452             :  * \param srclen length of \a src in bytes, or -1 to indicate it's null-terminated.  
    6453             :  * \param dest \em output: client-provided output buffer. 
    6454             :  * \param destlen size of \a dest in bytes, or -1 to indicate it's "big enough" and the data should be null-terminated.  
    6455             :  * \param quotetype
    6456             :         - \c DBSINGLE Doubles all single quotes (').
    6457             :         - \c DBDOUBLE Doubles all double quotes (").
    6458             :         - \c DBBOTH   Doubles all single and double quotes.
    6459             :  * \retval SUCCEED everything worked.
    6460             :  * \retval FAIL no such \a quotetype, or insufficient room in \a dest.
    6461             :  * \sa dbcmd(), dbfcmd(). 
    6462             :  */
    6463             : RETCODE
    6464          50 : dbsafestr(DBPROCESS * dbproc, const char *src, DBINT srclen, char *dest, DBINT destlen, int quotetype)
    6465             : {
    6466          50 :         int i, j = 0;
    6467          50 :         bool squote = false, dquote = false;
    6468             : 
    6469          50 :         tdsdump_log(TDS_DBG_FUNC, "dbsafestr(%p, %s, %d, %s, %d, %d)\n", dbproc, src, srclen, dest, destlen, quotetype);
    6470          50 :         CHECK_NULP(src, "dbsafestr", 2, FAIL);
    6471          50 :         CHECK_NULP(dest, "dbsafestr", 4, FAIL);
    6472             : 
    6473             :         /* check parameters */
    6474          50 :         if (srclen < -1 || destlen < -1)
    6475             :                 return FAIL;
    6476             : 
    6477          50 :         if (srclen == -1)
    6478          50 :                 srclen = (int)strlen(src);
    6479             : 
    6480          50 :         if (quotetype == DBSINGLE || quotetype == DBBOTH)
    6481          40 :                 squote = true;
    6482          50 :         if (quotetype == DBDOUBLE || quotetype == DBBOTH)
    6483          30 :                 dquote = true;
    6484             : 
    6485             :         /* return FAIL if invalid quotetype */
    6486          50 :         if (!dquote && !squote)
    6487             :                 return FAIL;
    6488             : 
    6489             : 
    6490        1790 :         for (i = 0; i < srclen; i++) {
    6491             : 
    6492             :                 /* dbsafestr returns fail if the deststr is not big enough */
    6493             :                 /* need one char + one for terminator */
    6494        1800 :                 if (destlen >= 0 && j >= destlen)
    6495             :                         return FAIL;
    6496             : 
    6497        1790 :                 if (squote && src[i] == '\'')
    6498          40 :                         dest[j++] = '\'';
    6499        1750 :                 else if (dquote && src[i] == '\"')
    6500          30 :                         dest[j++] = '\"';
    6501             : 
    6502        1790 :                 if (destlen >= 0 && j >= destlen)
    6503             :                         return FAIL;
    6504             : 
    6505        1790 :                 dest[j++] = src[i];
    6506             :         }
    6507             : 
    6508          40 :         if (destlen >= 0 && j >= destlen)
    6509             :                 return FAIL;
    6510             : 
    6511          30 :         dest[j] = '\0';
    6512          30 :         return SUCCEED;
    6513             : }
    6514             : 
    6515             : /**
    6516             :  * \ingroup dblib_core
    6517             :  * \brief Print a token value's name to a buffer
    6518             :  * 
    6519             :  * \param token server SYB* value, e.g. SYBINT.  
    6520             : 
    6521             :  * \return ASCII null-terminated string.  
    6522             :  * \sa dbaltop(), dbalttype(), dbcoltype(), dbrettype().
    6523             :  */
    6524             : const char *
    6525          24 : dbprtype(int token)
    6526             : {
    6527          24 :         tdsdump_log(TDS_DBG_FUNC, "dbprtype(%d)\n", token);
    6528          24 :         return tds_prtype(token);
    6529             : }
    6530             : 
    6531             : /**
    6532             :  * \ingroup dblib_core
    6533             :  * \brief describe table column attributes with a single call (Freetds-only API function modelled on dbcolinfo)
    6534             :  * 
    6535             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6536             :  * \param column Nth in the result set, starting from 1.
    6537             :  * \param pdbcol address of structure to be populated by this function.  
    6538             :  * \return SUCCEED or FAIL. 
    6539             :  * \sa dbcolinfo().
    6540             :  */
    6541             : RETCODE
    6542          30 : dbtablecolinfo(DBPROCESS *dbproc, DBINT column, DBCOL *pdbcol)
    6543             : {
    6544             :         TDSCOLUMN *colinfo;
    6545             : 
    6546          30 :         tdsdump_log(TDS_DBG_FUNC, "dbtablecolinfo(%p, %d, %p)\n", dbproc, column, pdbcol);
    6547          30 :         CHECK_CONN(FAIL);
    6548          30 :         CHECK_NULP(pdbcol, "dbtablecolinfo", 3, FAIL);
    6549          30 :         DBPERROR_RETURN(pdbcol->SizeOfStruct != sizeof(DBCOL)
    6550             :                         && pdbcol->SizeOfStruct != sizeof(DBCOL2), SYBECOLSIZE);
    6551             : 
    6552          30 :         colinfo = dbcolptr(dbproc, column);
    6553          30 :         if (!colinfo)
    6554             :                 return FAIL;
    6555             : 
    6556          60 :         strlcpy(pdbcol->Name, tds_dstr_cstr(&colinfo->column_name), sizeof(pdbcol->Name));
    6557             :         /* returns table_column_name if available */
    6558          60 :         if (tds_dstr_isempty(&colinfo->table_column_name))
    6559          16 :                 strlcpy(pdbcol->ActualName, tds_dstr_cstr(&colinfo->column_name), sizeof(pdbcol->ActualName));
    6560             :         else
    6561          44 :                 strlcpy(pdbcol->ActualName, tds_dstr_cstr(&colinfo->table_column_name), sizeof(pdbcol->ActualName));
    6562          60 :         strlcpy(pdbcol->TableName, tds_dstr_cstr(&colinfo->table_name), sizeof(pdbcol->TableName));
    6563             : 
    6564          30 :         pdbcol->Type = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
    6565          30 :         pdbcol->UserType = colinfo->column_usertype;
    6566          30 :         pdbcol->MaxLength = colinfo->column_size;
    6567          30 :         if (colinfo->column_nullable)
    6568           0 :                 pdbcol->Null = TRUE;
    6569             :         else
    6570          30 :                 pdbcol->Null = FALSE;
    6571             : 
    6572          30 :         pdbcol->VarLength = FALSE;
    6573             : 
    6574          30 :         if (colinfo->column_nullable
    6575          30 :             || is_nullable_type(colinfo->column_type))
    6576           0 :                 pdbcol->VarLength = TRUE;
    6577             :         
    6578          30 :         pdbcol->Precision = colinfo->column_prec;
    6579          30 :         pdbcol->Scale = colinfo->column_scale;
    6580             : 
    6581          30 :         pdbcol->Updatable = colinfo->column_writeable ? TRUE : FALSE;
    6582          30 :         pdbcol->Identity = colinfo->column_identity ? TRUE : FALSE;
    6583             : 
    6584          30 :         if (pdbcol->SizeOfStruct >= sizeof(DBCOL2)) {
    6585          30 :                 DBCOL2 *col = (DBCOL2 *) pdbcol;
    6586             :                 TDSRET rc;
    6587             : 
    6588          30 :                 col->ServerType = colinfo->on_server.column_type;
    6589          30 :                 col->ServerMaxLength = colinfo->on_server.column_size;
    6590             : 
    6591          30 :                 rc = tds_get_column_declaration(dbproc->tds_socket, colinfo, col->ServerTypeDeclaration);
    6592          30 :                 if (TDS_FAILED(rc))
    6593             :                         return FAIL;
    6594             :         }
    6595             : 
    6596             :         return SUCCEED;
    6597             : }
    6598             : 
    6599             : /**
    6600             :  * \ingroup dblib_core
    6601             :  * \brief Get text timestamp for a column in the current row.
    6602             :  * 
    6603             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6604             :  * \param column number of the column in the \c SELECT statement, starting at 1.
    6605             :  * \return timestamp for \a column, may be NULL.
    6606             :  * \sa dbtxptr(), dbwritetext().  
    6607             :  */
    6608             : DBBINARY *
    6609          56 : dbtxtimestamp(DBPROCESS * dbproc, int column)
    6610             : {
    6611             :         TDSCOLUMN *colinfo;
    6612             :         TDSBLOB *blob;
    6613             : 
    6614          56 :         tdsdump_log(TDS_DBG_FUNC, "dbtxtimestamp(%p, %d)\n", dbproc, column);
    6615             : 
    6616          56 :         colinfo = dbcolptr(dbproc, column);
    6617          56 :         if (!colinfo || !is_blob_col(colinfo))
    6618             :                 return NULL;
    6619             : 
    6620          56 :         blob = (TDSBLOB *) colinfo->column_data;
    6621             : 
    6622             :         /* test if valid */
    6623          56 :         if (!blob->valid_ptr)
    6624             :                 return NULL;
    6625             : 
    6626          36 :         return (DBBINARY *) blob->timestamp;
    6627             : }
    6628             : 
    6629             : /**
    6630             :  * \ingroup dblib_core
    6631             :  * \brief Get text pointer for a column in the current row.
    6632             :  * 
    6633             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6634             :  * \param column number of the column in the \c SELECT statement, starting at 1.
    6635             :  * \return text pointer for \a column, may be NULL.
    6636             :  * \sa dbtxtimestamp(), dbwritetext(). 
    6637             :  */
    6638             : DBBINARY *
    6639          56 : dbtxptr(DBPROCESS * dbproc, int column)
    6640             : {
    6641             :         TDSCOLUMN *colinfo;
    6642             :         TDSBLOB *blob;
    6643             : 
    6644          56 :         tdsdump_log(TDS_DBG_FUNC, "dbtxptr(%p, %d)\n", dbproc, column);
    6645             : 
    6646          56 :         colinfo = dbcolptr(dbproc, column);
    6647          56 :         if (!colinfo || !is_blob_col(colinfo))
    6648             :                 return NULL;
    6649             : 
    6650          56 :         blob = (TDSBLOB *) colinfo->column_data;
    6651             : 
    6652             :         /* test if valid */
    6653          56 :         if (!blob->valid_ptr)
    6654             :                 return NULL;
    6655             : 
    6656          36 :         return (DBBINARY *) blob->textptr;
    6657             : }
    6658             : 
    6659             : /**
    6660             :  * \ingroup dblib_core
    6661             :  * \brief Send text or image data to the server.
    6662             :  * 
    6663             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6664             :  * \param objname table name
    6665             :  * \param textptr text pointer to be modified, obtained from dbtxptr(). 
    6666             :  * \param textptrlen \em Ignored.  Supposed to be \c DBTXPLEN.
    6667             :  * \param timestamp text timestamp to be modified, obtained from dbtxtimestamp() or dbtxtsnewval(), may be \c NULL.
    6668             :  * \param log \c TRUE if the operation is to be recorded in the transaction log.
    6669             :  * \param size overall size of the data (in total, not just for this call), in bytes.  A guideline, must not overstate the case.  
    6670             :  * \param text the chunk of data to write.  
    6671             :  * \retval SUCCEED everything worked.
    6672             :  * \retval FAIL not sent, possibly because \a timestamp is invalid or was changed in the database since it was fetched.  
    6673             :  * \sa dbmoretext(), dbtxptr(), dbtxtimestamp(), dbwritetext(), dbtxtsput().  
    6674             :  */
    6675             : RETCODE
    6676          36 : dbwritetext(DBPROCESS * dbproc, char *objname, DBBINARY * textptr, DBTINYINT textptrlen, DBBINARY * timestamp, DBBOOL log,
    6677             :             DBINT size, BYTE * text)
    6678             : {
    6679             :         char textptr_string[35];        /* 16 * 2 + 2 (0x) + 1 */
    6680             :         char timestamp_string[19];      /* 8 * 2 + 2 (0x) + 1 */
    6681             :         TDS_INT result_type;
    6682             : 
    6683          36 :         tdsdump_log(TDS_DBG_FUNC, "dbwritetext(%p, %s, %p, %d, %p, %d)\n", 
    6684             :                                   dbproc, objname, textptr, textptrlen, timestamp, log);
    6685          36 :         CHECK_CONN(FAIL);
    6686          36 :         CHECK_NULP(objname, "dbwritetext", 2, FAIL);
    6687          36 :         CHECK_NULP(textptr, "dbwritetext", 3, FAIL);
    6688          36 :         CHECK_NULP(timestamp, "dbwritetext", 5, FAIL);
    6689          36 :         CHECK_PARAMETER(size, SYBEZTXT, FAIL);
    6690             : 
    6691             :         if (IS_TDSDEAD(dbproc->tds_socket))
    6692             :                 return FAIL;
    6693             : 
    6694          36 :         if (textptrlen > DBTXPLEN)
    6695             :                 return FAIL;
    6696             : 
    6697          36 :         dbconvert(dbproc, SYBBINARY, (BYTE *) textptr, textptrlen, SYBCHAR, (BYTE *) textptr_string, -1);
    6698          36 :         dbconvert(dbproc, SYBBINARY, (BYTE *) timestamp, 8, SYBCHAR, (BYTE *) timestamp_string, -1);
    6699             : 
    6700          36 :         dbproc->dbresults_state = _DB_RES_INIT;
    6701             : 
    6702          36 :         if (dbproc->tds_socket->state == TDS_PENDING) {
    6703           0 :                 const TDSRET ret = tds_process_tokens(dbproc->tds_socket, &result_type, NULL, TDS_TOKEN_TRAILING);
    6704           0 :                 if (ret != TDS_NO_MORE_RESULTS) {
    6705           0 :                         dbperror(dbproc, SYBERPND, 0);
    6706           0 :                         dbproc->command_state = DBCMDSENT;
    6707           0 :                         return FAIL;
    6708             :                 }
    6709             :         }
    6710             :         
    6711          36 :         if (TDS_FAILED(tds_writetext_start(dbproc->tds_socket, objname, 
    6712             :                 textptr_string, timestamp_string, (log == TRUE), size)))
    6713             :                 return FAIL;
    6714             : 
    6715          36 :         if (!text) {
    6716          18 :                 dbproc->text_size = size;
    6717          18 :                 dbproc->text_sent = 0;
    6718          18 :                 return SUCCEED;
    6719             :         }
    6720             : 
    6721          18 :         tds_writetext_continue(dbproc->tds_socket, text, size);
    6722          18 :         tds_writetext_end(dbproc->tds_socket);
    6723          18 :         dbproc->text_sent = 0;
    6724             : 
    6725          18 :         if (dbsqlok(dbproc) == SUCCEED && dbresults(dbproc) == SUCCEED)
    6726             :                 return SUCCEED;
    6727             :         return FAIL;
    6728             : }
    6729             : 
    6730             : /**
    6731             :  * \ingroup dblib_core
    6732             :  * \brief Fetch part of a text or image value from the server.
    6733             :  * 
    6734             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6735             :  * \param buf \em output: buffer into which text will be placed.
    6736             :  * \param bufsize size of \a buf, in bytes. 
    6737             :  * \return 
    6738             :         - \c >0 count of bytes placed in \a buf.
    6739             :         - \c  0 end of row.  
    6740             :         - \c -1 \em error, no result set ready for \a dbproc.
    6741             :         - \c NO_MORE_ROWS all rows read, no further data. 
    6742             :  * \sa dbmoretext(), dbnextrow(), dbwritetext(). 
    6743             :  */
    6744             : STATUS
    6745         636 : dbreadtext(DBPROCESS * dbproc, void *buf, DBINT bufsize)
    6746             : {
    6747             :         TDSSOCKET *tds;
    6748             :         TDSCOLUMN *curcol;
    6749             :         int cpbytes, bytes_avail;
    6750             :         TDS_INT result_type;
    6751             :         TDSRESULTINFO *resinfo;
    6752             : 
    6753         636 :         tdsdump_log(TDS_DBG_FUNC, "dbreadtext(%p, %p, %d)\n", dbproc, buf, bufsize);
    6754         636 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    6755         636 :         CHECK_NULP(buf, "dbreadtext", 2, -1);
    6756             : 
    6757         636 :         tds = dbproc->tds_socket;
    6758             : 
    6759         636 :         if (!tds || !tds->res_info || !tds->res_info->columns[0])
    6760             :                 return -1;
    6761             : 
    6762         636 :         resinfo = tds->res_info;
    6763         636 :         curcol = resinfo->columns[0];
    6764             : 
    6765             :         /*
    6766             :          * if the current position is beyond the end of the text
    6767             :          * set pos to 0 and return 0 to denote the end of the 
    6768             :          * text 
    6769             :          */
    6770         636 :         if (curcol->column_textpos && curcol->column_textpos >= curcol->column_cur_size) {
    6771          36 :                 curcol->column_textpos = 0;
    6772          36 :                 return 0;
    6773             :         }
    6774             : 
    6775             :         /*
    6776             :          * if pos is 0 (first time through or last call exhausted the text)
    6777             :          * then read another row
    6778             :          */
    6779             : 
    6780         600 :         if (curcol->column_textpos == 0) {
    6781          96 :                 const int mask = TDS_STOPAT_ROWFMT|TDS_STOPAT_DONE|TDS_RETURN_ROW|TDS_RETURN_COMPUTE;
    6782          96 :                 buffer_save_row(dbproc);
    6783          96 :                 switch (tds_process_tokens(dbproc->tds_socket, &result_type, NULL, mask)) {
    6784          96 :                 case TDS_SUCCESS:
    6785          96 :                         if (result_type == TDS_ROW_RESULT || result_type == TDS_COMPUTE_RESULT)
    6786             :                                 break;
    6787             :                 case TDS_NO_MORE_RESULTS:
    6788             :                         return NO_MORE_ROWS;
    6789           0 :                 default:
    6790           0 :                         return -1;
    6791             :                 }
    6792         552 :         }
    6793             : 
    6794             :         /* find the number of bytes to return */
    6795         552 :         bytes_avail = TDS_MAX(curcol->column_cur_size, 0) - curcol->column_textpos;
    6796         552 :         cpbytes = bytes_avail > bufsize ? bufsize : bytes_avail;
    6797         552 :         memcpy(buf, &((TDSBLOB *) curcol->column_data)->textvalue[curcol->column_textpos], cpbytes);
    6798         552 :         curcol->column_textpos += cpbytes;
    6799         552 :         return cpbytes;
    6800             : }
    6801             : 
    6802             : /**
    6803             :  * \ingroup dblib_core
    6804             :  * \brief Send chunk of a text/image value to the server.
    6805             :  * 
    6806             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6807             :  * \param size count of bytes to send.  
    6808             :  * \param text textpointer, obtained from dbtxptr.
    6809             :  * \retval SUCCEED always.
    6810             :  * \sa dbtxptr(), dbtxtimestamp(), dbwritetext(). 
    6811             :  * \todo Check return value of called functions and return \c FAIL if appropriate. 
    6812             :  */
    6813             : RETCODE
    6814         270 : dbmoretext(DBPROCESS * dbproc, DBINT size, const BYTE text[])
    6815             : {
    6816         270 :         tdsdump_log(TDS_DBG_FUNC, "dbmoretext(%p, %d, %p)\n", dbproc, size, text);
    6817         270 :         CHECK_CONN(FAIL);
    6818         270 :         CHECK_NULP(text, "dbmoretext", 3, FAIL);
    6819             : 
    6820         270 :         assert(dbproc->text_size >= dbproc->text_sent);
    6821             : 
    6822             :         /* TODO this test should be inside tds_writetext_continue, currently not */
    6823         270 :         if (size < 0 || size > dbproc->text_size - dbproc->text_sent)
    6824             :                 return FAIL;
    6825             : 
    6826         270 :         if (size) {
    6827         270 :                 if (TDS_FAILED(tds_writetext_continue(dbproc->tds_socket, text, size)))
    6828             :                         return FAIL;
    6829         270 :                 dbproc->text_sent += size;
    6830             : 
    6831         270 :                 if (dbproc->text_sent == dbproc->text_size) {
    6832          18 :                         tds_writetext_end(dbproc->tds_socket);
    6833          18 :                         dbproc->text_sent = 0;
    6834             :                 }
    6835             :         }
    6836             : 
    6837             :         return SUCCEED;
    6838             : }
    6839             : 
    6840             : /**
    6841             :  * \ingroup dblib_core
    6842             :  * \brief Record to a file all SQL commands sent to the server
    6843             :  * 
    6844             :  * \param filename name of file to write to. 
    6845             :  * \remarks Files are named \em filename.n, where n is an integer, starting with 0, and incremented with each callto dbopen().  
    6846             :  * \sa dbopen(), TDSDUMP environment variable(). 
    6847             :  */
    6848             : void
    6849           0 : dbrecftos(const char filename[])
    6850             : {
    6851             :         char *f;
    6852             : 
    6853           0 :         tdsdump_log(TDS_DBG_FUNC, "dbrecftos(%s)\n", filename);
    6854           0 :         if (filename == NULL) { 
    6855           0 :                 dbperror(NULL, SYBENULP, 0); 
    6856           0 :                 return;
    6857             :         }
    6858             :         
    6859           0 :         f = strdup(filename);
    6860           0 :         if (!f) {
    6861           0 :                 dbperror(NULL, SYBEMEM, 0); 
    6862           0 :                 return;
    6863             :         }
    6864             :         
    6865           0 :         tds_mutex_lock(&dblib_mutex);
    6866           0 :         free(g_dblib_ctx.recftos_filename);
    6867           0 :         g_dblib_ctx.recftos_filename = f;
    6868           0 :         g_dblib_ctx.recftos_filenum = 0;
    6869           0 :         tds_mutex_unlock(&dblib_mutex);
    6870             : }
    6871             : 
    6872             : /** \internal
    6873             :  * \ingroup dblib_internal
    6874             :  * \brief Get the TDS version in use for \a dbproc.  
    6875             :  * 
    6876             :  * 
    6877             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6878             :  * \return a \c DBTDS* token.  
    6879             :  * \remarks The integer values of the constants are counterintuitive.  
    6880             :  * \sa DBTDS().
    6881             :  */
    6882             : int
    6883         464 : dbtds(DBPROCESS * dbproc)
    6884             : {
    6885         464 :         tdsdump_log(TDS_DBG_FUNC, "dbtds(%p)\n", dbproc);
    6886         464 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    6887             : 
    6888         464 :         if (dbproc->tds_socket) {
    6889         464 :                 switch (dbproc->tds_socket->conn->tds_version) {
    6890             :                 case 0x402:
    6891             :                         return DBTDS_4_2;
    6892           0 :                 case 0x406:
    6893           0 :                         return DBTDS_4_6;
    6894          78 :                 case 0x500:
    6895          78 :                         return DBTDS_5_0;
    6896           0 :                 case 0x700:
    6897           0 :                         return DBTDS_7_0;
    6898         184 :                 case 0x701:
    6899         184 :                         return DBTDS_7_1;
    6900           0 :                 case 0x702:
    6901           0 :                         return DBTDS_7_2;
    6902         100 :                 case 0x703:
    6903         100 :                         return DBTDS_7_3;
    6904         102 :                 case 0x704:
    6905         102 :                         return DBTDS_7_4;
    6906           0 :                 case 0x800:
    6907           0 :                         return DBTDS_8_0_;
    6908           0 :                 default:
    6909           0 :                         return DBTDS_UNKNOWN;
    6910             :                 }
    6911             :         }
    6912             :         return -1;
    6913             : }
    6914             : 
    6915             : /**
    6916             :  * \ingroup dblib_core
    6917             :  * \brief See which version of db-lib is in use.
    6918             :  * 
    6919             :  * \return null-terminated ASCII string representing the version of db-lib.  
    6920             :  * \remarks FreeTDS returns the CVS version string of dblib.c.  
    6921             :  * \sa 
    6922             :  */
    6923             : const char *
    6924           0 : dbversion(void)
    6925             : {
    6926           0 :         tdsdump_log(TDS_DBG_FUNC, "dbversion(void)\n");
    6927           0 :         return TDS_VERSION_NO;
    6928             : }
    6929             : 
    6930             : #if defined(DBLIB_UNIMPLEMENTED)
    6931             : /**
    6932             :  * \ingroup dblib_core
    6933             :  * \brief Set the default character set.  
    6934             :  * 
    6935             :  * \param charset null-terminated ASCII string, matching a row in master..syscharsets.  
    6936             :  * \sa dbsetdeflang(), dbsetdefcharset(), dblogin(), dbopen(). 
    6937             :  * \todo Unimplemented.
    6938             :  */
    6939             : RETCODE
    6940             : dbsetdefcharset(char *charset)
    6941             : {
    6942             :         tdsdump_log(TDS_DBG_FUNC, "dbsetdefcharset(%s)\n", charset);
    6943             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbsetdefcharset()\n");
    6944             :         return SUCCEED;
    6945             : }
    6946             : 
    6947             : /**
    6948             :  * \ingroup dblib_core
    6949             :  * \brief Ready execution of a registered procedure.
    6950             :  * 
    6951             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6952             :  * \param procedure_name to call.
    6953             :  * \param namelen size of \a procedure_name, in bytes.
    6954             :  * \sa dbregparam(), dbregexec(), dbregwatch(), dbreglist(), dbregwatchlist
    6955             :  * \todo Unimplemented.
    6956             :  */
    6957             : RETCODE
    6958             : dbreginit(DBPROCESS * dbproc, DBCHAR * procedure_name, DBSMALLINT namelen)
    6959             : {
    6960             :         tdsdump_log(TDS_DBG_FUNC, "dbreginit(%p, %s, %d)\n", dbproc, procedure_name, namelen);
    6961             :         CHECK_CONN(FAIL);
    6962             :         CHECK_NULP(procedure_name, "dbreginit", 2, FAIL);
    6963             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbreginit()\n");
    6964             :         return SUCCEED;
    6965             : }
    6966             : 
    6967             : 
    6968             : /**
    6969             :  * \ingroup dblib_core
    6970             :  * \brief Get names of Open Server registered procedures.
    6971             :  * 
    6972             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6973             :  * \sa dbregparam(), dbregexec(), dbregwatch(), dbreglist(), dbregwatchlist(). 
    6974             :  * \todo Unimplemented.
    6975             :  */
    6976             : RETCODE
    6977             : dbreglist(DBPROCESS * dbproc)
    6978             : {
    6979             :         tdsdump_log(TDS_DBG_FUNC, "dbreglist(%p)\n", dbproc);
    6980             :         CHECK_CONN(FAIL);
    6981             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbreglist()\n");
    6982             :         return SUCCEED;
    6983             : }
    6984             : 
    6985             : 
    6986             : /**
    6987             :  * \ingroup dblib_core
    6988             :  * \brief  Describe parameter of registered procedure .
    6989             :  * 
    6990             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    6991             :  * \param param_name
    6992             :  * \param type \c SYB* datatype. 
    6993             :  * \param datalen size of \a data.
    6994             :  * \param data address of buffer holding value for the parameter.  
    6995             :  * \sa dbreginit(), dbregexec(), dbnpdefine(), dbnpcreate(), dbregwatch(). 
    6996             :  * \todo Unimplemented.
    6997             :  */
    6998             : RETCODE
    6999             : dbregparam(DBPROCESS * dbproc, char *param_name, int type, DBINT datalen, BYTE * data)
    7000             : {
    7001             :         tdsdump_log(TDS_DBG_FUNC, "dbregparam(%p, %s, %d, %d, %p)\n", dbproc, param_name, type, datalen, data);
    7002             :         CHECK_CONN(FAIL);
    7003             :         CHECK_NULP(param_name, "dbregparam", 2, FAIL);
    7004             :         CHECK_NULP(data, "dbregparam", 5, FAIL);
    7005             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbregparam()\n");
    7006             :         return SUCCEED;
    7007             : }
    7008             : 
    7009             : 
    7010             : /**
    7011             :  * \ingroup dblib_core
    7012             :  * \brief Execute a registered procedure.
    7013             :  * 
    7014             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7015             :  * \param options
    7016             :  * \sa dbreginit(), dbregparam(), dbregwatch(), dbregnowatch
    7017             :  * \todo Unimplemented.
    7018             :  */
    7019             : RETCODE
    7020             : dbregexec(DBPROCESS * dbproc, DBUSMALLINT options)
    7021             : {
    7022             :         tdsdump_log(TDS_DBG_FUNC, "dbregexec(%p, %d)\n", dbproc, options);
    7023             :         CHECK_CONN(FAIL);
    7024             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbregexec()\n");
    7025             :         return SUCCEED;
    7026             : }
    7027             : #endif
    7028             : 
    7029             : 
    7030             : /**
    7031             :  * \ingroup dblib_datetime
    7032             :  * \brief Get name of a month, in some human language.
    7033             :  * 
    7034             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7035             :  * \param language \em ignored.
    7036             :  * \param monthnum number of the month, starting with 1.
    7037             :  * \param shortform set to \c TRUE for a three letter output ("Jan" - "Dec"), else zero.  
    7038             :  * \return address of null-terminated ASCII string, or \c NULL on error. 
    7039             :  * \sa db12hour(), dbdateorder(), dbdayname(), DBSETLNATLANG(), dbsetopt().  
    7040             :  */
    7041             : const char *
    7042           0 : dbmonthname(DBPROCESS * dbproc, char *language, int monthnum, DBBOOL shortform)
    7043             : {
    7044             :         static const char shortmon[][4] = {
    7045             :                 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    7046             :         };
    7047             :         static const char longmon[][12] = {
    7048             :                 "January", "February", "March", "April", "May", "June",
    7049             :                 "July", "August", "September", "October", "November", "December"
    7050             :         };
    7051             : 
    7052           0 :         tdsdump_log(TDS_DBG_FUNC, "dbmonthname(%p, %s, %d, %d)\n", dbproc, language, monthnum, shortform);
    7053           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    7054           0 :         CHECK_NULP(language, "dbmonthname", 2, NULL);
    7055             : 
    7056           0 :         if (monthnum < 1 || monthnum > 12)
    7057             :                 return NULL;
    7058           0 :         return (shortform) ? shortmon[monthnum - 1] : longmon[monthnum - 1];
    7059             : }
    7060             : 
    7061             : /**
    7062             :  * \ingroup dblib_core
    7063             :  * \brief See if a command caused the current database to change.
    7064             :  * 
    7065             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7066             :  * \return name of new database, if changed, as a null-terminated ASCII string, else \c NULL.
    7067             : 
    7068             :  * \sa dbname(), dbresults(), dbsqlexec(), dbsqlsend(), dbuse().  
    7069             :  */
    7070             : char *
    7071           0 : dbchange(DBPROCESS * dbproc)
    7072             : {
    7073           0 :         tdsdump_log(TDS_DBG_FUNC, "dbchange(%p)\n", dbproc);
    7074           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    7075             : 
    7076           0 :         if (dbproc->envchange_rcv & (1 << (TDS_ENV_DATABASE - 1))) {
    7077           0 :                 return dbproc->dbcurdb;
    7078             :         }
    7079             :         return NULL;
    7080             : }
    7081             : 
    7082             : /**
    7083             :  * \ingroup dblib_core
    7084             :  * \brief Get name of current database.
    7085             :  * 
    7086             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7087             :  * \return current database name, as null-terminated ASCII string.
    7088             :  * \sa dbchange(), dbuse().  
    7089             :  */
    7090             : char *
    7091           0 : dbname(DBPROCESS * dbproc)
    7092             : {
    7093           0 :         tdsdump_log(TDS_DBG_FUNC, "dbname(%p)\n", dbproc);
    7094           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    7095           0 :         return dbproc->dbcurdb;
    7096             : }
    7097             : 
    7098             : /**
    7099             :  * \ingroup dblib_core
    7100             :  * \brief Get \c syscharset name of the server character set.
    7101             :  * 
    7102             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7103             :  * \return name of server's charset, as null-terminated ASCII string.
    7104             :  * \sa dbcharsetconv(), dbgetcharset(), DBSETLCHARSET().  
    7105             :  */
    7106             : char *
    7107           0 : dbservcharset(DBPROCESS * dbproc)
    7108             : {
    7109             : 
    7110           0 :         tdsdump_log(TDS_DBG_FUNC, "dbservcharset(%p)\n", dbproc);
    7111           0 :         CHECK_PARAMETER(dbproc, SYBENULL, NULL);
    7112             : 
    7113           0 :         return dbproc->servcharset;
    7114             : }
    7115             : 
    7116             : /**
    7117             :  * \ingroup dblib_core
    7118             :  * \brief Transmit the command buffer to the server.  \em Non-blocking, does not wait for a response.
    7119             :  * 
    7120             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7121             :  * \retval SUCCEED SQL sent.
    7122             :  * \retval FAIL protocol problem, unless dbsqlsend() when it's not supposed to be (in which case a db-lib error
    7123             :  message will be emitted).  
    7124             :  * \sa dbcmd(), dbfcmd(), DBIORDESC(), DBIOWDESC(), dbnextrow(), dbpoll(), dbresults(), dbsettime(), dbsqlexec(), dbsqlok().  
    7125             :  */
    7126             : RETCODE
    7127       20484 : dbsqlsend(DBPROCESS * dbproc)
    7128             : {
    7129             :         TDSSOCKET *tds;
    7130             :         char *cmdstr;
    7131             :         TDSRET rc;
    7132             :         TDS_INT result_type;
    7133             :         char timestr[256];
    7134             : 
    7135       20484 :         tdsdump_log(TDS_DBG_FUNC, "dbsqlsend(%p)\n", dbproc);
    7136       20484 :         CHECK_CONN(FAIL);
    7137             : 
    7138       20484 :         tds = dbproc->tds_socket;
    7139             : 
    7140       20484 :         if (tds->state == TDS_PENDING) {
    7141             : 
    7142         130 :                 if (tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_TRAILING) != TDS_NO_MORE_RESULTS) {
    7143          70 :                         dbperror(dbproc, SYBERPND, 0);
    7144          70 :                         dbproc->command_state = DBCMDSENT;
    7145          70 :                         return FAIL;
    7146             :                 }
    7147             :         }
    7148             : 
    7149       20414 :         if (dbproc->dboptcmd) {
    7150           0 :                 if ((cmdstr = dbstring_get(dbproc->dboptcmd)) == NULL) {
    7151           0 :                         dbperror(dbproc, SYBEASEC, 0); /* Attempt to send an empty command buffer to the server */
    7152           0 :                         return FAIL;
    7153             :                 }
    7154           0 :                 rc = tds_submit_query(dbproc->tds_socket, cmdstr);
    7155           0 :                 free(cmdstr);
    7156           0 :                 dbstring_free(&(dbproc->dboptcmd));
    7157           0 :                 if (TDS_FAILED(rc)) {
    7158             :                         return FAIL;
    7159             :                 }
    7160           0 :                 dbproc->avail_flag = FALSE;
    7161           0 :                 dbproc->envchange_rcv = 0;
    7162           0 :                 dbproc->dbresults_state = _DB_RES_INIT;
    7163           0 :                 while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS))
    7164             :                        == TDS_SUCCESS);
    7165           0 :                 if (rc != TDS_NO_MORE_RESULTS) {
    7166             :                         return FAIL;
    7167             :                 }
    7168             :         }
    7169       20414 :         dbproc->more_results = TRUE;
    7170             : 
    7171       20414 :         if (dbproc->ftos != NULL) {
    7172           0 :                 fprintf(dbproc->ftos, "%s\n", dbproc->dbbuf);
    7173           0 :                 fprintf(dbproc->ftos, "go /* %s */\n", _dbprdate(timestr));
    7174           0 :                 fflush(dbproc->ftos);
    7175             :         }
    7176             : 
    7177       20414 :         if (TDS_FAILED(tds_submit_query(dbproc->tds_socket, (char *) dbproc->dbbuf))) {
    7178             :                 return FAIL;
    7179             :         }
    7180       20404 :         dbproc->avail_flag = FALSE;
    7181       20404 :         dbproc->envchange_rcv = 0;
    7182       20404 :         dbproc->dbresults_state = _DB_RES_INIT;
    7183       20404 :         dbproc->command_state = DBCMDSENT;
    7184       20404 :         return SUCCEED;
    7185             : }
    7186             : 
    7187             : /**
    7188             :  * \ingroup dblib_core
    7189             :  * \brief Get user-defined datatype of a compute column.
    7190             :  * 
    7191             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7192             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    7193             :  * \param column Nth column in \a computeid, starting from 1.
    7194             :  * \returns user-defined datatype of compute column, else -1.
    7195             :  * \sa dbalttype(), dbcolutype().
    7196             :  */
    7197             : DBINT
    7198           0 : dbaltutype(DBPROCESS * dbproc, int computeid, int column)
    7199             : {
    7200             :         TDSCOLUMN *colinfo;
    7201             : 
    7202           0 :         tdsdump_log(TDS_DBG_FUNC, "dbaltutype(%p, %d, %d)\n", dbproc, computeid, column);
    7203             : 
    7204           0 :         colinfo = dbacolptr(dbproc, computeid, column, false);
    7205           0 :         if (!colinfo)
    7206             :                 return -1;
    7207             : 
    7208           0 :         return colinfo->column_usertype;
    7209             : }
    7210             : 
    7211             : /**
    7212             :  * \ingroup dblib_core
    7213             :  * \brief Get size of data in compute column.
    7214             :  * 
    7215             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7216             :  * \param computeid of \c COMPUTE clause to which we're referring. 
    7217             :  * \param column Nth column in \a computeid, starting from 1.
    7218             :  * \sa dbadata(), dbadlen(), dbalttype(), dbgetrow(), dbnextrow(), dbnumalts().
    7219             :  */
    7220             : DBINT
    7221           0 : dbaltlen(DBPROCESS * dbproc, int computeid, int column)
    7222             : {
    7223             :         TDSCOLUMN *colinfo;
    7224             : 
    7225           0 :         tdsdump_log(TDS_DBG_FUNC, "dbaltlen(%p, %d, %d)\n", dbproc, computeid, column);
    7226             : 
    7227           0 :         colinfo = dbacolptr(dbproc, computeid, column, false);
    7228           0 :         if (!colinfo)
    7229             :                 return -1;
    7230             : 
    7231           0 :         return colinfo->column_size;
    7232             : 
    7233             : }
    7234             : 
    7235             : /**
    7236             :  * \ingroup dblib_core
    7237             :  * \brief See if a server response has arrived.
    7238             :  * 
    7239             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7240             :  * \param milliseconds how long to wait for the server before returning:
    7241             :         - \c  0 return immediately.
    7242             :         - \c -1 do not return until the server responds or a system interrupt occurs.
    7243             :  * \param ready_dbproc \em output: DBPROCESS for which a response arrived, of \c NULL. 
    7244             :  * \param return_reason \em output: 
    7245             :         - \c DBRESULT server responded.
    7246             :         - \c DBNOTIFICATION registered procedure notification has arrived. dbpoll() the registered handler, if
    7247             :                 any, before it returns.
    7248             :         - \c DBTIMEOUT \a milliseconds elapsed before the server responded.
    7249             :         - \c DBINTERRUPT operating-system interrupt occurred before the server responded.
    7250             :  * \retval SUCCEED everything worked.
    7251             :  * \retval FAIL a server connection died.
    7252             :  * \sa  DBIORDESC(), DBRBUF(), dbresults(), dbreghandle(), dbsqlok(). 
    7253             :  * \todo Unimplemented.
    7254             :  */
    7255             : #if defined(DBLIB_UNIMPLEMENTED)
    7256             : RETCODE
    7257             : dbpoll(DBPROCESS * dbproc, long milliseconds, DBPROCESS ** ready_dbproc, int *return_reason)
    7258             : {
    7259             :         tdsdump_log(TDS_DBG_FUNC, "dbpoll(%p, %ld, %p, %p)\n", dbproc, milliseconds, ready_dbproc, return_reason);
    7260             :         CHECK_CONN(FAIL);
    7261             :         CHECK_NULP(ready_dbproc, "dbpoll", 3, FAIL);
    7262             :         CHECK_NULP(return_reason, "dbpoll", 4, FAIL);
    7263             :         tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED dbpoll()\n");
    7264             :         return SUCCEED;
    7265             : }
    7266             : #endif
    7267             : 
    7268             : /** \internal
    7269             :  * \ingroup dblib_internal
    7270             :  * \brief Get number of the first row in the row buffer.
    7271             :  * 
    7272             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7273             :  * \sa DBFIRSTROW(), dbclrbuf(), DBCURROW(), dbgetrow(), DBLASTROW(), dbnextrow(), dbsetopt(). 
    7274             :  */
    7275             : DBINT
    7276           0 : dbfirstrow(DBPROCESS * dbproc)
    7277             : {
    7278           0 :         tdsdump_log(TDS_DBG_FUNC, "dbfirstrow(%p)\n", dbproc);
    7279           0 :         CHECK_CONN(0);
    7280           0 :         return buffer_idx2row(&dbproc->row_buf, dbproc->row_buf.tail);
    7281             : }
    7282             : 
    7283             : /** \internal
    7284             :  * \ingroup dblib_internal
    7285             :  * \brief Get number of the last row in the row buffer.
    7286             :  * 
    7287             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7288             :  * \sa DBLASTROW(), dbclrbuf(), DBCURROW(), DBFIRSTROW(), dbgetrow(), dbnextrow(), dbsetopt(). 
    7289             :  */
    7290             : DBINT
    7291           0 : dblastrow(DBPROCESS * dbproc)
    7292             : {
    7293             :         int idx;
    7294             : 
    7295           0 :         tdsdump_log(TDS_DBG_FUNC, "dblastrow(%p)\n", dbproc);
    7296           0 :         CHECK_PARAMETER(dbproc, SYBENULL, 0);
    7297           0 :         idx = dbproc->row_buf.head;
    7298           0 :         if (dbproc->row_buf.head != dbproc->row_buf.tail) {
    7299           0 :                 if (--idx < 0) 
    7300           0 :                         idx = dbproc->row_buf.capacity - 1;
    7301             :         }
    7302           0 :         assert(idx >= 0);
    7303           0 :         return buffer_idx2row(&dbproc->row_buf, idx);
    7304             : }
    7305             : 
    7306             : 
    7307             : /** \internal
    7308             :  * \ingroup dblib_internal
    7309             :  * \brief Get file descriptor of the socket used by a \c DBPROCESS to read data coming from the server. (!)
    7310             :  * 
    7311             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7312             :  * \sa dbcmd(), DBIORDESC(), DBIOWDESC(), dbnextrow(), dbpoll(), DBRBUF(), dbresults(), dbsqlok(), dbsqlsend().  
    7313             :  */
    7314             : int
    7315           0 : dbiordesc(DBPROCESS * dbproc)
    7316             : {
    7317           0 :         tdsdump_log(TDS_DBG_FUNC, "dbiordesc(%p)\n", dbproc);
    7318           0 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    7319           0 :         return (int) tds_get_s(dbproc->tds_socket);
    7320             : }
    7321             : 
    7322             : 
    7323             : /** \internal
    7324             :  * \ingroup dblib_internal
    7325             :  * \brief Get file descriptor of the socket used by a \c DBPROCESS to write data coming to the server. (!)
    7326             :  * 
    7327             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7328             :  * \sa dbcmd(), DBIORDESC(), DBIOWDESC(), dbnextrow(), dbpoll(), DBRBUF(), dbresults(), dbsqlok(), dbsqlsend().  
    7329             :  */
    7330             : int
    7331          20 : dbiowdesc(DBPROCESS * dbproc)
    7332             : {
    7333          20 :         tdsdump_log(TDS_DBG_FUNC, "dbiowdesc(%p)\n", dbproc);
    7334          20 :         CHECK_PARAMETER(dbproc, SYBENULL, -1);
    7335             : 
    7336          20 :         return (int) tds_get_s(dbproc->tds_socket);
    7337             : }
    7338             : 
    7339             : DBBOOL
    7340           0 : dbisavail(DBPROCESS * dbproc)
    7341             : {
    7342           0 :         tdsdump_log(TDS_DBG_FUNC, "dbisavail(%p)\n", dbproc);
    7343           0 :         CHECK_PARAMETER(dbproc, SYBENULL, FALSE);
    7344           0 :         return dbproc->avail_flag;
    7345             : }
    7346             : 
    7347             : 
    7348             : /** \internal
    7349             :  * \ingroup dblib_internal
    7350             :  * \brief Mark a \c DBPROCESS as "available".
    7351             :  * 
    7352             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7353             :  * \remarks Basically bogus.  \c FreeTDS behaves the way Sybase's implementation does, but so what?  
    7354             :         Many \c db-lib functions set the \c DBPROCESS to "not available", but only 
    7355             :         dbsetavail() resets it to "available".  
    7356             :  * \sa DBISAVAIL(). DBSETAVAIL().
    7357             :  */
    7358             : void
    7359           0 : dbsetavail(DBPROCESS * dbproc)
    7360             : {
    7361           0 :         tdsdump_log(TDS_DBG_FUNC, "dbsetavail(%p)\n", dbproc);
    7362           0 :         CHECK_PARAMETER(dbproc, SYBENULL, );
    7363           0 :         dbproc->avail_flag = TRUE;
    7364             : }
    7365             : 
    7366             : 
    7367             : /**
    7368             :  * \ingroup dblib_core
    7369             :  * \brief Build a printable string from text containing placeholders for variables.
    7370             :  * 
    7371             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    7372             :  * \param charbuf \em output: buffer that will contain the ASCII null-terminated string built by \c dbstrbuild().
    7373             :  * \param bufsize size of \a charbuf, in bytes. 
    7374             :  * \param text null-terminated ASCII string, with \em placeholders for variables. \em A Placeholder is a
    7375             :  *      three-byte string, made up of: 
    7376             :         - '%' a percent sign
    7377             :         - 0-9 an integer (designates the argument number to use, starting with 1.)
    7378             :         - '!' an exclamation point
    7379             :  * \param formats null-terminated ASCII sprintf-style string.  Has one format specifier for each placeholder in \a text.
    7380             :  * \remarks Following \a formats are the arguments, the values to substitute for the placeholders.  
    7381             :  * \sa dbconvert(), dbdatename(), dbdatepart().  
    7382             :  */
    7383             : int
    7384          80 : dbstrbuild(DBPROCESS * dbproc, char *charbuf, int bufsize, char *text, char *formats, ...)
    7385             : {
    7386             :         va_list ap;
    7387             :         TDSRET rc;
    7388             :         int resultlen;
    7389             : 
    7390          80 :         tdsdump_log(TDS_DBG_FUNC, "dbstrbuild(%p, %s, %d, %s, %s, ...)\n", dbproc, charbuf, bufsize, text, formats);
    7391          80 :         CHECK_NULP(charbuf, "dbstrbuild", 2, FAIL);
    7392          80 :         CHECK_NULP(text, "dbstrbuild", 4, FAIL);
    7393          80 :         CHECK_NULP(formats, "dbstrbuild", 5, FAIL);
    7394             : 
    7395          80 :         va_start(ap, formats);
    7396          80 :         rc = tds_vstrbuild(charbuf, bufsize, &resultlen, text, TDS_NULLTERM, formats, TDS_NULLTERM, ap);
    7397          80 :         charbuf[resultlen] = '\0';
    7398          80 :         va_end(ap);
    7399          80 :         return TDS_SUCCEED(rc) ? resultlen : -1;
    7400             : }
    7401             : 
    7402             : static char *
    7403           0 : _dbprdate(char *timestr)
    7404             : {
    7405           0 :         time_t currtime = time(NULL);
    7406             :         
    7407           0 :         assert(timestr);
    7408             : 
    7409           0 :         strcpy(timestr, asctime(gmtime(&currtime)));
    7410           0 :         timestr[strlen(timestr) - 1] = '\0';    /* remove newline */
    7411           0 :         return timestr;
    7412             : 
    7413             : }
    7414             : 
    7415             : static DBINT
    7416           0 : _dbnullable(DBPROCESS * dbproc, int column)
    7417             : {
    7418             :         TDSCOLUMN *colinfo;
    7419             :         TDSRESULTINFO *resinfo;
    7420             : 
    7421           0 :         assert(dbproc && dbproc->tds_socket);
    7422           0 :         resinfo = dbproc->tds_socket->res_info;
    7423           0 :         if (!resinfo || column < 1 || column > resinfo->num_cols)
    7424             :                 return FALSE;
    7425           0 :         colinfo = resinfo->columns[column - 1];
    7426             : 
    7427           0 :         if (colinfo->column_nullable) 
    7428             :                 return TRUE;
    7429           0 :         return FALSE;
    7430             : }
    7431             : 
    7432             : /** Returns type in string. Used for debugging purpose */
    7433             : static const char *
    7434           0 : tds_prdatatype(int datatype_token)
    7435             : {
    7436           0 :         switch ((TDS_SERVER_TYPE) datatype_token) {
    7437             :         case SYBCHAR:           return "SYBCHAR";
    7438           0 :         case SYBVARCHAR:        return "SYBVARCHAR";
    7439           0 :         case SYBINTN:           return "SYBINTN";
    7440           0 :         case SYBINT1:           return "SYBINT1";
    7441           0 :         case SYBINT2:           return "SYBINT2";
    7442           0 :         case SYBINT4:           return "SYBINT4";
    7443           0 :         case SYBINT8:           return "SYBINT8";
    7444           0 :         case SYBFLT8:           return "SYBFLT8";
    7445           0 :         case SYBDATETIME:       return "SYBDATETIME";
    7446           0 :         case SYBBIT:            return "SYBBIT";
    7447           0 :         case SYBTEXT:           return "SYBTEXT";
    7448           0 :         case SYBNTEXT:          return "SYBNTEXT";
    7449           0 :         case SYBIMAGE:          return "SYBIMAGE";
    7450           0 :         case SYBMONEY4:         return "SYBMONEY4";
    7451           0 :         case SYBMONEY:          return "SYBMONEY";
    7452           0 :         case SYBDATETIME4:      return "SYBDATETIME4";
    7453           0 :         case SYBREAL:           return "SYBREAL";
    7454           0 :         case SYBBINARY:         return "SYBBINARY";
    7455           0 :         case SYBVOID:           return "SYBVOID";
    7456           0 :         case SYBVARBINARY:      return "SYBVARBINARY";
    7457           0 :         case SYBNVARCHAR:       return "SYBNVARCHAR";
    7458           0 :         case SYBBITN:           return "SYBBITN";
    7459           0 :         case SYBNUMERIC:        return "SYBNUMERIC";
    7460           0 :         case SYBDECIMAL:        return "SYBDECIMAL";
    7461           0 :         case SYBFLTN:           return "SYBFLTN";
    7462           0 :         case SYBMONEYN:         return "SYBMONEYN";
    7463           0 :         case SYBDATETIMN:       return "SYBDATETIMN";
    7464           0 :         case XSYBCHAR:          return "XSYBCHAR";
    7465           0 :         case XSYBVARCHAR:       return "XSYBVARCHAR";
    7466           0 :         case XSYBNVARCHAR:      return "XSYBNVARCHAR";
    7467           0 :         case XSYBNCHAR:         return "XSYBNCHAR";
    7468           0 :         case XSYBVARBINARY:     return "XSYBVARBINARY";
    7469           0 :         case XSYBBINARY:        return "XSYBBINARY";
    7470           0 :         case SYBLONGBINARY:     return "SYBLONGBINARY";
    7471           0 :         case SYBSINT1:          return "SYBSINT1";
    7472           0 :         case SYBUINT2:          return "SYBUINT2";
    7473           0 :         case SYBUINT4:          return "SYBUINT4";
    7474           0 :         case SYBUINT8:          return "SYBUINT8";
    7475           0 :         case SYBUNIQUE:         return "SYBUNIQUE";
    7476           0 :         case SYBVARIANT:        return "SYBVARIANT";
    7477           0 :         case SYBMSXML:          return "SYBMSXML";
    7478           0 :         case SYBMSDATE:         return "SYBMSDATE";
    7479           0 :         case SYBMSTIME:         return "SYBMSTIME";
    7480           0 :         case SYBMSDATETIME2:    return "SYBMSDATETIME2";
    7481           0 :         case SYBMSDATETIMEOFFSET: return "SYBMSDATETIMEOFFSET";
    7482           0 :         case SYBDATE:           return "SYBDATE";
    7483           0 :         case SYBTIME:           return "SYBTIME";
    7484           0 :         case SYB5BIGDATETIME:   return "SYBBIGDATETIME";
    7485           0 :         case SYB5BIGTIME:       return "SYBBIGTIME";
    7486           0 :         case SYBMSUDT:          return "SYBMSUDT";
    7487           0 :         case SYBUINT1:          return "SYBUINT1";
    7488           0 :         case SYBDATEN:          return "SYBDATEN";
    7489           0 :         case SYB5INT8:          return "SYB5INT8";
    7490           0 :         case SYBINTERVAL:       return "SYBINTERVAL";
    7491           0 :         case SYBTIMEN:          return "SYBTIMEN";
    7492           0 :         case SYBUINTN:          return "SYBUINTN";
    7493           0 :         case SYBUNITEXT:        return "SYBUNITEXT";
    7494           0 :         case SYBXML:            return "SYBXML";
    7495           0 :         case SYBMSTABLE:        return "SYBMSTABLE";
    7496             :         }
    7497           0 :         return "(unknown)";
    7498             : }
    7499             : #if 1
    7500             : void
    7501      410744 : copy_data_to_host_var(DBPROCESS * dbproc, TDS_SERVER_TYPE srctype, const BYTE * src, DBINT srclen, 
    7502             :                       BYTE * dest, DBINT destlen,
    7503             :                       int bindtype, DBINT *indicator)
    7504             : {
    7505             :         CONV_RESULT dres;
    7506             :         DBINT ret;
    7507             :         int len;
    7508      410744 :         DBINT indicator_value = 0;
    7509             : 
    7510      410744 :         bool limited_dest_space = false;
    7511      410744 :         TDS_SERVER_TYPE desttype = dblib_bound_type(bindtype);
    7512             : 
    7513      410744 :         tdsdump_log(TDS_DBG_FUNC, "copy_data_to_host_var(%d [%s] len %d => %d [%s] len %d)\n", 
    7514             :                      srctype, tds_prdatatype(srctype), srclen, desttype, tds_prdatatype(desttype), destlen);
    7515      820990 :         CHECK_NULP(src, "copy_data_to_host_var", 3, );
    7516      410744 :         CHECK_NULP(dest, "copy_data_to_host_var", 6, );
    7517      410744 :         if (desttype == TDS_INVALID_TYPE)
    7518             :                 return;
    7519             :         /* indicator can be NULL */
    7520             : 
    7521      410744 :         assert(srclen >= 0);
    7522             : 
    7523      410744 :         if (destlen > 0) {
    7524         290 :                 limited_dest_space = true;
    7525             :         }
    7526             : 
    7527             :         /* oft times we are asked to convert a data type to itself */
    7528             : 
    7529      410744 :         if (desttype == SYBNUMERIC) {
    7530         240 :                 DBNUMERIC *num = NULL;          /* num->scale is unsigned */
    7531             : 
    7532             :                 /* only MS, use always source */
    7533         240 :                 if (bindtype == SRCNUMERICBIND || bindtype == SRCDECIMALBIND) {
    7534         120 :                         if (is_numeric_type(srctype))
    7535             :                                 num = (DBNUMERIC*) src;
    7536             :                         else
    7537          40 :                                 num = (DBNUMERIC*) dest;
    7538         120 :                 } else if (dbproc->msdblib) {
    7539             :                         /* MS by default use only destination information */
    7540             :                         num = (DBNUMERIC*) dest;
    7541             :                 } else {
    7542             :                         /* Sybase, dbbind means source or default */
    7543             :                         /* TODO if dbbind_ps is used is more complicated */
    7544          60 :                         if (is_numeric_type(srctype))
    7545             :                                 num = (DBNUMERIC*) src;
    7546             :                 }
    7547             :                 if (!num) {
    7548          20 :                         dres.n.precision = 18;
    7549          20 :                         dres.n.scale = 0;
    7550             :                 } else {
    7551         220 :                         dres.n.precision = num->precision;
    7552         220 :                         dres.n.scale = num->scale;
    7553             :                 }
    7554      411850 :         } else if ((srctype == desttype) ||
    7555        2434 :                 (is_similar_type(srctype, desttype))) {
    7556             : 
    7557      410246 :                 tdsdump_log(TDS_DBG_INFO1, "copy_data_to_host_var() srctype == desttype\n");
    7558      410246 :                 switch (desttype) {
    7559             : 
    7560          10 :                 case SYBVARBINARY:
    7561             :                 case SYBBINARY:
    7562             :                 case SYBIMAGE:
    7563          10 :                         if (bindtype == VARYBINBIND) {
    7564          10 :                                 DBVARYBIN *bin = (DBVARYBIN*) dest;
    7565          10 :                                 if (limited_dest_space) {
    7566          10 :                                         if (srclen > sizeof(bin->array)) {
    7567           0 :                                                 dbperror(dbproc, SYBECOFL, 0);
    7568           0 :                                                 indicator_value = srclen;
    7569           0 :                                                 srclen = sizeof(bin->array);
    7570             :                                         }
    7571             :                                 }
    7572          10 :                                 memcpy(bin->array, src, srclen);
    7573          10 :                                 bin->len = srclen;
    7574          10 :                                 break;
    7575             :                         }
    7576             : 
    7577           0 :                         if (srclen > destlen && destlen >= 0) {
    7578           0 :                                 dbperror(dbproc, SYBECOFL, 0);
    7579             :                         } else {
    7580           0 :                                 memcpy(dest, src, srclen);
    7581           0 :                                 if (srclen < destlen)
    7582           0 :                                         memset(dest + srclen, 0, destlen - srclen);
    7583             :                         }
    7584             :                         break;
    7585             : 
    7586      205622 :                 case SYBCHAR:
    7587             :                 case SYBVARCHAR:
    7588             :                 case SYBTEXT:
    7589             : 
    7590      205622 :                         switch (bindtype) {
    7591             :                                 case NTBSTRINGBIND: /* strip trailing blanks, null term */
    7592         574 :                                         while (srclen && src[srclen - 1] == ' ') {
    7593         252 :                                                 --srclen;
    7594             :                                         }
    7595         322 :                                         if (limited_dest_space) {
    7596          40 :                                                 if (srclen + 1 > destlen) {
    7597          10 :                                                         dbperror(dbproc, SYBECOFL, 0);
    7598          10 :                                                         indicator_value = srclen + 1;
    7599          10 :                                                         srclen = destlen - 1;
    7600             :                                                 }
    7601             :                                         }
    7602         322 :                                         memcpy(dest, src, srclen);
    7603         322 :                                         dest[srclen] = '\0';
    7604         322 :                                         break;
    7605      205240 :                                 case STRINGBIND:   /* pad with blanks, NUL term */
    7606      205240 :                                         if (limited_dest_space) {
    7607          30 :                                                 if (srclen + 1 > destlen) {
    7608          20 :                                                         dbperror(dbproc, SYBECOFL, 0);
    7609          20 :                                                         indicator_value = srclen + 1;
    7610          20 :                                                         srclen = destlen - 1;
    7611             :                                                 }
    7612             :                                         } else {
    7613      205210 :                                                 destlen = srclen + 1;
    7614             :                                         }
    7615      205240 :                                         memcpy(dest, src, srclen);
    7616      205240 :                                         if (srclen < destlen)
    7617      205240 :                                                 memset(dest + srclen, ' ', destlen - srclen - 1);
    7618      205240 :                                         dest[destlen - 1] = '\0';
    7619      205240 :                                         break;
    7620          40 :                                 case CHARBIND:   /* pad with blanks, NO NUL term */
    7621          40 :                                         if (limited_dest_space) {
    7622          30 :                                                 if (srclen > destlen) {
    7623          10 :                                                         dbperror(dbproc, SYBECOFL, 0);
    7624          10 :                                                         indicator_value = srclen;
    7625          10 :                                                         srclen = destlen;
    7626             :                                                 }
    7627             :                                         } else {
    7628             :                                                 destlen = srclen; 
    7629             :                                         }
    7630          40 :                                         memcpy(dest, src, srclen);
    7631          40 :                                         if (srclen < destlen)
    7632          10 :                                                 memset(dest + srclen, ' ', destlen - srclen);
    7633             :                                         break;
    7634          20 :                                 case VARYCHARBIND: /* strip trailing blanks, NO NUL term */
    7635          20 :                                         if (limited_dest_space) {
    7636          20 :                                                 if (srclen > destlen) {
    7637           0 :                                                         dbperror(dbproc, SYBECOFL, 0);
    7638           0 :                                                         indicator_value = srclen;
    7639           0 :                                                         srclen = destlen;
    7640             :                                                 }
    7641             :                                         }
    7642          20 :                                         memcpy(((DBVARYCHAR *)dest)->str, src, srclen);
    7643          20 :                                         ((DBVARYCHAR *)dest)->len = srclen;
    7644          20 :                                         break;
    7645             :                         } 
    7646             :                         break;
    7647      204614 :                 case SYBINT1:
    7648             :                 case SYBINT2:
    7649             :                 case SYBINT4:
    7650             :                 case SYBINT8:
    7651             :                 case SYBFLT8:
    7652             :                 case SYBREAL:
    7653             :                 case SYBBIT:
    7654             :                 case SYBBITN:
    7655             :                 case SYBMONEY:
    7656             :                 case SYBMONEY4:
    7657             :                 case SYBDATETIME:
    7658             :                 case SYBDATETIME4:
    7659             :                 case SYBDATE:
    7660             :                 case SYBTIME:
    7661             :                 case SYB5BIGDATETIME:
    7662             :                 case SYB5BIGTIME:
    7663             :                 case SYBUNIQUE:
    7664      204614 :                         ret = tds_get_size_by_type(desttype);
    7665      204614 :                         memcpy(dest, src, ret);
    7666      204614 :                         break;
    7667             : 
    7668           0 :                 case SYBMSDATE:
    7669             :                 case SYBMSTIME:
    7670             :                 case SYBMSDATETIME2:
    7671             :                 case SYBMSDATETIMEOFFSET:
    7672           0 :                         ret = sizeof(TDS_DATETIMEALL);
    7673           0 :                         memcpy(dest, src, ret);
    7674           0 :                         break;
    7675             : 
    7676             :                 default:
    7677             :                         break;
    7678             :                 }
    7679      410246 :                 if (indicator)
    7680         136 :                         *indicator = indicator_value;
    7681             : 
    7682             :                 return;
    7683             : 
    7684             :         } /* end srctype == desttype */
    7685             : 
    7686         498 :         len = tds_convert(g_dblib_ctx.tds_ctx, srctype, src, srclen, desttype, &dres);
    7687             : 
    7688         498 :         tdsdump_log(TDS_DBG_INFO1, "copy_data_to_host_var(): tds_convert returned %d\n", len);
    7689             : 
    7690         498 :         if (len < 0) {
    7691           0 :                 _dblib_convert_err(dbproc, len);
    7692           0 :                 return;
    7693             :         }
    7694             : 
    7695         498 :         switch (desttype) {
    7696          60 :         case SYBVARBINARY:
    7697             :         case SYBBINARY:
    7698             :         case SYBIMAGE:
    7699          60 :                 if (bindtype == VARYBINBIND) {
    7700          30 :                         if (limited_dest_space) {
    7701          30 :                                 if (len > sizeof(((DBVARYBIN *)dest)->array)) {
    7702           0 :                                         dbperror(dbproc, SYBECOFL, 0);
    7703           0 :                                         indicator_value = len;
    7704           0 :                                         len = sizeof(((DBVARYBIN *)dest)->array);
    7705             :                                 }
    7706             :                         }
    7707          30 :                         memcpy(((DBVARYBIN *)dest)->array, dres.c, len);
    7708          30 :                         ((DBVARYBIN *)dest)->len = len;
    7709             :                 } else {
    7710          30 :                         if (len > destlen && destlen >= 0) {
    7711           0 :                                 dbperror(dbproc, SYBECOFL, 0);
    7712             :                         } else {
    7713          30 :                                 memcpy(dest, dres.ib, len);
    7714          30 :                                 if (len < destlen)
    7715          10 :                                         memset(dest + len, 0, destlen - len);
    7716             :                         }
    7717             :                 }
    7718          60 :                 TDS_ZERO_FREE(dres.ib);
    7719          60 :                 break;
    7720         250 :         case SYBINT1:
    7721             :         case SYBINT2:
    7722             :         case SYBINT4:
    7723             :         case SYBINT8:
    7724             :         case SYBFLT8:
    7725             :         case SYBREAL:
    7726             :         case SYBBIT:
    7727             :         case SYBBITN:
    7728             :         case SYBMONEY:
    7729             :         case SYBMONEY4:
    7730             :         case SYBDATETIME:
    7731             :         case SYBDATETIME4:
    7732             :         case SYBDATE:
    7733             :         case SYBTIME:
    7734             :         case SYBNUMERIC:
    7735             :         case SYBDECIMAL:
    7736             :         case SYBUNIQUE:
    7737             :         case SYBMSDATE:
    7738             :         case SYBMSTIME:
    7739             :         case SYB5BIGDATETIME:
    7740             :         case SYB5BIGTIME:
    7741             :         case SYBMSDATETIME2:
    7742             :         case SYBMSDATETIMEOFFSET:
    7743         250 :                 memcpy(dest, &(dres.ti), len);
    7744         250 :                 break;
    7745         188 :         case SYBCHAR:
    7746             :         case SYBVARCHAR:
    7747             :         case SYBTEXT:
    7748         188 :                 tdsdump_log(TDS_DBG_INFO1, "copy_data_to_host_var() outputs %d bytes char data destlen = %d \n", len, destlen);
    7749         188 :                 switch (bindtype) {
    7750             :                         case NTBSTRINGBIND: /* strip trailing blanks, null term */
    7751          40 :                                 while (len && dres.c[len - 1] == ' ') {
    7752           0 :                                         --len;
    7753             :                                 }
    7754          40 :                                 if (limited_dest_space) {
    7755          30 :                                         if (len + 1 > destlen) {
    7756          10 :                                                 dbperror(dbproc, SYBECOFL, 0);
    7757          10 :                                                 len = destlen - 1;
    7758             :                                         }
    7759             :                                 }
    7760          40 :                                 memcpy(dest, dres.c, len);
    7761          40 :                                 dest[len] = '\0';
    7762          40 :                                 break;
    7763          98 :                         case STRINGBIND:   /* pad with blanks, null term */
    7764          98 :                                 if (limited_dest_space) {
    7765          30 :                                         if (len + 1 > destlen) {
    7766          10 :                                                 dbperror(dbproc, SYBECOFL, 0);
    7767          10 :                                                 len = destlen - 1;
    7768             :                                         }
    7769             :                                 } else {
    7770          68 :                                         destlen = len + 1;
    7771             :                                 }
    7772          98 :                                 memcpy(dest, dres.c, len);
    7773          98 :                                 if (len < destlen)
    7774          98 :                                         memset(dest + len, ' ', destlen - len - 1);
    7775          98 :                                 dest[destlen - 1] = '\0';
    7776          98 :                                 break;
    7777          50 :                         case CHARBIND:   /* pad with blanks, NO null term */
    7778          50 :                                 if (limited_dest_space) {
    7779          40 :                                         if (len > destlen) {
    7780          10 :                                                 dbperror(dbproc, SYBECOFL, 0);
    7781          10 :                                                 indicator_value = len;
    7782          10 :                                                 len = destlen;
    7783             :                                         }
    7784             :                                 } else {
    7785             :                                         destlen = len; 
    7786             :                                 }
    7787          50 :                                 memcpy(dest, dres.c, len);
    7788          50 :                                 if (len < destlen)
    7789          20 :                                         memset(dest + len, ' ', destlen - len);
    7790             :                                 break;
    7791           0 :                         case VARYCHARBIND: /* strip trailing blanks, NO null term */
    7792           0 :                                 if (limited_dest_space) {
    7793           0 :                                         if (len > sizeof(((DBVARYCHAR *)dest)->str)) {
    7794           0 :                                                 dbperror(dbproc, SYBECOFL, 0);
    7795           0 :                                                 indicator_value = len;
    7796           0 :                                                 len = sizeof(((DBVARYCHAR *)dest)->str);
    7797             :                                         }
    7798             :                                 } 
    7799           0 :                                 memcpy(((DBVARYCHAR *)dest)->str, dres.c, len);
    7800           0 :                                 ((DBVARYCHAR *)dest)->len = len;
    7801           0 :                                 break;
    7802             :                 } 
    7803             : 
    7804         188 :                 free(dres.c);
    7805         188 :                 break;
    7806           0 :         default:
    7807           0 :                 tdsdump_log(TDS_DBG_INFO1, "error: copy_data_to_host_var(): unrecognized desttype %d \n", desttype);
    7808             :                 break;
    7809             : 
    7810             :         }
    7811         498 :         if (indicator)
    7812           0 :                 *indicator = indicator_value;
    7813             : }
    7814             : #endif
    7815             : 
    7816             : /** \internal
    7817             :  * \ingroup dblib_internal
    7818             :  * \remarks member msgno Vendor-defined message number
    7819             :  * \remarks member severity Is passed to the error handler 
    7820             :  * \remarks member msgtext Text of message
    7821             :  */
    7822             : typedef struct _dblib_error_message 
    7823             : {
    7824             :         DBINT msgno;
    7825             :         int severity;
    7826             :         const char *msgtext;
    7827             : } DBLIB_ERROR_MESSAGE;
    7828             : 
    7829             : /*
    7830             :  * The msgtext member holds up to two strings.  The first one is the message text, which may contain placeholders.  
    7831             :  * The second one, if it exists, is the format string for dbstrbuild().  Messages containing no placeholders still need
    7832             :  * an extra NULL to indicate a zero-length format string. 
    7833             :  */
    7834             : static const DBLIB_ERROR_MESSAGE dblib_error_messages[] = 
    7835             :         { { SYBEVERDOWN,           EXINFO,      "TDS version downgraded to 7.1!\0" }
    7836             :         , { SYBEICONVIU,     EXCONVERSION,      "Some character(s) could not be converted into client's character set\0" }
    7837             :         , { SYBEICONVAVAIL,  EXCONVERSION,      "Character set conversion is not available between client character set '%1!' and "
    7838             :                                                 "server character set '%2!'\0%s %s" }
    7839             :         , { SYBEICONVO,      EXCONVERSION,      "Error converting characters into server's character set. Some character(s) could "
    7840             :                                                 "not be converted\0" }
    7841             :         , { SYBEICONVI,      EXCONVERSION,      "Some character(s) could not be converted into client's character set.  Unconverted "
    7842             :                                                 "bytes were changed to question marks ('?')\0" }
    7843             :         , { SYBEICONV2BIG,   EXCONVERSION,      "Buffer overflow converting characters from client into server's character set\0" }
    7844             :         
    7845             :         
    7846             :         , { SYBEPORT,              EXUSER,      "Both port and instance specified\0" }
    7847             :         , { SYBETDSVER,            EXUSER,      "Cannot bcp with TDSVER < 5.0\0" }
    7848             :         , { SYBEAAMT,           EXPROGRAM,      "User attempted a dbaltbind with mismatched column and variable types\0" }
    7849             :         , { SYBEABMT,           EXPROGRAM,      "User attempted a dbbind with mismatched column and variable types\0" }
    7850             :         , { SYBEABNC,           EXPROGRAM,      "Attempt to bind to a non-existent column\0" }
    7851             :         , { SYBEABNP,           EXPROGRAM,      "Attempt to bind using NULL pointers\0" }
    7852             :         , { SYBEABNV,           EXPROGRAM,      "Attempt to bind to a NULL program variable\0" }
    7853             :         , { SYBEACNV,        EXCONVERSION,      "Attempt to do data-conversion with NULL destination variable.\0" }
    7854             :         , { SYBEADST,       EXCONSISTENCY,      "International Release: Error in attempting to determine the size of a pair of "
    7855             :                                                 "translation tables\0" }
    7856             :         , { SYBEAICF,       EXCONSISTENCY,      "International Release: Error in attempting to install custom format\0" }
    7857             :         , { SYBEALTT,       EXCONSISTENCY,      "International Release: Error in attempting to load a pair of translation tables\0" }
    7858             :         , { SYBEAOLF,          EXRESOURCE,      "International Release: Error in attempting to open a localization file\0" }
    7859             :         , { SYBEAPCT,       EXCONSISTENCY,      "International Release: Error in attempting to perform a character set translation\0" }
    7860             :         , { SYBEAPUT,           EXPROGRAM,      "Attempt to print unknown token\0" }
    7861             :         , { SYBEARDI,          EXRESOURCE,      "International Release: Error in attempting to read datetime information from a "
    7862             :                                                 "localization file\0" }
    7863             :         , { SYBEARDL,          EXRESOURCE,      "International Release: Error in attempting to read the dblib.loc localization file\0" }
    7864             :         , { SYBEASEC,           EXPROGRAM,      "Attempt to send an empty command buffer to the server\0" }
    7865             :         , { SYBEASNL,           EXPROGRAM,      "Attempt to set fields in a null LOGINREC\0" }
    7866             :         , { SYBEASTL,           EXPROGRAM,      "Synchronous I/O attempted at AST level\0" }
    7867             :         , { SYBEASUL,           EXPROGRAM,      "Attempt to set unknown LOGINREC field\0" }
    7868             :         , { SYBEAUTN,           EXPROGRAM,      "Attempt to update the timestamp of a table that has no timestamp column\0" }
    7869             :         , { SYBEBADPK,             EXINFO,      "Packet size of %1! not supported -- size of %2! used instead!\0%d %d" }
    7870             :         , { SYBEBBCI,              EXINFO,      "Batch successfully bulk copied to the server\0" }
    7871             :         , { SYBEBBL,            EXPROGRAM,      "Bad bindlen parameter passed to dbsetnull\0" }
    7872             :         , { SYBEBCBC,           EXPROGRAM,      "bcp_columns must be called before bcp_colfmt and bcp_colfmt_ps\0" }
    7873             :         , { SYBEBCBNPR,         EXPROGRAM,      "bcp_bind: if varaddr is NULL, prefixlen must be 0 "
    7874             :                                                 "and no terminator should be specified\0" }
    7875             :         , { SYBEBCBNTYP,        EXPROGRAM,      "bcp_bind: if varaddr is NULL and varlen greater than 0, the table column type "
    7876             :                                                 "must be SYBTEXT or SYBIMAGE and the program variable type must be SYBTEXT, SYBCHAR, "
    7877             :                                                 "SYBIMAGE or SYBBINARY\0" }
    7878             :         , { SYBEBCBPREF,        EXPROGRAM,      "Illegal prefix length. Legal values are 0, 1, 2 or 4\0" }
    7879             :         , { SYBEBCFO,              EXUSER,      "bcp host files must contain at least one column\0" }
    7880             :         , { SYBEBCHLEN,         EXPROGRAM,      "host_collen should be greater than or equal to -1\0" }
    7881             :         , { SYBEBCIS,       EXCONSISTENCY,      "Attempt to bulk copy an illegally-sized column value to the server\0" }
    7882             :         , { SYBEBCIT,           EXPROGRAM,      "It is illegal to use BCP terminators with program variables other than SYBCHAR, "
    7883             :                                                 "SYBBINARY, SYBTEXT, or SYBIMAGE\0" }
    7884             :         , { SYBEBCITBLEN,       EXPROGRAM,      "bcp_init: tblname parameter is too long\0" }
    7885             :         , { SYBEBCITBNM,        EXPROGRAM,      "bcp_init: tblname parameter cannot be NULL\0" }
    7886             :         , { SYBEBCMTXT,         EXPROGRAM,      "bcp_moretext may be used only when there is at least one text or image column in "
    7887             :                                                 "the server table\0" }
    7888             :         , { SYBEBCNL,          EXNONFATAL,      "Negative length-prefix found in BCP data-file\0" }
    7889             :         , { SYBEBCNN,              EXUSER,      "Attempt to bulk copy a NULL value into a Server column "
    7890             :                                                 "which does not accept null values\0" }
    7891             :         , { SYBEBCNT,              EXUSER,      "Attempt to use Bulk Copy with a non-existent Server table\0" }
    7892             :         , { SYBEBCOR,       EXCONSISTENCY,      "Attempt to bulk copy an oversized row to the server\0" }
    7893             :         , { SYBEBCPB,           EXPROGRAM,      "bcp_bind, bcp_moretext and bcp_sendrow may not be used after bcp_init has been "
    7894             :                                                 "passed a non-NULL input file name\0" }
    7895             :         , { SYBEBCPCTYP,        EXPROGRAM,      "bcp_colfmt: If table_colnum is 0, host_type cannot be 0\0" }
    7896             :         , { SYBEBCPI,           EXPROGRAM,      "bcp_init must be called before any other bcp routines\0" }
    7897             :         , { SYBEBCPN,           EXPROGRAM,      "bcp_bind, bcp_collen, bcp_colptr, bcp_moretext and bcp_sendrow may be used only "
    7898             :                                                 "after bcp_init has been called with the copy direction set to DB_IN\0" }
    7899             :         , { SYBEBCPREC,        EXNONFATAL,      "Column %1!: Illegal precision value encountered\0%d" }
    7900             :         , { SYBEBCPREF,         EXPROGRAM,      "Illegal prefix length. Legal values are -1, 0, 1, 2 or 4\0" }
    7901             :         , { SYBEBCRE,          EXNONFATAL,      "I/O error while reading bcp datafile\0" }
    7902             :         , { SYBEBCRO,              EXINFO,      "The BCP hostfile '%1!' contains only %2! rows. It was impossible to read the "
    7903             :                                                 "requested %3! rows\0%s %d %d" }
    7904             :         , { SYBEBCSA,              EXUSER,      "The BCP hostfile '%1!' contains only %2! rows. "
    7905             :                                                 "Skipping all of these rows is not allowed\0%s %d" }
    7906             :         , { SYBEBCSET,      EXCONSISTENCY,      "Unknown character-set encountered\0" }
    7907             :         , { SYBEBCSI,           EXPROGRAM,      "Host-file columns may be skipped only when copying into the Server\0" }
    7908             :         , { SYBEBCSNDROW,       EXPROGRAM,      "bcp_sendrow may not be called unless all text data for the previous row has been "
    7909             :                                                 "sent using bcp_moretext\0" }
    7910             :         , { SYBEBCSNTYP,        EXPROGRAM,      "column number %1!: if varaddr is NULL and varlen greater than 0, the table column "
    7911             :                                                 "type must be SYBTEXT or SYBIMAGE and the program variable type must be SYBTEXT, "
    7912             :                                                 "SYBCHAR, SYBIMAGE or SYBBINARY\0%d" }
    7913             :         , { SYBEBCUC,          EXRESOURCE,      "bcp: Unable to close host datafile\0" }
    7914             :         , { SYBEBCUO,          EXRESOURCE,      "bcp: Unable to open host datafile\0" }
    7915             :         , { SYBEBCVH,           EXPROGRAM,      "bcp_exec may be called only after bcp_init has been passed a valid host file\0" }
    7916             :         , { SYBEBCVLEN,         EXPROGRAM,      "varlen should be greater than or equal to -1\0" }
    7917             :         , { SYBEBCWE,          EXNONFATAL,      "I/O error while writing bcp datafile\0" }
    7918             :         , { SYBEBDIO,           EXPROGRAM,      "Bad bulk copy direction. Must be either IN or OUT\0" }
    7919             :         , { SYBEBEOF,          EXNONFATAL,      "Unexpected EOF encountered in bcp datafile\0" }
    7920             :         , { SYBEBIHC,           EXPROGRAM,      "Incorrect host-column number found in bcp format file\0" }
    7921             :         , { SYBEBIVI,           EXPROGRAM,      "bcp_columns, bcp_colfmt and bcp_colfmt_ps may be used only after bcp_init has been "
    7922             :                                                 "passed a valid input file\0" }
    7923             :         , { SYBEBNCR,           EXPROGRAM,      "Attempt to bind user variable to a non-existent compute row\0" }
    7924             :         , { SYBEBNUM,           EXPROGRAM,      "Bad numbytes parameter passed to dbstrcpy\0" }
    7925             :         , { SYBEBPKS,           EXPROGRAM,      "In DBSETLPACKET, the packet size parameter must be between 0 and 999999\0" }
    7926             :         , { SYBEBPREC,          EXPROGRAM,      "Illegal precision specified\0" }
    7927             :         , { SYBEBPROBADDEF, EXCONSISTENCY,      "bcp protocol error: illegal default column id received\0" }
    7928             :         , { SYBEBPROCOL,    EXCONSISTENCY,      "bcp protocol error: returned column count differs from the actual number of "
    7929             :                                                 "columns received\0" }
    7930             :         , { SYBEBPRODEF,    EXCONSISTENCY,      "bcp protocol error: expected default information and got none\0" }
    7931             :         , { SYBEBPRODEFID,  EXCONSISTENCY,      "bcp protocol error: default column id and actual column id are not same\0" }
    7932             :         , { SYBEBPRODEFTYP, EXCONSISTENCY,      "bcp protocol error: default value datatype differs from column datatype\0" }
    7933             :         , { SYBEBPROEXTDEF, EXCONSISTENCY,      "bcp protocol error: more than one row of default information received\0" }
    7934             :         , { SYBEBPROEXTRES, EXCONSISTENCY,      "bcp protocol error: unexpected set of results received\0" }
    7935             :         , { SYBEBPRONODEF,  EXCONSISTENCY,      "bcp protocol error: default value received for column that does not have default\0" }
    7936             :         , { SYBEBPRONUMDEF, EXCONSISTENCY,      "bcp protocol error: expected number of defaults differs from the actual number of "
    7937             :                                                 "defaults received\0" }
    7938             :         , { SYBEBRFF,          EXRESOURCE,      "I/O error while reading bcp format file\0" }
    7939             :         , { SYBEBSCALE,         EXPROGRAM,      "Illegal scale specified\0" }
    7940             :         , { SYBEBTMT,           EXPROGRAM,      "Attempt to send too much text data via the bcp_moretext call\0" }
    7941             :         , { SYBEBTOK,              EXCOMM,      "Bad token from the server: Datastream processing out of sync\0" }
    7942             :         , { SYBEBTYP,           EXPROGRAM,      "Unknown bind type passed to DB-Library function\0" }
    7943             :         , { SYBEBTYPSRV,        EXPROGRAM,      "Datatype is not supported by the server\0" }
    7944             :         , { SYBEBUCE,          EXRESOURCE,      "bcp: Unable to close error file\0" }
    7945             :         , { SYBEBUCF,           EXPROGRAM,      "bcp: Unable to close format file\0" }
    7946             :         , { SYBEBUDF,           EXPROGRAM,      "bcp: Unrecognized datatype found in format file\0" }
    7947             :         , { SYBEBUFF,           EXPROGRAM,      "bcp: Unable to create format file\0" }
    7948             :         , { SYBEBUFL,       EXCONSISTENCY,      "DB-Library internal error-send buffer length corrupted\0" }
    7949             :         , { SYBEBUOE,          EXRESOURCE,      "bcp: Unable to open error file\0" }
    7950             :         , { SYBEBUOF,           EXPROGRAM,      "bcp: Unable to open format file\0" }
    7951             :         , { SYBEBWEF,          EXNONFATAL,      "I/O error while writing bcp error file\0" }
    7952             :         , { SYBEBWFF,          EXRESOURCE,      "I/O error while writing bcp format file\0" }
    7953             :         , { SYBECAP,               EXCOMM,      "DB-Library capabilities not accepted by the Server\0" }
    7954             :         , { SYBECAPTYP,            EXCOMM,      "Unexpected capability type in CAPABILITY datastream\0" }
    7955             :         , { SYBECDNS,       EXCONSISTENCY,      "Datastream indicates that a compute column is derived from a non-existent select "
    7956             :                                                 "list member\0" }
    7957             :         , { SYBECDOMAIN,     EXCONVERSION,      "Source field value is not within the domain of legal values\0" }
    7958             :         , { SYBECINTERNAL,   EXCONVERSION,      "Internal Conversion error\0" }
    7959             :         , { SYBECLOS,              EXCOMM,      "Error in closing network connection\0" }
    7960             :         , { SYBECLPR,        EXCONVERSION,      "Data conversion resulted in loss of precision\0" }
    7961             :         , { SYBECNOR,           EXPROGRAM,      "Column number out of range\0" }
    7962             :         , { SYBECNOV,        EXCONVERSION,      "Attempt to set variable to NULL resulted in overflow\0" }
    7963             :         , { SYBECOFL,        EXCONVERSION,      "Data conversion resulted in overflow\0" }
    7964             :         , { SYBECONN,              EXCOMM,      "Unable to connect: TDS server is unavailable or does not exist\0" }
    7965             :         , { SYBECRNC,           EXPROGRAM,      "The current row is not a result of compute clause %1!, so it is illegal to attempt "
    7966             :                                                 "to extract that data from this row\0%d" }
    7967             :         , { SYBECRSAGR,         EXPROGRAM,      "Aggregate functions are not allowed in a cursor statement\0" }
    7968             :         , { SYBECRSBROL,        EXPROGRAM,      "Backward scrolling cannot be used in a forward scrolling cursor\0" }
    7969             :         , { SYBECRSBSKEY,       EXPROGRAM,      "Keyset cannot be scrolled backward in mixed cursors with a previous fetch type\0" }
    7970             :         , { SYBECRSBUFR,        EXPROGRAM,      "Row buffering should not be turned on when using cursor APIs\0" }
    7971             :         , { SYBECRSDIS,         EXPROGRAM,      "Cursor statement contains one of the disallowed phrases compute, union, for "
    7972             :                                                 "browse, or select into\0" }
    7973             :         , { SYBECRSFLAST,       EXPROGRAM,      "Fetch type LAST requires fully keyset driven cursors\0" }
    7974             :         , { SYBECRSFRAND,       EXPROGRAM,      "Fetch types RANDOM and RELATIVE can only be used within the keyset of keyset "
    7975             :                                                 "driven cursors\0" }
    7976             :         , { SYBECRSFROWN,       EXPROGRAM,      "Row number to be fetched is outside valid range\0" }
    7977             :         , { SYBECRSFTYPE,      EXRESOURCE,      "Unknown fetch type\0" }
    7978             :         , { SYBECRSINV,         EXPROGRAM,      "Invalid cursor statement\0" }
    7979             :         , { SYBECRSINVALID,    EXRESOURCE,      "The cursor handle is invalid\0" }
    7980             :         , { SYBECRSMROWS,      EXRESOURCE,      "Multiple rows are returned, only one is expected while retrieving dbname\0" }
    7981             :         , { SYBECRSNOBIND,      EXPROGRAM,      "Cursor bind must be called prior to dbcursor invocation\0" }
    7982             :         , { SYBECRSNOCOUNT,     EXPROGRAM,      "The DBNOCOUNT option should not be turned on "
    7983             :                                                 "when doing updates or deletes with dbcursor\0" }
    7984             :         , { SYBECRSNOFREE,      EXPROGRAM,      "The DBNOAUTOFREE option should not be turned on when using cursor APIs\0" }
    7985             :         , { SYBECRSNOIND,       EXPROGRAM,      "One of the tables involved in the cursor statement does not have a unique index\0" }
    7986             :         , { SYBECRSNOKEYS,     EXRESOURCE,      "The entire keyset must be defined for KEYSET type cursors\0" }
    7987             :         , { SYBECRSNOLEN,      EXRESOURCE,      "No unique index found\0" }
    7988             :         , { SYBECRSNOPTCC,     EXRESOURCE,      "No OPTCC was found\0" }
    7989             :         , { SYBECRSNORDER,     EXRESOURCE,      "The order of clauses must be from, where, and order by\0" }
    7990             :         , { SYBECRSNORES,       EXPROGRAM,      "Cursor statement generated no results\0" }
    7991             :         , { SYBECRSNROWS,      EXRESOURCE,      "No rows returned, at least one is expected\0" }
    7992             :         , { SYBECRSNOTABLE,    EXRESOURCE,      "Table name is NULL\0" }
    7993             :         , { SYBECRSNOUPD,       EXPROGRAM,      "Update or delete operation did not affect any rows\0" }
    7994             :         , { SYBECRSNOWHERE,     EXPROGRAM,      "A WHERE clause is not allowed in a cursor update or insert\0" }
    7995             :         , { SYBECRSNUNIQUE,    EXRESOURCE,      "No unique keys associated with this view\0" }
    7996             :         , { SYBECRSORD,         EXPROGRAM,      "Only fully keyset driven cursors can have order by, group by, or having phrases\0" }
    7997             :         , { SYBECRSRO,          EXPROGRAM,      "Data locking or modifications cannot be made in a READONLY cursor\0" }
    7998             :         , { SYBECRSSET,         EXPROGRAM,      "A SET clause is required for a cursor update or insert\0" }
    7999             :         , { SYBECRSTAB,         EXPROGRAM,      "Table name must be determined in operations involving data locking or modifications\0" }
    8000             :         , { SYBECRSVAR,        EXRESOURCE,      "There is no valid address associated with this bind\0" }
    8001             :         , { SYBECRSVIEW,        EXPROGRAM,      "A view cannot be joined with another table or a view in a cursor statement\0" }
    8002             :         , { SYBECRSVIIND,       EXPROGRAM,      "The view used in the cursor statement does not include all the unique index "
    8003             :                                                 "columns of the underlying tables\0" }
    8004             :         , { SYBECRSUPDNB,       EXPROGRAM,      "Update or insert operations cannot use bind variables when binding type is NOBIND\0" }
    8005             :         , { SYBECRSUPDTAB,      EXPROGRAM,      "Update or insert operations using bind variables require single table cursors\0" }
    8006             :         , { SYBECSYN,        EXCONVERSION,      "Attempt to convert data stopped by syntax error in source field\0" }
    8007             :         , { SYBECUFL,        EXCONVERSION,      "Data conversion resulted in underflow\0" }
    8008             :         , { SYBECWLL,           EXPROGRAM,      "Attempt to set column width less than 1\0" }
    8009             :         , { SYBEDBPS,          EXRESOURCE,      "Maximum number of DBPROCESSes already allocated\0" }
    8010             :         , { SYBEDDNE,              EXCOMM,      "DBPROCESS is dead or not enabled\0" }
    8011             :         , { SYBEDIVZ,              EXUSER,      "Attempt to divide by $0.00 in function %1!\0%s" }
    8012             :         , { SYBEDNTI,           EXPROGRAM,      "Attempt to use dbtxtsput to put a new text timestamp into a column whose datatype "
    8013             :                                                 "is neither SYBTEXT nor SYBIMAGE\0" }
    8014             :         , { SYBEDPOR,           EXPROGRAM,      "Out-of-range datepart constant\0" }
    8015             :         , { SYBEDVOR,           EXPROGRAM,      "Day values must be between 1 and 7\0" }
    8016             :         , { SYBEECAN,              EXINFO,      "Attempted to cancel unrequested event notification\0" }
    8017             :         , { SYBEEINI,              EXINFO,      "Must call dbreginit before dbregexec\0" }
    8018             :         , { SYBEETD,            EXPROGRAM,      "Failure to send the expected amount of TEXT or IMAGE data via dbmoretext\0" }
    8019             :         , { SYBEEUNR,              EXCOMM,      "Unsolicited event notification received\0" }
    8020             :         , { SYBEEVOP,              EXINFO,      "Called dbregwatch with a bad options parameter\0" }
    8021             :         , { SYBEEVST,              EXINFO,      "Must initiate a transaction before calling dbregparam\0" }
    8022             :         , { SYBEFCON,              EXCOMM,      "TDS server connection failed\0" }
    8023             :         , { SYBEFRES,             EXFATAL,      "Challenge-Response function failed\0" }
    8024             :         , { SYBEFSHD,          EXRESOURCE,      "Error in attempting to find the Sybase home directory\0" }
    8025             :         , { SYBEFUNC,           EXPROGRAM,      "Functionality not supported at the specified version level\0" }
    8026             :         , { SYBEICN,            EXPROGRAM,      "Invalid computeid or compute column number\0" }
    8027             :         , { SYBEIDCL,       EXCONSISTENCY,      "Illegal datetime column length returned by TDS server. Legal datetime lengths "
    8028             :                                                 "are 4 and 8 bytes\0" }
    8029             :         , { SYBEIDECCL,     EXCONSISTENCY,      "Invalid decimal column length returned by the server\0" }
    8030             :         , { SYBEIFCL,       EXCONSISTENCY,      "Illegal floating-point column length returned by TDS server. Legal "
    8031             :                                                 "floating-point lengths are 4 and 8 bytes\0" }
    8032             :         , { SYBEIFNB,           EXPROGRAM,      "Illegal field number passed to bcp_control\0" }
    8033             :         , { SYBEIICL,       EXCONSISTENCY,      "Illegal integer column length returned by TDS server. Legal integer lengths "
    8034             :                                                 "are 1, 2, and 4 bytes\0" }
    8035             :         , { SYBEIMCL,       EXCONSISTENCY,      "Illegal money column length returned by TDS server. Legal money lengths are 4 "
    8036             :                                                 "and 8 bytes\0" }
    8037             :         , { SYBEINLN,              EXUSER,      "Interface file: unexpected end-of-line\0" }
    8038             :         , { SYBEINTF,              EXUSER,      "Server name not found in configuration files\0" }
    8039             :         , { SYBEINUMCL,     EXCONSISTENCY,      "Invalid numeric column length returned by the server\0" }
    8040             :         , { SYBEIPV,               EXINFO,      "%1! is an illegal value for the %2! parameter of %3!\0%d %s %s" }
    8041             :         , { SYBEISOI,       EXCONSISTENCY,      "International Release: Invalid sort-order information found\0" }
    8042             :         , { SYBEISRVPREC,   EXCONSISTENCY,      "Illegal precision value returned by the server\0" }
    8043             :         , { SYBEISRVSCL,    EXCONSISTENCY,      "Illegal scale value returned by the server\0" }
    8044             :         , { SYBEITIM,           EXPROGRAM,      "Illegal timeout value specified\0" }
    8045             :         , { SYBEIVERS,          EXPROGRAM,      "Illegal version level specified\0" }
    8046             :         , { SYBEKBCI,              EXINFO,      "1000 rows sent to the server\0" }
    8047             :         , { SYBEKBCO,              EXINFO,      "1000 rows successfully bulk copied to host file\0" }
    8048             :         , { SYBEMEM,           EXRESOURCE,      "Unable to allocate sufficient memory\0" }
    8049             :         , { SYBEMOV,               EXUSER,      "Money arithmetic resulted in overflow in function %1!\0%s" }
    8050             :         , { SYBEMPLL,              EXUSER,      "Attempt to set maximum number of DBPROCESSes lower than 1\0" }
    8051             :         , { SYBEMVOR,           EXPROGRAM,      "Month values must be between 1 and 12\0" }
    8052             :         , { SYBENBUF,              EXINFO,      "Called dbsendpassthru with a NULL buf parameter\0" }
    8053             :         , { SYBENBVP,           EXPROGRAM,      "Cannot pass dbsetnull a NULL bindval pointer\0" }
    8054             :         , { SYBENDC,            EXPROGRAM,      "Cannot have negative component in date in numeric form\0" }
    8055             :         , { SYBENDTP,           EXPROGRAM,      "Called dbdatecrack with NULL datetime parameter\0" }
    8056             :         , { SYBENEG,               EXCOMM,      "Negotiated login attempt failed\0" }
    8057             :         , { SYBENHAN,              EXINFO,      "Called dbrecvpassthru with a NULL handle parameter\0" }
    8058             :         , { SYBENMOB,           EXPROGRAM,      "No such member of order by clause\0" }
    8059             :         , { SYBENOEV,              EXINFO,      "DBPOLL can not be called when registered procedure notifications have been disabled\0" }
    8060             :         , { SYBENPRM,           EXPROGRAM,      "NULL parameter not allowed for this dboption\0" }
    8061             :         , { SYBENSIP,           EXPROGRAM,      "Negative starting index passed to dbstrcpy\0" }
    8062             :         , { SYBENTLL,              EXUSER,      "Name too long for LOGINREC field\0" }
    8063             :         , { SYBENTTN,           EXPROGRAM,      "Attempt to use dbtxtsput to put a new text timestamp into a non-existent data row\0" }
    8064             :         , { SYBENULL,              EXINFO,      "NULL DBPROCESS pointer passed to DB-Library\0" }
    8065             :         , { SYBENULP,           EXPROGRAM,      "Called %1! with parameter %2! NULL\0%s %d" }
    8066             :         , { SYBENXID,          EXNONFATAL,      "The Server did not grant us a distributed-transaction ID\0" }
    8067             :         , { SYBEONCE,           EXPROGRAM,      "Function can be called only once\0" }
    8068             :         , { SYBEOOB,               EXCOMM,      "Error in sending out-of-band data to the server\0" }
    8069             :         , { SYBEOPIN,          EXNONFATAL,      "Could not open interface file\0" }
    8070             :         , { SYBEOPNA,          EXNONFATAL,      "Option is not available with current server\0" }
    8071             :         , { SYBEOREN,              EXINFO,      "International Release: Warning: an out-of-range error-number was encountered in "
    8072             :                                                 "dblib.loc. The maximum permissible error-number is defined as DBERRCOUNT in sybdb.h\0" }
    8073             :         , { SYBEORPF,              EXUSER,      "Attempt to set remote password would overflow "
    8074             :                                                 "the login record's remote password field\0" }
    8075             :         , { SYBEPOLL,              EXINFO,      "There is already an active dbpoll\0" }
    8076             :         , { SYBEPRTF,              EXINFO,      "dbtracestring may only be called from a printfunc\0" }
    8077             :         , { SYBEPWD,               EXUSER,      "Login incorrect\0" }
    8078             :         , { SYBERDCN,        EXCONVERSION,      "Requested data conversion does not exist\0" }
    8079             :         , { SYBERDNR,           EXPROGRAM,      "Attempt to retrieve data from a non-existent row\0" }
    8080             :         , { SYBEREAD,              EXCOMM,      "Read from the server failed\0" }
    8081             :         , { SYBERESP,           EXPROGRAM,      "Response function address passed to dbresponse must be non-NULL\0" }
    8082             :         , { SYBERPCS,              EXINFO,      "Must call dbrpcinit before dbrpcparam or dbrpcsend\0" }
    8083             :         , { SYBERPIL,           EXPROGRAM,      "It is illegal to pass -1 to dbrpcparam for the datalen of parameters which are of "
    8084             :                                                 "type SYBCHAR, SYBVARCHAR, SYBBINARY, or SYBVARBINARY\0" }
    8085             :         , { SYBERPNA,          EXNONFATAL,      "The RPC facility is available only when using a server whose version number is 4.0 "
    8086             :                                                 "or later\0" }
    8087             :         , { SYBERPND,           EXPROGRAM,      "Attempt to initiate a new TDS server operation with results pending\0" }
    8088             :         , { SYBERPNULL,         EXPROGRAM,      "value parameter for dbrpcparam can be NULL, only if the datalen parameter is 0\0" }
    8089             :         , { SYBERPTXTIM,        EXPROGRAM,      "RPC parameters cannot be of type text or image\0" }
    8090             :         , { SYBERPUL,           EXPROGRAM,      "When passing a SYBINTN, SYBDATETIMN, SYBMONEYN, or SYBFLTN parameter via "
    8091             :                                                 "dbrpcparam, it is necessary to specify the parameter's maximum or actual length so "
    8092             :                                                 "that DB-Library can recognize it as a SYINT1, SYBINT2, SYBINT4, SYBMONEY, SYBMONEY4, "
    8093             :                                                 "and so on\0" }
    8094             :         , { SYBERTCC,           EXPROGRAM,      "dbreadtext may not be used to receive the results of a query that contains a "
    8095             :                                                 "COMPUTE clause\0" }
    8096             :         , { SYBERTSC,           EXPROGRAM,      "dbreadtext may be used only to receive the results of a query that contains a "
    8097             :                                                 "single result column\0" }
    8098             :         , { SYBERXID,          EXNONFATAL,      "The Server did not recognize our distributed-transaction ID\0" }
    8099             :         , { SYBESECURE,         EXPROGRAM,      "Secure SQL Server function not supported in this version\0" }
    8100             :         , { SYBESEFA,           EXPROGRAM,      "DBSETNOTIFS cannot be called if connections are present\0" }
    8101             :         , { SYBESEOF,              EXCOMM,      "Unexpected EOF from the server\0" }
    8102             :         , { SYBESFOV,           EXPROGRAM,      "International Release: dbsafestr overflowed its destination buffer\0" }
    8103             :         , { SYBESMSG,            EXSERVER,      "General TDS server error: Check messages from the server\0" }
    8104             :         , { SYBESOCK,              EXCOMM,      "Unable to open socket\0" }
    8105             :         , { SYBESPID,           EXPROGRAM,      "Called dbspid with a NULL dbproc\0" }
    8106             :         , { SYBESYNC,              EXCOMM,      "Read attempted while out of synchronization with TDS server\0" }
    8107             :         , { SYBETEXS,              EXINFO,      "Called dbmoretext with a bad size parameter\0" }
    8108             :         , { SYBETIME,              EXTIME,      "TDS server connection timed out\0" }
    8109             :         , { SYBETMCF,           EXPROGRAM,      "Attempt to install too many custom formats via dbfmtinstall\0" }
    8110             :         , { SYBETMTD,           EXPROGRAM,      "Attempt to send too much TEXT data via the dbmoretext call\0" }
    8111             :         , { SYBETPAR,           EXPROGRAM,      "No SYBTEXT or SYBIMAGE parameters were defined\0" }
    8112             :         , { SYBETPTN,              EXUSER,      "Syntax error: only two periods are permitted in table names\0" }
    8113             :         , { SYBETRAC,              EXINFO,      "Attempted to turn off a trace flag that was not on\0" }
    8114             :         , { SYBETRAN,              EXINFO,      "DBPROCESS is being used for another transaction\0" }
    8115             :         , { SYBETRAS,              EXINFO,      "DB-Library internal error - trace structure not found\0" }
    8116             :         , { SYBETRSN,              EXINFO,      "Bad numbytes parameter passed to dbtracestring\0" }
    8117             :         , { SYBETSIT,              EXINFO,      "Attempt to call dbtsput with an invalid timestamp\0" }
    8118             :         , { SYBETTS,               EXUSER,      "The table which bulk copy is attempting to copy to a host file is shorter than the "
    8119             :                                                 "number of rows which bulk copy was instructed to skip\0" }
    8120             :         , { SYBETYPE,              EXINFO,      "Invalid argument type given to Hyper/DB-Library\0" }
    8121             :         , { SYBEUCPT,              EXUSER,      "Unrecognized custom-format parameter-type encountered in dbstrbuild\0" }
    8122             :         , { SYBEUCRR,       EXCONSISTENCY,      "Internal software error: Unknown connection result reported by dbpasswd\0" }
    8123             :         , { SYBEUDTY,       EXCONSISTENCY,      "Unknown datatype encountered\0" }
    8124             :         , { SYBEUFDS,              EXUSER,      "Unrecognized format encountered in dbstrbuild\0" }
    8125             :         , { SYBEUFDT,       EXCONSISTENCY,      "Unknown fixed-length datatype encountered\0" }
    8126             :         , { SYBEUHST,              EXUSER,      "Unknown host machine name\0" }
    8127             :         , { SYBEUMSG,              EXCOMM,      "Unknown message-id in MSG datastream\0" }
    8128             :         , { SYBEUNAM,             EXFATAL,      "Unable to get current user name from operating system\0" }
    8129             :         , { SYBEUNOP,          EXNONFATAL,      "Unknown option passed to dbsetopt\0" }
    8130             :         , { SYBEUNT,               EXUSER,      "Unknown network type found in interface file\0" }
    8131             :         , { SYBEURCI,          EXRESOURCE,      "International Release: Unable to read copyright information from the DB-Library "
    8132             :                                                 "localization file\0" }
    8133             :         , { SYBEUREI,          EXRESOURCE,      "International Release: Unable to read error information from the DB-Library "
    8134             :                                                 "localization file\0" }
    8135             :         , { SYBEUREM,          EXRESOURCE,      "International Release: Unable to read error mnemonic from the DB-Library "
    8136             :                                                 "localization file\0" }
    8137             :         , { SYBEURES,          EXRESOURCE,      "International Release: Unable to read error string from the DB-Library "
    8138             :                                                 "localization file. 401 Error severities\0" }
    8139             :         , { SYBEURMI,          EXRESOURCE,      "International Release: Unable to read money-format information from the DB-Library "
    8140             :                                                 "localization file\0" }
    8141             :         , { SYBEUSCT,              EXCOMM,      "Unable to set communications timer\0" }
    8142             :         , { SYBEUTDS,              EXCOMM,      "Unrecognized TDS version received from the server\0" }
    8143             :         , { SYBEUVBF,           EXPROGRAM,      "Attempt to read an unknown version of bcp format file\0" }
    8144             :         , { SYBEUVDT,       EXCONSISTENCY,      "Unknown variable-length datatype encountered\0" }
    8145             :         , { SYBEVDPT,              EXUSER,      "For bulk copy, all variable-length data must have either a length-prefix or a "
    8146             :                                                 "terminator specified\0" }
    8147             :         , { SYBEWAID,       EXCONSISTENCY,      "DB-Library internal error: ALTFMT following ALTNAME has wrong id\0" }
    8148             :         , { SYBEWRIT,              EXCOMM,      "Write to the server failed\0" }
    8149             :         , { SYBEXOCI,          EXNONFATAL,      "International Release: A character-set translation overflowed its destination "
    8150             :                                                 "buffer while using bcp to copy data from a host-file to the server\0" }
    8151             :         , { SYBEXTDN,           EXPROGRAM,      "Warning: the xlt_todisp parameter to dbfree_xlate was NULL. The space associated "
    8152             :                                                 "with the xlt_tosrv parameter has been freed\0" }
    8153             :         , { SYBEXTN,            EXPROGRAM,      "The xlt_tosrv and xlt_todisp parameters to dbfree_xlate were NULL\0" }
    8154             :         , { SYBEXTSN,           EXPROGRAM,      "Warning: the xlt_tosrv parameter to dbfree_xlate was NULL. The space associated "
    8155             :                                                 "with the xlt_todisp parameter has been freed\0" }
    8156             :         , { SYBEZTXT,              EXINFO,      "Attempt to send zero length TEXT or IMAGE to dataserver via dbwritetext\0" }
    8157             :         , { SYBECOLSIZE,           EXINFO,      "Invalid column information structure size\0" }
    8158             :         };
    8159             : 
    8160             : /**  \internal
    8161             :  * \ingroup dblib_internal
    8162             :  * \brief Call client-installed error handler
    8163             :  * 
    8164             :  * \param dbproc contains all information needed by db-lib to manage communications with the server.
    8165             :  * \param msgno identifies the error message to be passed to the client's handler.
    8166             :  * \param errnum identifies the OS error (errno), if any.  Use 0 if not applicable.  
    8167             :  * \returns the handler's return code, subject to correction and adjustment for vendor style:
    8168             :  *      - INT_CANCEL    The db-lib function that encountered the error will return FAIL.  
    8169             :  *      - INT_TIMEOUT   The db-lib function will cancel the operation and return FAIL.  \a dbproc remains useable.  
    8170             :  *      - INT_CONTINUE  The db-lib function will retry the operation.  
    8171             :  * \remarks 
    8172             :  *      The client-installed handler may also return INT_EXIT.  If Sybase semantics are used, this function notifies
    8173             :  *      the user and calls exit(3).  If Microsoft semantics are used, this function returns INT_CANCEL.  
    8174             :  *
    8175             :  *      If the client-installed handler returns something other than these four INT_* values, or returns timeout-related
    8176             :  *      value for anything but SYBETIME, it's treated here as INT_EXIT (see above).  
    8177             :  *
    8178             :  * Instead of sprinkling error text all over db-lib, we consolidate it here, 
    8179             :  * where it can be translated (one day), and where it can be mapped to the TDS error number.  
    8180             :  * The libraries don't use consistent error numbers or messages, so when libtds has to emit 
    8181             :  * an error message, it can't include the text.  It can pass its error number to a client-library
    8182             :  * function, which will interpret it, add the text, call the application's installed handler
    8183             :  * (if any) and return the handler's return code back to the caller.  
    8184             :  * 
    8185             :  * The call stack may look something like this:
    8186             :  *
    8187             :  * -#   application
    8188             :  * -#           db-lib function (encounters error)
    8189             :  * -#           dbperror
    8190             :  * -#   error handler (installed by application)
    8191             :  *
    8192             :  * The error handling in this case is unambiguous: the caller invokes this function, the client's handler returns its 
    8193             :  * instruction, which the caller receives.  Quite often the caller will get INT_CANCEL, in which case it should put its 
    8194             :  * house in order and return FAIL.  
    8195             :  *
    8196             :  * The call stack may otherwise look something like this:
    8197             :  *                      
    8198             :  * -#   application
    8199             :  * -#           db-lib function
    8200             :  * -#                   libtds function (encounters error)
    8201             :  * -#           _dblib_handle_err_message
    8202             :  * -#           dbperror
    8203             :  * -#   error handler (installed by application)
    8204             :  *
    8205             :  * Because different client libraries specify their handler semantics differently, 
    8206             :  * and because libtds doesn't know which client library is in charge of any given connection, it cannot interpret the 
    8207             :  * raw return code from a db-lib error handler.  For these reasons, 
    8208             :  * libtds calls _dblib_handle_err_message, which translates between libtds and db-lib semantics.  
    8209             :  * \sa dberrhandle(), _dblib_handle_err_message().
    8210             :  */
    8211             : int
    8212         260 : dbperror(DBPROCESS *dbproc, DBINT msgno, long errnum, ...)
    8213             : {
    8214             :         static const char int_exit_text[] = "FreeTDS: db-lib: exiting because client error handler returned %s for msgno %d\n";
    8215             :         static const char int_invalid_text[] = "%s (%d) received from client-installed error handler for nontimeout for error %d."
    8216             :                                                "  Treating as INT_EXIT\n";
    8217             :         static const DBLIB_ERROR_MESSAGE default_message = { 0, EXCONSISTENCY, "unrecognized msgno" };
    8218         260 :         DBLIB_ERROR_MESSAGE constructed_message = { 0, EXCONSISTENCY, NULL };
    8219         260 :         const DBLIB_ERROR_MESSAGE *msg = &default_message;
    8220             :         
    8221         260 :         int i, rc = INT_CANCEL;
    8222         260 :         const char *os_msgtext = strerror((int) errnum);
    8223         260 :         const char *rc_name = "logic error";
    8224             :         char rc_buf[16];
    8225             : 
    8226         260 :         tdsdump_log(TDS_DBG_FUNC, "dbperror(%p, %d, %ld)\n", dbproc, msgno, errnum);  /* dbproc can be NULL */
    8227             : 
    8228             : #ifdef _WIN32
    8229             :         /*
    8230             :          * Unfortunately MinGW uses the "old" msvcrt.dll (Visual C++ 2005 uses
    8231             :          * a newer version) which does not set errno when allocation functions
    8232             :          * cannot allocate memory, so we do it for them.
    8233             :          */
    8234             :         if (msgno == SYBEMEM)
    8235             :                 errnum = ENOMEM;
    8236             : #endif
    8237             : 
    8238         260 :         if (os_msgtext == NULL)
    8239           0 :                 os_msgtext = "no OS error";
    8240             :         
    8241         260 :         assert(_dblib_err_handler != NULL);     /* always installed by dbinit() or dberrhandle() */
    8242             : 
    8243             :         /* look up the error message */
    8244       89840 :         for (i = 0; i < TDS_VECTOR_SIZE(dblib_error_messages); i++) {
    8245             :                 const char *ptext, *pformats;
    8246             : 
    8247       45050 :                 if (dblib_error_messages[i].msgno != msgno)
    8248       44790 :                         continue;
    8249             : 
    8250             :                 /*
    8251             :                  * See if the message has placeholders.  If so, build a message string on the heap.
    8252             :                  * The presence of placeholders is indicated by the existence of a "string after the string",
    8253             :                  * i.e., a format string (for dbstrbuild) after a null "terminator" in the message.
    8254             :                  * On error -- can't allocate, can't build the string -- give up and call the client handler anyway.
    8255             :                  */
    8256         260 :                 ptext = dblib_error_messages[i].msgtext;
    8257         260 :                 pformats = ptext + strlen(ptext) + 1;
    8258         260 :                 msg = &dblib_error_messages[i];
    8259         260 :                 assert(*(pformats - 1) == '\0');
    8260         260 :                 if (*pformats != '\0') {
    8261             :                         va_list ap;
    8262          10 :                         int result_len, len = 2 * (int) strlen(ptext);
    8263          10 :                         char *buffer = tds_new0(char, len);
    8264             : 
    8265          10 :                         if (buffer == NULL)
    8266             :                                 break;
    8267          10 :                         va_start(ap, errnum);
    8268          10 :                         rc = tds_vstrbuild(buffer, len, &result_len, ptext, TDS_NULLTERM, pformats, TDS_NULLTERM, ap);
    8269          10 :                         buffer[result_len] = '\0';
    8270          10 :                         va_end(ap);
    8271          10 :                         if (TDS_FAILED(rc)) {
    8272           0 :                                 free(buffer);
    8273           0 :                                 break;
    8274             :                         }
    8275          10 :                         constructed_message.msgtext = buffer;
    8276          10 :                         constructed_message.severity = msg->severity;
    8277          10 :                         msg = &constructed_message;
    8278             :                 }
    8279             :                 break;
    8280             :         }
    8281             : 
    8282         260 :         if (dbproc && dbproc->tds_socket && dbproc->tds_socket->login) {
    8283           0 :                 DSTR server_name_dstr = dbproc->tds_socket->login->server_name;
    8284           0 :                 if (!tds_dstr_isempty(&server_name_dstr)) {
    8285           0 :                         char * buffer = NULL;
    8286           0 :                         if (asprintf(&buffer, "%s (%s)", msg->msgtext,
    8287             :                                      tds_dstr_cstr(&server_name_dstr)) >= 0) {
    8288           0 :                                 free((char*) constructed_message.msgtext);
    8289           0 :                                 constructed_message.msgtext = buffer;
    8290           0 :                                 constructed_message.severity = msg->severity;
    8291           0 :                                 msg = &constructed_message;
    8292             :                         }
    8293             :                 }
    8294             :         }
    8295             : 
    8296         260 :         tdsdump_log(TDS_DBG_FUNC, "dbperror: Calling dblib_err_handler with msgno = %d; msg->msgtext = \"%s\"\n",
    8297             :                 msgno, msg->msgtext);
    8298             : 
    8299             :         /* call the error handler */
    8300         260 :         rc = (*_dblib_err_handler)(dbproc, msg->severity, msgno, (int) errnum, (char*) msg->msgtext, (char*) os_msgtext);
    8301         260 :         switch (rc) {
    8302             :         case INT_EXIT:
    8303             :                 rc_name = "INT_EXIT"; 
    8304             :                 break;
    8305          40 :         case INT_CONTINUE:      
    8306          40 :                 rc_name = "INT_CONTINUE";
    8307          40 :                 break;
    8308         200 :         case INT_CANCEL:
    8309         200 :                 rc_name = "INT_CANCEL";
    8310         200 :                 break;
    8311          20 :         case INT_TIMEOUT:
    8312          20 :                 rc_name = "INT_TIMEOUT";
    8313          20 :                 break;
    8314           0 :         default:
    8315           0 :                 rc_name = "invalid";
    8316           0 :                 break;
    8317             :         }
    8318         260 :         tdsdump_log(TDS_DBG_FUNC, "dbperror: dblib_err_handler for msgno = %d; msg->msgtext = \"%s\" -- returns %d (%s)\n",
    8319             :                 msgno, msg->msgtext, rc, rc_name);
    8320             : 
    8321             :         /* we're done with the dynamic string now. */
    8322         260 :         free((char*) constructed_message.msgtext);
    8323             :         
    8324             :         /* Timeout return codes are errors for non-timeout conditions. */
    8325         260 :         if (msgno != SYBETIME) {
    8326         190 :                 switch (rc) {
    8327           0 :                 case INT_CONTINUE:
    8328           0 :                         tdsdump_log(TDS_DBG_SEVERE, int_invalid_text, "INT_CONTINUE", rc, msgno);
    8329             :                         rc = INT_EXIT;
    8330             :                         break;
    8331           0 :                 case INT_TIMEOUT:
    8332           0 :                         tdsdump_log(TDS_DBG_SEVERE, int_invalid_text, "INT_TIMEOUT", rc, msgno);
    8333             :                         rc = INT_EXIT;
    8334             :                         break;
    8335             :                 default:
    8336             :                         break;
    8337             :                 }
    8338          70 :         }
    8339             : 
    8340             :         /* 
    8341             :          * Sybase exits on INT_EXIT; Microsoft converts to INT_CANCEL.
    8342             :          * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dblibc/dbc_pdc04c_6v39.asp
    8343             :          */
    8344         260 :         switch (rc) {
    8345          40 :         case INT_CONTINUE:
    8346             :                 /* Microsoft does not define INT_TIMEOUT.  Instead, two consecutive INT_CONTINUEs yield INT_CANCEL. */
    8347          40 :                 if (dbproc && dbproc->msdblib && ++dbproc->ntimeouts >=2) {
    8348           0 :                         dbproc->ntimeouts = 0;
    8349           0 :                         rc = INT_CANCEL;
    8350             :                 }       /* fall through */
    8351             :         case INT_CANCEL:
    8352             :         case INT_TIMEOUT:
    8353             :                 return rc;      /* normal case */
    8354             :                 break;
    8355           0 :         default:
    8356           0 :                 sprintf(rc_buf, "%d", rc);
    8357           0 :                 rc_name = rc_buf;
    8358           0 :                 tdsdump_log(TDS_DBG_SEVERE, int_invalid_text, "Invalid return code", rc, msgno);
    8359             :                 /* fall through */
    8360             :         case INT_EXIT:
    8361           0 :                 if (dbproc && dbproc->msdblib) {
    8362             :                         /* Microsoft behavior */
    8363             :                         return INT_CANCEL;
    8364             :                 }
    8365             :                 /* fprintf(stderr, int_exit_text, rc_name, msgno); */
    8366           0 :                 tdsdump_log(TDS_DBG_SEVERE, int_exit_text, rc_name, msgno);
    8367             :                 break;
    8368             :         }
    8369           0 :         exit(EXIT_FAILURE);
    8370             :         return rc; /* not reached */
    8371             : }
    8372             : 

Generated by: LCOV version 1.13