convert.c 58.6 KB
Newer Older
1
/*-------
2
 * Module:				 convert.c
3
 *
B
Bruce Momjian 已提交
4 5 6 7 8 9
 * Description:    This module contains routines related to
 *				   converting parameters and columns into requested data types.
 *				   Parameters are converted from their SQL_C data types into
 *				   the appropriate postgres type.  Columns are converted from
 *				   their postgres type (SQL type) into the appropriate SQL_C
 *				   data type.
10
 *
B
Bruce Momjian 已提交
11
 * Classes:		   n/a
12 13 14
 *
 * API functions:  none
 *
B
Bruce Momjian 已提交
15
 * Comments:	   See "notice.txt" for copyright and license information.
16
 *-------
17
 */
H
Hiroshi Inoue 已提交
18
/* Multibyte support  Eiji Tokuya	2001-03-15	*/
19

20 21
#include "convert.h"

22 23
#include <stdio.h>
#include <string.h>
24
#include <ctype.h>
B
Byron Nikolaidis 已提交
25

H
Hiroshi Inoue 已提交
26 27 28 29
#ifdef MULTIBYTE
#include "multibyte.h"
#endif

30
#include <time.h>
31
#include <math.h>
32
#include <stdlib.h>
33
#include "statement.h"
B
Byron Nikolaidis 已提交
34
#include "qresult.h"
35 36
#include "bind.h"
#include "pgtypes.h"
37 38
#include "lobj.h"
#include "connection.h"
39
#include "pgapifunc.h"
40

41
#ifdef	__CYGWIN__
42
#define TIMEZONE_GLOBAL _timezone
43
#elif	defined(WIN32) || defined(HAVE_INT_TIMEZONE)
44
#define TIMEZONE_GLOBAL timezone
45
#endif
46

47 48 49 50
/*
 *	How to map ODBC scalar functions {fn func(args)} to Postgres.
 *	This is just a simple substitution.  List augmented from:
 *	http://www.merant.com/datadirect/download/docs/odbc16/Odbcref/rappc.htm
51
 *	- thomas 2000-04-03
52
 */
B
Bruce Momjian 已提交
53 54 55 56
char	   *mapFuncs[][2] = {
/*	{ "ASCII",		 "ascii"	  }, */
	{"CHAR", "chr"},
	{"CONCAT", "textcat"},
B
Bruce Momjian 已提交
57
/*	{ "DIFFERENCE",  "difference" }, */
B
Bruce Momjian 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
/*	{ "INSERT",		 "insert"	  }, */
	{"LCASE", "lower"},
	{"LEFT", "ltrunc"},
	{"LOCATE", "strpos"},
	{"LENGTH", "char_length"},
/*	{ "LTRIM",		 "ltrim"	  }, */
	{"RIGHT", "rtrunc"},
/*	{ "REPEAT",		 "repeat"	  }, */
/*	{ "REPLACE",	 "replace"	  }, */
/*	{ "RTRIM",		 "rtrim"	  }, */
/*	{ "SOUNDEX",	 "soundex"	  }, */
	{"SUBSTRING", "substr"},
	{"UCASE", "upper"},

/*	{ "ABS",		 "abs"		  }, */
/*	{ "ACOS",		 "acos"		  }, */
/*	{ "ASIN",		 "asin"		  }, */
/*	{ "ATAN",		 "atan"		  }, */
/*	{ "ATAN2",		 "atan2"	  }, */
	{"CEILING", "ceil"},
/*	{ "COS",		 "cos"		  }, */
/*	{ "COT",		 "cot"		  }, */
/*	{ "DEGREES",	 "degrees"	  }, */
/*	{ "EXP",		 "exp"		  }, */
/*	{ "FLOOR",		 "floor"	  }, */
	{"LOG", "ln"},
	{"LOG10", "log"},
/*	{ "MOD",		 "mod"		  }, */
/*	{ "PI",			 "pi"		  }, */
	{"POWER", "pow"},
/*	{ "RADIANS",	 "radians"	  }, */
	{"RAND", "random"},
/*	{ "ROUND",		 "round"	  }, */
/*	{ "SIGN",		 "sign"		  }, */
/*	{ "SIN",		 "sin"		  }, */
/*	{ "SQRT",		 "sqrt"		  }, */
/*	{ "TAN",		 "tan"		  }, */
	{"TRUNCATE", "trunc"},

97 98 99 100 101
	{"CURRENT_DATE", "curdate"},
	{"CURRENT_TIME", "curtime"},
	{"CURRENT_TIMESTAMP", "odbc_timestamp"},
	{"CURRENT_USER", "odbc_current_user"},
	{"SESSION_USER", "odbc_session_user"},
B
Bruce Momjian 已提交
102 103 104
/*	{ "CURDATE",	 "curdate"	  }, */
/*	{ "CURTIME",	 "curtime"	  }, */
/*	{ "DAYNAME",	 "dayname"	  }, */
B
Bruce Momjian 已提交
105
/*	{ "DAYOFMONTH",  "dayofmonth" }, */
B
Bruce Momjian 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
/*	{ "DAYOFWEEK",	 "dayofweek"  }, */
/*	{ "DAYOFYEAR",	 "dayofyear"  }, */
/*	{ "HOUR",		 "hour"		  }, */
/*	{ "MINUTE",		 "minute"	  }, */
/*	{ "MONTH",		 "month"	  }, */
/*	{ "MONTHNAME",	 "monthname"  }, */
/*	{ "NOW",		 "now"		  }, */
/*	{ "QUARTER",	 "quarter"	  }, */
/*	{ "SECOND",		 "second"	  }, */
/*	{ "WEEK",		 "week"		  }, */
/*	{ "YEAR",		 "year"		  }, */

/*	{ "DATABASE",	 "database"   }, */
	{"IFNULL", "coalesce"},
	{"USER", "odbc_user"},
	{0, 0}
122 123
};

124
static char *mapFunction(const char *func);
125 126
static unsigned int conv_from_octal(const unsigned char *s);
static unsigned int conv_from_hex(const unsigned char *s);
127
static char *conv_to_octal(unsigned char val);
128

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
/*---------
 *			A Guide for date/time/timestamp conversions
 *
 *			field_type		fCType				Output
 *			----------		------				----------
 *			PG_TYPE_DATE	SQL_C_DEFAULT		SQL_C_DATE
 *			PG_TYPE_DATE	SQL_C_DATE			SQL_C_DATE
 *			PG_TYPE_DATE	SQL_C_TIMESTAMP		SQL_C_TIMESTAMP		(time = 0 (midnight))
 *			PG_TYPE_TIME	SQL_C_DEFAULT		SQL_C_TIME
 *			PG_TYPE_TIME	SQL_C_TIME			SQL_C_TIME
 *			PG_TYPE_TIME	SQL_C_TIMESTAMP		SQL_C_TIMESTAMP		(date = current date)
 *			PG_TYPE_ABSTIME SQL_C_DEFAULT		SQL_C_TIMESTAMP
 *			PG_TYPE_ABSTIME SQL_C_DATE			SQL_C_DATE			(time is truncated)
 *			PG_TYPE_ABSTIME SQL_C_TIME			SQL_C_TIME			(date is truncated)
 *			PG_TYPE_ABSTIME SQL_C_TIMESTAMP		SQL_C_TIMESTAMP
 *---------
 */
146 147 148



149
/*
150 151 152 153
 *	TIMESTAMP <-----> SIMPLE_TIME
 *		precision support since 7.2.
 *		time zone support is unavailable(the stuff is unreliable)
 */
