convert.c 69.2 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 */
H
Hiroshi Inoue 已提交
1294

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

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

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

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

1312 1313 1314 1315 1316 1317 1318
#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)
1319
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1320 1321 1322 1323 1324 1325 1326
	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)
1327
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1328 1329
		else
			search_from_pos = TRUE;
1330
	}
1331
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1332 1333 1334 1335 1336 1337

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

1339
	stmt->miscinfo = 0;
H
Hiroshi Inoue 已提交
1340 1341
	token_len = 0;
	prev_token_end = TRUE;
1342 1343 1344 1345 1346 1347 1348 1349
	/* 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)
			{
1350 1351 1352 1353 1354
				if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1))
				{
					strcpy(new_statement, "BEGIN;");
					begin_first = TRUE;
				}
1355 1356 1357
			}
			else if (ci->drivers.use_declarefetch)
				SC_set_fetchcursor(stmt);
H
Hiroshi Inoue 已提交
1358
			sprintf(new_statement, "%sdeclare %s cursor for ",
1359
					new_statement, stmt->cursor_name);
1360
			npos = strlen(new_statement);
H
Hiroshi Inoue 已提交
1361
			check_cursor_ok = TRUE;
1362 1363 1364 1365
			declare_pos = npos;
		}
	}
	param_number = -1;
H
Hiroshi Inoue 已提交
1366
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1367
	make_encoded_str(&encstr, conn, old_statement);
H
Hiroshi Inoue 已提交
1368
#endif
1369

B
Bruce Momjian 已提交
1370 1371
	for (opos = 0; opos < oldstmtlen; opos++)
	{
1372
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1373 1374
		oldchar = encoded_byte_check(&encstr, opos);
		if (ENCODE_STATUS(encstr) != 0)
1375
		{
1376
			CVT_APPEND_CHAR(oldchar);
1377 1378
			continue;
		}
1379

1380
		/*
1381
		 * From here we are guaranteed to handle a 1-byte character.
1382
		 */
H
Hiroshi Inoue 已提交
1383 1384
#else
		oldchar = old_statement[opos];
1385
#endif
1386

1387
		if (in_escape)			/* escape check */
1388 1389
		{
			in_escape = FALSE;
1390
			CVT_APPEND_CHAR(oldchar);
1391
			continue;
1392
		}
1393 1394
		else if (in_quote || in_dquote) /* quote/double quote check */
		{
1395 1396 1397
			if (oldchar == '\\')
				in_escape = TRUE;
			else if (oldchar == '\'' && in_quote)
1398
				in_quote = FALSE;
1399
			else if (oldchar == '\"' && in_dquote)
1400
				in_dquote = FALSE;
1401
			CVT_APPEND_CHAR(oldchar);
1402
			continue;
1403
		}
1404

1405
		/*
1406 1407
		 * From here we are guranteed to be in neither an escape, a quote
		 * nor a double quote.
1408
		 */
1409
		/* Squeeze carriage-return/linefeed pairs to linefeed only */
H
Hiroshi Inoue 已提交
1410
		else if (lf_conv && oldchar == '\r' && opos + 1 < oldstmtlen &&
1411
				 old_statement[opos + 1] == '\n')
1412
			continue;
1413

B
Bruce Momjian 已提交
1414 1415 1416 1417
		/*
		 * Handle literals (date, time, timestamp) and ODBC scalar
		 * functions
		 */
1418
		else if (oldchar == '{')
B
Bruce Momjian 已提交
1419
		{
H
Hiroshi Inoue 已提交
1420
			char	   *begin = &old_statement[opos], *end;
B
Bruce Momjian 已提交
1421

H
Hiroshi Inoue 已提交
1422 1423 1424
			/* procedure calls */
			if (stmt->statement_type == STMT_TYPE_PROCCALL)
			{
H
Hiroshi Inoue 已提交
1425
				int	lit_call_len = 4;
1426

H
Hiroshi Inoue 已提交
1427
				while (isspace((unsigned char) old_statement[++opos]));
H
Hiroshi Inoue 已提交
1428
				/* '?=' to accept return values exists ? */
H
Hiroshi Inoue 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
				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]));
				}
1440
				if (strnicmp(&old_statement[opos], "call", lit_call_len) ||
1441
					!isspace((unsigned char) old_statement[opos + lit_call_len]))
H
Hiroshi Inoue 已提交
1442 1443 1444 1445
				{
					opos--;
					continue;
				}
1446
				opos += lit_call_len;
1447
				CVT_APPEND_STR("SELECT ");
H
Hiroshi Inoue 已提交
1448
				if (my_strchr(conn, &old_statement[opos], '('))
1449
					proc_no_param = FALSE;
1450
				continue;
H
Hiroshi Inoue 已提交
1451
			}
H
Hiroshi Inoue 已提交
1452 1453
			if (convert_escape(begin, stmt, &npos, &new_stsize, &end
) != CONVERT_ESCAPE_OK)
H
Hiroshi Inoue 已提交
1454 1455 1456 1457
			{
				stmt->errormsg = "ODBC escape convert error";
				stmt->errornumber = STMT_EXEC_ERROR;
				return SQL_ERROR;
1458
			}
H
Hiroshi Inoue 已提交
1459 1460
			opos = end - old_statement; /* positioned at the last } */
			new_statement = stmt->stmt_with_params;
1461 1462
			if (isalnum(end[1]))
				CVT_APPEND_CHAR(' ');
1463 1464
			continue;
		}
H
Hiroshi Inoue 已提交
1465 1466
		/* End of a procedure call */
		else if (oldchar == '}' && stmt->statement_type == STMT_TYPE_PROCCALL)
