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

20 21
#include "convert.h"

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

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

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

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

47 48 49 50
/*
 *	How to map ODBC scalar functions {fn func(args)} to Postgres.
 *	This is just a simple substitution.  List augmented from:
 *	http://www.merant.com/datadirect/download/docs/odbc16/Odbcref/rappc.htm
51
 *	- thomas 2000-04-03
52
 */
B
Bruce Momjian 已提交
53
char	   *mapFuncs[][2] = {
H
Hiroshi Inoue 已提交
54 55 56 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 113 114 115 116 117 118 119
/*	{ "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)" },
	{"DAYOFYEAR",	 "cast(extract(doy from $1) as integer)" }, 
	{"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 已提交
120 121

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

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

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



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

	*bZone = FALSE;
	*zone = 0;
	st->fr = 0;
	if ((scnt = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d%s", &st->y, &st->m, &st->d, &st->hh, &st->mm, &st->ss, rest)) < 6)
		return FALSE;
	else if (scnt == 6)
		return TRUE;
	switch (rest[0])
	{
		case '+':
			*bZone = TRUE;
			*zone = atoi(&rest[1]);
			break;
		case '-':
			*bZone = TRUE;
			*zone = -atoi(&rest[1]);
			break;
		case '.':
			if ((ptr = strchr(rest, '+')) != NULL)
			{
				*bZone = TRUE;
				*zone = atoi(&ptr[1]);
				*ptr = '\0';
			}
			else if ((ptr = strchr(rest, '-')) != NULL)
			{
				*bZone = TRUE;
				*zone = -atoi(&ptr[1]);
				*ptr = '\0';
			}
			for (i = 1; i < 10; i++)
			{
199
				if (!isdigit((unsigned char) rest[i]))
200 201 202 203 204 205 206 207
					break;
			}
			for (; i < 10; i++)
				rest[i] = '0';
			rest[i] = '\0';
			st->fr = atoi(&rest[1]);
			break;
		default:
208
			return TRUE;
209 210 211 212 213 214 215 216 217 218
	}
	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;
219
	if (!daylight && timediff == 0)		/* the same timezone */
220 221 222
		return TRUE;
	else
	{
223 224
		struct tm	tm,
				   *tm2;
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
		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;
240
		if (timediff == 0)		/* the same time zone */
241 242 243 244 245 246 247
			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;
248 249 250
			st->hh = tm2->tm_hour;
			st->mm = tm2->tm_min;
			st->ss = tm2->tm_sec;
251 252 253
			*bZone = TRUE;
		}
	}
254 255
#endif   /* WIN32 */
	return TRUE;
256 257
}

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

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

		zoneint = TIMEZONE_GLOBAL;
285 286
		if (daylight && st->y >= 1900)
		{
287 288 289 290 291 292 293 294 295 296 297 298
			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)
299
			sprintf(zonestr, "-%02d", (int) zoneint / 3600);
300
		else
301
			sprintf(zonestr, "+%02d", -(int) zoneint / 3600);
302
	}
303
#endif   /* WIN32 */
304
	sprintf(str, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s", st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr);
305
	return TRUE;
306 307
}

308 309
/*	This is called by SQLFetch() */
int
310
copy_and_convert_field_bindinfo(StatementClass *stmt, Int4 field_type, void *value, int col)
311
{
B
Bruce Momjian 已提交
312
	BindInfoClass *bic = &(stmt->bindings[col]);
H
Hiroshi Inoue 已提交
313
	UInt4	offset = stmt->options.row_offset_ptr ? *stmt->options.row_offset_ptr : 0;
314

H
Hiroshi Inoue 已提交
315 316
	return copy_and_convert_field(stmt, field_type, value, (Int2) bic->returntype, (PTR) (bic->buffer + offset),
							 (SDWORD) bic->buflen, (SDWORD *) (bic->used + (offset >> 2)));
317 318
}

319

320 321
/*	This is called by SQLGetData() */
int
322 323
copy_and_convert_field(StatementClass *stmt, Int4 field_type, void *value, Int2 fCType,
					   PTR rgbValue, SDWORD cbValueMax, SDWORD *pcbValue)
324
{
H
Hiroshi Inoue 已提交
325
	static char *func = "copy_and_convert_field";
B
Bruce Momjian 已提交
326 327
	Int4		len = 0,
				copy_len = 0;
328
	SIMPLE_TIME st;
B
Bruce Momjian 已提交
329 330 331 332
	time_t		t = time(NULL);
	struct tm  *tim;
	int			pcbValueOffset,
				rgbValueOffset;
333
	char	   *rgbValueBindRow;
334
	const char *ptr;
B
Bruce Momjian 已提交
335 336 337
	int			bind_row = stmt->bind_row;
	int			bind_size = stmt->options.bind_size;
	int			result = COPY_OK;
H
Hiroshi Inoue 已提交
338
	BOOL		changed, true_is_minus1 = FALSE;
339
	const char *neut_str = value;
340 341
	char		midtemp[2][32];
	int			mtemp_cnt = 0;
342 343
	static BindInfoClass sbic;
	BindInfoClass *pbic;
H
Hiroshi Inoue 已提交
344 345 346
#ifdef	UNICODE_SUPPORT
	BOOL	wchanged =   FALSE;
#endif /* UNICODE_SUPPORT */
347

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

B
Bruce Momjian 已提交
372
	if (bind_size > 0)
373
		pcbValueOffset = rgbValueOffset = (bind_size * bind_row);
B
Bruce Momjian 已提交
374 375
	else
	{
376 377
		pcbValueOffset = bind_row * sizeof(SDWORD);
		rgbValueOffset = bind_row * cbValueMax;
378

379
	}
380 381 382

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

B
Bruce Momjian 已提交
383
	/* Initialize current date */
384 385 386 387 388
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;

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

B
Bruce Momjian 已提交
391 392
	if (!value)
	{
393
		/*
394 395
		 * handle a null just by returning SQL_NULL_DATA in pcbValue, and
		 * doing nothing to the buffer.
396
		 */
B
Bruce Momjian 已提交
397
		if (pcbValue)
H
Hiroshi Inoue 已提交
398
		{
399
			*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = SQL_NULL_DATA;
H
Hiroshi Inoue 已提交
400 401 402 403 404 405 406 407 408
			return COPY_OK;
		}
		else
		{
			stmt->errornumber = STMT_RETURN_NULL_WITHOUT_INDICATOR;
			stmt->errormsg = "StrLen_or_IndPtr was a null pointer and NULL data was retrieved";	
			SC_log_error(func, "", stmt);
			return	SQL_ERROR;
		}
B
Byron Nikolaidis 已提交
409 410
	}

B
Bruce Momjian 已提交
411 412 413 414 415 416 417 418 419
	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 已提交
420 421
	}

422
	/*
423
	 * First convert any specific postgres types into more useable data.
424
	 *
425 426
	 * NOTE: Conversions from PG char/varchar of a date/time/timestamp value
	 * to SQL_C_DATE,SQL_C_TIME, SQL_C_TIMESTAMP not supported
427
	 */
B
Bruce Momjian 已提交
428 429
	switch (field_type)
	{
430 431 432 433
			/*
			 * $$$ need to add parsing for date/time/timestamp strings in
			 * PG_TYPE_CHAR,VARCHAR $$$
			 */
B
Bruce Momjian 已提交
434 435 436
		case PG_TYPE_DATE:
			sscanf(value, "%4d-%2d-%2d", &st.y, &st.m, &st.d);
			break;
437

B
Bruce Momjian 已提交
438 439 440
		case PG_TYPE_TIME:
			sscanf(value, "%2d:%2d:%2d", &st.hh, &st.mm, &st.ss);
			break;
441

B
Bruce Momjian 已提交
442 443 444
		case PG_TYPE_ABSTIME:
		case PG_TYPE_DATETIME:
		case PG_TYPE_TIMESTAMP:
445
			st.fr = 0;
B
Bruce Momjian 已提交
446
			if (strnicmp(value, "invalid", 7) != 0)
447
			{
448 449 450 451 452 453 454 455
				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 */
456 457
				timestamp2stime(value, &st, &bZone, &zone);
			}
B
Bruce Momjian 已提交
458
			else
459 460
			{
				/*
461 462
				 * The timestamp is invalid so set something conspicuous,
				 * like the epoch
463
				 */
B
Bruce Momjian 已提交
464 465 466 467 468 469 470 471 472 473 474 475
				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:
476
			{					/* change T/F to 1/0 */
477
				char	   *s;
B
Bruce Momjian 已提交
478

479
				s = midtemp[mtemp_cnt];
H
Hiroshi Inoue 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
				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");
				}
495 496
				neut_str = midtemp[mtemp_cnt];
				mtemp_cnt++;
B
Bruce Momjian 已提交
497 498 499
			}
			break;

500
			/* This is for internal use by SQLStatistics() */
B
Bruce Momjian 已提交
501 502 503 504
		case PG_TYPE_INT2VECTOR:
			{
				int			nval,
							i;
505
				const char *vp;
B
Bruce Momjian 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534

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

536
#if 0
B
Bruce Momjian 已提交
537 538 539 540 541 542 543 544 545
				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]);
546
#endif
B
Byron Nikolaidis 已提交
547

B
Bruce Momjian 已提交
548 549 550
				/* There is no corresponding fCType for this. */
				if (pcbValue)
					*(SDWORD *) ((char *) pcbValue + pcbValueOffset) = len;
B
Byron Nikolaidis 已提交
551

B
Bruce Momjian 已提交
552 553 554
				return COPY_OK; /* dont go any further or the data will be
								 * trashed */
			}
B
Byron Nikolaidis 已提交
555

B
Bruce Momjian 已提交
556 557 558 559 560
			/*
			 * This is a large object OID, which is used to store
			 * LONGVARBINARY objects.
			 */
		case PG_TYPE_LO:
B
Byron Nikolaidis 已提交
561

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

B
Bruce Momjian 已提交
564
		default:
B
Byron Nikolaidis 已提交
565

B
Bruce Momjian 已提交
566 567 568
			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 已提交
569 570
	}

