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

20 21
#include "convert.h"

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

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

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

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

47 48 49 50
/*
 *	How to map ODBC scalar functions {fn func(args)} to Postgres.
 *	This is just a simple substitution.  List augmented from:
 *	http://www.merant.com/datadirect/download/docs/odbc16/Odbcref/rappc.htm
51
 *	- thomas 2000-04-03
52
 */
B
Bruce Momjian 已提交
53
char	   *mapFuncs[][2] = {
H
Hiroshi Inoue 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
/*	{ "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)" },
B
Bruce Momjian 已提交
110
	{"DAYOFYEAR",	 "cast(extract(doy from $1) as integer)" },
H
Hiroshi Inoue 已提交
111 112 113 114 115 116 117 118 119
	{"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;
B
Bruce Momjian 已提交
164
#if defined(WIN32) || defined(HAVE_INT_TIMEZONE)
165
	long		timediff;
B
Bruce Momjian 已提交
166
#endif
167
	BOOL		withZone = *bZone;
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 199 200

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

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

	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)
	{
282
		long		zoneint;
283 284 285 286
		struct tm	tm;
		time_t		time0;

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

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

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

321

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

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

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

381
	}
382 383 384

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

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

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

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

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

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

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

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

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

502
			/* This is for internal use by SQLStatistics() */
B
Bruce Momjian 已提交
503 504 505 506
		case PG_TYPE_INT2VECTOR:
			{
				int			nval,
							i;
507
				const char *vp;
B
Bruce Momjian 已提交
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 535 536

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

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

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

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

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

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

B
Bruce Momjian 已提交
566
		default:
B
Byron Nikolaidis 已提交
567

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

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

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

581 582
	rgbValueBindRow = (char *) rgbValue + rgbValueOffset;

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

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

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

B
Bruce Momjian 已提交
609 610 611 612 613 614 615 616
			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;
617

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

957
				if (stmt->current_col < 0)
958
				{
959 960
					pbic = &sbic;
					pbic->data_left = -1;
961
				}
962 963 964 965 966 967 968 969 970 971 972
				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;
973

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

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

B
Bruce Momjian 已提交
990
				}
991

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

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

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

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

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

			default:
				return COPY_UNSUPPORTED_TYPE;
B
Byron Nikolaidis 已提交
1021 1022
		}
	}
1023

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

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

1032 1033
}

1034

1035 1036 1037 1038
/*--------------------------------------------------------------------
 *	Functions/Macros to get rid of query size limit.
 *
 *	I always used the follwoing macros to convert from
1039
 *	old_statement to new_statement.  Please improve it
1040 1041 1042
 *	if you have a better way.	Hiroshi 2001/05/22
 *--------------------------------------------------------------------
 */
1043 1044
#define INIT_MIN_ALLOC	4096
static int
1045
enlarge_statement(StatementClass *stmt, unsigned int newsize)
1046
{
1047
	unsigned int newalsize = INIT_MIN_ALLOC;
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	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.
 *----------
 */
1073
#define ENLARGE_NEWSTATEMENT(newpos) \
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	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.
 *----------
 */
1084
#define CVT_INIT(size) \
1085
do { \
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	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'; \
1100 1101
} while (0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

H
Hiroshi Inoue 已提交
1539
							if (check_cursor_ok &&
1540 1541
								strnicmp(token_save, "for", 3) == 0 &&
								table_for_update(&old_statement[opos], &endpos))
H
Hiroshi Inoue 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
							{
								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;
								}
							}
						}
1557
					}
H
Hiroshi Inoue 已提交
1558 1559 1560 1561 1562 1563 1564
				}
				else if (prev_token_end)
				{
					prev_token_end = FALSE;
					token_save[0] = oldchar;
					token_len = 1;
				}
H
Hiroshi Inoue 已提交
1565
				else if (token_len + 1 < sizeof(token_save))
H
Hiroshi Inoue 已提交
1566
					token_save[token_len++] = oldchar;
1567
			}
1568
			CVT_APPEND_CHAR(oldchar);
1569 1570 1571
			continue;
		}

1572 1573 1574
		/*
		 * Its a '?' parameter alright
		 */
1575 1576
		param_number++;

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

B
Bruce Momjian 已提交
1592 1593 1594
		/* Assign correct buffers based on data at exec param or not */
		if (stmt->parameters[param_number].data_at_exec)
		{
1595 1596 1597
			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 已提交
1598 1599
		else
		{
H
Hiroshi Inoue 已提交
1600 1601
			UInt4	bind_size = stmt->options.param_bind_type;
			UInt4	ctypelen;
1602

H
Hiroshi Inoue 已提交
1603 1604 1605 1606 1607 1608 1609
			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;
B
Bruce Momjian 已提交
1610
				else
H
Hiroshi Inoue 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
					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;
1624 1625
		}

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

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

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

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

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

H
Hiroshi Inoue 已提交
1661
		allocbuf = buf = NULL;
1662 1663 1664
		param_string[0] = '\0';
		cbuf[0] = '\0';

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

H
Hiroshi Inoue 已提交
1673 1674 1675 1676 1677 1678 1679
#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 已提交
1680
			case SQL_C_DOUBLE:
1681
				sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
1682 1683
						*((SDOUBLE *) buffer));
				break;