1467 1468 1469
		{
			if (proc_no_param)
				CVT_APPEND_STR("()");
H
Hiroshi Inoue 已提交
1470
			continue;
1471
		}
1472

B
Bruce Momjian 已提交
1473 1474 1475 1476 1477
		/*
		 * 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.
		 */
1478
		else if (oldchar == '?')
B
Bruce Momjian 已提交
1479 1480 1481
			;					/* ok */
		else
		{
1482
			if (oldchar == '\'')
1483
				in_quote = TRUE;
1484
			else if (oldchar == '\\')
1485
				in_escape = TRUE;
1486
			else if (oldchar == '\"')
1487
				in_dquote = TRUE;
1488
			else
1489
			{
1490
				if (isspace((unsigned char) oldchar))
H
Hiroshi Inoue 已提交
1491 1492 1493 1494 1495 1496 1497 1498
				{
					if (!prev_token_end)
					{
						prev_token_end = TRUE;
						token_save[token_len] = '\0';
						if (token_len == 4)
						{
							if (check_cursor_ok &&
1499
								into_table_from(&old_statement[opos - token_len]))
H
Hiroshi Inoue 已提交
1500 1501 1502 1503 1504 1505 1506 1507
							{
								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;
							}
1508
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
1509
							else if (search_from_pos && /* where's from clause */
1510
									 strnicmp(token_save, "from", 4) == 0)
H
Hiroshi Inoue 已提交
1511 1512 1513 1514 1515
							{
								search_from_pos = FALSE;
								npos -= 5;
								CVT_APPEND_STR(", CTID, OID from");
							}
1516
#endif   /* DRIVER_CURSOR_IMPLEMENT */
H
Hiroshi Inoue 已提交
1517 1518 1519
						}
						if (token_len == 3)
						{
1520 1521
							int			endpos;

H
Hiroshi Inoue 已提交
1522
							if (check_cursor_ok &&
1523 1524
								strnicmp(token_save, "for", 3) == 0 &&
								table_for_update(&old_statement[opos], &endpos))
H
Hiroshi Inoue 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
							{
								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;
								}
							}
						}
1540
					}
H
Hiroshi Inoue 已提交
1541 1542 1543 1544 1545 1546 1547
				}
				else if (prev_token_end)
				{
					prev_token_end = FALSE;
					token_save[0] = oldchar;
					token_len = 1;
				}
H
Hiroshi Inoue 已提交
1548
				else if (token_len + 1 < sizeof(token_save))
H
Hiroshi Inoue 已提交
1549
					token_save[token_len++] = oldchar;
1550
			}
1551
			CVT_APPEND_CHAR(oldchar);
1552 1553 1554
			continue;
		}

1555 1556 1557
		/*
		 * Its a '?' parameter alright
		 */
1558 1559
		param_number++;

B
Bruce Momjian 已提交
1560
		if (param_number >= stmt->parameters_allocated)
1561 1562 1563
		{
			if (stmt->pre_executing)
			{
1564
				CVT_APPEND_STR("NULL");
1565 1566 1567 1568 1569
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1570
				CVT_APPEND_CHAR('?');
1571 1572 1573
				continue;
			}
		}
1574

