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

20 21
#include "convert.h"

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

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

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

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

50 51 52 53
/*
 *	How to map ODBC scalar functions {fn func(args)} to Postgres.
 *	This is just a simple substitution.  List augmented from:
 *	http://www.merant.com/datadirect/download/docs/odbc16/Odbcref/rappc.htm
54
 *	- thomas 2000-04-03
55
 */
B
Bruce Momjian 已提交
56
char	   *mapFuncs[][2] = {
H
Hiroshi Inoue 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
/*	{ "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" },
106 107
	{"LOCALTIME", "localtime" },
	{"LOCALTIMESTAMP", "localtimestamp" },
H
Hiroshi Inoue 已提交
108 109 110 111 112 113 114
	{"CURRENT_USER", "cast(current_user as text)" },
	{"SESSION_USER", "cast(session_user as text)" },
	{"CURDATE",	 "current_date" },
	{"CURTIME",	 "current_time" },
	{"DAYNAME",	 "to_char($1, 'Day')" },
	{"DAYOFMONTH",  "cast(extract(day from $1) as integer)" },
	{"DAYOFWEEK",	 "(cast(extract(dow from $1) as integer) + 1)" },
H
Hiroshi Inoue 已提交
115
	{"DAYOFYEAR",	 "cast(extract(doy from $1) as integer)" }, 
H
Hiroshi Inoue 已提交
116 117 118 119 120 121 122 123 124
	{"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 已提交
125 126

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

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

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



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

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

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

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

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

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

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

338

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

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

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

402
	}
403 404 405

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

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

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

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

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

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

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

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

524
				s = midtemp[mtemp_cnt];
H
Hiroshi Inoue 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
				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");
				}
540 541
				neut_str = midtemp[mtemp_cnt];
				mtemp_cnt++;
B
Bruce Momjian 已提交
542 543 544
			}
			break;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
#if (ODBCVER >= 0x0300)
                        case SQL_C_NUMERIC:
#ifdef HAVE_LOCALE_H
			/* strcpy(saved_locale, setlocale(LC_ALL, NULL));
			setlocale(LC_ALL, "C"); not needed currently */ 
#endif /* HAVE_LOCALE_H */
			{
			SQL_NUMERIC_STRUCT      *ns;
			int	i, nlen, bit, hval, tv, dig, sta, olen;
			char	calv[SQL_MAX_NUMERIC_LEN * 3], *wv;
			BOOL	dot_exist;

			len = sizeof(SQL_NUMERIC_STRUCT);
			if (bind_size > 0)
				ns = (SQL_NUMERIC_STRUCT *) ((char *) rgbValue + (bind_row * bind_size));
			else
				ns = (SQL_NUMERIC_STRUCT *) rgbValue + bind_row;
			for (wv = neut_str; *wv && isspace(*wv); wv++)
				;
			ns->sign = 1;
			if (*wv == '-')
			{
				ns->sign = 0;
				wv++;
			}
			else if (*wv == '+')
				wv++;
			while (*wv == '0') wv++;
			ns->precision = 0;
			ns->scale = 0;
			for (nlen = 0, dot_exist = FALSE;; wv++) 
			{
				if (*wv == '.')
				{
					if (dot_exist)
						break;
					dot_exist = TRUE;
				}
				else if (!isdigit(*wv))
						break;
				else
				{
					if (dot_exist)
						ns->scale++;
					else
						ns->precision++;
					calv[nlen++] = *wv;
				}
			}
			memset(ns->val, 0, sizeof(ns->val));
			for (hval = 0, bit = 1L, sta = 0, olen = 0; sta < nlen;)
			{
				for (dig = 0, i = sta; i < nlen; i++)
				{
					tv = dig * 10 + calv[i] - '0';
					dig = tv % 2;
					calv[i] = tv / 2 + '0';
					if (i == sta && tv < 2)
						sta++;
				}
				if (dig > 0)
					hval |= bit;
				bit <<= 1;
				if (bit >= (1L << 8))
				{
					ns->val[olen++] = hval;
					hval = 0;
					bit = 1L;
					if (olen >= SQL_MAX_NUMERIC_LEN - 1)
					{
						ns->scale = sta - ns->precision;
						break;
					}
				} 
			}
			if (hval && olen < SQL_MAX_NUMERIC_LEN - 1)
				ns->val[olen++] = hval;
			}
#ifdef HAVE_LOCALE_H
			/* setlocale(LC_ALL, saved_locale); */
#endif /* HAVE_LOCALE_H */
			break;
#endif /* ODBCVER */

B
Bruce Momjian 已提交
1072 1073 1074 1075
			case SQL_C_SSHORT:
			case SQL_C_SHORT:
				len = 2;
				if (bind_size > 0)
1076
					*(SWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
1077
				else
1078
					*((SWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
1079
				break;
1080

B
Bruce Momjian 已提交
1081 1082 1083
			case SQL_C_USHORT:
				len = 2;
				if (bind_size > 0)
1084
					*(UWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atoi(neut_str);
B
Bruce Momjian 已提交
1085
				else
1086
					*((UWORD *) rgbValue + bind_row) = atoi(neut_str);
B
Bruce Momjian 已提交
1087
				break;
1088

B
Bruce Momjian 已提交
1089 1090 1091 1092
			case SQL_C_SLONG:
			case SQL_C_LONG:
				len = 4;
				if (bind_size > 0)
1093
					*(SDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
1094
				else
1095
					*((SDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
1096 1097 1098 1099 1100
				break;

			case SQL_C_ULONG:
				len = 4;
				if (bind_size > 0)
1101
					*(UDWORD *) ((char *) rgbValue + (bind_row * bind_size)) = atol(neut_str);
B
Bruce Momjian 已提交
1102
				else
1103
					*((UDWORD *) rgbValue + bind_row) = atol(neut_str);
B
Bruce Momjian 已提交
1104
				break;
1105

H
Hiroshi Inoue 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
#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 已提交
1126
			case SQL_C_BINARY:
1127

B
Bruce Momjian 已提交
1128 1129
				/* truncate if necessary */
				/* convert octal escapes to bytes */
1130

1131
				if (stmt->current_col < 0)
1132
				{
1133 1134
					pbic = &sbic;
					pbic->data_left = -1;
1135
				}
1136
				else
H
Hiroshi Inoue 已提交
1137
					pbic = &opts->bindings[stmt->current_col];
1138 1139 1140 1141 1142 1143 1144 1145 1146
				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;
1147

B
Bruce Momjian 已提交
1148 1149 1150 1151 1152 1153
				if (stmt->current_col >= 0)
				{
					/*
					 * Second (or more) call to SQLGetData so move the
					 * pointer
					 */
1154
					if (pbic->data_left > 0)
B
Bruce Momjian 已提交
1155
					{
1156 1157
						ptr += len - pbic->data_left;
						len = pbic->data_left;
B
Bruce Momjian 已提交
1158
					}
1159

B
Bruce Momjian 已提交
1160 1161
					/* First call to SQLGetData so initialize data_left */
					else
1162
						pbic->data_left = len;
1163

B
Bruce Momjian 已提交
1164
				}
1165

B
Bruce Momjian 已提交
1166 1167 1168
				if (cbValueMax > 0)
				{
					copy_len = (len > cbValueMax) ? cbValueMax : len;
1169

B
Bruce Momjian 已提交
1170 1171
					/* Copy the data */
					memcpy(rgbValueBindRow, ptr, copy_len);
1172

B
Bruce Momjian 已提交
1173 1174
					/* Adjust data_left for next time */
					if (stmt->current_col >= 0)
1175
						pbic->data_left -= copy_len;
1176
				}
1177

B
Bruce Momjian 已提交
1178 1179 1180 1181 1182 1183
				/*
				 * Finally, check for truncation so that proper status can
				 * be returned
				 */
				if (len > cbValueMax)
					result = COPY_RESULT_TRUNCATED;
1184

1185
				if (pbic->ttlbuf)
1186
				{
1187 1188
					free(pbic->ttlbuf);
					pbic->ttlbuf = NULL;
1189
				}
B
Bruce Momjian 已提交
1190 1191 1192 1193 1194
				mylog("SQL_C_BINARY: len = %d, copy_len = %d\n", len, copy_len);
				break;

			default:
				return COPY_UNSUPPORTED_TYPE;
B
Byron Nikolaidis 已提交
1195 1196
		}
	}
1197

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

1202
	if (result == COPY_OK && stmt->current_col >= 0)
H
Hiroshi Inoue 已提交
1203
		opts->bindings[stmt->current_col].data_left = 0;
1204
	return result;
1205

1206 1207
}

1208

1209 1210 1211 1212
/*--------------------------------------------------------------------
 *	Functions/Macros to get rid of query size limit.
 *
 *	I always used the follwoing macros to convert from
1213
 *	old_statement to new_statement.  Please improve it
1214 1215 1216
 *	if you have a better way.	Hiroshi 2001/05/22
 *--------------------------------------------------------------------
 */
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

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

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

	return q->stmt_len;
}

#define	FLGB_PRE_EXECUTING	1L
#define	FLGB_INACCURATE_RESULT	(1L << 1)
1266 1267
#define	FLGB_CREATE_KEYSET	(1L << 2)
#define	FLGB_KEYSET_DRIVEN	(1L << 3)
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
typedef struct _QueryBuild {
	char	*query_statement;
	UInt4	str_size_limit;
	UInt4	str_alsize;
	UInt4	npos;
	int	current_row;
	int	param_number;
	APDFields *apdopts;
	UInt4	load_stmt_len;
	UInt4	flags;
	BOOL	lf_conv;
	int	ccsc;
	int	errornumber;
	const char *errormsg;

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

1287 1288
#define INIT_MIN_ALLOC	4096
static int
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
QB_initialize(QueryBuild *qb, UInt4 size, StatementClass *stmt, ConnectionClass *conn)
{
	UInt4	newsize = 0;

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

	return newsize;
}

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

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

	return size;
}

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

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

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

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

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

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

#define F_OldPos(qp) \
qp->opos

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

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

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

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

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


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

static int
enlarge_query_statement(QueryBuild *qb, unsigned int newsize)
1438
{
1439
	unsigned int newalsize = INIT_MIN_ALLOC;
1440 1441
	static char *func = "enlarge_statement";

1442
	if (qb->str_size_limit > 0 && qb->str_size_limit < (int) newsize)
1443
	{
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
		free(qb->query_statement);
		qb->query_statement = NULL;
		qb->str_alsize = 0;
		if (qb->stmt)
		{
			qb->stmt->errormsg = "Query buffer overflow in copy_statement_with_parameters";
			qb->stmt->errornumber = STMT_EXEC_ERROR;
			SC_log_error(func, "", qb->stmt);
		}
		else
		{
			qb->errormsg = "Query buffer overflow in copy_statement_with_parameters";
			qb->errornumber = STMT_EXEC_ERROR;
		}
1458 1459 1460 1461
		return -1;
	}
	while (newalsize <= newsize)
		newalsize *= 2;
1462
	if (!(qb->query_statement = realloc(qb->query_statement, newalsize)))
1463
	{
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
		qb->str_alsize = 0;
		if (qb->stmt)
		{
			qb->stmt->errormsg = "Query buffer allocate error in copy_statement_with_parameters";
			qb->stmt->errornumber = STMT_EXEC_ERROR;
		}
		else
		{
			qb->errormsg = "Query buffer allocate error in copy_statement_with_parameters";
			qb->errornumber = STMT_EXEC_ERROR;
		}
1475 1476
		return 0;
	}
1477
	qb->str_alsize = newalsize;
1478 1479 1480 1481 1482 1483 1484
	return newalsize;
}

/*----------
 *	Enlarge stmt_with_params if necessary.
 *----------
 */
1485 1486
#define ENLARGE_NEWSTATEMENT(qb, newpos) \
	if (newpos >= qb->str_alsize) \
1487
	{ \
1488
		if (enlarge_query_statement(qb, newpos) <= 0) \
1489 1490
			return SQL_ERROR; \
	}
1491

1492 1493 1494 1495
/*----------
 *	Terminate the stmt_with_params string with NULL.
 *----------
 */
1496
#define CVT_TERMINATE(qb) \
1497
do { \
1498
	qb->query_statement[qb->npos] = '\0'; \
1499
} while (0)
1500 1501 1502 1503 1504

/*----------
 *	Append a data.
 *----------
 */
1505
#define CVT_APPEND_DATA(qb, s, len) \
1506
do { \
1507 1508 1509 1510 1511
	unsigned int	newpos = qb->npos + len; \
	ENLARGE_NEWSTATEMENT(qb, newpos) \
	memcpy(&qb->query_statement[qb->npos], s, len); \
	qb->npos = newpos; \
	qb->query_statement[newpos] = '\0'; \
1512 1513
} while (0)

1514 1515 1516 1517
/*----------
 *	Append a string.
 *----------
 */
1518
#define CVT_APPEND_STR(qb, s) \
1519
do { \
1520
	unsigned int len = strlen(s); \
1521
	CVT_APPEND_DATA(qb, s, len); \
1522 1523
} while (0)

1524
/*----------
1525
 *	Append a char.
1526 1527
 *----------
 */
1528
#define CVT_APPEND_CHAR(qb, c) \
1529
do { \
1530 1531
	ENLARGE_NEWSTATEMENT(qb, qb->npos + 1); \
	qb->query_statement[qb->npos++] = c; \
1532 1533
} while (0)

1534 1535
/*----------
 *	Append a binary data.
1536
 *	Newly reqeuired size may be overestimated currently.
1537 1538
 *----------
 */
1539
#define CVT_APPEND_BINARY(qb, buf, used) \
1540
do { \
1541 1542 1543
	unsigned int	newlimit = qb->npos + 5 * used; \
	ENLARGE_NEWSTATEMENT(qb, newlimit); \
	qb->npos += convert_to_pgbinary(buf, &qb->query_statement[qb->npos], used); \
1544 1545
} while (0)

1546 1547 1548 1549
/*----------
 *
 *----------
 */
1550
#define CVT_SPECIAL_CHARS(qb, buf, used) \
1551
do { \
1552 1553
	int cnvlen = convert_special_chars(buf, NULL, used, qb->lf_conv, qb->ccsc); \
	unsigned int	newlimit = qb->npos + cnvlen; \
1554
\
1555 1556 1557
	ENLARGE_NEWSTATEMENT(qb, newlimit); \
	convert_special_chars(buf, &qb->query_statement[qb->npos], used, qb->lf_conv, qb->ccsc); \
	qb->npos += cnvlen; \
1558
} while (0)
1559 1560

/*----------
1561
 *	Check if the statement is
1562 1563
 *	SELECT ... INTO table FROM .....
 *	This isn't really a strict check but ...
1564
 *----------
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
 */
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;
1581
		case '\"':				/* double quoted table name ? */
1582 1583 1584
			do
			{
				do
1585
					while (*(++stmt) != '\"' && *stmt);
1586
				while (*stmt && *(++stmt) == '\"');
1587 1588
				while (*stmt && !isspace((unsigned char) *stmt) && *stmt != '\"')
					stmt++;
1589 1590 1591 1592 1593 1594 1595
			}
			while (*stmt == '\"');
			break;
		default:
			while (!isspace((unsigned char) *(++stmt)));
			break;
	}
1596
	if (!*stmt)
1597 1598 1599 1600 1601 1602 1603
		return FALSE;
	while (isspace((unsigned char) *(++stmt)));
	if (strnicmp(stmt, "from", 4))
		return FALSE;
	return isspace((unsigned char) stmt[4]);
}

H
Hiroshi Inoue 已提交
1604
/*----------
1605
 *	Check if the statement is
H
Hiroshi Inoue 已提交
1606 1607
 *	SELECT ... FOR UPDATE .....
 *	This isn't really a strict check but ...
1608
 *----------
H
Hiroshi Inoue 已提交
1609 1610 1611 1612 1613
 */
static BOOL
table_for_update(const char *stmt, int *endpos)
{
	const char *wstmt = stmt;
1614

H
Hiroshi Inoue 已提交
1615
	while (isspace((unsigned char) *(++wstmt)));
1616
	if (!*wstmt)
H
Hiroshi Inoue 已提交
1617 1618 1619 1620 1621 1622 1623 1624
		return FALSE;
	if (strnicmp(wstmt, "update", 6))
		return FALSE;
	wstmt += 6;
	*endpos = wstmt - stmt;
	return !wstmt[0] || isspace((unsigned char) wstmt[0]);
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
/*----------
 *	Check if the statement is
 *	INSERT INTO ... () VALUES ()
 *	This isn't really a strict check but ...
 *----------
 */
static BOOL
insert_without_target(const char *stmt, int *endpos)
{
	const char *wstmt = stmt;

	while (isspace((unsigned char) *(++wstmt)));
	if (!*wstmt)
		return FALSE;
	if (strnicmp(wstmt, "VALUES", 6))
		return FALSE;
	wstmt += 6;
	if (!wstmt[0] || !isspace((unsigned char) wstmt[0]))
		return FALSE;
	while (isspace((unsigned char) *(++wstmt)));
	if (*wstmt != '(' || *(++wstmt) != ')')
		return FALSE;
	wstmt++;
	*endpos = wstmt - stmt;
	return !wstmt[0] || isspace((unsigned char) wstmt[0])
		|| ';' == wstmt[0];
}

H
Hiroshi Inoue 已提交
1653
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
1654
#define		my_strchr(conn, s1,c1) pg_mbschr(conn->ccsc, s1,c1)
H
Hiroshi Inoue 已提交
1655
#else
H
Hiroshi Inoue 已提交
1656
#define		my_strchr(conn, s1,c1) strchr(s1,c1)
H
Hiroshi Inoue 已提交
1657
#endif
1658 1659 1660
/*
 *	This function inserts parameters into an SQL statements.
 *	It will also modify a SELECT statement for use with declare/fetch cursors.
1661
 *	This function does a dynamic memory allocation to get rid of query size limit!
1662
 */
1663
int
1664
copy_statement_with_parameters(StatementClass *stmt)
1665
{
B
Bruce Momjian 已提交
1666
	static char *func = "copy_statement_with_parameters";
1667 1668 1669
	RETCODE		retval;
	QueryParse	query_org, *qp;
	QueryBuild	query_crt, *qb;
1670

1671
	char	   *new_statement;
H
Hiroshi Inoue 已提交
1672

1673 1674 1675 1676
	BOOL	begin_first = FALSE, prepare_dummy_cursor = FALSE;
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
	int		current_row;
B
Bruce Momjian 已提交
1677

1678
	if (!stmt->statement)
B
Bruce Momjian 已提交
1679
	{
B
Byron Nikolaidis 已提交
1680
		SC_log_error(func, "No statement string", stmt);
1681
		return SQL_ERROR;
B
Byron Nikolaidis 已提交
1682
	}
1683

1684 1685 1686 1687 1688 1689 1690 1691
	current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row;
	qp = &query_org;
	QP_initialize(qp, stmt);

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


1694 1695 1696 1697 1698 1699 1700
#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)
1701
		stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1702 1703 1704 1705
	else if (stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY)
	{
		if (stmt->parse_status == STMT_PARSE_NONE)
			parse_statement(stmt);
1706 1707
		if (stmt->parse_status == STMT_PARSE_FATAL)
		{
1708
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1709 1710 1711 1712
			return SQL_ERROR;
		}
		else if (!stmt->updatable)
		{
1713
			stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
1714 1715
			stmt->options.cursor_type = SQL_CURSOR_STATIC;
		}
1716
		else
1717
		{
1718 1719
			qp->from_pos = stmt->from_pos;
			qp->where_pos = stmt->where_pos;
1720
		}
1721
	}
H
Hiroshi Inoue 已提交
1722 1723 1724
#else
	stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY;
	if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN)
1725
		stmt->options.cursor_type = SQL_CURSOR_STATIC;
1726
#endif   /* DRIVER_CURSOR_IMPLEMENT */
1727 1728 1729 1730

	/* 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);
1731 1732 1733 1734 1735 1736 1737 1738 1739
	if (stmt->stmt_with_params)
	{
		free(stmt->stmt_with_params);
		stmt->stmt_with_params = NULL;
	}
	qb = &query_crt;
	if (QB_initialize(qb, qp->stmt_len, stmt, NULL) < 0)
		return SQL_ERROR;
	new_statement = qb->query_statement;
H
Hiroshi Inoue 已提交
1740

1741 1742 1743 1744 1745 1746 1747 1748 1749
	stmt->miscinfo = 0;
	/* For selects, prepend a declare cursor to the statement */
	if (stmt->statement_type == STMT_TYPE_SELECT)
	{
		SC_set_pre_executable(stmt);
		if (prepare_dummy_cursor || ci->drivers.use_declarefetch)
		{
			if (prepare_dummy_cursor)
			{
1750 1751 1752 1753 1754
				if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1))
				{
					strcpy(new_statement, "BEGIN;");
					begin_first = TRUE;
				}
1755 1756 1757
			}
			else if (ci->drivers.use_declarefetch)
				SC_set_fetchcursor(stmt);
H
Hiroshi Inoue 已提交
1758
			sprintf(new_statement, "%sdeclare %s cursor for ",
1759
					new_statement, stmt->cursor_name);
1760 1761 1762
			qb->npos = strlen(new_statement);
			qp->flags |= FLGP_CURSOR_CHECK_OK;
			qp->declare_pos = qb->npos;
1763
		}
1764 1765 1766 1767 1768 1769
		else if (SQL_CONCUR_READ_ONLY != stmt->options.scroll_concurrency)
		{
			qb->flags |= FLGB_CREATE_KEYSET;
			if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type)
				qb->flags |= FLGB_KEYSET_DRIVEN;
		}
1770
	}