1684

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

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

H
Hiroshi Inoue 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
#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 已提交
1710 1711 1712 1713 1714
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				sprintf(param_string, "%d",
						*((SWORD *) buffer));
				break;
1715

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

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

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

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

B
Bruce Momjian 已提交
1737 1738 1739
			case SQL_C_BIT:
				{
					int			i = *((UCHAR *) buffer);
1740

B
Bruce Momjian 已提交
1741 1742 1743
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
				}
1744

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

B
Bruce Momjian 已提交
1752 1753 1754
					st.m = ds->month;
					st.d = ds->day;
					st.y = ds->year;
1755

B
Bruce Momjian 已提交
1756 1757
					break;
				}
1758

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

B
Bruce Momjian 已提交
1766 1767 1768
					st.hh = ts->hour;
					st.mm = ts->minute;
					st.ss = ts->second;
1769

B
Bruce Momjian 已提交
1770 1771
					break;
				}
1772

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

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

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

B
Bruce Momjian 已提交
1790
					break;
1791

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

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

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

1818
				CVT_APPEND_CHAR('\'');	/* Open Quote */
1819

B
Bruce Momjian 已提交
1820 1821
				/* it was a SQL_C_CHAR */
				if (buf)
1822
					CVT_SPECIAL_CHARS(buf, used);
1823

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

B
Bruce Momjian 已提交
1828 1829 1830 1831 1832
				/* 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);
1833

1834
					CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1835
				}
1836

1837
				CVT_APPEND_CHAR('\'');	/* Close Quote */
1838

B
Bruce Momjian 已提交
1839
				break;
1840

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

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

1853
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1854
				break;
1855

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

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

1868
				CVT_APPEND_STR(tmp);
B
Bruce Momjian 已提交
1869
				break;
1870

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

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

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

1891
				CVT_APPEND_STR(tmp);
1892

B
Bruce Momjian 已提交
1893
				break;
1894

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

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

1902
				CVT_APPEND_BINARY(buf, used);
1903

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

B
Bruce Momjian 已提交
1906
				break;
1907

B
Bruce Momjian 已提交
1908 1909 1910 1911 1912 1913 1914
			case SQL_LONGVARBINARY:

				if (stmt->parameters[param_number].data_at_exec)
					lobj_oid = stmt->parameters[param_number].lobj_oid;
				else
				{
					/* begin transaction if needed */
1915
					if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
1916
					{
H
Hiroshi Inoue 已提交
1917
						if (!CC_begin(conn))
B
Bruce Momjian 已提交
1918 1919 1920 1921 1922 1923 1924
						{
							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 已提交
1925

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

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

1946
					retval = lo_write(conn, lobj_fd, buffer, used);
1947

1948
					lo_close(conn, lobj_fd);
1949

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

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

B
Bruce Momjian 已提交
1971 1972 1973 1974 1975 1976 1977
				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) */
1978

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

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

				if (param_sqltype == SQL_BIT)
2026
					CVT_APPEND_CHAR('\'');		/* Close Quote */
B
Bruce Momjian 已提交
2027 2028

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

B
Bruce Momjian 已提交
2036
	/* make sure new_statement is always null-terminated */
2037
	CVT_TERMINATE;
2038

2039
	if (conn->DriverToDataSource != NULL)
B
Bruce Momjian 已提交
2040 2041 2042
	{
		int			length = strlen(new_statement);

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

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

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

2072 2073 2074
	return SQL_SUCCESS;
}

2075

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

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

	return NULL;
}
2095

2096

H
Hiroshi Inoue 已提交
2097 2098 2099
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]);

2100
/*
H
Hiroshi Inoue 已提交
2101 2102
 * inner_convert_escape()
 * work with embedded escapes sequences
2103
 */
B
Bruce Momjian 已提交
2104

H
Hiroshi Inoue 已提交
2105 2106 2107 2108
static
int inner_convert_escape(const ConnectionClass *conn, const char *value,
		char *result, UInt4 maxLen, const char **input_resume,
		UInt4 *count)