B
Bruce Momjian 已提交
1575 1576 1577
		/* Assign correct buffers based on data at exec param or not */
		if (stmt->parameters[param_number].data_at_exec)
		{
1578 1579 1580
			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 已提交
1581 1582
		else
		{
H
Hiroshi Inoue 已提交
1583 1584
			UInt4	bind_size = stmt->options.param_bind_type;
			UInt4	ctypelen;
1585

H
Hiroshi Inoue 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
			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;
1607 1608
		}

B
Bruce Momjian 已提交
1609 1610 1611
		/* Handle NULL parameter data */
		if (used == SQL_NULL_DATA)
		{
1612
			CVT_APPEND_STR("NULL");
1613 1614 1615
			continue;
		}

B
Bruce Momjian 已提交
1616 1617 1618 1619 1620 1621
		/*
		 * If no buffer, and it's not null, then what the hell is it? Just
		 * leave it alone then.
		 */
		if (!buffer)
		{
1622 1623
			if (stmt->pre_executing)
			{
1624
				CVT_APPEND_STR("NULL");
1625 1626 1627 1628 1629
				stmt->inaccurate_result = TRUE;
				continue;
			}
			else
			{
1630
				CVT_APPEND_CHAR('?');
1631 1632
				continue;
			}
1633
		}
1634 1635 1636

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

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

B
Bruce Momjian 已提交
1640
		/* replace DEFAULT with something we can use */
B
Bruce Momjian 已提交
1641
		if (param_ctype == SQL_C_DEFAULT)
1642 1643
			param_ctype = sqltype_to_default_ctype(param_sqltype);

H
Hiroshi Inoue 已提交
1644
		allocbuf = buf = NULL;
1645 1646 1647
		param_string[0] = '\0';
		cbuf[0] = '\0';

B
Bruce Momjian 已提交
1648 1649 1650 1651 1652 1653 1654
		/* Convert input C type to a neutral format */
		switch (param_ctype)
		{
			case SQL_C_BINARY:
			case SQL_C_CHAR:
				buf = buffer;
				break;
1655

H
Hiroshi Inoue 已提交
1656 1657 1658 1659 1660 1661 1662
#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 已提交
1663
			case SQL_C_DOUBLE:
1664
				sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
1665 1666
						*((SDOUBLE *) buffer));
				break;
1667

B
Bruce Momjian 已提交
1668
			case SQL_C_FLOAT:
1669
				sprintf(param_string, "%.6g",
B
Bruce Momjian 已提交
1670 1671
						*((SFLOAT *) buffer));
				break;
1672

B
Bruce Momjian 已提交
1673 1674 1675 1676 1677
			case SQL_C_SLONG:
			case SQL_C_LONG:
				sprintf(param_string, "%ld",
						*((SDWORD *) buffer));
				break;
1678

H
Hiroshi Inoue 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
#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 已提交
1693 1694 1695 1696 1697
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				sprintf(param_string, "%d",
						*((SWORD *) buffer));
				break;
1698

B
Bruce Momjian 已提交
1699 1700 1701 1702 1703
			case SQL_C_STINYINT:
			case SQL_C_TINYINT:
				sprintf(param_string, "%d",
						*((SCHAR *) buffer));
				break;
1704

B
Bruce Momjian 已提交
1705 1706 1707 1708
			case SQL_C_ULONG:
				sprintf(param_string, "%lu",
						*((UDWORD *) buffer));
				break;
1709

B
Bruce Momjian 已提交
1710 1711 1712 1713
			case SQL_C_USHORT:
				sprintf(param_string, "%u",
						*((UWORD *) buffer));
				break;
1714

B
Bruce Momjian 已提交
1715 1716 1717 1718
			case SQL_C_UTINYINT:
				sprintf(param_string, "%u",
						*((UCHAR *) buffer));
				break;
1719

B
Bruce Momjian 已提交
1720 1721 1722
			case SQL_C_BIT:
				{
					int			i = *((UCHAR *) buffer);
1723

B
Bruce Momjian 已提交
1724 1725 1726
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
				}
1727

B
Bruce Momjian 已提交
1728
			case SQL_C_DATE:
1729
#if (ODBCVER >= 0x0300)
1730
			case SQL_C_TYPE_DATE:		/* 91 */
1731
#endif
B
Bruce Momjian 已提交
1732 1733
				{
					DATE_STRUCT *ds = (DATE_STRUCT *) buffer;
1734

B
Bruce Momjian 已提交
1735 1736 1737
					st.m = ds->month;
					st.d = ds->day;
					st.y = ds->year;
1738

B
Bruce Momjian 已提交
1739 1740
					break;
				}
1741

B
Bruce Momjian 已提交
1742
			case SQL_C_TIME:
1743
#if (ODBCVER >= 0x0300)
1744
			case SQL_C_TYPE_TIME:		/* 92 */
1745
#endif
B
Bruce Momjian 已提交
1746 1747
				{
					TIME_STRUCT *ts = (TIME_STRUCT *) buffer;
1748

B
Bruce Momjian 已提交
1749 1750 1751
					st.hh = ts->hour;
					st.mm = ts->minute;
					st.ss = ts->second;
1752

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

B
Bruce Momjian 已提交
1756
			case SQL_C_TIMESTAMP:
1757
#if (ODBCVER >= 0x0300)
1758
			case SQL_C_TYPE_TIMESTAMP:	/* 93 */
1759
#endif
B
Bruce Momjian 已提交
1760 1761
				{
					TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer;
1762

B
Bruce Momjian 已提交
1763 1764 1765 1766 1767 1768
					st.m = tss->month;
					st.d = tss->day;
					st.y = tss->year;
					st.hh = tss->hour;
					st.mm = tss->minute;
					st.ss = tss->second;
1769
					st.fr = tss->fraction;
1770

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

B
Bruce Momjian 已提交
1773
					break;
1774

B
Bruce Momjian 已提交
1775 1776 1777 1778 1779
				}
			default:
				/* error */
				stmt->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters";
				stmt->errornumber = STMT_NOT_IMPLEMENTED_ERROR;
1780
				CVT_TERMINATE;	/* just in case */
B
Bruce Momjian 已提交
1781 1782 1783
				SC_log_error(func, "", stmt);
				return SQL_ERROR;
		}
1784

B
Bruce Momjian 已提交
1785 1786 1787 1788
		/*
		 * Now that the input data is in a neutral format, convert it to
		 * the desired output format (sqltype)
		 */
1789

B
Bruce Momjian 已提交
1790 1791 1792 1793 1794
		switch (param_sqltype)
		{
			case SQL_CHAR:
			case SQL_VARCHAR:
			case SQL_LONGVARCHAR:
H
Hiroshi Inoue 已提交
1795 1796 1797 1798 1799
#ifdef	UNICODE_SUPPORT
			case SQL_WCHAR:
			case SQL_WVARCHAR:
			case SQL_WLONGVARCHAR:
#endif /* UNICODE_SUPPORT */
1800

1801
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1802

B
Bruce Momjian 已提交
1803 1804
				/* it was a SQL_C_CHAR */
				if (buf)
1805
					CVT_SPECIAL_CHARS(buf, used);
1806

B
Bruce Momjian 已提交
1807 1808
				/* it was a numeric type */
				else if (param_string[0] != '\0')
1809
					CVT_APPEND_STR(param_string);
1810

B
Bruce Momjian 已提交
1811 1812 1813 1814 1815
				/* 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);
1816

1817
					CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1818
				}
1819

1820
				CVT_APPEND_CHAR('\'');	/* Close Quote */
1821

B
Bruce Momjian 已提交
1822
				break;
1823

B
Bruce Momjian 已提交
1824
			case SQL_DATE:
1825
#if (ODBCVER >= 0x0300)
1826
			case SQL_TYPE_DATE:	/* 91 */
1827
#endif
B
Bruce Momjian 已提交
1828 1829 1830 1831 1832
				if (buf)
				{				/* copy char data to time */
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1833

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

1836
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1837
				break;
1838

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

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

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

B
Bruce Momjian 已提交
1854
			case SQL_TIMESTAMP:
1855
#if (ODBCVER >= 0x0300)
1856
			case SQL_TYPE_TIMESTAMP:	/* 93 */
1857
#endif
1858

B
Bruce Momjian 已提交
1859 1860 1861 1862 1863
				if (buf)
				{
					my_strcpy(cbuf, sizeof(cbuf), buf, used);
					parse_datetime(cbuf, &st);
				}
1864

1865 1866 1867 1868
				/*
				 * sprintf(tmp, "'%.4d-%.2d-%.2d %.2d:%.2d:%.2d'", st.y,
				 * st.m, st.d, st.hh, st.mm, st.ss);
				 */
1869 1870
				tmp[0] = '\'';
				/* Time zone stuff is unreliable */
H
Hiroshi Inoue 已提交
1871
				stime2timestamp(&st, tmp + 1, USE_ZONE, PG_VERSION_GE(conn, 7.2));
H
Hiroshi Inoue 已提交
1872
				strcat(tmp, "'::timestamp");
1873

1874
				CVT_APPEND_STR(tmp);
1875

B
Bruce Momjian 已提交
1876
				break;
1877

B
Bruce Momjian 已提交
1878 1879 1880
			case SQL_BINARY:
			case SQL_VARBINARY:/* non-ascii characters should be
								 * converted to octal */
1881
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1882

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

1885
				CVT_APPEND_BINARY(buf, used);
1886

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

B
Bruce Momjian 已提交
1889
				break;
1890

B
Bruce Momjian 已提交
1891 1892 1893 1894 1895 1896 1897
			case SQL_LONGVARBINARY:

				if (stmt->parameters[param_number].data_at_exec)
					lobj_oid = stmt->parameters[param_number].lobj_oid;
				else
				{
					/* begin transaction if needed */
1898
					if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
1899
					{
H
Hiroshi Inoue 已提交
1900
						if (!CC_begin(conn))
B
Bruce Momjian 已提交
1901 1902 1903 1904 1905 1906 1907
						{
							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 已提交
1908

B
Bruce Momjian 已提交
1909
					/* store the oid */
1910
					lobj_oid = lo_creat(conn, INV_READ | INV_WRITE);
B
Bruce Momjian 已提交
1911 1912
					if (lobj_oid == 0)
					{
B
Byron Nikolaidis 已提交
1913
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1914
						stmt->errormsg = "Couldnt create (in-line) large object.";
B
Byron Nikolaidis 已提交
1915 1916 1917
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}
B
Bruce Momjian 已提交
1918 1919

					/* store the fd */
1920
					lobj_fd = lo_open(conn, lobj_oid, INV_WRITE);
B
Bruce Momjian 已提交
1921 1922
					if (lobj_fd < 0)
					{
B
Byron Nikolaidis 已提交
1923
						stmt->errornumber = STMT_EXEC_ERROR;
B
Bruce Momjian 已提交
1924
						stmt->errormsg = "Couldnt open (in-line) large object for writing.";
B
Byron Nikolaidis 已提交
1925 1926 1927 1928
						SC_log_error(func, "", stmt);
						return SQL_ERROR;
					}

1929
					retval = lo_write(conn, lobj_fd, buffer, used);
1930

1931
					lo_close(conn, lobj_fd);
1932

B
Bruce Momjian 已提交
1933
					/* commit transaction if needed */
1934
					if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
1935
					{
H
Hiroshi Inoue 已提交
1936
						if (!CC_commit(conn))
B
Bruce Momjian 已提交
1937 1938 1939 1940 1941 1942 1943 1944
						{
							stmt->errormsg = "Could not commit (in-line) a transaction";
							stmt->errornumber = STMT_EXEC_ERROR;
							SC_log_error(func, "", stmt);
							return SQL_ERROR;
						}
					}
				}
1945

B
Bruce Momjian 已提交
1946 1947 1948 1949 1950 1951
				/*
				 * 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);
1952
				CVT_APPEND_STR(param_string);
1953

B
Bruce Momjian 已提交
1954 1955 1956 1957 1958 1959 1960
				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) */
1961

B
Bruce Momjian 已提交
1962 1963 1964 1965
			case SQL_REAL:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float4", param_string);
1966
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1967 1968 1969 1970 1971 1972
				break;
			case SQL_FLOAT:
			case SQL_DOUBLE:
				if (buf)
					my_strcpy(param_string, sizeof(param_string), buf, used);
				sprintf(tmp, "'%s'::float8", param_string);
1973
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
				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);
1986
				CVT_APPEND_STR(cbuf);
B
Bruce Momjian 已提交
1987 1988 1989
				break;
			default:			/* a numeric type or SQL_BIT */
				if (param_sqltype == SQL_BIT)
1990
					CVT_APPEND_CHAR('\'');		/* Open Quote */
B
Bruce Momjian 已提交
1991 1992 1993

				if (buf)
				{
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
					switch (used)
					{
						case SQL_NULL_DATA:
							break;
						case SQL_NTS:
							CVT_APPEND_STR(buf);
							break;
						default:
							CVT_APPEND_DATA(buf, used);
					}
B
Bruce Momjian 已提交
2004 2005
				}
				else
2006
					CVT_APPEND_STR(param_string);
B
Bruce Momjian 已提交
2007 2008

				if (param_sqltype == SQL_BIT)
2009
					CVT_APPEND_CHAR('\'');		/* Close Quote */
B
Bruce Momjian 已提交
2010 2011

				break;
2012
		}
H
Hiroshi Inoue 已提交
2013 2014 2015 2016
#ifdef	UNICODE_SUPPORT
		if (allocbuf)
			free(allocbuf);
#endif /* UNICODE_SUPPORT */
B
Bruce Momjian 已提交
2017
	}							/* end, for */
2018

B
Bruce Momjian 已提交
2019
	/* make sure new_statement is always null-terminated */
2020
	CVT_TERMINATE;
2021

2022
	if (conn->DriverToDataSource != NULL)
B
Bruce Momjian 已提交
2023 2024 2025
	{
		int			length = strlen(new_statement);

2026
		conn->DriverToDataSource(conn->translation_option,
2027 2028 2029 2030
								 SQL_CHAR,
								 new_statement, length,
								 new_statement, length, NULL,
								 NULL, 0, NULL);
B
Byron Nikolaidis 已提交
2031 2032
	}

2033
#ifdef	DRIVER_CURSOR_IMPLEMENT
H
Hiroshi Inoue 已提交
2034
	if (search_from_pos)
2035
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
2036
#endif   /* DRIVER_CURSOR_IMPLEMENT */
2037 2038
	if (prepare_dummy_cursor && SC_is_pre_executable(stmt))
	{
2039 2040
		char		fetchstr[128];

2041 2042
		sprintf(fetchstr, ";fetch backward in %s;close %s;",
				stmt->cursor_name, stmt->cursor_name);
2043 2044
		if (begin_first && CC_is_in_autocommit(conn))
			strcat(fetchstr, "COMMIT;");
2045 2046 2047 2048
		CVT_APPEND_STR(fetchstr);
		stmt->inaccurate_result = TRUE;
	}

2049 2050 2051
	return SQL_SUCCESS;
}

2052

H
Hiroshi Inoue 已提交
2053 2054
static const char *
mapFunction(const char *func, int param_count)
2055
{
B
Bruce Momjian 已提交
2056
	int			i;
2057 2058

	for (i = 0; mapFuncs[i][0]; i++)
H
Hiroshi Inoue 已提交
2059 2060 2061 2062 2063 2064 2065 2066
	{
		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))
2067
			return mapFuncs[i][1];
H
Hiroshi Inoue 已提交
2068
	}