1771 1772

	for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++)
B
Bruce Momjian 已提交
1773
	{
1774 1775
		retval = inner_process_tokens(qp, qb);
		if (SQL_ERROR == retval)
1776
		{
1777 1778 1779 1780 1781 1782 1783 1784
			if (0 == stmt->errornumber)
			{
				stmt->errornumber = qb->errornumber;
				stmt->errormsg = qb->errormsg;
			}
			SC_log_error(func, "", stmt);
			QB_Destructor(qb);
			return retval;
1785
		}
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
	}
	/* make sure new_statement is always null-terminated */
	CVT_TERMINATE(qb);

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

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

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

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

		if (0 == npos)
1822
		{
1823
			npos = qb->npos;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
			for (; npos > 0; npos--)
			{
				if (isspace(new_statement[npos - 1]))
					continue;
				if (';' != new_statement[npos - 1])
					break;
			}
			if (0 != (qb->flags & FLGB_KEYSET_DRIVEN))
			{
				qb->npos = npos;
				/* ----------
				 * 1st query is for field information
				 * 2nd query is keyset gathering
				 */
				CVT_APPEND_STR(qb, " where ctid = '(,)';select ctid, oid from ");
				CVT_APPEND_DATA(qb, qp->statement + qp->from_pos + 5, npos - qp->from_pos - 5);
			}
		}