B
Bruce Momjian 已提交
571 572 573
	/* Change default into something useable */
	if (fCType == SQL_C_DEFAULT)
	{
B
Byron Nikolaidis 已提交
574 575 576 577 578
		fCType = pgtype_to_ctype(stmt, field_type);

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

579 580
	rgbValueBindRow = (char *) rgbValue + rgbValueOffset;

H
Hiroshi Inoue 已提交
581 582 583
#ifdef	UNICODE_SUPPORT
	if (fCType == SQL_C_CHAR || fCType == SQL_C_WCHAR)
#else
B
Bruce Momjian 已提交
584
	if (fCType == SQL_C_CHAR)
H
Hiroshi Inoue 已提交
585
#endif /* UNICODE_SUPPORT */
B
Bruce Momjian 已提交
586 587
	{
		/* Special character formatting as required */
588

B
Bruce Momjian 已提交
589 590 591 592 593 594 595 596 597 598 599
		/*
		 * 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;
600

B
Bruce Momjian 已提交
601 602 603 604 605
			case PG_TYPE_TIME:
				len = 8;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.2d:%.2d:%.2d", st.hh, st.mm, st.ss);
				break;
606

B
Bruce Momjian 已提交
607 608 609 610 611 612 613 614
			case PG_TYPE_ABSTIME:
			case PG_TYPE_DATETIME:
			case PG_TYPE_TIMESTAMP:
				len = 19;
				if (cbValueMax > len)
					sprintf(rgbValueBindRow, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
							st.y, st.m, st.d, st.hh, st.mm, st.ss);
				break;
615

B
Bruce Momjian 已提交
616
			case PG_TYPE_BOOL:
H
Hiroshi Inoue 已提交
617
				len = strlen(neut_str);
B
Bruce Momjian 已提交
618 619
				if (cbValueMax > len)
				{
620
					strcpy(rgbValueBindRow, neut_str);
B
Bruce Momjian 已提交
621 622 623
					mylog("PG_TYPE_BOOL: rgbValueBindRow = '%s'\n", rgbValueBindRow);
				}
				break;
624

B
Bruce Momjian 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
				/*
				 * 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") */
640
				len = convert_pgbinary_to_char(neut_str, rgbValueBindRow, cbValueMax);
B
Bruce Momjian 已提交
641 642 643

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

B
Bruce Momjian 已提交
645
			default:
646 647 648 649 650 651 652 653
				if (stmt->current_col < 0)
				{
					pbic = &sbic;
					pbic->data_left = -1;
				}
				else
					pbic = &stmt->bindings[stmt->current_col];
				if (pbic->data_left < 0)
654
				{
H
Hiroshi Inoue 已提交
655 656 657 658 659 660 661 662 663 664
					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 */
665
					/* convert linefeeds to carriage-return/linefeed */
H
Hiroshi Inoue 已提交
666
					len = convert_linefeeds(neut_str, NULL, 0, lf_conv, &changed);
667 668
					if (cbValueMax == 0)		/* just returns length
												 * info */
669 670 671 672
					{
						result = COPY_RESULT_TRUNCATED;
						break;
					}
673 674
					if (!pbic->ttlbuf)
						pbic->ttlbuflen = 0;
675 676
					if (changed || len >= cbValueMax)
					{
677
						if (len >= (int) pbic->ttlbuflen)
678
						{
679 680
							pbic->ttlbuf = realloc(pbic->ttlbuf, len + 1);
							pbic->ttlbuflen = len + 1;
681
						}
H
Hiroshi Inoue 已提交
682 683 684 685 686 687 688 689
#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);
690
						ptr = pbic->ttlbuf;
691 692 693
					}
					else
					{
694
						if (pbic->ttlbuf)
695
						{
696 697
							free(pbic->ttlbuf);
							pbic->ttlbuf = NULL;
698
						}
699
						ptr = neut_str;
700 701 702
					}
				}
				else
703
					ptr = pbic->ttlbuf;
B
Bruce Momjian 已提交
704 705 706 707 708

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

				if (stmt->current_col >= 0)
				{
709
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
710
					{
711 712
						ptr += strlen(ptr) - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
713 714
					}
					else
715
						pbic->data_left = len;
716 717
				}

B
Bruce Momjian 已提交
718 719 720
				if (cbValueMax > 0)
				{
					copy_len = (len >= cbValueMax) ? cbValueMax - 1 : len;
721

B
Bruce Momjian 已提交
722
					/* Copy the data */
723 724
					memcpy(rgbValueBindRow, ptr, copy_len);
					rgbValueBindRow[copy_len] = '\0';
725

B
Bruce Momjian 已提交
726 727
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
728
						pbic->data_left -= copy_len;
729 730
				}

B
Bruce Momjian 已提交
731 732 733 734
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
735
				if (cbValueMax > 0 && len >= cbValueMax)
B
Bruce Momjian 已提交
736
					result = COPY_RESULT_TRUNCATED;
737 738
				else
				{
739
					if (pbic->ttlbuf != NULL)
740
					{
741 742
						free(pbic->ttlbuf);
						pbic->ttlbuf = NULL;
743 744
					}
				}
745 746


B
Bruce Momjian 已提交
747 748
				mylog("    SQL_C_CHAR, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow);
				break;
B
Byron Nikolaidis 已提交
749
		}
H
Hiroshi Inoue 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
#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;
				free(str); 
			}
			else
			{
				len *= 2;
				result = COPY_RESULT_TRUNCATED;
			}
		}
#endif /* UNICODE_SUPPORT */
769

B
Bruce Momjian 已提交
770 771 772 773 774 775 776 777
	}
	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 已提交
778
		if (field_type == PG_TYPE_MONEY)