2069 2070 2071

	return NULL;
}
2072

2073

H
Hiroshi Inoue 已提交
2074 2075 2076
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]);

2077
/*
H
Hiroshi Inoue 已提交
2078 2079
 * inner_convert_escape()
 * work with embedded escapes sequences
2080
 */
H
Hiroshi Inoue 已提交
2081 2082 2083 2084 2085
     
static
int inner_convert_escape(const ConnectionClass *conn, const char *value,
		char *result, UInt4 maxLen, const char **input_resume,
		UInt4 *count)
2086
{
H
Hiroshi Inoue 已提交
2087 2088 2089 2090 2091
	static const char *func = "inner_convert_escape";
	int	subret, param_count;
	char valnts[1024], params[1024];
	char key[33], *end;
	const char *valptr;
2092
	UInt4	vlen, prtlen, input_consumed, param_consumed, extra_len;
H
Hiroshi Inoue 已提交
2093 2094 2095 2096 2097
	Int4	param_pos[16][2];
 
	valptr = value;
	if (*valptr == '{') /* skip the first { */
		valptr++;
2098
	/* Separate off the key, skipping leading and trailing whitespace */
H
Hiroshi Inoue 已提交
2099 2100 2101 2102 2103 2104 2105 2106
	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 已提交
2107
	if (end = my_strchr(conn, valptr, '}'), NULL == end)
H
Hiroshi Inoue 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
	{
		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);
     
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
	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 已提交
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
	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 已提交
2152
	{
2153
		/* Literal; return the escape part as-is */
H
Hiroshi Inoue 已提交
2154 2155
		strncpy(result, valnts, maxLen);
		prtlen = vlen; 
2156
	}
B
Bruce Momjian 已提交
2157 2158 2159 2160 2161
	else if (strcmp(key, "fn") == 0)
	{
		/*
		 * Function invocation Separate off the func name, skipping
		 * trailing whitespace.
2162
		 */
H
Hiroshi Inoue 已提交
2163 2164 2165 2166 2167
		char	*funcEnd = valnts;
		char     svchar;
		const char	*mapExpr;
     
		params[sizeof(params)-1] = '\0';
2168 2169

		while ((*funcEnd != '\0') && (*funcEnd != '(') &&
H
Hiroshi Inoue 已提交
2170
			(!isspace((unsigned char) *funcEnd)))
2171
			funcEnd++;
2172 2173
		svchar = *funcEnd;
		*funcEnd = '\0';
H
Hiroshi Inoue 已提交
2174
		sscanf(valnts, "%32s", key);
2175
		*funcEnd = svchar;
2176 2177
		while ((*funcEnd != '\0') && isspace((unsigned char) *funcEnd))
			funcEnd++;
2178

B
Bruce Momjian 已提交
2179
		/*
H
Hiroshi Inoue 已提交
2180
 		 * We expect left parenthesis here, else return fn body as-is
B
Bruce Momjian 已提交
2181
		 * since it is one of those "function constants".
2182
		 */
B
Bruce Momjian 已提交
2183 2184
		if (*funcEnd != '(')
		{
H
Hiroshi Inoue 已提交
2185 2186
			strncpy(result, valnts, maxLen);
			return CONVERT_ESCAPE_OK;
2187
		}
B
Bruce Momjian 已提交
2188 2189

		/*
H
Hiroshi Inoue 已提交
2190 2191 2192
		 * Process parameter list and inner escape
		 * sequences
		 * Aceto 2002-01-29
2193
		 */
H
Hiroshi Inoue 已提交
2194 2195 2196 2197 2198 2199

		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 已提交
2200
		{
H
Hiroshi Inoue 已提交
2201 2202
			if (param_pos[param_count][0] < 0)
				break;
2203
		}
H
Hiroshi Inoue 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 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
		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;
2268
	}
B
Bruce Momjian 已提交
2269 2270
	else
	{
2271
		/* Bogus key, leave untranslated */
H
Hiroshi Inoue 已提交
2272 2273 2274 2275
		return CONVERT_ESCAPE_ERROR;
	}
     
	if (count)
2276
		*count = prtlen + extra_len;
H
Hiroshi Inoue 已提交
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
	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 已提交
2301 2302 2303
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif   /* MULTIBYTE */
H
Hiroshi Inoue 已提交
2304 2305 2306 2307 2308 2309
 
	buf[sizeof(buf)-1] = '\0';
	innerParenthesis = 0;
	in_quote = in_dquote = in_escape = leadingSpace = FALSE;
	param_count = 0;
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2310
	make_encoded_str(&encstr, conn, value);
H
Hiroshi Inoue 已提交
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
#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 已提交
2328 2329
		encoded_byte_check(&encstr, ipos);
		if (ENCODE_STATUS(encstr) != 0)
H
Hiroshi Inoue 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 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
		{
			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;
2418
	}
H
Hiroshi Inoue 已提交
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
	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;
2436

H
Hiroshi Inoue 已提交
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
	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;
2447 2448 2449
}