1842
		stmt->load_statement = malloc(npos + 1);
1843 1844
		memcpy(stmt->load_statement, qb->query_statement, npos);
		stmt->load_statement[npos] = '\0';
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
	}
#endif   /* DRIVER_CURSOR_IMPLEMENT */
	if (prepare_dummy_cursor && SC_is_pre_executable(stmt))
	{
		char		fetchstr[128];

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

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

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

	RETCODE	retval;
	char	   oldchar;

	if (qp->from_pos == (Int4) qp->opos)
	{
		CVT_APPEND_STR(qb, ", CTID, OID ");
	}
	else if (qp->where_pos == (Int4) qp->opos)
1877
	{
1878
		qb->load_stmt_len = qb->npos;
1879 1880 1881 1882 1883 1884
		if (0 != (qb->flags & FLGB_KEYSET_DRIVEN))
		{
			CVT_APPEND_STR(qb, "where ctid = '(,)';select CTID, OID from ");
			CVT_APPEND_DATA(qb, qp->statement + qp->from_pos + 5, qp->where_pos - qp->from_pos - 5);
		}
	}
1885
#ifdef MULTIBYTE
1886 1887 1888 1889 1890 1891
	oldchar = encoded_byte_check(&qp->encstr, qp->opos);
	if (ENCODE_STATUS(qp->encstr) != 0)
	{
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
1892

1893 1894 1895
	/*
	 * From here we are guaranteed to handle a 1-byte character.
	 */
H
Hiroshi Inoue 已提交
1896
#else
1897
	oldchar = qp->statement[qp->opos];
1898
#endif
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
	if (qp->in_escape)			/* escape check */
	{
		qp->in_escape = FALSE;
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
	else if (qp->in_quote || qp->in_dquote) /* quote/double quote check */
	{
		if (oldchar == '\\')
			qp->in_escape = TRUE;
		else if (oldchar == '\'' && qp->in_quote)
			qp->in_quote = FALSE;
		else if (oldchar == '\"' && qp->in_dquote)
			qp->in_dquote = FALSE;
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
1917

1918 1919 1920 1921 1922 1923 1924 1925
	/*
	 * From here we are guranteed to be in neither an escape, a quote
	 * nor a double quote.
	 */
	/* Squeeze carriage-return/linefeed pairs to linefeed only */
	else if (lf_conv && oldchar == '\r' && qp->opos + 1 < qp->stmt_len &&
			qp->statement[qp->opos + 1] == '\n')
		return SQL_SUCCESS;
1926

1927 1928 1929 1930 1931 1932 1933
	/*
	 * Handle literals (date, time, timestamp) and ODBC scalar
	 * functions
	 */
	else if (oldchar == '{')
	{
		if (SQL_ERROR == convert_escape(qp, qb))
B
Bruce Momjian 已提交
1934
		{
1935
			if (0 == qb->errornumber)
H
Hiroshi Inoue 已提交
1936
			{
1937 1938
				qb->errornumber = STMT_EXEC_ERROR;
				qb->errormsg = "ODBC escape convert error";
1939
			}
1940 1941
			mylog("%s convert_escape error\n", func);
			return SQL_ERROR;
1942
		}
1943 1944 1945 1946 1947 1948 1949 1950
		if (isalnum(F_OldPtr(qp)[1]))
			CVT_APPEND_CHAR(qb, ' ');
		return SQL_SUCCESS;
	}
	/* End of an escape sequence */
	else if (oldchar == '}')
	{
		if (qp->statement_type == STMT_TYPE_PROCCALL)
1951
		{
1952 1953
			if (qp->proc_no_param)
				CVT_APPEND_STR(qb, "()");
1954
		}
1955 1956 1957 1958
		else if (!isspace(F_OldPtr(qp)[1]))
			CVT_APPEND_CHAR(qb, ' ');
		return SQL_SUCCESS;
	}
1959

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
	/*
	 * Can you have parameter markers inside of quotes?  I dont think
	 * so. All the queries I've seen expect the driver to put quotes
	 * if needed.
	 */
	else if (oldchar != '?')
	{
		if (oldchar == '\'')
			qp->in_quote = TRUE;
		else if (oldchar == '\\')
			qp->in_escape = TRUE;
		else if (oldchar == '\"')
			qp->in_dquote = TRUE;
B
Bruce Momjian 已提交
1973 1974
		else
		{
1975
			if (isspace((unsigned char) oldchar))
1976
			{
1977
				if (!qp->prev_token_end)
H
Hiroshi Inoue 已提交
1978
				{
1979 1980 1981
					qp->prev_token_end = TRUE;
					qp->token_save[qp->token_len] = '\0';
					if (qp->token_len == 4)
H
Hiroshi Inoue 已提交
1982
					{
1983 1984
						if (0 != (qp->flags & FLGP_CURSOR_CHECK_OK) &&
							into_table_from(&qp->statement[qp->opos - qp->token_len]))
H
Hiroshi Inoue 已提交
1985
						{
1986 1987
							qp->flags |= FLGP_SELECT_INTO;
							qp->flags &= ~FLGP_CURSOR_CHECK_OK;
1988
							qb->flags &= ~FLGB_KEYSET_DRIVEN;
1989 1990 1991
							qp->statement_type = STMT_TYPE_CREATE;
							memmove(qb->query_statement, qb->query_statement + qp->declare_pos, qb->npos - qp->declare_pos);
							qb->npos -= qp->declare_pos;
H
Hiroshi Inoue 已提交
1992
						}
1993
					}
1994
					else if (qp->token_len == 3)
1995 1996
					{
						int			endpos;
1997

1998 1999 2000 2001 2002 2003 2004
						if (0 != (qp->flags & FLGP_CURSOR_CHECK_OK) &&
							strnicmp(qp->token_save, "for", 3) == 0 &&
							table_for_update(&qp->statement[qp->opos], &endpos))
						{
							qp->flags |= FLGP_SELECT_FOR_UPDATE;
							qp->flags &= ~FLGP_CURSOR_CHECK_OK;
							if (qp->flags & FLGP_PREPARE_DUMMY_CURSOR)
H
Hiroshi Inoue 已提交
2005
							{
2006 2007 2008 2009 2010 2011 2012
								qb->npos -= 4;
								qp->opos += endpos;
							}
							else
							{
								memmove(qb->query_statement, qb->query_statement + qp->declare_pos, qb->npos - qp->declare_pos);
								qb->npos -= qp->declare_pos;
H
Hiroshi Inoue 已提交
2013 2014
							}
						}
2015
					}
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
					else if (qp->token_len == 2)
					{
						int	endpos;

						if (STMT_TYPE_INSERT == qp->statement_type &&
							strnicmp(qp->token_save, "()", 2) == 0 &&
							insert_without_target(&qp->statement[qp->opos], &endpos))
						{
							qb->npos -= 2;
							CVT_APPEND_STR(qb, "DEFAULT VALUES");
							qp->opos += endpos;
							return SQL_SUCCESS;
						}
					}
H
Hiroshi Inoue 已提交
2030
				}
2031
			}
2032
			else if (qp->prev_token_end)
2033
			{
2034 2035 2036
				qp->prev_token_end = FALSE;
				qp->token_save[0] = oldchar;
				qp->token_len = 1;
2037
			}
2038 2039
			else if (qp->token_len + 1 < sizeof(qp->token_save))
				qp->token_save[qp->token_len++] = oldchar;
2040
		}
2041 2042 2043
		CVT_APPEND_CHAR(qb, oldchar);
		return SQL_SUCCESS;
	}
2044

2045 2046 2047 2048 2049 2050 2051 2052 2053
	/*
	 * Its a '?' parameter alright
	 */
	if (retval = ResolveOneParam(qb), retval < 0)
		return retval;

	return SQL_SUCCESS;
}

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
#if (ODBCVER >= 0x0300)
static BOOL
ResolveNumericParam(const SQL_NUMERIC_STRUCT *ns, char *chrform)
{
	static int prec[] = {1, 3, 5, 8, 10, 13, 15, 17, 20, 22, 25, 29, 32, 34, 37, 39};
	Int4	i, j, k, ival, vlen, len, newlen;
	unsigned char		calv[40];
	const unsigned char	*val = (const unsigned char *) ns->val;
	BOOL	next_figure;

	if (0 == ns->precision)
	{
		strcpy(chrform, "0");
		return TRUE;
	}
	else if (ns->precision < prec[sizeof(Int4)])
	{
		for (i = 0, ival = 0; i < sizeof(Int4) && prec[i] <= ns->precision; i++)
		{
			ival += (val[i] << (8 * i)); /* ns->val is little endian */
		}
		if (0 == ns->scale)
		{
			if (0 == ns->sign)
				ival *= -1;
			sprintf(chrform, "%d", ival);
		}
		else if (ns->scale > 0)
		{
			Int4	i, div, o1val, o2val;

			for (i = 0, div = 1; i < ns->scale; i++)
				div *= 10;
			o1val = ival / div;
			o2val = ival % div;
			if (0 == ns->sign)
				o1val *= -1;
			sprintf(chrform, "%d.%0.*d", o1val, ns->scale, o2val);
		}
		return TRUE;
	}

	for (i = 0; i < SQL_MAX_NUMERIC_LEN && prec[i] <= ns->precision; i++)
		;
	vlen = i;
	len = 0;
	memset(calv, 0, sizeof(calv));
	for (i = vlen - 1; i >= 0; i--)
	{
		for (j = len - 1; j >= 0; j--)
		{
			if (!calv[j])
				continue;
			ival = (((Int4)calv[j]) << 8);
			calv[j] = (ival % 10);
			ival /= 10;
			calv[j + 1] += (ival % 10);
			ival /= 10;
			calv[j + 2] += (ival % 10);
			ival /= 10;
			calv[j + 3] += ival;
			for (k = j;; k++)
			{
				next_figure = FALSE;
				if (calv[k] > 0)
				{
					if (k >= len)
						len = k + 1;
					while (calv[k] > 9)
					{
						calv[k + 1]++;
						calv[k] -= 10;
						next_figure = TRUE;
					}
				}
				if (k >= j + 3 && !next_figure)
					break;
			}
		}
		ival = val[i];
		if (!ival)
			continue;
		calv[0] += (ival % 10);
		ival /= 10;
		calv[1] += (ival % 10);
		ival /= 10;
		calv[2] += ival;
		for (j = 0;; j++)
		{
			next_figure = FALSE;
			if (calv[j] > 0)
			{
				if (j >= len)
					len = j + 1;
				while (calv[j] > 9)
				{
					calv[j + 1]++;
					calv[j] -= 10;
					next_figure = TRUE;
				}
			}
			if (j >= 2 && !next_figure)
				break;
		}
	}
	newlen = 0;
	if (0 == ns->sign)
		chrform[newlen++] = '-';
	for (i = len - 1; i >= ns->scale; i--)
		chrform[newlen++] = calv[i] + '0';
	if (ns->scale > 0)
	{
		chrform[newlen++] = '.';
		for (; i >= 0; i--)
			chrform[newlen++] = calv[i] + '0';
	}
	chrform[newlen] = '\0';
	return TRUE;
}
#endif /* ODBCVER */

/*
 *
 */
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
static int
ResolveOneParam(QueryBuild *qb)
{
	const char *func = "ResolveOneParam";

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

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

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

	if (param_number >= opts->allocated)
	{
		if (0 != (qb->flags & FLGB_PRE_EXECUTING))
B
Bruce Momjian 已提交
2209
		{
2210 2211 2212
			CVT_APPEND_STR(qb, "NULL");
			qb->flags |= FLGB_INACCURATE_RESULT;
			return SQL_SUCCESS;
2213
		}
B
Bruce Momjian 已提交
2214 2215
		else
		{
2216 2217 2218 2219
			CVT_APPEND_CHAR(qb, '?');
			return SQL_SUCCESS;
		}
	}
2220

2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
	/* Assign correct buffers based on data at exec param or not */
	if (opts->parameters[param_number].data_at_exec)
	{
		used = opts->parameters[param_number].EXEC_used ? *opts->parameters[param_number].EXEC_used : SQL_NTS;
		buffer = opts->parameters[param_number].EXEC_buffer;
	}
	else
	{
		UInt4	bind_size = opts->param_bind_type;
		UInt4	ctypelen;

		buffer = opts->parameters[param_number].buffer + offset;
		if (current_row > 0)
		{
			if (bind_size > 0)
				buffer += (bind_size * current_row);
			else if (ctypelen = ctype_length(opts->parameters[param_number].CType), ctypelen > 0)
				buffer += current_row * ctypelen;
			else 
				buffer += current_row * opts->parameters[param_number].buflen;
		}
		if (opts->parameters[param_number].used)
		{
			UInt4	p_offset = offset;
			if (bind_size > 0)
				p_offset = offset + bind_size * current_row;
H
Hiroshi Inoue 已提交
2247
			else
2248 2249
				p_offset = offset + sizeof(SDWORD) * current_row;
			used = *(SDWORD *)((char *)opts->parameters[param_number].used + p_offset);
2250
		}
2251 2252 2253
		else
			used = SQL_NTS;
	}	
2254

2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
	/* Handle NULL parameter data */
	if (used == SQL_NULL_DATA)
	{
		CVT_APPEND_STR(qb, "NULL");
		return SQL_SUCCESS;
	}

	/*
	 * If no buffer, and it's not null, then what the hell is it? Just
	 * leave it alone then.
	 */
	if (!buffer)
	{
		if (0 != (qb->flags & FLGB_PRE_EXECUTING))
B
Bruce Momjian 已提交
2269
		{
2270 2271 2272
			CVT_APPEND_STR(qb, "NULL");
			qb->flags |= FLGB_INACCURATE_RESULT;
			return SQL_SUCCESS;
2273
		}
2274
		else
B
Bruce Momjian 已提交
2275
		{
2276 2277
			CVT_APPEND_CHAR(qb, '?');
			return SQL_SUCCESS;
2278
		}
2279
	}
2280

2281 2282
	param_ctype = opts->parameters[param_number].CType;
	param_sqltype = opts->parameters[param_number].SQLType;
B
Bruce Momjian 已提交
2283

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

2287 2288 2289
	/* replace DEFAULT with something we can use */
	if (param_ctype == SQL_C_DEFAULT)
		param_ctype = sqltype_to_default_ctype(param_sqltype);
2290

2291 2292 2293 2294 2295 2296 2297 2298 2299
	allocbuf = buf = NULL;
	param_string[0] = '\0';
	cbuf[0] = '\0';
	memset(&st, 0, sizeof(st));
	t = time(NULL);
	tim = localtime(&t);
	st.m = tim->tm_mon + 1;
	st.d = tim->tm_mday;
	st.y = tim->tm_year + 1900;
2300

2301 2302 2303 2304 2305 2306 2307
	/* Convert input C type to a neutral format */
	switch (param_ctype)
	{
		case SQL_C_BINARY:
		case SQL_C_CHAR:
			buf = buffer;
			break;
2308

H
Hiroshi Inoue 已提交
2309
#ifdef	UNICODE_SUPPORT
2310 2311 2312 2313
		case SQL_C_WCHAR:
			buf = allocbuf = ucs2_to_utf8((SQLWCHAR *) buffer, used / 2, &used);
			used *= 2;
			break;
H
Hiroshi Inoue 已提交
2314 2315
#endif /* UNICODE_SUPPORT */

2316 2317
		case SQL_C_DOUBLE:
			sprintf(param_string, "%.15g",
B
Bruce Momjian 已提交
2318
						*((SDOUBLE *) buffer));
2319
			break;
2320

2321 2322 2323 2324
		case SQL_C_FLOAT:
			sprintf(param_string, "%.6g",
					*((SFLOAT *) buffer));
			break;
2325

2326 2327 2328 2329 2330
		case SQL_C_SLONG:
		case SQL_C_LONG:
			sprintf(param_string, "%ld",
					*((SDWORD *) buffer));
			break;
2331

H
Hiroshi Inoue 已提交
2332 2333
#if (ODBCVER >= 0x0300) && defined(ODBCINT64)
#ifdef WIN32
2334 2335 2336 2337
		case SQL_C_SBIGINT:
			sprintf(param_string, "%I64d",
					*((SQLBIGINT *) buffer));
			break;
H
Hiroshi Inoue 已提交
2338

2339 2340 2341 2342
		case SQL_C_UBIGINT:
			sprintf(param_string, "%I64u",
					*((SQLUBIGINT *) buffer));
			break;
H
Hiroshi Inoue 已提交
2343 2344 2345

#endif /* WIN32 */
#endif /* ODBCINT64 */
2346 2347 2348 2349 2350
		case SQL_C_SSHORT:
		case SQL_C_SHORT:
			sprintf(param_string, "%d",
					*((SWORD *) buffer));
			break;
2351

2352 2353 2354 2355 2356
		case SQL_C_STINYINT:
		case SQL_C_TINYINT:
			sprintf(param_string, "%d",
					*((SCHAR *) buffer));
			break;
2357

2358 2359 2360 2361
		case SQL_C_ULONG:
			sprintf(param_string, "%lu",
					*((UDWORD *) buffer));
			break;
2362

2363 2364 2365 2366
		case SQL_C_USHORT:
			sprintf(param_string, "%u",
					*((UWORD *) buffer));
			break;
2367

2368 2369 2370 2371
		case SQL_C_UTINYINT:
			sprintf(param_string, "%u",
					*((UCHAR *) buffer));
			break;
2372

2373 2374 2375
		case SQL_C_BIT:
			{
				int			i = *((UCHAR *) buffer);
2376

B
Bruce Momjian 已提交
2377 2378
					sprintf(param_string, "%d", i ? 1 : 0);
					break;
2379
			}
2380

2381
		case SQL_C_DATE:
2382
#if (ODBCVER >= 0x0300)
2383
		case SQL_C_TYPE_DATE:		/* 91 */
2384
#endif
2385 2386
			{
				DATE_STRUCT *ds = (DATE_STRUCT *) buffer;
2387

2388 2389 2390
				st.m = ds->month;
				st.d = ds->day;
				st.y = ds->year;
2391

2392 2393
				break;
			}
2394

2395
		case SQL_C_TIME:
2396
#if (ODBCVER >= 0x0300)
2397
		case SQL_C_TYPE_TIME:		/* 92 */
2398
#endif
2399 2400
			{
				TIME_STRUCT *ts = (TIME_STRUCT *) buffer;
2401

2402 2403 2404
				st.hh = ts->hour;
				st.mm = ts->minute;
				st.ss = ts->second;
2405

2406 2407
				break;
			}
2408

2409
		case SQL_C_TIMESTAMP:
2410
#if (ODBCVER >= 0x0300)
2411
		case SQL_C_TYPE_TIMESTAMP:	/* 93 */
2412
#endif
2413 2414
			{
				TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer;
2415

2416 2417 2418 2419 2420 2421 2422
				st.m = tss->month;
				st.d = tss->day;
				st.y = tss->year;
				st.hh = tss->hour;
				st.mm = tss->minute;
				st.ss = tss->second;
				st.fr = tss->fraction;
2423

2424
				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);
2425

2426
				break;
2427

2428
			}
2429 2430 2431 2432 2433
#if (ODBCVER >= 0x0300)
		case SQL_C_NUMERIC:
			if (ResolveNumericParam((SQL_NUMERIC_STRUCT *) buffer, param_string))
				break;
#endif
2434 2435 2436 2437 2438 2439 2440
		default:
			/* error */
			qb->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters";
			qb->errornumber = STMT_NOT_IMPLEMENTED_ERROR;
			CVT_TERMINATE(qb);	/* just in case */
			return SQL_ERROR;
	}
2441

2442 2443 2444 2445
	/*
	 * Now that the input data is in a neutral format, convert it to
	 * the desired output format (sqltype)
	 */
2446

2447 2448 2449 2450 2451
	switch (param_sqltype)
	{
		case SQL_CHAR:
		case SQL_VARCHAR:
		case SQL_LONGVARCHAR:
H
Hiroshi Inoue 已提交
2452
#ifdef	UNICODE_SUPPORT
2453 2454 2455
		case SQL_WCHAR:
		case SQL_WVARCHAR:
		case SQL_WLONGVARCHAR:
H
Hiroshi Inoue 已提交
2456
#endif /* UNICODE_SUPPORT */
2457

2458
			CVT_APPEND_CHAR(qb, '\'');	/* Open Quote */
2459

2460 2461 2462
			/* it was a SQL_C_CHAR */
			if (buf)
				CVT_SPECIAL_CHARS(qb, buf, used);
2463

2464 2465 2466
			/* it was a numeric type */
			else if (param_string[0] != '\0')
				CVT_APPEND_STR(qb, param_string);
2467

2468 2469 2470 2471 2472
			/* 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);
2473

2474 2475
				CVT_APPEND_STR(qb, tmp);
			}
2476

2477
			CVT_APPEND_CHAR(qb, '\'');	/* Close Quote */
2478

2479
			break;
2480

2481
		case SQL_DATE:
2482
#if (ODBCVER >= 0x0300)
2483
		case SQL_TYPE_DATE:	/* 91 */
2484
#endif
2485 2486 2487 2488 2489
			if (buf)
			{				/* copy char data to time */
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2490

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

2493 2494
			CVT_APPEND_STR(qb, tmp);
			break;
2495

2496
		case SQL_TIME:
2497
#if (ODBCVER >= 0x0300)
2498
		case SQL_TYPE_TIME:	/* 92 */
2499
#endif
2500 2501 2502 2503 2504
			if (buf)
			{				/* copy char data to time */
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2505

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

2508 2509
			CVT_APPEND_STR(qb, tmp);
			break;
2510

2511
		case SQL_TIMESTAMP:
2512
#if (ODBCVER >= 0x0300)
2513
		case SQL_TYPE_TIMESTAMP:	/* 93 */
2514
#endif
2515

2516 2517 2518 2519 2520
			if (buf)
			{
				my_strcpy(cbuf, sizeof(cbuf), buf, used);
				parse_datetime(cbuf, &st);
			}
2521

2522 2523 2524 2525 2526 2527 2528 2529
			/*
			 * sprintf(tmp, "'%.4d-%.2d-%.2d %.2d:%.2d:%.2d'", st.y,
			 * st.m, st.d, st.hh, st.mm, st.ss);
			 */
			tmp[0] = '\'';
			/* Time zone stuff is unreliable */
			stime2timestamp(&st, tmp + 1, USE_ZONE, PG_VERSION_GE(conn, 7.2));
			strcat(tmp, "'::timestamp");
2530

2531
			CVT_APPEND_STR(qb, tmp);
2532

2533
			break;
2534

2535 2536 2537 2538
		case SQL_BINARY:
		case SQL_VARBINARY:/* non-ascii characters should be
							* converted to octal */
			CVT_APPEND_CHAR(qb, '\'');	/* Open Quote */
2539

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

2542
			CVT_APPEND_BINARY(qb, buf, used);
2543

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

2546
			break;
2547

2548
		case SQL_LONGVARBINARY:
B
Bruce Momjian 已提交
2549

2550 2551 2552 2553 2554 2555
			if (opts->parameters[param_number].data_at_exec)
				lobj_oid = opts->parameters[param_number].lobj_oid;
			else
			{
				/* begin transaction if needed */
				if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
2556
				{
2557
					if (!CC_begin(conn))
B
Bruce Momjian 已提交
2558
					{
2559 2560
						qb->errormsg = "Could not begin (in-line) a transaction";
						qb->errornumber = STMT_EXEC_ERROR;
B
Byron Nikolaidis 已提交
2561 2562
						return SQL_ERROR;
					}
2563
				}
B
Bruce Momjian 已提交
2564

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
				/* store the oid */
				lobj_oid = lo_creat(conn, INV_READ | INV_WRITE);
				if (lobj_oid == 0)
				{
					qb->errornumber = STMT_EXEC_ERROR;
					qb->errormsg = "Couldnt create (in-line) large object.";
					return SQL_ERROR;
				}

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

2583
				retval = lo_write(conn, lobj_fd, buffer, used);
2584

2585
				lo_close(conn, lobj_fd);
2586

2587 2588 2589 2590
				/* commit transaction if needed */
				if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
				{
					if (!CC_commit(conn))
B
Bruce Momjian 已提交
2591
					{
2592 2593 2594
						qb->errormsg = "Could not commit (in-line) a transaction";
						qb->errornumber = STMT_EXEC_ERROR;
						return SQL_ERROR;
B
Bruce Momjian 已提交
2595 2596
					}
				}
2597
			}
2598

2599 2600 2601 2602 2603 2604 2605
			/*
			 * the oid of the large object -- just put that in for the
			 * parameter marker -- the data has already been sent to
			 * the large object
			 */
			sprintf(param_string, "'%d'", lobj_oid);
			CVT_APPEND_STR(qb, param_string);
2606

2607
			break;
B
Bruce Momjian 已提交
2608

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

2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
		case SQL_REAL:
			if (buf)
				my_strcpy(param_string, sizeof(param_string), buf, used);
			sprintf(tmp, "'%s'::float4", param_string);
			CVT_APPEND_STR(qb, tmp);
			break;
		case SQL_FLOAT:
		case SQL_DOUBLE:
			if (buf)
				my_strcpy(param_string, sizeof(param_string), buf, used);
			sprintf(tmp, "'%s'::float8", param_string);
			CVT_APPEND_STR(qb, tmp);
			break;
		case SQL_NUMERIC:
			if (buf)
			{
				cbuf[0] = '\'';
2632 2633
				my_strcpy(cbuf + 1, sizeof(cbuf) - 3, buf, used);	/* 3 = 1('\'') +
																	* strlen("'")
2634
																	* + 1('\0') */
2635
				strcat(cbuf, "'");
2636 2637
			}
			else
2638
				sprintf(cbuf, "'%s'", param_string);
2639 2640
			CVT_APPEND_STR(qb, cbuf);
			break;
2641
		default:			/* a numeric type or SQL_BIT */
2642 2643
			if (param_sqltype == SQL_BIT)
				CVT_APPEND_CHAR(qb, '\'');		/* Open Quote */
B
Bruce Momjian 已提交
2644

2645 2646 2647
			if (buf)
			{
				switch (used)
B
Bruce Momjian 已提交
2648
				{
2649 2650 2651 2652 2653 2654 2655
					case SQL_NULL_DATA:
						break;
					case SQL_NTS:
						CVT_APPEND_STR(qb, buf);
						break;
					default:
						CVT_APPEND_DATA(qb, buf, used);
B
Bruce Momjian 已提交
2656
				}
2657 2658 2659
			}
			else
				CVT_APPEND_STR(qb, param_string);
B
Bruce Momjian 已提交
2660

2661 2662
			if (param_sqltype == SQL_BIT)
				CVT_APPEND_CHAR(qb, '\'');		/* Close Quote */
B
Bruce Momjian 已提交
2663

2664 2665
			break;
	}
H
Hiroshi Inoue 已提交
2666
#ifdef	UNICODE_SUPPORT
2667 2668
	if (allocbuf)
		free(allocbuf);
H
Hiroshi Inoue 已提交
2669
#endif /* UNICODE_SUPPORT */
2670 2671 2672
	return SQL_SUCCESS;
}

2673

H
Hiroshi Inoue 已提交
2674 2675
static const char *
mapFunction(const char *func, int param_count)
2676
{
B
Bruce Momjian 已提交
2677
	int			i;
2678 2679

	for (i = 0; mapFuncs[i][0]; i++)
H
Hiroshi Inoue 已提交
2680 2681 2682 2683
	{
		if (mapFuncs[i][0][0] == '%')
		{
			if (mapFuncs[i][0][1] - '0' == param_count &&
H
Hiroshi Inoue 已提交
2684
			    !stricmp(mapFuncs[i][0] + 2, func))
H
Hiroshi Inoue 已提交
2685 2686 2687
				return mapFuncs[i][1];
		}
		else if (!stricmp(mapFuncs[i][0], func))
2688
			return mapFuncs[i][1];
H
Hiroshi Inoue 已提交
2689
	}
2690 2691 2692

	return NULL;
}
2693

2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
/*
 * processParameters()
 * Process function parameters and work with embedded escapes sequences.
 */
static int
processParameters(QueryParse *qp, QueryBuild *qb,
		UInt4 *output_count, Int4 param_pos[][2])
{
	static const char *func = "processParameters";
	int retval, innerParenthesis, param_count;
	BOOL stop;

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

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

			case '}':
				stop = (0 == innerParenthesis);
				break;
2758

2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
		}
		if (stop) /* returns with the last } position */
			break;
	}
	if (param_pos[param_count][0] >= 0)
	{
		mylog("%s closing ) not found %d\n", func, innerParenthesis);
		qb->errornumber = STMT_EXEC_ERROR;
		qb->errormsg = "processParameters closing ) not found";
		return SQL_ERROR;
	}
	else if (1 == param_count) /* the 1 parameter is really valid ? */
	{
		BOOL	param_exist = FALSE;
		int	i;

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

	return SQL_SUCCESS;
}
H
Hiroshi Inoue 已提交
2791

2792
/*
2793 2794
 * convert_escape()
 * This function doesn't return a pointer to static memory any longer !
2795
 */
2796 2797
static int
convert_escape(QueryParse *qp, QueryBuild *qb)
2798
{
2799 2800 2801 2802 2803
	static const char *func = "convert_escape";
	RETCODE	retval = SQL_SUCCESS;
	char		buf[1024], key[65];
	unsigned char	ucv;
	UInt4		prtlen;
H
Hiroshi Inoue 已提交
2804
 
2805 2806
	if (F_OldChar(qp) == '{') /* skip the first { */
		F_OldNext(qp);
2807
	/* Separate off the key, skipping leading and trailing whitespace */
2808 2809 2810 2811 2812 2813
	while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv))
		F_OldNext(qp);
	/*
	 * procedure calls
	 */
	if (qp->statement_type == STMT_TYPE_PROCCALL)
2814
	{
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
		int	lit_call_len = 4;
		ConnectionClass *conn = qb->conn;

		/* '?=' to accept return values exists ? */
		if (F_OldChar(qp) == '?')
		{
			qb->param_number++;
			while (isspace((unsigned char) qp->statement[++qp->opos]));
			if (F_OldChar(qp) != '=')
			{
				F_OldPrior(qp);
				return SQL_SUCCESS;
			}
			while (isspace((unsigned char) qp->statement[++qp->opos]));
		}
		if (strnicmp(F_OldPtr(qp), "call", lit_call_len) ||
			!isspace((unsigned char) F_OldPtr(qp)[lit_call_len]))
2832
		{
2833 2834
			F_OldPrior(qp);
			return SQL_SUCCESS;
2835
		}
2836 2837 2838 2839 2840
		qp->opos += lit_call_len;
		CVT_APPEND_STR(qb, "SELECT ");
		if (my_strchr(conn, F_OldPtr(qp), '('))
			qp->proc_no_param = FALSE;
		return SQL_SUCCESS;
2841
	}
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853

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

	if (F_NewPos(qb) > 0 && isalnum(F_NewPtr(qb)[-1]))
		CVT_APPEND_CHAR(qb, ' ');
	
H
Hiroshi Inoue 已提交
2854 2855 2856
	if (strcmp(key, "d") == 0)
	{
		/* Literal; return the escape part adding type cast */
2857 2858 2859
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		prtlen = snprintf(buf, sizeof(buf), "%s::date ", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2860 2861 2862 2863
	}
	else if (strcmp(key, "t") == 0)
	{
		/* Literal; return the escape part adding type cast */
2864 2865 2866
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		prtlen = snprintf(buf, sizeof(buf), "%s::time", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2867 2868 2869 2870
	}
	else if (strcmp(key, "ts") == 0)
	{
		/* Literal; return the escape part adding type cast */
2871 2872 2873
		F_ExtractOldTo(qp, buf, '}', sizeof(buf));
		if (PG_VERSION_LT(qb->conn, 7.1))
			prtlen = snprintf(buf, sizeof(buf), "%s::datetime", buf);
H
Hiroshi Inoue 已提交
2874
		else
2875 2876
			prtlen = snprintf(buf, sizeof(buf), "%s::timestamp", buf);
		CVT_APPEND_DATA(qb, buf, prtlen);
H
Hiroshi Inoue 已提交
2877 2878
	}
	else if (strcmp(key, "oj") == 0) /* {oj syntax support for 7.1 * servers */
B
Bruce Momjian 已提交
2879
	{
2880 2881
		F_OldPrior(qp);
		return SQL_SUCCESS; /* Continue at inner_process_tokens loop */
2882
	}
B
Bruce Momjian 已提交
2883 2884
	else if (strcmp(key, "fn") == 0)
	{
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
		QueryBuild	nqb;
		const char *mapExpr;
		int	i, param_count;
		UInt4	param_consumed;
		Int4	param_pos[16][2];

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

B
Bruce Momjian 已提交
2904
		/*
H
Hiroshi Inoue 已提交
2905
 		 * We expect left parenthesis here, else return fn body as-is
B
Bruce Momjian 已提交
2906
		 * since it is one of those "function constants".
2907
		 */
2908
		if (F_OldChar(qp) != '(')
B
Bruce Momjian 已提交
2909
		{
2910 2911
			CVT_APPEND_STR(qb, key);
			return SQL_SUCCESS;
2912
		}
B
Bruce Momjian 已提交
2913 2914

		/*
H
Hiroshi Inoue 已提交
2915 2916 2917
		 * Process parameter list and inner escape
		 * sequences
		 * Aceto 2002-01-29
2918
		 */
H
Hiroshi Inoue 已提交
2919

2920 2921 2922 2923 2924 2925 2926 2927
		QB_initialize_copy(&nqb, qb, 1024);
		if (retval = processParameters(qp, &nqb, &param_consumed, param_pos), retval == SQL_ERROR)
		{
			qb->errornumber = nqb.errornumber;
			qb->errormsg = nqb.errormsg;
			QB_Destructor(&nqb);
			return retval;
		}
H
Hiroshi Inoue 已提交
2928 2929

		for (param_count = 0;; param_count++)
B
Bruce Momjian 已提交
2930
		{
H
Hiroshi Inoue 已提交
2931 2932
			if (param_pos[param_count][0] < 0)
				break;
2933
		}
H
Hiroshi Inoue 已提交
2934
		if (param_count == 1 &&
H
Hiroshi Inoue 已提交
2935
		    param_pos[0][1] < param_pos[0][0])
H
Hiroshi Inoue 已提交
2936
			param_count = 0;
2937

H
Hiroshi Inoue 已提交
2938 2939
		mapExpr = mapFunction(key, param_count);
		if (mapExpr == NULL)
2940 2941 2942 2943
		{
			CVT_APPEND_STR(qb, key);
			CVT_APPEND_DATA(qb, nqb.query_statement, nqb.npos);
		}
H
Hiroshi Inoue 已提交
2944 2945 2946 2947 2948 2949 2950 2951 2952
		else
		{
			const char *mapptr;
			int	from, to, pidx, paramlen;

			for (prtlen = 0, mapptr = mapExpr; *mapptr; mapptr++)
			{
				if (*mapptr != '$')
				{
2953
					CVT_APPEND_CHAR(qb, *mapptr);
H
Hiroshi Inoue 已提交
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
					continue;
				}
				mapptr++;
				if (*mapptr == '*')
				{
					from = 1;
					to = param_consumed - 2;
				}
				else if (isdigit(*mapptr))
				{
					pidx = *mapptr - '0' - 1;
					if (pidx < 0 ||
H
Hiroshi Inoue 已提交
2966
					    param_pos[pidx][0] < 0)
H
Hiroshi Inoue 已提交
2967
					{
2968 2969
						qb->errornumber = STMT_EXEC_ERROR;
						qb->errormsg = "param not found";
H
Hiroshi Inoue 已提交
2970
						qlog("%s %dth param not found for the expression %s\n", pidx + 1, mapExpr);
2971 2972
						retval = SQL_ERROR;
						break;
H
Hiroshi Inoue 已提交
2973 2974 2975 2976 2977 2978
					}
					from = param_pos[pidx][0];
					to = param_pos[pidx][1];
				}
				else
				{
2979 2980
					qb->errornumber = STMT_EXEC_ERROR;
					qb->errormsg = "internal expression error";
H
Hiroshi Inoue 已提交
2981
					qlog("%s internal expression error %s\n", func, mapExpr);
2982
					retval = SQL_ERROR;
H
Hiroshi Inoue 已提交
2983 2984
					break;
				}
2985
				paramlen = to - from + 1;
H
Hiroshi Inoue 已提交
2986
				if (paramlen > 0)
2987
					CVT_APPEND_DATA(qb, nqb.query_statement+ from, paramlen);
H
Hiroshi Inoue 已提交
2988 2989
			}
		}
2990
		if (0 == qb->errornumber)
H
Hiroshi Inoue 已提交
2991
		{
2992 2993
			qb->errornumber = nqb.errornumber;
			qb->errormsg = nqb.errormsg;
H
Hiroshi Inoue 已提交
2994
		}
2995
		if (SQL_ERROR != retval)
H
Hiroshi Inoue 已提交
2996
		{
2997 2998
			qb->param_number = nqb.param_number;
			qb->flags = nqb.flags;
H
Hiroshi Inoue 已提交
2999
		}
3000
		QB_Destructor(&nqb);
H
Hiroshi Inoue 已提交
3001
	}
3002
	else
H
Hiroshi Inoue 已提交
3003
	{
3004 3005
		/* Bogus key, leave untranslated */
		return SQL_ERROR;
H
Hiroshi Inoue 已提交
3006
	}
3007 3008
 
	return retval;
3009 3010
}

3011 3012
BOOL
convert_money(const char *s, char *sout, size_t soutmax)
3013
{
3014 3015
	size_t		i = 0,
				out = 0;
3016

3017
	for (i = 0; s[i]; i++)
B
Bruce Momjian 已提交
3018
	{
3019
		if (s[i] == '$' || s[i] == ',' || s[i] == ')')
B
Bruce Momjian 已提交
3020
			;					/* skip these characters */
3021
		else
3022 3023
		{
			if (out + 1 >= soutmax)
3024
				return FALSE;	/* sout is too short */
3025 3026 3027 3028 3029
			if (s[i] == '(')
				sout[out++] = '-';
			else
				sout[out++] = s[i];
		}
3030
	}
3031 3032
	sout[out] = '\0';
	return TRUE;
3033 3034 3035
}


3036 3037 3038 3039
/*
 *	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
 */
3040
char
3041
parse_datetime(const char *buf, SIMPLE_TIME *st)
3042
{
B
Bruce Momjian 已提交
3043 3044 3045 3046 3047 3048 3049 3050
	int			y,
				m,
				d,
				hh,
				mm,
				ss;
	int			nf;

3051
	y = m = d = hh = mm = ss = 0;
3052 3053
	st->fr = 0;
	st->infinity = 0;
3054

3055 3056 3057 3058 3059 3060 3061 3062
	/* escape sequence ? */
	if (buf[0] == '{')
	{
		while (*(++buf) && *buf != '\'');
		if (!(*buf))
			return FALSE;
		buf++;
	}
B
Bruce Momjian 已提交
3063 3064
	if (buf[4] == '-')			/* year first */
		nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss);
3065
	else
B
Bruce Momjian 已提交
3066
		nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss);
3067

B
Bruce Momjian 已提交
3068 3069
	if (nf == 5 || nf == 6)
	{
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
		st->y = y;
		st->m = m;
		st->d = d;
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

B
Bruce Momjian 已提交
3080
	if (buf[4] == '-')			/* year first */
3081 3082 3083 3084
		nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d);
	else
		nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y);

B
Bruce Momjian 已提交
3085 3086
	if (nf == 3)
	{
3087 3088 3089 3090 3091 3092 3093 3094
		st->y = y;
		st->m = m;
		st->d = d;

		return TRUE;
	}

	nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss);
