odbconn.cpp 79.6 KB
Newer Older
1 2
/***********************************************************************/
/*  Name: ODBCONN.CPP  Version 2.3                                     */
Alexander Barkov's avatar
Alexander Barkov committed
3
/*                                                                     */
4
/*  (C) Copyright to the author Olivier BERTRAND          1998-2017    */
Alexander Barkov's avatar
Alexander Barkov committed
5 6 7 8 9 10 11
/*                                                                     */
/*  This file contains the ODBC connection classes functions.          */
/***********************************************************************/

/***********************************************************************/
/*  Include relevant MariaDB header file.                              */
/***********************************************************************/
12 13
#include <my_global.h>
#include <m_string.h>
14
#if defined(__WIN__)
Alexander Barkov's avatar
Alexander Barkov committed
15 16
//nclude <io.h>
//nclude <fcntl.h>
17
#include <direct.h>                      // for getcwd
Alexander Barkov's avatar
Alexander Barkov committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#if defined(__BORLANDC__)
#define __MFC_COMPAT__                   // To define min/max as macro
#endif
//#include <windows.h>
#else
#if defined(UNIX)
#include <errno.h>
#else
//nclude <io.h>
#endif
//nclude <fcntl.h>
#define NODW
#endif

/***********************************************************************/
/*  Required objects includes.                                         */
/***********************************************************************/
#include "global.h"
#include "plgdbsem.h"
#include "xobject.h"
#include "xtable.h"
39
#include "tabext.h"
40
#include "odbccat.h"
41
#include "tabodbc.h"
Alexander Barkov's avatar
Alexander Barkov committed
42 43 44
#include "plgcnx.h"                       // For DB types
#include "resource.h"
#include "valblk.h"
45
#include "osutil.h"
Alexander Barkov's avatar
Alexander Barkov committed
46 47


48
#if defined(__WIN__)
Alexander Barkov's avatar
Alexander Barkov committed
49 50 51 52 53
/***********************************************************************/
/*  For dynamic load of ODBC32.DLL                                     */
/***********************************************************************/
#pragma comment(lib, "odbc32.lib")
extern "C" HINSTANCE s_hModule;           // Saved module handle
54
#endif // __WIN__
Alexander Barkov's avatar
Alexander Barkov committed
55

56
TYPCONV GetTypeConv();
57 58
int GetConvSize();

Alexander Barkov's avatar
Alexander Barkov committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/***********************************************************************/
/*  Some macro's (should be defined elsewhere to be more accessible)   */
/***********************************************************************/
#if defined(_DEBUG)
#define ASSERT(f)          assert(f)
#define DEBUG_ONLY(f)      (f)
#else   // !_DEBUG
#define ASSERT(f)          ((void)0)
#define DEBUG_ONLY(f)      ((void)0)
#endif  // !_DEBUG

/***********************************************************************/
/*  GetSQLType: returns the SQL_TYPE corresponding to a PLG type.      */
/***********************************************************************/
static short GetSQLType(int type)
  {
  short tp = SQL_TYPE_NULL;

  switch (type) {
    case TYPE_STRING: tp = SQL_CHAR;      break;
    case TYPE_SHORT:  tp = SQL_SMALLINT;  break;
    case TYPE_INT:    tp = SQL_INTEGER;   break;
    case TYPE_DATE:   tp = SQL_TIMESTAMP; break;
82
    case TYPE_BIGINT: tp = SQL_BIGINT;    break;                //  (-5)
83 84 85
    case TYPE_DOUBLE: tp = SQL_DOUBLE;    break;
    case TYPE_TINY:   tp = SQL_TINYINT;   break;
    case TYPE_DECIM:  tp = SQL_DECIMAL;   break;
Alexander Barkov's avatar
Alexander Barkov committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    } // endswitch type

  return tp;
  } // end of GetSQLType

/***********************************************************************/
/*  GetSQLCType: returns the SQL_C_TYPE corresponding to a PLG type.   */
/***********************************************************************/
static int GetSQLCType(int type)
  {
  int tp = SQL_TYPE_NULL;

  switch (type) {
    case TYPE_STRING: tp = SQL_C_CHAR;      break;
    case TYPE_SHORT:  tp = SQL_C_SHORT;     break;
    case TYPE_INT:    tp = SQL_C_LONG;      break;
    case TYPE_DATE:   tp = SQL_C_TIMESTAMP; break;
    case TYPE_BIGINT: tp = SQL_C_SBIGINT;   break;
104
    case TYPE_DOUBLE: tp = SQL_C_DOUBLE;    break;
105
    case TYPE_TINY :  tp = SQL_C_TINYINT;   break;
106 107 108
//#if (ODBCVER >= 0x0300)
//    case TYPE_DECIM:  tp = SQL_C_NUMERIC;   break;  (CRASH!!!)
//#else
109
    case TYPE_DECIM:  tp = SQL_C_CHAR;      break;
110 111
//#endif

Alexander Barkov's avatar
Alexander Barkov committed
112 113 114 115 116 117 118 119
    } // endswitch type

  return tp;
  } // end of GetSQLCType

/***********************************************************************/
/*  TranslateSQLType: translate a SQL Type to a PLG type.              */
/***********************************************************************/
120
int TranslateSQLType(int stp, int prec, int& len, char& v, bool& w)
Alexander Barkov's avatar
Alexander Barkov committed
121 122 123 124
  {
  int type;

  switch (stp) {
125 126
    case SQL_WVARCHAR:                      //  (-9)
      w = true;
Alexander Barkov's avatar
Alexander Barkov committed
127
    case SQL_VARCHAR:                       //   12
128
      v = 'V';
129 130 131 132
      type = TYPE_STRING;
      break;
    case SQL_WCHAR:                         //  (-8)
      w = true;
133
    case SQL_CHAR:                          //    1
Alexander Barkov's avatar
Alexander Barkov committed
134 135
      type = TYPE_STRING;
      break;
136 137
    case SQL_WLONGVARCHAR:                  // (-10)
      w = true;
Alexander Barkov's avatar
Alexander Barkov committed
138
    case SQL_LONGVARCHAR:                   //  (-1)
139 140 141 142 143 144 145
			if (GetTypeConv() == TPC_YES) {
				v = 'V';
				type = TYPE_STRING;
				len = MY_MIN(abs(len), GetConvSize());
			} else
				type = TYPE_ERROR;

Alexander Barkov's avatar
Alexander Barkov committed
146 147 148
      break;
    case SQL_NUMERIC:                       //    2
    case SQL_DECIMAL:                       //    3
149 150 151
//    type = (prec || len > 20) ? TYPE_DOUBLE
//         : (len > 10) ? TYPE_BIGINT : TYPE_INT;
      type = TYPE_DECIM;
Alexander Barkov's avatar
Alexander Barkov committed
152 153 154 155 156
      break;
    case SQL_INTEGER:                       //    4
      type = TYPE_INT;
      break;
    case SQL_SMALLINT:                      //    5
157 158
      type = TYPE_SHORT;
      break;
Alexander Barkov's avatar
Alexander Barkov committed
159 160
    case SQL_TINYINT:                       //  (-6)
    case SQL_BIT:                           //  (-7)
161
      type = TYPE_TINY;
Alexander Barkov's avatar
Alexander Barkov committed
162 163 164 165
      break;
    case SQL_FLOAT:                         //    6
    case SQL_REAL:                          //    7
    case SQL_DOUBLE:                        //    8
166
      type = TYPE_DOUBLE;
Alexander Barkov's avatar
Alexander Barkov committed
167 168
      break;
    case SQL_DATETIME:                      //    9
169 170 171 172
      type = TYPE_DATE;
      len = 19;
      break;
    case SQL_TYPE_DATE:                     //   91
Alexander Barkov's avatar
Alexander Barkov committed
173 174
      type = TYPE_DATE;
      len = 10;
175
      v = 'D';
Alexander Barkov's avatar
Alexander Barkov committed
176 177
      break;
    case SQL_INTERVAL:                      //   10
178
    case SQL_TYPE_TIME:                     //   92
Alexander Barkov's avatar
Alexander Barkov committed
179 180
      type = TYPE_STRING;
      len = 8 + ((prec) ? (prec+1) : 0);
181
      v = 'T';
Alexander Barkov's avatar
Alexander Barkov committed
182 183
      break;
    case SQL_TIMESTAMP:                     //   11
184
    case SQL_TYPE_TIMESTAMP:                //   93
Alexander Barkov's avatar
Alexander Barkov committed
185 186
      type = TYPE_DATE;
      len = 19 + ((prec) ? (prec+1) : 0);
187
      v = 'S';
Alexander Barkov's avatar
Alexander Barkov committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
      break;
    case SQL_BIGINT:                        //  (-5)
      type = TYPE_BIGINT;
      break;
    case SQL_UNKNOWN_TYPE:                  //    0
    case SQL_BINARY:                        //  (-2)
    case SQL_VARBINARY:                     //  (-3)
    case SQL_LONGVARBINARY:                 //  (-4)
    case SQL_GUID:                          // (-11)
    default:
      type = TYPE_ERROR;
      len = 0;
    } // endswitch type

  return type;
  } // end of TranslateSQLType

205
#if defined(PROMPT_OK)
Alexander Barkov's avatar
Alexander Barkov committed
206
/***********************************************************************/
207
/*  ODBCCheckConnection: Check completeness of connection string.      */
Alexander Barkov's avatar
Alexander Barkov committed
208
/***********************************************************************/
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
char *ODBCCheckConnection(PGLOBAL g, char *dsn, int cop)
  {
  char    *newdsn, dir[_MAX_PATH], buf[_MAX_PATH];
  int      rc;
  DWORD    options = ODBConn::openReadOnly;
  ODBConn *ocp = new(g) ODBConn(g, NULL);

  (void) getcwd(dir, sizeof(dir) - 1);

  switch (cop) {
    case 1: options |= ODBConn::forceOdbcDialog; break;
    case 2: options |= ODBConn::noOdbcDialog;    break;
    } // endswitch cop

  if (ocp->Open(dsn, options) < 1)
    newdsn = NULL;
  else
    newdsn = ocp->GetConnect();

  (void) getcwd(buf, sizeof(buf) - 1);

  // Some data sources change the current directory
  if (strcmp(dir, buf))
    rc = chdir(dir);

  ocp->Close();
  return newdsn;         // Return complete connection string
  } // end of ODBCCheckConnection
237
#endif   // PROMPT_OK
Alexander Barkov's avatar
Alexander Barkov committed
238 239 240 241

/***********************************************************************/
/*  Allocate the structure used to refer to the result set.            */
/***********************************************************************/
242 243 244 245 246
static CATPARM *AllocCatInfo(PGLOBAL g, CATINFO fid, PCSZ db,
	                                      PCSZ tab, PQRYRES qrp)
{
	size_t   i, m, n;
	CATPARM *cap;
Alexander Barkov's avatar
Alexander Barkov committed
247 248

#if defined(_DEBUG)
249
	assert(qrp);
Alexander Barkov's avatar
Alexander Barkov committed
250
#endif
251

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
	try {
		m = (size_t)qrp->Maxres;
		n = (size_t)qrp->Nbcol;
		cap = (CATPARM *)PlugSubAlloc(g, NULL, sizeof(CATPARM));
		memset(cap, 0, sizeof(CATPARM));
		cap->Id = fid;
		cap->Qrp = qrp;
		cap->DB = db;
		cap->Tab = tab;
		cap->Vlen = (SQLLEN* *)PlugSubAlloc(g, NULL, n * sizeof(SQLLEN *));

		for (i = 0; i < n; i++)
			cap->Vlen[i] = (SQLLEN *)PlugSubAlloc(g, NULL, m * sizeof(SQLLEN));

		cap->Status = (UWORD *)PlugSubAlloc(g, NULL, m * sizeof(UWORD));

	} catch (int n) {
		htrc("Exeption %d: %s\n", n, g->Message);
		cap = NULL;
	} catch (const char *msg) {
		htrc(g->Message, msg);
		printf("%s\n", g->Message);
		cap = NULL;
	} // end catch

	return cap;
} // end of AllocCatInfo
Alexander Barkov's avatar
Alexander Barkov committed
279

280
#if 0
Alexander Barkov's avatar
Alexander Barkov committed
281 282 283
/***********************************************************************/
/*  Check for nulls and reset them to Null (?) values.                 */
/***********************************************************************/
284
static void ResetNullValues(CATPARM *cap)
Alexander Barkov's avatar
Alexander Barkov committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  {
  int      i, n, ncol;
  PCOLRES  crp;
  PQRYRES  qrp = cap->Qrp;

#if defined(_DEBUG)
  assert(qrp);
#endif

  ncol = qrp->Nbcol;

  for (i = 0, crp = qrp->Colresp; i < ncol && crp; i++, crp = crp->Next)
    for (n = 0; n < qrp->Nblin; n++)
      if (cap->Vlen[i][n] == SQL_NULL_DATA)
        crp->Kdata->Reset(n);

  } // end of ResetNullValues
302
#endif
Alexander Barkov's avatar
Alexander Barkov committed
303 304 305 306 307

/***********************************************************************/
/*  ODBCColumns: constructs the result blocks containing all columns   */
/*  of an ODBC table that will be retrieved by GetData commands.       */
/***********************************************************************/
308 309
PQRYRES ODBCColumns(PGLOBAL g, PCSZ dsn, PCSZ db, PCSZ table,
	                  PCSZ colpat, int maxres, bool info, POPARM sop)