2450 2451
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
2452
{
2453 2454
	size_t		i = 0,
				out = 0;
2455

2456
	for (i = 0; s[i]; i++)
B
Bruce Momjian 已提交
2457
	{
2458
		if (s[i] == '$' || s[i] == ',' || s[i] == ')')
B
Bruce Momjian 已提交
2459
			;					/* skip these characters */
2460
		else
2461 2462
		{
			if (out + 1 >= soutmax)
2463
				return FALSE;	/* sout is too short */
2464 2465 2466 2467 2468
			if (s[i] == '(')
				sout[out++] = '-';
			else
				sout[out++] = s[i];
		}
2469
	}
2470 2471
	sout[out] = '\0';
	return TRUE;
2472 2473 2474
}


2475 2476 2477 2478
/*
 *	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
 */
2479
char
2480
parse_datetime(char *buf, SIMPLE_TIME *st)
2481
{
B
Bruce Momjian 已提交
2482 2483 2484 2485 2486 2487 2488 2489
	int			y,
				m,
				d,
				hh,
				mm,
				ss;
	int			nf;

2490 2491
	y = m = d = hh = mm = ss = 0;

2492 2493 2494 2495 2496 2497 2498 2499
	/* escape sequence ? */
	if (buf[0] == '{')
	{
		while (*(++buf) && *buf != '\'');
		if (!(*buf))
			return FALSE;
		buf++;
	}
B
Bruce Momjian 已提交
2500 2501
	if (buf[4] == '-')			/* year first */
		nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss);