B
Bruce Momjian 已提交
3095 3096
	if (nf == 2 || nf == 3)
	{
3097 3098 3099 3100 3101 3102 3103 3104 3105
		st->hh = hh;
		st->mm = mm;
		st->ss = ss;

		return TRUE;
	}

	return FALSE;
}
3106

3107

3108
/*	Change linefeed to carriage-return/linefeed */
3109
int
H
Hiroshi Inoue 已提交
3110
convert_linefeeds(const char *si, char *dst, size_t max, BOOL convlf, BOOL *changed)
3111
{
B
Bruce Momjian 已提交
3112 3113
	size_t		i = 0,
				out = 0;
3114

3115 3116 3117 3118
	if (max == 0)
		max = 0xffffffff;
	*changed = FALSE;
	for (i = 0; si[i] && out < max - 1; i++)
B
Bruce Momjian 已提交
3119
	{
H
Hiroshi Inoue 已提交
3120
		if (convlf && si[i] == '\n')
B
Bruce Momjian 已提交
3121 3122 3123 3124
		{
			/* Only add the carriage-return if needed */
			if (i > 0 && si[i - 1] == '\r')
			{
3125 3126 3127 3128
				if (dst)
					dst[out++] = si[i];
				else
					out++;
B
Byron Nikolaidis 已提交
3129 3130
				continue;
			}
3131
			*changed = TRUE;
B
Byron Nikolaidis 已提交
3132

3133 3134 3135 3136 3137 3138 3139
			if (dst)
			{
				dst[out++] = '\r';
				dst[out++] = '\n';
			}
			else
				out += 2;
3140 3141
		}
		else
3142 3143 3144 3145 3146 3147
		{
			if (dst)
				dst[out++] = si[i];
			else
				out++;
		}
3148
	}
3149 3150
	if (dst)
		dst[out] = '\0';
3151
	return out;
3152 3153
}