Alexander Barkov's avatar
Alexander Barkov committed
310
  {
311 312 313
  int  buftyp[] = {TYPE_STRING, TYPE_STRING, TYPE_STRING, TYPE_STRING,
                   TYPE_SHORT,  TYPE_STRING, TYPE_INT,    TYPE_INT,
                   TYPE_SHORT,  TYPE_SHORT,  TYPE_SHORT,  TYPE_STRING};
314 315 316
  XFLD fldtyp[] = {FLD_CAT,   FLD_SCHEM,    FLD_TABNAME, FLD_NAME,
                   FLD_TYPE,  FLD_TYPENAME, FLD_PREC,    FLD_LENGTH,
                   FLD_SCALE, FLD_RADIX,    FLD_NULL,    FLD_REM};
317
  unsigned int length[] = {0, 0, 0, 0, 6, 0, 10, 10, 6, 6, 6, 0};
318 319 320 321
	bool     b[] = {true,true,false,false,false,false,false,false,true,true,false,true};
  int      i, n, ncol = 12;
	PCOLRES  crp;
	PQRYRES  qrp;
Alexander Barkov's avatar
Alexander Barkov committed
322
  CATPARM *cap;
323
  ODBConn *ocp = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
324 325 326 327

  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
328 329 330
  if (!info) {
    ocp = new(g) ODBConn(g, NULL);

331
    if (ocp->Open(dsn, sop, 10) < 1)  // openReadOnly + noODBCdialog
332 333
      return NULL;

334 335 336
    if (table && !strchr(table, '%')) {
      // We fix a MySQL limit because some data sources return 32767
      n = ocp->GetMaxValue(SQL_MAX_COLUMNS_IN_TABLE);
337
      maxres = (n) ? MY_MIN(n, 4096) : 4096;
338 339 340
    } else if (!maxres)
      maxres = 20000;

341
//  n = ocp->GetMaxValue(SQL_MAX_CATALOG_NAME_LEN);
342
//  length[0] = (n) ? (n + 1) : 0;
343
//  n = ocp->GetMaxValue(SQL_MAX_SCHEMA_NAME_LEN);
344 345 346
//  length[1] = (n) ? (n + 1) : 0;
//  n = ocp->GetMaxValue(SQL_MAX_TABLE_NAME_LEN);
//  length[2] = (n) ? (n + 1) : 0;
347 348
    n = ocp->GetMaxValue(SQL_MAX_COLUMN_NAME_LEN);
    length[3] = (n) ? (n + 1) : 128;
349 350 351 352 353
  } else {                 // Info table
    maxres = 0;
    length[0] = 128;
    length[1] = 128;
    length[2] = 128;
354
    length[3] = 128;
355 356
    length[5] = 30;
    length[11] = 255;
357
  } // endif ocp
Alexander Barkov's avatar
Alexander Barkov committed
358

359
  if (trace)
360
    htrc("ODBCColumns: max=%d len=%d,%d,%d,%d\n",
361
         maxres, length[0], length[1], length[2], length[3]);
Alexander Barkov's avatar
Alexander Barkov committed
362 363 364 365

  /************************************************************************/
  /*  Allocate the structures used to refer to the result set.            */
  /************************************************************************/
366
  qrp = PlgAllocResult(g, ncol, maxres, IDS_COLUMNS,
367
                          buftyp, fldtyp, length, false, true);
Alexander Barkov's avatar
Alexander Barkov committed
368

369 370 371 372
	for (i = 0, crp = qrp->Colresp; crp; i++, crp = crp->Next)
		if (b[i])
			crp->Kdata->SetNullable(true);

373
  if (info || !qrp)                      // Info table
374 375
    return qrp;

376 377
  if (trace)
    htrc("Getting col results ncol=%d\n", qrp->Nbcol);
Alexander Barkov's avatar
Alexander Barkov committed
378

379 380 381
  if (!(cap = AllocCatInfo(g, CAT_COL, db, table, qrp)))
    return NULL;

382
  cap->Pat = colpat;
Alexander Barkov's avatar
Alexander Barkov committed
383 384 385 386 387 388

  /************************************************************************/
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
  if ((n = ocp->GetCatInfo(cap)) >= 0) {
    qrp->Nblin = n;
389
//  ResetNullValues(cap);
Alexander Barkov's avatar
Alexander Barkov committed
390

391 392 393
    if (trace)
      htrc("Columns: NBCOL=%d NBLIN=%d\n", qrp->Nbcol, qrp->Nblin);

Alexander Barkov's avatar
Alexander Barkov committed
394 395 396
  } else
    qrp = NULL;

397 398 399
  /* Cleanup */
  ocp->Close();

Alexander Barkov's avatar
Alexander Barkov committed
400 401 402 403 404 405
  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
  } // end of ODBCColumns

406 407 408 409
/**************************************************************************/
/*  ODBCSrcCols: constructs the result blocks containing the              */
/*  description of all the columns of a Srcdef option.                    */
/**************************************************************************/
410
PQRYRES ODBCSrcCols(PGLOBAL g, char *dsn, char *src, POPARM sop)
411
  {
412
	char    *sqry;
413 414
  ODBConn *ocp = new(g) ODBConn(g, NULL);

415 416 417
  if (ocp->Open(dsn, sop, 10) < 1)   // openReadOnly + noOdbcDialog
    return NULL;

418 419 420 421 422 423 424 425
	if (strstr(src, "%s")) {
		// Place holder for an eventual where clause
		sqry = (char*)PlugSubAlloc(g, NULL, strlen(src) + 3);
		sprintf(sqry, src, "1=1", "1=1");			 // dummy where clause
	} else
		sqry = src;

  return ocp->GetMetaData(g, dsn, sqry);
426 427
  } // end of ODBCSrcCols

428
#if 0
Alexander Barkov's avatar
Alexander Barkov committed
429 430 431
/**************************************************************************/
/* MyODBCCols: returns column info as required by ha_connect::pre_create. */
/**************************************************************************/
432
PQRYRES MyODBCCols(PGLOBAL g, char *dsn, char *tab, bool info)
Alexander Barkov's avatar
Alexander Barkov committed
433
  {
434
//  int      i, type, len, prec;
435
  bool     w = false;
436
//  PCOLRES  crp, crpt, crpl, crpp;
Alexander Barkov's avatar
Alexander Barkov committed
437
  PQRYRES  qrp;
438
  ODBConn *ocp;
Alexander Barkov's avatar
Alexander Barkov committed
439 440 441 442

  /**********************************************************************/
  /*  Open the connection with the ODBC data source.                    */
  /**********************************************************************/
443 444 445 446 447 448 449 450
  if (!info) {
    ocp = new(g) ODBConn(g, NULL);

    if (ocp->Open(dsn, 2) < 1)        // 2 is openReadOnly
      return NULL;

  } else
    ocp = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
451 452 453 454

  /**********************************************************************/
  /*  Get the information about the ODBC table columns.                 */
  /**********************************************************************/
455
  if ((qrp = ODBCColumns(g, ocp, dsn, NULL, tab, 0, NULL)) && ocp)
Alexander Barkov's avatar
Alexander Barkov committed
456 457 458 459 460
    dsn = ocp->GetConnect();        // Complete connect string

  /************************************************************************/
  /*  Close the local connection.                                         */
  /************************************************************************/
461 462
  if (ocp)
    ocp->Close();
Alexander Barkov's avatar
Alexander Barkov committed
463

464 465 466
  if (!qrp)
    return NULL;             // Error in ODBCColumns

Alexander Barkov's avatar
Alexander Barkov committed
467 468 469
  /************************************************************************/
  /*  Keep only the info used by ha_connect::pre_create.                  */
  /************************************************************************/
470
  qrp->Colresp = qrp->Colresp->Next->Next;  // Skip Schema and Table names
Alexander Barkov's avatar
Alexander Barkov committed
471 472 473 474 475 476 477 478 479 480

  crpt = qrp->Colresp->Next;                // SQL type
  crpl = crpt->Next->Next;                  // Length
  crpp = crpl->Next->Next;                  // Decimals

  for (int i = 0; i < qrp->Nblin; i++) {
    // Types must be PLG types, not SQL types
    type = crpt->Kdata->GetIntValue(i);
    len  = crpl->Kdata->GetIntValue(i);
    prec = crpp->Kdata->GetIntValue(i);
481
    type = TranslateSQLType(type, prec, len, w);
Alexander Barkov's avatar
Alexander Barkov committed
482 483 484
    crpt->Kdata->SetValue(type, i);

    // Some data sources do not count prec in length
485
    if (type == TYPE_DOUBLE)
Alexander Barkov's avatar
Alexander Barkov committed
486 487 488 489 490 491 492
      len += (prec + 2);                    // To be safe

    // Could have been changed for blobs or numeric
    crpl->Kdata->SetValue(len, i);          
    } // endfor i

  crpp->Next = crpp->Next->Next->Next;      // Should be Remark
493 494 495 496 497 498

  // Renumber crp's for flag comparison
  for (i = 0, crp = qrp->Colresp; crp; crp = crp->Next)
    crp->Ncol = ++i;

  qrp->Nbcol = i;             // Should be 7; was 11, skipped 4
Alexander Barkov's avatar
Alexander Barkov committed
499 500
  return qrp;
  } // end of MyODBCCols
501
#endif // 0
Alexander Barkov's avatar
Alexander Barkov committed
502 503

/*************************************************************************/
504 505
/*  ODBCDrivers: constructs the result blocks containing all ODBC        */
/*  drivers available on the local host.                                 */
506
/*  Called with info=true to have result column names.                   */
Alexander Barkov's avatar
Alexander Barkov committed
507
/*************************************************************************/
508
PQRYRES ODBCDrivers(PGLOBAL g, int maxres, bool info)
Alexander Barkov's avatar
Alexander Barkov committed
509
  {
510 511 512
  int      buftyp[] = {TYPE_STRING, TYPE_STRING};
  XFLD     fldtyp[] = {FLD_NAME, FLD_REM};
  unsigned int length[] = {128, 256};
513 514 515 516
	bool     b[] = {false, true};
	int      i, ncol = 2;
	PCOLRES  crp;
	PQRYRES  qrp;
517
  ODBConn *ocp = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
518 519 520 521

  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
522 523
  if (!info) {
    ocp = new(g) ODBConn(g, NULL);
524 525 526 527 528

    if (!maxres)
      maxres = 256;         // Estimated max number of drivers

  } else
529
    maxres = 0;
Alexander Barkov's avatar
Alexander Barkov committed
530

531
  if (trace)
532
    htrc("ODBCDrivers: max=%d len=%d\n", maxres, length[0]);
Alexander Barkov's avatar
Alexander Barkov committed
533 534 535 536

  /************************************************************************/
  /*  Allocate the structures used to refer to the result set.            */
  /************************************************************************/
537
  qrp = PlgAllocResult(g, ncol, maxres, IDS_DRIVER, 
538
                          buftyp, fldtyp, length, false, true);
Alexander Barkov's avatar
Alexander Barkov committed
539

540 541 542 543 544
	for (i = 0, crp = qrp->Colresp; crp; i++, crp = crp->Next)
		if (b[i])
			crp->Kdata->SetNullable(true);

	/************************************************************************/
Alexander Barkov's avatar
Alexander Barkov committed
545 546
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
547
  if (!info && qrp && ocp->GetDrivers(qrp))
Alexander Barkov's avatar
Alexander Barkov committed
548 549 550 551 552 553
    qrp = NULL;

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
554
  } // end of ODBCDrivers
Alexander Barkov's avatar
Alexander Barkov committed
555

556
/*************************************************************************/
557 558
/*  ODBCDataSources: constructs the result blocks containing all ODBC    */
/*  data sources available on the local host.                            */
559 560
/*  Called with info=true to have result column names.                   */
/*************************************************************************/
561
PQRYRES ODBCDataSources(PGLOBAL g, int maxres, bool info)
562
  {
563 564 565
  int      buftyp[] = {TYPE_STRING, TYPE_STRING};
  XFLD     fldtyp[] = {FLD_NAME, FLD_REM};
  unsigned int length[] = {0, 256};
566 567 568 569
	bool     b[] = {false, true};
	int      i, n = 0, ncol = 2;
	PCOLRES  crp;
	PQRYRES  qrp;
570 571 572 573 574 575 576
  ODBConn *ocp = NULL;

  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
  if (!info) {
    ocp = new(g) ODBConn(g, NULL);
577 578 579 580 581 582 583 584
    n = ocp->GetMaxValue(SQL_MAX_DSN_LENGTH);
    length[0] = (n) ? (n + 1) : 256;

    if (!maxres)
      maxres = 512;         // Estimated max number of data sources

  } else {
    length[0] = 256;
585
    maxres = 0;
586
  } // endif info
587

588
  if (trace)
589
    htrc("ODBCDataSources: max=%d len=%d\n", maxres, length[0]);
590 591 592 593

  /************************************************************************/
  /*  Allocate the structures used to refer to the result set.            */
  /************************************************************************/
594
  qrp = PlgAllocResult(g, ncol, maxres, IDS_DSRC, 
595
                          buftyp, fldtyp, length, false, true);
596

597 598 599 600 601
	for (i = 0, crp = qrp->Colresp; crp; i++, crp = crp->Next)
		if (b[i])
			crp->Kdata->SetNullable(true);

	/************************************************************************/
602 603
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
604
  if (!info && qrp && ocp->GetDataSources(qrp))
605 606 607 608 609 610
    qrp = NULL;

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
611
  } // end of ODBCDataSources
612

613 614 615 616
/**************************************************************************/
/*  ODBCTables: constructs the result blocks containing all tables in     */
/*  an ODBC database that will be retrieved by GetData commands.          */
/**************************************************************************/
617 618
PQRYRES ODBCTables(PGLOBAL g, PCSZ dsn, PCSZ db, PCSZ tabpat, PCSZ tabtyp,
	                 int maxres, bool info, POPARM sop)