2502
	else
B
Bruce Momjian 已提交
2503
		nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss);
2504

B
Bruce Momjian 已提交
2505 2506
	if (nf == 5 || nf == 6)
	{
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
		st->y = y;
		st->m = m;
		st->d = d;
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

B
Bruce Momjian 已提交
2517
	if (buf[4] == '-')			/* year first */
2518 2519 2520 2521
		nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d);
	else
		nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y);

B
Bruce Momjian 已提交
2522 2523
	if (nf == 3)
	{
2524 2525 2526 2527 2528 2529 2530 2531
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

	nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss);
B
Bruce Momjian 已提交
2532 2533
	if (nf == 2 || nf == 3)
	{
2534 2535 2536 2537 2538 2539 2540 2541 2542
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

	return FALSE;
}
2543

2544

2545
/*	Change linefeed to carriage-return/linefeed */
2546
int
H
Hiroshi Inoue 已提交
2547
convert_linefeeds(const char *si, char *dst, size_t max, BOOL convlf, BOOL *changed)
2548
{
B
Bruce Momjian 已提交
2549 2550
	size_t		i = 0,
				out = 0;
2551

2552 2553 2554 2555
	if (max == 0)
		max = 0xffffffff;
	*changed = FALSE;
	for (i = 0; si[i] && out < max - 1; i++)
B
Bruce Momjian 已提交
2556
	{
H
Hiroshi Inoue 已提交
2557
		if (convlf && si[i] == '\n')
B
Bruce Momjian 已提交
2558 2559 2560 2561
		{
			/* Only add the carriage-return if needed */
			if (i > 0 && si[i - 1] == '\r')
			{
2562 2563 2564 2565
				if (dst)
					dst[out++] = si[i];
				else
					out++;
B
Byron Nikolaidis 已提交
2566 2567
				continue;
			}
2568
			*changed = TRUE;
B
Byron Nikolaidis 已提交
2569

2570 2571 2572 2573 2574 2575 2576
			if (dst)
			{
				dst[out++] = '\r';
				dst[out++] = '\n';
			}
			else
				out += 2;
2577 2578
		}
		else
2579 2580 2581 2582 2583 2584
		{
			if (dst)
				dst[out++] = si[i];
			else
				out++;
		}
2585
	}
2586 2587
	if (dst)
		dst[out] = '\0';
2588
	return out;
2589 2590
}

2591 2592 2593 2594 2595

/*
 *	Change carriage-return/linefeed to just linefeed
 *	Plus, escape any special characters.
 */