3154 3155 3156 3157 3158

/*
 *	Change carriage-return/linefeed to just linefeed
 *	Plus, escape any special characters.
 */
3159
int
H
Hiroshi Inoue 已提交
3160
convert_special_chars(const char *si, char *dst, int used, BOOL convlf, int ccsc)
3161
{
B
Bruce Momjian 已提交
3162 3163 3164
	size_t		i = 0,
				out = 0,
				max;
3165
	char	   *p = NULL;
H
Hiroshi Inoue 已提交
3166 3167 3168
#ifdef MULTIBYTE
	encoded_str	encstr;
#endif
3169 3170 3171 3172 3173 3174


	if (used == SQL_NTS)
		max = strlen(si);
	else
		max = used;
3175 3176 3177 3178 3179
	if (dst)
	{
		p = dst;
		p[0] = '\0';
	}
H
Hiroshi Inoue 已提交
3180
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
3181
	encoded_str_constr(&encstr, ccsc, si);
H
Hiroshi Inoue 已提交
3182
#endif
3183

H
Hiroshi Inoue 已提交
3184
	for (i = 0; i < max && si[i]; i++)
B
Bruce Momjian 已提交
3185
	{
3186
#ifdef MULTIBYTE
H
Hiroshi Inoue 已提交
3187 3188
		encoded_nextchar(&encstr);
		if (ENCODE_STATUS(encstr) != 0)
3189 3190 3191 3192 3193 3194 3195
		{
			if (p)
				p[out] = si[i];
			out++;
			continue;
		}
#endif
H
Hiroshi Inoue 已提交
3196
		if (convlf && si[i] == '\r' && si[i + 1] == '\n')
3197
			continue;
B
Byron Nikolaidis 已提交
3198
		else if (si[i] == '\'' || si[i] == '\\')
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
		{
			if (p)
				p[out++] = '\\';
			else
				out++;
		}
		if (p)
			p[out++] = si[i];
		else
			out++;
3209
	}
3210 3211 3212
	if (p)
		p[out] = '\0';
	return out;
3213 3214
}