Alexander Barkov's avatar
Alexander Barkov committed
619
  {
620 621
  int      buftyp[] = {TYPE_STRING, TYPE_STRING, TYPE_STRING,
                       TYPE_STRING, TYPE_STRING};
622 623
  XFLD     fldtyp[] = {FLD_CAT,  FLD_SCHEM, FLD_NAME,
                       FLD_TYPE, FLD_REM};
624
  unsigned int length[] = {0, 0, 0, 16, 0};
625 626 627 628
	bool     b[] ={ true, true, false, false, true };
	int      i, n, ncol = 5;
	PCOLRES  crp;
	PQRYRES  qrp;
Alexander Barkov's avatar
Alexander Barkov committed
629
  CATPARM *cap;
630
  ODBConn *ocp = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
631

632 633 634
  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
635
  if (!info) {
Alexander Barkov's avatar
Alexander Barkov committed
636 637 638 639 640
    /**********************************************************************/
    /*  Open the connection with the ODBC data source.                    */
    /**********************************************************************/
    ocp = new(g) ODBConn(g, NULL);

641
    if (ocp->Open(dsn, sop, 2) < 1)        // 2 is openReadOnly
Alexander Barkov's avatar
Alexander Barkov committed
642 643
      return NULL;

644 645 646
    if (!maxres)
      maxres = 10000;                 // This is completely arbitrary

647
//  n = ocp->GetMaxValue(SQL_MAX_CATALOG_NAME_LEN);
648
//  length[0] = (n) ? (n + 1) : 0;
649
//  n = ocp->GetMaxValue(SQL_MAX_SCHEMA_NAME_LEN);
650
//  length[1] = (n) ? (n + 1) : 0;
651 652
    n = ocp->GetMaxValue(SQL_MAX_TABLE_NAME_LEN);
    length[2] = (n) ? (n + 1) : 128;
653 654 655 656
  } else {
    maxres = 0;
    length[0] = 128;
    length[1] = 128;
657
    length[2] = 128;
658
    length[4] = 255;
659
  } // endif info
Alexander Barkov's avatar
Alexander Barkov committed
660

661 662
  if (trace)
    htrc("ODBCTables: max=%d len=%d,%d\n", maxres, length[0], length[1]);
Alexander Barkov's avatar
Alexander Barkov committed
663 664 665 666

  /************************************************************************/
  /*  Allocate the structures used to refer to the result set.            */
  /************************************************************************/
Olivier Bertrand's avatar
Olivier Bertrand committed
667
  qrp = PlgAllocResult(g, ncol, maxres, IDS_TABLES, buftyp,
668
                                        fldtyp, length, false, true);
Alexander Barkov's avatar
Alexander Barkov committed
669

670 671 672 673 674
	for (i = 0, crp = qrp->Colresp; crp; i++, crp = crp->Next)
		if (b[i])
			crp->Kdata->SetNullable(true);

	if (info || !qrp)
675 676
    return qrp;

677 678 679
  if (!(cap = AllocCatInfo(g, CAT_TAB, db, tabpat, qrp)))
    return NULL;

680
	cap->Pat = tabtyp;
Alexander Barkov's avatar
Alexander Barkov committed
681

682 683
  if (trace)
    htrc("Getting table results ncol=%d\n", cap->Qrp->Nbcol);
Alexander Barkov's avatar
Alexander Barkov committed
684 685 686 687 688 689

  /************************************************************************/
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
  if ((n = ocp->GetCatInfo(cap)) >= 0) {
    qrp->Nblin = n;
690
//  ResetNullValues(cap);
Alexander Barkov's avatar
Alexander Barkov committed
691

692 693 694
    if (trace)
      htrc("Tables: NBCOL=%d NBLIN=%d\n", qrp->Nbcol, qrp->Nblin);

Alexander Barkov's avatar
Alexander Barkov committed
695 696 697 698 699 700
  } else
    qrp = NULL;

  /************************************************************************/
  /*  Close any local connection.                                         */
  /************************************************************************/
701
  ocp->Close();
Alexander Barkov's avatar
Alexander Barkov committed
702 703 704 705 706 707 708

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
  } // end of ODBCTables

709
#if 0                           // Currently not used by CONNECT
Alexander Barkov's avatar
Alexander Barkov committed
710 711 712 713 714 715 716
/**************************************************************************/
/*  PrimaryKeys: constructs the result blocks containing all the          */
/*  ODBC catalog information concerning primary keys.                     */
/**************************************************************************/
PQRYRES ODBCPrimaryKeys(PGLOBAL g, ODBConn *op, char *dsn, char *table)
  {
  static int buftyp[] = {TYPE_STRING, TYPE_STRING, TYPE_STRING,
717 718
                         TYPE_STRING, TYPE_SHORT,  TYPE_STRING};
  static unsigned int length[] = {0, 0, 0, 0, 6, 128};
Alexander Barkov's avatar
Alexander Barkov committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
  int      n, ncol = 5;
  int     maxres;
  PQRYRES  qrp;
  CATPARM *cap;
  ODBConn *ocp = op;

  if (!op) {
    /**********************************************************************/
    /*  Open the connection with the ODBC data source.                    */
    /**********************************************************************/
    ocp = new(g) ODBConn(g, NULL);

    if (ocp->Open(dsn, 2) < 1)        // 2 is openReadOnly
      return NULL;

    } // endif op

  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
  n = ocp->GetMaxValue(SQL_MAX_COLUMNS_IN_TABLE);
  maxres = (n) ? (int)n : 250;
741
  n = ocp->GetMaxValue(SQL_MAX_CATALOG_NAME_LEN);
Alexander Barkov's avatar
Alexander Barkov committed
742
  length[0] = (n) ? (n + 1) : 128;
743
  n = ocp->GetMaxValue(SQL_MAX_SCHEMA_NAME_LEN);
Alexander Barkov's avatar
Alexander Barkov committed
744
  length[1] = (n) ? (n + 1) : 128;
745
  n = ocp->GetMaxValue(SQL_MAX_TABLE_NAME_LEN);
Alexander Barkov's avatar
Alexander Barkov committed
746
  length[2] = (n) ? (n + 1) : 128;
747 748
  n = ocp->GetMaxValue(SQL_MAX_COLUMN_NAME_LEN);
  length[3] = (n) ? (n + 1) : 128;
Alexander Barkov's avatar
Alexander Barkov committed
749

750 751
  if (trace)
    htrc("ODBCPrimaryKeys: max=%d len=%d,%d,%d\n",
Alexander Barkov's avatar
Alexander Barkov committed
752 753 754 755 756
         maxres, length[0], length[1], length[2]);

  /************************************************************************/
  /*  Allocate the structure used to refer to the result set.             */
  /************************************************************************/
757
  qrp = PlgAllocResult(g, ncol, maxres, IDS_PKEY,
758
                          buftyp, NULL, length, false, true);
Alexander Barkov's avatar
Alexander Barkov committed
759

760 761
  if (trace)
    htrc("Getting pkey results ncol=%d\n", qrp->Nbcol);
Alexander Barkov's avatar
Alexander Barkov committed
762

763
  cap = AllocCatInfo(g, CAT_KEY, NULL, table, qrp);
Alexander Barkov's avatar
Alexander Barkov committed
764 765 766 767 768 769

  /************************************************************************/
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
  if ((n = ocp->GetCatInfo(cap)) >= 0) {
    qrp->Nblin = n;
770
//  ResetNullValues(cap);
Alexander Barkov's avatar
Alexander Barkov committed
771

772 773 774
    if (trace)
      htrc("PrimaryKeys: NBCOL=%d NBLIN=%d\n", qrp->Nbcol, qrp->Nblin);

Alexander Barkov's avatar
Alexander Barkov committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
  } else
    qrp = NULL;

  /************************************************************************/
  /*  Close any local connection.                                         */
  /************************************************************************/
  if (!op)
    ocp->Close();

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
  } // end of ODBCPrimaryKeys

/**************************************************************************/
/*  Statistics: constructs the result blocks containing statistics        */
/*  about one or several tables to be retrieved by GetData commands.      */
/**************************************************************************/
PQRYRES ODBCStatistics(PGLOBAL g, ODBConn *op, char *dsn, char *pat,
                                               int un, int acc)
  {
797 798
  static int buftyp[] = {TYPE_STRING,
                         TYPE_STRING, TYPE_STRING, TYPE_SHORT, TYPE_STRING,
Alexander Barkov's avatar
Alexander Barkov committed
799 800
                         TYPE_STRING, TYPE_SHORT,  TYPE_SHORT, TYPE_STRING,
                         TYPE_STRING, TYPE_INT,   TYPE_INT,  TYPE_STRING};
801 802
  static unsigned int length[] = {0, 0, 0 ,6 ,0 ,0 ,6 ,6 ,0 ,2 ,10 ,10 ,128};
  int      n, ncol = 13;
Alexander Barkov's avatar
Alexander Barkov committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  int     maxres;
  PQRYRES  qrp;
  CATPARM *cap;
  ODBConn *ocp = op;

  if (!op) {
    /**********************************************************************/
    /*  Open the connection with the ODBC data source.                    */
    /**********************************************************************/
    ocp = new(g) ODBConn(g, NULL);

    if (ocp->Open(dsn, 2) < 1)        // 2 is openReadOnly
      return NULL;

    } // endif op

  /************************************************************************/
  /*  Do an evaluation of the result size.                                */
  /************************************************************************/
  n = 1 + ocp->GetMaxValue(SQL_MAX_COLUMNS_IN_INDEX);
  maxres = (n) ? (int)n : 32;
824
  n = ocp->GetMaxValue(SQL_MAX_SCHEMA_NAME_LEN);
825
  length[1] = (n) ? (n + 1) : 128;
Alexander Barkov's avatar
Alexander Barkov committed
826
  n = ocp->GetMaxValue(SQL_MAX_TABLE_NAME_LEN);
827
  length[2] = length[5] = (n) ? (n + 1) : 128;
828
  n = ocp->GetMaxValue(SQL_MAX_CATALOG_NAME_LEN);
829
  length[0] = length[4] = (n) ? (n + 1) : length[2];
Alexander Barkov's avatar
Alexander Barkov committed
830 831 832
  n = ocp->GetMaxValue(SQL_MAX_COLUMN_NAME_LEN);
  length[7] = (n) ? (n + 1) : 128;

833 834
  if (trace)
    htrc("SemStatistics: max=%d pat=%s\n", maxres, SVP(pat));
Alexander Barkov's avatar
Alexander Barkov committed
835 836 837 838

  /************************************************************************/
  /*  Allocate the structure used to refer to the result set.             */
  /************************************************************************/
839
  qrp = PlgAllocResult(g, ncol, maxres, IDS_STAT,
840
                          buftyp, NULL, length, false, true);
Alexander Barkov's avatar
Alexander Barkov committed
841

842 843
  if (trace)
    htrc("Getting stat results ncol=%d\n", qrp->Nbcol);
Alexander Barkov's avatar
Alexander Barkov committed
844

845
  cap = AllocCatInfo(g, CAT_STAT, NULL, pat, qrp);
Alexander Barkov's avatar
Alexander Barkov committed
846 847 848 849 850 851 852 853
  cap->Unique = (un < 0) ? SQL_INDEX_UNIQUE : (UWORD)un;
  cap->Accuracy = (acc < 0) ? SQL_QUICK : (UWORD)acc;

  /************************************************************************/
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
  if ((n = ocp->GetCatInfo(cap)) >= 0) {
    qrp->Nblin = n;
854
//  ResetNullValues(cap);
Alexander Barkov's avatar
Alexander Barkov committed
855

856 857 858
    if (trace)
      htrc("Statistics: NBCOL=%d NBLIN=%d\n", qrp->Nbcol, qrp->Nblin);

Alexander Barkov's avatar
Alexander Barkov committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  } else
    qrp = NULL;

  /************************************************************************/
  /*  Close any local connection.                                         */
  /************************************************************************/
  if (!op)
    ocp->Close();

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
  } // end of Statistics
#endif // 0

/***********************************************************************/
/*  Implementation of DBX class.                                       */
/***********************************************************************/
878
DBX::DBX(RETCODE rc, PCSZ msg)
Alexander Barkov's avatar
Alexander Barkov committed
879 880
  {
  m_RC = rc;
881
  m_Msg = msg;
Alexander Barkov's avatar
Alexander Barkov committed
882 883 884 885 886 887 888 889 890

  for (int i = 0; i < MAX_NUM_OF_MSG; i++)
    m_ErrMsg[i] = NULL;

  } // end of DBX constructor

/***********************************************************************/
/*  This function is called by ThrowDBX.                               */
/***********************************************************************/
891
bool DBX::BuildErrorMessage(ODBConn* pdb, HSTMT hstmt)
Alexander Barkov's avatar
Alexander Barkov committed
892 893 894 895 896 897 898 899 900 901 902 903
  {
  if (pdb) {
    SWORD   len;
    RETCODE rc;
    UCHAR   msg[SQL_MAX_MESSAGE_LENGTH + 1];
    UCHAR   state[SQL_SQLSTATE_SIZE + 1];
    SDWORD  native;
    PGLOBAL g = pdb->m_G;

    rc = SQLError(pdb->m_henv, pdb->m_hdbc, hstmt, state,
                  &native, msg, SQL_MAX_MESSAGE_LENGTH - 1, &len);

904 905 906
    if (rc == SQL_NO_DATA_FOUND)
      return false;
    else if (rc != SQL_INVALID_HANDLE) {
Alexander Barkov's avatar
Alexander Barkov committed
907 908 909 910
    // Skip non-errors
      for (int i = 0; i < MAX_NUM_OF_MSG
              && (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO)
              && strcmp((char*)state, "00000"); i++) {
911
        m_ErrMsg[i] = (PSZ)PlugDup(g, (char*)msg);
Alexander Barkov's avatar
Alexander Barkov committed
912

913
        if (trace)
914
          htrc("%s: %s, Native=%d\n", state, msg, native);
Alexander Barkov's avatar
Alexander Barkov committed
915 916 917

        rc = SQLError(pdb->m_henv, pdb->m_hdbc, hstmt, state,
                      &native, msg, SQL_MAX_MESSAGE_LENGTH - 1, &len);
918

Alexander Barkov's avatar
Alexander Barkov committed
919 920
        } // endfor i

921
      return true;
922 923 924
    } else {
      snprintf((char*)msg, SQL_MAX_MESSAGE_LENGTH + 1, "%s: %s", m_Msg,
               MSG(BAD_HANDLE_VAL));
925
      m_ErrMsg[0] = (PSZ)PlugDup(g, (char*)msg);
926 927 928 929

      if (trace)
        htrc("%s: rc=%hd\n", SVP(m_ErrMsg[0]), m_RC); 

930
      return true;
931
    } // endif rc
Alexander Barkov's avatar
Alexander Barkov committed
932 933 934 935

  } else
    m_ErrMsg[0] = "No connexion address provided";

936 937 938
  if (trace)
    htrc("%s: rc=%hd (%s)\n", SVP(m_Msg), m_RC, SVP(m_ErrMsg[0])); 

939
  return true;
Alexander Barkov's avatar
Alexander Barkov committed
940 941
  } // end of BuildErrorMessage