2596
int
H
Hiroshi Inoue 已提交
2597
convert_special_chars(const char *si, char *dst, int used, BOOL convlf, int ccsc)
2598
{
B
Bruce Momjian 已提交
2599 2600 2601
	size_t		i = 0,
				out = 0,
				max;
2602
	char	   *p = NULL;
H
Hiroshi Inoue 已提交
2603 2604 2605
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif
2606 2607 2608 2609 2610 2611


	if (used == SQL_NTS)
		max = strlen(si);
	else
		max = used;
2612 2613 2614 2615 2616
	if (dst)
	{
		p = dst;
		p[0] = '\0';
	}
H
Hiroshi Inoue 已提交
2617
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2618
	encoded_str_constr(&encstr, ccsc, si);
H
Hiroshi Inoue 已提交
2619
#endif
2620

H
Hiroshi Inoue 已提交
2621
	for (i = 0; i < max && si[i]; i++)
B
Bruce Momjian 已提交
2622
	{
2623
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2624 2625
		encoded_nextchar(&encstr);
		if (ENCODE_STATUS(encstr) != 0)
2626 2627 2628 2629 2630 2631 2632
		{
			if (p)
				p[out] = si[i];
			out++;
			continue;
		}
#endif
H
Hiroshi Inoue 已提交
2633
		if (convlf && si[i] == '\r' && si[i + 1] == '\n')
2634
			continue;
B
Byron Nikolaidis 已提交
2635
		else if (si[i] == '\'' || si[i] == '\\')
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
		{
			if (p)
				p[out++] = '\\';
			else
				out++;
		}
		if (p)
			p[out++] = si[i];
		else
			out++;
2646
	}
2647 2648 2649
	if (p)
		p[out] = '\0';
	return out;
2650 2651
}

2652

2653 2654
/*	!!! Need to implement this function !!!  */
int
2655
convert_pgbinary_to_char(const char *value, char *rgbValue, int cbValueMax)
2656
{
2657 2658 2659
	mylog("convert_pgbinary_to_char: value = '%s'\n", value);

	strncpy_null(rgbValue, value, cbValueMax);
2660 2661 2662
	return 0;
}

2663

2664
static unsigned int
2665
conv_from_octal(const unsigned char *s)
2666
{
B
Bruce Momjian 已提交
2667 2668
	int			i,
				y = 0;
2669

B
Bruce Momjian 已提交
2670 2671
	for (i = 1; i <= 3; i++)
		y += (s[i] - 48) * (int) pow(8, 3 - i);
2672 2673

	return y;
2674

2675 2676
}

2677

2678
static unsigned int
2679
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
2680
{
B
Bruce Momjian 已提交
2681 2682 2683
	int			i,
				y = 0,
				val;
2684

B
Bruce Momjian 已提交
2685 2686 2687 2688 2689 2690 2691 2692
	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 已提交
2693

B
Bruce Momjian 已提交
2694
		y += val * (int) pow(16, 2 - i);
B
Byron Nikolaidis 已提交
2695 2696 2697 2698 2699
	}

	return y;
}

2700

B
Bruce Momjian 已提交
2701
/*	convert octal escapes to bytes */
2702
int
2703
convert_from_pgbinary(const unsigned char *value, unsigned char *rgbValue, int cbValueMax)
2704
{
2705 2706
	size_t		i,
				ilen = strlen(value);
B
Bruce Momjian 已提交
2707
	int			o = 0;
2708

B
Bruce Momjian 已提交
2709

2710
	for (i = 0; i < ilen;)
B
Bruce Momjian 已提交
2711 2712 2713
	{
		if (value[i] == '\\')
		{
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
			if (value[i + 1] == '\\')
			{
				rgbValue[o] = value[i];
				i += 2;
			}
			else
			{
				rgbValue[o] = conv_from_octal(&value[i]);
				i += 4;
			}
2724
		}
B
Bruce Momjian 已提交
2725
		else
2726 2727 2728 2729
			rgbValue[o] = value[i++];
		mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]);
		o++;
	}
2730

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

2733 2734 2735 2736
	return o;
}


2737
static char *
2738 2739
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
2740 2741
	int			i;
	static char x[6];
2742 2743 2744 2745 2746

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

B
Bruce Momjian 已提交
2747 2748
	for (i = 4; i > 1; i--)
	{
2749 2750 2751 2752 2753 2754 2755
		x[i] = (val & 7) + 48;
		val >>= 3;
	}

	return x;
}

2756

B
Bruce Momjian 已提交
2757
/*	convert non-ascii bytes to octal escape sequences */
2758
int
2759
convert_to_pgbinary(const unsigned char *in, char *out, int len)
2760
{
B
Bruce Momjian 已提交
2761 2762
	int			i,
				o = 0;
2763

B
Bruce Momjian 已提交
2764 2765
	for (i = 0; i < len; i++)
	{
2766
		mylog("convert_to_pgbinary: in[%d] = %d, %c\n", i, in[i], in[i]);
B
Bruce Momjian 已提交
2767
		if (isalnum(in[i]) || in[i] == ' ')
2768
			out[o++] = in[i];
B
Bruce Momjian 已提交
2769 2770 2771
		else
		{
			strcpy(&out[o], conv_to_octal(in[i]));
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
			o += 5;
		}
	}

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

	return o;
}