3215

3216 3217
/*	!!! Need to implement this function !!!  */
int
3218
convert_pgbinary_to_char(const char *value, char *rgbValue, int cbValueMax)
3219
{
3220 3221 3222
	mylog("convert_pgbinary_to_char: value = '%s'\n", value);

	strncpy_null(rgbValue, value, cbValueMax);
3223 3224 3225
	return 0;
}

3226

3227
static unsigned int
3228
conv_from_octal(const unsigned char *s)
3229
{
B
Bruce Momjian 已提交
3230 3231
	int			i,
				y = 0;
3232

B
Bruce Momjian 已提交
3233
	for (i = 1; i <= 3; i++)
3234
		y += (s[i] - '0') << (3 * (3 - i));
3235 3236

	return y;
3237

3238 3239
}

3240

3241
static unsigned int
3242
conv_from_hex(const unsigned char *s)
B
Byron Nikolaidis 已提交
3243
{
B
Bruce Momjian 已提交
3244 3245 3246
	int			i,
				y = 0,
				val;
3247

B
Bruce Momjian 已提交
3248 3249 3250 3251 3252 3253 3254 3255
	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 已提交
3256

3257
		y += val << (4 * (2 - i));
B
Byron Nikolaidis 已提交
3258 3259 3260 3261 3262
	}

	return y;
}