942 943 944 945 946 947 948 949 950 951 952
const char *DBX::GetErrorMessage(int i)
  {
    if (i < 0 || i >= MAX_NUM_OF_MSG)
      return "No ODBC error";
    else if (m_ErrMsg[i])
      return m_ErrMsg[i];
    else
      return (m_Msg) ? m_Msg : "Unknown error";

  } // end of GetErrorMessage

Alexander Barkov's avatar
Alexander Barkov committed
953 954 955 956 957 958 959
/***********************************************************************/
/*  ODBConn construction/destruction.                                  */
/***********************************************************************/
ODBConn::ODBConn(PGLOBAL g, TDBODBC *tdbp)
  {
  m_G = g;
  m_Tdb = tdbp;
960
  m_henv = SQL_NULL_HENV;
Alexander Barkov's avatar
Alexander Barkov committed
961 962 963 964 965 966 967 968
  m_hdbc = SQL_NULL_HDBC;
//m_Recset = NULL
  m_hstmt = SQL_NULL_HSTMT;
  m_LoginTimeout = DEFAULT_LOGIN_TIMEOUT;
  m_QueryTimeout = DEFAULT_QUERY_TIMEOUT;
  m_UpdateOptions = 0;
  m_RowsetSize = (DWORD)((tdbp) ? tdbp->Rows : 10);
  m_Catver = (tdbp) ? tdbp->Catver : 0;
969
  m_Rows = 0;
970
  m_Fetch = 0;
Alexander Barkov's avatar
Alexander Barkov committed
971
  m_Connect = NULL;
972 973
  m_User = NULL;
  m_Pwd = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
974
  m_Updatable = true;
975
  m_Transact = false;
976
  m_Scrollable = (tdbp) ? tdbp->Scrollable : false;
977
  m_Full = false;
978
  m_UseCnc = false;
979 980
  m_IDQuoteChar[0] = '"';
  m_IDQuoteChar[1] = 0;
Alexander Barkov's avatar
Alexander Barkov committed
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
//*m_ErrMsg = '\0';
  } // end of ODBConn

//ODBConn::~ODBConn()
//  {
//if (Connected())
//  EndCom();

//  } // end of ~ODBConn

/***********************************************************************/
/*  Screen for errors.                                                 */
/***********************************************************************/
bool ODBConn::Check(RETCODE rc)
  {
  switch (rc) {
    case SQL_SUCCESS_WITH_INFO:
998
      if (trace) {
Alexander Barkov's avatar
Alexander Barkov committed
999 1000
        DBX x(rc);

1001 1002 1003 1004
        if (x.BuildErrorMessage(this, m_hstmt))
          htrc("ODBC Success With Info, hstmt=%p %s\n",
            m_hstmt, x.GetErrorMessage(0));

1005
        } // endif trace
Alexander Barkov's avatar
Alexander Barkov committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

      // Fall through
    case SQL_SUCCESS:
    case SQL_NO_DATA_FOUND:
      return true;
    } // endswitch rc

  return false;
  } // end of Check

/***********************************************************************/
/*  DB exception throw routines.                                       */
/***********************************************************************/
1019
void ODBConn::ThrowDBX(RETCODE rc, PCSZ msg, HSTMT hstmt)
Alexander Barkov's avatar
Alexander Barkov committed
1020
  {
1021
  DBX* xp = new(m_G) DBX(rc, msg);
Alexander Barkov's avatar
Alexander Barkov committed
1022

1023 1024 1025 1026
  // Don't throw if no error
  if (xp->BuildErrorMessage(this, hstmt))
    throw xp;

Alexander Barkov's avatar
Alexander Barkov committed
1027 1028
  } // end of ThrowDBX

1029
void ODBConn::ThrowDBX(PCSZ msg)
Alexander Barkov's avatar
Alexander Barkov committed
1030
  {
1031
  DBX* xp = new(m_G) DBX(0, "Error");
Alexander Barkov's avatar
Alexander Barkov committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

  xp->m_ErrMsg[0] = msg;
  throw xp;
  } // end of ThrowDBX

/***********************************************************************/
/*  Utility routine.                                                   */
/***********************************************************************/
PSZ ODBConn::GetStringInfo(ushort infotype)
  {
//ASSERT(m_hdbc != SQL_NULL_HDBC);
  char   *p, buffer[MAX_STRING_INFO];
  SWORD   result;
  RETCODE rc;

  rc = SQLGetInfo(m_hdbc, infotype, buffer, sizeof(buffer), &result);

1049 1050
  if (!Check(rc)) {
    ThrowDBX(rc, "SQLGetInfo");  // Temporary
Alexander Barkov's avatar
Alexander Barkov committed
1051
//  *buffer = '\0';
1052
    } // endif rc
Alexander Barkov's avatar
Alexander Barkov committed
1053

1054
  p = PlugDup(m_G, buffer);
Alexander Barkov's avatar
Alexander Barkov committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  return p;
  } // end of GetStringInfo

/***********************************************************************/
/*  Utility routine.                                                   */
/***********************************************************************/
int ODBConn::GetMaxValue(ushort infotype)
  {
//ASSERT(m_hdbc != SQL_NULL_HDBC);
  ushort  maxval;
  RETCODE rc;

  rc = SQLGetInfo(m_hdbc, infotype, &maxval, 0, NULL);

  if (!Check(rc))
    maxval = 0;

  return (int)maxval;
  } // end of GetMaxValue

/***********************************************************************/
/*  Utility routines.                                                  */
/***********************************************************************/
void ODBConn::OnSetOptions(HSTMT hstmt)
  {
  RETCODE rc;
  ASSERT(m_hdbc != SQL_NULL_HDBC);

  if ((signed)m_QueryTimeout != -1) {
    // Attempt to set query timeout.  Ignore failure
    rc = SQLSetStmtOption(hstmt, SQL_QUERY_TIMEOUT, m_QueryTimeout);

    if (!Check(rc))
      // don't attempt it again
      m_QueryTimeout = (DWORD)-1;

    } // endif m_QueryTimeout

  if (m_RowsetSize > 0) {
    // Attempt to set rowset size.
    // In case of failure reset it to 0 to use Fetch.
    rc = SQLSetStmtOption(hstmt, SQL_ROWSET_SIZE, m_RowsetSize);

    if (!Check(rc))
      // don't attempt it again
      m_RowsetSize = 0;

    } // endif m_RowsetSize

  } // end of OnSetOptions

/***********************************************************************/
/*  Open: connect to a data source.                                    */
/***********************************************************************/
1109
int ODBConn::Open(PCSZ ConnectString, POPARM sop, DWORD options)
Alexander Barkov's avatar
Alexander Barkov committed
1110 1111 1112 1113 1114 1115 1116 1117
  {
  PGLOBAL& g = m_G;
//ASSERT_VALID(this);
//ASSERT(ConnectString == NULL || AfxIsValidString(ConnectString));
  ASSERT(!(options & noOdbcDialog && options & forceOdbcDialog));

  m_Updatable = !(options & openReadOnly);
  m_Connect = ConnectString;
1118 1119 1120 1121 1122
  m_User = sop->User;
  m_Pwd = sop->Pwd;
  m_LoginTimeout = sop->Cto;
  m_QueryTimeout = sop->Qto;
  m_UseCnc = sop->UseCnc;
Alexander Barkov's avatar
Alexander Barkov committed
1123 1124 1125

  // Allocate the HDBC and make connection
  try {
1126
    /*PSZ ver;*/
Alexander Barkov's avatar
Alexander Barkov committed
1127 1128

    AllocConnect(options);
1129
    /*ver = GetStringInfo(SQL_ODBC_VER);*/
Alexander Barkov's avatar
Alexander Barkov committed
1130

1131 1132 1133 1134 1135 1136 1137 1138
    if (!m_UseCnc) {
      if (DriverConnect(options)) {
        strcpy(g->Message, MSG(CONNECT_CANCEL));
        return 0;
        } // endif

    } else           // Connect using SQLConnect
      Connect();
Alexander Barkov's avatar
Alexander Barkov committed
1139

1140
    /*ver = GetStringInfo(SQL_DRIVER_ODBC_VER);*/
1141 1142 1143
    // Verify support for required functionality and cache info
//  VerifyConnect();         Deprecated
    GetConnectInfo();
Alexander Barkov's avatar
Alexander Barkov committed
1144
  } catch(DBX *xp) {
1145
    sprintf(g->Message, "%s: %s", xp->m_Msg, xp->GetErrorMessage(0));
1146 1147
    Close();
//  Free();
Alexander Barkov's avatar
Alexander Barkov committed
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    return -1;
  } // end try-catch

  return 1;
  } // end of Open