2109
{
H
Hiroshi Inoue 已提交
2110 2111 2112 2113 2114
	static const char *func = "inner_convert_escape";
	int	subret, param_count;
	char valnts[1024], params[1024];
	char key[33], *end;
	const char *valptr;
2115
	UInt4	vlen, prtlen, input_consumed, param_consumed, extra_len;
H
Hiroshi Inoue 已提交
2116
	Int4	param_pos[16][2];
B
Bruce Momjian 已提交
2117

H
Hiroshi Inoue 已提交
2118 2119 2120
	valptr = value;
	if (*valptr == '{') /* skip the first { */
		valptr++;
2121
	/* Separate off the key, skipping leading and trailing whitespace */
H
Hiroshi Inoue 已提交
2122 2123 2124 2125 2126 2127 2128
	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++;
B
Bruce Momjian 已提交
2129

H
Hiroshi Inoue 已提交
2130
	if (end = my_strchr(conn, valptr, '}'), NULL == end)
H
Hiroshi Inoue 已提交
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
	{
		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);
B
Bruce Momjian 已提交
2141

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
	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 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
	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 已提交
2175
	{
2176
		/* Literal; return the escape part as-is */
H
Hiroshi Inoue 已提交
2177
		strncpy(result, valnts, maxLen);
B
Bruce Momjian 已提交
2178
		prtlen = vlen;
2179
	}
B
Bruce Momjian 已提交
2180 2181 2182 2183 2184
	else if (strcmp(key, "fn") == 0)
	{
		/*
		 * Function invocation Separate off the func name, skipping
		 * trailing whitespace.
2185
		 */
H
Hiroshi Inoue 已提交
2186 2187 2188
		char	*funcEnd = valnts;
		char     svchar;
		const char	*mapExpr;
B
Bruce Momjian 已提交
2189

H
Hiroshi Inoue 已提交
2190
		params[sizeof(params)-1] = '\0';
2191 2192

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

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

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

		valptr += (UInt4)(funcEnd - valnts);
B
Bruce Momjian 已提交
2219
		if (subret = processParameters(conn, valptr, params, sizeof(params) - 1, &input_consumed, &param_consumed, param_pos), CONVERT_ESCAPE_OK != subret)
H
Hiroshi Inoue 已提交
2220 2221 2222
			return CONVERT_ESCAPE_ERROR;

		for (param_count = 0;; param_count++)
B
Bruce Momjian 已提交
2223
		{
H
Hiroshi Inoue 已提交
2224 2225
			if (param_pos[param_count][0] < 0)
				break;
2226
		}
H
Hiroshi Inoue 已提交
2227
		if (param_count == 1 &&
B
Bruce Momjian 已提交
2228
			param_pos[0][1] < param_pos[0][0])
H
Hiroshi Inoue 已提交
2229
			param_count = 0;
B
Bruce Momjian 已提交
2230

H
Hiroshi Inoue 已提交
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
		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 ||
B
Bruce Momjian 已提交
2262
						param_pos[pidx][0] <0)
H
Hiroshi Inoue 已提交
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
					{
						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;
2291
	}
B
Bruce Momjian 已提交
2292 2293
	else
	{
2294
		/* Bogus key, leave untranslated */
H
Hiroshi Inoue 已提交
2295 2296
		return CONVERT_ESCAPE_ERROR;
	}
B
Bruce Momjian 已提交
2297

H
Hiroshi Inoue 已提交
2298
	if (count)
2299
		*count = prtlen + extra_len;
H
Hiroshi Inoue 已提交
2300 2301 2302 2303 2304 2305 2306
	if (prtlen < 0 || prtlen >= maxLen) /* buffer overflow */
	{
		mylog("%s %d bytes buffer overflow\n", func, maxLen);
		return CONVERT_ESCAPE_OVERFLOW;
	}
	return CONVERT_ESCAPE_OK;
}
B
Bruce Momjian 已提交
2307

H
Hiroshi Inoue 已提交
2308 2309 2310 2311
/*
 * processParameters()
 * Process function parameters and work with embedded escapes sequences.
 */
B
Bruce Momjian 已提交
2312

H
Hiroshi Inoue 已提交
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
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 已提交
2324 2325 2326
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif   /* MULTIBYTE */
B
Bruce Momjian 已提交
2327

H
Hiroshi Inoue 已提交
2328 2329 2330 2331 2332
	buf[sizeof(buf)-1] = '\0';
	innerParenthesis = 0;
	in_quote = in_dquote = in_escape = leadingSpace = FALSE;
	param_count = 0;
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
2333
	make_encoded_str(&encstr, conn, value);
H
Hiroshi Inoue 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
#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 已提交
2351 2352
		encoded_byte_check(&encstr, ipos);
		if (ENCODE_STATUS(encstr) != 0)