154 155
static BOOL
timestamp2stime(const char *str, SIMPLE_TIME *st, BOOL *bZone, int *zone)
156
{
157 158 159 160
	char		rest[64],
			   *ptr;
	int			scnt,
				i;
161
	long		timediff;
162
	BOOL		withZone = *bZone;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

	*bZone = FALSE;
	*zone = 0;
	st->fr = 0;
	if ((scnt = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d%s", &st->y, &st->m, &st->d, &st->hh, &st->mm, &st->ss, rest)) < 6)
		return FALSE;
	else if (scnt == 6)
		return TRUE;
	switch (rest[0])
	{
		case '+':
			*bZone = TRUE;
			*zone = atoi(&rest[1]);
			break;
		case '-':
			*bZone = TRUE;
			*zone = -atoi(&rest[1]);
			break;
		case '.':
			if ((ptr = strchr(rest, '+')) != NULL)
			{
				*bZone = TRUE;
				*zone = atoi(&ptr[1]);
				*ptr = '\0';
			}
			else if ((ptr = strchr(rest, '-')) != NULL)
			{
				*bZone = TRUE;
				*zone = -atoi(&ptr[1]);
				*ptr = '\0';
			}
			for (i = 1; i < 10; i++)
			{
196
				if (!isdigit((unsigned char) rest[i]))
197 198 199 200 201 202 203 204
					break;
			}
			for (; i < 10; i++)
				rest[i] = '0';
			rest[i] = '\0';
			st->fr = atoi(&rest[1]);
			break;
		default:
205
			return TRUE;
206 207 208 209 210 211 212 213 214 215
	}
	if (!withZone || !*bZone || st->y < 1970)
		return TRUE;
#if defined(WIN32) || defined(HAVE_INT_TIMEZONE)
	if (!tzname[0] || !tzname[0][0])
	{
		*bZone = FALSE;
		return TRUE;
	}
	timediff = TIMEZONE_GLOBAL + (*zone) * 3600;
216
	if (!daylight && timediff == 0)		/* the same timezone */
217 218 219
		return TRUE;
	else
	{
220 221
		struct tm	tm,
				   *tm2;
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
		time_t		time0;

		*bZone = FALSE;
		tm.tm_year = st->y - 1900;
		tm.tm_mon = st->m - 1;
		tm.tm_mday = st->d;
		tm.tm_hour = st->hh;
		tm.tm_min = st->mm;
		tm.tm_sec = st->ss;
		tm.tm_isdst = -1;
		time0 = mktime(&tm);
		if (time0 < 0)
			return TRUE;
		if (tm.tm_isdst > 0)
			timediff -= 3600;
237
		if (timediff == 0)		/* the same time zone */
238 239 240 241 242 243 244
			return TRUE;
		time0 -= timediff;
		if (time0 >= 0 && (tm2 = localtime(&time0)) != NULL)
		{
			st->y = tm2->tm_year + 1900;
			st->m = tm2->tm_mon + 1;
			st->d = tm2->tm_mday;
245 246 247
			st->hh = tm2->tm_hour;
			st->mm = tm2->tm_min;
			st->ss = tm2->tm_sec;
248 249 250
			*bZone = TRUE;
		}
	}
251 252
#endif   /* WIN32 */
	return TRUE;
253 254
}

255 256
static BOOL
stime2timestamp(const SIMPLE_TIME *st, char *str, BOOL bZone, BOOL precision)
257
{
258 259 260
	char		precstr[16],
				zonestr[16];
	int			i;
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

	precstr[0] = '\0';
	if (precision && st->fr)
	{
		sprintf(precstr, ".%09d", st->fr);
		for (i = 9; i > 0; i--)
		{
			if (precstr[i] != '0')
				break;
			precstr[i] = '\0';
		}
	}
	zonestr[0] = '\0';
#if defined(WIN32) || defined(HAVE_INT_TIMEZONE)
	if (bZone && tzname[0] && tzname[0][0] && st->y >= 1970)
	{
277
		long		zoneint;
278 279 280 281
		struct tm	tm;
		time_t		time0;

		zoneint = TIMEZONE_GLOBAL;
282 283
		if (daylight && st->y >= 1900)
		{
284 285 286 287 288 289 290 291 292 293 294 295
			tm.tm_year = st->y - 1900;
			tm.tm_mon = st->m - 1;
			tm.tm_mday = st->d;
			tm.tm_hour = st->hh;
			tm.tm_min = st->mm;
			tm.tm_sec = st->ss;
			tm.tm_isdst = -1;
			time0 = mktime(&tm);
			if (time0 >= 0 && tm.tm_isdst > 0)
				zoneint -= 3600;
		}
		if (zoneint > 0)
296
			sprintf(zonestr, "-%02d", (int) zoneint / 3600);
297
		else
298
			sprintf(zonestr, "+%02d", -(int) zoneint / 3600);
299
	}
300
#endif   /* WIN32 */
301
	sprintf(str, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s", st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr);
302
	return TRUE;
303 304
}

305 306
/*	This is called by SQLFetch() */
int
307
copy_and_convert_field_bindinfo(StatementClass *stmt, Int4 field_type, void *value, int col)
308
{
B
Bruce Momjian 已提交
309
	BindInfoClass *bic = &(stmt->bindings[col]);
310

B
Bruce Momjian 已提交
311 312
	return copy_and_convert_field(stmt, field_type, value, (Int2) bic->returntype, (PTR) bic->buffer,
							 (SDWORD) bic->buflen, (SDWORD *) bic->used);
313 314
}

315

316 317
/*	This is called by SQLGetData() */
int
318 319
copy_and_convert_field(StatementClass *stmt, Int4 field_type, void *value, Int2 fCType,
					   PTR rgbValue, SDWORD cbValueMax, SDWORD *pcbValue)
320
{
B
Bruce Momjian 已提交
321 322
	Int4		len = 0,
				copy_len = 0;
323
	SIMPLE_TIME st;
B
Bruce Momjian 已提交
324 325 326 327
	time_t		t = time(NULL);
	struct tm  *tim;
	int			pcbValueOffset,
				rgbValueOffset;
328
	char	   *rgbValueBindRow;
329
	const char *ptr;
B
Bruce Momjian 已提交
330 331 332
	int			bind_row = stmt->bind_row;
	int			bind_size = stmt->options.bind_size;
	int			result = COPY_OK;
333
	BOOL		changed;
334
	const char *neut_str = value;
335 336
	char		midtemp[2][32];
	int			mtemp_cnt = 0;
337 338
	static BindInfoClass sbic;
	BindInfoClass *pbic;
339

340 341 342 343
	if (stmt->current_col >= 0)
	{
		pbic = &stmt->bindings[stmt->current_col];
		if (pbic->data_left == -2)
344 345
			pbic->data_left = (cbValueMax > 0) ? 0 : -1;		/* This seems to be *
																 * needed for ADO ? */
346 347 348 349 350 351 352 353
		if (pbic->data_left == 0)
		{
			if (pbic->ttlbuf != NULL)
			{
				free(pbic->ttlbuf);
				pbic->ttlbuf = NULL;
				pbic->ttlbuflen = 0;
			}
354 355
			pbic->data_left = -2;		/* needed by ADO ? */
			return COPY_NO_DATA_FOUND;
356 357
		}
	}
358 359 360 361 362
	/*---------
	 *	rgbValueOffset is *ONLY* for character and binary data.
	 *	pcbValueOffset is for computing any pcbValue location
	 *---------
	 */
363

B
Bruce Momjian 已提交
364
	if (bind_size > 0)
365
		pcbValueOffset = rgbValueOffset = (bind_size * bind_row);
B
Bruce Momjian 已提交
366 367
	else
	{
368 369
		pcbValueOffset = bind_row * sizeof(SDWORD);
		rgbValueOffset = bind_row * cbValueMax;
370

371
	}
372 373 374

	memset(&st, 0, sizeof(SIMPLE_TIME));

B
Bruce Momjian 已提交
375
	/* Initialize current date */
376 377 378 379 380
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;

B
Bruce Momjian 已提交
381
	mylog("copy_and_convert: field_type = %d, fctype = %d, value = '%s', cbValueMax=%d\n", field_type, fCType, (value == NULL) ? "<NULL>" : value, cbValueMax);
382

B
Bruce Momjian 已提交
383 384
	if (!value)
	{
385
		/*
386 387
		 * handle a null just by returning SQL_NULL_DATA in pcbValue, and
		 * doing nothing to the buffer.
388
		 */
B
Bruce Momjian 已提交
389
		if (pcbValue)
390
			*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = SQL_NULL_DATA;
B
Byron Nikolaidis 已提交
391 392 393
		return COPY_OK;
	}

B
Bruce Momjian 已提交
394 395 396 397 398 399 400 401 402
	if (stmt->hdbc->DataSourceToDriver != NULL)
	{
		int			length = strlen(value);

		stmt->hdbc->DataSourceToDriver(stmt->hdbc->translation_option,
									   SQL_CHAR,
									   value, length,
									   value, length, NULL,
									   NULL, 0, NULL);
B
Byron Nikolaidis 已提交
403 404
	}

405
	/*
406
	 * First convert any specific postgres types into more useable data.
407
	 *
408 409
	 * NOTE: Conversions from PG char/varchar of a date/time/timestamp value
	 * to SQL_C_DATE,SQL_C_TIME, SQL_C_TIMESTAMP not supported
410
	 */
B
Bruce Momjian 已提交
411 412
	switch (field_type)
	{
413 414 415 416
			/*
			 * $$$ need to add parsing for date/time/timestamp strings in
			 * PG_TYPE_CHAR,VARCHAR $$$
			 */
B
Bruce Momjian 已提交
417 418 419
		case PG_TYPE_DATE:
			sscanf(value, "%4d-%2d-%2d", &st.y, &st.m, &st.d);
			break;
420

B
Bruce Momjian 已提交
421 422 423
		case PG_TYPE_TIME:
			sscanf(value, "%2d:%2d:%2d", &st.hh, &st.mm, &st.ss);
			break;
424

B
Bruce Momjian 已提交
425 426 427
		case PG_TYPE_ABSTIME:
		case PG_TYPE_DATETIME:
		case PG_TYPE_TIMESTAMP:
428
			st.fr = 0;
B
Bruce Momjian 已提交
429
			if (strnicmp(value, "invalid", 7) != 0)
430
			{
431 432 433 434 435 436 437 438
				BOOL		bZone = (field_type != PG_TYPE_TIMESTAMP_NO_TMZONE && PG_VERSION_GE(SC_get_conn(stmt), 7.2));
				int			zone;

				/*
				 * sscanf(value, "%4d-%2d-%2d %2d:%2d:%2d", &st.y, &st.m,
				 * &st.d, &st.hh, &st.mm, &st.ss);
				 */
				bZone = FALSE;	/* time zone stuff is unreliable */
439 440
				timestamp2stime(value, &st, &bZone, &zone);
			}
B
Bruce Momjian 已提交
441
			else
442 443
			{
				/*
444 445
				 * The timestamp is invalid so set something conspicuous,
				 * like the epoch
446
				 */
B
Bruce Momjian 已提交
447 448 449 450 451 452 453 454 455 456 457 458
				t = 0;
				tim = localtime(&t);
				st.m = tim->tm_mon + 1;
				st.d = tim->tm_mday;
				st.y = tim->tm_year + 1900;
				st.hh = tim->tm_hour;
				st.mm = tim->tm_min;
				st.ss = tim->tm_sec;
			}
			break;

		case PG_TYPE_BOOL:
459
			{					/* change T/F to 1/0 */
460
				char	   *s;
B
Bruce Momjian 已提交
461

462 463
				s = midtemp[mtemp_cnt];
				strcpy(s, (char *) value);
464
				if (s[0] == 'f' || s[0] == 'F' || s[0] == 'n' || s[0] == 'N' || s[0] == '0')
465
					s[0] = '0';
B
Bruce Momjian 已提交
466
				else
467 468 469 470
					s[0] = '1';
				s[1] = '\0';
				neut_str = midtemp[mtemp_cnt];
				mtemp_cnt++;
471

B
Bruce Momjian 已提交
472 473 474
			}
			break;

475
			/* This is for internal use by SQLStatistics() */
B
Bruce Momjian 已提交
476 477 478 479
		case PG_TYPE_INT2VECTOR:
			{
				int			nval,
							i;
480
				const char *vp;
B
Bruce Momjian 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

				/* this is an array of eight integers */
				short	   *short_array = (short *) ((char *) rgbValue + rgbValueOffset);

				len = 32;
				vp = value;
				nval = 0;
				mylog("index=(");
				for (i = 0; i < 16; i++)
				{
					if (sscanf(vp, "%hd", &short_array[i]) != 1)
						break;

					mylog(" %d", short_array[i]);
					nval++;

					/* skip the current token */
					while ((*vp != '\0') && (!isspace((unsigned char) *vp)))
						vp++;
					/* and skip the space to the next token */
					while ((*vp != '\0') && (isspace((unsigned char) *vp)))
						vp++;
					if (*vp == '\0')
						break;
				}
				mylog(") nval = %d\n", nval);

				for (i = nval; i < 16; i++)
					short_array[i] = 0;
B
Byron Nikolaidis 已提交
510

511
#if 0
B
Bruce Momjian 已提交
512 513 514 515 516 517 518 519 520
				sscanf(value, "%hd %hd %hd %hd %hd %hd %hd %hd",
					   &short_array[0],
					   &short_array[1],
					   &short_array[2],
					   &short_array[3],
					   &short_array[4],
					   &short_array[5],
					   &short_array[6],
					   &short_array[7]);
521
#endif
B
Byron Nikolaidis 已提交
522

B
Bruce Momjian 已提交
523 524 525
				/* There is no corresponding fCType for this. */
				if (pcbValue)
					*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = len;
B
Byron Nikolaidis 已提交
526

B
Bruce Momjian 已提交
527 528 529
				return COPY_OK; /* dont go any further or the data will be
								 * trashed */
			}
B
Byron Nikolaidis 已提交
530

B
Bruce Momjian 已提交
531 532 533 534 535
			/*
			 * This is a large object OID, which is used to store
			 * LONGVARBINARY objects.
			 */
		case PG_TYPE_LO:
B
Byron Nikolaidis 已提交
536

B
Bruce Momjian 已提交
537
			return convert_lo(stmt, value, fCType, ((char *) rgbValue + rgbValueOffset), cbValueMax, (SDWORD *) ((char *) pcbValue + pcbValueOffset));
B
Byron Nikolaidis 已提交
538

B
Bruce Momjian 已提交
539
		default:
B
Byron Nikolaidis 已提交
540

B
Bruce Momjian 已提交
541 542 543
			if (field_type == stmt->hdbc->lobj_type)	/* hack until permanent
														 * type available */
				return convert_lo(stmt, value, fCType, ((char *) rgbValue + rgbValueOffset), cbValueMax, (SDWORD *) ((char *) pcbValue + pcbValueOffset));
B
Byron Nikolaidis 已提交
544 545
	}

B
Bruce Momjian 已提交
546 547 548
	/* Change default into something useable */
	if (fCType == SQL_C_DEFAULT)
	{
B
Byron Nikolaidis 已提交
549 550 551 552 553
		fCType = pgtype_to_ctype(stmt, field_type);

		mylog("copy_and_convert, SQL_C_DEFAULT: fCType = %d\n", fCType);
	}

554 555
	rgbValueBindRow = (char *) rgbValue + rgbValueOffset;

B
Bruce Momjian 已提交
556 557 558
	if (fCType == SQL_C_CHAR)
	{
		/* Special character formatting as required */
559

B
Bruce Momjian 已提交
560 561 562 563 564 565 566 567 568 569 570
		/*
		 * These really should return error if cbValueMax is not big
		 * enough.
		 */
		switch (field_type)
		{
			case PG_TYPE_DATE:
				len = 10;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.4d-%.2d-%.2d", st.y, st.m, st.d);
				break;
571

B
Bruce Momjian 已提交
572 573 574 575 576
			case PG_TYPE_TIME:
				len = 8;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.2d:%.2d:%.2d", st.hh, st.mm, st.ss);
				break;
577

B
Bruce Momjian 已提交
578 579 580 581 582 583 584 585
			case PG_TYPE_ABSTIME:
			case PG_TYPE_DATETIME:
			case PG_TYPE_TIMESTAMP:
				len = 19;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
							st.y, st.m, st.d, st.hh, st.mm, st.ss);
				break;
586

B
Bruce Momjian 已提交
587 588 589 590
			case PG_TYPE_BOOL:
				len = 1;
				if (cbValueMax > len)
				{
591
					strcpy(rgbValueBindRow, neut_str);
B
Bruce Momjian 已提交
592 593 594
					mylog("PG_TYPE_BOOL: rgbValueBindRow = '%s'\n", rgbValueBindRow);
				}
				break;
595

B
Bruce Momjian 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
				/*
				 * Currently, data is SILENTLY TRUNCATED for BYTEA and
				 * character data types if there is not enough room in
				 * cbValueMax because the driver can't handle multiple
				 * calls to SQLGetData for these, yet.	Most likely, the
				 * buffer passed in will be big enough to handle the
				 * maximum limit of postgres, anyway.
				 *
				 * LongVarBinary types are handled correctly above, observing
				 * truncation and all that stuff since there is
				 * essentially no limit on the large object used to store
				 * those.
				 */
			case PG_TYPE_BYTEA:/* convert binary data to hex strings
								 * (i.e, 255 = "FF") */
611
				len = convert_pgbinary_to_char(neut_str, rgbValueBindRow, cbValueMax);
B
Bruce Momjian 已提交
612 613 614

				/***** THIS IS NOT PROPERLY IMPLEMENTED *****/
				break;
615

B
Bruce Momjian 已提交
616
			default:
617 618 619 620 621 622 623 624
				if (stmt->current_col < 0)
				{
					pbic = &sbic;
					pbic->data_left = -1;
				}
				else
					pbic = &stmt->bindings[stmt->current_col];
				if (pbic->data_left < 0)
625 626
				{
					/* convert linefeeds to carriage-return/linefeed */
627
					len = convert_linefeeds(neut_str, NULL, 0, &changed);
628 629
					if (cbValueMax == 0)		/* just returns length
												 * info */
630 631 632 633
					{
						result = COPY_RESULT_TRUNCATED;
						break;
					}
634 635
					if (!pbic->ttlbuf)
						pbic->ttlbuflen = 0;
636 637
					if (changed || len >= cbValueMax)
					{
638
						if (len >= (int) pbic->ttlbuflen)
639
						{
640 641
							pbic->ttlbuf = realloc(pbic->ttlbuf, len + 1);
							pbic->ttlbuflen = len + 1;
642
						}
643 644
						convert_linefeeds(neut_str, pbic->ttlbuf, pbic->ttlbuflen, &changed);
						ptr = pbic->ttlbuf;
645 646 647
					}
					else
					{
648
						if (pbic->ttlbuf)
649
						{
650 651
							free(pbic->ttlbuf);
							pbic->ttlbuf = NULL;
652
						}
653
						ptr = neut_str;
654 655 656
					}
				}
				else
657
					ptr = pbic->ttlbuf;
B
Bruce Momjian 已提交
658 659 660 661 662

				mylog("DEFAULT: len = %d, ptr = '%s'\n", len, ptr);

				if (stmt->current_col >= 0)
				{
663
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
664
					{
665 666
						ptr += strlen(ptr) - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
667 668
					}
					else
669
						pbic->data_left = len;
670 671
				}

B
Bruce Momjian 已提交
672 673 674
				if (cbValueMax > 0)
				{
					copy_len = (len >= cbValueMax) ? cbValueMax - 1 : len;
675

B
Bruce Momjian 已提交
676
					/* Copy the data */
677 678
					memcpy(rgbValueBindRow, ptr, copy_len);
					rgbValueBindRow[copy_len] = '\0';
679

B
Bruce Momjian 已提交
680 681
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
682
						pbic->data_left -= copy_len;
683 684
				}

B
Bruce Momjian 已提交
685 686 687 688
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
689
				if (cbValueMax > 0 && len >= cbValueMax)
B
Bruce Momjian 已提交
690
					result = COPY_RESULT_TRUNCATED;
691 692
				else
				{
693
					if (pbic->ttlbuf != NULL)
694
					{
695 696
						free(pbic->ttlbuf);
						pbic->ttlbuf = NULL;
697 698
					}
				}
699 700


B
Bruce Momjian 已提交
701 702
				mylog("    SQL_C_CHAR, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow);
				break;
B
Byron Nikolaidis 已提交
703
		}
704 705


B
Bruce Momjian 已提交
706 707 708 709 710 711 712 713
	}
	else
	{
		/*
		 * for SQL_C_CHAR, it's probably ok to leave currency symbols in.
		 * But to convert to numeric types, it is necessary to get rid of
		 * those.
		 */
B
Byron Nikolaidis 已提交
714
		if (field_type == PG_TYPE_MONEY)
715 716 717 718 719 720 721 722 723
		{
			if (convert_money(neut_str, midtemp[mtemp_cnt], sizeof(midtemp[0])))
			{
				neut_str = midtemp[mtemp_cnt];
				mtemp_cnt++;
			}
			else
				return COPY_UNSUPPORTED_TYPE;
		}
B
Byron Nikolaidis 已提交
724

B
Bruce Momjian 已提交
725 726 727
		switch (fCType)
		{
			case SQL_C_DATE:
728
#if (ODBCVER >= 0x0300)
729
			case SQL_C_TYPE_DATE:		/* 91 */
730
#endif
B
Bruce Momjian 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743
				len = 6;
				{
					DATE_STRUCT *ds;

					if (bind_size > 0)
						ds = (DATE_STRUCT *) ((char *) rgbValue + (bind_row * bind_size));
					else
						ds = (DATE_STRUCT *) rgbValue + bind_row;
					ds->year = st.y;
					ds->month = st.m;
					ds->day = st.d;
				}
				break;
744

B
Bruce Momjian 已提交
745
			case SQL_C_TIME:
746
#if (ODBCVER >= 0x0300)
747
			case SQL_C_TYPE_TIME:		/* 92 */
748
#endif
B
Bruce Momjian 已提交
749 750 751 752 753 754 755 756 757 758 759 760 761
				len = 6;
				{
					TIME_STRUCT *ts;

					if (bind_size > 0)
						ts = (TIME_STRUCT *) ((char *) rgbValue + (bind_row * bind_size));
					else
						ts = (TIME_STRUCT *) rgbValue + bind_row;
					ts->hour = st.hh;
					ts->minute = st.mm;
					ts->second = st.ss;
				}
				break;
B
Byron Nikolaidis 已提交
762

B
Bruce Momjian 已提交
763
			case SQL_C_TIMESTAMP:
764
#if (ODBCVER >= 0x0300)
765
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
766
#endif
B
Bruce Momjian 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780
				len = 16;
				{
					TIMESTAMP_STRUCT *ts;

					if (bind_size > 0)
						ts = (TIMESTAMP_STRUCT *) ((char *) rgbValue + (bind_row * bind_size));
					else
						ts = (TIMESTAMP_STRUCT *) rgbValue + bind_row;
					ts->year = st.y;
					ts->month = st.m;
					ts->day = st.d;
					ts->hour = st.hh;
					ts->minute = st.mm;
					ts->second = st.ss;
781
					ts->fraction = st.fr;
B
Bruce Momjian 已提交
782 783
				}
				break;
784

B
Bruce Momjian 已提交
785 786 787
			case SQL_C_BIT:
				len = 1;
				if (bind_size > 0)
788
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
789
				else
790
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
791

B
Bruce Momjian 已提交
792
				/*
793 794 795
				 * mylog("SQL_C_BIT: bind_row = %d val = %d, cb = %d,
				 * rgb=%d\n", bind_row, atoi(neut_str), cbValueMax,
				 * *((UCHAR *)rgbValue));
B
Bruce Momjian 已提交
796 797
				 */
				break;
798

B
Bruce Momjian 已提交
799 800 801 802
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				len = 1;
				if (bind_size > 0)
803
					*(SCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
804
				else
805
					*((SCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
806
				break;
807

B
Bruce Momjian 已提交
808 809 810
			case SQL_C_UTINYINT:
				len = 1;
				if (bind_size > 0)
811
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
812
				else
813
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
814
				break;
815

B
Bruce Momjian 已提交
816 817 818
			case SQL_C_FLOAT:
				len = 4;
				if (bind_size > 0)
819
					*(SFLOAT *) ((char *) rgbValue + (bind_row * bind_size)) = (float) atof(neut_str);
B
Bruce Momjian 已提交
820
				else
821
					*((SFLOAT *) rgbValue + bind_row) = (float) atof(neut_str);
B
Bruce Momjian 已提交
822
				break;
823

B
Bruce Momjian 已提交
824 825 826
			case SQL_C_DOUBLE:
				len = 8;
				if (bind_size > 0)
827
					*(SDOUBLE *) ((char *) rgbValue + (bind_row * bind_size)) = atof(neut_str);
B
Bruce Momjian 已提交
828
				else
829
					*((SDOUBLE *) rgbValue + bind_row) = atof(neut_str);
B
Bruce Momjian 已提交
830
				break;
831

B
Bruce Momjian 已提交
832 833 834 835
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				len = 2;
				if (bind_size > 0)
836
					*(SWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
837
				else
838
					*((SWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
839
				break;
840

B
Bruce Momjian 已提交
841 842 843
			case SQL_C_USHORT:
				len = 2;
				if (bind_size > 0)
844
					*(UWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
845
				else
846
					*((UWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
847
				break;
848

B
Bruce Momjian 已提交
849 850 851 852
			case SQL_C_SLONG:
			case SQL_C_LONG:
				len = 4;
				if (bind_size > 0)
853
					*(SDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
854
				else
855
					*((SDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
856 857 858 859 860
				break;

			case SQL_C_ULONG:
				len = 4;
				if (bind_size > 0)
861
					*(UDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
862
				else
863
					*((UDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
864
				break;
865

B
Bruce Momjian 已提交
866
			case SQL_C_BINARY:
867

B
Bruce Momjian 已提交
868 869
				/* truncate if necessary */
				/* convert octal escapes to bytes */
870

871
				if (stmt->current_col < 0)
872
				{
873 874
					pbic = &sbic;
					pbic->data_left = -1;
875
				}
876 877 878 879 880 881 882 883 884 885 886
				else
					pbic = &stmt->bindings[stmt->current_col];
				if (!pbic->ttlbuf)
					pbic->ttlbuflen = 0;
				if (len = strlen(neut_str), len >= (int) pbic->ttlbuflen)
				{
					pbic->ttlbuf = realloc(pbic->ttlbuf, len + 1);
					pbic->ttlbuflen = len + 1;
				}
				len = convert_from_pgbinary(neut_str, pbic->ttlbuf, pbic->ttlbuflen);
				ptr = pbic->ttlbuf;
887

B
Bruce Momjian 已提交
888 889 890 891 892 893
				if (stmt->current_col >= 0)
				{
					/*
					 * Second (or more) call to SQLGetData so move the
					 * pointer
					 */
894
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
895
					{
896 897
						ptr += len - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
898
					}
899

B
Bruce Momjian 已提交
900 901
					/* First call to SQLGetData so initialize data_left */
					else
902
						pbic->data_left = len;
903

B
Bruce Momjian 已提交
904
				}
905

B
Bruce Momjian 已提交
906 907 908
				if (cbValueMax > 0)
				{
					copy_len = (len > cbValueMax) ? cbValueMax : len;
909

B
Bruce Momjian 已提交
910 911
					/* Copy the data */
					memcpy(rgbValueBindRow, ptr, copy_len);
912

B
Bruce Momjian 已提交
913 914
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
915
						pbic->data_left -= copy_len;
916
				}
917

B
Bruce Momjian 已提交
918 919 920 921 922 923
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
				if (len > cbValueMax)
					result = COPY_RESULT_TRUNCATED;
924

925
				if (pbic->ttlbuf)
926
				{
927 928
					free(pbic->ttlbuf);
					pbic->ttlbuf = NULL;
929
				}
B
Bruce Momjian 已提交
930 931 932 933 934
				mylog("SQL_C_BINARY: len = %d, copy_len = %d\n", len, copy_len);
				break;

			default:
				return COPY_UNSUPPORTED_TYPE;
B
Byron Nikolaidis 已提交
935 936
		}
	}
937

B
Bruce Momjian 已提交
938 939 940
	/* store the length of what was copied, if there's a place for it */
	if (pcbValue)
		*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = len;
941

942
	if (result == COPY_OK && stmt->current_col >= 0)
943
		stmt->bindings[stmt->current_col].data_left = 0;
944
	return result;
945

946 947
}

948

949 950 951 952
/*--------------------------------------------------------------------
 *	Functions/Macros to get rid of query size limit.
 *
 *	I always used the follwoing macros to convert from
953
 *	old_statement to new_statement.  Please improve it
954 955 956
 *	if you have a better way.	Hiroshi 2001/05/22
 *--------------------------------------------------------------------
 */
957 958
#define INIT_MIN_ALLOC	4096
static int
959
enlarge_statement(StatementClass *stmt, unsigned int newsize)
960
{
961
	unsigned int newalsize = INIT_MIN_ALLOC;
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
	static char *func = "enlarge_statement";

	if (stmt->stmt_size_limit > 0 && stmt->stmt_size_limit < (int) newsize)
	{
		stmt->errormsg = "Query buffer overflow in copy_statement_with_parameters";
		stmt->errornumber = STMT_EXEC_ERROR;
		SC_log_error(func, "", stmt);
		return -1;
	}
	while (newalsize <= newsize)
		newalsize *= 2;
	if (!(stmt->stmt_with_params = realloc(stmt->stmt_with_params, newalsize)))
	{
		stmt->errormsg = "Query buffer allocate error in copy_statement_with_parameters";
		stmt->errornumber = STMT_EXEC_ERROR;
		SC_log_error(func, "", stmt);
		return 0;
	}
	return newalsize;
}

/*----------
 *	Enlarge stmt_with_params if necessary.
 *----------
 */
987
#define ENLARGE_NEWSTATEMENT(newpos) \
988 989 990 991 992 993 994 995 996 997
	if (newpos >= new_stsize) \
	{ \
		if ((new_stsize = enlarge_statement(stmt, newpos)) <= 0) \
			return SQL_ERROR; \
		new_statement = stmt->stmt_with_params; \
	}
/*----------
 *	Initialize stmt_with_params, new_statement etc.
 *----------
 */
998
#define CVT_INIT(size) \
999
do { \
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
	if (stmt->stmt_with_params) \
		free(stmt->stmt_with_params); \
	if (stmt->stmt_size_limit > 0) \
		new_stsize = stmt->stmt_size_limit; \
	else \
	{ \
		new_stsize = INIT_MIN_ALLOC; \
		while (new_stsize <= size) \
			new_stsize *= 2; \
	} \
	new_statement = malloc(new_stsize); \
	stmt->stmt_with_params = new_statement; \
	npos = 0; \
	new_statement[0] = '\0'; \
1014 1015
} while (0)

1016 1017 1018 1019
/*----------
 *	Terminate the stmt_with_params string with NULL.
 *----------
 */
1020
#define CVT_TERMINATE \
1021 1022 1023
do { \
	new_statement[npos] = '\0'; \
} while (0)
1024 1025 1026 1027 1028

/*----------
 *	Append a data.
 *----------
 */
1029
#define CVT_APPEND_DATA(s, len) \
1030
do { \
1031 1032 1033 1034 1035
	unsigned int	newpos = npos + len; \
	ENLARGE_NEWSTATEMENT(newpos) \
	memcpy(&new_statement[npos], s, len); \
	npos = newpos; \
	new_statement[npos] = '\0'; \
1036 1037
} while (0)

1038 1039 1040 1041
/*----------
 *	Append a string.
 *----------
 */
1042
#define CVT_APPEND_STR(s) \
1043
do { \
1044 1045
	unsigned int len = strlen(s); \
	CVT_APPEND_DATA(s, len); \
1046 1047
} while (0)

1048
/*----------
1049
 *	Append a char.
1050 1051
 *----------
 */
1052
#define CVT_APPEND_CHAR(c) \
1053
do { \
1054 1055
	ENLARGE_NEWSTATEMENT(npos + 1); \
	new_statement[npos++] = c; \
1056 1057
} while (0)

1058 1059
/*----------
 *	Append a binary data.
1060
 *	Newly reqeuired size may be overestimated currently.
1061 1062
 *----------
 */
1063
#define CVT_APPEND_BINARY(buf, used) \
1064
do { \
1065 1066 1067
	unsigned int	newlimit = npos + 5 * used; \
	ENLARGE_NEWSTATEMENT(newlimit); \
	npos += convert_to_pgbinary(buf, &new_statement[npos], used); \
1068 1069
} while (0)

1070 1071 1072 1073
/*----------
 *
 *----------
 */
1074
#define CVT_SPECIAL_CHARS(buf, used) \
1075
do { \
1076
	int cnvlen = convert_special_chars(buf, NULL, used); \
1077 1078 1079 1080 1081
	unsigned int	newlimit = npos + cnvlen; \
\
	ENLARGE_NEWSTATEMENT(newlimit); \
	convert_special_chars(buf, &new_statement[npos], used); \
	npos += cnvlen; \
1082
} while (0)
1083 1084

/*----------
1085
 *	Check if the statement is
1086 1087
 *	SELECT ... INTO table FROM .....
 *	This isn't really a strict check but ...
1088
 *----------
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
 */
static BOOL
into_table_from(const char *stmt)
{
	if (strnicmp(stmt, "into", 4))
		return FALSE;
	stmt += 4;
	if (!isspace((unsigned char) *stmt))
		return FALSE;
	while (isspace((unsigned char) *(++stmt)));
	switch (*stmt)
	{
		case '\0':
		case ',':
		case '\'':
			return FALSE;
1105
		case '\"':				/* double quoted table name ? */
1106 1107 1108
			do
			{
				do
1109
					while (*(++stmt) != '\"' && *stmt);
1110
				while (*stmt && *(++stmt) == '\"');
1111 1112
				while (*stmt && !isspace((unsigned char) *stmt) && *stmt != '\"')
					stmt++;
1113 1114 1115 1116 1117 1118 1119
			}
			while (*stmt == '\"');
			break;
		default:
			while (!isspace((unsigned char) *(++stmt)));
			break;
	}
1120
	if (!*stmt)
1121 1122 1123 1124 1125 1126 1127
		return FALSE;
	while (isspace((unsigned char) *(++stmt)));
	if (strnicmp(stmt, "from", 4))
		return FALSE;
	return isspace((unsigned char) stmt[4]);
}

H
Hiroshi Inoue 已提交
1128
/*----------
1129
 *	Check if the statement is
H
Hiroshi Inoue 已提交
1130 1131
 *	SELECT ... FOR UPDATE .....
 *	This isn't really a strict check but ...
1132
 *----------
H
Hiroshi Inoue 已提交
1133 1134 1135 1136 1137
 */
static BOOL
table_for_update(const char *stmt, int *endpos)
{
	const char *wstmt = stmt;
1138

H
Hiroshi Inoue 已提交
1139
	while (isspace((unsigned char) *(++wstmt)));
1140
	if (!*wstmt)
H
Hiroshi Inoue 已提交
1141 1142 1143 1144 1145 1146 1147 1148
		return FALSE;
	if (strnicmp(wstmt, "update", 6))
		return FALSE;
	wstmt += 6;
	*endpos = wstmt - stmt;
	return !wstmt[0] || isspace((unsigned char) wstmt[0]);
}

1149 1150 1151
/*
 *	This function inserts parameters into an SQL statements.
 *	It will also modify a SELECT statement for use with declare/fetch cursors.
1152
 *	This function does a dynamic memory allocation to get rid of query size limit!
1153
 */
1154
int
1155
copy_statement_with_parameters(StatementClass *stmt)
1156
{
B
Bruce Momjian 已提交
1157 1158 1159 1160 1161 1162
	static char *func = "copy_statement_with_parameters";
	unsigned int opos,
				npos,
				oldstmtlen;
	char		param_string[128],
				tmp[256],
1163 1164 1165
				cbuf[PG_NUMERIC_MAX_PRECISION * 2];		/* seems big enough to
														 * handle the data in
														 * this function */
B
Bruce Momjian 已提交
1166 1167 1168
	int			param_number;
	Int2		param_ctype,
				param_sqltype;
1169 1170
	char	   *old_statement = stmt->statement,
				oldchar;
B
Bruce Momjian 已提交
1171
	char	   *new_statement = stmt->stmt_with_params;
1172
	unsigned int new_stsize = 0;
B
Bruce Momjian 已提交
1173 1174 1175 1176
	SIMPLE_TIME st;
	time_t		t = time(NULL);
	struct tm  *tim;
	SDWORD		used;
1177 1178 1179 1180 1181
	char	   *buffer,
			   *buf;
	BOOL		in_quote = FALSE,
				in_dquote = FALSE,
				in_escape = FALSE;
B
Bruce Momjian 已提交
1182 1183 1184
	Oid			lobj_oid;
	int			lobj_fd,
				retval;
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
	BOOL		check_cursor_ok = FALSE;		/* check cursor
												 * restriction */
	BOOL		proc_no_param = TRUE;
	unsigned int declare_pos = 0;
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
	BOOL		prepare_dummy_cursor = FALSE,
				begin_first = FALSE;
	char		token_save[64];
	int			token_len;
	BOOL		prev_token_end;

1197
#ifdef	DRIVER_CURSOR_IMPLEMENT
1198
	BOOL		search_from_pos = FALSE;
1199
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1200 1201
	if (ci->disallow_premature)
		prepare_dummy_cursor = stmt->pre_executing;
B
Bruce Momjian 已提交
1202 1203 1204

	if (!old_statement)
	{
B
Byron Nikolaidis 已提交
1205
		SC_log_error(func, "No statement string", stmt);
1206
		return SQL_ERROR;
B
Byron Nikolaidis 已提交
1207
	}
1208

1209 1210
	memset(&st, 0, sizeof(SIMPLE_TIME));

B
Bruce Momjian 已提交
1211
	/* Initialize current date */
1212 1213 1214 1215 1216
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;

1217 1218 1219 1220 1221 1222 1223
#ifdef	DRIVER_CURSOR_IMPLEMENT
	if (stmt->statement_type != STMT_TYPE_SELECT)
	{
		stmt->options.cursor_type = SQL_CURSOR_FORWARD_ONLY;
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
	}
	else if (stmt->options.cursor_type == SQL_CURSOR_FORWARD_ONLY)
1224
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1225 1226 1227 1228 1229 1230 1231
	else if (stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY)
	{
		if (stmt->parse_status == STMT_PARSE_NONE)
			parse_statement(stmt);
		if (stmt->parse_status != STMT_PARSE_COMPLETE)
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
		else if (!stmt->ti || stmt->ntab != 1)
1232
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1233 1234
		else
			search_from_pos = TRUE;
1235
	}
1236
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1237 1238 1239 1240 1241 1242

	/* If the application hasn't set a cursor name, then generate one */
	if (stmt->cursor_name[0] == '\0')
		sprintf(stmt->cursor_name, "SQL_CUR%p", stmt);
	oldstmtlen = strlen(old_statement);
	CVT_INIT(oldstmtlen);
H
Hiroshi Inoue 已提交
1243

1244
	stmt->miscinfo = 0;
H
Hiroshi Inoue 已提交
1245 1246
	token_len = 0;
	prev_token_end = TRUE;
1247 1248 1249 1250 1251 1252 1253 1254
	/* For selects, prepend a declare cursor to the statement */
	if (stmt->statement_type == STMT_TYPE_SELECT)
	{
		SC_set_pre_executable(stmt);
		if (prepare_dummy_cursor || ci->drivers.use_declarefetch)
		{
			if (prepare_dummy_cursor)
			{
1255 1256 1257 1258 1259
				if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1))
				{
					strcpy(new_statement, "BEGIN;");
					begin_first = TRUE;
				}
1260 1261 1262
			}
			else if (ci->drivers.use_declarefetch)
				SC_set_fetchcursor(stmt);
H
Hiroshi Inoue 已提交
1263
			sprintf(new_statement, "%sdeclare %s cursor for ",
1264
					new_statement, stmt->cursor_name);
1265
			npos = strlen(new_statement);
H
Hiroshi Inoue 已提交
1266
			check_cursor_ok = TRUE;
1267 1268 1269 1270
			declare_pos = npos;
		}
	}
	param_number = -1;
H
Hiroshi Inoue 已提交
1271
#ifdef MULTIBYTE
B
Bruce Momjian 已提交
1272
	multibyte_init();
H
Hiroshi Inoue 已提交
1273
#endif
1274

B
Bruce Momjian 已提交
1275 1276
	for (opos = 0; opos < oldstmtlen; opos++)
	{
1277
		oldchar = old_statement[opos];
1278
#ifdef MULTIBYTE
1279
		if (multibyte_char_check(oldchar) != 0)
1280
		{
1281
			CVT_APPEND_CHAR(oldchar);
1282 1283
			continue;
		}
1284

1285
		/*
1286
		 * From here we are guaranteed to handle a 1-byte character.
1287 1288
		 */
#endif
1289

1290
		if (in_escape)			/* escape check */
1291 1292
		{
			in_escape = FALSE;
1293
			CVT_APPEND_CHAR(oldchar);
1294
			continue;
1295
		}
1296 1297
		else if (in_quote || in_dquote) /* quote/double quote check */
		{
1298 1299 1300
			if (oldchar == '\\')
				in_escape = TRUE;
			else if (oldchar == '\'' && in_quote)
1301
				in_quote = FALSE;
1302
			else if (oldchar == '\"' && in_dquote)
1303
				in_dquote = FALSE;
1304
			CVT_APPEND_CHAR(oldchar);
1305
			continue;
1306
		}
1307

1308
		/*
1309 1310
		 * From here we are guranteed to be in neither an escape, a quote
		 * nor a double quote.
1311
		 */
1312 1313
		/* Squeeze carriage-return/linefeed pairs to linefeed only */
		else if (oldchar == '\r' && opos + 1 < oldstmtlen &&
1314
				 old_statement[opos + 1] == '\n')
1315
			continue;
1316

B
Bruce Momjian 已提交
1317 1318 1319 1320
		/*
		 * Handle literals (date, time, timestamp) and ODBC scalar
		 * functions
		 */
1321
		else if (oldchar == '{')
B
Bruce Momjian 已提交
1322 1323 1324 1325
		{
			char	   *esc;
			char	   *begin = &old_statement[opos + 1];

H
Hiroshi Inoue 已提交
1326
#ifdef MULTIBYTE
B
Bruce Momjian 已提交
1327
			char	   *end = multibyte_strchr(begin, '}');
1328

H
Hiroshi Inoue 已提交
1329
#else
B
Bruce Momjian 已提交
1330
			char	   *end = strchr(begin, '}');
H
Hiroshi Inoue 已提交
1331
#endif
1332

B
Bruce Momjian 已提交
1333
			if (!end)
1334
				continue;
H
Hiroshi Inoue 已提交
1335 1336 1337
			/* procedure calls */
			if (stmt->statement_type == STMT_TYPE_PROCCALL)
			{
1338 1339
				int			lit_call_len = 4;

H
Hiroshi Inoue 已提交
1340
				while (isspace((unsigned char) old_statement[++opos]));
1341
				/* '=?' to accept return values exists ? */
H
Hiroshi Inoue 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
				if (old_statement[opos] == '?')
				{
					param_number++;
					while (isspace((unsigned char) old_statement[++opos]));
					if (old_statement[opos] != '=')
					{
						opos--;
						continue;
					}
					while (isspace((unsigned char) old_statement[++opos]));
				}
1353
				if (strnicmp(&old_statement[opos], "call", lit_call_len) ||
1354
					!isspace((unsigned char) old_statement[opos + lit_call_len]))
H
Hiroshi Inoue 已提交
1355 1356 1357 1358
				{
					opos--;
					continue;
				}
1359
				opos += lit_call_len;
1360
				CVT_APPEND_STR("SELECT ");
H
Hiroshi Inoue 已提交
1361 1362 1363
#ifdef MULTIBYTE
				if (multibyte_strchr(&old_statement[opos], '('))
#else
1364
				if (strchr(&old_statement[opos], '('))
1365
#endif   /* MULTIBYTE */
1366
					proc_no_param = FALSE;
1367
				continue;
H
Hiroshi Inoue 已提交
1368
			}
1369 1370 1371
			*end = '\0';

			esc = convert_escape(begin);
B
Bruce Momjian 已提交
1372
			if (esc)
1373
				CVT_APPEND_STR(esc);
B
Bruce Momjian 已提交
1374 1375 1376
			else
			{					/* it's not a valid literal so just copy */
				*end = '}';
1377
				CVT_APPEND_CHAR(oldchar);
1378 1379
				continue;
			}
1380

1381
			opos += end - begin + 1;
1382 1383 1384
			*end = '}';
			continue;
		}
H
Hiroshi Inoue 已提交
1385 1386
		/* End of a procedure call */
		else if (oldchar == '}' && stmt->statement_type == STMT_TYPE_PROCCALL)
1387 1388 1389
		{
			if (proc_no_param)
				CVT_APPEND_STR("()");
H
Hiroshi Inoue 已提交
1390
			continue;
1391
		}
1392

B
Bruce Momjian 已提交
1393 1394 1395 1396 1397
		/*
		 * Can you have parameter markers inside of quotes?  I dont think
		 * so. All the queries I've seen expect the driver to put quotes
		 * if needed.
		 */
1398
		else if (oldchar == '?')
B
Bruce Momjian 已提交
1399 1400 1401
			;					/* ok */
		else
		{
1402
			if (oldchar == '\'')
1403
				in_quote = TRUE;
1404
			else if (oldchar == '\\')
1405
				in_escape = TRUE;
1406
			else if (oldchar == '\"')
1407
				in_dquote = TRUE;
1408
			else
1409
			{
1410
				if (isspace((unsigned char) oldchar))
H
Hiroshi Inoue 已提交
1411 1412 1413 1414 1415 1416 1417 1418
				{
					if (!prev_token_end)
					{
						prev_token_end = TRUE;
						token_save[token_len] = '\0';
						if (token_len == 4)
						{
							if (check_cursor_ok &&
1419
								into_table_from(&old_statement[opos - token_len]))
H
Hiroshi Inoue 已提交
1420 1421 1422 1423 1424 1425 1426 1427
							{
								stmt->statement_type = STMT_TYPE_CREATE;
								SC_no_pre_executable(stmt);
								SC_no_fetchcursor(stmt);
								stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
								memmove(new_statement, new_statement + declare_pos, npos - declare_pos);
								npos -= declare_pos;
							}
1428
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
1429
							else if (search_from_pos && /* where's from clause */
1430
									 strnicmp(token_save, "from", 4) == 0)
H
Hiroshi Inoue 已提交
1431 1432 1433 1434 1435
							{
								search_from_pos = FALSE;
								npos -= 5;
								CVT_APPEND_STR(", CTID, OID from");
							}
1436
#endif   /* DRIVER_CURSOR_IMPLEMENT */
H
Hiroshi Inoue 已提交
1437 1438 1439
						}
						if (token_len == 3)
						{
1440 1441
							int			endpos;

H
Hiroshi Inoue 已提交
1442
							if (check_cursor_ok &&
1443 1444
								strnicmp(token_save, "for", 3) == 0 &&
								table_for_update(&old_statement[opos], &endpos))
H
Hiroshi Inoue 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
							{
								SC_no_fetchcursor(stmt);
								stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
								if (prepare_dummy_cursor)
								{
									npos -= 4;
									opos += endpos;
								}
								else
								{
									memmove(new_statement, new_statement + declare_pos, npos - declare_pos);
									npos -= declare_pos;
								}
							}
						}
1460
					}
H
Hiroshi Inoue 已提交
1461 1462 1463 1464 1465 1466 1467
				}
				else if (prev_token_end)
				{
					prev_token_end = FALSE;
					token_save[0] = oldchar;
					token_len = 1;
				}
H
Hiroshi Inoue 已提交
1468
				else if (token_len + 1 < sizeof(token_save))
H
Hiroshi Inoue 已提交
1469
					token_save[token_len++] = oldchar;
1470
			}
1471
			CVT_APPEND_CHAR(oldchar);
1472 1473 1474
			continue;
		}

1475 1476 1477
		/*
		 * Its a '?' parameter alright
		 */
1478 1479
		param_number++;

B
Bruce Momjian 已提交
1480
		if (param_number >= stmt->parameters_allocated)
1481 1482 1483
		{
			if (stmt->pre_executing)
			{
1484
				CVT_APPEND_STR("NULL");
1485 1486 1487 1488 1489
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1490
				CVT_APPEND_CHAR('?');
1491 1492 1493
				continue;
			}
		}
1494

B
Bruce Momjian 已提交
1495 1496 1497
		/* Assign correct buffers based on data at exec param or not */
		if (stmt->parameters[param_number].data_at_exec)
		{
1498 1499 1500
			used = stmt->parameters[param_number].EXEC_used ? *stmt->parameters[param_number].EXEC_used : SQL_NTS;
			buffer = stmt->parameters[param_number].EXEC_buffer;
		}
B
Bruce Momjian 已提交
1501 1502
		else
		{
1503 1504


1505
			used = stmt->parameters[param_number].used ? *stmt->parameters[param_number].used : SQL_NTS;
1506

1507 1508 1509
			buffer = stmt->parameters[param_number].buffer;
		}

B
Bruce Momjian 已提交
1510 1511 1512
		/* Handle NULL parameter data */
		if (used == SQL_NULL_DATA)
		{
1513
			CVT_APPEND_STR("NULL");
1514 1515 1516
			continue;
		}

B
Bruce Momjian 已提交
1517 1518 1519 1520 1521 1522
		/*
		 * If no buffer, and it's not null, then what the hell is it? Just
		 * leave it alone then.
		 */
		if (!buffer)
		{
1523 1524
			if (stmt->pre_executing)
			{
1525
				CVT_APPEND_STR("NULL");
1526 1527 1528 1529 1530
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1531
				CVT_APPEND_CHAR('?');
1532 1533
				continue;
			}
1534
		}
1535 1536 1537

		param_ctype = stmt->parameters[param_number].CType;
		param_sqltype = stmt->parameters[param_number].SQLType;
B
Bruce Momjian 已提交
1538

1539
		mylog("copy_statement_with_params: from(fcType)=%d, to(fSqlType)=%d\n", param_ctype, param_sqltype);
B
Bruce Momjian 已提交
1540

B
Bruce Momjian 已提交
1541
		/* replace DEFAULT with something we can use */
B
Bruce Momjian 已提交
1542
		if (param_ctype == SQL_C_DEFAULT)
1543 1544 1545 1546 1547 1548
			param_ctype = sqltype_to_default_ctype(param_sqltype);

		buf = NULL;
		param_string[0] = '\0';
		cbuf[0] = '\0';

B
Bruce Momjian 已提交
1549 1550 1551 1552 1553 1554 1555
		/* Convert input C type to a neutral format */
		switch (param_ctype)
		{
			case SQL_C_BINARY:
			case SQL_C_CHAR:
				buf = buffer;
				break;
1556

B
Bruce Momjian 已提交
1557
			case SQL_C_DOUBLE:
1558
				sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
1559 1560
						*((SDOUBLE *) buffer));
				break;
1561

B
Bruce Momjian 已提交
1562
			case SQL_C_FLOAT:
1563
				sprintf(param_string, "%.6g",
B
Bruce Momjian 已提交
1564 1565
						*((SFLOAT *) buffer));
				break;
1566

B
Bruce Momjian 已提交
1567 1568 1569 1570 1571
			case SQL_C_SLONG:
			case SQL_C_LONG:
				sprintf(param_string, "%ld",
						*((SDWORD *) buffer));
				break;
1572

B
Bruce Momjian 已提交
1573 1574 1575 1576 1577
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				sprintf(param_string, "%d",
						*((SWORD *) buffer));
				break;
1578

B
Bruce Momjian 已提交
1579 1580 1581 1582 1583
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				sprintf(param_string, "%d",
						*((SCHAR *) buffer));
				break;
1584

B
Bruce Momjian 已提交
1585 1586 1587 1588
			case SQL_C_ULONG:
				sprintf(param_string, "%lu",
						*((UDWORD *) buffer));
				break;
1589

B
Bruce Momjian 已提交
1590 1591 1592 1593
			case SQL_C_USHORT:
				sprintf(param_string, "%u",
						*((UWORD *) buffer));
				break;
1594

B
Bruce Momjian 已提交
1595 1596 1597 1598
			case SQL_C_UTINYINT:
				sprintf(param_string, "%u",
						*((UCHAR *) buffer));
				break;
1599

B
Bruce Momjian 已提交
1600 1601 1602
			case SQL_C_BIT:
				{
					int			i = *((UCHAR *) buffer);
1603

B
Bruce Momjian 已提交
1604 1605 1606
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
				}
1607

B
Bruce Momjian 已提交
1608
			case SQL_C_DATE:
1609
#if (ODBCVER >= 0x0300)
1610
			case SQL_C_TYPE_DATE:		/* 91 */
1611
#endif
B
Bruce Momjian 已提交
1612 1613
				{
					DATE_STRUCT *ds = (DATE_STRUCT *) buffer;
1614

B
Bruce Momjian 已提交
1615 1616 1617
					st.m = ds->month;
					st.d = ds->day;
					st.y = ds->year;
1618

B
Bruce Momjian 已提交
1619 1620
					break;
				}
1621

B
Bruce Momjian 已提交
1622
			case SQL_C_TIME:
1623
#if (ODBCVER >= 0x0300)
1624
			case SQL_C_TYPE_TIME:		/* 92 */
1625
#endif
B
Bruce Momjian 已提交
1626 1627
				{
					TIME_STRUCT *ts = (TIME_STRUCT *) buffer;
1628

B
Bruce Momjian 已提交
1629 1630 1631
					st.hh = ts->hour;
					st.mm = ts->minute;
					st.ss = ts->second;
1632

B
Bruce Momjian 已提交
1633 1634
					break;
				}
1635

B
Bruce Momjian 已提交
1636
			case SQL_C_TIMESTAMP:
1637
#if (ODBCVER >= 0x0300)
1638
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
1639
#endif
B
Bruce Momjian 已提交
1640 1641
				{
					TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer;
1642

B
Bruce Momjian 已提交
1643 1644 1645 1646 1647 1648
					st.m = tss->month;
					st.d = tss->day;
					st.y = tss->year;
					st.hh = tss->hour;
					st.mm = tss->minute;
					st.ss = tss->second;
1649
					st.fr = tss->fraction;
1650

B
Bruce Momjian 已提交
1651
					mylog("m=%d,d=%d,y=%d,hh=%d,mm=%d,ss=%d\n", st.m, st.d, st.y, st.hh, st.mm, st.ss);
1652

B
Bruce Momjian 已提交
1653
					break;
1654

B
Bruce Momjian 已提交
1655 1656 1657 1658 1659
				}
			default:
				/* error */
				stmt->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters";
				stmt->errornumber = STMT_NOT_IMPLEMENTED_ERROR;
1660
				CVT_TERMINATE;	/* just in case */
B
Bruce Momjian 已提交
1661 1662 1663
				SC_log_error(func, "", stmt);
				return SQL_ERROR;
		}
1664

B
Bruce Momjian 已提交
1665 1666 1667 1668
		/*
		 * Now that the input data is in a neutral format, convert it to
		 * the desired output format (sqltype)
		 */
1669

B
Bruce Momjian 已提交
1670 1671 1672 1673 1674
		switch (param_sqltype)
		{
			case SQL_CHAR:
			case SQL_VARCHAR:
			case SQL_LONGVARCHAR:
1675

1676
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1677

B
Bruce Momjian 已提交
1678 1679
				/* it was a SQL_C_CHAR */
				if (buf)
1680
					CVT_SPECIAL_CHARS(buf, used);
1681

B
Bruce Momjian 已提交
1682 1683
				/* it was a numeric type */
				else if (param_string[0] != '\0')
1684
					CVT_APPEND_STR(param_string);
1685

B
Bruce Momjian 已提交
1686 1687 1688 1689 1690
				/* it was date,time,timestamp -- use m,d,y,hh,mm,ss */
				else
				{
					sprintf(tmp, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
							st.y, st.m, st.d, st.hh, st.mm, st.ss);
1691

1692
					CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1693
				}
1694

1695
				CVT_APPEND_CHAR('\'');	/* Close Quote */
1696

B
Bruce Momjian 已提交
1697
				break;
1698

B
Bruce Momjian 已提交
1699
			case SQL_DATE:
1700
#if (ODBCVER >= 0x0300)
1701
			case SQL_TYPE_DATE:	/* 91 */
1702
#endif
B
Bruce Momjian 已提交
1703 1704 1705 1706 1707
				if (buf)
				{				/* copy char data to time */
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1708

B
Bruce Momjian 已提交
1709
				sprintf(tmp, "'%.4d-%.2d-%.2d'", st.y, st.m, st.d);
1710

1711
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1712
				break;
1713

B
Bruce Momjian 已提交
1714
			case SQL_TIME:
1715
#if (ODBCVER >= 0x0300)
1716
			case SQL_TYPE_TIME:	/* 92 */
1717
#endif
B
Bruce Momjian 已提交
1718 1719 1720 1721 1722
				if (buf)
				{				/* copy char data to time */
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1723

B
Bruce Momjian 已提交
1724
				sprintf(tmp, "'%.2d:%.2d:%.2d'", st.hh, st.mm, st.ss);
1725

1726
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1727
				break;
1728

B
Bruce Momjian 已提交
1729
			case SQL_TIMESTAMP:
1730
#if (ODBCVER >= 0x0300)
1731
			case SQL_TYPE_TIMESTAMP:	/* 93 */
1732
#endif
1733

B
Bruce Momjian 已提交
1734 1735 1736 1737 1738
				if (buf)
				{
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1739

1740 1741 1742 1743
				/*
				 * sprintf(tmp, "'%.4d-%.2d-%.2d %.2d:%.2d:%.2d'", st.y,
				 * st.m, st.d, st.hh, st.mm, st.ss);
				 */
1744 1745 1746 1747
				tmp[0] = '\'';
				/* Time zone stuff is unreliable */
				stime2timestamp(&st, tmp + 1, FALSE, PG_VERSION_GE(conn, 7.2));
				strcat(tmp, "'");
1748

1749
				CVT_APPEND_STR(tmp);
1750

B
Bruce Momjian 已提交
1751
				break;
1752

B
Bruce Momjian 已提交
1753 1754 1755
			case SQL_BINARY:
			case SQL_VARBINARY:/* non-ascii characters should be
								 * converted to octal */
1756
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1757

B
Bruce Momjian 已提交
1758
				mylog("SQL_VARBINARY: about to call convert_to_pgbinary, used = %d\n", used);
1759

1760
				CVT_APPEND_BINARY(buf, used);
1761

1762
				CVT_APPEND_CHAR('\'');	/* Close Quote */
B
Byron Nikolaidis 已提交
1763

B
Bruce Momjian 已提交
1764
				break;
1765

B
Bruce Momjian 已提交
1766 1767 1768 1769 1770 1771 1772
			case SQL_LONGVARBINARY:

				if (stmt->parameters[param_number].data_at_exec)
					lobj_oid = stmt->parameters[param_number].lobj_oid;
				else
				{
					/* begin transaction if needed */
1773
					if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
1774 1775 1776 1777
					{
						QResultClass *res;
						char		ok;

1778
						res = CC_send_query(conn, "BEGIN", NULL);
B
Bruce Momjian 已提交
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
						if (!res)
						{
							stmt->errormsg = "Could not begin (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
						ok = QR_command_successful(res);
						QR_Destructor(res);
						if (!ok)
						{
							stmt->errormsg = "Could not begin (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
1795

1796
						CC_set_in_trans(conn);
B
Bruce Momjian 已提交
1797
					}
B
Byron Nikolaidis 已提交
1798

B
Bruce Momjian 已提交
1799
					/* store the oid */
1800
					lobj_oid = lo_creat(conn, INV_READ | INV_WRITE);
B
Bruce Momjian 已提交
1801 1802
					if (lobj_oid == 0)
					{
B
Byron Nikolaidis 已提交
1803
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1804
						stmt->errormsg = "Couldnt create (in-line) large object.";
B
Byron Nikolaidis 已提交
1805 1806 1807
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}
B
Bruce Momjian 已提交
1808 1809

					/* store the fd */
1810
					lobj_fd = lo_open(conn, lobj_oid, INV_WRITE);
B
Bruce Momjian 已提交
1811 1812
					if (lobj_fd < 0)
					{
B
Byron Nikolaidis 已提交
1813
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1814
						stmt->errormsg = "Couldnt open (in-line) large object for writing.";
B
Byron Nikolaidis 已提交
1815 1816 1817 1818
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}

1819
					retval = lo_write(conn, lobj_fd, buffer, used);
1820

1821
					lo_close(conn, lobj_fd);
1822

B
Bruce Momjian 已提交
1823
					/* commit transaction if needed */
1824
					if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
1825 1826 1827
					{
						QResultClass *res;
						char		ok;
1828

1829
						res = CC_send_query(conn, "COMMIT", NULL);
B
Bruce Momjian 已提交
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
						if (!res)
						{
							stmt->errormsg = "Could not commit (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
						ok = QR_command_successful(res);
						QR_Destructor(res);
						if (!ok)
						{
							stmt->errormsg = "Could not commit (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
1846

1847
						CC_set_no_trans(conn);
B
Bruce Momjian 已提交
1848 1849
					}
				}
1850

B
Bruce Momjian 已提交
1851 1852 1853 1854 1855 1856
				/*
				 * the oid of the large object -- just put that in for the
				 * parameter marker -- the data has already been sent to
				 * the large object
				 */
				sprintf(param_string, "'%d'", lobj_oid);
1857
				CVT_APPEND_STR(param_string);
1858

B
Bruce Momjian 已提交
1859 1860 1861 1862 1863 1864 1865
				break;

				/*
				 * because of no conversion operator for bool and int4,
				 * SQL_BIT
				 */
				/* must be quoted (0 or 1 is ok to use inside the quotes) */
1866

B
Bruce Momjian 已提交
1867 1868 1869 1870
			case SQL_REAL:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float4", param_string);
1871
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1872 1873 1874 1875 1876 1877
				break;
			case SQL_FLOAT:
			case SQL_DOUBLE:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float8", param_string);
1878
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
				break;
			case SQL_NUMERIC:
				if (buf)
				{
					cbuf[0] = '\'';
					my_strcpy(cbuf + 1, sizeof(cbuf) - 12, buf, used);	/* 12 = 1('\'') +
																		 * strlen("'::numeric")
																		 * + 1('\0') */
					strcat(cbuf, "'::numeric");
				}
				else
					sprintf(cbuf, "'%s'::numeric", param_string);
1891
				CVT_APPEND_STR(cbuf);
B
Bruce Momjian 已提交
1892 1893 1894
				break;
			default:			/* a numeric type or SQL_BIT */
				if (param_sqltype == SQL_BIT)
1895
					CVT_APPEND_CHAR('\'');		/* Open Quote */
B
Bruce Momjian 已提交
1896 1897 1898

				if (buf)
				{
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
					switch (used)
					{
						case SQL_NULL_DATA:
							break;
						case SQL_NTS:
							CVT_APPEND_STR(buf);
							break;
						default:
							CVT_APPEND_DATA(buf, used);
					}
B
Bruce Momjian 已提交
1909 1910
				}
				else
1911
					CVT_APPEND_STR(param_string);
B
Bruce Momjian 已提交
1912 1913

				if (param_sqltype == SQL_BIT)
1914
					CVT_APPEND_CHAR('\'');		/* Close Quote */
B
Bruce Momjian 已提交
1915 1916

				break;
1917
		}
B
Bruce Momjian 已提交
1918
	}							/* end, for */
1919

B
Bruce Momjian 已提交
1920
	/* make sure new_statement is always null-terminated */
1921
	CVT_TERMINATE;
1922

1923
	if (conn->DriverToDataSource != NULL)
B
Bruce Momjian 已提交
1924 1925 1926
	{
		int			length = strlen(new_statement);

1927
		conn->DriverToDataSource(conn->translation_option,
1928 1929 1930 1931
								 SQL_CHAR,
								 new_statement, length,
								 new_statement, length, NULL,
								 NULL, 0, NULL);
B
Byron Nikolaidis 已提交
1932 1933
	}

1934
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
1935
	if (search_from_pos)
1936
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1937
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1938 1939
	if (prepare_dummy_cursor && SC_is_pre_executable(stmt))
	{
1940 1941
		char		fetchstr[128];

1942 1943
		sprintf(fetchstr, ";fetch backward in %s;close %s;",
				stmt->cursor_name, stmt->cursor_name);
1944 1945
		if (begin_first && CC_is_in_autocommit(conn))
			strcat(fetchstr, "COMMIT;");
1946 1947 1948 1949
		CVT_APPEND_STR(fetchstr);
		stmt->inaccurate_result = TRUE;
	}

1950 1951 1952
	return SQL_SUCCESS;
}

1953

1954
static char *
1955
mapFunction(const char *func)
1956
{
B
Bruce Momjian 已提交
1957
	int			i;
1958 1959

	for (i = 0; mapFuncs[i][0]; i++)
B
Bruce Momjian 已提交
1960
		if (!stricmp(mapFuncs[i][0], func))
1961 1962 1963 1964
			return mapFuncs[i][1];

	return NULL;
}
1965

1966 1967 1968 1969

/*
 * convert_escape()
 *
1970 1971
 * This function returns a pointer to static memory!
 */
1972 1973 1974
char *
convert_escape(char *value)
{
B
Bruce Momjian 已提交
1975 1976
	static char escape[1024];
	char		key[33];
1977

1978
	/* Separate off the key, skipping leading and trailing whitespace */
B
Bruce Momjian 已提交
1979 1980
	while ((*value != '\0') && isspace((unsigned char) *value))
		value++;
1981
	sscanf(value, "%32s", key);
B
Bruce Momjian 已提交
1982 1983 1984 1985
	while ((*value != '\0') && (!isspace((unsigned char) *value)))
		value++;
	while ((*value != '\0') && isspace((unsigned char) *value))
		value++;
1986

1987
	mylog("convert_escape: key='%s', val='%s'\n", key, value);
1988

B
Bruce Momjian 已提交
1989 1990
	if ((strcmp(key, "d") == 0) ||
		(strcmp(key, "t") == 0) ||
1991 1992
		(strcmp(key, "oj") == 0) ||		/* {oj syntax support for 7.1
										 * servers */
B
Bruce Momjian 已提交
1993 1994
		(strcmp(key, "ts") == 0))
	{
1995
		/* Literal; return the escape part as-is */
B
Bruce Momjian 已提交
1996
		strncpy(escape, value, sizeof(escape) - 1);
1997
	}
B
Bruce Momjian 已提交
1998 1999 2000 2001 2002
	else if (strcmp(key, "fn") == 0)
	{
		/*
		 * Function invocation Separate off the func name, skipping
		 * trailing whitespace.
2003
		 */
B
Bruce Momjian 已提交
2004 2005 2006
		char	   *funcEnd = value;
		char		svchar;
		char	   *mapFunc;
2007 2008

		while ((*funcEnd != '\0') && (*funcEnd != '(') &&
B
Bruce Momjian 已提交
2009
			   (!isspace((unsigned char) *funcEnd)))
2010
			funcEnd++;
2011 2012 2013 2014
		svchar = *funcEnd;
		*funcEnd = '\0';
		sscanf(value, "%32s", key);
		*funcEnd = svchar;
2015 2016
		while ((*funcEnd != '\0') && isspace((unsigned char) *funcEnd))
			funcEnd++;
2017

B
Bruce Momjian 已提交
2018 2019 2020
		/*
		 * We expect left parenthesis here, else return fn body as-is
		 * since it is one of those "function constants".
2021
		 */
B
Bruce Momjian 已提交
2022 2023 2024
		if (*funcEnd != '(')
		{
			strncpy(escape, value, sizeof(escape) - 1);
2025
			return escape;
2026
		}
2027
		mapFunc = mapFunction(key);
B
Bruce Momjian 已提交
2028 2029

		/*
2030 2031
		 * We could have mapFunction() return key if not in table... -
		 * thomas 2000-04-03
2032
		 */
B
Bruce Momjian 已提交
2033 2034
		if (mapFunc == NULL)
		{
2035
			/* If unrecognized function name, return fn body as-is */
B
Bruce Momjian 已提交
2036
			strncpy(escape, value, sizeof(escape) - 1);
2037 2038 2039 2040
			return escape;
		}
		/* copy mapped name and remaining input string */
		strcpy(escape, mapFunc);
B
Bruce Momjian 已提交
2041
		strncat(escape, funcEnd, sizeof(escape) - 1 - strlen(mapFunc));
2042
	}
B
Bruce Momjian 已提交
2043 2044
	else
	{
2045
		/* Bogus key, leave untranslated */
2046 2047 2048 2049 2050 2051 2052
		return NULL;
	}

	return escape;
}


2053 2054
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
2055
{
2056 2057
	size_t		i = 0,
				out = 0;
2058

2059
	for (i = 0; s[i]; i++)
B
Bruce Momjian 已提交
2060
	{
2061
		if (s[i] == '$' || s[i] == ',' || s[i] == ')')
B
Bruce Momjian 已提交
2062
			;					/* skip these characters */
2063
		else
2064 2065
		{
			if (out + 1 >= soutmax)
2066
				return FALSE;	/* sout is too short */
2067 2068 2069 2070 2071
			if (s[i] == '(')
				sout[out++] = '-';
			else
				sout[out++] = s[i];
		}
2072
	}
2073 2074
	sout[out] = '\0';
	return TRUE;
2075 2076 2077
}


2078 2079 2080 2081
/*
 *	This function parses a character string for date/time info and fills in SIMPLE_TIME
 *	It does not zero out SIMPLE_TIME in case it is desired to initialize it with a value
 */
2082
char
2083
parse_datetime(char *buf, SIMPLE_TIME *st)
2084
{
B
Bruce Momjian 已提交
2085 2086 2087 2088 2089 2090 2091 2092
	int			y,
				m,
				d,
				hh,
				mm,
				ss;
	int			nf;

2093 2094
	y = m = d = hh = mm = ss = 0;

2095 2096 2097 2098 2099 2100 2101 2102
	/* escape sequence ? */
	if (buf[0] == '{')
	{
		while (*(++buf) && *buf != '\'');
		if (!(*buf))
			return FALSE;
		buf++;
	}
B
Bruce Momjian 已提交
2103 2104
	if (buf[4] == '-')			/* year first */
		nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss);
2105
	else
B
Bruce Momjian 已提交
2106
		nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss);
2107

B
Bruce Momjian 已提交
2108 2109
	if (nf == 5 || nf == 6)
	{
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
		st->y = y;
		st->m = m;
		st->d = d;
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

B
Bruce Momjian 已提交
2120
	if (buf[4] == '-')			/* year first */
2121 2122 2123 2124
		nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d);
	else
		nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y);

B
Bruce Momjian 已提交
2125 2126
	if (nf == 3)
	{
2127 2128 2129 2130 2131 2132 2133 2134
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

	nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss);
B
Bruce Momjian 已提交
2135 2136
	if (nf == 2 || nf == 3)
	{
2137 2138 2139 2140 2141 2142 2143 2144 2145
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

	return FALSE;
}
2146

2147

2148
/*	Change linefeed to carriage-return/linefeed */
2149
int
2150
convert_linefeeds(const char *si, char *dst, size_t max, BOOL *changed)
2151
{
B
Bruce Momjian 已提交
2152 2153
	size_t		i = 0,
				out = 0;
2154

2155 2156 2157 2158
	if (max == 0)
		max = 0xffffffff;
	*changed = FALSE;
	for (i = 0; si[i] && out < max - 1; i++)
B
Bruce Momjian 已提交
2159 2160 2161 2162 2163 2164
	{
		if (si[i] == '\n')
		{
			/* Only add the carriage-return if needed */
			if (i > 0 && si[i - 1] == '\r')
			{
2165 2166 2167 2168
				if (dst)
					dst[out++] = si[i];
				else
					out++;
B
Byron Nikolaidis 已提交
2169 2170
				continue;
			}
2171
			*changed = TRUE;
B
Byron Nikolaidis 已提交
2172

2173 2174 2175 2176 2177 2178 2179
			if (dst)
			{
				dst[out++] = '\r';
				dst[out++] = '\n';
			}
			else
				out += 2;
2180 2181
		}
		else
2182 2183 2184 2185 2186 2187
		{
			if (dst)
				dst[out++] = si[i];
			else
				out++;
		}
2188
	}
2189 2190
	if (dst)
		dst[out] = '\0';
2191
	return out;
2192 2193
}

2194 2195 2196 2197 2198

/*
 *	Change carriage-return/linefeed to just linefeed
 *	Plus, escape any special characters.
 */
2199
int
2200
convert_special_chars(const char *si, char *dst, int used)
2201
{
B
Bruce Momjian 已提交
2202 2203 2204
	size_t		i = 0,
				out = 0,
				max;
2205
	char	   *p = NULL;
2206 2207 2208 2209 2210 2211


	if (used == SQL_NTS)
		max = strlen(si);
	else
		max = used;
2212 2213 2214 2215 2216
	if (dst)
	{
		p = dst;
		p[0] = '\0';
	}
H
Hiroshi Inoue 已提交
2217 2218 2219
#ifdef MULTIBYTE
	multibyte_init();
#endif
2220

B
Bruce Momjian 已提交
2221 2222
	for (i = 0; i < max; i++)
	{
2223 2224 2225 2226 2227 2228 2229 2230 2231
#ifdef MULTIBYTE
		if (multibyte_char_check(si[i]) != 0)
		{
			if (p)
				p[out] = si[i];
			out++;
			continue;
		}
#endif
2232
		if (si[i] == '\r' && si[i + 1] == '\n')
2233
			continue;
B
Byron Nikolaidis 已提交
2234
		else if (si[i] == '\'' || si[i] == '\\')
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
		{
			if (p)
				p[out++] = '\\';
			else
				out++;
		}
		if (p)
			p[out++] = si[i];
		else
			out++;
2245
	}
2246 2247 2248
	if (p)
		p[out] = '\0';
	return out;
2249 2250
}

2251

2252 2253
/*	!!! Need to implement this function !!!  */
int
2254
convert_pgbinary_to_char(const char *value, char *rgbValue, int cbValueMax)
2255
{
2256 2257 2258
	mylog("convert_pgbinary_to_char: value = '%s'\n", value);

	strncpy_null(rgbValue, value, cbValueMax);
2259 2260 2261
	return 0;
}

2262

2263
static unsigned int
2264
conv_from_octal(const unsigned char *s)
2265
{
B
Bruce Momjian 已提交
2266 2267
	int			i,
				y = 0;
2268

B
Bruce Momjian 已提交
2269 2270
	for (i = 1; i <= 3; i++)
		y += (s[i] - 48) * (int) pow(8, 3 - i);
2271 2272

	return y;
2273

2274 2275
}

2276

2277
static unsigned int
2278
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
2279
{
B
Bruce Momjian 已提交
2280 2281 2282
	int			i,
				y = 0,
				val;
2283

B
Bruce Momjian 已提交
2284 2285 2286 2287 2288 2289 2290 2291
	for (i = 1; i <= 2; i++)
	{
		if (s[i] >= 'a' && s[i] <= 'f')
			val = s[i] - 'a' + 10;
		else if (s[i] >= 'A' && s[i] <= 'F')
			val = s[i] - 'A' + 10;
		else
			val = s[i] - '0';
B
Byron Nikolaidis 已提交
2292

B
Bruce Momjian 已提交
2293
		y += val * (int) pow(16, 2 - i);
B
Byron Nikolaidis 已提交
2294 2295 2296 2297 2298
	}

	return y;
}

2299

B
Bruce Momjian 已提交
2300
/*	convert octal escapes to bytes */
2301
int
2302
convert_from_pgbinary(const unsigned char *value, unsigned char *rgbValue, int cbValueMax)
2303
{
2304 2305
	size_t		i,
				ilen = strlen(value);
B
Bruce Momjian 已提交
2306
	int			o = 0;
2307

B
Bruce Momjian 已提交
2308

2309
	for (i = 0; i < ilen;)
B
Bruce Momjian 已提交
2310 2311 2312
	{
		if (value[i] == '\\')
		{
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
			if (value[i + 1] == '\\')
			{
				rgbValue[o] = value[i];
				i += 2;
			}
			else
			{
				rgbValue[o] = conv_from_octal(&value[i]);
				i += 4;
			}
2323
		}
B
Bruce Momjian 已提交
2324
		else
2325 2326 2327 2328
			rgbValue[o] = value[i++];
		mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]);
		o++;
	}
2329

B
Bruce Momjian 已提交
2330
	rgbValue[o] = '\0';			/* extra protection */
2331

2332 2333 2334 2335
	return o;
}


2336
static char *
2337 2338
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
2339 2340
	int			i;
	static char x[6];
2341 2342 2343 2344 2345

	x[0] = '\\';
	x[1] = '\\';
	x[5] = '\0';

B
Bruce Momjian 已提交
2346 2347
	for (i = 4; i > 1; i--)
	{
2348 2349 2350 2351 2352 2353 2354
		x[i] = (val & 7) + 48;
		val >>= 3;
	}

	return x;
}

2355

B
Bruce Momjian 已提交
2356
/*	convert non-ascii bytes to octal escape sequences */
2357
int
2358
convert_to_pgbinary(const unsigned char *in, char *out, int len)
2359
{
B
Bruce Momjian 已提交
2360 2361
	int			i,
				o = 0;
2362

B
Bruce Momjian 已提交
2363 2364
	for (i = 0; i < len; i++)
	{
2365
		mylog("convert_to_pgbinary: in[%d] = %d, %c\n", i, in[i], in[i]);
B
Bruce Momjian 已提交
2366
		if (isalnum(in[i]) || in[i] == ' ')
2367
			out[o++] = in[i];
B
Bruce Momjian 已提交
2368 2369 2370
		else
		{
			strcpy(&out[o], conv_to_octal(in[i]));
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
			o += 5;
		}
	}

	mylog("convert_to_pgbinary: returning %d, out='%.*s'\n", o, o, out);

	return o;
}


B
Byron Nikolaidis 已提交
2381
void
2382
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2383
{
2384 2385
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2386
				o = 0;
B
Byron Nikolaidis 已提交
2387

2388
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2389 2390 2391
	{
		if (in[i] == '+')
		{
B
Byron Nikolaidis 已提交
2392 2393 2394
			sprintf(&out[o], "%%2B");
			o += 3;
		}
B
Bruce Momjian 已提交
2395
		else if (isspace((unsigned char) in[i]))
B
Byron Nikolaidis 已提交
2396
			out[o++] = '+';
B
Bruce Momjian 已提交
2397 2398
		else if (!isalnum((unsigned char) in[i]))
		{
2399
			sprintf(&out[o], "%%%02x", (unsigned char) in[i]);
B
Byron Nikolaidis 已提交
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
			o += 3;
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}


void
2410
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2411
{
2412 2413
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2414
				o = 0;
B
Byron Nikolaidis 已提交
2415

2416
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2417
	{
B
Byron Nikolaidis 已提交
2418 2419
		if (in[i] == '+')
			out[o++] = ' ';
B
Bruce Momjian 已提交
2420 2421
		else if (in[i] == '%')
		{
B
Byron Nikolaidis 已提交
2422
			sprintf(&out[o++], "%c", conv_from_hex(&in[i]));
B
Bruce Momjian 已提交
2423
			i += 2;
B
Byron Nikolaidis 已提交
2424 2425 2426 2427 2428 2429 2430
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}

2431 2432 2433 2434
static const char *hextbl = "0123456789ABCDEF";
static int
pg_bin2hex(UCHAR *src, UCHAR *dst, int length)
{
2435 2436 2437 2438 2439 2440
	UCHAR		chr,
			   *src_wk,
			   *dst_wk;
	BOOL		backwards;
	int			i;

2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
	backwards = FALSE;
	if (dst < src)
	{
		if (dst + length > src + 1)
			return -1;
	}
	else if (dst < src + length)
		backwards = TRUE;
	if (backwards)
	{
		for (i = 0, src_wk = src + length - 1, dst_wk = dst + 2 * length - 1; i < length; i++, src_wk--)
		{
			chr = *src_wk;
			*dst_wk-- = hextbl[chr % 16];
			*dst_wk-- = hextbl[chr >> 4];
		}
	}
	else
	{
		for (i = 0, src_wk = src, dst_wk = dst; i < length; i++, src_wk++)
		{
			chr = *src_wk;
			*dst_wk++ = hextbl[chr >> 4];
			*dst_wk++ = hextbl[chr % 16];
		}
	}
	dst[2 * length] = '\0';
	return length;
}
2470

2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
/*-------
 *	1. get oid (from 'value')
 *	2. open the large object
 *	3. read from the large object (handle multiple GetData)
 *	4. close when read less than requested?  -OR-
 *		lseek/read each time
 *		handle case where application receives truncated and
 *		decides not to continue reading.
 *
 *	CURRENTLY, ONLY LONGVARBINARY is handled, since that is the only
 *	data type currently mapped to a PG_TYPE_LO.  But, if any other types
 *	are desired to map to a large object (PG_TYPE_LO), then that would
 *	need to be handled here.  For example, LONGVARCHAR could possibly be
 *	mapped to PG_TYPE_LO someday, instead of PG_TYPE_TEXT as it is now.
 *-------
 */
2487
int
2488 2489
convert_lo(StatementClass *stmt, const void *value, Int2 fCType, PTR rgbValue,
		   SDWORD cbValueMax, SDWORD *pcbValue)
2490
{
B
Bruce Momjian 已提交
2491 2492 2493 2494
	Oid			oid;
	int			retval,
				result,
				left = -1;
T
Tom Lane 已提交
2495
	BindInfoClass *bindInfo = NULL;
2496 2497
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
2498
	int			factor = (fCType == SQL_C_CHAR ? 2 : 1);
2499

2500
	/* If using SQLGetData, then current_col will be set */
B
Bruce Momjian 已提交
2501 2502
	if (stmt->current_col >= 0)
	{
2503 2504 2505
		bindInfo = &stmt->bindings[stmt->current_col];
		left = bindInfo->data_left;
	}
2506

B
Bruce Momjian 已提交
2507 2508 2509 2510
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
2511

B
Bruce Momjian 已提交
2512 2513
	if (!bindInfo || bindInfo->data_left == -1)
	{
B
Byron Nikolaidis 已提交
2514
		/* begin transaction if needed */
2515
		if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
2516
		{
B
Byron Nikolaidis 已提交
2517
			QResultClass *res;
B
Bruce Momjian 已提交
2518
			char		ok;
B
Byron Nikolaidis 已提交
2519

2520
			res = CC_send_query(conn, "BEGIN", NULL);
B
Bruce Momjian 已提交
2521 2522
			if (!res)
			{
B
Byron Nikolaidis 已提交
2523 2524 2525 2526 2527 2528
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
			ok = QR_command_successful(res);
			QR_Destructor(res);
B
Bruce Momjian 已提交
2529 2530
			if (!ok)
			{
B
Byron Nikolaidis 已提交
2531 2532 2533 2534 2535
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}

2536
			CC_set_in_trans(conn);
B
Byron Nikolaidis 已提交
2537 2538
		}

2539
		oid = atoi(value);
2540
		stmt->lobj_fd = lo_open(conn, oid, INV_READ);
B
Bruce Momjian 已提交
2541 2542
		if (stmt->lobj_fd < 0)
		{
2543
			stmt->errornumber = STMT_EXEC_ERROR;
2544
			stmt->errormsg = "Couldnt open large object for reading.";
2545 2546
			return COPY_GENERAL_ERROR;
		}
2547

B
Bruce Momjian 已提交
2548
		/* Get the size */
2549
		retval = lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END);
B
Bruce Momjian 已提交
2550 2551
		if (retval >= 0)
		{
2552
			left = lo_tell(conn, stmt->lobj_fd);
2553 2554 2555
			if (bindInfo)
				bindInfo->data_left = left;

B
Bruce Momjian 已提交
2556
			/* return to beginning */
2557
			lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET);
2558 2559
		}
	}
2560
	mylog("lo data left = %d\n", left);
2561

B
Bruce Momjian 已提交
2562
	if (left == 0)
2563
		return COPY_NO_DATA_FOUND;
2564

B
Bruce Momjian 已提交
2565 2566
	if (stmt->lobj_fd < 0)
	{
2567 2568 2569 2570
		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Large object FD undefined for multiple read.";
		return COPY_GENERAL_ERROR;
	}
2571

2572
	retval = lo_read(conn, stmt->lobj_fd, (char *) rgbValue, factor > 1 ? (cbValueMax - 1) / factor : cbValueMax);
B
Bruce Momjian 已提交
2573 2574
	if (retval < 0)
	{
2575
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
2576 2577

		/* commit transaction if needed */
2578
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
2579
		{
B
Byron Nikolaidis 已提交
2580
			QResultClass *res;
B
Bruce Momjian 已提交
2581
			char		ok;
B
Byron Nikolaidis 已提交
2582

2583
			res = CC_send_query(conn, "COMMIT", NULL);
B
Bruce Momjian 已提交
2584 2585
			if (!res)
			{
B
Byron Nikolaidis 已提交
2586 2587 2588 2589 2590 2591
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
			ok = QR_command_successful(res);
			QR_Destructor(res);
B
Bruce Momjian 已提交
2592 2593
			if (!ok)
			{
B
Byron Nikolaidis 已提交
2594 2595 2596 2597 2598
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}

2599
			CC_set_no_trans(conn);
B
Byron Nikolaidis 已提交
2600 2601
		}

2602 2603 2604 2605 2606 2607 2608
		stmt->lobj_fd = -1;

		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Error reading from large object.";
		return COPY_GENERAL_ERROR;
	}

2609 2610
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
2611 2612 2613 2614 2615 2616
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
2617
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
2618

B
Bruce Momjian 已提交
2619
	if (bindInfo && bindInfo->data_left > 0)
2620
		bindInfo->data_left -= retval;
2621

B
Bruce Momjian 已提交
2622 2623
	if (!bindInfo || bindInfo->data_left == 0)
	{
2624
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
2625 2626

		/* commit transaction if needed */
2627
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
2628
		{
B
Byron Nikolaidis 已提交
2629
			QResultClass *res;
B
Bruce Momjian 已提交
2630
			char		ok;
B
Byron Nikolaidis 已提交
2631

2632
			res = CC_send_query(conn, "COMMIT", NULL);
B
Bruce Momjian 已提交
2633 2634
			if (!res)
			{
B
Byron Nikolaidis 已提交
2635 2636 2637 2638 2639 2640
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
			ok = QR_command_successful(res);
			QR_Destructor(res);
B
Bruce Momjian 已提交
2641 2642
			if (!ok)
			{
B
Byron Nikolaidis 已提交
2643 2644 2645 2646 2647
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}

2648
			CC_set_no_trans(conn);
B
Byron Nikolaidis 已提交
2649 2650
		}

B
Bruce Momjian 已提交
2651
		stmt->lobj_fd = -1;		/* prevent further reading */
2652
	}
2653 2654

	return result;
2655
}