/***********************************************************************/
/*  Allocate an henv (first time called) and hdbc.                     */
/***********************************************************************/
void ODBConn::AllocConnect(DWORD Options)
  {
  if (m_hdbc != SQL_NULL_HDBC)
    return;

  RETCODE rc;
//AfxLockGlobals(CRIT_ODBC);

  // Need to allocate an environment for first connection
  if (m_henv == SQL_NULL_HENV) {
1167
//  ASSERT(m_nAlloc == 0);
Alexander Barkov's avatar
Alexander Barkov committed
1168 1169 1170 1171 1172

    rc = SQLAllocEnv(&m_henv);

    if (!Check(rc)) {
//    AfxUnlockGlobals(CRIT_ODBC);
1173 1174
      ThrowDBX(rc, "SQLAllocEnv");  // Fatal
      } // endif rc
Alexander Barkov's avatar
Alexander Barkov committed
1175 1176 1177 1178 1179 1180 1181 1182

    } // endif m_henv

  // Do the real thing, allocating connection data
  rc = SQLAllocConnect(m_henv, &m_hdbc);

  if (!Check(rc)) {
//  AfxUnlockGlobals(CRIT_ODBC);
1183 1184
    ThrowDBX(rc, "SQLAllocConnect");  // Fatal
    } // endif rc
Alexander Barkov's avatar
Alexander Barkov committed
1185

1186
//m_nAlloc++;                          // allocated at last
Alexander Barkov's avatar
Alexander Barkov committed
1187 1188 1189 1190
//AfxUnlockGlobals(CRIT_ODBC);

#if defined(_DEBUG)
  if (Options & traceSQL) {
1191
    SQLSetConnectOption(m_hdbc, SQL_OPT_TRACEFILE, (SQLULEN)"xodbc.out");
Alexander Barkov's avatar
Alexander Barkov committed
1192 1193 1194 1195
    SQLSetConnectOption(m_hdbc, SQL_OPT_TRACE, 1);
    } // endif
#endif // _DEBUG

1196 1197
  if ((signed)m_LoginTimeout >= 0) {
    rc = SQLSetConnectOption(m_hdbc, SQL_LOGIN_TIMEOUT, m_LoginTimeout);
Alexander Barkov's avatar
Alexander Barkov committed
1198

1199 1200 1201 1202
    if (trace && rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
      htrc("Warning: Failure setting login timeout\n");

    } // endif Timeout
Alexander Barkov's avatar
Alexander Barkov committed
1203 1204

  if (!m_Updatable) {
1205 1206 1207 1208 1209
    rc = SQLSetConnectOption(m_hdbc, SQL_ACCESS_MODE, SQL_MODE_READ_ONLY);
    
    if (trace && rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
      htrc("Warning: Failure setting read only access mode\n");

Alexander Barkov's avatar
Alexander Barkov committed
1210 1211 1212 1213
    } // endif

  // Turn on cursor lib support
  if (Options & useCursorLib)
1214
    rc = SQLSetConnectOption(m_hdbc, SQL_ODBC_CURSORS, SQL_CUR_USE_DRIVER);
Alexander Barkov's avatar
Alexander Barkov committed
1215 1216 1217 1218

  return;
  } // end of AllocConnect

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
/***********************************************************************/
/*  Connect to data source using SQLConnect.                           */
/***********************************************************************/
void ODBConn::Connect(void)
  {
  SQLRETURN   rc;
  SQLSMALLINT ul = (m_User ? SQL_NTS : 0); 
  SQLSMALLINT pl = (m_Pwd ? SQL_NTS : 0);

  rc = SQLConnect(m_hdbc, (SQLCHAR*)m_Connect, SQL_NTS, 
                          (SQLCHAR*)m_User, ul, (SQLCHAR*)m_Pwd, pl);
                  
  if (!Check(rc))
    ThrowDBX(rc, "SQLConnect");

  } // end of Connect

Alexander Barkov's avatar
Alexander Barkov committed
1236 1237 1238
/***********************************************************************/
/*  Connect to data source using SQLDriverConnect.                     */
/***********************************************************************/
1239
bool ODBConn::DriverConnect(DWORD Options)
Alexander Barkov's avatar
Alexander Barkov committed
1240 1241 1242 1243 1244
  {
  RETCODE rc;
  SWORD   nResult;
  PUCHAR  ConnOut = (PUCHAR)PlugSubAlloc(m_G, NULL, MAX_CONNECT_LEN);
  UWORD   wConnectOption = SQL_DRIVER_COMPLETE;
1245
#if defined(__WIN__)
Alexander Barkov's avatar
Alexander Barkov committed
1246 1247 1248 1249 1250
  HWND    hWndTop = GetForegroundWindow();
  HWND    hWnd = GetParent(hWndTop);

  if (hWnd == NULL)
    hWnd = GetDesktopWindow();
1251
#else   // !__WIN__
1252
  HWND    hWnd = (HWND)1;
1253
#endif  // !__WIN__
Alexander Barkov's avatar
Alexander Barkov committed
1254 1255 1256
  PGLOBAL& g = m_G;
  PDBUSER dup = PlgGetUser(g);

1257
//if (Options & noOdbcDialog || dup->Remote)
Alexander Barkov's avatar
Alexander Barkov committed
1258
    wConnectOption = SQL_DRIVER_NOPROMPT;
1259 1260
//else if (Options & forceOdbcDialog)
//  wConnectOption = SQL_DRIVER_PROMPT;
Alexander Barkov's avatar
Alexander Barkov committed
1261 1262 1263 1264 1265

  rc = SQLDriverConnect(m_hdbc, hWnd, (PUCHAR)m_Connect,
                        SQL_NTS, ConnOut, MAX_CONNECT_LEN,
                        &nResult, wConnectOption);

1266
#if defined(__WIN__)
Alexander Barkov's avatar
Alexander Barkov committed
1267 1268
  if (hWndTop)
    EnableWindow(hWndTop, true);
1269
#endif   // __WIN__
Alexander Barkov's avatar
Alexander Barkov committed
1270 1271 1272

  // If user hit 'Cancel'
  if (rc == SQL_NO_DATA_FOUND) {
1273 1274
    Close();
//  Free();
Alexander Barkov's avatar
Alexander Barkov committed
1275 1276 1277
    return true;
    } // endif rc

1278 1279
  if (!Check(rc))
    ThrowDBX(rc, "SQLDriverConnect");
Alexander Barkov's avatar
Alexander Barkov committed
1280 1281 1282 1283 1284 1285

  // Save connect string returned from ODBC
  m_Connect = (PSZ)ConnOut;

  // All done
  return false;
1286
  } // end of DriverConnect
Alexander Barkov's avatar
Alexander Barkov committed
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

void ODBConn::VerifyConnect()
  {
#if defined(NEWMSG) || defined(XMSG)
  PGLOBAL& g = m_G;
#endif   // NEWMSG  ||         XMSG
  RETCODE  rc;
  SWORD    result;
  SWORD    conformance;

  rc = SQLGetInfo(m_hdbc, SQL_ODBC_API_CONFORMANCE,
                  &conformance, sizeof(conformance), &result);

  if (!Check(rc))
1301
    ThrowDBX(rc, "SQLGetInfo");
Alexander Barkov's avatar
Alexander Barkov committed
1302 1303 1304 1305 1306 1307 1308 1309

  if (conformance < SQL_OAC_LEVEL1)
    ThrowDBX(MSG(API_CONF_ERROR));

  rc = SQLGetInfo(m_hdbc, SQL_ODBC_SQL_CONFORMANCE,
                  &conformance, sizeof(conformance), &result);

  if (!Check(rc))
1310
    ThrowDBX(rc, "SQLGetInfo");
Alexander Barkov's avatar
Alexander Barkov committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360

  if (conformance < SQL_OSC_MINIMUM)
    ThrowDBX(MSG(SQL_CONF_ERROR));

  } // end of VerifyConnect

void ODBConn::GetConnectInfo()
  {
  RETCODE rc;
  SWORD   nResult;
#if 0                   // Update not implemented yet
  UDWORD  DrvPosOp;

  // Reset the database update options
  m_UpdateOptions = 0;

  // Check for SQLSetPos support
  rc = SQLGetInfo(m_hdbc, SQL_POS_OPERATIONS,
                  &DrvPosOp, sizeof(DrvPosOp), &nResult);

  if (Check(rc) &&
      (DrvPosOp & SQL_POS_UPDATE) &&
      (DrvPosOp & SQL_POS_DELETE) &&
      (DrvPosOp & SQL_POS_ADD))
     m_UpdateOptions = SQL_SETPOSUPDATES;

  // Check for positioned update SQL support
  UDWORD PosStatements;

  rc = SQLGetInfo(m_hdbc, SQL_POSITIONED_STATEMENTS,
                        &PosStatements, sizeof(PosStatements),
                        &nResult);

  if (Check(rc) &&
      (PosStatements & SQL_PS_POSITIONED_DELETE) &&
      (PosStatements & SQL_PS_POSITIONED_UPDATE))
    m_UpdateOptions |= SQL_POSITIONEDSQL;

  if (m_Updatable) {
    // Make sure data source is Updatable
    char ReadOnly[10];

    rc = SQLGetInfo(m_hdbc, SQL_DATA_SOURCE_READ_ONLY,
                    ReadOnly, sizeof(ReadOnly), &nResult);

    if (Check(rc) && nResult == 1)
      m_Updatable = !!strcmp(ReadOnly, "Y");
    else
      m_Updatable = false;

1361 1362 1363
    if (trace)
      htrc("Warning: data source is readonly\n");

Alexander Barkov's avatar
Alexander Barkov committed
1364 1365 1366 1367 1368
  } else // Make data source is !Updatable
    rc = SQLSetConnectOption(m_hdbc, SQL_ACCESS_MODE,
                                     SQL_MODE_READ_ONLY);
#endif   // 0

1369
  // Get the quote char to use when constructing SQL
Alexander Barkov's avatar
Alexander Barkov committed
1370
  rc = SQLGetInfo(m_hdbc, SQL_IDENTIFIER_QUOTE_CHAR,
1371
                  m_IDQuoteChar, sizeof(m_IDQuoteChar), &nResult);
Alexander Barkov's avatar
Alexander Barkov committed
1372

1373
  if (trace)
1374 1375
    htrc("DBMS: %s, Version: %s, rc=%d\n",
         GetStringInfo(SQL_DBMS_NAME), GetStringInfo(SQL_DBMS_VER), rc);
1376

Alexander Barkov's avatar
Alexander Barkov committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
  } // end of GetConnectInfo

/***********************************************************************/
/*  Allocate record set and execute an SQL query.                      */
/***********************************************************************/
int ODBConn::ExecDirectSQL(char *sql, ODBCCOL *tocols)
  {
  PGLOBAL& g = m_G;
  void    *buffer;
  bool     b;
  UWORD    n;
1388
  SWORD    len, tp, ncol = 0;
Alexander Barkov's avatar
Alexander Barkov committed
1389 1390 1391 1392 1393 1394 1395 1396
  ODBCCOL *colp;
  RETCODE  rc;
  HSTMT    hstmt;

  try {
    b = false;

    if (m_hstmt) {
1397
      // This is a Requery
1398 1399
      rc = SQLFreeStmt(m_hstmt, SQL_CLOSE);

1400
      if (!Check(rc))
1401
        ThrowDBX(rc, "SQLFreeStmt", m_hstmt);
1402

Alexander Barkov's avatar
Alexander Barkov committed
1403
      m_hstmt = NULL;
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
      } // endif m_hstmt

    rc = SQLAllocStmt(m_hdbc, &hstmt);

    if (!Check(rc))
      ThrowDBX(rc, "SQLAllocStmt");

    if (m_Scrollable) {
      rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_SCROLLABLE, 
                          (void*)SQL_SCROLLABLE, 0);
Alexander Barkov's avatar
Alexander Barkov committed
1414 1415

      if (!Check(rc))
1416
        ThrowDBX(rc, "Scrollable", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1417

1418
      } // endif m_Scrollable
Alexander Barkov's avatar
Alexander Barkov committed
1419 1420 1421 1422

    OnSetOptions(hstmt);
    b = true;

1423
    if (trace)
1424
      htrc("ExecDirect hstmt=%p %.256s\n", hstmt, sql);
Alexander Barkov's avatar
Alexander Barkov committed
1425

1426 1427 1428 1429 1430
    if (m_Tdb->Srcdef) {
      // Be sure this is a query returning a result set
      do {
        rc = SQLPrepare(hstmt, (PUCHAR)sql, SQL_NTS);
        } while (rc == SQL_STILL_EXECUTING);
Alexander Barkov's avatar
Alexander Barkov committed
1431

1432 1433
      if (!Check(rc))
        ThrowDBX(rc, "SQLPrepare", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1434

1435 1436
      if (!Check(rc = SQLNumResultCols(hstmt, &ncol)))
        ThrowDBX(rc, "SQLNumResultCols", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1437

1438 1439 1440 1441 1442 1443 1444 1445 1446
      if (ncol == 0) {
        strcpy(g->Message, "This Srcdef does not return a result set");
        return -1;
        } // endif ncol

      // Ok, now we can proceed
      do {
        rc = SQLExecute(hstmt);
        } while (rc == SQL_STILL_EXECUTING);
Alexander Barkov's avatar
Alexander Barkov committed
1447 1448

      if (!Check(rc))
1449
        ThrowDBX(rc, "SQLExecute", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1450

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    } else {
      do {
        rc = SQLExecDirect(hstmt, (PUCHAR)sql, SQL_NTS);
        } while (rc == SQL_STILL_EXECUTING);

      if (!Check(rc))
        ThrowDBX(rc, "SQLExecDirect", hstmt);

      do {
        rc = SQLNumResultCols(hstmt, &ncol);
        } while (rc == SQL_STILL_EXECUTING);

    } // endif Srcdef
Alexander Barkov's avatar
Alexander Barkov committed
1464 1465 1466

    for (n = 0, colp = tocols; colp; colp = (PODBCCOL)colp->GetNext())
      if (!colp->IsSpecial())
1467
        n++;
Alexander Barkov's avatar
Alexander Barkov committed
1468 1469

    // n can be 0 for query such as Select count(*) from table
1470
    if (n && n > (UWORD)ncol)
Alexander Barkov's avatar
Alexander Barkov committed
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
      ThrowDBX(MSG(COL_NUM_MISM));

    // Now bind the column buffers
    for (n = 1, colp = tocols; colp; colp = (PODBCCOL)colp->GetNext())
      if (!colp->IsSpecial()) {
        buffer = colp->GetBuffer(m_RowsetSize);
        len = colp->GetBuflen();
        tp = GetSQLCType(colp->GetResultType());

        if (tp == SQL_TYPE_NULL) {
          sprintf(m_G->Message, MSG(INV_COLUMN_TYPE),
                  colp->GetResultType(), SVP(colp->GetName()));
          ThrowDBX(m_G->Message);
          } // endif tp

1486
        if (trace)
Alexander Barkov's avatar
Alexander Barkov committed
1487 1488 1489 1490 1491 1492
          htrc("Binding col=%u type=%d buf=%p len=%d slen=%p\n",
                  n, tp, buffer, len, colp->GetStrLen());

        rc = SQLBindCol(hstmt, n, tp, buffer, len, colp->GetStrLen());

        if (!Check(rc))
1493
          ThrowDBX(rc, "SQLBindCol", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1494 1495 1496 1497 1498

        n++;
        } // endif pcol

  } catch(DBX *x) {
1499 1500 1501 1502
    if (trace)
      for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
        htrc(x->m_ErrMsg[i]);

1503
    sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
Alexander Barkov's avatar
Alexander Barkov committed
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534

    if (b)
      SQLCancel(hstmt);

    rc = SQLFreeStmt(hstmt, SQL_DROP);
    m_hstmt = NULL;
    return -1;
  } // end try/catch

  m_hstmt = hstmt;
  return (int)m_RowsetSize;   // May have been reset in OnSetOptions
  } // end of ExecDirectSQL

/***********************************************************************/
/*  Get the number of lines of the result set.                         */
/***********************************************************************/
int ODBConn::GetResultSize(char *sql, ODBCCOL *colp)
  {
  int    n = 0;
  RETCODE rc;

  if (ExecDirectSQL(sql, colp) < 0)
    return -1;

  try {
    for (n = 0; ; n++) {
      do {
        rc = SQLFetch(m_hstmt);
        } while (rc == SQL_STILL_EXECUTING);

      if (!Check(rc))
1535
        ThrowDBX(rc, "SQLFetch", m_hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1536 1537 1538 1539 1540 1541 1542 1543

      if (rc == SQL_NO_DATA_FOUND)
        break;

      } // endfor n

  } catch(DBX *x) {
    strcpy(m_G->Message, x->GetErrorMessage(0));
1544 1545 1546 1547 1548
    
    if (trace)
      for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
        htrc(x->m_ErrMsg[i]);

Alexander Barkov's avatar
Alexander Barkov committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    SQLCancel(m_hstmt);
    n = -2;
  } // end try/catch

  rc = SQLFreeStmt(m_hstmt, SQL_DROP);
  m_hstmt = NULL;

  if (n != 1)
    return -3;
  else
    return colp->GetIntValue();

  } // end of GetResultSize

/***********************************************************************/
/*  Fetch next row.                                                    */
/***********************************************************************/
1566
int ODBConn::Fetch(int pos)
Alexander Barkov's avatar
Alexander Barkov committed
1567 1568 1569 1570 1571 1572 1573 1574 1575
  {
  ASSERT(m_hstmt);
  int      irc;
  SQLULEN  crow;
  RETCODE  rc;
  PGLOBAL& g = m_G;

  try {
//  do {
1576 1577 1578
    if (pos) {
      rc = SQLExtendedFetch(m_hstmt, SQL_FETCH_ABSOLUTE, pos, &crow, NULL);
    } else if (m_RowsetSize) {
Alexander Barkov's avatar
Alexander Barkov committed
1579 1580 1581 1582 1583 1584 1585
      rc = SQLExtendedFetch(m_hstmt, SQL_FETCH_NEXT, 1, &crow, NULL);
    } else {
      rc = SQLFetch(m_hstmt);
      crow = 1;
    } // endif m_RowsetSize
//    } while (rc == SQL_STILL_EXECUTING);

1586
    if (trace > 1)
Alexander Barkov's avatar
Alexander Barkov committed
1587 1588 1589 1590
      htrc("Fetch: hstmt=%p RowseSize=%d rc=%d\n",
                     m_hstmt, m_RowsetSize, rc);

    if (!Check(rc))
1591
      ThrowDBX(rc, "Fetching", m_hstmt);
1592

1593 1594 1595 1596 1597
    if (rc == SQL_NO_DATA_FOUND) {
      m_Full = (m_Fetch == 1);
      irc = 0;
    } else
      irc = (int)crow;
1598

1599 1600
    m_Fetch++;
    m_Rows += irc;
Alexander Barkov's avatar
Alexander Barkov committed
1601
  } catch(DBX *x) {
1602
    if (trace)
Alexander Barkov's avatar
Alexander Barkov committed
1603 1604 1605
      for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
        htrc(x->m_ErrMsg[i]);

1606
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
Alexander Barkov's avatar
Alexander Barkov committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
    irc = -1;
  } // end try/catch

  return irc;
  } // end of Fetch

/***********************************************************************/
/*  Prepare an SQL statement for insert.                               */
/***********************************************************************/
int ODBConn::PrepareSQL(char *sql)
  {
  PGLOBAL& g = m_G;
  bool     b;
1620
  UINT     txn = 0;
Alexander Barkov's avatar
Alexander Barkov committed
1621 1622 1623 1624
  SWORD    nparm;
  RETCODE  rc;
  HSTMT    hstmt;

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
  if (m_Tdb->GetMode() != MODE_READ) {
    // Does the data source support transactions
    rc = SQLGetInfo(m_hdbc, SQL_TXN_CAPABLE, &txn, 0, NULL);

    if (Check(rc) && txn != SQL_TC_NONE) try {
      rc = SQLSetConnectAttr(m_hdbc, SQL_ATTR_AUTOCOMMIT,
                                     SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
      
      if (!Check(rc))
        ThrowDBX(SQL_INVALID_HANDLE, "SQLSetConnectAttr");

      m_Transact = true;
    } catch(DBX *x) {
      if (trace)
        for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
          htrc(x->m_ErrMsg[i]);

1642
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
1643 1644 1645 1646
    } // end try/catch

    } // endif Mode

Alexander Barkov's avatar
Alexander Barkov committed
1647 1648 1649 1650 1651 1652 1653 1654 1655
  try {
    b = false;

    if (m_hstmt) {
      RETCODE rc = SQLFreeStmt(m_hstmt, SQL_CLOSE);

      hstmt = m_hstmt;
      m_hstmt = NULL;

1656 1657
      if (m_Tdb->GetAmType() != TYPE_AM_XDBC)
        ThrowDBX(MSG(SEQUENCE_ERROR));
Alexander Barkov's avatar
Alexander Barkov committed
1658

1659 1660 1661 1662 1663 1664
      } // endif m_hstmt

    rc = SQLAllocStmt(m_hdbc, &hstmt);

    if (!Check(rc))
      ThrowDBX(SQL_INVALID_HANDLE, "SQLAllocStmt");
Alexander Barkov's avatar
Alexander Barkov committed
1665 1666 1667 1668

    OnSetOptions(hstmt);
    b = true;

1669
    if (trace)
Alexander Barkov's avatar
Alexander Barkov committed
1670 1671 1672 1673 1674 1675 1676
      htrc("Prepare hstmt=%p %.64s\n", hstmt, sql);

    do {
      rc = SQLPrepare(hstmt, (PUCHAR)sql, SQL_NTS);
      } while (rc == SQL_STILL_EXECUTING);

    if (!Check(rc))
1677
      ThrowDBX(rc, "SQLPrepare", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1678 1679 1680 1681 1682 1683

    do {
      rc = SQLNumParams(hstmt, &nparm);
      } while (rc == SQL_STILL_EXECUTING);

  } catch(DBX *x) {
1684 1685 1686 1687
    if (trace)
      for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
        htrc(x->m_ErrMsg[i]);

1688
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
Alexander Barkov's avatar
Alexander Barkov committed
1689 1690 1691 1692 1693 1694

    if (b)
      SQLCancel(hstmt);

    rc = SQLFreeStmt(hstmt, SQL_DROP);
    m_hstmt = NULL;
1695 1696 1697 1698 1699 1700

    if (m_Transact) {
      rc = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_ROLLBACK);
      m_Transact = false;
      } // endif m_Transact

Alexander Barkov's avatar
Alexander Barkov committed
1701 1702 1703 1704 1705 1706 1707 1708
    return -1;
  } // end try/catch

  m_hstmt = hstmt;
  return (int)nparm;
  } // end of PrepareSQL

/***********************************************************************/
1709
/*  Execute a prepared statement.                                      */
Alexander Barkov's avatar
Alexander Barkov committed
1710
/***********************************************************************/
1711
int ODBConn::ExecuteSQL(void)
Alexander Barkov's avatar
Alexander Barkov committed
1712
  {
1713 1714 1715 1716
  PGLOBAL& g = m_G;
  SWORD    ncol = 0;
  RETCODE  rc;
  SQLLEN   afrw = -1;
Alexander Barkov's avatar
Alexander Barkov committed
1717 1718

  try {
1719 1720 1721
    do {
      rc = SQLExecute(m_hstmt);
      } while (rc == SQL_STILL_EXECUTING);
Alexander Barkov's avatar
Alexander Barkov committed
1722 1723

    if (!Check(rc))
1724
      ThrowDBX(rc, "SQLExecute", m_hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1725

1726
    if (!Check(rc = SQLNumResultCols(m_hstmt, &ncol)))
1727 1728 1729
      ThrowDBX(rc, "SQLNumResultCols", m_hstmt);

    if (ncol) {
1730 1731
      // This should never happen while inserting
      strcpy(g->Message, "Logical error while inserting");
1732 1733
    } else {
      // Insert, Update or Delete statement
1734
      if (!Check(rc = SQLRowCount(m_hstmt, &afrw)))
1735 1736 1737 1738
        ThrowDBX(rc, "SQLRowCount", m_hstmt);

    } // endif ncol

Alexander Barkov's avatar
Alexander Barkov committed
1739
  } catch(DBX *x) {
1740
    sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
Alexander Barkov's avatar
Alexander Barkov committed
1741 1742 1743
    SQLCancel(m_hstmt);
    rc = SQLFreeStmt(m_hstmt, SQL_DROP);
    m_hstmt = NULL;
1744 1745 1746 1747 1748 1749

    if (m_Transact) {
      rc = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_ROLLBACK);
      m_Transact = false;
      } // endif m_Transact

1750
    afrw = -1;
Alexander Barkov's avatar
Alexander Barkov committed
1751 1752
  } // end try/catch

1753
  return (int)afrw;
Alexander Barkov's avatar
Alexander Barkov committed
1754 1755 1756 1757 1758 1759 1760
  } // end of ExecuteSQL

/***********************************************************************/
/*  Bind a parameter for inserting.                                    */
/***********************************************************************/
bool ODBConn::BindParam(ODBCCOL *colp)
  {
1761 1762 1763
  void        *buf;
  int          buftype = colp->GetResultType();
  SQLUSMALLINT n = colp->GetRank();
1764
	SQLSMALLINT  ct, sqlt, dec, nul __attribute__((unused));
1765 1766 1767 1768
  SQLULEN      colsize;
  SQLLEN       len;
  SQLLEN      *strlen = colp->GetStrLen();
  SQLRETURN    rc;
Alexander Barkov's avatar
Alexander Barkov committed
1769

1770
#if 0
Alexander Barkov's avatar
Alexander Barkov committed
1771
  try {
1772
		// This function is often not or badly implemented by data sources
1773
    rc = SQLDescribeParam(m_hstmt, n, &sqlt, &colsize, &dec, &nul);
Alexander Barkov's avatar
Alexander Barkov committed
1774 1775

    if (!Check(rc))
1776
      ThrowDBX(rc, "SQLDescribeParam", m_hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1777 1778

  } catch(DBX *x) {
1779
    sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
1780
#endif // 0
1781 1782
    colsize = colp->GetPrecision();
    sqlt = GetSQLType(buftype);
1783 1784 1785
		dec = IsTypeNum(buftype) ? colp->GetScale() : 0;
		nul = colp->IsNullable() ? SQL_NULLABLE : SQL_NO_NULLS;
//} // end try/catch
Alexander Barkov's avatar
Alexander Barkov committed
1786 1787

  buf = colp->GetBuffer(0);
1788 1789 1790
  len = IsTypeChar(buftype) ? colp->GetBuflen() : 0;
  ct = GetSQLCType(buftype);
  *strlen = IsTypeChar(buftype) ? SQL_NTS : 0;
Alexander Barkov's avatar
Alexander Barkov committed
1791 1792 1793

  try {
    rc = SQLBindParameter(m_hstmt, n, SQL_PARAM_INPUT, ct, sqlt,
1794
                          colsize, dec, buf, len, strlen);
Alexander Barkov's avatar
Alexander Barkov committed
1795 1796

    if (!Check(rc))
1797
      ThrowDBX(rc, "SQLBindParameter", m_hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809

  } catch(DBX *x) {
    strcpy(m_G->Message, x->GetErrorMessage(0));
    SQLCancel(m_hstmt);
    rc = SQLFreeStmt(m_hstmt, SQL_DROP);
    m_hstmt = NULL;
    return true;
  } // end try/catch

  return false;
  } // end of BindParam

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
/***********************************************************************/
/*  Execute an SQL command.                                            */
/***********************************************************************/
bool ODBConn::ExecSQLcommand(char *sql)
  {
  char     cmd[16];
  bool     b, rcd = false;
  UINT     txn = 0;
  PGLOBAL& g = m_G;
  SWORD    ncol = 0;
  SQLLEN   afrw;
  RETCODE  rc;
  HSTMT    hstmt;

  try {
    b = FALSE;

    // Check whether we should use transaction
    if (sscanf(sql, " %15s ", cmd) == 1) {
      if (!stricmp(cmd, "INSERT") || !stricmp(cmd, "UPDATE") ||
          !stricmp(cmd, "DELETE") || !stricmp(cmd, "REPLACE")) {
        // Does the data source support transactions
        rc = SQLGetInfo(m_hdbc, SQL_TXN_CAPABLE, &txn, 0, NULL);
    
        if (Check(rc) && txn != SQL_TC_NONE) {
          rc = SQLSetConnectAttr(m_hdbc, SQL_ATTR_AUTOCOMMIT,
                                 SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
        
          if (!Check(rc))
            ThrowDBX(SQL_INVALID_HANDLE, "SQLSetConnectAttr");
    
          m_Transact = TRUE;
          } // endif txn

        } // endif cmd

      } // endif sql

    // Allocate the statement handle
    rc = SQLAllocStmt(m_hdbc, &hstmt);

    if (!Check(rc))
      ThrowDBX(SQL_INVALID_HANDLE, "SQLAllocStmt");

    OnSetOptions(hstmt);
    b = true;

    if (trace)
      htrc("ExecSQLcommand hstmt=%p %.64s\n", hstmt, sql);

    // Proceed with command execution
    do {
      rc = SQLExecDirect(hstmt, (PUCHAR)sql, SQL_NTS);
      } while (rc == SQL_STILL_EXECUTING);

    if (!Check(rc))
      ThrowDBX(rc, "SQLExecDirect", hstmt);

    // Check whether this is a query returning a result set
    if (!Check(rc = SQLNumResultCols(hstmt, &ncol)))
      ThrowDBX(rc, "SQLNumResultCols", hstmt);

    if (!ncol) {
      if (!Check(SQLRowCount(hstmt, &afrw)))
        ThrowDBX(rc, "SQLRowCount", hstmt);

      m_Tdb->AftRows = (int)afrw;
      strcpy(g->Message, "Affected rows");
    } else {
      m_Tdb->AftRows = (int)ncol;
      strcpy(g->Message, "Result set column number");
    } // endif ncol

  } catch(DBX *x) {
		if (trace)
			for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
				htrc(x->m_ErrMsg[i]);

1888
    sprintf(g->Message, "Remote %s: %s", x->m_Msg, x->GetErrorMessage(0));
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915

    if (b)
      SQLCancel(hstmt);

    m_Tdb->AftRows = -1;
    rcd = true;
  } // end try/catch

  if (!Check(rc = SQLFreeStmt(hstmt, SQL_CLOSE)))
    sprintf(g->Message, "SQLFreeStmt: rc=%d", rc);

  if (m_Transact) {
    // Terminate the transaction
    if (!Check(rc = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, 
                       (rcd) ? SQL_ROLLBACK : SQL_COMMIT)))
      sprintf(g->Message, "SQLEndTran: rc=%d", rc);

    if (!Check(rc = SQLSetConnectAttr(m_hdbc, SQL_ATTR_AUTOCOMMIT,
               (SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_IS_UINTEGER)))
      sprintf(g->Message, "SQLSetConnectAttr: rc=%d", rc);

    m_Transact = false;
    } // endif m_Transact

  return rcd;
  } // end of ExecSQLcommand

1916 1917 1918 1919
/**************************************************************************/
/*  GetMetaData: constructs the result blocks containing the              */
/*  description of all the columns of an SQL command.                     */
/**************************************************************************/
1920
PQRYRES ODBConn::GetMetaData(PGLOBAL g, PCSZ dsn, PCSZ src)
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
  {
  static int  buftyp[] = {TYPE_STRING, TYPE_SHORT, TYPE_INT,
                          TYPE_SHORT,  TYPE_SHORT};
  static XFLD fldtyp[] = {FLD_NAME,  FLD_TYPE, FLD_PREC,
                          FLD_SCALE, FLD_NULL};
  static unsigned int length[] = {0, 6, 10, 6, 6};
  unsigned char cn[60];
  int     qcol = 5;
  short   nl, type, prec, nul, cns = (short)sizeof(cn);
  PQRYRES qrp = NULL;
  PCOLRES crp;
  USHORT  i;
1933
  SQLULEN n;
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
  SWORD   ncol;
  RETCODE rc;
  HSTMT   hstmt;

  try {
    rc = SQLAllocStmt(m_hdbc, &hstmt);

    if (!Check(rc))
      ThrowDBX(SQL_INVALID_HANDLE, "SQLAllocStmt");

    OnSetOptions(hstmt);

    do {
      rc = SQLPrepare(hstmt, (PUCHAR)src, SQL_NTS);
//    rc = SQLExecDirect(hstmt, (PUCHAR)src, SQL_NTS);
      } while (rc == SQL_STILL_EXECUTING);

    if (!Check(rc))
      ThrowDBX(rc, "SQLExecDirect", hstmt);

    do {
      rc = SQLNumResultCols(hstmt, &ncol);
      } while (rc == SQL_STILL_EXECUTING);

    if (!Check(rc))
      ThrowDBX(rc, "SQLNumResultCols", hstmt);

    if (ncol) for (i = 1; i <= ncol; i++) {
      do {
        rc = SQLDescribeCol(hstmt, i, NULL, 0, &nl, NULL, NULL, NULL, NULL); 
        } while (rc == SQL_STILL_EXECUTING);

      if (!Check(rc))
        ThrowDBX(rc, "SQLDescribeCol", hstmt);

1969
      length[0] = MY_MAX(length[0], (UINT)nl);
1970 1971 1972
      } // endfor i

  } catch(DBX *x) {
1973
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    goto err;
  } // end try/catch

  if (!ncol) {
    strcpy(g->Message, "Invalid Srcdef");
    goto err;
    } // endif ncol

  /************************************************************************/
  /*  Allocate the structures used to refer to the result set.            */
  /************************************************************************/
1985 1986 1987
  if (!(qrp = PlgAllocResult(g, qcol, ncol, IDS_COLUMNS + 3,
                             buftyp, fldtyp, length, false, true)))
    return NULL;
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023

  // Some columns must be renamed
  for (i = 0, crp = qrp->Colresp; crp; crp = crp->Next)
    switch (++i) {
      case 3: crp->Name = "Precision"; break;
      case 4: crp->Name = "Scale";     break;
      case 5: crp->Name = "Nullable";  break;
      } // endswitch i

  /************************************************************************/
  /*  Now get the results into blocks.                                    */
  /************************************************************************/
  try {
    for (i = 0; i < ncol; i++) {
      do {
        rc = SQLDescribeCol(hstmt, i+1, cn, cns, &nl, &type, &n, &prec, &nul); 
        } while (rc == SQL_STILL_EXECUTING);

      if (!Check(rc))
        ThrowDBX(rc, "SQLDescribeCol", hstmt);
      else
        qrp->Nblin++;

      crp = qrp->Colresp;                    // Column_Name
      crp->Kdata->SetValue((char*)cn, i);
      crp = crp->Next;                       // Data_Type
      crp->Kdata->SetValue(type, i);
      crp = crp->Next;                       // Precision (length)
      crp->Kdata->SetValue((int)n, i);
      crp = crp->Next;                       // Scale
      crp->Kdata->SetValue(prec, i);
      crp = crp->Next;                       // Nullable
      crp->Kdata->SetValue(nul, i);
      } // endfor i

  } catch(DBX *x) {
2024
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    qrp = NULL;
  } // end try/catch

  /* Cleanup */
 err:
  SQLCancel(hstmt);
  rc = SQLFreeStmt(hstmt, SQL_DROP);
  Close();

  /************************************************************************/
  /*  Return the result pointer for use by GetData routines.              */
  /************************************************************************/
  return qrp;
  } // end of GetMetaData

Alexander Barkov's avatar
Alexander Barkov committed
2040 2041 2042 2043 2044
/***********************************************************************/
/*  Get the list of Data Sources and set it in qrp.                    */
/***********************************************************************/
bool ODBConn::GetDataSources(PQRYRES qrp)
  {
2045
  bool    rv = false;
Alexander Barkov's avatar
Alexander Barkov committed
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
  UCHAR  *dsn, *des;
  UWORD   dir = SQL_FETCH_FIRST;
  SWORD   n1, n2, p1, p2;
  PCOLRES crp1 = qrp->Colresp, crp2 = qrp->Colresp->Next;
  RETCODE rc;

  n1 = crp1->Clen;
  n2 = crp2->Clen;

  try {
    rc = SQLAllocEnv(&m_henv);

    if (!Check(rc))
2059
      ThrowDBX(rc, "SQLAllocEnv"); // Fatal
Alexander Barkov's avatar
Alexander Barkov committed
2060 2061 2062 2063 2064 2065 2066 2067 2068

    for (int i = 0; i < qrp->Maxres; i++) {
      dsn = (UCHAR*)crp1->Kdata->GetValPtr(i);
      des = (UCHAR*)crp2->Kdata->GetValPtr(i);
      rc = SQLDataSources(m_henv, dir, dsn, n1, &p1, des, n2, &p2);

      if (rc == SQL_NO_DATA_FOUND)
        break;
      else if (!Check(rc))
2069
        ThrowDBX(rc, "SQLDataSources");
Alexander Barkov's avatar
Alexander Barkov committed
2070 2071 2072 2073 2074 2075

      qrp->Nblin++;
      dir = SQL_FETCH_NEXT;
      } // endfor i

  } catch(DBX *x) {
2076
    sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
2077
    rv = true;
Alexander Barkov's avatar
Alexander Barkov committed
2078 2079
  } // end try/catch

2080 2081
  Close();
  return rv;
Alexander Barkov's avatar
Alexander Barkov committed
2082 2083
  } // end of GetDataSources

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
/***********************************************************************/
/*  Get the list of Drivers and set it in qrp.                         */
/***********************************************************************/
bool ODBConn::GetDrivers(PQRYRES qrp)
  {
  int     i, n;
  bool    rv = false;
  UCHAR  *des, *att;
  UWORD   dir = SQL_FETCH_FIRST;
  SWORD   n1, n2, p1, p2;
  PCOLRES crp1 = qrp->Colresp, crp2 = qrp->Colresp->Next;
  RETCODE rc;

  n1 = crp1->Clen;
  n2 = crp2->Clen;

  try {
    rc = SQLAllocEnv(&m_henv);

    if (!Check(rc))
2104
      ThrowDBX(rc, "SQLAllocEnv"); // Fatal
2105 2106 2107 2108 2109 2110 2111 2112 2113

    for (n = 0; n < qrp->Maxres; n++) {
      des = (UCHAR*)crp1->Kdata->GetValPtr(n);
      att = (UCHAR*)crp2->Kdata->GetValPtr(n);
      rc = SQLDrivers(m_henv, dir, des, n1, &p1, att, n2, &p2);

      if (rc == SQL_NO_DATA_FOUND)
        break;
      else if (!Check(rc))
2114 2115
        ThrowDBX(rc, "SQLDrivers");

2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126

      // The attributes being separated by '\0', set them to ';'
      for (i = 0; i < p2; i++)
        if (!att[i])
          att[i] = ';';

      qrp->Nblin++;
      dir = SQL_FETCH_NEXT;
      } // endfor n

  } catch(DBX *x) {
2127
    sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
2128 2129 2130 2131 2132 2133 2134
    rv = true;
  } // end try/catch

  Close();
  return rv;
  } // end of GetDrivers

2135 2136 2137 2138 2139 2140 2141 2142
/***********************************************************************/
/*  A helper class to split an optionally qualified table name into    */
/*  components.                                                        */
/*  These formats are understood:                                      */
/*    "CatalogName.SchemaName.TableName"                               */
/*    "SchemaName.TableName"                                           */
/*    "TableName"                                                      */
/***********************************************************************/
2143 2144
class SQLQualifiedName
{
2145
  static const uint max_parts= 3;          // Catalog.Schema.Table
2146 2147
  MYSQL_LEX_STRING m_part[max_parts];
  char m_buf[512];
2148

2149 2150 2151 2152
  void lex_string_set(MYSQL_LEX_STRING *S, char *str, size_t length)
  {
    S->str= str;
    S->length= length;
2153
  } // end of lex_string_set
2154

2155 2156 2157 2158 2159
  void lex_string_shorten_down(MYSQL_LEX_STRING *S, size_t offs)
  {
    DBUG_ASSERT(offs <= S->length);
    S->str+= offs;
    S->length-= offs;
2160 2161 2162 2163 2164 2165 2166 2167
  } // end of lex_string_shorten_down

  /*********************************************************************/
  /*  Find the rightmost '.' delimiter and return the length           */
  /*  of the qualifier, including the rightmost '.' delimier.          */
  /*  For example, for the string {"a.b.c",5} it will return 4,        */
  /*  which is the length of the qualifier "a.b."                      */
  /*********************************************************************/
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
  size_t lex_string_find_qualifier(MYSQL_LEX_STRING *S)
  {
    size_t i;
    for (i= S->length; i > 0; i--)
    {
      if (S->str[i - 1] == '.')
      {
        S->str[i - 1]= '\0';
        return i;
      }
    }
    return 0;
2180 2181
  } // end of lex_string_find_qualifier

2182
public:
2183 2184 2185 2186 2187 2188
  /*********************************************************************/
  /*  Initialize to the given optionally qualified name.               */
  /*  NULL pointer in "name" is supported.                             */
  /*  name qualifier has precedence over schema.                       */
  /*********************************************************************/
  SQLQualifiedName(CATPARM *cap)
2189
  {
2190 2191 2192 2193 2194 2195
    const char *name = (const char *)cap->Tab;
    char       *db = (char *)cap->DB;
    size_t      len, i;

    // Initialize the parts
    for (i = 0 ; i < max_parts; i++)
2196
      lex_string_set(&m_part[i], NULL, 0);
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219

    if (name) {
      // Initialize the first (rightmost) part
      lex_string_set(&m_part[0], m_buf,
                     strmake(m_buf, name, sizeof(m_buf) - 1) - m_buf);
  
      // Initialize the other parts, if exist. 
      for (i= 1; i < max_parts; i++) {
        if (!(len= lex_string_find_qualifier(&m_part[i - 1])))
          break;
  
        lex_string_set(&m_part[i], m_part[i - 1].str, len - 1);
        lex_string_shorten_down(&m_part[i - 1], len);
        } // endfor i

      } // endif name

    // If it was not specified, set schema as the passed db name
    if (db && !m_part[1].length)
      lex_string_set(&m_part[1], db, strlen(db));

  } // end of SQLQualifiedName

2220 2221 2222 2223
  SQLCHAR *ptr(uint i)
  {
    DBUG_ASSERT(i < max_parts);
    return (SQLCHAR *) (m_part[i].length ? m_part[i].str : NULL);
2224 2225
  } // end of ptr

2226 2227 2228 2229
  size_t length(uint i)
  {
    DBUG_ASSERT(i < max_parts);
    return m_part[i].length;
2230 2231 2232
  } // end of length

}; // end of class SQLQualifiedName
2233

Alexander Barkov's avatar
Alexander Barkov committed
2234 2235 2236 2237 2238 2239 2240 2241 2242
/***********************************************************************/
/*  Allocate recset and call SQLTables, SQLColumns or SQLPrimaryKeys.  */
/***********************************************************************/
int ODBConn::GetCatInfo(CATPARM *cap)
  {
  PGLOBAL& g = m_G;
  void    *buffer;
  int      i, irc;
  bool     b;
2243
  PCSZ     fnc = "Unknown";
Alexander Barkov's avatar
Alexander Barkov committed
2244 2245
  UWORD    n;
  SWORD    ncol, len, tp;
2246
  SQLULEN  crow = 0;
2247
  PQRYRES  qrp = cap->Qrp;
Alexander Barkov's avatar
Alexander Barkov committed
2248
  PCOLRES  crp;
2249
  RETCODE  rc = 0;
Alexander Barkov's avatar
Alexander Barkov committed
2250
  HSTMT    hstmt = NULL;
2251
  SQLLEN  *vl, *vlen = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
2252
  PVAL    *pval = NULL;
2253
  char*   *pbuf = NULL;
Alexander Barkov's avatar
Alexander Barkov committed
2254 2255 2256 2257 2258 2259 2260 2261

  try {
    b = false;

    if (!m_hstmt) {
      rc = SQLAllocStmt(m_hdbc, &hstmt);

      if (!Check(rc))
2262
        ThrowDBX(SQL_INVALID_HANDLE, "SQLAllocStmt");
Alexander Barkov's avatar
Alexander Barkov committed
2263 2264 2265 2266 2267 2268

    } else
      ThrowDBX(MSG(SEQUENCE_ERROR));

    b = true;

2269 2270
    // Currently m_Catver should be always 0 here
    assert(!m_Catver);     // This may be temporary
Alexander Barkov's avatar
Alexander Barkov committed
2271

2272 2273 2274
    if (qrp->Maxres > 0)
      m_RowsetSize = 1;
    else
Alexander Barkov's avatar
Alexander Barkov committed
2275 2276
      ThrowDBX("0-sized result");

2277 2278
    SQLQualifiedName name(cap);

Alexander Barkov's avatar
Alexander Barkov committed
2279 2280 2281
    // Now do call the proper ODBC API
    switch (cap->Id) {
      case CAT_TAB:
2282
        fnc = "SQLTables";
2283 2284 2285
        rc = SQLTables(hstmt, name.ptr(2), name.length(2),
                              name.ptr(1), name.length(1),
                              name.ptr(0), name.length(0),
2286 2287
					                    (SQLCHAR *)cap->Pat, 
					                    cap->Pat ? SQL_NTS : 0);
Alexander Barkov's avatar
Alexander Barkov committed
2288 2289
        break;
      case CAT_COL:
2290
        fnc = "SQLColumns";
2291 2292 2293
        rc = SQLColumns(hstmt, name.ptr(2), name.length(2),
                               name.ptr(1), name.length(1),
                               name.ptr(0), name.length(0),
2294 2295
															 (SQLCHAR *)cap->Pat, 
					                     cap->Pat ? SQL_NTS : 0);
Alexander Barkov's avatar
Alexander Barkov committed
2296 2297
        break;
      case CAT_KEY:
2298
        fnc = "SQLPrimaryKeys";
2299 2300 2301
        rc = SQLPrimaryKeys(hstmt, name.ptr(2), name.length(2),
                                   name.ptr(1), name.length(1),
                                   name.ptr(0), name.length(0));
Alexander Barkov's avatar
Alexander Barkov committed
2302 2303
        break;
      case CAT_STAT:
2304
        fnc = "SQLStatistics";
2305 2306 2307
        rc = SQLStatistics(hstmt, name.ptr(2), name.length(2),
                                  name.ptr(1), name.length(1),
                                  name.ptr(0), name.length(0),
Alexander Barkov's avatar
Alexander Barkov committed
2308 2309 2310 2311
                                  cap->Unique, cap->Accuracy);
        break;
      case CAT_SPC:
        ThrowDBX("SQLSpecialColumns not available yet");
2312 2313
      default:
        ThrowDBX("Invalid SQL function id");
Alexander Barkov's avatar
Alexander Barkov committed
2314 2315 2316
      } // endswitch infotype

    if (!Check(rc))
2317
      ThrowDBX(rc, fnc, hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
2318 2319 2320

    rc = SQLNumResultCols(hstmt, &ncol);

2321
    // n because we no more ignore the first column
2322
    if ((n = (UWORD)qrp->Nbcol) > (UWORD)ncol)
Alexander Barkov's avatar
Alexander Barkov committed
2323 2324
      ThrowDBX(MSG(COL_NUM_MISM));

2325 2326 2327
    // Unconditional to handle STRBLK's
    pval = (PVAL *)PlugSubAlloc(g, NULL, n * sizeof(PVAL));
    vlen = (SQLLEN *)PlugSubAlloc(g, NULL, n * sizeof(SQLLEN));
2328
    pbuf = (char**)PlugSubAlloc(g, NULL, n * sizeof(char*));
Alexander Barkov's avatar
Alexander Barkov committed
2329 2330

    // Now bind the column buffers
2331 2332 2333 2334
    for (n = 0, crp = qrp->Colresp; crp; crp = crp->Next) {
      if ((tp = GetSQLCType(crp->Type)) == SQL_TYPE_NULL) {
        sprintf(g->Message, MSG(INV_COLUMN_TYPE), crp->Type, crp->Name);
        ThrowDBX(g->Message);
Alexander Barkov's avatar
Alexander Barkov committed
2335 2336
        } // endif tp

2337 2338 2339 2340 2341
      if (!(len = GetTypeSize(crp->Type, crp->Length))) {
        len = 255;           // for STRBLK's
        ((STRBLK*)crp->Kdata)->SetSorted(true);
        } // endif len

2342
      pval[n] = AllocateValue(g, crp->Type, len);
2343
			pval[n]->SetNullable(true);
2344 2345 2346 2347 2348 2349 2350

      if (crp->Type == TYPE_STRING) {
        pbuf[n] = (char*)PlugSubAlloc(g, NULL, len);
        buffer = pbuf[n];
      } else
        buffer = pval[n]->GetTo_Val();

2351 2352
      vl = vlen + n;

2353 2354
      // n + 1 because column numbers begin with 1
      rc = SQLBindCol(hstmt, n + 1, tp, buffer, len, vl);
Alexander Barkov's avatar
Alexander Barkov committed
2355 2356

      if (!Check(rc))
2357
        ThrowDBX(rc, "SQLBindCol", hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
2358 2359 2360 2361

      n++;
      } // endfor crp

2362 2363
    fnc = "SQLFetch";

Alexander Barkov's avatar
Alexander Barkov committed
2364
    // Now fetch the result
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
    // Extended fetch cannot be used because of STRBLK's
    for (i = 0; i < qrp->Maxres; i++) {
      if ((rc = SQLFetch(hstmt)) == SQL_NO_DATA_FOUND)
        break;
      else if (rc != SQL_SUCCESS) {
        if (trace > 1 || (trace && rc != SQL_SUCCESS_WITH_INFO)) {
          UCHAR   msg[SQL_MAX_MESSAGE_LENGTH + 1];
          UCHAR   state[SQL_SQLSTATE_SIZE + 1];
          RETCODE erc;
          SDWORD  native;

          htrc("SQLFetch: row %d rc=%d\n", i+1, rc);
          erc = SQLError(m_henv, m_hdbc, hstmt, state, &native, msg,
                         SQL_MAX_MESSAGE_LENGTH - 1, &len);

          if (rc != SQL_INVALID_HANDLE)
            // Skip non-errors
            for (n = 0; n < MAX_NUM_OF_MSG
                 && (erc == SQL_SUCCESS || erc == SQL_SUCCESS_WITH_INFO)
                 && strcmp((char*)state, "00000"); n++) {
              htrc("%s: %s, Native=%d\n", state, msg, native);
              erc = SQLError(m_henv, m_hdbc, hstmt, state, &native,
                             msg, SQL_MAX_MESSAGE_LENGTH - 1, &len);
              } // endfor n

          } // endif trace

        if (rc != SQL_SUCCESS_WITH_INFO)
          qrp->BadLines++;

        } // endif rc

      for (n = 0, crp = qrp->Colresp; crp; n++, crp = crp->Next) {
2398 2399 2400
				if (vlen[n] == SQL_NO_TOTAL)
					ThrowDBX("Unexpected SQL_NO_TOTAL returned from SQLFetch");
				else if (vlen[n] == SQL_NULL_DATA)
2401
          pval[n]->SetNull(true);
2402
        else if (crp->Type == TYPE_STRING/* && vlen[n] != SQL_NULL_DATA*/)
2403 2404 2405 2406
          pval[n]->SetValue_char(pbuf[n], vlen[n]);
        else
          pval[n]->SetNull(false);

2407 2408 2409
        crp->Kdata->SetValue(pval[n], i);
        cap->Vlen[n][i] = vlen[n];
        } // endfor crp
Alexander Barkov's avatar
Alexander Barkov committed
2410

2411
      } // endfor i
Alexander Barkov's avatar
Alexander Barkov committed
2412

2413
#if 0
2414 2415
    if ((crow = i) && (rc == SQL_NO_DATA || rc == SQL_SUCCESS_WITH_INFO))
      rc = SQL_SUCCESS;
Alexander Barkov's avatar
Alexander Barkov committed
2416 2417 2418

    if (rc == SQL_NO_DATA_FOUND) {
      if (cap->Pat)
2419
        sprintf(g->Message, MSG(NO_TABCOL_DATA), cap->Tab, cap->Pat);
Alexander Barkov's avatar
Alexander Barkov committed
2420
      else
2421 2422 2423 2424 2425 2426
        sprintf(g->Message, MSG(NO_TAB_DATA), cap->Tab);

      ThrowDBX(g->Message);
    } else if (rc == SQL_SUCCESS) {
      if ((rc = SQLFetch(hstmt)) != SQL_NO_DATA_FOUND)
        qrp->Truncated = true; 
Alexander Barkov's avatar
Alexander Barkov committed
2427

2428
    } else
2429
      ThrowDBX(rc, fnc, hstmt);
2430 2431 2432 2433 2434 2435 2436 2437 2438
#endif // 0

    if (!rc || rc == SQL_NO_DATA || rc == SQL_SUCCESS_WITH_INFO) {
      if ((rc = SQLFetch(hstmt)) != SQL_NO_DATA_FOUND)
        qrp->Truncated = true; 

      crow = i;
    } else
      ThrowDBX(rc, fnc, hstmt);
Alexander Barkov's avatar
Alexander Barkov committed
2439 2440 2441

    irc = (int)crow;
  } catch(DBX *x) {
2442 2443 2444 2445
    if (trace)
      for (int i = 0; i < MAX_NUM_OF_MSG && x->m_ErrMsg[i]; i++)
        htrc(x->m_ErrMsg[i]);

2446
    sprintf(g->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
Alexander Barkov's avatar
Alexander Barkov committed
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
    irc = -1;
  } // end try/catch

  if (b)
    SQLCancel(hstmt);

  // All this (hstmt vs> m_hstmt) to be revisited
  if (hstmt)
    rc = SQLFreeStmt(hstmt, SQL_DROP);

  return irc;
  } // end of GetCatInfo

2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
/***********************************************************************/
/*  Allocate a CONNECT result structure from the ODBC result.          */
/***********************************************************************/
PQRYRES ODBConn::AllocateResult(PGLOBAL g)
  {
  bool         uns;
  PODBCCOL     colp;
  PCOLRES     *pcrp, crp;
  PQRYRES      qrp;

  if (!m_Rows) {
    strcpy(g->Message, "Void result");
    return NULL;
    } // endif m_Res

  /*********************************************************************/
  /*  Allocate the result storage for future retrieval.                */
  /*********************************************************************/
  qrp = (PQRYRES)PlugSubAlloc(g, NULL, sizeof(QRYRES));
  pcrp = &qrp->Colresp;
  qrp->Continued = FALSE;
  qrp->Truncated = FALSE;
  qrp->Info = FALSE;
  qrp->Suball = TRUE;
  qrp->BadLines = 0;
  qrp->Maxsize = m_Rows;
  qrp->Maxres = m_Rows;
  qrp->Nbcol = 0;
  qrp->Nblin = 0;
  qrp->Cursor = 0;

2491 2492
  for (colp = (PODBCCOL)m_Tdb->Columns; colp; 
       colp = (PODBCCOL)colp->GetNext())
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    if (!colp->IsSpecial()) {
      *pcrp = (PCOLRES)PlugSubAlloc(g, NULL, sizeof(COLRES));
      crp = *pcrp;
      pcrp = &crp->Next;
      memset(crp, 0, sizeof(COLRES));
      crp->Ncol = ++qrp->Nbcol;
      crp->Name = colp->GetName();
      crp->Type = colp->GetResultType();
      crp->Prec = colp->GetScale();
      crp->Length = colp->GetLength();
      crp->Clen = colp->GetBuflen();
      uns = colp->IsUnsigned();

      if (!(crp->Kdata = AllocValBlock(g, NULL, crp->Type, m_Rows,
                                     crp->Clen, 0, FALSE, TRUE, uns))) {
        sprintf(g->Message, MSG(INV_RESULT_TYPE),
                          GetFormatType(crp->Type));
        return NULL;
        } // endif Kdata

      if (!colp->IsNullable())
        crp->Nulls = NULL;
      else {
        crp->Nulls = (char*)PlugSubAlloc(g, NULL, m_Rows);
        memset(crp->Nulls, ' ', m_Rows);
      } // endelse Nullable

      colp->SetCrp(crp);
      } // endif colp

  *pcrp = NULL;
//qrp->Nblin = n;
  return qrp;
  } // end of AllocateResult

2528 2529 2530
/***********************************************************************/
/*  Restart from beginning of result set                               */
/***********************************************************************/
2531
int ODBConn::Rewind(char *sql, ODBCCOL *tocols)
2532
  {
2533
  int rc, rbuf = -1;
2534 2535

  if (!m_hstmt)
2536 2537 2538 2539
    rbuf = -1;
  else if (m_Full)
    rbuf = m_Rows;           // No need to "rewind"
  else if (m_Scrollable) {
2540 2541
    SQLULEN  crow;

2542
    try {
2543
      rc = SQLExtendedFetch(m_hstmt, SQL_FETCH_FIRST, 1, &crow, NULL);
2544

2545 2546
      if (!Check(rc))
        ThrowDBX(rc, "SQLExtendedFetch", m_hstmt);
2547

2548
      rbuf = (int)crow;
2549
    } catch(DBX *x) {
2550
      sprintf(m_G->Message, "%s: %s", x->m_Msg, x->GetErrorMessage(0));
2551
      rbuf = -1;
2552 2553
    } // end try/catch

2554 2555
  } else if (ExecDirectSQL(sql, tocols) >= 0)
    rbuf = 0;
2556

2557
  return rbuf;
2558 2559
  } // end of Rewind

Alexander Barkov's avatar
Alexander Barkov committed
2560 2561 2562 2563 2564
/***********************************************************************/
/*  Disconnect connection                                              */
/***********************************************************************/
void ODBConn::Close()
  {
2565
  RETCODE rc;
Alexander Barkov's avatar
Alexander Barkov committed
2566 2567 2568

  if (m_hstmt) {
    // Is required for multiple tables
2569
    rc = SQLFreeStmt(m_hstmt, SQL_DROP);
Alexander Barkov's avatar
Alexander Barkov committed
2570 2571
    m_hstmt = NULL;
    } // endif m_hstmt
2572
                                       
Alexander Barkov's avatar
Alexander Barkov committed
2573
  if (m_hdbc != SQL_NULL_HDBC) {
2574 2575 2576 2577 2578
    if (m_Transact) {
      rc = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_COMMIT);
      m_Transact = false;
      } // endif m_Transact

2579
    rc = SQLDisconnect(m_hdbc);
Alexander Barkov's avatar
Alexander Barkov committed
2580

2581 2582
    if (trace && rc != SQL_SUCCESS)
      htrc("Error: SQLDisconnect rc=%d\n", rc);
Alexander Barkov's avatar
Alexander Barkov committed
2583

2584
    rc = SQLFreeConnect(m_hdbc);
2585

2586 2587
    if (trace && rc != SQL_SUCCESS)
      htrc("Error: SQLFreeConnect rc=%d\n", rc);
2588

2589 2590
    m_hdbc = SQL_NULL_HDBC;
    } // endif m_hdbc
Alexander Barkov's avatar
Alexander Barkov committed
2591 2592

  if (m_henv != SQL_NULL_HENV) {
2593
    rc = SQLFreeEnv(m_henv);
2594

2595 2596 2597 2598
    if (trace && rc != SQL_SUCCESS)   // Nothing we can do
      htrc("Error: SQLFreeEnv failure ignored in Close\n");
          
    m_henv = SQL_NULL_HENV;
2599
    } // endif m_henv
Alexander Barkov's avatar
Alexander Barkov committed
2600 2601

  } // end of Close