convert.c 74.0 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 32 33
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
34
#include <math.h>
35
#include <stdlib.h>
36
#include "statement.h"
B
Byron Nikolaidis 已提交
37
#include "qresult.h"
38 39
#include "bind.h"
#include "pgtypes.h"
40 41
#include "lobj.h"
#include "connection.h"
42
#include "pgapifunc.h"
43

44
#ifdef	__CYGWIN__
45
#define TIMEZONE_GLOBAL _timezone
46
#elif	defined(WIN32) || defined(HAVE_INT_TIMEZONE)
47
#define TIMEZONE_GLOBAL timezone
48
#endif
49

50 51 52 53
/*
 *	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
54
 *	- thomas 2000-04-03
55
 */
B
Bruce Momjian 已提交
56
char	   *mapFuncs[][2] = {
H
Hiroshi Inoue 已提交
57 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
/*	{ "ASCII",		 "ascii"	  }, built_in */
	{"CHAR", "chr($*)" },
	{"CONCAT", "textcat($*)" },
/*	{ "DIFFERENCE", "difference" }, how to ? */
	{"INSERT", "substring($1 from 1 for $2 - 1) || $4 || substring($1 from $2 + $3)" },
	{"LCASE", "lower($*)" },
	{"LEFT", "ltrunc($*)" },
	{"%2LOCATE", "strpos($2,  $1)" },	/* 2 parameters */
	{"%3LOCATE", "strpos(substring($2 from $3), $1) + $3 - 1" },	/* 3 parameters */
	{"LENGTH", "char_length($*)"},
/*	{ "LTRIM",		 "ltrim"	  }, built_in */
	{"RIGHT", "rtrunc($*)" },
	{"SPACE", "repeat('' '', $1)" },
/*	{ "REPEAT",		 "repeat"	  }, built_in */
/*	{ "REPLACE", "replace" }, ??? */
/*	{ "RTRIM",		 "rtrim"	  }, built_in */
/*	{ "SOUNDEX", "soundex" }, how to ? */
	{"SUBSTRING", "substr($*)" },
	{"UCASE", "upper($*)" },

/*	{ "ABS",		 "abs"		  }, built_in */
/*	{ "ACOS",		 "acos"		  }, built_in */
/*	{ "ASIN",		 "asin"		  }, built_in */
/*	{ "ATAN",		 "atan"		  }, built_in */
/*	{ "ATAN2",		 "atan2"	  }, bui;t_in */
	{"CEILING", "ceil($*)" },
/*	{ "COS",		 "cos" 		  }, built_in */
/*	{ "COT",		 "cot" 		  }, built_in */
/*	{ "DEGREES",		 "degrees" 	  }, built_in */
/*	{ "EXP",		 "exp" 		  }, built_in */
/*	{ "FLOOR",		 "floor" 	  }, built_in */
	{"LOG", "ln($*)" },
	{"LOG10", "log($*)" },
/*	{ "MOD",		 "mod" 		  }, built_in */
/*	{ "PI",			 "pi" 		  }, built_in */
	{"POWER", "pow($*)" },
/*	{ "RADIANS",		 "radians"	  }, built_in */
	{"%0RAND", "random()" },	/* 0 parameters */
	{"%1RAND", "(setseed($1) * .0 + random())" },	/* 1 parameters */
/*	{ "ROUND",		 "round"	  }, built_in */
/*	{ "SIGN",		 "sign"		  }, built_in */
/*	{ "SIN",		 "sin"		  }, built_in */
/*	{ "SQRT",		 "sqrt"		  }, built_in */
/*	{ "TAN",		 "tan"		  }, built_in */
	{"TRUNCATE", "trunc($*)" },

	{"CURRENT_DATE", "current_date" },
	{"CURRENT_TIME", "current_time" },
	{"CURRENT_TIMESTAMP", "current_timestamp" },
	{"CURRENT_USER", "cast(current_user as text)" },
	{"SESSION_USER", "cast(session_user as text)" },
	{"CURDATE",	 "current_date" },
	{"CURTIME",	 "current_time" },
	{"DAYNAME",	 "to_char($1, 'Day')" },
	{"DAYOFMONTH",  "cast(extract(day from $1) as integer)" },
	{"DAYOFWEEK",	 "(cast(extract(dow from $1) as integer) + 1)" },
H
Hiroshi Inoue 已提交
113
	{"DAYOFYEAR",	 "cast(extract(doy from $1) as integer)" }, 
H
Hiroshi Inoue 已提交
114 115 116 117 118 119 120 121 122
	{"HOUR",	 "cast(extract(hour from $1) as integer)" },
	{"MINUTE",	"cast(extract(minute from $1) as integer)" },
	{"MONTH",	"cast(extract(month from $1) as integer)" },
	{"MONTHNAME",	 " to_char($1, 'Month')" },
/*	{ "NOW",		 "now"		  }, built_in */
	{"QUARTER",	 "cast(extract(quarter from $1) as integer)" },
	{"SECOND",	"cast(extract(second from $1) as integer)" },
	{"WEEK",	"cast(extract(week from $1) as integer)" },
	{"YEAR",	"cast(extract(year from $1) as integer)" },
B
Bruce Momjian 已提交
123 124

/*	{ "DATABASE",	 "database"   }, */
H
Hiroshi Inoue 已提交
125 126
	{"IFNULL", "coalesce($*)" },
	{"USER", "cast(current_user as text)" },
B
Bruce Momjian 已提交
127
	{0, 0}
128 129
};

H
Hiroshi Inoue 已提交
130
static const char *mapFunction(const char *func, int param_count);
131 132
static unsigned int conv_from_octal(const unsigned char *s);
static unsigned int conv_from_hex(const unsigned char *s);
133
static char *conv_to_octal(unsigned char val);
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
/*---------
 *			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
 *---------
 */
152 153 154



155
/*
156 157 158 159
 *	TIMESTAMP <-----> SIMPLE_TIME
 *		precision support since 7.2.
 *		time zone support is unavailable(the stuff is unreliable)
 */
160 161
static BOOL
timestamp2stime(const char *str, SIMPLE_TIME *st, BOOL *bZone, int *zone)
162
{
163 164 165 166
	char		rest[64],
			   *ptr;
	int			scnt,
				i;
B
Bruce Momjian 已提交
167
#if defined(WIN32) || defined(HAVE_INT_TIMEZONE)
168
	long		timediff;
B
Bruce Momjian 已提交
169
#endif
170
	BOOL		withZone = *bZone;
171 172 173 174

	*bZone = FALSE;
	*zone = 0;
	st->fr = 0;
H
Hiroshi Inoue 已提交
175
	st->infinity = 0;
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
	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++)
			{
205
				if (!isdigit((unsigned char) rest[i]))
206 207 208 209 210 211 212 213
					break;
			}
			for (; i < 10; i++)
				rest[i] = '0';
			rest[i] = '\0';
			st->fr = atoi(&rest[1]);
			break;
		default:
214
			return TRUE;
215 216 217 218 219 220 221 222 223 224
	}
	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;
225
	if (!daylight && timediff == 0)		/* the same timezone */
226 227 228
		return TRUE;
	else
	{
229 230
		struct tm	tm,
				   *tm2;
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
		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;
246
		if (timediff == 0)		/* the same time zone */
247 248 249 250 251 252 253
			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;
254 255 256
			st->hh = tm2->tm_hour;
			st->mm = tm2->tm_min;
			st->ss = tm2->tm_sec;
257 258 259
			*bZone = TRUE;
		}
	}
260 261
#endif   /* WIN32 */
	return TRUE;
262 263
}

264 265
static BOOL
stime2timestamp(const SIMPLE_TIME *st, char *str, BOOL bZone, BOOL precision)
266
{
267 268 269
	char		precstr[16],
				zonestr[16];
	int			i;
270 271

	precstr[0] = '\0';
272 273 274 275 276 277 278 279 280 281
	if (st->infinity > 0)
	{
		strcpy(str, "Infinity");
		return TRUE;
	}
	else if (st->infinity < 0)
	{
		strcpy(str, "-Infinity");
		return TRUE;
	}
282 283 284 285 286 287 288 289 290 291 292 293 294 295
	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)
	{
296
		long		zoneint;
297 298 299 300
		struct tm	tm;
		time_t		time0;

		zoneint = TIMEZONE_GLOBAL;
301 302
		if (daylight && st->y >= 1900)
		{
303 304 305 306 307 308 309 310 311 312 313 314
			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)
315
			sprintf(zonestr, "-%02d", (int) zoneint / 3600);
316
		else
317
			sprintf(zonestr, "+%02d", -(int) zoneint / 3600);
318
	}
319
#endif   /* WIN32 */
320
	sprintf(str, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s", st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr);
321
	return TRUE;
322 323
}

324 325
/*	This is called by SQLFetch() */
int
326
copy_and_convert_field_bindinfo(StatementClass *stmt, Int4 field_type, void *value, int col)
327
{
H
Hiroshi Inoue 已提交
328 329 330
	ARDFields *opts = SC_get_ARD(stmt);
	BindInfoClass *bic = &(opts->bindings[col]);
	UInt4	offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0;
331

H
Hiroshi Inoue 已提交
332 333
	return copy_and_convert_field(stmt, field_type, value, (Int2) bic->returntype, (PTR) (bic->buffer + offset),
							 (SDWORD) bic->buflen, (SDWORD *) (bic->used + (offset >> 2)));
334 335
}

336

337 338
/*	This is called by SQLGetData() */
int
339 340
copy_and_convert_field(StatementClass *stmt, Int4 field_type, void *value, Int2 fCType,
					   PTR rgbValue, SDWORD cbValueMax, SDWORD *pcbValue)
341
{
H
Hiroshi Inoue 已提交
342
	static char *func = "copy_and_convert_field";
H
Hiroshi Inoue 已提交
343
	ARDFields	*opts = SC_get_ARD(stmt);
B
Bruce Momjian 已提交
344 345
	Int4		len = 0,
				copy_len = 0;
346
	SIMPLE_TIME st;
B
Bruce Momjian 已提交
347 348 349 350
	time_t		t = time(NULL);
	struct tm  *tim;
	int			pcbValueOffset,
				rgbValueOffset;
351
	char	   *rgbValueBindRow;
352
	const char *ptr;
B
Bruce Momjian 已提交
353
	int			bind_row = stmt->bind_row;
H
Hiroshi Inoue 已提交
354
	int			bind_size = opts->bind_size;
B
Bruce Momjian 已提交
355
	int			result = COPY_OK;
356 357 358
#ifdef HAVE_LOCALE_H
	char saved_locale[256];
#endif /* HAVE_LOCALE_H */
H
Hiroshi Inoue 已提交
359
	BOOL		changed, true_is_minus1 = FALSE;
360
	const char *neut_str = value;
361 362
	char		midtemp[2][32];
	int			mtemp_cnt = 0;
363 364
	static BindInfoClass sbic;
	BindInfoClass *pbic;
H
Hiroshi Inoue 已提交
365 366 367
#ifdef	UNICODE_SUPPORT
	BOOL	wchanged =   FALSE;
#endif /* UNICODE_SUPPORT */
368

369 370
	if (stmt->current_col >= 0)
	{
H
Hiroshi Inoue 已提交
371
		pbic = &opts->bindings[stmt->current_col];
372
		if (pbic->data_left == -2)
373 374
			pbic->data_left = (cbValueMax > 0) ? 0 : -1; /* This seems to be *
						 * needed for ADO ? */
375 376 377 378 379 380 381 382
		if (pbic->data_left == 0)
		{
			if (pbic->ttlbuf != NULL)
			{
				free(pbic->ttlbuf);
				pbic->ttlbuf = NULL;
				pbic->ttlbuflen = 0;
			}
383 384
			pbic->data_left = -2;		/* needed by ADO ? */
			return COPY_NO_DATA_FOUND;
385 386
		}
	}
387 388 389 390 391
	/*---------
	 *	rgbValueOffset is *ONLY* for character and binary data.
	 *	pcbValueOffset is for computing any pcbValue location
	 *---------
	 */
392

B
Bruce Momjian 已提交
393
	if (bind_size > 0)
394
		pcbValueOffset = rgbValueOffset = (bind_size * bind_row);
B
Bruce Momjian 已提交
395 396
	else
	{
397 398
		pcbValueOffset = bind_row * sizeof(SDWORD);
		rgbValueOffset = bind_row * cbValueMax;
399

400
	}
401 402 403

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

B
Bruce Momjian 已提交
404
	/* Initialize current date */
405 406 407 408 409
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;

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

B
Bruce Momjian 已提交
412 413
	if (!value)
	{
414
		/*
415 416
		 * handle a null just by returning SQL_NULL_DATA in pcbValue, and
		 * doing nothing to the buffer.
417
		 */
B
Bruce Momjian 已提交
418
		if (pcbValue)
H
Hiroshi Inoue 已提交
419
		{
420
			*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = SQL_NULL_DATA;
H
Hiroshi Inoue 已提交
421 422 423 424 425
			return COPY_OK;
		}
		else
		{
			stmt->errornumber = STMT_RETURN_NULL_WITHOUT_INDICATOR;
H
Hiroshi Inoue 已提交
426
			stmt->errormsg = "StrLen_or_IndPtr was a null pointer and NULL data was retrieved";	
H
Hiroshi Inoue 已提交
427 428 429
			SC_log_error(func, "", stmt);
			return	SQL_ERROR;
		}
B
Byron Nikolaidis 已提交
430 431
	}

B
Bruce Momjian 已提交
432 433 434 435 436 437 438 439 440
	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 已提交
441 442
	}