779 780 781 782 783 784 785 786 787
		{
			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 已提交
788

B
Bruce Momjian 已提交
789 790 791
		switch (fCType)
		{
			case SQL_C_DATE:
792
#if (ODBCVER >= 0x0300)
793
			case SQL_C_TYPE_DATE:		/* 91 */
794
#endif
B
Bruce Momjian 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807
				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;
808

B
Bruce Momjian 已提交
809
			case SQL_C_TIME:
810
#if (ODBCVER >= 0x0300)
811
			case SQL_C_TYPE_TIME:		/* 92 */
812
#endif
B
Bruce Momjian 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825
				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 已提交
826

B
Bruce Momjian 已提交
827
			case SQL_C_TIMESTAMP:
828
#if (ODBCVER >= 0x0300)
829
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
830
#endif
B
Bruce Momjian 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844
				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;
845
					ts->fraction = st.fr;
B
Bruce Momjian 已提交
846 847
				}
				break;
848

B
Bruce Momjian 已提交
849 850 851
			case SQL_C_BIT:
				len = 1;
				if (bind_size > 0)
852
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
853
				else
854
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
855

B
Bruce Momjian 已提交
856
				/*
857 858 859
				 * 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 已提交
860 861
				 */
				break;
862

B
Bruce Momjian 已提交
863 864 865 866
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				len = 1;
				if (bind_size > 0)
867
					*(SCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
868
				else
869
					*((SCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
870
				break;
871

B
Bruce Momjian 已提交
872 873 874
			case SQL_C_UTINYINT:
				len = 1;
				if (bind_size > 0)
875
					*(UCHAR *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
876
				else
877
					*((UCHAR *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
878
				break;
879

B
Bruce Momjian 已提交
880 881 882
			case SQL_C_FLOAT:
				len = 4;
				if (bind_size > 0)
883
					*(SFLOAT *) ((char *) rgbValue + (bind_row * bind_size)) = (float) atof(neut_str);
B
Bruce Momjian 已提交
884
				else
885
					*((SFLOAT *) rgbValue + bind_row) = (float) atof(neut_str);
B
Bruce Momjian 已提交
886
				break;
887

B
Bruce Momjian 已提交
888 889 890
			case SQL_C_DOUBLE:
				len = 8;
				if (bind_size > 0)
891
					*(SDOUBLE *) ((char *) rgbValue + (bind_row * bind_size)) = atof(neut_str);
B
Bruce Momjian 已提交
892
				else
893
					*((SDOUBLE *) rgbValue + bind_row) = atof(neut_str);
B
Bruce Momjian 已提交
894
				break;
895

B
Bruce Momjian 已提交
896 897 898 899
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				len = 2;
				if (bind_size > 0)
900
					*(SWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
901
				else
902
					*((SWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
903
				break;
904

B
Bruce Momjian 已提交
905 906 907
			case SQL_C_USHORT:
				len = 2;
				if (bind_size > 0)
908
					*(UWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
909
				else
910
					*((UWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
911
				break;
912

B
Bruce Momjian 已提交
913 914 915 916
			case SQL_C_SLONG:
			case SQL_C_LONG:
				len = 4;
				if (bind_size > 0)
917
					*(SDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
918
				else
919
					*((SDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
920 921 922 923 924
				break;

			case SQL_C_ULONG:
				len = 4;
				if (bind_size > 0)
925
					*(UDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
926
				else
927
					*((UDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
928
				break;
929

H
Hiroshi Inoue 已提交
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
#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 已提交
950
			case SQL_C_BINARY:
951

B
Bruce Momjian 已提交
952 953
				/* truncate if necessary */
				/* convert octal escapes to bytes */
954

955
				if (stmt->current_col < 0)
956
				{
957 958
					pbic = &sbic;
					pbic->data_left = -1;
959
				}
960 961 962 963 964 965 966 967 968 969 970
				else
					pbic = &stmt->bindings[stmt->current_col];
				if (!pbic->ttlbuf)
					pbic->ttlbuflen = 0;
				if (len = strlen(neut_str), len >= (int) pbic->ttlbuflen)
				{
					pbic->ttlbuf = realloc(pbic->ttlbuf, len + 1);
					pbic->ttlbuflen = len + 1;
				}
				len = convert_from_pgbinary(neut_str, pbic->ttlbuf, pbic->ttlbuflen);
				ptr = pbic->ttlbuf;
971

B
Bruce Momjian 已提交
972 973 974 975 976 977
				if (stmt->current_col >= 0)
				{
					/*
					 * Second (or more) call to SQLGetData so move the
					 * pointer
					 */
978
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
979
					{
980 981
						ptr += len - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
982
					}
983

B
Bruce Momjian 已提交
984 985
					/* First call to SQLGetData so initialize data_left */
					else
986
						pbic->data_left = len;
987

B
Bruce Momjian 已提交
988
				}
989

B
Bruce Momjian 已提交
990 991 992
				if (cbValueMax > 0)
				{
					copy_len = (len > cbValueMax) ? cbValueMax : len;
993

B
Bruce Momjian 已提交
994 995
					/* Copy the data */
					memcpy(rgbValueBindRow, ptr, copy_len);
996

B
Bruce Momjian 已提交
997 998
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
999
						pbic->data_left -= copy_len;
1000
				}
1001

B
Bruce Momjian 已提交
1002 1003 1004 1005 1006 1007
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
				if (len > cbValueMax)
					result = COPY_RESULT_TRUNCATED;
1008

1009
				if (pbic->ttlbuf)
1010
				{
1011 1012
					free(pbic->ttlbuf);
					pbic->ttlbuf = NULL;
1013
				}
B
Bruce Momjian 已提交
1014 1015 1016 1017 1018
				mylog("SQL_C_BINARY: len = %d, copy_len = %d\n", len, copy_len);
				break;

			default:
				return COPY_UNSUPPORTED_TYPE;
B
Byron Nikolaidis 已提交
1019 1020
		}
	}
1021

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

1026
	if (result == COPY_OK && stmt->current_col >= 0)
1027
		stmt->bindings[stmt->current_col].data_left = 0;
1028
	return result;
1029

1030 1031
}

1032

1033 1034 1035 1036
/*--------------------------------------------------------------------
 *	Functions/Macros to get rid of query size limit.
 *
 *	I always used the follwoing macros to convert from
1037
 *	old_statement to new_statement.  Please improve it
1038 1039 1040
 *	if you have a better way.	Hiroshi 2001/05/22
 *--------------------------------------------------------------------
 */
1041 1042
#define INIT_MIN_ALLOC	4096
static int
1043
enlarge_statement(StatementClass *stmt, unsigned int newsize)
1044
{
1045
	unsigned int newalsize = INIT_MIN_ALLOC;
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	static char *func = "enlarge_statement";

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

/*----------
 *	Enlarge stmt_with_params if necessary.
 *----------
 */
1071
#define ENLARGE_NEWSTATEMENT(newpos) \
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	if (newpos >= new_stsize) \
	{ \
		if ((new_stsize = enlarge_statement(stmt, newpos)) <= 0) \
			return SQL_ERROR; \
		new_statement = stmt->stmt_with_params; \
	}
/*----------
 *	Initialize stmt_with_params, new_statement etc.
 *----------
 */
1082
#define CVT_INIT(size) \
1083
do { \
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
	if (stmt->stmt_with_params) \
		free(stmt->stmt_with_params); \
	if (stmt->stmt_size_limit > 0) \
		new_stsize = stmt->stmt_size_limit; \
	else \
	{ \
		new_stsize = INIT_MIN_ALLOC; \
		while (new_stsize <= size) \
			new_stsize *= 2; \
	} \
	new_statement = malloc(new_stsize); \
	stmt->stmt_with_params = new_statement; \
	npos = 0; \
	new_statement[0] = '\0'; \
1098 1099
} while (0)

1100 1101 1102 1103
/*----------
 *	Terminate the stmt_with_params string with NULL.
 *----------
 */
1104
#define CVT_TERMINATE \
1105 1106 1107
do { \
	new_statement[npos] = '\0'; \
} while (0)
1108 1109 1110 1111 1112

/*----------
 *	Append a data.
 *----------
 */
1113
#define CVT_APPEND_DATA(s, len) \
1114
do { \
1115 1116 1117 1118 1119
	unsigned int	newpos = npos + len; \
	ENLARGE_NEWSTATEMENT(newpos) \
	memcpy(&new_statement[npos], s, len); \
	npos = newpos; \
	new_statement[npos] = '\0'; \
1120 1121
} while (0)

1122 1123 1124 1125
/*----------
 *	Append a string.
 *----------
 */
1126
#define CVT_APPEND_STR(s) \
1127
do { \
1128 1129
	unsigned int len = strlen(s); \
	CVT_APPEND_DATA(s, len); \
1130 1131
} while (0)

1132
/*----------
1133
 *	Append a char.
1134 1135
 *----------
 */
1136
#define CVT_APPEND_CHAR(c) \
1137
do { \
1138 1139
	ENLARGE_NEWSTATEMENT(npos + 1); \
	new_statement[npos++] = c; \
1140 1141
} while (0)

1142 1143
/*----------
 *	Append a binary data.
1144
 *	Newly reqeuired size may be overestimated currently.
1145 1146
 *----------
 */
1147
#define CVT_APPEND_BINARY(buf, used) \
1148
do { \
1149 1150 1151
	unsigned int	newlimit = npos + 5 * used; \
	ENLARGE_NEWSTATEMENT(newlimit); \
	npos += convert_to_pgbinary(buf, &new_statement[npos], used); \
1152 1153
} while (0)

1154 1155 1156 1157
/*----------
 *
 *----------
 */
1158
#define CVT_SPECIAL_CHARS(buf, used) \
1159
do { \
H
Hiroshi Inoue 已提交
1160
	int cnvlen = convert_special_chars(buf, NULL, used, lf_conv, conn->ccsc); \
1161 1162 1163
	unsigned int	newlimit = npos + cnvlen; \
\
	ENLARGE_NEWSTATEMENT(newlimit); \
H
Hiroshi Inoue 已提交
1164
	convert_special_chars(buf, &new_statement[npos], used, lf_conv, conn->ccsc); \
1165
	npos += cnvlen; \
1166
} while (0)
1167 1168

/*----------
1169
 *	Check if the statement is
1170 1171
 *	SELECT ... INTO table FROM .....
 *	This isn't really a strict check but ...
1172
 *----------
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
 */
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;
1189
		case '\"':				/* double quoted table name ? */
1190 1191 1192
			do
			{
				do
1193
					while (*(++stmt) != '\"' && *stmt);
1194
				while (*stmt && *(++stmt) == '\"');
1195 1196
				while (*stmt && !isspace((unsigned char) *stmt) && *stmt != '\"')
					stmt++;
1197 1198 1199 1200 1201 1202 1203
			}
			while (*stmt == '\"');
			break;
		default:
			while (!isspace((unsigned char) *(++stmt)));
			break;
	}
1204
	if (!*stmt)
1205 1206 1207 1208 1209 1210 1211
		return FALSE;
	while (isspace((unsigned char) *(++stmt)));
	if (strnicmp(stmt, "from", 4))
		return FALSE;
	return isspace((unsigned char) stmt[4]);
}

H
Hiroshi Inoue 已提交
1212
/*----------
1213
 *	Check if the statement is
H
Hiroshi Inoue 已提交
1214 1215
 *	SELECT ... FOR UPDATE .....
 *	This isn't really a strict check but ...
1216
 *----------
H
Hiroshi Inoue 已提交
1217 1218 1219 1220 1221
 */
static BOOL
table_for_update(const char *stmt, int *endpos)
{
	const char *wstmt = stmt;
1222

H
Hiroshi Inoue 已提交
1223
	while (isspace((unsigned char) *(++wstmt)));
1224
	if (!*wstmt)
H
Hiroshi Inoue 已提交
1225 1226 1227 1228 1229 1230 1231 1232
		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 已提交
1233
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1234
#define		my_strchr(conn, s1,c1) pg_mbschr(conn->ccsc, s1,c1)
H
Hiroshi Inoue 已提交
1235
#else
H
Hiroshi Inoue 已提交
1236
#define		my_strchr(conn, s1,c1) strchr(s1,c1)
H
Hiroshi Inoue 已提交
1237
#endif
1238 1239 1240
/*
 *	This function inserts parameters into an SQL statements.
 *	It will also modify a SELECT statement for use with declare/fetch cursors.
1241
 *	This function does a dynamic memory allocation to get rid of query size limit!
1242
 */
1243
int
1244
copy_statement_with_parameters(StatementClass *stmt)
1245
{
B
Bruce Momjian 已提交
1246 1247 1248 1249 1250 1251
	static char *func = "copy_statement_with_parameters";
	unsigned int opos,
				npos,
				oldstmtlen;
	char		param_string[128],
				tmp[256],
1252 1253 1254
				cbuf[PG_NUMERIC_MAX_PRECISION * 2];		/* seems big enough to
														 * handle the data in
														 * this function */
B
Bruce Momjian 已提交
1255 1256 1257
	int			param_number;
	Int2		param_ctype,
				param_sqltype;
1258 1259
	char	   *old_statement = stmt->statement,
				oldchar;
B
Bruce Momjian 已提交
1260
	char	   *new_statement = stmt->stmt_with_params;
1261
	unsigned int new_stsize = 0;
B
Bruce Momjian 已提交
1262 1263 1264 1265
	SIMPLE_TIME st;
	time_t		t = time(NULL);
	struct tm  *tim;
	SDWORD		used;
H
Hiroshi Inoue 已提交
1266
	char	   *buffer, *buf, *allocbuf;
1267 1268 1269
	BOOL		in_quote = FALSE,
				in_dquote = FALSE,
				in_escape = FALSE;
B
Bruce Momjian 已提交
1270 1271 1272
	Oid			lobj_oid;
	int			lobj_fd,
				retval;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
	BOOL		check_cursor_ok = FALSE;		/* check cursor
												 * restriction */
	BOOL		proc_no_param = TRUE;
	unsigned int declare_pos = 0;
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
	BOOL		prepare_dummy_cursor = FALSE,
				begin_first = FALSE;
	char		token_save[64];
	int			token_len;
	BOOL		prev_token_end;
H
Hiroshi Inoue 已提交
1284 1285
	UInt4	offset = stmt->options.param_offset_ptr ? *stmt->options.param_offset_ptr : 0;
	UInt4	current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row;
H
Hiroshi Inoue 已提交
1286 1287 1288 1289
	BOOL	lf_conv = ci->lf_conversion;
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif   /* MULTIBYTE */
1290

1291
#ifdef	DRIVER_CURSOR_IMPLEMENT
1292
	BOOL		search_from_pos = FALSE;
1293
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1294
	Int4	from_pos = -1, where_pos = -1;
H
Hiroshi Inoue 已提交
1295

1296 1297
	if (ci->disallow_premature)
		prepare_dummy_cursor = stmt->pre_executing;
B
Bruce Momjian 已提交
1298 1299 1300

	if (!old_statement)
	{
B
Byron Nikolaidis 已提交
1301
		SC_log_error(func, "No statement string", stmt);
1302
		return SQL_ERROR;
B
Byron Nikolaidis 已提交
1303
	}
1304

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

B
Bruce Momjian 已提交
1307
	/* Initialize current date */
1308 1309 1310 1311 1312
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;

1313 1314 1315 1316 1317 1318 1319
#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)
1320
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1321 1322 1323 1324 1325 1326 1327
	else if (stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY)
	{
		if (stmt->parse_status == STMT_PARSE_NONE)
			parse_statement(stmt);
		if (stmt->parse_status != STMT_PARSE_COMPLETE)
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
		else if (!stmt->ti || stmt->ntab != 1)
1328
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1329
		else
1330 1331 1332 1333 1334
		{
			/** search_from_pos = TRUE; **/
			from_pos = stmt->from_pos;
			where_pos = stmt->where_pos;
		}
1335
	}
1336
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1337 1338 1339 1340 1341 1342

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

1344
	stmt->miscinfo = 0;
H
Hiroshi Inoue 已提交
1345 1346
	token_len = 0;
	prev_token_end = TRUE;
1347 1348 1349 1350 1351 1352 1353 1354
	/* 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)
			{
1355 1356 1357 1358 1359
				if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1))
				{
					strcpy(new_statement, "BEGIN;");
					begin_first = TRUE;
				}
1360 1361 1362
			}
			else if (ci->drivers.use_declarefetch)
				SC_set_fetchcursor(stmt);
H
Hiroshi Inoue 已提交
1363
			sprintf(new_statement, "%sdeclare %s cursor for ",
1364
					new_statement, stmt->cursor_name);
1365
			npos = strlen(new_statement);
H
Hiroshi Inoue 已提交
1366
			check_cursor_ok = TRUE;
1367 1368 1369 1370
			declare_pos = npos;
		}
	}
	param_number = -1;
H
Hiroshi Inoue 已提交
1371
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1372
	make_encoded_str(&encstr, conn, old_statement);
H
Hiroshi Inoue 已提交
1373
#endif
B
Bruce Momjian 已提交
1374 1375
	for (opos = 0; opos < oldstmtlen; opos++)
	{
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
		if (from_pos == (Int4) opos)
		{
			CVT_APPEND_STR(", CTID, OID ");
		}
		else if (where_pos == (Int4) opos)
		{
			stmt->load_statement = malloc(npos + 1);
			memcpy(stmt->load_statement, new_statement, npos);
			stmt->load_statement[npos] = '\0';
		}
1386
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1387 1388
		oldchar = encoded_byte_check(&encstr, opos);
		if (ENCODE_STATUS(encstr) != 0)
1389
		{
1390
			CVT_APPEND_CHAR(oldchar);
1391 1392
			continue;
		}
1393

1394
		/*
1395
		 * From here we are guaranteed to handle a 1-byte character.
1396
		 */
H
Hiroshi Inoue 已提交
1397 1398
#else
		oldchar = old_statement[opos];
1399
#endif
1400

1401
		if (in_escape)			/* escape check */
1402 1403
		{
			in_escape = FALSE;
1404
			CVT_APPEND_CHAR(oldchar);
1405
			continue;
1406
		}
1407 1408
		else if (in_quote || in_dquote) /* quote/double quote check */
		{
1409 1410 1411
			if (oldchar == '\\')
				in_escape = TRUE;
			else if (oldchar == '\'' && in_quote)
1412
				in_quote = FALSE;
1413
			else if (oldchar == '\"' && in_dquote)
1414
				in_dquote = FALSE;
1415
			CVT_APPEND_CHAR(oldchar);
1416
			continue;
1417
		}
1418

1419
		/*
1420 1421
		 * From here we are guranteed to be in neither an escape, a quote
		 * nor a double quote.
1422
		 */
1423
		/* Squeeze carriage-return/linefeed pairs to linefeed only */
H
Hiroshi Inoue 已提交
1424
		else if (lf_conv && oldchar == '\r' && opos + 1 < oldstmtlen &&
1425
				 old_statement[opos + 1] == '\n')
1426
			continue;
1427

B
Bruce Momjian 已提交
1428 1429 1430 1431
		/*
		 * Handle literals (date, time, timestamp) and ODBC scalar
		 * functions
		 */
1432
		else if (oldchar == '{')
B
Bruce Momjian 已提交
1433
		{
H
Hiroshi Inoue 已提交
1434
			char	   *begin = &old_statement[opos], *end;
B
Bruce Momjian 已提交
1435

H
Hiroshi Inoue 已提交
1436 1437 1438
			/* procedure calls */
			if (stmt->statement_type == STMT_TYPE_PROCCALL)
			{
H
Hiroshi Inoue 已提交
1439
				int	lit_call_len = 4;
1440

H
Hiroshi Inoue 已提交
1441
				while (isspace((unsigned char) old_statement[++opos]));
H
Hiroshi Inoue 已提交
1442
				/* '?=' to accept return values exists ? */
H
Hiroshi Inoue 已提交
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
				if (old_statement[opos] == '?')
				{
					param_number++;
					while (isspace((unsigned char) old_statement[++opos]));
					if (old_statement[opos] != '=')
					{
						opos--;
						continue;
					}
					while (isspace((unsigned char) old_statement[++opos]));
				}
1454
				if (strnicmp(&old_statement[opos], "call", lit_call_len) ||
1455
					!isspace((unsigned char) old_statement[opos + lit_call_len]))
H
Hiroshi Inoue 已提交
1456 1457 1458 1459
				{
					opos--;
					continue;
				}
1460
				opos += lit_call_len;
1461
				CVT_APPEND_STR("SELECT ");
H
Hiroshi Inoue 已提交
1462
				if (my_strchr(conn, &old_statement[opos], '('))
1463
					proc_no_param = FALSE;
1464
				continue;
H
Hiroshi Inoue 已提交
1465
			}
H
Hiroshi Inoue 已提交
1466 1467
			if (convert_escape(begin, stmt, &npos, &new_stsize, &end
) != CONVERT_ESCAPE_OK)
H
Hiroshi Inoue 已提交
1468 1469 1470 1471
			{
				stmt->errormsg = "ODBC escape convert error";
				stmt->errornumber = STMT_EXEC_ERROR;
				return SQL_ERROR;
1472
			}
H
Hiroshi Inoue 已提交
1473 1474
			opos = end - old_statement; /* positioned at the last } */
			new_statement = stmt->stmt_with_params;
1475 1476
			if (isalnum(end[1]))
				CVT_APPEND_CHAR(' ');
1477 1478
			continue;
		}
H
Hiroshi Inoue 已提交
1479 1480
		/* End of a procedure call */
		else if (oldchar == '}' && stmt->statement_type == STMT_TYPE_PROCCALL)
1481 1482 1483
		{
			if (proc_no_param)
				CVT_APPEND_STR("()");
H
Hiroshi Inoue 已提交
1484
			continue;
1485
		}
1486

B
Bruce Momjian 已提交
1487 1488 1489 1490 1491
		/*
		 * 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.
		 */
1492
		else if (oldchar == '?')
B
Bruce Momjian 已提交
1493 1494 1495
			;					/* ok */
		else
		{
1496
			if (oldchar == '\'')
1497
				in_quote = TRUE;
1498
			else if (oldchar == '\\')
1499
				in_escape = TRUE;
1500
			else if (oldchar == '\"')
1501
				in_dquote = TRUE;
1502
			else
1503
			{
1504
				if (isspace((unsigned char) oldchar))
H
Hiroshi Inoue 已提交
1505 1506 1507 1508 1509 1510 1511 1512
				{
					if (!prev_token_end)
					{
						prev_token_end = TRUE;
						token_save[token_len] = '\0';
						if (token_len == 4)
						{
							if (check_cursor_ok &&
1513
								into_table_from(&old_statement[opos - token_len]))
H
Hiroshi Inoue 已提交
1514 1515 1516 1517 1518 1519 1520 1521
							{
								stmt->statement_type = STMT_TYPE_CREATE;
								SC_no_pre_executable(stmt);
								SC_no_fetchcursor(stmt);
								stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
								memmove(new_statement, new_statement + declare_pos, npos - declare_pos);
								npos -= declare_pos;
							}
1522
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
1523
							else if (search_from_pos && /* where's from clause */
1524
									 strnicmp(token_save, "from", 4) == 0)
H
Hiroshi Inoue 已提交
1525 1526 1527 1528 1529
							{
								search_from_pos = FALSE;
								npos -= 5;
								CVT_APPEND_STR(", CTID, OID from");
							}
1530
#endif   /* DRIVER_CURSOR_IMPLEMENT */
H
Hiroshi Inoue 已提交
1531 1532 1533
						}
						if (token_len == 3)
						{
1534 1535
							int			endpos;

H
Hiroshi Inoue 已提交
1536
							if (check_cursor_ok &&
1537 1538
								strnicmp(token_save, "for", 3) == 0 &&
								table_for_update(&old_statement[opos], &endpos))
H
Hiroshi Inoue 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
							{
								SC_no_fetchcursor(stmt);
								stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
								if (prepare_dummy_cursor)
								{
									npos -= 4;
									opos += endpos;
								}
								else
								{
									memmove(new_statement, new_statement + declare_pos, npos - declare_pos);
									npos -= declare_pos;
								}
							}
						}
1554
					}
H
Hiroshi Inoue 已提交
1555 1556 1557 1558 1559 1560 1561
				}
				else if (prev_token_end)
				{
					prev_token_end = FALSE;
					token_save[0] = oldchar;
					token_len = 1;
				}
H
Hiroshi Inoue 已提交
1562
				else if (token_len + 1 < sizeof(token_save))
H
Hiroshi Inoue 已提交
1563
					token_save[token_len++] = oldchar;
1564
			}
1565
			CVT_APPEND_CHAR(oldchar);
1566 1567 1568
			continue;
		}

1569 1570 1571
		/*
		 * Its a '?' parameter alright
		 */
1572 1573
		param_number++;

B
Bruce Momjian 已提交
1574
		if (param_number >= stmt->parameters_allocated)
1575 1576 1577
		{
			if (stmt->pre_executing)
			{
1578
				CVT_APPEND_STR("NULL");
1579 1580 1581 1582 1583
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1584
				CVT_APPEND_CHAR('?');
1585 1586 1587
				continue;
			}
		}
1588

B
Bruce Momjian 已提交
1589 1590 1591
		/* Assign correct buffers based on data at exec param or not */
		if (stmt->parameters[param_number].data_at_exec)
		{
1592 1593 1594
			used = stmt->parameters[param_number].EXEC_used ? *stmt->parameters[param_number].EXEC_used : SQL_NTS;
			buffer = stmt->parameters[param_number].EXEC_buffer;
		}
B
Bruce Momjian 已提交
1595 1596
		else
		{
H
Hiroshi Inoue 已提交
1597 1598
			UInt4	bind_size = stmt->options.param_bind_type;
			UInt4	ctypelen;
1599

H
Hiroshi Inoue 已提交
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
			buffer = stmt->parameters[param_number].buffer + offset;
			if (current_row > 0)
			{
				if (bind_size > 0)
					buffer += (bind_size * current_row);
				else if (ctypelen = ctype_length(stmt->parameters[param_number].CType), ctypelen > 0)
					buffer += current_row * ctypelen;
				else 
					buffer += current_row * stmt->parameters[param_number].buflen;
			}
			if (stmt->parameters[param_number].used)
			{
				UInt4	p_offset = offset;
				if (bind_size > 0)
					p_offset = offset + bind_size * current_row;
				else
					p_offset = offset + sizeof(SDWORD) * current_row;
				used = *(SDWORD *)((char *)stmt->parameters[param_number].used + p_offset);
			}
			else
				used = SQL_NTS;
1621 1622
		}

B
Bruce Momjian 已提交
1623 1624 1625
		/* Handle NULL parameter data */
		if (used == SQL_NULL_DATA)
		{
1626
			CVT_APPEND_STR("NULL");
1627 1628 1629
			continue;
		}

B
Bruce Momjian 已提交
1630 1631 1632 1633 1634 1635
		/*
		 * If no buffer, and it's not null, then what the hell is it? Just
		 * leave it alone then.
		 */
		if (!buffer)
		{
1636 1637
			if (stmt->pre_executing)
			{
1638
				CVT_APPEND_STR("NULL");
1639 1640 1641 1642 1643
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1644
				CVT_APPEND_CHAR('?');
1645 1646
				continue;
			}
1647
		}
1648 1649 1650

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

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

B
Bruce Momjian 已提交
1654
		/* replace DEFAULT with something we can use */
B
Bruce Momjian 已提交
1655
		if (param_ctype == SQL_C_DEFAULT)
1656 1657
			param_ctype = sqltype_to_default_ctype(param_sqltype);

H
Hiroshi Inoue 已提交
1658
		allocbuf = buf = NULL;
1659 1660 1661
		param_string[0] = '\0';
		cbuf[0] = '\0';

B
Bruce Momjian 已提交
1662 1663 1664 1665 1666 1667 1668
		/* Convert input C type to a neutral format */
		switch (param_ctype)
		{
			case SQL_C_BINARY:
			case SQL_C_CHAR:
				buf = buffer;
				break;
1669

H
Hiroshi Inoue 已提交
1670 1671 1672 1673 1674 1675 1676
#ifdef	UNICODE_SUPPORT
			case SQL_C_WCHAR:
				buf = allocbuf = ucs2_to_utf8((SQLWCHAR *) buffer, used / 2, &used);
				used *= 2;
				break;
#endif /* UNICODE_SUPPORT */

B
Bruce Momjian 已提交
1677
			case SQL_C_DOUBLE:
1678
				sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
1679 1680
						*((SDOUBLE *) buffer));
				break;
1681

B
Bruce Momjian 已提交
1682
			case SQL_C_FLOAT:
1683
				sprintf(param_string, "%.6g",
B
Bruce Momjian 已提交
1684 1685
						*((SFLOAT *) buffer));
				break;
1686

B
Bruce Momjian 已提交
1687 1688 1689 1690 1691
			case SQL_C_SLONG:
			case SQL_C_LONG:
				sprintf(param_string, "%ld",
						*((SDWORD *) buffer));
				break;
1692

H
Hiroshi Inoue 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
#if (ODBCVER >= 0x0300) && defined(ODBCINT64)
#ifdef WIN32
			case SQL_C_SBIGINT:
				sprintf(param_string, "%I64d",
						*((SQLBIGINT *) buffer));
				break;

			case SQL_C_UBIGINT:
				sprintf(param_string, "%I64u",
						*((SQLUBIGINT *) buffer));
				break;

#endif /* WIN32 */
#endif /* ODBCINT64 */
B
Bruce Momjian 已提交
1707 1708 1709 1710 1711
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				sprintf(param_string, "%d",
						*((SWORD *) buffer));
				break;
1712

B
Bruce Momjian 已提交
1713 1714 1715 1716 1717
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				sprintf(param_string, "%d",
						*((SCHAR *) buffer));
				break;
1718

B
Bruce Momjian 已提交
1719 1720 1721 1722
			case SQL_C_ULONG:
				sprintf(param_string, "%lu",
						*((UDWORD *) buffer));
				break;
1723

B
Bruce Momjian 已提交
1724 1725 1726 1727
			case SQL_C_USHORT:
				sprintf(param_string, "%u",
						*((UWORD *) buffer));
				break;
1728

B
Bruce Momjian 已提交
1729 1730 1731 1732
			case SQL_C_UTINYINT:
				sprintf(param_string, "%u",
						*((UCHAR *) buffer));
				break;
1733

B
Bruce Momjian 已提交
1734 1735 1736
			case SQL_C_BIT:
				{
					int			i = *((UCHAR *) buffer);
1737

B
Bruce Momjian 已提交
1738 1739 1740
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
				}
1741

B
Bruce Momjian 已提交
1742
			case SQL_C_DATE:
1743
#if (ODBCVER >= 0x0300)
1744
			case SQL_C_TYPE_DATE:		/* 91 */
1745
#endif
B
Bruce Momjian 已提交
1746 1747
				{
					DATE_STRUCT *ds = (DATE_STRUCT *) buffer;
1748

B
Bruce Momjian 已提交
1749 1750 1751
					st.m = ds->month;
					st.d = ds->day;
					st.y = ds->year;
1752

B
Bruce Momjian 已提交
1753 1754
					break;
				}
1755

B
Bruce Momjian 已提交
1756
			case SQL_C_TIME:
1757
#if (ODBCVER >= 0x0300)
1758
			case SQL_C_TYPE_TIME:		/* 92 */
1759
#endif
B
Bruce Momjian 已提交
1760 1761
				{
					TIME_STRUCT *ts = (TIME_STRUCT *) buffer;
1762

B
Bruce Momjian 已提交
1763 1764 1765
					st.hh = ts->hour;
					st.mm = ts->minute;
					st.ss = ts->second;
1766

B
Bruce Momjian 已提交
1767 1768
					break;
				}
1769

B
Bruce Momjian 已提交
1770
			case SQL_C_TIMESTAMP:
1771
#if (ODBCVER >= 0x0300)
1772
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
1773
#endif
B
Bruce Momjian 已提交
1774 1775
				{
					TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer;
1776

B
Bruce Momjian 已提交
1777 1778 1779 1780 1781 1782
					st.m = tss->month;
					st.d = tss->day;
					st.y = tss->year;
					st.hh = tss->hour;
					st.mm = tss->minute;
					st.ss = tss->second;
1783
					st.fr = tss->fraction;
1784

B
Bruce Momjian 已提交
1785
					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);
1786

B
Bruce Momjian 已提交
1787
					break;
1788

B
Bruce Momjian 已提交
1789 1790 1791 1792 1793
				}
			default:
				/* error */
				stmt->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters";
				stmt->errornumber = STMT_NOT_IMPLEMENTED_ERROR;
1794
				CVT_TERMINATE;	/* just in case */
B
Bruce Momjian 已提交
1795 1796 1797
				SC_log_error(func, "", stmt);
				return SQL_ERROR;
		}
1798

B
Bruce Momjian 已提交
1799 1800 1801 1802
		/*
		 * Now that the input data is in a neutral format, convert it to
		 * the desired output format (sqltype)
		 */
1803

B
Bruce Momjian 已提交
1804 1805 1806 1807 1808
		switch (param_sqltype)
		{
			case SQL_CHAR:
			case SQL_VARCHAR:
			case SQL_LONGVARCHAR:
H
Hiroshi Inoue 已提交
1809 1810 1811 1812 1813
#ifdef	UNICODE_SUPPORT
			case SQL_WCHAR:
			case SQL_WVARCHAR:
			case SQL_WLONGVARCHAR:
#endif /* UNICODE_SUPPORT */
1814

1815
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1816

B
Bruce Momjian 已提交
1817 1818
				/* it was a SQL_C_CHAR */
				if (buf)
1819
					CVT_SPECIAL_CHARS(buf, used);
1820

B
Bruce Momjian 已提交
1821 1822
				/* it was a numeric type */
				else if (param_string[0] != '\0')
1823
					CVT_APPEND_STR(param_string);
1824

B
Bruce Momjian 已提交
1825 1826 1827 1828 1829
				/* 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);
1830

1831
					CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1832
				}
1833

1834
				CVT_APPEND_CHAR('\'');	/* Close Quote */
1835

B
Bruce Momjian 已提交
1836
				break;
1837

B
Bruce Momjian 已提交
1838
			case SQL_DATE:
1839
#if (ODBCVER >= 0x0300)
1840
			case SQL_TYPE_DATE:	/* 91 */
1841
#endif
B
Bruce Momjian 已提交
1842 1843 1844 1845 1846
				if (buf)
				{				/* copy char data to time */
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1847

H
Hiroshi Inoue 已提交
1848
				sprintf(tmp, "'%.4d-%.2d-%.2d'::date", st.y, st.m, st.d);
1849

1850
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1851
				break;
1852

B
Bruce Momjian 已提交
1853
			case SQL_TIME:
1854
#if (ODBCVER >= 0x0300)
1855
			case SQL_TYPE_TIME:	/* 92 */
1856
#endif
B
Bruce Momjian 已提交
1857 1858 1859 1860 1861
				if (buf)
				{				/* copy char data to time */
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1862

H
Hiroshi Inoue 已提交
1863
				sprintf(tmp, "'%.2d:%.2d:%.2d'::time", st.hh, st.mm, st.ss);
1864

1865
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1866
				break;
1867

B
Bruce Momjian 已提交
1868
			case SQL_TIMESTAMP:
1869
#if (ODBCVER >= 0x0300)
1870
			case SQL_TYPE_TIMESTAMP:	/* 93 */
1871
#endif
1872

B
Bruce Momjian 已提交
1873 1874 1875 1876 1877
				if (buf)
				{
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1878

1879 1880 1881 1882
				/*
				 * sprintf(tmp, "'%.4d-%.2d-%.2d %.2d:%.2d:%.2d'", st.y,
				 * st.m, st.d, st.hh, st.mm, st.ss);
				 */
1883 1884
				tmp[0] = '\'';
				/* Time zone stuff is unreliable */
H
Hiroshi Inoue 已提交
1885
				stime2timestamp(&st, tmp + 1, USE_ZONE, PG_VERSION_GE(conn, 7.2));
H
Hiroshi Inoue 已提交
1886
				strcat(tmp, "'::timestamp");
1887

1888
				CVT_APPEND_STR(tmp);
1889

B
Bruce Momjian 已提交
1890
				break;
1891

B
Bruce Momjian 已提交
1892 1893 1894
			case SQL_BINARY:
			case SQL_VARBINARY:/* non-ascii characters should be
								 * converted to octal */
1895
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1896

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

1899
				CVT_APPEND_BINARY(buf, used);
1900

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

B
Bruce Momjian 已提交
1903
				break;
1904

B
Bruce Momjian 已提交
1905 1906 1907 1908 1909 1910 1911
			case SQL_LONGVARBINARY:

				if (stmt->parameters[param_number].data_at_exec)
					lobj_oid = stmt->parameters[param_number].lobj_oid;
				else
				{
					/* begin transaction if needed */
1912
					if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
1913
					{
H
Hiroshi Inoue 已提交
1914
						if (!CC_begin(conn))
B
Bruce Momjian 已提交
1915 1916 1917 1918 1919 1920 1921
						{
							stmt->errormsg = "Could not begin (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
					}
B
Byron Nikolaidis 已提交
1922

B
Bruce Momjian 已提交
1923
					/* store the oid */
1924
					lobj_oid = lo_creat(conn, INV_READ | INV_WRITE);
B
Bruce Momjian 已提交
1925 1926
					if (lobj_oid == 0)
					{
B
Byron Nikolaidis 已提交
1927
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1928
						stmt->errormsg = "Couldnt create (in-line) large object.";
B
Byron Nikolaidis 已提交
1929 1930 1931
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}
B
Bruce Momjian 已提交
1932 1933

					/* store the fd */
1934
					lobj_fd = lo_open(conn, lobj_oid, INV_WRITE);
B
Bruce Momjian 已提交
1935 1936
					if (lobj_fd < 0)
					{
B
Byron Nikolaidis 已提交
1937
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1938
						stmt->errormsg = "Couldnt open (in-line) large object for writing.";
B
Byron Nikolaidis 已提交
1939 1940 1941 1942
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}

1943
					retval = lo_write(conn, lobj_fd, buffer, used);
1944

1945
					lo_close(conn, lobj_fd);
1946

B
Bruce Momjian 已提交
1947
					/* commit transaction if needed */
1948
					if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
1949
					{
H
Hiroshi Inoue 已提交
1950
						if (!CC_commit(conn))
B
Bruce Momjian 已提交
1951 1952 1953 1954 1955 1956 1957 1958
						{
							stmt->errormsg = "Could not commit (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
					}
				}
1959

B
Bruce Momjian 已提交
1960 1961 1962 1963 1964 1965
				/*
				 * 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);
1966
				CVT_APPEND_STR(param_string);
1967

B
Bruce Momjian 已提交
1968 1969 1970 1971 1972 1973 1974
				break;

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

B
Bruce Momjian 已提交
1976 1977 1978 1979
			case SQL_REAL:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float4", param_string);
1980
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1981 1982 1983 1984 1985 1986
				break;
			case SQL_FLOAT:
			case SQL_DOUBLE:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float8", param_string);
1987
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
				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);
2000
				CVT_APPEND_STR(cbuf);
B
Bruce Momjian 已提交
2001 2002 2003
				break;
			default:			/* a numeric type or SQL_BIT */
				if (param_sqltype == SQL_BIT)
2004
					CVT_APPEND_CHAR('\'');		/* Open Quote */
B
Bruce Momjian 已提交
2005 2006 2007

				if (buf)
				{
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
					switch (used)
					{
						case SQL_NULL_DATA:
							break;
						case SQL_NTS:
							CVT_APPEND_STR(buf);
							break;
						default:
							CVT_APPEND_DATA(buf, used);
					}
B
Bruce Momjian 已提交
2018 2019
				}
				else
2020
					CVT_APPEND_STR(param_string);
B
Bruce Momjian 已提交
2021 2022

				if (param_sqltype == SQL_BIT)
2023
					CVT_APPEND_CHAR('\'');		/* Close Quote */
B
Bruce Momjian 已提交
2024 2025

				break;
2026
		}
H
Hiroshi Inoue 已提交
2027 2028 2029 2030
#ifdef	UNICODE_SUPPORT
		if (allocbuf)
			free(allocbuf);
#endif /* UNICODE_SUPPORT */
B
Bruce Momjian 已提交
2031
	}							/* end, for */
2032

B
Bruce Momjian 已提交
2033
	/* make sure new_statement is always null-terminated */
2034
	CVT_TERMINATE;
2035

2036
	if (conn->DriverToDataSource != NULL)
B
Bruce Momjian 已提交
2037 2038 2039
	{
		int			length = strlen(new_statement);

2040
		conn->DriverToDataSource(conn->translation_option,
2041 2042 2043 2044
								 SQL_CHAR,
								 new_statement, length,
								 new_statement, length, NULL,
								 NULL, 0, NULL);
B
Byron Nikolaidis 已提交
2045 2046
	}

2047
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
2048
	if (search_from_pos)
2049
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
2050 2051 2052 2053 2054 2055
	if (!stmt->load_statement && from_pos >=0)
	{
		stmt->load_statement = malloc(npos + 1);
		memcpy(stmt->load_statement, new_statement, npos);
		stmt->load_statement[npos] = '\0';
	}
2056
#endif   /* DRIVER_CURSOR_IMPLEMENT */
2057 2058
	if (prepare_dummy_cursor && SC_is_pre_executable(stmt))
	{
2059 2060
		char		fetchstr[128];

2061 2062
		sprintf(fetchstr, ";fetch backward in %s;close %s;",
				stmt->cursor_name, stmt->cursor_name);
2063 2064
		if (begin_first && CC_is_in_autocommit(conn))
			strcat(fetchstr, "COMMIT;");
2065 2066 2067 2068
		CVT_APPEND_STR(fetchstr);
		stmt->inaccurate_result = TRUE;
	}

2069 2070 2071
	return SQL_SUCCESS;
}

2072

H
Hiroshi Inoue 已提交
2073 2074
static const char *
mapFunction(const char *func, int param_count)
2075
{
B
Bruce Momjian 已提交
2076
	int			i;
2077 2078

	for (i = 0; mapFuncs[i][0]; i++)
H
Hiroshi Inoue 已提交
2079 2080 2081 2082 2083 2084 2085 2086
	{
		if (mapFuncs[i][0][0] == '%')
		{
			if (mapFuncs[i][0][1] - '0' == param_count &&
			    !stricmp(mapFuncs[i][0] + 2, func))
				return mapFuncs[i][1];
		}
		else if (!stricmp(mapFuncs[i][0], func))
2087
			return mapFuncs[i][1];
H
Hiroshi Inoue 已提交
2088
	}
2089 2090 2091

	return NULL;
}
2092

2093

H
Hiroshi Inoue 已提交
2094 2095 2096
static int inner_convert_escape(const ConnectionClass *conn, const char *value, char *result, UInt4 maxLen, const char **input_resume, UInt4 *count);
static int processParameters(const ConnectionClass *conn, const char *value, char *result, UInt4 maxLen, UInt4 *input_consumed, UInt4 *count, Int4 param_pos[][2]);

2097
/*
H
Hiroshi Inoue 已提交
2098 2099
 * inner_convert_escape()
 * work with embedded escapes sequences
2100
 */
H
Hiroshi Inoue 已提交
2101 2102 2103 2104 2105
     
static
int inner_convert_escape(const ConnectionClass *conn, const char *value,
		char *result, UInt4 maxLen, const char **input_resume,
		UInt4 *count)
2106
{
H
Hiroshi Inoue 已提交
2107 2108 2109 2110 2111
	static const char *func = "inner_convert_escape";
	int	subret, param_count;
	char valnts[1024], params[1024];
	char key[33], *end;
	const char *valptr;
2112
	UInt4	vlen, prtlen, input_consumed, param_consumed, extra_len;
H
Hiroshi Inoue 已提交
2113 2114 2115 2116 2117
	Int4	param_pos[16][2];
 
	valptr = value;
	if (*valptr == '{') /* skip the first { */
		valptr++;
2118
	/* Separate off the key, skipping leading and trailing whitespace */
H
Hiroshi Inoue 已提交
2119 2120 2121 2122 2123 2124 2125 2126
	while ((*valptr != '\0') && isspace((unsigned char) *valptr))
		valptr++;
	sscanf(valptr, "%32s", key);
	while ((*valptr != '\0') && (!isspace((unsigned char) *valptr)))
		valptr++;
	while ((*valptr != '\0') && isspace((unsigned char) *valptr))
		valptr++;
     
H
Hiroshi Inoue 已提交
2127
	if (end = my_strchr(conn, valptr, '}'), NULL == end)
H
Hiroshi Inoue 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
	{
		mylog("%s couldn't find the ending }\n",func);
		return CONVERT_ESCAPE_ERROR;
	}
	if (vlen = (UInt4)(end - valptr), maxLen <= vlen)
		return CONVERT_ESCAPE_OVERFLOW;
	memcpy(valnts, valptr, vlen);
	valnts[vlen] = '\0';
	*input_resume = valptr + vlen; /* resume from the last } */
	mylog("%s: key='%s', val='%s'\n", func, key, valnts);
     
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
	extra_len = 0;
	if (isalnum(result[-1])) /* Avoid the concatenation of the function name with the previous word. Aceto */
	{
		if (1 >= maxLen)
		{
			mylog("%s %d bytes buffer overflow\n", func, maxLen);
			return CONVERT_ESCAPE_OVERFLOW;
		}
		*result = ' ';
		result++;
		*result = '\0';
		maxLen--;
		extra_len++;
	}
H
Hiroshi Inoue 已提交
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
	if (strcmp(key, "d") == 0)
	{
		/* Literal; return the escape part adding type cast */
		prtlen = snprintf(result, maxLen, "%s::date", valnts);
	}
	else if (strcmp(key, "t") == 0)
	{
		/* Literal; return the escape part adding type cast */
		prtlen = snprintf(result, maxLen, "%s::time", valnts);
	}
	else if (strcmp(key, "ts") == 0)
	{
		/* Literal; return the escape part adding type cast */
		if (PG_VERSION_LT(conn, 7.1))
			prtlen = snprintf(result, maxLen, "%s::datetime", valnts);
		else
			prtlen = snprintf(result, maxLen, "%s::timestamp", valnts);
	}
	else if (strcmp(key, "oj") == 0) /* {oj syntax support for 7.1 * servers */
B
Bruce Momjian 已提交
2172
	{
2173
		/* Literal; return the escape part as-is */
H
Hiroshi Inoue 已提交
2174 2175
		strncpy(result, valnts, maxLen);
		prtlen = vlen; 
2176
	}
B
Bruce Momjian 已提交
2177 2178 2179 2180 2181
	else if (strcmp(key, "fn") == 0)
	{
		/*
		 * Function invocation Separate off the func name, skipping
		 * trailing whitespace.
2182
		 */
H
Hiroshi Inoue 已提交
2183 2184 2185 2186 2187
		char	*funcEnd = valnts;
		char     svchar;
		const char	*mapExpr;
     
		params[sizeof(params)-1] = '\0';
2188 2189

		while ((*funcEnd != '\0') && (*funcEnd != '(') &&
H
Hiroshi Inoue 已提交
2190
			(!isspace((unsigned char) *funcEnd)))
2191
			funcEnd++;
2192 2193
		svchar = *funcEnd;
		*funcEnd = '\0';
H
Hiroshi Inoue 已提交
2194
		sscanf(valnts, "%32s", key);
2195
		*funcEnd = svchar;
2196 2197
		while ((*funcEnd != '\0') && isspace((unsigned char) *funcEnd))
			funcEnd++;
2198

B
Bruce Momjian 已提交
2199
		/*
H
Hiroshi Inoue 已提交
2200
 		 * We expect left parenthesis here, else return fn body as-is
B
Bruce Momjian 已提交
2201
		 * since it is one of those "function constants".
2202
		 */
B
Bruce Momjian 已提交
2203 2204
		if (*funcEnd != '(')
		{
H
Hiroshi Inoue 已提交
2205 2206
			strncpy(result, valnts, maxLen);
			return CONVERT_ESCAPE_OK;
2207
		}
B
Bruce Momjian 已提交
2208 2209

		/*
H
Hiroshi Inoue 已提交
2210 2211 2212
		 * Process parameter list and inner escape
		 * sequences
		 * Aceto 2002-01-29
2213
		 */
H
Hiroshi Inoue 已提交
2214 2215 2216 2217 2218 2219

		valptr += (UInt4)(funcEnd - valnts);
		if (subret = processParameters(conn, valptr, params, sizeof(params) - 1, &input_consumed, &param_consumed, param_pos), CONVERT_ESCAPE_OK != subret) 
			return CONVERT_ESCAPE_ERROR;

		for (param_count = 0;; param_count++)
B
Bruce Momjian 已提交
2220
		{
H
Hiroshi Inoue 已提交
2221 2222
			if (param_pos[param_count][0] < 0)
				break;
2223
		}
H
Hiroshi Inoue 已提交
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
		if (param_count == 1 &&
		    param_pos[0][1] < param_pos[0][0])
			param_count = 0;
		
		mapExpr = mapFunction(key, param_count);
		if (mapExpr == NULL)
			prtlen = snprintf(result, maxLen, "%s%s", key, params);
		else
		{
			const char *mapptr;
			int	from, to, pidx, paramlen;

			for (prtlen = 0, mapptr = mapExpr; *mapptr; mapptr++)
			{
				if (prtlen + 1 >= maxLen) /* buffer overflow */
				{
					result[prtlen] = '\0';
					prtlen++;
					break;
				}
				if (*mapptr != '$')
				{
					result[prtlen++] = *mapptr;
					continue;
				}
				mapptr++;
				if (*mapptr == '*')
				{
					from = 1;
					to = param_consumed - 2;
				}
				else if (isdigit(*mapptr))
				{
					pidx = *mapptr - '0' - 1;
					if (pidx < 0 ||
					    param_pos[pidx][0] <0)
					{
						qlog("%s %dth param not found for the expression %s\n", pidx + 1, mapExpr);
						return CONVERT_ESCAPE_ERROR;
					}
					from = param_pos[pidx][0];
					to = param_pos[pidx][1];
				}
				else
				{
					qlog("%s internal expression error %s\n", func, mapExpr);
					return CONVERT_ESCAPE_ERROR;
				}
				paramlen = to - from + 1;
				if (prtlen + paramlen >= maxLen) /* buffer overflow */
				{
					prtlen = maxLen;
					break;
				}
				if (paramlen > 0)
					memcpy(&result[prtlen], params + from, paramlen);
				prtlen += paramlen;
			}
			if (prtlen < maxLen)
				result[prtlen] = '\0';
			/** prtlen = snprintf(result, maxLen, "%s%s", mapExpr, params); **/
		}
		valptr += input_consumed;
		*input_resume = valptr;
2288
	}
B
Bruce Momjian 已提交
2289 2290
	else
	{
2291
		/* Bogus key, leave untranslated */
H
Hiroshi Inoue 已提交
2292 2293 2294 2295
		return CONVERT_ESCAPE_ERROR;
	}
     
	if (count)
2296
		*count = prtlen + extra_len;
H
Hiroshi Inoue 已提交
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
	if (prtlen < 0 || prtlen >= maxLen) /* buffer overflow */
	{
		mylog("%s %d bytes buffer overflow\n", func, maxLen);
		return CONVERT_ESCAPE_OVERFLOW;
	}
	return CONVERT_ESCAPE_OK;
}
     
/*
 * processParameters()
 * Process function parameters and work with embedded escapes sequences.
 */
     
static
int processParameters(const ConnectionClass *conn, const char *value,
		char *result, UInt4 maxLen, UInt4 *input_consumed,
		UInt4 *output_count, Int4 param_pos[][2])
{
	int		innerParenthesis, subret, param_count;
	UInt4	ipos, count, inner_count;
	unsigned char	stop;
	const char	*valptr;
	char	buf[1024];
	BOOL	in_quote, in_dquote, in_escape, leadingSpace;
H
Hiroshi Inoue 已提交
2321 2322 2323
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif   /* MULTIBYTE */
H
Hiroshi Inoue 已提交
2324 2325 2326 2327 2328 2329
 
	buf[sizeof(buf)-1] = '\0';
	innerParenthesis = 0;
	in_quote = in_dquote = in_escape = leadingSpace = FALSE;
	param_count = 0;
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2330
	make_encoded_str(&encstr, conn, value);
H
Hiroshi Inoue 已提交
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
#endif /* MULTIBYTE */
	/* begin with outer '(' */
	for (stop = FALSE, valptr = value, ipos = count = 0; *valptr != '\0'; ipos++, valptr++)
	{
		if (leadingSpace)
		{
			if (isspace(*valptr))
				continue;
			leadingSpace = FALSE;
		}
		if (count + 1 >= maxLen) /* buffer overflow */
		{
			*input_consumed = 0;
			result[count++] = '\0';
			return CONVERT_ESCAPE_OVERFLOW;
		}
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2348 2349
		encoded_byte_check(&encstr, ipos);
		if (ENCODE_STATUS(encstr) != 0)
H
Hiroshi Inoue 已提交
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 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
		{
			result[count++] = *valptr;
			continue;
		}
		/*
		 * From here we are guaranteed to handle a 1-byte character.
		 */
#endif
		if (in_quote)
		{
			if (in_escape)
				in_escape = FALSE;
			else if (*valptr == '\\')
				in_escape = TRUE;
			else if (*valptr == '\'')
				in_quote = FALSE;
			result[count++] = *valptr;
			continue;
		}
		else if (in_dquote)
		{
			if (*valptr == '\"')
				in_dquote = FALSE;
			result[count++] = *valptr;
			continue;
		}
		switch (*valptr)
		{
			case '\'':
				in_quote = TRUE;
				break;
			case '\"':
				in_dquote = TRUE;
				break;
			case ',':
				if (1 == innerParenthesis)
				{
					param_pos[param_count][1] = count - 1;
					param_count++;
					param_pos[param_count][0] = count + 1;
					param_pos[param_count][1] = -1;
					leadingSpace = TRUE;
				}
				break;
			case '(':
				if (0 == innerParenthesis)
				{
					param_pos[param_count][0] = count + 1;
					param_pos[param_count][1] = -1;
					leadingSpace = TRUE;
				}
				innerParenthesis++;
				break;
     
			case ')':
				innerParenthesis--;
				if (0 == innerParenthesis)
				{
					param_pos[param_count][1] = count - 1;
					param_count++;
					param_pos[param_count][0] =
					param_pos[param_count][1] = -1;
				}
				break;
     
			case '}':
				stop = TRUE;
				break;
     
			case '{':
				if (subret = inner_convert_escape(conn, valptr, buf, sizeof(buf) - 1, &valptr, &inner_count), CONVERT_ESCAPE_OK != subret)
					return CONVERT_ESCAPE_ERROR;
     
				if (inner_count + count >= maxLen)
					return CONVERT_ESCAPE_OVERFLOW;
				memcpy(&result[count], buf, inner_count); 
				count += inner_count;
				ipos = (UInt4) (valptr - value);
				continue;
		}
		if (stop) /* returns with the last } position */
			break;
		result[count++] = *valptr;
	}
	if (param_pos[param_count][0] >= 0)
	{
		mylog("processParameters closing ) not found %d\n", innerParenthesis);
		return CONVERT_ESCAPE_ERROR;
2438
	}
H
Hiroshi Inoue 已提交
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
	result[count] = '\0';
	*input_consumed = ipos;
	if (output_count)
		*output_count = count;
	return CONVERT_ESCAPE_OK;
}
     
/*
 * convert_escape()
 * This function returns a pointer to static memory!
 */
     
int
convert_escape(const char *value, StatementClass *stmt, int *npos, int *stsize, const char **val_resume)
{
	int	ret, pos = *npos;
	UInt4 	count;
2456

H
Hiroshi Inoue 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
	while (ret = inner_convert_escape(SC_get_conn(stmt), value,
		stmt->stmt_with_params + pos, *stsize - pos, val_resume, &count),
		CONVERT_ESCAPE_OVERFLOW == ret)
	{
		if ((*stsize = enlarge_statement(stmt, *stsize * 2)) <= 0)
			return CONVERT_ESCAPE_ERROR;
	}
	if (CONVERT_ESCAPE_OK == ret)
		*npos += count;
	return ret;
2467 2468 2469
}


2470 2471
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
2472
{
2473 2474
	size_t		i = 0,
				out = 0;
2475

2476
	for (i = 0; s[i]; i++)
B
Bruce Momjian 已提交
2477
	{
2478
		if (s[i] == '$' || s[i] == ',' || s[i] == ')')
B
Bruce Momjian 已提交
2479
			;					/* skip these characters */
2480
		else
2481 2482
		{
			if (out + 1 >= soutmax)
2483
				return FALSE;	/* sout is too short */
2484 2485 2486 2487 2488
			if (s[i] == '(')
				sout[out++] = '-';
			else
				sout[out++] = s[i];
		}
2489
	}
2490 2491
	sout[out] = '\0';
	return TRUE;
2492 2493 2494
}


2495 2496 2497 2498
/*
 *	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
 */
2499
char
2500
parse_datetime(char *buf, SIMPLE_TIME *st)
2501
{
B
Bruce Momjian 已提交
2502 2503 2504 2505 2506 2507 2508 2509
	int			y,
				m,
				d,
				hh,
				mm,
				ss;
	int			nf;

2510 2511
	y = m = d = hh = mm = ss = 0;

2512 2513 2514 2515 2516 2517 2518 2519
	/* escape sequence ? */
	if (buf[0] == '{')
	{
		while (*(++buf) && *buf != '\'');
		if (!(*buf))
			return FALSE;
		buf++;
	}
B
Bruce Momjian 已提交
2520 2521
	if (buf[4] == '-')			/* year first */
		nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss);
2522
	else
B
Bruce Momjian 已提交
2523
		nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss);
2524

B
Bruce Momjian 已提交
2525 2526
	if (nf == 5 || nf == 6)
	{
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
		st->y = y;
		st->m = m;
		st->d = d;
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

B
Bruce Momjian 已提交
2537
	if (buf[4] == '-')			/* year first */
2538 2539 2540 2541
		nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d);
	else
		nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y);

B
Bruce Momjian 已提交
2542 2543
	if (nf == 3)
	{
2544 2545 2546 2547 2548 2549 2550 2551
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

	nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss);
B
Bruce Momjian 已提交
2552 2553
	if (nf == 2 || nf == 3)
	{
2554 2555 2556 2557 2558 2559 2560 2561 2562
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

	return FALSE;
}
2563

2564

2565
/*	Change linefeed to carriage-return/linefeed */
2566
int
H
Hiroshi Inoue 已提交
2567
convert_linefeeds(const char *si, char *dst, size_t max, BOOL convlf, BOOL *changed)
2568
{
B
Bruce Momjian 已提交
2569 2570
	size_t		i = 0,
				out = 0;
2571

2572 2573 2574 2575
	if (max == 0)
		max = 0xffffffff;
	*changed = FALSE;
	for (i = 0; si[i] && out < max - 1; i++)
B
Bruce Momjian 已提交
2576
	{
H
Hiroshi Inoue 已提交
2577
		if (convlf && si[i] == '\n')
B
Bruce Momjian 已提交
2578 2579 2580 2581
		{
			/* Only add the carriage-return if needed */
			if (i > 0 && si[i - 1] == '\r')
			{
2582 2583 2584 2585
				if (dst)
					dst[out++] = si[i];
				else
					out++;
B
Byron Nikolaidis 已提交
2586 2587
				continue;
			}
2588
			*changed = TRUE;
B
Byron Nikolaidis 已提交
2589

2590 2591 2592 2593 2594 2595 2596
			if (dst)
			{
				dst[out++] = '\r';
				dst[out++] = '\n';
			}
			else
				out += 2;
2597 2598
		}
		else
2599 2600 2601 2602 2603 2604
		{
			if (dst)
				dst[out++] = si[i];
			else
				out++;
		}
2605
	}
2606 2607
	if (dst)
		dst[out] = '\0';
2608
	return out;
2609 2610
}

2611 2612 2613 2614 2615

/*
 *	Change carriage-return/linefeed to just linefeed
 *	Plus, escape any special characters.
 */
2616
int
H
Hiroshi Inoue 已提交
2617
convert_special_chars(const char *si, char *dst, int used, BOOL convlf, int ccsc)
2618
{
B
Bruce Momjian 已提交
2619 2620 2621
	size_t		i = 0,
				out = 0,
				max;
2622
	char	   *p = NULL;
H
Hiroshi Inoue 已提交
2623 2624 2625
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif
2626 2627 2628 2629 2630 2631


	if (used == SQL_NTS)
		max = strlen(si);
	else
		max = used;
2632 2633 2634 2635 2636
	if (dst)
	{
		p = dst;
		p[0] = '\0';
	}
H
Hiroshi Inoue 已提交
2637
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2638
	encoded_str_constr(&encstr, ccsc, si);
H
Hiroshi Inoue 已提交
2639
#endif
2640

H
Hiroshi Inoue 已提交
2641
	for (i = 0; i < max && si[i]; i++)
B
Bruce Momjian 已提交
2642
	{
2643
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2644 2645
		encoded_nextchar(&encstr);
		if (ENCODE_STATUS(encstr) != 0)
2646 2647 2648 2649 2650 2651 2652
		{
			if (p)
				p[out] = si[i];
			out++;
			continue;
		}
#endif
H
Hiroshi Inoue 已提交
2653
		if (convlf && si[i] == '\r' && si[i + 1] == '\n')
2654
			continue;
B
Byron Nikolaidis 已提交
2655
		else if (si[i] == '\'' || si[i] == '\\')
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665
		{
			if (p)
				p[out++] = '\\';
			else
				out++;
		}
		if (p)
			p[out++] = si[i];
		else
			out++;
2666
	}
2667 2668 2669
	if (p)
		p[out] = '\0';
	return out;
2670 2671
}

2672

2673 2674
/*	!!! Need to implement this function !!!  */
int
2675
convert_pgbinary_to_char(const char *value, char *rgbValue, int cbValueMax)
2676
{
2677 2678 2679
	mylog("convert_pgbinary_to_char: value = '%s'\n", value);

	strncpy_null(rgbValue, value, cbValueMax);
2680 2681 2682
	return 0;
}

2683

2684
static unsigned int
2685
conv_from_octal(const unsigned char *s)
2686
{
B
Bruce Momjian 已提交
2687 2688
	int			i,
				y = 0;
2689

B
Bruce Momjian 已提交
2690 2691
	for (i = 1; i <= 3; i++)
		y += (s[i] - 48) * (int) pow(8, 3 - i);
2692 2693

	return y;
2694

2695 2696
}

2697

2698
static unsigned int
2699
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
2700
{
B
Bruce Momjian 已提交
2701 2702 2703
	int			i,
				y = 0,
				val;
2704

B
Bruce Momjian 已提交
2705 2706 2707 2708 2709 2710 2711 2712
	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 已提交
2713

B
Bruce Momjian 已提交
2714
		y += val * (int) pow(16, 2 - i);
B
Byron Nikolaidis 已提交
2715 2716 2717 2718 2719
	}

	return y;
}

2720

B
Bruce Momjian 已提交
2721
/*	convert octal escapes to bytes */
2722
int
2723
convert_from_pgbinary(const unsigned char *value, unsigned char *rgbValue, int cbValueMax)
2724
{
2725 2726
	size_t		i,
				ilen = strlen(value);
B
Bruce Momjian 已提交
2727
	int			o = 0;
2728

B
Bruce Momjian 已提交
2729

2730
	for (i = 0; i < ilen;)
B
Bruce Momjian 已提交
2731 2732 2733
	{
		if (value[i] == '\\')
		{
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
			if (value[i + 1] == '\\')
			{
				rgbValue[o] = value[i];
				i += 2;
			}
			else
			{
				rgbValue[o] = conv_from_octal(&value[i]);
				i += 4;
			}
2744
		}
B
Bruce Momjian 已提交
2745
		else
2746 2747 2748 2749
			rgbValue[o] = value[i++];
		mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]);
		o++;
	}
2750

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

2753 2754 2755 2756
	return o;
}


2757
static char *
2758 2759
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
2760 2761
	int			i;
	static char x[6];
2762 2763 2764 2765 2766

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

B
Bruce Momjian 已提交
2767 2768
	for (i = 4; i > 1; i--)
	{
2769 2770 2771 2772 2773 2774 2775
		x[i] = (val & 7) + 48;
		val >>= 3;
	}

	return x;
}

2776

B
Bruce Momjian 已提交
2777
/*	convert non-ascii bytes to octal escape sequences */
2778
int
2779
convert_to_pgbinary(const unsigned char *in, char *out, int len)
2780
{
B
Bruce Momjian 已提交
2781 2782
	int			i,
				o = 0;
2783

B
Bruce Momjian 已提交
2784 2785
	for (i = 0; i < len; i++)
	{
2786
		mylog("convert_to_pgbinary: in[%d] = %d, %c\n", i, in[i], in[i]);
B
Bruce Momjian 已提交
2787
		if (isalnum(in[i]) || in[i] == ' ')
2788
			out[o++] = in[i];
B
Bruce Momjian 已提交
2789 2790 2791
		else
		{
			strcpy(&out[o], conv_to_octal(in[i]));
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
			o += 5;
		}
	}

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

	return o;
}


B
Byron Nikolaidis 已提交
2802
void
2803
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2804
{
2805 2806
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2807
				o = 0;
B
Byron Nikolaidis 已提交
2808

2809
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2810 2811 2812
	{
		if (in[i] == '+')
		{
B
Byron Nikolaidis 已提交
2813 2814 2815
			sprintf(&out[o], "%%2B");
			o += 3;
		}
B
Bruce Momjian 已提交
2816
		else if (isspace((unsigned char) in[i]))
B
Byron Nikolaidis 已提交
2817
			out[o++] = '+';
B
Bruce Momjian 已提交
2818 2819
		else if (!isalnum((unsigned char) in[i]))
		{
2820
			sprintf(&out[o], "%%%02x", (unsigned char) in[i]);
B
Byron Nikolaidis 已提交
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
			o += 3;
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}


void
2831
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2832
{
2833 2834
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2835
				o = 0;
B
Byron Nikolaidis 已提交
2836

2837
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2838
	{
B
Byron Nikolaidis 已提交
2839 2840
		if (in[i] == '+')
			out[o++] = ' ';
B
Bruce Momjian 已提交
2841 2842
		else if (in[i] == '%')
		{
B
Byron Nikolaidis 已提交
2843
			sprintf(&out[o++], "%c", conv_from_hex(&in[i]));
B
Bruce Momjian 已提交
2844
			i += 2;
B
Byron Nikolaidis 已提交
2845 2846 2847 2848 2849 2850 2851
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}

2852 2853 2854 2855
static const char *hextbl = "0123456789ABCDEF";
static int
pg_bin2hex(UCHAR *src, UCHAR *dst, int length)
{
2856 2857 2858 2859 2860 2861
	UCHAR		chr,
			   *src_wk,
			   *dst_wk;
	BOOL		backwards;
	int			i;

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
	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;
}
2891

2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
/*-------
 *	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.
 *-------
 */
2908
int
2909 2910
convert_lo(StatementClass *stmt, const void *value, Int2 fCType, PTR rgbValue,
		   SDWORD cbValueMax, SDWORD *pcbValue)
2911
{
B
Bruce Momjian 已提交
2912 2913 2914 2915
	Oid			oid;
	int			retval,
				result,
				left = -1;
T
Tom Lane 已提交
2916
	BindInfoClass *bindInfo = NULL;
2917 2918
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
2919
	int			factor = (fCType == SQL_C_CHAR ? 2 : 1);
2920

2921
	/* If using SQLGetData, then current_col will be set */
B
Bruce Momjian 已提交
2922 2923
	if (stmt->current_col >= 0)
	{
2924 2925 2926
		bindInfo = &stmt->bindings[stmt->current_col];
		left = bindInfo->data_left;
	}
2927

B
Bruce Momjian 已提交
2928 2929 2930 2931
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
2932

B
Bruce Momjian 已提交
2933 2934
	if (!bindInfo || bindInfo->data_left == -1)
	{
B
Byron Nikolaidis 已提交
2935
		/* begin transaction if needed */
2936
		if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
2937
		{
H
Hiroshi Inoue 已提交
2938
			if (!CC_begin(conn))
B
Bruce Momjian 已提交
2939
			{
B
Byron Nikolaidis 已提交
2940 2941 2942 2943 2944 2945
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

2946
		oid = atoi(value);
2947
		stmt->lobj_fd = lo_open(conn, oid, INV_READ);
B
Bruce Momjian 已提交
2948 2949
		if (stmt->lobj_fd < 0)
		{
2950
			stmt->errornumber = STMT_EXEC_ERROR;
2951
			stmt->errormsg = "Couldnt open large object for reading.";
2952 2953
			return COPY_GENERAL_ERROR;
		}
2954

B
Bruce Momjian 已提交
2955
		/* Get the size */
2956
		retval = lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END);
B
Bruce Momjian 已提交
2957 2958
		if (retval >= 0)
		{
2959
			left = lo_tell(conn, stmt->lobj_fd);
2960 2961 2962
			if (bindInfo)
				bindInfo->data_left = left;

B
Bruce Momjian 已提交
2963
			/* return to beginning */
2964
			lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET);
2965 2966
		}
	}
2967
	mylog("lo data left = %d\n", left);
2968

B
Bruce Momjian 已提交
2969
	if (left == 0)
2970
		return COPY_NO_DATA_FOUND;
2971

B
Bruce Momjian 已提交
2972 2973
	if (stmt->lobj_fd < 0)
	{
2974 2975 2976 2977
		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Large object FD undefined for multiple read.";
		return COPY_GENERAL_ERROR;
	}
2978

2979
	retval = lo_read(conn, stmt->lobj_fd, (char *) rgbValue, factor > 1 ? (cbValueMax - 1) / factor : cbValueMax);
B
Bruce Momjian 已提交
2980 2981
	if (retval < 0)
	{
2982
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
2983 2984

		/* commit transaction if needed */
2985
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
2986
		{
H
Hiroshi Inoue 已提交
2987
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
2988
			{
B
Byron Nikolaidis 已提交
2989 2990 2991 2992 2993 2994
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

2995 2996 2997 2998 2999 3000 3001
		stmt->lobj_fd = -1;

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

3002 3003
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
3004 3005 3006 3007 3008 3009
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
3010
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
3011

B
Bruce Momjian 已提交
3012
	if (bindInfo && bindInfo->data_left > 0)
3013
		bindInfo->data_left -= retval;
3014

B
Bruce Momjian 已提交
3015 3016
	if (!bindInfo || bindInfo->data_left == 0)
	{
3017
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3018 3019

		/* commit transaction if needed */
3020
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3021
		{
H
Hiroshi Inoue 已提交
3022
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3023
			{
B
Byron Nikolaidis 已提交
3024 3025 3026 3027 3028 3029
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

B
Bruce Momjian 已提交
3030
		stmt->lobj_fd = -1;		/* prevent further reading */
3031
	}
3032 3033

	return result;
3034
}