3263

B
Bruce Momjian 已提交
3264
/*	convert octal escapes to bytes */
3265
int
3266
convert_from_pgbinary(const unsigned char *value, unsigned char *rgbValue, int cbValueMax)
3267
{
3268 3269
	size_t		i,
				ilen = strlen(value);
B
Bruce Momjian 已提交
3270
	int			o = 0;
3271

B
Bruce Momjian 已提交
3272

3273
	for (i = 0; i < ilen;)
B
Bruce Momjian 已提交
3274 3275 3276
	{
		if (value[i] == '\\')
		{
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
			if (value[i + 1] == '\\')
			{
				rgbValue[o] = value[i];
				i += 2;
			}
			else
			{
				rgbValue[o] = conv_from_octal(&value[i]);
				i += 4;
			}
3287
		}
B
Bruce Momjian 已提交
3288
		else
3289 3290 3291 3292
			rgbValue[o] = value[i++];
		mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]);
		o++;
	}
3293

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

3296 3297 3298 3299
	return o;
}


3300
static char *
3301 3302
conv_to_octal(unsigned char val)
{
B
Bruce Momjian 已提交
3303 3304
	int			i;
	static char x[6];
3305 3306 3307 3308 3309

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

B
Bruce Momjian 已提交
3310 3311
	for (i = 4; i > 1; i--)
	{
3312
		x[i] = (val & 7) + '0';
3313 3314 3315 3316 3317 3318
		val >>= 3;
	}

	return x;
}