H
Hiroshi Inoue 已提交
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
		{
			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;
B
Bruce Momjian 已提交
2406

H
Hiroshi Inoue 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
			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;
B
Bruce Momjian 已提交
2417

H
Hiroshi Inoue 已提交
2418 2419 2420
			case '}':
				stop = TRUE;
				break;
B
Bruce Momjian 已提交
2421

H
Hiroshi Inoue 已提交
2422 2423 2424
			case '{':
				if (subret = inner_convert_escape(conn, valptr, buf, sizeof(buf) - 1, &valptr, &inner_count), CONVERT_ESCAPE_OK != subret)
					return CONVERT_ESCAPE_ERROR;
B
Bruce Momjian 已提交
2425

H
Hiroshi Inoue 已提交
2426 2427
				if (inner_count + count >= maxLen)
					return CONVERT_ESCAPE_OVERFLOW;
B
Bruce Momjian 已提交
2428
				memcpy(&result[count], buf, inner_count);
H
Hiroshi Inoue 已提交
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
				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;
2441
	}
H
Hiroshi Inoue 已提交
2442 2443 2444 2445 2446 2447
	result[count] = '\0';
	*input_consumed = ipos;
	if (output_count)
		*output_count = count;
	return CONVERT_ESCAPE_OK;
}
B
Bruce Momjian 已提交
2448

H
Hiroshi Inoue 已提交
2449 2450 2451 2452
/*
 * convert_escape()
 * This function returns a pointer to static memory!
 */
B
Bruce Momjian 已提交
2453

H
Hiroshi Inoue 已提交
2454
int
B
Bruce Momjian 已提交
2455 2456
convert_escape(const char *value, StatementClass *stmt, int *npos, int *stsize,
			   const char **val_resume)
H
Hiroshi Inoue 已提交
2457 2458 2459
{
	int	ret, pos = *npos;
	UInt4 	count;
2460

H
Hiroshi Inoue 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
	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;
2471 2472 2473
}


2474 2475
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
2476
{
2477 2478
	size_t		i = 0,
				out = 0;
2479

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


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

2514 2515
	y = m = d = hh = mm = ss = 0;

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

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

		return TRUE;
	}

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

B
Bruce Momjian 已提交
2546 2547
	if (nf == 3)
	{
2548 2549 2550 2551 2552 2553 2554 2555
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

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

		return TRUE;
	}

	return FALSE;
}
2567

2568

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

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

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

2615 2616 2617 2618 2619

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


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

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

2676

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

	strncpy_null(rgbValue, value, cbValueMax);
2684 2685 2686
	return 0;
}

2687

2688
static unsigned int
2689
conv_from_octal(const unsigned char *s)
2690
{
B
Bruce Momjian 已提交
2691 2692
	int			i,
				y = 0;
2693

B
Bruce Momjian 已提交
2694 2695
	for (i = 1; i <= 3; i++)
		y += (s[i] - 48) * (int) pow(8, 3 - i);
2696 2697

	return y;
2698

2699 2700
}

2701

2702
static unsigned int
2703
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
2704
{
B
Bruce Momjian 已提交
2705 2706 2707
	int			i,
				y = 0,
				val;
2708

B
Bruce Momjian 已提交
2709 2710 2711 2712 2713 2714 2715 2716
	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 已提交
2717

B
Bruce Momjian 已提交
2718
		y += val * (int) pow(16, 2 - i);
B
Byron Nikolaidis 已提交
2719 2720 2721 2722 2723
	}

	return y;
}

2724

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

B
Bruce Momjian 已提交
2733

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

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

2757 2758 2759 2760
	return o;
}


2761
static char *
2762 2763
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
2764 2765
	int			i;
	static char x[6];
2766 2767 2768 2769 2770

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

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

	return x;
}

2780

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

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

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

	return o;
}


B
Byron Nikolaidis 已提交
2806
void
2807
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2808
{
2809 2810
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2811
				o = 0;
B
Byron Nikolaidis 已提交
2812

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


void
2835
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
2836
{
2837 2838
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
2839
				o = 0;
B
Byron Nikolaidis 已提交
2840

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

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

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

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

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

B
Bruce Momjian 已提交
2932 2933 2934 2935
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
2936

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

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

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

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

B
Bruce Momjian 已提交
2973
	if (left == 0)
2974
		return COPY_NO_DATA_FOUND;
2975

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

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

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

2999 3000 3001 3002 3003 3004 3005
		stmt->lobj_fd = -1;

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

3006 3007
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
3008 3009 3010 3011 3012 3013
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
3014
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
3015

B
Bruce Momjian 已提交
3016
	if (bindInfo && bindInfo->data_left > 0)
3017
		bindInfo->data_left -= retval;
3018

B
Bruce Momjian 已提交
3019 3020
	if (!bindInfo || bindInfo->data_left == 0)
	{
3021
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3022 3023

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

B
Bruce Momjian 已提交
3034
		stmt->lobj_fd = -1;		/* prevent further reading */
3035
	}
3036 3037

	return result;
3038
}