443
	/*
444
	 * First convert any specific postgres types into more useable data.
445
	 *
446 447
	 * NOTE: Conversions from PG char/varchar of a date/time/timestamp value
	 * to SQL_C_DATE,SQL_C_TIME, SQL_C_TIMESTAMP not supported
448
	 */
B
Bruce Momjian 已提交
449 450
	switch (field_type)
	{
451 452 453 454
			/*
			 * $$$ need to add parsing for date/time/timestamp strings in
			 * PG_TYPE_CHAR,VARCHAR $$$
			 */
B
Bruce Momjian 已提交
455 456 457
		case PG_TYPE_DATE:
			sscanf(value, "%4d-%2d-%2d", &st.y, &st.m, &st.d);
			break;
458

B
Bruce Momjian 已提交
459 460 461
		case PG_TYPE_TIME:
			sscanf(value, "%2d:%2d:%2d", &st.hh, &st.mm, &st.ss);
			break;
462

B
Bruce Momjian 已提交
463 464
		case PG_TYPE_ABSTIME:
		case PG_TYPE_DATETIME:
H
Hiroshi Inoue 已提交
465
		case PG_TYPE_TIMESTAMP_NO_TMZONE:
B
Bruce Momjian 已提交
466
		case PG_TYPE_TIMESTAMP:
467
			st.fr = 0;
468 469 470 471 472 473 474
			st.infinity = 0;
			if (strnicmp(value, "infinity", 8) == 0)
			{
				st.infinity = 1;
				st.m = 12;
				st.d = 31;
				st.y = 9999;
H
Hiroshi Inoue 已提交
475 476 477
				st.hh = 23;
				st.mm = 59;
				st.ss = 59;
478 479 480 481 482 483 484 485 486 487 488
			}
			if (strnicmp(value, "-infinity", 9) == 0)
			{
				st.infinity = -1;
				st.m = 0;
				st.d = 0;
				st.y = 0;
				st.hh = 0;
				st.mm = 0;
				st.ss = 0;
			}
B
Bruce Momjian 已提交
489
			if (strnicmp(value, "invalid", 7) != 0)
490
			{
491 492 493 494 495 496 497 498
				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 */
499
				timestamp2stime(value, &st, &bZone, &zone);
500
inolog("2stime fr=%d\n", st.fr);
501
			}
B
Bruce Momjian 已提交
502
			else
503 504
			{
				/*
505 506
				 * The timestamp is invalid so set something conspicuous,
				 * like the epoch
507
				 */
B
Bruce Momjian 已提交
508 509 510 511 512 513 514 515 516 517 518 519
				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:
520
			{					/* change T/F to 1/0 */
521
				char	   *s;
B
Bruce Momjian 已提交
522

523
				s = midtemp[mtemp_cnt];
H
Hiroshi Inoue 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
				switch (((char *)value)[0])
				{
					case 'f':
					case 'F':
					case 'n':
					case 'N':
					case '0':
						strcpy(s, "0");
						break;
					default:
						if (true_is_minus1)
							strcpy(s, "-1");
						else
							strcpy(s, "1");
				}
539 540
				neut_str = midtemp[mtemp_cnt];
				mtemp_cnt++;
B
Bruce Momjian 已提交
541 542 543
			}
			break;

544
			/* This is for internal use by SQLStatistics() */
B
Bruce Momjian 已提交
545 546 547 548
		case PG_TYPE_INT2VECTOR:
			{
				int			nval,
							i;
549
				const char *vp;
B
Bruce Momjian 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

				/* 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 已提交
579

580
#if 0
B
Bruce Momjian 已提交
581 582 583 584 585 586 587 588 589
				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]);
590
#endif
B
Byron Nikolaidis 已提交
591

B
Bruce Momjian 已提交
592 593 594
				/* There is no corresponding fCType for this. */
				if (pcbValue)
					*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = len;
B
Byron Nikolaidis 已提交
595

B
Bruce Momjian 已提交
596 597 598
				return COPY_OK; /* dont go any further or the data will be
								 * trashed */
			}
B
Byron Nikolaidis 已提交
599

B
Bruce Momjian 已提交
600 601 602 603 604
			/*
			 * This is a large object OID, which is used to store
			 * LONGVARBINARY objects.
			 */
		case PG_TYPE_LO:
B
Byron Nikolaidis 已提交
605

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

B
Bruce Momjian 已提交
608
		default:
B
Byron Nikolaidis 已提交
609

B
Bruce Momjian 已提交
610 611 612
			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 已提交
613 614
	}

B
Bruce Momjian 已提交
615 616 617
	/* Change default into something useable */
	if (fCType == SQL_C_DEFAULT)
	{
B
Byron Nikolaidis 已提交
618 619 620 621 622
		fCType = pgtype_to_ctype(stmt, field_type);

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

623 624
	rgbValueBindRow = (char *) rgbValue + rgbValueOffset;

H
Hiroshi Inoue 已提交
625 626 627
#ifdef	UNICODE_SUPPORT
	if (fCType == SQL_C_CHAR || fCType == SQL_C_WCHAR)
#else
B
Bruce Momjian 已提交
628
	if (fCType == SQL_C_CHAR)
H
Hiroshi Inoue 已提交
629
#endif /* UNICODE_SUPPORT */
B
Bruce Momjian 已提交
630 631
	{
		/* Special character formatting as required */
632

B
Bruce Momjian 已提交
633 634 635 636 637 638 639 640 641 642 643
		/*
		 * 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;
644

B
Bruce Momjian 已提交
645 646 647 648 649
			case PG_TYPE_TIME:
				len = 8;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.2d:%.2d:%.2d", st.hh, st.mm, st.ss);
				break;
650

B
Bruce Momjian 已提交
651 652
			case PG_TYPE_ABSTIME:
			case PG_TYPE_DATETIME:
H
Hiroshi Inoue 已提交
653
			case PG_TYPE_TIMESTAMP_NO_TMZONE:
B
Bruce Momjian 已提交
654 655 656 657 658 659
			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;
660

B
Bruce Momjian 已提交
661
			case PG_TYPE_BOOL:
H
Hiroshi Inoue 已提交
662
				len = strlen(neut_str);
B
Bruce Momjian 已提交
663 664
				if (cbValueMax > len)
				{
665
					strcpy(rgbValueBindRow, neut_str);
B
Bruce Momjian 已提交
666 667 668
					mylog("PG_TYPE_BOOL: rgbValueBindRow = '%s'\n", rgbValueBindRow);
				}
				break;
669

B
Bruce Momjian 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
				/*
				 * 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") */
685
				len = convert_pgbinary_to_char(neut_str, rgbValueBindRow, cbValueMax);
B
Bruce Momjian 已提交
686 687 688

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

B
Bruce Momjian 已提交
690
			default:
691 692 693 694 695 696
				if (stmt->current_col < 0)
				{
					pbic = &sbic;
					pbic->data_left = -1;
				}
				else
H
Hiroshi Inoue 已提交
697
					pbic = &opts->bindings[stmt->current_col];
698
				if (pbic->data_left < 0)
699
				{
H
Hiroshi Inoue 已提交
700 701 702 703 704 705 706 707 708 709
					BOOL lf_conv = SC_get_conn(stmt)->connInfo.lf_conversion;
#ifdef	UNICODE_SUPPORT
					if (fCType == SQL_C_WCHAR)
					{
						len = utf8_to_ucs2(neut_str, -1, NULL, 0);
						len *= 2;
						wchanged = changed = TRUE;
					}
					else
#endif /* UNICODE_SUPPORT */
710
					/* convert linefeeds to carriage-return/linefeed */
H
Hiroshi Inoue 已提交
711
					len = convert_linefeeds(neut_str, NULL, 0, lf_conv, &changed);
712 713
					if (cbValueMax == 0)		/* just returns length
												 * info */
714 715 716 717
					{
						result = COPY_RESULT_TRUNCATED;
						break;
					}
718 719
					if (!pbic->ttlbuf)
						pbic->ttlbuflen = 0;
720 721
					if (changed || len >= cbValueMax)
					{
722
						if (len >= (int) pbic->ttlbuflen)
723
						{
724 725
							pbic->ttlbuf = realloc(pbic->ttlbuf, len + 1);
							pbic->ttlbuflen = len + 1;
726
						}
H
Hiroshi Inoue 已提交
727 728 729 730 731 732 733 734
#ifdef	UNICODE_SUPPORT
						if (fCType == SQL_C_WCHAR)
						{
							utf8_to_ucs2(neut_str, -1, (SQLWCHAR *) pbic->ttlbuf, len / 2);
						}
						else
#endif /* UNICODE_SUPPORT */
						convert_linefeeds(neut_str, pbic->ttlbuf, pbic->ttlbuflen, lf_conv, &changed);
735
						ptr = pbic->ttlbuf;
736 737 738
					}
					else
					{
739
						if (pbic->ttlbuf)
740
						{
741 742
							free(pbic->ttlbuf);
							pbic->ttlbuf = NULL;
743
						}
744
						ptr = neut_str;
745 746 747
					}
				}
				else
748
					ptr = pbic->ttlbuf;
B
Bruce Momjian 已提交
749 750 751 752 753

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

				if (stmt->current_col >= 0)
				{
754
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
755
					{
756 757
						ptr += strlen(ptr) - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
758 759
					}
					else
760
						pbic->data_left = len;
761 762
				}

B
Bruce Momjian 已提交
763 764 765
				if (cbValueMax > 0)
				{
					copy_len = (len >= cbValueMax) ? cbValueMax - 1 : len;
766

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
#ifdef HAVE_LOCALE_H
					switch (field_type)
					{
						case PG_TYPE_FLOAT4:
						case PG_TYPE_FLOAT8:
						case PG_TYPE_NUMERIC:
						{
							struct lconv	*lc;
							char		*new_string;
							int		i, j;

							new_string = malloc( cbValueMax );
							lc = localeconv();
							for (i = 0, j = 0; ptr[i]; i++)
								if (ptr[i] == '.')
								{
									strncpy(&new_string[j], lc->decimal_point, strlen(lc->decimal_point));
									j += strlen(lc->decimal_point);
								}
								else
									new_string[j++] = ptr[i];
							new_string[j] = '\0';
 							strncpy_null(rgbValueBindRow, new_string, copy_len + 1);
							free(new_string);
 							break;
						}
						default:
						/*      Copy the data */
						strncpy_null(rgbValueBindRow, ptr, copy_len + 1);
 					}
#else /* HAVE_LOCALE_H */
B
Bruce Momjian 已提交
798
					/* Copy the data */
799 800
					memcpy(rgbValueBindRow, ptr, copy_len);
					rgbValueBindRow[copy_len] = '\0';
801
#endif /* HAVE_LOCALE_H */
802

B
Bruce Momjian 已提交
803 804
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
805
						pbic->data_left -= copy_len;
806 807
				}

B
Bruce Momjian 已提交
808 809 810 811
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
812
				if (cbValueMax > 0 && len >= cbValueMax)
B
Bruce Momjian 已提交
813
					result = COPY_RESULT_TRUNCATED;
814 815
				else
				{
816
					if (pbic->ttlbuf != NULL)
817
					{
818 819
						free(pbic->ttlbuf);
						pbic->ttlbuf = NULL;
820 821
					}
				}
822 823


B
Bruce Momjian 已提交
824 825
				mylog("    SQL_C_CHAR, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow);
				break;
B
Byron Nikolaidis 已提交
826
		}
H
Hiroshi Inoue 已提交
827 828 829 830 831 832 833 834 835 836
#ifdef	UNICODE_SUPPORT
		if (SQL_C_WCHAR == fCType && ! wchanged)
		{
			if (cbValueMax > 2 * len)
			{
				char *str = strdup(rgbValueBindRow);
				UInt4	ucount = utf8_to_ucs2(str, len, (SQLWCHAR *) rgbValueBindRow, cbValueMax / 2);
				if (cbValueMax < 2 * (SDWORD) ucount)
					result = COPY_RESULT_TRUNCATED;
				len = ucount * 2;
H
Hiroshi Inoue 已提交
837
				free(str); 
H
Hiroshi Inoue 已提交
838 839 840 841 842 843 844 845
			}
			else
			{
				len *= 2;
				result = COPY_RESULT_TRUNCATED;
			}
		}
#endif /* UNICODE_SUPPORT */
846

B
Bruce Momjian 已提交
847 848 849 850 851 852 853 854
	}
	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 已提交
855
		if (field_type == PG_TYPE_MONEY)
856 857 858 859 860 861 862 863 864
		{
			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 已提交
865

B
Bruce Momjian 已提交
866 867 868
		switch (fCType)
		{
			case SQL_C_DATE:
869
#if (ODBCVER >= 0x0300)
870
			case SQL_C_TYPE_DATE:		/* 91 */
871
#endif
B
Bruce Momjian 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884
				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;
885

B
Bruce Momjian 已提交
886
			case SQL_C_TIME:
887
#if (ODBCVER >= 0x0300)
888
			case SQL_C_TYPE_TIME:		/* 92 */
889
#endif
B
Bruce Momjian 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902
				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 已提交
903

B
Bruce Momjian 已提交
904
			case SQL_C_TIMESTAMP:
905
#if (ODBCVER >= 0x0300)
906
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
907
#endif
B
Bruce Momjian 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921
				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;
922
					ts->fraction = st.fr;
B
Bruce Momjian 已提交
923 924
				}
				break;
925

B
Bruce Momjian 已提交
926 927 928
			case SQL_C_BIT:
				len = 1;
				if (bind_size > 0)
929
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
930
				else
931
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
932

B
Bruce Momjian 已提交
933
				/*
934 935 936
				 * 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 已提交
937 938
				 */
				break;
939

B
Bruce Momjian 已提交
940 941 942 943
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				len = 1;
				if (bind_size > 0)
944
					*(SCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
945
				else
946
					*((SCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
947
				break;
948

B
Bruce Momjian 已提交
949 950 951
			case SQL_C_UTINYINT:
				len = 1;
				if (bind_size > 0)
952
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
953
				else
954
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
955
				break;
956

B
Bruce Momjian 已提交
957
			case SQL_C_FLOAT:
958 959 960 961
#ifdef HAVE_LOCALE_H
				strcpy(saved_locale, setlocale(LC_ALL, NULL));
				setlocale(LC_ALL, "C");
#endif /* HAVE_LOCALE_H */
B
Bruce Momjian 已提交
962 963
				len = 4;
				if (bind_size > 0)
964
					*(SFLOAT *) ((char *) rgbValue + (bind_row * bind_size)) = (float) atof(neut_str);
B
Bruce Momjian 已提交
965
				else
966
					*((SFLOAT *) rgbValue + bind_row) = (float) atof(neut_str);
967 968 969
#ifdef HAVE_LOCALE_H
				setlocale(LC_ALL, saved_locale);
#endif /* HAVE_LOCALE_H */
B
Bruce Momjian 已提交
970
				break;
971

B
Bruce Momjian 已提交
972
			case SQL_C_DOUBLE:
973 974 975 976
#ifdef HAVE_LOCALE_H
				strcpy(saved_locale, setlocale(LC_ALL, NULL));
				setlocale(LC_ALL, "C");
#endif /* HAVE_LOCALE_H */
B
Bruce Momjian 已提交
977 978
				len = 8;
				if (bind_size > 0)
979
					*(SDOUBLE *) ((char *) rgbValue + (bind_row * bind_size)) = atof(neut_str);
B
Bruce Momjian 已提交
980
				else
981
					*((SDOUBLE *) rgbValue + bind_row) = atof(neut_str);
982 983 984
#ifdef HAVE_LOCALE_H
				setlocale(LC_ALL, saved_locale);
#endif /* HAVE_LOCALE_H */
B
Bruce Momjian 已提交
985
				break;
986

B
Bruce Momjian 已提交
987 988 989 990
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				len = 2;
				if (bind_size > 0)
991
					*(SWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
992
				else
993
					*((SWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
994
				break;
995

B
Bruce Momjian 已提交
996 997 998
			case SQL_C_USHORT:
				len = 2;
				if (bind_size > 0)
999
					*(UWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
1000
				else
1001
					*((UWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
1002
				break;
1003

B
Bruce Momjian 已提交
1004 1005 1006 1007
			case SQL_C_SLONG:
			case SQL_C_LONG:
				len = 4;
				if (bind_size > 0)
1008
					*(SDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
1009
				else
1010
					*((SDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
1011 1012 1013 1014
				break;

			case SQL_C_ULONG:
				len = 4;
H
Hiroshi Inoue 已提交
1015
inolog("rgb=%x + %d, pcb=%x, set %s\n", rgbValue, bind_row * bind_size, pcbValue, neut_str);
B
Bruce Momjian 已提交
1016
				if (bind_size > 0)
1017
					*(UDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
1018
				else
1019
					*((UDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
1020
				break;
1021

H
Hiroshi Inoue 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
#if (ODBCVER >= 0x0300) && defined(ODBCINT64)
#ifdef WIN32
			case SQL_C_SBIGINT:
				len = 8;
				if (bind_size > 0)
					*(SQLBIGINT *) ((char *) rgbValue + (bind_row * bind_size)) = _atoi64(neut_str);
				else
					*((SQLBIGINT *) rgbValue + bind_row) = _atoi64(neut_str);
				break;

			case SQL_C_UBIGINT:
				len = 8;
				if (bind_size > 0)
					*(SQLUBIGINT *) ((char *) rgbValue + (bind_row * bind_size)) = _atoi64(neut_str);
				else
					*((SQLUBIGINT *) rgbValue + bind_row) = _atoi64(neut_str);
				break;

#endif /* WIN32 */
#endif /* ODBCINT64 */
B
Bruce Momjian 已提交
1042
			case SQL_C_BINARY:
1043

B
Bruce Momjian 已提交
1044 1045
				/* truncate if necessary */
				/* convert octal escapes to bytes */
1046

1047
				if (stmt->current_col < 0)
1048
				{
1049 1050
					pbic = &sbic;
					pbic->data_left = -1;
1051
				}
1052
				else
H
Hiroshi Inoue 已提交
1053
					pbic = &opts->bindings[stmt->current_col];
1054 1055 1056 1057 1058 1059 1060 1061 1062
				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;
1063

B
Bruce Momjian 已提交
1064 1065 1066 1067 1068 1069
				if (stmt->current_col >= 0)
				{
					/*
					 * Second (or more) call to SQLGetData so move the
					 * pointer
					 */
1070
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
1071
					{
1072 1073
						ptr += len - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
1074
					}
1075

B
Bruce Momjian 已提交
1076 1077
					/* First call to SQLGetData so initialize data_left */
					else
1078
						pbic->data_left = len;
1079

B
Bruce Momjian 已提交
1080
				}
1081

B
Bruce Momjian 已提交
1082 1083 1084
				if (cbValueMax > 0)
				{
					copy_len = (len > cbValueMax) ? cbValueMax : len;
1085

B
Bruce Momjian 已提交
1086 1087
					/* Copy the data */
					memcpy(rgbValueBindRow, ptr, copy_len);
1088

B
Bruce Momjian 已提交
1089 1090
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
1091
						pbic->data_left -= copy_len;
1092
				}
1093

B
Bruce Momjian 已提交
1094 1095 1096 1097 1098 1099
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
				if (len > cbValueMax)
					result = COPY_RESULT_TRUNCATED;
1100

1101
				if (pbic->ttlbuf)
1102
				{
1103 1104
					free(pbic->ttlbuf);
					pbic->ttlbuf = NULL;
1105
				}
B
Bruce Momjian 已提交
1106 1107 1108 1109 1110
				mylog("SQL_C_BINARY: len = %d, copy_len = %d\n", len, copy_len);
				break;

			default:
				return COPY_UNSUPPORTED_TYPE;
B
Byron Nikolaidis 已提交
1111 1112
		}
	}
1113

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

1118
	if (result == COPY_OK && stmt->current_col >= 0)
H
Hiroshi Inoue 已提交
1119
		opts->bindings[stmt->current_col].data_left = 0;
1120
	return result;
1121

1122 1123
}

1124

1125 1126 1127 1128
/*--------------------------------------------------------------------
 *	Functions/Macros to get rid of query size limit.
 *
 *	I always used the follwoing macros to convert from
1129
 *	old_statement to new_statement.  Please improve it
1130 1131 1132
 *	if you have a better way.	Hiroshi 2001/05/22
 *--------------------------------------------------------------------
 */
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

#define	FLGP_PREPARE_DUMMY_CURSOR	1L
#define	FLGP_CURSOR_CHECK_OK	(1L << 1)
#define	FLGP_SELECT_INTO		(1L << 2)
#define	FLGP_SELECT_FOR_UPDATE	(1L << 3)
typedef struct _QueryParse {
	const char	*statement;
	int		statement_type;
	UInt4		opos;
	int		from_pos;
	int		where_pos;
	UInt4		stmt_len;
	BOOL		in_quote, in_dquote, in_escape;
	char		token_save[64];
	int		token_len;
	BOOL		prev_token_end;
	BOOL		proc_no_param;
	unsigned	int declare_pos;
	UInt4		flags;
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif   /* MULTIBYTE */
}	QueryParse;

static int
QP_initialize(QueryParse *q, const StatementClass *stmt)
{
	q->statement = stmt->statement;
	q->statement_type = stmt->statement_type;
	q->opos = 0;
	q->from_pos = -1;
	q->where_pos = -1;
	q->stmt_len = (q->statement) ? strlen(q->statement) : -1;
	q->in_quote = q->in_dquote = q->in_escape = FALSE;
	q->token_save[0] = '\0';
	q->token_len = 0;
	q->prev_token_end = TRUE;
	q->proc_no_param = TRUE;
	q->declare_pos = 0;
	q->flags = 0;
#ifdef MULTIBYTE
	make_encoded_str(&q->encstr, SC_get_conn(stmt), q->statement);
#endif   /* MULTIBYTE */

	return q->stmt_len;
}

#define	FLGB_PRE_EXECUTING	1L
#define	FLGB_INACCURATE_RESULT	(1L << 1)
typedef struct _QueryBuild {
	char	*query_statement;
	UInt4	str_size_limit;
	UInt4	str_alsize;
	UInt4	npos;
	int	current_row;
	int	param_number;
	APDFields *apdopts;
	UInt4	load_stmt_len;
	UInt4	flags;
	BOOL	lf_conv;
	int	ccsc;
	int	errornumber;
	const char *errormsg;

	ConnectionClass	*conn; /* mainly needed for LO handling */
	StatementClass	*stmt; /* needed to set error info in ENLARGE_.. */ 
}	QueryBuild;

1201 1202
#define INIT_MIN_ALLOC	4096
static int
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 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
QB_initialize(QueryBuild *qb, UInt4 size, StatementClass *stmt, ConnectionClass *conn)
{
	UInt4	newsize = 0;

	qb->flags = 0;
	qb->load_stmt_len = 0;
	qb->stmt = stmt;
	qb->apdopts = NULL;
	if (conn)
		qb->conn = conn;
	else if (stmt)
	{
		qb->apdopts = SC_get_APD(stmt);
		qb->conn = SC_get_conn(stmt);
		if (stmt->pre_executing)
			qb->flags |= FLGB_PRE_EXECUTING;
	}
	else
	{
		qb->conn = NULL;
		return -1;
	}
	qb->lf_conv = qb->conn->connInfo.lf_conversion;
	qb->ccsc = qb->conn->ccsc;
		
	if (stmt)
		qb->str_size_limit = stmt->stmt_size_limit;
	else
		qb->str_size_limit = -1;
	if (qb->str_size_limit > 0)
	{
		if (size > qb->str_size_limit)
			return -1;
		newsize = qb->str_size_limit;
	}
	else 
	{
		newsize = INIT_MIN_ALLOC;
		while (newsize <= size)
			newsize *= 2;
	}
	if ((qb->query_statement = malloc(newsize)) == NULL)
	{
		qb->str_alsize = 0;
		return -1;
	}	
	qb->query_statement[0] = '\0';
	qb->str_alsize = newsize;
	qb->npos = 0;
	qb->current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row;
	qb->param_number = -1;
	qb->errornumber = 0;
	qb->errormsg = NULL;

	return newsize;
}

static int
QB_initialize_copy(QueryBuild *qb_to, const QueryBuild *qb_from, UInt4 size)
{
	memcpy(qb_to, qb_from, sizeof(QueryBuild));

	if (qb_to->str_size_limit > 0)
	{
		if (size > qb_to->str_size_limit)
			return -1;
	}
	if ((qb_to->query_statement = malloc(size)) == NULL)
	{
		qb_to->str_alsize = 0;
		return -1;
	}	
	qb_to->query_statement[0] = '\0';
	qb_to->str_alsize = size;
	qb_to->npos = 0;

	return size;
}

static void
QB_Destructor(QueryBuild *qb)
{
	if (qb->query_statement)
	{
		free(qb->query_statement);
		qb->query_statement = NULL;
		qb->str_alsize = 0;
	}
}

/*
 * New macros (Aceto)
 *--------------------
 */

#define F_OldChar(qp) \
qp->statement[qp->opos]

#define F_OldPtr(qp) \
(qp->statement + qp->opos)

#define F_OldNext(qp) \
(++qp->opos)

#define F_OldPrior(qp) \
(--qp->opos)

#define F_OldPos(qp) \
qp->opos

#define F_ExtractOldTo(qp, buf, ch, maxsize) \
do { \
	unsigned int	c = 0; \
	while (qp->statement[qp->opos] != '\0' && qp->statement[qp->opos] != ch) \
	{ \
	    buf[c++] = qp->statement[qp->opos++]; \
		if (c >= maxsize) \
			break; \
	} \
	if (qp->statement[qp->opos] == '\0') \
		return SQL_ERROR; \
	buf[c] = '\0'; \
} while (0)

#define F_NewChar(qb) \
qb->query_statement[qb->npos]

#define F_NewPtr(qb) \
(qb->query_statement + qb->npos)

#define F_NewNext(qb) \
(++qb->npos)

#define F_NewPos(qb) \
(qb->npos)


static int
convert_escape(QueryParse *qp, QueryBuild *qb);
static int
inner_process_tokens(QueryParse *qp, QueryBuild *qb);
static int
ResolveOneParam(QueryBuild *qb);
static int
processParameters(QueryParse *qp, QueryBuild *qb,
UInt4 *output_count, Int4 param_pos[][2]);

static int
enlarge_query_statement(QueryBuild *qb, unsigned int newsize)
1352
{
1353
	unsigned int newalsize = INIT_MIN_ALLOC;
1354 1355
	static char *func = "enlarge_statement";

1356
	if (qb->str_size_limit > 0 && qb->str_size_limit < (int) newsize)
1357
	{
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
		free(qb->query_statement);
		qb->query_statement = NULL;
		qb->str_alsize = 0;
		if (qb->stmt)
		{
			qb->stmt->errormsg = "Query buffer overflow in copy_statement_with_parameters";
			qb->stmt->errornumber = STMT_EXEC_ERROR;
			SC_log_error(func, "", qb->stmt);
		}
		else
		{
			qb->errormsg = "Query buffer overflow in copy_statement_with_parameters";
			qb->errornumber = STMT_EXEC_ERROR;
		}
1372 1373 1374 1375
		return -1;
	}
	while (newalsize <= newsize)
		newalsize *= 2;
1376
	if (!(qb->query_statement = realloc(qb->query_statement, newalsize)))
1377
	{
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
		qb->str_alsize = 0;
		if (qb->stmt)
		{
			qb->stmt->errormsg = "Query buffer allocate error in copy_statement_with_parameters";
			qb->stmt->errornumber = STMT_EXEC_ERROR;
		}
		else
		{
			qb->errormsg = "Query buffer allocate error in copy_statement_with_parameters";
			qb->errornumber = STMT_EXEC_ERROR;
		}
1389 1390
		return 0;
	}
1391
	qb->str_alsize = newalsize;
1392 1393 1394 1395 1396 1397 1398
	return newalsize;
}

/*----------
 *	Enlarge stmt_with_params if necessary.
 *----------
 */
1399 1400
#define ENLARGE_NEWSTATEMENT(qb, newpos) \
	if (newpos >= qb->str_alsize) \
1401
	{ \
1402
		if (enlarge_query_statement(qb, newpos) <= 0) \
1403 1404
			return SQL_ERROR; \
	}
1405

1406 1407 1408 1409
/*----------
 *	Terminate the stmt_with_params string with NULL.
 *----------
 */
1410
#define CVT_TERMINATE(qb) \
1411
do { \
1412
	qb->query_statement[qb->npos] = '\0'; \
1413
} while (0)
1414 1415 1416 1417 1418

/*----------
 *	Append a data.
 *----------
 */
1419
#define CVT_APPEND_DATA(qb, s, len) \
1420
do { \
1421 1422 1423 1424 1425
	unsigned int	newpos = qb->npos + len; \
	ENLARGE_NEWSTATEMENT(qb, newpos) \
	memcpy(&qb->query_statement[qb->npos], s, len); \
	qb->npos = newpos; \
	qb->query_statement[newpos] = '\0'; \
1426 1427
} while (0)

1428 1429 1430 1431
/*----------
 *	Append a string.
 *----------
 */
1432
#define CVT_APPEND_STR(qb, s) \
1433
do { \
1434
	unsigned int len = strlen(s); \
1435
	CVT_APPEND_DATA(qb, s, len); \
1436 1437
} while (0)

1438
/*----------
1439
 *	Append a char.
1440 1441
 *----------
 */
1442
#define CVT_APPEND_CHAR(qb, c) \
1443
do { \
1444 1445
	ENLARGE_NEWSTATEMENT(qb, qb->npos + 1); \
	qb->query_statement[qb->npos++] = c; \
1446 1447
} while (0)

1448 1449
/*----------
 *	Append a binary data.
1450
 *	Newly reqeuired size may be overestimated currently.
1451 1452
 *----------
 */
1453
#define CVT_APPEND_BINARY(qb, buf, used) \
1454
do { \
1455 1456 1457
	unsigned int	newlimit = qb->npos + 5 * used; \
	ENLARGE_NEWSTATEMENT(qb, newlimit); \
	qb->npos += convert_to_pgbinary(buf, &qb->query_statement[qb->npos], used); \
1458 1459
} while (0)

1460 1461 1462 1463
/*----------
 *
 *----------
 */
1464
#define CVT_SPECIAL_CHARS(qb, buf, used) \
1465
do { \
1466 1467
	int cnvlen = convert_special_chars(buf, NULL, used, qb->lf_conv, qb->ccsc); \
	unsigned int	newlimit = qb->npos + cnvlen; \
1468
\
1469 1470 1471
	ENLARGE_NEWSTATEMENT(qb, newlimit); \
	convert_special_chars(buf, &qb->query_statement[qb->npos], used, qb->lf_conv, qb->ccsc); \
	qb->npos += cnvlen; \
1472
} while (0)
1473 1474

/*----------
1475
 *	Check if the statement is
1476 1477
 *	SELECT ... INTO table FROM .....
 *	This isn't really a strict check but ...
1478
 *----------
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
 */
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;
1495
		case '\"':				/* double quoted table name ? */
1496 1497 1498
			do
			{
				do
1499
					while (*(++stmt) != '\"' && *stmt);
1500
				while (*stmt && *(++stmt) == '\"');
1501 1502
				while (*stmt && !isspace((unsigned char) *stmt) && *stmt != '\"')
					stmt++;
1503 1504 1505 1506 1507 1508 1509
			}
			while (*stmt == '\"');
			break;
		default:
			while (!isspace((unsigned char) *(++stmt)));
			break;
	}
1510
	if (!*stmt)
1511 1512 1513 1514 1515 1516 1517
		return FALSE;
	while (isspace((unsigned char) *(++stmt)));
	if (strnicmp(stmt, "from", 4))
		return FALSE;
	return isspace((unsigned char) stmt[4]);
}

H
Hiroshi Inoue 已提交
1518
/*----------
1519
 *	Check if the statement is
H
Hiroshi Inoue 已提交
1520 1521
 *	SELECT ... FOR UPDATE .....
 *	This isn't really a strict check but ...
1522
 *----------
H
Hiroshi Inoue 已提交
1523 1524 1525 1526 1527
 */
static BOOL
table_for_update(const char *stmt, int *endpos)
{
	const char *wstmt = stmt;
1528

H
Hiroshi Inoue 已提交
1529
	while (isspace((unsigned char) *(++wstmt)));
1530
	if (!*wstmt)
H
Hiroshi Inoue 已提交
1531 1532 1533 1534 1535 1536 1537 1538
		return FALSE;
	if (strnicmp(wstmt, "update", 6))
		return FALSE;
	wstmt += 6;
	*endpos = wstmt - stmt;
	return !wstmt[0] || isspace((unsigned char) wstmt[0]);
}

H
Hiroshi Inoue 已提交
1539
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1540
#define		my_strchr(conn, s1,c1) pg_mbschr(conn->ccsc, s1,c1)
H
Hiroshi Inoue 已提交
1541
#else
H
Hiroshi Inoue 已提交
1542
#define		my_strchr(conn, s1,c1) strchr(s1,c1)
H
Hiroshi Inoue 已提交
1543
#endif
1544 1545 1546
/*
 *	This function inserts parameters into an SQL statements.
 *	It will also modify a SELECT statement for use with declare/fetch cursors.
1547
 *	This function does a dynamic memory allocation to get rid of query size limit!
1548
 */
1549
int
1550
copy_statement_with_parameters(StatementClass *stmt)
1551
{
B
Bruce Momjian 已提交
1552
	static char *func = "copy_statement_with_parameters";
1553 1554 1555
	RETCODE		retval;
	QueryParse	query_org, *qp;
	QueryBuild	query_crt, *qb;
1556

1557
	char	   *new_statement;
H
Hiroshi Inoue 已提交
1558

1559 1560 1561 1562
	BOOL	begin_first = FALSE, prepare_dummy_cursor = FALSE;
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
	int		current_row;
B
Bruce Momjian 已提交
1563

1564
	if (!stmt->statement)
B
Bruce Momjian 已提交
1565
	{
B
Byron Nikolaidis 已提交
1566
		SC_log_error(func, "No statement string", stmt);
1567
		return SQL_ERROR;
B
Byron Nikolaidis 已提交
1568
	}
1569

1570 1571 1572 1573 1574 1575 1576 1577
	current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row;
	qp = &query_org;
	QP_initialize(qp, stmt);

	if (ci->disallow_premature)
		prepare_dummy_cursor = stmt->pre_executing;
	if (prepare_dummy_cursor);
		qp->flags |= FLGP_PREPARE_DUMMY_CURSOR;
1578 1579


1580 1581 1582 1583 1584 1585 1586
#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)
1587
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1588 1589 1590 1591
	else if (stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY)
	{
		if (stmt->parse_status == STMT_PARSE_NONE)
			parse_statement(stmt);
H
Hiroshi Inoue 已提交
1592
		/*if (stmt->parse_status != STMT_PARSE_COMPLETE)
1593
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
H
Hiroshi Inoue 已提交
1594
		else*/ if (!stmt->updatable)
1595
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1596
		else
1597
		{
1598 1599
			qp->from_pos = stmt->from_pos;
			qp->where_pos = stmt->where_pos;
1600
		}
1601
	}
H
Hiroshi Inoue 已提交
1602 1603 1604 1605
#else
	stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
	if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN)
		stmt->options.cursor_type = SQL_CURSOR_FORWARD_ONLY;
1606
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1607 1608 1609 1610

	/* 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);
1611 1612 1613 1614 1615 1616 1617 1618 1619
	if (stmt->stmt_with_params)
	{
		free(stmt->stmt_with_params);
		stmt->stmt_with_params = NULL;
	}
	qb = &query_crt;
	if (QB_initialize(qb, qp->stmt_len, stmt, NULL) < 0)
		return SQL_ERROR;
	new_statement = qb->query_statement;
H
Hiroshi Inoue 已提交
1620

1621 1622 1623 1624 1625 1626 1627 1628 1629
	stmt->miscinfo = 0;
	/* 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)
			{
1630 1631 1632 1633 1634
				if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1))
				{
					strcpy(new_statement, "BEGIN;");
					begin_first = TRUE;
				}
1635 1636 1637
			}
			else if (ci->drivers.use_declarefetch)
				SC_set_fetchcursor(stmt);
H
Hiroshi Inoue 已提交
1638
			sprintf(new_statement, "%sdeclare %s cursor for ",
1639
					new_statement, stmt->cursor_name);
1640 1641 1642
			qb->npos = strlen(new_statement);
			qp->flags |= FLGP_CURSOR_CHECK_OK;
			qp->declare_pos = qb->npos;
1643 1644
		}
	}
1645 1646

	for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++)
B
Bruce Momjian 已提交
1647
	{
1648 1649
		retval = inner_process_tokens(qp, qb);
		if (SQL_ERROR == retval)
1650
		{
1651 1652 1653 1654 1655 1656 1657 1658
			if (0 == stmt->errornumber)
			{
				stmt->errornumber = qb->errornumber;
				stmt->errormsg = qb->errormsg;
			}
			SC_log_error(func, "", stmt);
			QB_Destructor(qb);
			return retval;
1659
		}
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
	}
	/* make sure new_statement is always null-terminated */
	CVT_TERMINATE(qb);

	new_statement = qb->query_statement;
	stmt->statement_type = qp->statement_type;
	stmt->inaccurate_result = (0 != (qb->flags & FLGB_INACCURATE_RESULT));
	if (0 != (qp->flags & FLGP_SELECT_INTO))
	{
		SC_no_pre_executable(stmt);
		SC_no_fetchcursor(stmt);
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
	}
	if (0 != (qp->flags & FLGP_SELECT_FOR_UPDATE))
	{
		SC_no_fetchcursor(stmt);
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
	}

	if (conn->DriverToDataSource != NULL)
	{
		int			length = strlen(new_statement);

		conn->DriverToDataSource(conn->translation_option,
								 SQL_CHAR,
								 new_statement, length,
								 new_statement, length, NULL,
								 NULL, 0, NULL);
	}

#ifdef	DRIVER_CURSOR_IMPLEMENT
	if (!stmt->load_statement && qp->from_pos >= 0)
	{
		UInt4	npos = qb->load_stmt_len;

		if (0 == npos)
			npos = qb->npos;
		stmt->load_statement = malloc(npos + 1);
		memcpy(stmt->load_statement, new_statement, npos);
		if (stmt->load_statement[npos - 1] == ';')
			stmt->load_statement[npos - 1] = '\0';
		else
1702
			stmt->load_statement[npos] = '\0';
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
	}
#endif   /* DRIVER_CURSOR_IMPLEMENT */
	if (prepare_dummy_cursor && SC_is_pre_executable(stmt))
	{
		char		fetchstr[128];

		sprintf(fetchstr, ";fetch backward in %s;close %s;",
				stmt->cursor_name, stmt->cursor_name);
		if (begin_first && CC_is_in_autocommit(conn))
			strcat(fetchstr, "COMMIT;");
		CVT_APPEND_STR(qb, fetchstr);
		stmt->inaccurate_result = TRUE;
	}

	stmt->stmt_with_params = qb->query_statement;
	return SQL_SUCCESS;
}

static int
inner_process_tokens(QueryParse *qp, QueryBuild *qb)
{
	static char *func = "inner_process_tokens";
	BOOL	lf_conv = qb->lf_conv;

	RETCODE	retval;
	char	   oldchar;

	if (qp->from_pos == (Int4) qp->opos)
	{
		CVT_APPEND_STR(qb, ", CTID, OID ");
	}
	else if (qp->where_pos == (Int4) qp->opos)
		qb->load_stmt_len = qb->npos;
1736
#ifdef MULTIBYTE
1737 1738 1739 1740 1741 1742
	oldchar = encoded_byte_check(&qp->encstr, qp->opos);
	if (ENCODE_STATUS(qp->encstr) != 0)
	{
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
1743

1744 1745 1746
	/*
	 * From here we are guaranteed to handle a 1-byte character.
	 */
H
Hiroshi Inoue 已提交
1747
#else
1748
	oldchar = qp->statement[qp->opos];
1749
#endif
1750

1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
	if (qp->in_escape)			/* escape check */
	{
		qp->in_escape = FALSE;
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
	else if (qp->in_quote || qp->in_dquote) /* quote/double quote check */
	{
		if (oldchar == '\\')
			qp->in_escape = TRUE;
		else if (oldchar == '\'' && qp->in_quote)
			qp->in_quote = FALSE;
		else if (oldchar == '\"' && qp->in_dquote)
			qp->in_dquote = FALSE;
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
1768

1769 1770 1771 1772 1773 1774 1775 1776
	/*
	 * From here we are guranteed to be in neither an escape, a quote
	 * nor a double quote.
	 */
	/* Squeeze carriage-return/linefeed pairs to linefeed only */
	else if (lf_conv && oldchar == '\r' && qp->opos + 1 < qp->stmt_len &&
			qp->statement[qp->opos + 1] == '\n')
		return SQL_SUCCESS;
1777

1778 1779 1780 1781 1782 1783 1784
	/*
	 * Handle literals (date, time, timestamp) and ODBC scalar
	 * functions
	 */
	else if (oldchar == '{')
	{
		if (SQL_ERROR == convert_escape(qp, qb))
B
Bruce Momjian 已提交
1785
		{
1786
			if (0 == qb->errornumber)
H
Hiroshi Inoue 已提交
1787
			{
1788 1789
				qb->errornumber = STMT_EXEC_ERROR;
				qb->errormsg = "ODBC escape convert error";
1790
			}
1791 1792
			mylog("%s convert_escape error\n", func);
			return SQL_ERROR;
1793
		}
1794 1795 1796 1797 1798 1799 1800 1801
		if (isalnum(F_OldPtr(qp)[1]))
			CVT_APPEND_CHAR(qb, ' ');
		return SQL_SUCCESS;
	}
	/* End of an escape sequence */
	else if (oldchar == '}')
	{
		if (qp->statement_type == STMT_TYPE_PROCCALL)
1802
		{
1803 1804
			if (qp->proc_no_param)
				CVT_APPEND_STR(qb, "()");
1805
		}
1806 1807 1808 1809
		else if (!isspace(F_OldPtr(qp)[1]))
			CVT_APPEND_CHAR(qb, ' ');
		return SQL_SUCCESS;
	}
1810

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
	/*
	 * 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.
	 */
	else if (oldchar != '?')
	{
		if (oldchar == '\'')
			qp->in_quote = TRUE;
		else if (oldchar == '\\')
			qp->in_escape = TRUE;
		else if (oldchar == '\"')
			qp->in_dquote = TRUE;
B
Bruce Momjian 已提交
1824 1825
		else
		{
1826
			if (isspace((unsigned char) oldchar))
1827
			{
1828
				if (!qp->prev_token_end)
H
Hiroshi Inoue 已提交
1829
				{
1830 1831 1832
					qp->prev_token_end = TRUE;
					qp->token_save[qp->token_len] = '\0';
					if (qp->token_len == 4)
H
Hiroshi Inoue 已提交
1833
					{
1834 1835
						if (0 != (qp->flags & FLGP_CURSOR_CHECK_OK) &&
							into_table_from(&qp->statement[qp->opos - qp->token_len]))
H
Hiroshi Inoue 已提交
1836
						{
1837 1838 1839 1840 1841
							qp->flags |= FLGP_SELECT_INTO;
							qp->flags &= ~FLGP_CURSOR_CHECK_OK;
							qp->statement_type = STMT_TYPE_CREATE;
							memmove(qb->query_statement, qb->query_statement + qp->declare_pos, qb->npos - qp->declare_pos);
							qb->npos -= qp->declare_pos;
H
Hiroshi Inoue 已提交
1842
						}
1843 1844 1845 1846
					}
					if (qp->token_len == 3)
					{
						int			endpos;
1847

1848 1849 1850 1851 1852 1853 1854
						if (0 != (qp->flags & FLGP_CURSOR_CHECK_OK) &&
							strnicmp(qp->token_save, "for", 3) == 0 &&
							table_for_update(&qp->statement[qp->opos], &endpos))
						{
							qp->flags |= FLGP_SELECT_FOR_UPDATE;
							qp->flags &= ~FLGP_CURSOR_CHECK_OK;
							if (qp->flags & FLGP_PREPARE_DUMMY_CURSOR)
H
Hiroshi Inoue 已提交
1855
							{
1856 1857 1858 1859 1860 1861 1862
								qb->npos -= 4;
								qp->opos += endpos;
							}
							else
							{
								memmove(qb->query_statement, qb->query_statement + qp->declare_pos, qb->npos - qp->declare_pos);
								qb->npos -= qp->declare_pos;
H
Hiroshi Inoue 已提交
1863 1864
							}
						}
1865
					}
H
Hiroshi Inoue 已提交
1866
				}
1867
			}
1868
			else if (qp->prev_token_end)
1869
			{
1870 1871 1872
				qp->prev_token_end = FALSE;
				qp->token_save[0] = oldchar;
				qp->token_len = 1;
1873
			}
1874 1875
			else if (qp->token_len + 1 < sizeof(qp->token_save))
				qp->token_save[qp->token_len++] = oldchar;
1876
		}
1877 1878 1879
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
1880

1881 1882 1883 1884 1885 1886 1887 1888 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 1916 1917 1918 1919 1920
	/*
	 * Its a '?' parameter alright
	 */
	if (retval = ResolveOneParam(qb), retval < 0)
		return retval;

	return SQL_SUCCESS;
}

static int
ResolveOneParam(QueryBuild *qb)
{
	const char *func = "ResolveOneParam";

	ConnectionClass *conn = qb->conn;
	ConnInfo   *ci = &(conn->connInfo);
	APDFields *opts = qb->apdopts;

	int		param_number;
	char		param_string[128], tmp[256],
			cbuf[PG_NUMERIC_MAX_PRECISION * 2]; /* seems big enough to handle the data in this function */
	Int2		param_ctype, param_sqltype;
	SIMPLE_TIME	st;
	time_t		t;
	struct tm	*tim;
	SDWORD		used;
	char		*buffer, *buf, *allocbuf;
	Oid		lobj_oid;
	int		lobj_fd, retval;
	UInt4	offset = opts->param_offset_ptr ? *opts->param_offset_ptr : 0;
	UInt4	current_row = qb->current_row;

	/*
	 * Its a '?' parameter alright
	 */
	param_number = ++qb->param_number;

	if (param_number >= opts->allocated)
	{
		if (0 != (qb->flags & FLGB_PRE_EXECUTING))
B
Bruce Momjian 已提交
1921
		{
1922 1923 1924
			CVT_APPEND_STR(qb, "NULL");
			qb->flags |= FLGB_INACCURATE_RESULT;
			return SQL_SUCCESS;
1925
		}
B
Bruce Momjian 已提交
1926 1927
		else
		{
1928 1929 1930 1931
			CVT_APPEND_CHAR(qb, '?');
			return SQL_SUCCESS;
		}
	}
1932

1933 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
	/* Assign correct buffers based on data at exec param or not */
	if (opts->parameters[param_number].data_at_exec)
	{
		used = opts->parameters[param_number].EXEC_used ? *opts->parameters[param_number].EXEC_used : SQL_NTS;
		buffer = opts->parameters[param_number].EXEC_buffer;
	}
	else
	{
		UInt4	bind_size = opts->param_bind_type;
		UInt4	ctypelen;

		buffer = opts->parameters[param_number].buffer + offset;
		if (current_row > 0)
		{
			if (bind_size > 0)
				buffer += (bind_size * current_row);
			else if (ctypelen = ctype_length(opts->parameters[param_number].CType), ctypelen > 0)
				buffer += current_row * ctypelen;
			else 
				buffer += current_row * opts->parameters[param_number].buflen;
		}
		if (opts->parameters[param_number].used)
		{
			UInt4	p_offset = offset;
			if (bind_size > 0)
				p_offset = offset + bind_size * current_row;
H
Hiroshi Inoue 已提交
1959
			else
1960 1961
				p_offset = offset + sizeof(SDWORD) * current_row;
			used = *(SDWORD *)((char *)opts->parameters[param_number].used + p_offset);
1962
		}
1963 1964 1965
		else
			used = SQL_NTS;
	}	
1966

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
	/* Handle NULL parameter data */
	if (used == SQL_NULL_DATA)
	{
		CVT_APPEND_STR(qb, "NULL");
		return SQL_SUCCESS;
	}

	/*
	 * If no buffer, and it's not null, then what the hell is it? Just
	 * leave it alone then.
	 */
	if (!buffer)
	{
		if (0 != (qb->flags & FLGB_PRE_EXECUTING))
B
Bruce Momjian 已提交
1981
		{
1982 1983 1984
			CVT_APPEND_STR(qb, "NULL");
			qb->flags |= FLGB_INACCURATE_RESULT;
			return SQL_SUCCESS;
1985
		}
1986
		else
B
Bruce Momjian 已提交
1987
		{
1988 1989
			CVT_APPEND_CHAR(qb, '?');
			return SQL_SUCCESS;
1990
		}
1991
	}
1992

1993 1994
	param_ctype = opts->parameters[param_number].CType;
	param_sqltype = opts->parameters[param_number].SQLType;
B
Bruce Momjian 已提交
1995

1996 1997
	mylog("%s: from(fcType)=%d, to(fSqlType)=%d\n", func,
				param_ctype, param_sqltype);
B
Bruce Momjian 已提交
1998

1999 2000 2001
	/* replace DEFAULT with something we can use */
	if (param_ctype == SQL_C_DEFAULT)
		param_ctype = sqltype_to_default_ctype(param_sqltype);
2002

2003 2004 2005 2006 2007 2008 2009 2010 2011
	allocbuf = buf = NULL;
	param_string[0] = '\0';
	cbuf[0] = '\0';
	memset(&st, 0, sizeof(st));
	t = time(NULL);
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;
2012

2013 2014 2015 2016 2017 2018 2019
	/* Convert input C type to a neutral format */
	switch (param_ctype)
	{
		case SQL_C_BINARY:
		case SQL_C_CHAR:
			buf = buffer;
			break;
2020

H
Hiroshi Inoue 已提交
2021
#ifdef	UNICODE_SUPPORT
2022 2023 2024 2025
		case SQL_C_WCHAR:
			buf = allocbuf = ucs2_to_utf8((SQLWCHAR *) buffer, used / 2, &used);
			used *= 2;
			break;
H
Hiroshi Inoue 已提交
2026 2027
#endif /* UNICODE_SUPPORT */

2028 2029
		case SQL_C_DOUBLE:
			sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
2030
						*((SDOUBLE *) buffer));
2031
			break;
2032

2033 2034 2035 2036
		case SQL_C_FLOAT:
			sprintf(param_string, "%.6g",
					*((SFLOAT *) buffer));
			break;
2037

2038 2039 2040 2041 2042
		case SQL_C_SLONG:
		case SQL_C_LONG:
			sprintf(param_string, "%ld",
					*((SDWORD *) buffer));
			break;
2043

H
Hiroshi Inoue 已提交
2044 2045
#if (ODBCVER >= 0x0300) && defined(ODBCINT64)
#ifdef WIN32
2046 2047 2048 2049
		case SQL_C_SBIGINT:
			sprintf(param_string, "%I64d",
					*((SQLBIGINT *) buffer));
			break;
H
Hiroshi Inoue 已提交
2050

2051 2052 2053 2054
		case SQL_C_UBIGINT:
			sprintf(param_string, "%I64u",
					*((SQLUBIGINT *) buffer));
			break;
H
Hiroshi Inoue 已提交
2055 2056 2057

#endif /* WIN32 */
#endif /* ODBCINT64 */
2058 2059 2060 2061 2062
		case SQL_C_SSHORT:
		case SQL_C_SHORT:
			sprintf(param_string, "%d",
					*((SWORD *) buffer));
			break;
2063

2064 2065 2066 2067 2068
		case SQL_C_STINYINT:
		case SQL_C_TINYINT:
			sprintf(param_string, "%d",
					*((SCHAR *) buffer));
			break;
2069

2070 2071 2072 2073
		case SQL_C_ULONG:
			sprintf(param_string, "%lu",
					*((UDWORD *) buffer));
			break;
2074

2075 2076 2077 2078
		case SQL_C_USHORT:
			sprintf(param_string, "%u",
					*((UWORD *) buffer));
			break;
2079

2080 2081 2082 2083
		case SQL_C_UTINYINT:
			sprintf(param_string, "%u",
					*((UCHAR *) buffer));
			break;
2084

2085 2086 2087
		case SQL_C_BIT:
			{
				int			i = *((UCHAR *) buffer);
2088

B
Bruce Momjian 已提交
2089 2090
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
2091
			}
2092

2093
		case SQL_C_DATE:
2094
#if (ODBCVER >= 0x0300)
2095
		case SQL_C_TYPE_DATE:		/* 91 */
2096
#endif
2097 2098
			{
				DATE_STRUCT *ds = (DATE_STRUCT *) buffer;
2099

2100 2101 2102
				st.m = ds->month;
				st.d = ds->day;
				st.y = ds->year;
2103

2104 2105
				break;
			}
2106

2107
		case SQL_C_TIME:
2108
#if (ODBCVER >= 0x0300)
2109
		case SQL_C_TYPE_TIME:		/* 92 */
2110
#endif
2111 2112
			{
				TIME_STRUCT *ts = (TIME_STRUCT *) buffer;
2113

2114 2115 2116
				st.hh = ts->hour;
				st.mm = ts->minute;
				st.ss = ts->second;
2117

2118 2119
				break;
			}
2120

2121
		case SQL_C_TIMESTAMP:
2122
#if (ODBCVER >= 0x0300)
2123
		case SQL_C_TYPE_TIMESTAMP:	/* 93 */
2124
#endif
2125 2126
			{
				TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer;
2127

2128 2129 2130 2131 2132 2133 2134
				st.m = tss->month;
				st.d = tss->day;
				st.y = tss->year;
				st.hh = tss->hour;
				st.mm = tss->minute;
				st.ss = tss->second;
				st.fr = tss->fraction;
2135

2136
				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);
2137

2138
				break;
2139

2140 2141 2142 2143 2144 2145 2146 2147
			}
		default:
			/* error */
			qb->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters";
			qb->errornumber = STMT_NOT_IMPLEMENTED_ERROR;
			CVT_TERMINATE(qb);	/* just in case */
			return SQL_ERROR;
	}
2148

2149 2150 2151 2152
	/*
	 * Now that the input data is in a neutral format, convert it to
	 * the desired output format (sqltype)
	 */
2153

2154 2155 2156 2157 2158
	switch (param_sqltype)
	{
		case SQL_CHAR:
		case SQL_VARCHAR:
		case SQL_LONGVARCHAR:
H
Hiroshi Inoue 已提交
2159
#ifdef	UNICODE_SUPPORT
2160 2161 2162
		case SQL_WCHAR:
		case SQL_WVARCHAR:
		case SQL_WLONGVARCHAR:
H
Hiroshi Inoue 已提交
2163
#endif /* UNICODE_SUPPORT */
2164

2165
			CVT_APPEND_CHAR(qb, '\'');	/* Open Quote */
2166

2167 2168 2169
			/* it was a SQL_C_CHAR */
			if (buf)
				CVT_SPECIAL_CHARS(qb, buf, used);
2170

2171 2172 2173
			/* it was a numeric type */
			else if (param_string[0] != '\0')
				CVT_APPEND_STR(qb, param_string);
2174

2175 2176 2177 2178 2179
			/* 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);
2180

2181 2182
				CVT_APPEND_STR(qb, tmp);
			}
2183

2184
			CVT_APPEND_CHAR(qb, '\'');	/* Close Quote */
2185

2186
			break;
2187

2188
		case SQL_DATE:
2189
#if (ODBCVER >= 0x0300)
2190
		case SQL_TYPE_DATE:	/* 91 */
2191
#endif
2192 2193 2194 2195 2196
			if (buf)
			{				/* copy char data to time */
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2197

2198
			sprintf(tmp, "'%.4d-%.2d-%.2d'::date", st.y, st.m, st.d);
2199

2200 2201
			CVT_APPEND_STR(qb, tmp);
			break;
2202

2203
		case SQL_TIME:
2204
#if (ODBCVER >= 0x0300)
2205
		case SQL_TYPE_TIME:	/* 92 */
2206
#endif
2207 2208 2209 2210 2211
			if (buf)
			{				/* copy char data to time */
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2212

2213
			sprintf(tmp, "'%.2d:%.2d:%.2d'::time", st.hh, st.mm, st.ss);
2214

2215 2216
			CVT_APPEND_STR(qb, tmp);
			break;
2217

2218
		case SQL_TIMESTAMP:
2219
#if (ODBCVER >= 0x0300)
2220
		case SQL_TYPE_TIMESTAMP:	/* 93 */
2221
#endif
2222

2223 2224 2225 2226 2227
			if (buf)
			{
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2228

2229 2230 2231 2232 2233 2234 2235 2236
			/*
			 * sprintf(tmp, "'%.4d-%.2d-%.2d %.2d:%.2d:%.2d'", st.y,
			 * st.m, st.d, st.hh, st.mm, st.ss);
			 */
			tmp[0] = '\'';
			/* Time zone stuff is unreliable */
			stime2timestamp(&st, tmp + 1, USE_ZONE, PG_VERSION_GE(conn, 7.2));
			strcat(tmp, "'::timestamp");
2237

2238
			CVT_APPEND_STR(qb, tmp);
2239

2240
			break;
2241

2242 2243 2244 2245
		case SQL_BINARY:
		case SQL_VARBINARY:/* non-ascii characters should be
							* converted to octal */
			CVT_APPEND_CHAR(qb, '\'');	/* Open Quote */
2246

2247
			mylog("SQL_VARBINARY: about to call convert_to_pgbinary, used = %d\n", used);
2248

2249
			CVT_APPEND_BINARY(qb, buf, used);
2250

2251
			CVT_APPEND_CHAR(qb, '\'');	/* Close Quote */
B
Byron Nikolaidis 已提交
2252

2253
			break;
2254

2255
		case SQL_LONGVARBINARY:
B
Bruce Momjian 已提交
2256

2257 2258 2259 2260 2261 2262
			if (opts->parameters[param_number].data_at_exec)
				lobj_oid = opts->parameters[param_number].lobj_oid;
			else
			{
				/* begin transaction if needed */
				if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
2263
				{
2264
					if (!CC_begin(conn))
B
Bruce Momjian 已提交
2265
					{
2266 2267
						qb->errormsg = "Could not begin (in-line) a transaction";
						qb->errornumber = STMT_EXEC_ERROR;
B
Byron Nikolaidis 已提交
2268 2269
						return SQL_ERROR;
					}
2270
				}
B
Bruce Momjian 已提交
2271

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
				/* store the oid */
				lobj_oid = lo_creat(conn, INV_READ | INV_WRITE);
				if (lobj_oid == 0)
				{
					qb->errornumber = STMT_EXEC_ERROR;
					qb->errormsg = "Couldnt create (in-line) large object.";
					return SQL_ERROR;
				}

				/* store the fd */
				lobj_fd = lo_open(conn, lobj_oid, INV_WRITE);
				if (lobj_fd < 0)
				{
					qb->errornumber = STMT_EXEC_ERROR;
					qb->errormsg = "Couldnt open (in-line) large object for writing.";
					return SQL_ERROR;
				}
B
Byron Nikolaidis 已提交
2289

2290
				retval = lo_write(conn, lobj_fd, buffer, used);
2291

2292
				lo_close(conn, lobj_fd);
2293

2294 2295 2296 2297
				/* commit transaction if needed */
				if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
				{
					if (!CC_commit(conn))
B
Bruce Momjian 已提交
2298
					{
2299 2300 2301
						qb->errormsg = "Could not commit (in-line) a transaction";
						qb->errornumber = STMT_EXEC_ERROR;
						return SQL_ERROR;
B
Bruce Momjian 已提交
2302 2303
					}
				}
2304
			}
2305

2306 2307 2308 2309 2310 2311 2312
			/*
			 * 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);
			CVT_APPEND_STR(qb, param_string);
2313

2314
			break;
B
Bruce Momjian 已提交
2315

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

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
		case SQL_REAL:
			if (buf)
				my_strcpy(param_string, sizeof(param_string), buf, used);
			sprintf(tmp, "'%s'::float4", param_string);
			CVT_APPEND_STR(qb, tmp);
			break;
		case SQL_FLOAT:
		case SQL_DOUBLE:
			if (buf)
				my_strcpy(param_string, sizeof(param_string), buf, used);
			sprintf(tmp, "'%s'::float8", param_string);
			CVT_APPEND_STR(qb, tmp);
			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);
			CVT_APPEND_STR(qb, cbuf);
			break;
B
Bruce Momjian 已提交
2348
			default:			/* a numeric type or SQL_BIT */
2349 2350
			if (param_sqltype == SQL_BIT)
				CVT_APPEND_CHAR(qb, '\'');		/* Open Quote */
B
Bruce Momjian 已提交
2351

2352 2353 2354
			if (buf)
			{
				switch (used)
B
Bruce Momjian 已提交
2355
				{
2356 2357 2358 2359 2360 2361 2362
					case SQL_NULL_DATA:
						break;
					case SQL_NTS:
						CVT_APPEND_STR(qb, buf);
						break;
					default:
						CVT_APPEND_DATA(qb, buf, used);
B
Bruce Momjian 已提交
2363
				}
2364 2365 2366
			}
			else
				CVT_APPEND_STR(qb, param_string);
B
Bruce Momjian 已提交
2367

2368 2369
			if (param_sqltype == SQL_BIT)
				CVT_APPEND_CHAR(qb, '\'');		/* Close Quote */
B
Bruce Momjian 已提交
2370

2371 2372
			break;
	}
H
Hiroshi Inoue 已提交
2373
#ifdef	UNICODE_SUPPORT
2374 2375
	if (allocbuf)
		free(allocbuf);
H
Hiroshi Inoue 已提交
2376
#endif /* UNICODE_SUPPORT */
2377 2378 2379
	return SQL_SUCCESS;
}

2380

H
Hiroshi Inoue 已提交
2381 2382
static const char *
mapFunction(const char *func, int param_count)
2383
{
B
Bruce Momjian 已提交
2384
	int			i;
2385 2386

	for (i = 0; mapFuncs[i][0]; i++)
H
Hiroshi Inoue 已提交
2387 2388 2389 2390
	{
		if (mapFuncs[i][0][0] == '%')
		{
			if (mapFuncs[i][0][1] - '0' == param_count &&
H
Hiroshi Inoue 已提交
2391
			    !stricmp(mapFuncs[i][0] + 2, func))
H
Hiroshi Inoue 已提交
2392 2393 2394
				return mapFuncs[i][1];
		}
		else if (!stricmp(mapFuncs[i][0], func))
2395
			return mapFuncs[i][1];
H
Hiroshi Inoue 已提交
2396
	}
2397 2398 2399

	return NULL;
}
2400

2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
/*
 * processParameters()
 * Process function parameters and work with embedded escapes sequences.
 */
static int
processParameters(QueryParse *qp, QueryBuild *qb,
		UInt4 *output_count, Int4 param_pos[][2])
{
	static const char *func = "processParameters";
	int retval, innerParenthesis, param_count;
	BOOL stop;

	/* begin with outer '(' */
	innerParenthesis = 0;
	param_count = 0;
	stop = FALSE;
	for (; F_OldPos(qp) < qp->stmt_len; F_OldNext(qp))
	{
		retval = inner_process_tokens(qp, qb);
		if (retval == SQL_ERROR)
			return retval;
#ifdef MULTIBYTE
		if (ENCODE_STATUS(qp->encstr) != 0)
			continue;
#endif
		if (qp->in_dquote || qp->in_quote || qp->in_escape)
			continue;

		switch (F_OldChar(qp))
		{
			case ',':
				if (1 == innerParenthesis)
				{
					param_pos[param_count][1] = F_NewPos(qb) - 2;
					param_count++;
					param_pos[param_count][0] = F_NewPos(qb);
					param_pos[param_count][1] = -1;
				}
				break;
			case '(':
				if (0 == innerParenthesis)
				{
					param_pos[param_count][0] = F_NewPos(qb);
					param_pos[param_count][1] = -1;
				}
				innerParenthesis++;
				break;
     
			case ')':
				innerParenthesis--;
				if (0 == innerParenthesis)
				{
					param_pos[param_count][1] = F_NewPos(qb) - 2;
					param_count++;
					param_pos[param_count][0] =
					param_pos[param_count][1] = -1;
				}
				if (output_count)
					*output_count = F_NewPos(qb);
				break;

			case '}':
				stop = (0 == innerParenthesis);
				break;
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 2491 2492 2493 2494 2495 2496 2497
		}
		if (stop) /* returns with the last } position */
			break;
	}
	if (param_pos[param_count][0] >= 0)
	{
		mylog("%s closing ) not found %d\n", func, innerParenthesis);
		qb->errornumber = STMT_EXEC_ERROR;
		qb->errormsg = "processParameters closing ) not found";
		return SQL_ERROR;
	}
	else if (1 == param_count) /* the 1 parameter is really valid ? */
	{
		BOOL	param_exist = FALSE;
		int	i;

		for (i = param_pos[0][0]; i <= param_pos[0][1]; i++)
		{
			if (!isspace(qb->query_statement[i]))
			{
				param_exist = TRUE;
				break;
			}
		}
		if (!param_exist)
		{
			param_pos[0][0] = param_pos[0][1] = -1;
		}
	}

	return SQL_SUCCESS;
}
H
Hiroshi Inoue 已提交
2498

2499
/*
2500 2501
 * convert_escape()
 * This function doesn't return a pointer to static memory any longer !
2502
 */
2503 2504
static int
convert_escape(QueryParse *qp, QueryBuild *qb)
2505
{
2506 2507 2508 2509 2510
	static const char *func = "convert_escape";
	RETCODE	retval = SQL_SUCCESS;
	char		buf[1024], key[65];
	unsigned char	ucv;
	UInt4		prtlen;
H
Hiroshi Inoue 已提交
2511
 
2512 2513
	if (F_OldChar(qp) == '{') /* skip the first { */
		F_OldNext(qp);
2514
	/* Separate off the key, skipping leading and trailing whitespace */
2515 2516 2517 2518 2519 2520
	while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv))
		F_OldNext(qp);
	/*
	 * procedure calls
	 */
	if (qp->statement_type == STMT_TYPE_PROCCALL)
2521
	{
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
		int	lit_call_len = 4;
		ConnectionClass *conn = qb->conn;

		/* '?=' to accept return values exists ? */
		if (F_OldChar(qp) == '?')
		{
			qb->param_number++;
			while (isspace((unsigned char) qp->statement[++qp->opos]));
			if (F_OldChar(qp) != '=')
			{
				F_OldPrior(qp);
				return SQL_SUCCESS;
			}
			while (isspace((unsigned char) qp->statement[++qp->opos]));
		}
		if (strnicmp(F_OldPtr(qp), "call", lit_call_len) ||
			!isspace((unsigned char) F_OldPtr(qp)[lit_call_len]))
2539
		{
2540 2541
			F_OldPrior(qp);
			return SQL_SUCCESS;
2542
		}
2543 2544 2545 2546 2547
		qp->opos += lit_call_len;
		CVT_APPEND_STR(qb, "SELECT ");
		if (my_strchr(conn, F_OldPtr(qp), '('))
			qp->proc_no_param = FALSE;
		return SQL_SUCCESS;
2548
	}
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560

	sscanf(F_OldPtr(qp), "%32s", key);
	while ((ucv = F_OldChar(qp)) != '\0' && (!isspace(ucv)))
		F_OldNext(qp);
	while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv))
		F_OldNext(qp);
    
	/* Avoid the concatenation of the function name with the previous word. Aceto */

	if (F_NewPos(qb) > 0 && isalnum(F_NewPtr(qb)[-1]))
		CVT_APPEND_CHAR(qb, ' ');
	
H
Hiroshi Inoue 已提交
2561 2562 2563
	if (strcmp(key, "d") == 0)
	{
		/* Literal; return the escape part adding type cast */
2564 2565 2566
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		prtlen = snprintf(buf, sizeof(buf), "%s::date ", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2567 2568 2569 2570
	}
	else if (strcmp(key, "t") == 0)
	{
		/* Literal; return the escape part adding type cast */
2571 2572 2573
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		prtlen = snprintf(buf, sizeof(buf), "%s::time", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2574 2575 2576 2577
	}
	else if (strcmp(key, "ts") == 0)
	{
		/* Literal; return the escape part adding type cast */
2578 2579 2580
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		if (PG_VERSION_LT(qb->conn, 7.1))
			prtlen = snprintf(buf, sizeof(buf), "%s::datetime", buf);
H
Hiroshi Inoue 已提交
2581
		else
2582 2583
			prtlen = snprintf(buf, sizeof(buf), "%s::timestamp", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2584 2585
	}
	else if (strcmp(key, "oj") == 0) /* {oj syntax support for 7.1 * servers */
B
Bruce Momjian 已提交
2586
	{
2587 2588
		F_OldPrior(qp);
		return SQL_SUCCESS; /* Continue at inner_process_tokens loop */
2589
	}
B
Bruce Momjian 已提交
2590 2591
	else if (strcmp(key, "fn") == 0)
	{
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
		QueryBuild	nqb;
		const char *mapExpr;
		int	i, param_count;
		UInt4	param_consumed;
		Int4	param_pos[16][2];

		/* Separate off the func name, skipping leading and trailing whitespace */
		i = 0;
		while ((ucv = F_OldChar(qp)) != '\0' && ucv != '(' &&
			   (!isspace(ucv)))
		{
			if (i < sizeof(key)-1)
				key[i++] = ucv;
			F_OldNext(qp);
		}
		key[i] = '\0';
		while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv))
			F_OldNext(qp);
2610

B
Bruce Momjian 已提交
2611
		/*
H
Hiroshi Inoue 已提交
2612
 		 * We expect left parenthesis here, else return fn body as-is
B
Bruce Momjian 已提交
2613
		 * since it is one of those "function constants".
2614
		 */
2615
		if (F_OldChar(qp) != '(')
B
Bruce Momjian 已提交
2616
		{
2617 2618
			CVT_APPEND_STR(qb, key);
			return SQL_SUCCESS;
2619
		}
B
Bruce Momjian 已提交
2620 2621

		/*
H
Hiroshi Inoue 已提交
2622 2623 2624
		 * Process parameter list and inner escape
		 * sequences
		 * Aceto 2002-01-29
2625
		 */
H
Hiroshi Inoue 已提交
2626

2627 2628 2629 2630 2631 2632 2633 2634
		QB_initialize_copy(&nqb, qb, 1024);
		if (retval = processParameters(qp, &nqb, &param_consumed, param_pos), retval == SQL_ERROR)
		{
			qb->errornumber = nqb.errornumber;
			qb->errormsg = nqb.errormsg;
			QB_Destructor(&nqb);
			return retval;
		}
H
Hiroshi Inoue 已提交
2635 2636

		for (param_count = 0;; param_count++)
B
Bruce Momjian 已提交
2637
		{
H
Hiroshi Inoue 已提交
2638 2639
			if (param_pos[param_count][0] < 0)
				break;
2640
		}
H
Hiroshi Inoue 已提交
2641
		if (param_count == 1 &&
H
Hiroshi Inoue 已提交
2642
		    param_pos[0][1] < param_pos[0][0])
H
Hiroshi Inoue 已提交
2643
			param_count = 0;
2644

H
Hiroshi Inoue 已提交
2645 2646
		mapExpr = mapFunction(key, param_count);
		if (mapExpr == NULL)
2647 2648 2649 2650
		{
			CVT_APPEND_STR(qb, key);
			CVT_APPEND_DATA(qb, nqb.query_statement, nqb.npos);
		}
H
Hiroshi Inoue 已提交
2651 2652 2653 2654 2655 2656 2657 2658 2659
		else
		{
			const char *mapptr;
			int	from, to, pidx, paramlen;

			for (prtlen = 0, mapptr = mapExpr; *mapptr; mapptr++)
			{
				if (*mapptr != '$')
				{
2660
					CVT_APPEND_CHAR(qb, *mapptr);
H
Hiroshi Inoue 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
					continue;
				}
				mapptr++;
				if (*mapptr == '*')
				{
					from = 1;
					to = param_consumed - 2;
				}
				else if (isdigit(*mapptr))
				{
					pidx = *mapptr - '0' - 1;
					if (pidx < 0 ||
H
Hiroshi Inoue 已提交
2673
					    param_pos[pidx][0] < 0)
H
Hiroshi Inoue 已提交
2674
					{
2675 2676
						qb->errornumber = STMT_EXEC_ERROR;
						qb->errormsg = "param not found";
H
Hiroshi Inoue 已提交
2677
						qlog("%s %dth param not found for the expression %s\n", pidx + 1, mapExpr);
2678 2679
						retval = SQL_ERROR;
						break;
H
Hiroshi Inoue 已提交
2680 2681 2682 2683 2684 2685
					}
					from = param_pos[pidx][0];
					to = param_pos[pidx][1];
				}
				else
				{
2686 2687
					qb->errornumber = STMT_EXEC_ERROR;
					qb->errormsg = "internal expression error";
H
Hiroshi Inoue 已提交
2688
					qlog("%s internal expression error %s\n", func, mapExpr);
2689
					retval = SQL_ERROR;
H
Hiroshi Inoue 已提交
2690 2691
					break;
				}
2692
				paramlen = to - from + 1;
H
Hiroshi Inoue 已提交
2693
				if (paramlen > 0)
2694
					CVT_APPEND_DATA(qb, nqb.query_statement+ from, paramlen);
H
Hiroshi Inoue 已提交
2695 2696
			}
		}
2697
		if (0 == qb->errornumber)
H
Hiroshi Inoue 已提交
2698
		{
2699 2700
			qb->errornumber = nqb.errornumber;
			qb->errormsg = nqb.errormsg;
H
Hiroshi Inoue 已提交
2701
		}
2702
		if (SQL_ERROR != retval)
H
Hiroshi Inoue 已提交
2703
		{
2704 2705
			qb->param_number = nqb.param_number;
			qb->flags = nqb.flags;
H
Hiroshi Inoue 已提交
2706
		}
2707
		QB_Destructor(&nqb);
H
Hiroshi Inoue 已提交
2708
	}
2709
	else
H
Hiroshi Inoue 已提交
2710
	{
2711 2712
		/* Bogus key, leave untranslated */
		return SQL_ERROR;
H
Hiroshi Inoue 已提交
2713
	}
2714 2715
 
	return retval;
2716 2717
}

2718 2719
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
2720
{
2721 2722
	size_t		i = 0,
				out = 0;
2723

2724
	for (i = 0; s[i]; i++)
B
Bruce Momjian 已提交
2725
	{
2726
		if (s[i] == '$' || s[i] == ',' || s[i] == ')')
B
Bruce Momjian 已提交
2727
			;					/* skip these characters */
2728
		else
2729 2730
		{
			if (out + 1 >= soutmax)
2731
				return FALSE;	/* sout is too short */
2732 2733 2734 2735 2736
			if (s[i] == '(')
				sout[out++] = '-';
			else
				sout[out++] = s[i];
		}
2737
	}
2738 2739
	sout[out] = '\0';
	return TRUE;
2740 2741 2742
}


2743 2744 2745 2746
/*
 *	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
 */
2747
char
2748
parse_datetime(const char *buf, SIMPLE_TIME *st)
2749
{
B
Bruce Momjian 已提交
2750 2751 2752 2753 2754 2755 2756 2757
	int			y,
				m,
				d,
				hh,
				mm,
				ss;
	int			nf;

2758
	y = m = d = hh = mm = ss = 0;
2759 2760
	st->fr = 0;
	st->infinity = 0;
2761

2762 2763 2764 2765 2766 2767 2768 2769
	/* escape sequence ? */
	if (buf[0] == '{')
	{
		while (*(++buf) && *buf != '\'');
		if (!(*buf))
			return FALSE;
		buf++;
	}
B
Bruce Momjian 已提交
2770 2771
	if (buf[4] == '-')			/* year first */
		nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss);
2772
	else
B
Bruce Momjian 已提交
2773
		nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss);
2774

B
Bruce Momjian 已提交
2775 2776
	if (nf == 5 || nf == 6)
	{
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
		st->y = y;
		st->m = m;
		st->d = d;
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

B
Bruce Momjian 已提交
2787
	if (buf[4] == '-')			/* year first */
2788 2789 2790 2791
		nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d);
	else
		nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y);

B
Bruce Momjian 已提交
2792 2793
	if (nf == 3)
	{
2794 2795 2796 2797 2798 2799 2800 2801
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

	nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss);
B
Bruce Momjian 已提交
2802 2803
	if (nf == 2 || nf == 3)
	{
2804 2805 2806 2807 2808 2809 2810 2811 2812
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

	return FALSE;
}
2813

2814

2815
/*	Change linefeed to carriage-return/linefeed */
2816
int
H
Hiroshi Inoue 已提交
2817
convert_linefeeds(const char *si, char *dst, size_t max, BOOL convlf, BOOL *changed)
2818
{
B
Bruce Momjian 已提交
2819 2820
	size_t		i = 0,
				out = 0;
2821

2822 2823 2824 2825
	if (max == 0)
		max = 0xffffffff;
	*changed = FALSE;
	for (i = 0; si[i] && out < max - 1; i++)
B
Bruce Momjian 已提交
2826
	{
H
Hiroshi Inoue 已提交
2827
		if (convlf && si[i] == '\n')
B
Bruce Momjian 已提交
2828 2829 2830 2831
		{
			/* Only add the carriage-return if needed */
			if (i > 0 && si[i - 1] == '\r')
			{
2832 2833 2834 2835
				if (dst)
					dst[out++] = si[i];
				else
					out++;
B
Byron Nikolaidis 已提交
2836 2837
				continue;
			}
2838
			*changed = TRUE;
B
Byron Nikolaidis 已提交
2839

2840 2841 2842 2843 2844 2845 2846
			if (dst)
			{
				dst[out++] = '\r';
				dst[out++] = '\n';
			}
			else
				out += 2;
2847 2848
		}
		else
2849 2850 2851 2852 2853 2854
		{
			if (dst)
				dst[out++] = si[i];
			else
				out++;
		}
2855
	}
2856 2857
	if (dst)
		dst[out] = '\0';
2858
	return out;
2859 2860
}

2861 2862 2863 2864 2865

/*
 *	Change carriage-return/linefeed to just linefeed
 *	Plus, escape any special characters.
 */
2866
int
H
Hiroshi Inoue 已提交
2867
convert_special_chars(const char *si, char *dst, int used, BOOL convlf, int ccsc)
2868
{
B
Bruce Momjian 已提交
2869 2870 2871
	size_t		i = 0,
				out = 0,
				max;
2872
	char	   *p = NULL;
H
Hiroshi Inoue 已提交
2873 2874 2875
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif
2876 2877 2878 2879 2880 2881


	if (used == SQL_NTS)
		max = strlen(si);
	else
		max = used;
2882 2883 2884 2885 2886
	if (dst)
	{
		p = dst;
		p[0] = '\0';
	}
H
Hiroshi Inoue 已提交
2887
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2888
	encoded_str_constr(&encstr, ccsc, si);
H
Hiroshi Inoue 已提交
2889
#endif
2890

H
Hiroshi Inoue 已提交
2891
	for (i = 0; i < max && si[i]; i++)
B
Bruce Momjian 已提交
2892
	{
2893
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2894 2895
		encoded_nextchar(&encstr);
		if (ENCODE_STATUS(encstr) != 0)
2896 2897 2898 2899 2900 2901 2902
		{
			if (p)
				p[out] = si[i];
			out++;
			continue;
		}
#endif
H
Hiroshi Inoue 已提交
2903
		if (convlf && si[i] == '\r' && si[i + 1] == '\n')
2904
			continue;
B
Byron Nikolaidis 已提交
2905
		else if (si[i] == '\'' || si[i] == '\\')
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
		{
			if (p)
				p[out++] = '\\';
			else
				out++;
		}
		if (p)
			p[out++] = si[i];
		else
			out++;
2916
	}
2917 2918 2919
	if (p)
		p[out] = '\0';
	return out;
2920 2921
}

2922

2923 2924
/*	!!! Need to implement this function !!!  */
int
2925
convert_pgbinary_to_char(const char *value, char *rgbValue, int cbValueMax)
2926
{
2927 2928 2929
	mylog("convert_pgbinary_to_char: value = '%s'\n", value);

	strncpy_null(rgbValue, value, cbValueMax);
2930 2931 2932
	return 0;
}

2933

2934
static unsigned int
2935
conv_from_octal(const unsigned char *s)
2936
{
B
Bruce Momjian 已提交
2937 2938
	int			i,
				y = 0;
2939

B
Bruce Momjian 已提交
2940
	for (i = 1; i <= 3; i++)
2941
		y += (s[i] - '0') << (3  * (3 - i));
2942 2943

	return y;
2944

2945 2946
}

2947

2948
static unsigned int
2949
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
2950
{
B
Bruce Momjian 已提交
2951 2952 2953
	int			i,
				y = 0,
				val;
2954

B
Bruce Momjian 已提交
2955 2956 2957 2958 2959 2960 2961 2962
	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 已提交
2963

2964
		y += val << (4 * (2 - i));
B
Byron Nikolaidis 已提交
2965 2966 2967 2968 2969
	}

	return y;
}

2970

B
Bruce Momjian 已提交
2971
/*	convert octal escapes to bytes */
2972
int
2973
convert_from_pgbinary(const unsigned char *value, unsigned char *rgbValue, int cbValueMax)
2974
{
2975 2976
	size_t		i,
				ilen = strlen(value);
B
Bruce Momjian 已提交
2977
	int			o = 0;
2978

B
Bruce Momjian 已提交
2979

2980
	for (i = 0; i < ilen;)
B
Bruce Momjian 已提交
2981 2982 2983
	{
		if (value[i] == '\\')
		{
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
			if (value[i + 1] == '\\')
			{
				rgbValue[o] = value[i];
				i += 2;
			}
			else
			{
				rgbValue[o] = conv_from_octal(&value[i]);
				i += 4;
			}
2994
		}
B
Bruce Momjian 已提交
2995
		else
2996 2997 2998 2999
			rgbValue[o] = value[i++];
		mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]);
		o++;
	}
3000

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

3003 3004 3005 3006
	return o;
}


3007
static char *
3008 3009
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
3010 3011
	int			i;
	static char x[6];
3012 3013 3014 3015 3016

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

B
Bruce Momjian 已提交
3017 3018
	for (i = 4; i > 1; i--)
	{
3019
		x[i] = (val & 7) + '0';
3020 3021 3022 3023 3024 3025
		val >>= 3;
	}

	return x;
}

3026

B
Bruce Momjian 已提交
3027
/*	convert non-ascii bytes to octal escape sequences */
3028
int
3029
convert_to_pgbinary(const unsigned char *in, char *out, int len)
3030
{
B
Bruce Momjian 已提交
3031 3032
	int			i,
				o = 0;
3033

B
Bruce Momjian 已提交
3034 3035
	for (i = 0; i < len; i++)
	{
3036
		mylog("convert_to_pgbinary: in[%d] = %d, %c\n", i, in[i], in[i]);
B
Bruce Momjian 已提交
3037
		if (isalnum(in[i]) || in[i] == ' ')
3038
			out[o++] = in[i];
B
Bruce Momjian 已提交
3039 3040 3041
		else
		{
			strcpy(&out[o], conv_to_octal(in[i]));
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
			o += 5;
		}
	}

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

	return o;
}


B
Byron Nikolaidis 已提交
3052
void
3053
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
3054
{
3055 3056
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
3057
				o = 0;
B
Byron Nikolaidis 已提交
3058

3059
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
3060 3061 3062
	{
		if (in[i] == '+')
		{
B
Byron Nikolaidis 已提交
3063 3064 3065
			sprintf(&out[o], "%%2B");
			o += 3;
		}
B
Bruce Momjian 已提交
3066
		else if (isspace((unsigned char) in[i]))
B
Byron Nikolaidis 已提交
3067
			out[o++] = '+';
B
Bruce Momjian 已提交
3068 3069
		else if (!isalnum((unsigned char) in[i]))
		{
3070
			sprintf(&out[o], "%%%02x", (unsigned char) in[i]);
B
Byron Nikolaidis 已提交
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
			o += 3;
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}


void
3081
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
3082
{
3083 3084
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
3085
				o = 0;
B
Byron Nikolaidis 已提交
3086

3087
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
3088
	{
B
Byron Nikolaidis 已提交
3089 3090
		if (in[i] == '+')
			out[o++] = ' ';
B
Bruce Momjian 已提交
3091 3092
		else if (in[i] == '%')
		{
B
Byron Nikolaidis 已提交
3093
			sprintf(&out[o++], "%c", conv_from_hex(&in[i]));
B
Bruce Momjian 已提交
3094
			i += 2;
B
Byron Nikolaidis 已提交
3095 3096 3097 3098 3099 3100 3101
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}

3102 3103 3104 3105
static const char *hextbl = "0123456789ABCDEF";
static int
pg_bin2hex(UCHAR *src, UCHAR *dst, int length)
{
3106 3107 3108 3109 3110 3111
	UCHAR		chr,
			   *src_wk,
			   *dst_wk;
	BOOL		backwards;
	int			i;

3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
	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;
}
3141

3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
/*-------
 *	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.
 *-------
 */
3158
int
3159 3160
convert_lo(StatementClass *stmt, const void *value, Int2 fCType, PTR rgbValue,
		   SDWORD cbValueMax, SDWORD *pcbValue)
3161
{
B
Bruce Momjian 已提交
3162 3163 3164 3165
	Oid			oid;
	int			retval,
				result,
				left = -1;
T
Tom Lane 已提交
3166
	BindInfoClass *bindInfo = NULL;
3167 3168
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
H
Hiroshi Inoue 已提交
3169
	ARDFields	*opts = SC_get_ARD(stmt);
3170
	int			factor = (fCType == SQL_C_CHAR ? 2 : 1);
3171

3172
	/* If using SQLGetData, then current_col will be set */
B
Bruce Momjian 已提交
3173 3174
	if (stmt->current_col >= 0)
	{
H
Hiroshi Inoue 已提交
3175
		bindInfo = &opts->bindings[stmt->current_col];
3176 3177
		left = bindInfo->data_left;
	}
3178

B
Bruce Momjian 已提交
3179 3180 3181 3182
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
3183

B
Bruce Momjian 已提交
3184 3185
	if (!bindInfo || bindInfo->data_left == -1)
	{
B
Byron Nikolaidis 已提交
3186
		/* begin transaction if needed */
3187
		if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
3188
		{
H
Hiroshi Inoue 已提交
3189
			if (!CC_begin(conn))
B
Bruce Momjian 已提交
3190
			{
B
Byron Nikolaidis 已提交
3191 3192 3193 3194 3195 3196
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

3197
		oid = atoi(value);
3198
		stmt->lobj_fd = lo_open(conn, oid, INV_READ);
B
Bruce Momjian 已提交
3199 3200
		if (stmt->lobj_fd < 0)
		{
3201
			stmt->errornumber = STMT_EXEC_ERROR;
3202
			stmt->errormsg = "Couldnt open large object for reading.";
3203 3204
			return COPY_GENERAL_ERROR;
		}
3205

B
Bruce Momjian 已提交
3206
		/* Get the size */
3207
		retval = lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END);
B
Bruce Momjian 已提交
3208 3209
		if (retval >= 0)
		{
3210
			left = lo_tell(conn, stmt->lobj_fd);
3211 3212 3213
			if (bindInfo)
				bindInfo->data_left = left;

B
Bruce Momjian 已提交
3214
			/* return to beginning */
3215
			lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET);
3216 3217
		}
	}
3218
	mylog("lo data left = %d\n", left);
3219

B
Bruce Momjian 已提交
3220
	if (left == 0)
3221
		return COPY_NO_DATA_FOUND;
3222

B
Bruce Momjian 已提交
3223 3224
	if (stmt->lobj_fd < 0)
	{
3225 3226 3227 3228
		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Large object FD undefined for multiple read.";
		return COPY_GENERAL_ERROR;
	}
3229

3230
	retval = lo_read(conn, stmt->lobj_fd, (char *) rgbValue, factor > 1 ? (cbValueMax - 1) / factor : cbValueMax);
B
Bruce Momjian 已提交
3231 3232
	if (retval < 0)
	{
3233
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3234 3235

		/* commit transaction if needed */
3236
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3237
		{
H
Hiroshi Inoue 已提交
3238
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3239
			{
B
Byron Nikolaidis 已提交
3240 3241 3242 3243 3244 3245
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

3246 3247 3248 3249 3250 3251 3252
		stmt->lobj_fd = -1;

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

3253 3254
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
3255 3256 3257 3258 3259 3260
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
3261
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
3262

B
Bruce Momjian 已提交
3263
	if (bindInfo && bindInfo->data_left > 0)
3264
		bindInfo->data_left -= retval;
3265

B
Bruce Momjian 已提交
3266 3267
	if (!bindInfo || bindInfo->data_left == 0)
	{
3268
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3269 3270

		/* commit transaction if needed */
3271
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3272
		{
H
Hiroshi Inoue 已提交
3273
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3274
			{
B
Byron Nikolaidis 已提交
3275 3276 3277 3278 3279 3280
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

B
Bruce Momjian 已提交
3281
		stmt->lobj_fd = -1;		/* prevent further reading */
3282
	}
3283 3284

	return result;
3285
}