3319

B
Bruce Momjian 已提交
3320
/*	convert non-ascii bytes to octal escape sequences */
3321
int
3322
convert_to_pgbinary(const unsigned char *in, char *out, int len)
3323
{
B
Bruce Momjian 已提交
3324 3325
	int			i,
				o = 0;
3326

B
Bruce Momjian 已提交
3327 3328
	for (i = 0; i < len; i++)
	{
3329
		mylog("convert_to_pgbinary: in[%d] = %d, %c\n", i, in[i], in[i]);
B
Bruce Momjian 已提交
3330
		if (isalnum(in[i]) || in[i] == ' ')
3331
			out[o++] = in[i];
B
Bruce Momjian 已提交
3332 3333 3334
		else
		{
			strcpy(&out[o], conv_to_octal(in[i]));
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
			o += 5;
		}
	}

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

	return o;
}


B
Byron Nikolaidis 已提交
3345
void
3346
encode(const char *in, char *out)
B
Byron Nikolaidis 已提交
3347
{
3348 3349
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
3350
				o = 0;
B
Byron Nikolaidis 已提交
3351

3352
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
3353 3354 3355
	{
		if (in[i] == '+')
		{
B
Byron Nikolaidis 已提交
3356 3357 3358
			sprintf(&out[o], "%%2B");
			o += 3;
		}
B
Bruce Momjian 已提交
3359
		else if (isspace((unsigned char) in[i]))
B
Byron Nikolaidis 已提交
3360
			out[o++] = '+';
B
Bruce Momjian 已提交
3361 3362
		else if (!isalnum((unsigned char) in[i]))
		{
3363
			sprintf(&out[o], "%%%02x", (unsigned char) in[i]);
B
Byron Nikolaidis 已提交
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373
			o += 3;
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}


void
3374
decode(const char *in, char *out)
B
Byron Nikolaidis 已提交
3375
{
3376 3377
	unsigned int i,
				ilen = strlen(in),
B
Bruce Momjian 已提交
3378
				o = 0;
B
Byron Nikolaidis 已提交
3379

3380
	for (i = 0; i < ilen; i++)
B
Bruce Momjian 已提交
3381
	{
B
Byron Nikolaidis 已提交
3382 3383
		if (in[i] == '+')
			out[o++] = ' ';
B
Bruce Momjian 已提交
3384 3385
		else if (in[i] == '%')
		{
B
Byron Nikolaidis 已提交
3386
			sprintf(&out[o++], "%c", conv_from_hex(&in[i]));
B
Bruce Momjian 已提交
3387
			i += 2;
B
Byron Nikolaidis 已提交
3388 3389 3390 3391 3392 3393 3394
		}
		else
			out[o++] = in[i];
	}
	out[o++] = '\0';
}

3395 3396 3397 3398
static const char *hextbl = "0123456789ABCDEF";
static int
pg_bin2hex(UCHAR *src, UCHAR *dst, int length)
{
3399 3400 3401 3402 3403 3404
	UCHAR		chr,
			   *src_wk,
			   *dst_wk;
	BOOL		backwards;
	int			i;

3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
	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;
}
3434

3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
/*-------
 *	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.
 *-------
 */
3451
int
3452 3453
convert_lo(StatementClass *stmt, const void *value, Int2 fCType, PTR rgbValue,
		   SDWORD cbValueMax, SDWORD *pcbValue)
3454
{
B
Bruce Momjian 已提交
3455 3456 3457 3458
	Oid			oid;
	int			retval,
				result,
				left = -1;
T
Tom Lane 已提交
3459
	BindInfoClass *bindInfo = NULL;
3460 3461
	ConnectionClass *conn = SC_get_conn(stmt);
	ConnInfo   *ci = &(conn->connInfo);
H
Hiroshi Inoue 已提交
3462
	ARDFields	*opts = SC_get_ARD(stmt);
3463
	int			factor = (fCType == SQL_C_CHAR ? 2 : 1);
3464

3465
	/* If using SQLGetData, then current_col will be set */
B
Bruce Momjian 已提交
3466 3467
	if (stmt->current_col >= 0)
	{
H
Hiroshi Inoue 已提交
3468
		bindInfo = &opts->bindings[stmt->current_col];
3469 3470
		left = bindInfo->data_left;
	}
3471

B
Bruce Momjian 已提交
3472 3473 3474 3475
	/*
	 * if this is the first call for this column, open the large object
	 * for reading
	 */
3476

B
Bruce Momjian 已提交
3477 3478
	if (!bindInfo || bindInfo->data_left == -1)
	{
B
Byron Nikolaidis 已提交
3479
		/* begin transaction if needed */
3480
		if (!CC_is_in_trans(conn))
B
Bruce Momjian 已提交
3481
		{
H
Hiroshi Inoue 已提交
3482
			if (!CC_begin(conn))
B
Bruce Momjian 已提交
3483
			{
B
Byron Nikolaidis 已提交
3484 3485 3486 3487 3488 3489
				stmt->errormsg = "Could not begin (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

3490
		oid = atoi(value);
3491
		stmt->lobj_fd = lo_open(conn, oid, INV_READ);
B
Bruce Momjian 已提交
3492 3493
		if (stmt->lobj_fd < 0)
		{
3494
			stmt->errornumber = STMT_EXEC_ERROR;
3495
			stmt->errormsg = "Couldnt open large object for reading.";
3496 3497
			return COPY_GENERAL_ERROR;
		}
3498

B
Bruce Momjian 已提交
3499
		/* Get the size */
3500
		retval = lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END);
B
Bruce Momjian 已提交
3501 3502
		if (retval >= 0)
		{
3503
			left = lo_tell(conn, stmt->lobj_fd);
3504 3505 3506
			if (bindInfo)
				bindInfo->data_left = left;

B
Bruce Momjian 已提交
3507
			/* return to beginning */
3508
			lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET);
3509 3510
		}
	}
3511
	mylog("lo data left = %d\n", left);
3512

B
Bruce Momjian 已提交
3513
	if (left == 0)
3514
		return COPY_NO_DATA_FOUND;
3515

B
Bruce Momjian 已提交
3516 3517
	if (stmt->lobj_fd < 0)
	{
3518 3519 3520 3521
		stmt->errornumber = STMT_EXEC_ERROR;
		stmt->errormsg = "Large object FD undefined for multiple read.";
		return COPY_GENERAL_ERROR;
	}
3522

3523
	retval = lo_read(conn, stmt->lobj_fd, (char *) rgbValue, factor > 1 ? (cbValueMax - 1) / factor : cbValueMax);
B
Bruce Momjian 已提交
3524 3525
	if (retval < 0)
	{
3526
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3527 3528

		/* commit transaction if needed */
3529
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3530
		{
H
Hiroshi Inoue 已提交
3531
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3532
			{
B
Byron Nikolaidis 已提交
3533 3534 3535 3536 3537 3538
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

3539 3540 3541 3542 3543 3544 3545
		stmt->lobj_fd = -1;

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

3546 3547
	if (factor > 1)
		pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval);
3548 3549 3550 3551 3552 3553
	if (retval < left)
		result = COPY_RESULT_TRUNCATED;
	else
		result = COPY_OK;

	if (pcbValue)
3554
		*pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor;
3555

B
Bruce Momjian 已提交
3556
	if (bindInfo && bindInfo->data_left > 0)
3557
		bindInfo->data_left -= retval;
3558

B
Bruce Momjian 已提交
3559 3560
	if (!bindInfo || bindInfo->data_left == 0)
	{
3561
		lo_close(conn, stmt->lobj_fd);
B
Byron Nikolaidis 已提交
3562 3563

		/* commit transaction if needed */
3564
		if (!ci->drivers.use_declarefetch && CC_is_in_autocommit(conn))
B
Bruce Momjian 已提交
3565
		{
H
Hiroshi Inoue 已提交
3566
			if (!CC_commit(conn))
B
Bruce Momjian 已提交
3567
			{
B
Byron Nikolaidis 已提交
3568 3569 3570 3571 3572 3573
				stmt->errormsg = "Could not commit (in-line) a transaction";
				stmt->errornumber = STMT_EXEC_ERROR;
				return COPY_GENERAL_ERROR;
			}
		}

B
Bruce Momjian 已提交
3574
		stmt->lobj_fd = -1;		/* prevent further reading */
3575
	}
3576 3577

	return result;
3578
}