B
Byron Nikolaidis 已提交
2782
void
2783
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2784
{
2785 2786
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2787
				o = 0;
B
Byron Nikolaidis 已提交
2788

2789
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2790 2791 2792
	{
		if (in[i] == '+')
		{
B
Byron Nikolaidis 已提交
2793 2794 2795
			sprintf(&out[o], "%%2B");
			o += 3;
		}
B
Bruce Momjian 已提交
2796
		else if (isspace((unsigned char) in[i]))
B
Byron Nikolaidis 已提交
2797
			out[o++] = '+';
B
Bruce Momjian 已提交
2798 2799
		else if (!isalnum((unsigned char) in[i]))
		{
2800
			sprintf(&out[o], "%%%02x", (unsigned char) in[i]);
B
Byron Nikolaidis 已提交
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
			o += 3;
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}


void
2811
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2812
{
2813 2814
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2815
				o = 0;
B
Byron Nikolaidis 已提交
2816

2817
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
2818
	{
B
Byron Nikolaidis 已提交
2819 2820
		if (in[i] == '+')
			out[o++] = ' ';
B
Bruce Momjian 已提交
2821 2822
		else if (in[i] == '%')
		{
B
Byron Nikolaidis 已提交
2823
			sprintf(&out[o++], "%c", conv_from_hex(&in[i]));
B
Bruce Momjian 已提交
2824
			i += 2;
B
Byron Nikolaidis 已提交
2825 2826 2827 2828 2829 2830 2831
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}

2832 2833 2834 2835
static const char *hextbl = "0123456789ABCDEF";
static int
pg_bin2hex(UCHAR *src, UCHAR *dst, int length)
{
2836 2837 2838 2839 2840 2841
	UCHAR		chr,
			   *src_wk,
			   *dst_wk;
	BOOL		backwards;
	int			i;

2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
	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;
}
2871

2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
/*-------
 *	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.
 *-------
 */
2888
int
2889 2890
convert_lo(StatementClass *stmt, const void *value, Int2 fCType, PTR rgbValue,
		   SDWORD cbValueMax, SDWORD *pcbValue)
2891
{
B
Bruce Momjian 已提交
2892 2893 2894 2895
	Oid			oid;
	int			retval,
				result,
				left = -1;
T
Tom Lane 已提交
2896
	BindInfoClass *bindInfo = NULL;
2897 2898
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
2899
	int			factor = (fCType == SQL_C_CHAR ? 2 : 1);
2900

2901
	/* If using SQLGetData, then current_col will be set */
B
Bruce Momjian 已提交
2902 2903
	if (stmt->current_col >= 0)
	{
2904 2905 2906
		bindInfo = &stmt->bindings[stmt->current_col];
		left = bindInfo->data_left;
	}
2907

B
Bruce Momjian 已提交
2908 2909 2910 2911
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
2912

B
Bruce Momjian 已提交
2913 2914
	if (!bindInfo || bindInfo->data_left == -1)
	{
B
Byron Nikolaidis 已提交
2915
		/* begin transaction if needed */
2916
		if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
2917
		{
H
Hiroshi Inoue 已提交
2918
			if (!CC_begin(conn))
B
Bruce Momjian 已提交
2919
			{
B
Byron Nikolaidis 已提交
2920 2921 2922 2923 2924 2925
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

2926
		oid = atoi(value);
2927
		stmt->lobj_fd = lo_open(conn, oid, INV_READ);
B
Bruce Momjian 已提交
2928 2929
		if (stmt->lobj_fd < 0)
		{
2930
			stmt->errornumber = STMT_EXEC_ERROR;
2931
			stmt->errormsg = "Couldnt open large object for reading.";
2932 2933
			return COPY_GENERAL_ERROR;
		}
2934

B
Bruce Momjian 已提交
2935
		/* Get the size */
2936
		retval = lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END);
B
Bruce Momjian 已提交
2937 2938
		if (retval >= 0)
		{
2939
			left = lo_tell(conn, stmt->lobj_fd);
2940 2941 2942
			if (bindInfo)
				bindInfo->data_left = left;

B
Bruce Momjian 已提交
2943
			/* return to beginning */
2944
			lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET);
2945 2946
		}
	}
2947
	mylog("lo data left = %d\n", left);
2948

B
Bruce Momjian 已提交
2949
	if (left == 0)
2950
		return COPY_NO_DATA_FOUND;
2951

B
Bruce Momjian 已提交
2952 2953
	if (stmt->lobj_fd < 0)
	{
2954 2955 2956 2957
		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Large object FD undefined for multiple read.";
		return COPY_GENERAL_ERROR;
	}
2958

2959
	retval = lo_read(conn, stmt->lobj_fd, (char *) rgbValue, factor > 1 ? (cbValueMax - 1) / factor : cbValueMax);
B
Bruce Momjian 已提交
2960 2961
	if (retval < 0)
	{
2962
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
2963 2964

		/* commit transaction if needed */
2965
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
2966
		{
H
Hiroshi Inoue 已提交
2967
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
2968
			{
B
Byron Nikolaidis 已提交
2969 2970 2971 2972 2973 2974
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

2975 2976 2977 2978 2979 2980 2981
		stmt->lobj_fd = -1;

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

2982 2983
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
2984 2985 2986 2987 2988 2989
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
2990
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
2991

B
Bruce Momjian 已提交
2992
	if (bindInfo && bindInfo->data_left > 0)
2993
		bindInfo->data_left -= retval;
2994

B
Bruce Momjian 已提交
2995 2996
	if (!bindInfo || bindInfo->data_left == 0)
	{
2997
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
2998 2999

		/* commit transaction if needed */
3000
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3001
		{
H
Hiroshi Inoue 已提交
3002
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3003
			{
B
Byron Nikolaidis 已提交
3004 3005 3006 3007 3008 3009
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

B
Bruce Momjian 已提交
3010
		stmt->lobj_fd = -1;		/* prevent further reading */
3011
	}
3012 3013

	return result;
3014
}