statement.c 25.7 KB
Newer Older
1 2
/*-------
 * Module:			statement.c
3
 *
4 5
 * Description:		This module contains functions related to creating
 *					and manipulating a statement.
6
 *
7
 * Classes:			StatementClass (Functions prefix: "SC_")
8
 *
9
 * API functions:	SQLAllocStmt, SQLFreeStmt
10
 *
11
 * Comments:		See "notice.txt" for copyright and license information.
12
 *-------
13
 */
14

Byron Nikolaidis's avatar
Byron Nikolaidis committed
15
#ifdef HAVE_CONFIG_H
16
#include "config.h"
Byron Nikolaidis's avatar
Byron Nikolaidis committed
17 18
#endif

19 20 21 22 23 24
#include "statement.h"
#include "bind.h"
#include "connection.h"
#include "qresult.h"
#include "convert.h"
#include "environ.h"
25

26
#include <stdio.h>
Byron Nikolaidis's avatar
Byron Nikolaidis committed
27
#include <string.h>
28
#include <ctype.h>
29

30
#ifndef WIN32
Byron Nikolaidis's avatar
Byron Nikolaidis committed
31 32 33
#include "iodbc.h"
#include "isql.h"
#else
34 35
#include <windows.h>
#include <sql.h>
Byron Nikolaidis's avatar
Byron Nikolaidis committed
36
#endif
37

38 39
extern GLOBAL_VALUES globals;

40 41
#ifndef WIN32
#ifndef HAVE_STRICMP
42
#define stricmp(s1,s2)		strcasecmp(s1,s2)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
43 44 45
#define strnicmp(s1,s2,n)	strncasecmp(s1,s2,n)
#endif
#endif
46
#define PRN_NULLCHECK
Byron Nikolaidis's avatar
Byron Nikolaidis committed
47

48

49
/*	Map sql commands to statement types */
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
static struct
{
	int			type;
	char	   *s;
}			Statement_Type[] =

{
	{
		STMT_TYPE_SELECT, "SELECT"
	},
	{
		STMT_TYPE_INSERT, "INSERT"
	},
	{
		STMT_TYPE_UPDATE, "UPDATE"
	},
	{
		STMT_TYPE_DELETE, "DELETE"
	},
	{
		STMT_TYPE_CREATE, "CREATE"
	},
	{
		STMT_TYPE_ALTER, "ALTER"
	},
	{
		STMT_TYPE_DROP, "DROP"
	},
	{
		STMT_TYPE_GRANT, "GRANT"
	},
	{
		STMT_TYPE_REVOKE, "REVOKE"
	},
	{
		0, NULL
	}
87 88
};

89

90 91 92
RETCODE SQL_API
SQLAllocStmt(HDBC hdbc,
			 HSTMT FAR *phstmt)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
93
{
94 95 96
	static char *func = "SQLAllocStmt";
	ConnectionClass *conn = (ConnectionClass *) hdbc;
	StatementClass *stmt;
97

98 99
	mylog("%s: entering...\n", func);

100 101
	if (!conn)
	{
Byron Nikolaidis's avatar
Byron Nikolaidis committed
102
		CC_log_error(func, "", NULL);
103
		return SQL_INVALID_HANDLE;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
104
	}
105 106 107 108 109

	stmt = SC_Constructor();

	mylog("**** SQLAllocStmt: hdbc = %u, stmt = %u\n", hdbc, stmt);

110 111
	if (!stmt)
	{
112 113 114
		conn->errornumber = CONN_STMT_ALLOC_ERROR;
		conn->errormsg = "No more memory to allocate a further SQL-statement";
		*phstmt = SQL_NULL_HSTMT;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
115
		CC_log_error(func, "", conn);
116 117 118
		return SQL_ERROR;
	}

119 120 121 122
	if (!CC_add_statement(conn, stmt))
	{
		conn->errormsg = "Maximum number of connections exceeded.";
		conn->errornumber = CONN_STMT_ALLOC_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
123
		CC_log_error(func, "", conn);
124
		SC_Destructor(stmt);
125
		*phstmt = SQL_NULL_HSTMT;
126 127
		return SQL_ERROR;
	}
128 129 130

	*phstmt = (HSTMT) stmt;

131
	/* Copy default statement options based from Connection options */
132 133
	stmt->options = conn->stmtOptions;

134
	stmt->stmt_size_limit = CC_get_max_query_len(conn);
135
	/* Save the handle for later */
136 137
	stmt->phstmt = phstmt;

138
	return SQL_SUCCESS;
139 140 141
}


142 143 144
RETCODE SQL_API
SQLFreeStmt(HSTMT hstmt,
			UWORD fOption)
145
{
146 147
	static char *func = "SQLFreeStmt";
	StatementClass *stmt = (StatementClass *) hstmt;
148

149
	mylog("%s: entering...hstmt=%u, fOption=%d\n", func, hstmt, fOption);
150

151 152
	if (!stmt)
	{
Byron Nikolaidis's avatar
Byron Nikolaidis committed
153
		SC_log_error(func, "", NULL);
154
		return SQL_INVALID_HANDLE;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
155
	}
156

157 158
	if (fOption == SQL_DROP)
	{
159 160 161
		ConnectionClass *conn = stmt->hdbc;

		/* Remove the statement from the connection's statement list */
162 163 164 165
		if (conn)
		{
			if (!CC_remove_statement(conn, stmt))
			{
166 167
				stmt->errornumber = STMT_SEQUENCE_ERROR;
				stmt->errormsg = "Statement is currently executing a transaction.";
Byron Nikolaidis's avatar
Byron Nikolaidis committed
168
				SC_log_error(func, "", stmt);
169 170
				return SQL_ERROR;		/* stmt may be executing a
										 * transaction */
171 172
			}

173 174 175
			/* Free any cursors and discard any result info */
			if (stmt->result)
			{
176 177 178 179 180 181 182
				QR_Destructor(stmt->result);
				stmt->result = NULL;
			}
		}

		/* Destroy the statement and free any results, cursors, etc. */
		SC_Destructor(stmt);
183 184
	}
	else if (fOption == SQL_UNBIND)
185
		SC_unbind_cols(stmt);
186 187
	else if (fOption == SQL_CLOSE)
	{
188

189 190 191 192
		/*
		 * this should discard all the results, but leave the statement
		 * itself in place (it can be executed again)
		 */
193 194 195
		if (!SC_recycle_statement(stmt))
		{
			/* errormsg passed in above */
Byron Nikolaidis's avatar
Byron Nikolaidis committed
196
			SC_log_error(func, "", stmt);
197
			return SQL_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
198
		}
199 200
	}
	else if (fOption == SQL_RESET_PARAMS)
201
		SC_free_params(stmt, STMT_FREE_PARAMS_ALL);
202 203 204 205
	else
	{
		stmt->errormsg = "Invalid option passed to SQLFreeStmt.";
		stmt->errornumber = STMT_OPTION_OUT_OF_RANGE_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
206
		SC_log_error(func, "", stmt);
207 208
		return SQL_ERROR;
	}
209

210
	return SQL_SUCCESS;
211 212 213
}


214
/*
215 216
 * StatementClass implementation
 */
217
void
Bruce Momjian's avatar
Bruce Momjian committed
218
InitializeStatementOptions(StatementOptions *opt)
219
{
220 221
	opt->maxRows = 0;			/* driver returns all rows */
	opt->maxLength = 0;			/* driver returns all data for char/binary */
222
	opt->rowset_size = 1;
223
	opt->keyset_size = 0;		/* fully keyset driven is the default */
224 225 226 227
	opt->scroll_concurrency = SQL_CONCUR_READ_ONLY;
	opt->cursor_type = SQL_CURSOR_FORWARD_ONLY;
	opt->bind_size = 0;			/* default is to bind by column */
	opt->retrieve_data = SQL_RD_ON;
228
	opt->use_bookmarks = SQL_UB_OFF;
229
}
230

231

232
StatementClass *
233
SC_Constructor(void)
234
{
235
	StatementClass *rv;
236 237

	rv = (StatementClass *) malloc(sizeof(StatementClass));
238 239 240
	if (rv)
	{
		rv->hdbc = NULL;		/* no connection associated yet */
241
		rv->phstmt = NULL;
242 243 244 245
		rv->result = NULL;
		rv->manual_result = FALSE;
		rv->prepare = FALSE;
		rv->status = STMT_ALLOCATED;
246 247
		rv->internal = FALSE;

248 249 250
		rv->errormsg = NULL;
		rv->errornumber = 0;
		rv->errormsg_created = FALSE;
251
		rv->errormsg_malloced = FALSE;
252

253
		rv->statement = NULL;
254 255
		rv->stmt_with_params = NULL;
		rv->stmt_size_limit = -1;
256
		rv->statement_type = STMT_TYPE_UNKNOWN;
257

258 259
		rv->bindings = NULL;
		rv->bindings_allocated = 0;
260

261 262 263
		rv->bookmark.buffer = NULL;
		rv->bookmark.used = NULL;

264 265
		rv->parameters_allocated = 0;
		rv->parameters = 0;
266

267
		rv->currTuple = -1;
268
		rv->rowset_start = -1;
269
		rv->current_col = -1;
270 271 272 273
		rv->bind_row = 0;
		rv->last_fetch_count = 0;
		rv->save_rowset_size = -1;

274 275 276
		rv->data_at_exec = -1;
		rv->current_exec_param = -1;
		rv->put_data = FALSE;
277

278 279
		rv->lobj_fd = -1;
		rv->cursor_name[0] = '\0';
Byron Nikolaidis's avatar
Byron Nikolaidis committed
280

281
		/* Parse Stuff */
Byron Nikolaidis's avatar
Byron Nikolaidis committed
282 283 284 285 286
		rv->ti = NULL;
		rv->fi = NULL;
		rv->ntab = 0;
		rv->nfld = 0;
		rv->parse_status = STMT_PARSE_NONE;
287

288
		/* Clear Statement Options -- defaults will be set in AllocStmt */
289
		memset(&rv->options, 0, sizeof(StatementOptions));
290 291 292

		rv->pre_executing = FALSE;
		rv->inaccurate_result = FALSE;
293 294 295 296
	}
	return rv;
}

297

298
char
Bruce Momjian's avatar
Bruce Momjian committed
299
SC_Destructor(StatementClass *self)
300 301
{
	mylog("SC_Destructor: self=%u, self->result=%u, self->hdbc=%u\n", self, self->result, self->hdbc);
302 303
	if (STMT_EXECUTING == self->status)
	{
304 305 306 307 308
		self->errornumber = STMT_SEQUENCE_ERROR;
		self->errormsg = "Statement is currently executing a transaction.";
		return FALSE;
	}

309 310 311 312
	if (self->result)
	{
		if (!self->hdbc)
			self->result->conn = NULL;	/* prevent any dbase activity */
313 314 315 316 317 318

		QR_Destructor(self->result);
	}

	if (self->statement)
		free(self->statement);
319 320 321 322 323
	if (self->stmt_with_params)
	{
		free(self->stmt_with_params);
		self->stmt_with_params = NULL;
	}
324 325 326

	SC_free_params(self, STMT_FREE_PARAMS_ALL);

327 328
	/*
	 * the memory pointed to by the bindings is not deallocated by the
329 330
	 * driver but by the application that uses that driver, so we don't
	 * have to care
331
	 */
332 333 334 335
	/* about that here. */
	if (self->bindings)
		free(self->bindings);

336 337 338 339 340 341
	/* Free the parsed table information */
	if (self->ti)
	{
		int			i;

		for (i = 0; i < self->ntab; i++)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
342 343 344 345 346
			free(self->ti[i]);

		free(self->ti);
	}

347 348 349 350 351 352
	/* Free the parsed field information */
	if (self->fi)
	{
		int			i;

		for (i = 0; i < self->nfld; i++)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
353 354 355 356
			free(self->fi[i]);
		free(self->fi);
	}

357 358
	free(self);

359 360
	mylog("SC_Destructor: EXIT\n");

361 362 363
	return TRUE;
}

364 365 366 367 368

/*
 *	Free parameters and free the memory from the
 *	data-at-execution parameters that was allocated in SQLPutData.
 */
369
void
Bruce Momjian's avatar
Bruce Momjian committed
370
SC_free_params(StatementClass *self, char option)
371
{
372
	int			i;
373 374 375

	mylog("SC_free_params:  ENTER, self=%d\n", self);

376
	if (!self->parameters)
377 378
		return;

379 380 381 382 383 384
	for (i = 0; i < self->parameters_allocated; i++)
	{
		if (self->parameters[i].data_at_exec == TRUE)
		{
			if (self->parameters[i].EXEC_used)
			{
385 386 387 388
				free(self->parameters[i].EXEC_used);
				self->parameters[i].EXEC_used = NULL;
			}

389 390
			if (self->parameters[i].EXEC_buffer)
			{
391 392
				if (self->parameters[i].SQLType != SQL_LONGVARBINARY)
					free(self->parameters[i].EXEC_buffer);
393 394 395 396 397 398 399 400
				self->parameters[i].EXEC_buffer = NULL;
			}
		}
	}
	self->data_at_exec = -1;
	self->current_exec_param = -1;
	self->put_data = FALSE;

401 402
	if (option == STMT_FREE_PARAMS_ALL)
	{
403 404 405 406
		free(self->parameters);
		self->parameters = NULL;
		self->parameters_allocated = 0;
	}
407

408 409
	mylog("SC_free_params:  EXIT\n");
}
410 411


412
int
413 414
statement_type(char *statement)
{
415
	int			i;
416

417 418 419 420
	/* ignore leading whitespace in query string */
	while (*statement && isspace((unsigned char) *statement))
		statement++;

421
	for (i = 0; Statement_Type[i].s; i++)
422
		if (!strnicmp(statement, Statement_Type[i].s, strlen(Statement_Type[i].s)))
423 424 425
			return Statement_Type[i].type;

	return STMT_TYPE_OTHER;
426 427
}

Byron Nikolaidis's avatar
Byron Nikolaidis committed
428

429 430 431 432
/*
 *	Called from SQLPrepare if STMT_PREMATURE, or
 *	from SQLExecute if STMT_FINISHED, or
 *	from SQLFreeStmt(SQL_CLOSE)
433
 */
434
char
Bruce Momjian's avatar
Bruce Momjian committed
435
SC_recycle_statement(StatementClass *self)
436
{
437
	ConnectionClass *conn;
438

439
	mylog("recycle statement: self= %u\n", self);
440

441 442 443
	/* This would not happen */
	if (self->status == STMT_EXECUTING)
	{
444 445 446 447 448 449 450 451 452
		self->errornumber = STMT_SEQUENCE_ERROR;
		self->errormsg = "Statement is currently executing a transaction.";
		return FALSE;
	}

	self->errormsg = NULL;
	self->errornumber = 0;
	self->errormsg_created = FALSE;

453 454 455 456 457
	switch (self->status)
	{
		case STMT_ALLOCATED:
			/* this statement does not need to be recycled */
			return TRUE;
458

459 460
		case STMT_READY:
			break;
461

462
		case STMT_PREMATURE:
463

464 465 466 467 468 469 470 471 472
			/*
			 * Premature execution of the statement might have caused the
			 * start of a transaction. If so, we have to rollback that
			 * transaction.
			 */
			conn = SC_get_conn(self);
			if (!CC_is_in_autocommit(conn) && CC_is_in_trans(conn))
			{
				QResultClass *res = CC_send_query(conn, "ABORT", NULL);
473

474 475 476 477 478 479 480 481 482 483 484 485
				QR_Destructor(res);
				CC_set_no_trans(conn);
			}
			break;

		case STMT_FINISHED:
			break;

		default:
			self->errormsg = "An internal error occured while recycling statements";
			self->errornumber = STMT_INTERNAL_ERROR;
			return FALSE;
486
	}
487

488 489 490 491 492 493
	/* Free the parsed table information */
	if (self->ti)
	{
		int			i;

		for (i = 0; i < self->ntab; i++)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
494 495 496 497 498 499 500
			free(self->ti[i]);

		free(self->ti);
		self->ti = NULL;
		self->ntab = 0;
	}

501 502 503 504 505 506
	/* Free the parsed field information */
	if (self->fi)
	{
		int			i;

		for (i = 0; i < self->nfld; i++)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
507 508 509 510 511 512
			free(self->fi[i]);
		free(self->fi);
		self->fi = NULL;
		self->nfld = 0;
	}
	self->parse_status = STMT_PARSE_NONE;
513

514 515 516
	/* Free any cursors */
	if (self->result)
	{
517 518 519
		QR_Destructor(self->result);
		self->result = NULL;
	}
520
	self->inaccurate_result = FALSE;
521

522 523 524
	/*
	 * Reset only parameters that have anything to do with results
	 */
525
	self->status = STMT_READY;
526
	self->manual_result = FALSE;/* very important */
527

528
	self->currTuple = -1;
529
	self->rowset_start = -1;
530
	self->current_col = -1;
531 532
	self->bind_row = 0;
	self->last_fetch_count = 0;
533

534 535
	if (self->errormsg_malloced && self->errormsg)
		free(self->errormsg);
536 537 538
	self->errormsg = NULL;
	self->errornumber = 0;
	self->errormsg_created = FALSE;
539
	self->errormsg_malloced = FALSE;
540 541 542

	self->lobj_fd = -1;

543 544
	/*
	 * Free any data at exec params before the statement is executed
545 546
	 * again.  If not, then there will be a memory leak when the next
	 * SQLParamData/SQLPutData is called.
547
	 */
548
	SC_free_params(self, STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY);
549 550 551 552

	return TRUE;
}

553

554
/* Pre-execute a statement (SQLPrepare/SQLDescribeCol) */
555
void
Bruce Momjian's avatar
Bruce Momjian committed
556
SC_pre_execute(StatementClass *self)
557 558 559
{
	mylog("SC_pre_execute: status = %d\n", self->status);

560 561
	if (self->status == STMT_READY)
	{
562 563
		mylog("              preprocess: status = READY\n");

564 565
		if (self->statement_type == STMT_TYPE_SELECT)
		{
566 567
			char		old_pre_executing = self->pre_executing;

568 569 570 571
			self->pre_executing = TRUE;
			self->inaccurate_result = FALSE;

			SQLExecute(self);
572

573 574 575 576 577 578 579 580 581
			self->pre_executing = old_pre_executing;

			if (self->status == STMT_FINISHED)
			{
				mylog("              preprocess: after status = FINISHED, so set PREMATURE\n");
				self->status = STMT_PREMATURE;
			}
		}
		else
582
		{
583 584 585
			self->result = QR_Constructor();
			QR_set_status(self->result, PGRES_TUPLES_OK);
			self->inaccurate_result = TRUE;
586 587
			self->status = STMT_PREMATURE;
		}
588
	}
589 590
}

591

592
/* This is only called from SQLFreeStmt(SQL_UNBIND) */
593
char
Bruce Momjian's avatar
Bruce Momjian committed
594
SC_unbind_cols(StatementClass *self)
595
{
596
	Int2		lf;
597

598 599
	for (lf = 0; lf < self->bindings_allocated; lf++)
	{
600
		self->bindings[lf].data_left = -1;
601 602 603 604 605 606
		self->bindings[lf].buflen = 0;
		self->bindings[lf].buffer = NULL;
		self->bindings[lf].used = NULL;
		self->bindings[lf].returntype = SQL_C_CHAR;
	}

607 608 609
	self->bookmark.buffer = NULL;
	self->bookmark.used = NULL;

610
	return 1;
611 612
}

613

614
void
Bruce Momjian's avatar
Bruce Momjian committed
615
SC_clear_error(StatementClass *self)
616
{
617 618
	if (self->errormsg_malloced && self->errormsg)
		free(self->errormsg);
619 620 621
	self->errornumber = 0;
	self->errormsg = NULL;
	self->errormsg_created = FALSE;
622
	self->errormsg_malloced = FALSE;
623 624 625
}


626 627 628 629
/*
 *	This function creates an error msg which is the concatenation
 *	of the result, statement, connection, and socket messages.
 */
630
char *
Bruce Momjian's avatar
Bruce Momjian committed
631
SC_create_errormsg(StatementClass *self)
632
{
633 634 635 636
	QResultClass *res = self->result;
	ConnectionClass *conn = self->hdbc;
	int			pos;
	static char msg[4096];
637 638 639 640 641 642 643 644 645

	msg[0] = '\0';

	if (res && res->message)
		strcpy(msg, res->message);

	else if (self->errormsg)
		strcpy(msg, self->errormsg);

646 647
	if (conn)
	{
648 649
		SocketClass *sock = conn->sock;

650 651
		if (conn->errormsg && conn->errormsg[0] != '\0')
		{
652 653 654 655
			pos = strlen(msg);
			sprintf(&msg[pos], ";\n%s", conn->errormsg);
		}

656 657
		if (sock && sock->errormsg && sock->errormsg[0] != '\0')
		{
658 659 660 661
			pos = strlen(msg);
			sprintf(&msg[pos], ";\n%s", sock->errormsg);
		}
	}
662 663
	if (!msg[0] && res && QR_get_notice(res))
		return QR_get_notice(res);
664 665 666 667

	return msg;
}

668

669
char
Bruce Momjian's avatar
Bruce Momjian committed
670
SC_get_error(StatementClass *self, int *number, char **message)
671
{
672
	char		rv;
673

674
	/* Create a very informative errormsg if it hasn't been done yet. */
675 676
	if (!self->errormsg_created)
	{
677 678 679 680
		self->errormsg = SC_create_errormsg(self);
		self->errormsg_created = TRUE;
	}

681 682
	if (self->errornumber)
	{
683 684
		*number = self->errornumber;
		*message = self->errormsg;
685 686
		if (!self->errormsg_malloced)
			self->errormsg = NULL;
687 688 689 690 691 692 693 694
	}

	rv = (self->errornumber != 0);
	self->errornumber = 0;

	return rv;
}

695 696 697 698 699 700

/*
 *	Currently, the driver offers very simple bookmark support -- it is
 *	just the current row number.  But it could be more sophisticated
 *	someday, such as mapping a key to a 32 bit value
 */
701
unsigned long
Bruce Momjian's avatar
Bruce Momjian committed
702
SC_get_bookmark(StatementClass *self)
703
{
704
	return (self->currTuple + 1);
705
}
706

707

708
RETCODE
Bruce Momjian's avatar
Bruce Momjian committed
709
SC_fetch(StatementClass *self)
710
{
711 712 713 714 715 716 717 718 719 720
	static char *func = "SC_fetch";
	QResultClass *res = self->result;
	int			retval,
				result;
	Int2		num_cols,
				lf;
	Oid			type;
	char	   *value;
	ColumnInfoClass *ci;

721
	/* TupleField *tupleField; */
722 723

	self->last_fetch_count = 0;
724
	ci = QR_get_fields(res);	/* the column info */
725 726

	mylog("manual_result = %d, use_declarefetch = %d\n", self->manual_result, globals.use_declarefetch);
727

728 729 730 731 732
	if (self->manual_result || !globals.use_declarefetch)
	{
		if (self->currTuple >= QR_get_num_tuples(res) - 1 ||
			(self->options.maxRows > 0 && self->currTuple == self->options.maxRows - 1))
		{
733

734 735 736 737
			/*
			 * if at the end of the tuples, return "no data found" and set
			 * the cursor past the end of the result set
			 */
738
			self->currTuple = QR_get_num_tuples(res);
739 740
			return SQL_NO_DATA_FOUND;
		}
741

742 743 744
		mylog("**** SQLFetch: manual_result\n");
		(self->currTuple)++;
	}
745 746
	else
	{
747
		/* read from the cache or the physical next tuple */
748
		retval = QR_next_tuple(res);
749 750
		if (retval < 0)
		{
751 752 753 754
			mylog("**** SQLFetch: end_tuples\n");
			return SQL_NO_DATA_FOUND;
		}
		else if (retval > 0)
755 756 757
			(self->currTuple)++;/* all is well */
		else
		{
758 759 760 761 762 763 764 765 766 767 768 769 770
			mylog("SQLFetch: error\n");
			self->errornumber = STMT_EXEC_ERROR;
			self->errormsg = "Error fetching next row";
			SC_log_error(func, "", self);
			return SQL_ERROR;
		}
	}

	num_cols = QR_NumResultCols(res);

	result = SQL_SUCCESS;
	self->last_fetch_count = 1;

771 772 773 774 775 776 777 778 779
	/*
	 * If the bookmark column was bound then return a bookmark. Since this
	 * is used with SQLExtendedFetch, and the rowset size may be greater
	 * than 1, and an application can use row or column wise binding, use
	 * the code in copy_and_convert_field() to handle that.
	 */
	if (self->bookmark.buffer)
	{
		char		buf[32];
780 781

		sprintf(buf, "%ld", SC_get_bookmark(self));
782
		result = copy_and_convert_field(self, 0, buf,
783
			 SQL_C_ULONG, self->bookmark.buffer, 0, self->bookmark.used);
784 785
	}

786 787
	for (lf = 0; lf < num_cols; lf++)
	{
788 789
		mylog("fetch: cols=%d, lf=%d, self = %u, self->bindings = %u, buffer[] = %u\n", num_cols, lf, self, self->bindings, self->bindings[lf].buffer);

790
		/* reset for SQLGetData */
791 792
		self->bindings[lf].data_left = -1;

793 794
		if (self->bindings[lf].buffer != NULL)
		{
795
			/* this column has a binding */
796

797
			/* type = QR_get_field_type(res, lf); */
798
			type = CI_get_oid(ci, lf);	/* speed things up */
799 800 801

			mylog("type = %d\n", type);

802 803
			if (self->manual_result)
			{
804 805 806 807 808
				value = QR_get_value_manual(res, self->currTuple, lf);
				mylog("manual_result\n");
			}
			else if (globals.use_declarefetch)
				value = QR_get_value_backend(res, lf);
809
			else
810 811
				value = QR_get_value_backend_row(res, self->currTuple, lf);

812
			mylog("value = '%s'\n", (value == NULL) ? "<NULL>" : value);
813 814 815 816 817

			retval = copy_and_convert_field_bindinfo(self, type, value, lf);

			mylog("copy_and_convert: retval = %d\n", retval);

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
			switch (retval)
			{
				case COPY_OK:
					break;		/* OK, do next bound column */

				case COPY_UNSUPPORTED_TYPE:
					self->errormsg = "Received an unsupported type from Postgres.";
					self->errornumber = STMT_RESTRICTED_DATA_TYPE_ERROR;
					SC_log_error(func, "", self);
					result = SQL_ERROR;
					break;

				case COPY_UNSUPPORTED_CONVERSION:
					self->errormsg = "Couldn't handle the necessary data type conversion.";
					self->errornumber = STMT_RESTRICTED_DATA_TYPE_ERROR;
					SC_log_error(func, "", self);
					result = SQL_ERROR;
					break;

				case COPY_RESULT_TRUNCATED:
					self->errornumber = STMT_TRUNCATED;
					self->errormsg = "The buffer was too small for the result.";
					result = SQL_SUCCESS_WITH_INFO;
					break;

843
					/* error msg already filled in */
844
				case COPY_GENERAL_ERROR:
845 846 847 848
					SC_log_error(func, "", self);
					result = SQL_ERROR;
					break;

849
					/* This would not be meaningful in SQLFetch. */
850 851 852 853 854 855 856 857 858
				case COPY_NO_DATA_FOUND:
					break;

				default:
					self->errormsg = "Unrecognized return value from copy_and_convert_field.";
					self->errornumber = STMT_INTERNAL_ERROR;
					SC_log_error(func, "", self);
					result = SQL_ERROR;
					break;
859 860 861 862 863 864 865 866
			}
		}
	}

	return result;
}


867 868
RETCODE
SC_execute(StatementClass *self)
869
{
870 871 872 873 874 875 876 877 878
	static char *func = "SC_execute";
	ConnectionClass *conn;
	QResultClass *res;
	char		ok,
				was_ok,
				was_nonfatal;
	Int2		oldstatus,
				numcols;
	QueryInfo	qi;
879 880 881 882


	conn = SC_get_conn(self);

883 884
	/* Begin a transaction if one is not already in progress */

885
	/*
886 887 888 889 890 891 892 893 894 895
	 * Basically we don't have to begin a transaction in autocommit mode
	 * because Postgres backend runs in autocomit mode. We issue "BEGIN"
	 * in the following cases. 1) we use declare/fetch and the statement
	 * is SELECT (because declare/fetch must be called in a transaction).
	 * 2) we are in autocommit off state and the statement isn't of type
	 * OTHER.
	 */
	if (!self->internal && !CC_is_in_trans(conn) &&
		((globals.use_declarefetch && self->statement_type == STMT_TYPE_SELECT) || (!CC_is_in_autocommit(conn) && self->statement_type != STMT_TYPE_OTHER)))
	{
896
		mylog("   about to begin a transaction on statement = %u\n", self);
897
		res = CC_send_query(conn, "BEGIN", NULL);
898 899
		if (QR_aborted(res))
		{
900 901
			self->errormsg = "Could not begin a transaction";
			self->errornumber = STMT_EXEC_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
902
			SC_log_error(func, "", self);
903 904
			return SQL_ERROR;
		}
905 906 907

		ok = QR_command_successful(res);

908
		mylog("SQLExecute: ok = %d, status = %d\n", ok, QR_get_status(res));
909

910
		QR_Destructor(res);
911

912 913
		if (!ok)
		{
914 915
			self->errormsg = "Could not begin a transaction";
			self->errornumber = STMT_EXEC_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
916
			SC_log_error(func, "", self);
917 918 919 920 921 922 923 924 925 926
			return SQL_ERROR;
		}
		else
			CC_set_in_trans(conn);
	}

	oldstatus = conn->status;
	conn->status = CONN_EXECUTING;
	self->status = STMT_EXECUTING;

927 928 929 930 931 932 933 934 935 936
	/* If it's a SELECT statement, use a cursor. */

	/*
	 * Note that the declare cursor has already been prepended to the
	 * statement
	 */
	/* in copy_statement... */
	if (self->statement_type == STMT_TYPE_SELECT)
	{
		char		fetch[128];
937 938 939

		mylog("       Sending SELECT statement on stmt=%u, cursor_name='%s'\n", self, self->cursor_name);

940
		/* send the declare/select */
941
		self->result = CC_send_query(conn, self->stmt_with_params, NULL);
942

943
		if (globals.use_declarefetch && self->result != NULL &&
944 945
			QR_command_successful(self->result))
		{
946 947
			QR_Destructor(self->result);

948 949 950 951
			/*
			 * That worked, so now send the fetch to start getting data
			 * back
			 */
952 953 954 955
			qi.result_in = NULL;
			qi.cursor = self->cursor_name;
			qi.row_size = globals.fetch_max;

956 957 958 959 960 961 962
			/*
			 * Most likely the rowset size will not be set by the
			 * application until after the statement is executed, so might
			 * as well use the cache size. The qr_next_tuple() function
			 * will correct for any discrepancies in sizes and adjust the
			 * cache accordingly.
			 */
963
			sprintf(fetch, "fetch %d in %s", qi.row_size, self->cursor_name);
964

965
			self->result = CC_send_query(conn, fetch, &qi);
966 967 968
		}
		mylog("     done sending the query:\n");
	}
969
	else
970 971
	{
		/* not a SELECT statement so don't use a cursor */
972
		mylog("      it's NOT a select statement: stmt=%u\n", self);
973
		self->result = CC_send_query(conn, self->stmt_with_params, NULL);
974

975 976 977 978 979 980 981 982 983 984 985 986
		/*
		 * We shouldn't send COMMIT. Postgres backend does the autocommit
		 * if neccessary. (Zoltan, 04/26/2000)
		 */

		/*
		 * Above seems wrong. Even in case of autocommit, started
		 * transactions must be committed. (Hiroshi, 02/11/2001)
		 */
		if (!self->internal && CC_is_in_autocommit(conn) && CC_is_in_trans(conn))
		{
			res = CC_send_query(conn, "COMMIT", NULL);
987 988
			QR_Destructor(res);
			CC_set_no_trans(conn);
989
		}
990 991 992 993 994
	}

	conn->status = oldstatus;
	self->status = STMT_FINISHED;

995 996 997
	/* Check the status of the result */
	if (self->result)
	{
998 999
		was_ok = QR_command_successful(self->result);
		was_nonfatal = QR_command_nonfatal(self->result);
1000

1001
		if (was_ok)
1002 1003 1004
			self->errornumber = STMT_OK;
		else
			self->errornumber = was_nonfatal ? STMT_INFO_ONLY : STMT_ERROR_TAKEN_FROM_BACKEND;
1005

1006 1007
		/* set cursor before the first tuple in the list */
		self->currTuple = -1;
1008
		self->current_col = -1;
1009
		self->rowset_start = -1;
1010

1011 1012
		/* see if the query did return any result columns */
		numcols = QR_NumResultCols(self->result);
1013

1014
		/* now allocate the array to hold the binding info */
1015 1016
		if (numcols > 0)
		{
1017
			extend_bindings(self, numcols);
1018 1019
			if (self->bindings == NULL)
			{
1020 1021
				self->errornumber = STMT_NO_MEMORY_ERROR;
				self->errormsg = "Could not get enough free memory to store the binding information";
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1022
				SC_log_error(func, "", self);
1023 1024 1025
				return SQL_ERROR;
			}
		}
1026 1027
		/* issue "ABORT" when query aborted */
		if (QR_get_aborted(self->result) && !self->internal)
1028
			CC_abort(conn);
1029 1030
	}
	else
1031 1032
	{
		/* Bad Error -- The error message will be in the Connection */
1033 1034
		if (self->statement_type == STMT_TYPE_CREATE)
		{
1035 1036
			self->errornumber = STMT_CREATE_TABLE_ERROR;
			self->errormsg = "Error creating the table";
1037 1038 1039 1040 1041 1042 1043

			/*
			 * This would allow the table to already exists, thus
			 * appending rows to it.  BUT, if the table didn't have the
			 * same attributes, it would fail. return
			 * SQL_SUCCESS_WITH_INFO;
			 */
1044
		}
1045 1046
		else
		{
1047
			self->errornumber = STMT_EXEC_ERROR;
1048 1049
			self->errormsg = "Error while executing the query";
		}
1050

1051
		if (!self->internal)
1052
			CC_abort(conn);
1053 1054 1055 1056
	}

	if (self->errornumber == STMT_OK)
		return SQL_SUCCESS;
1057 1058
	else if (self->errornumber == STMT_INFO_ONLY)
		return SQL_SUCCESS_WITH_INFO;
1059 1060
	else
	{
1061
		self->errormsg = "Error while executing the query";
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1062
		SC_log_error(func, "", self);
1063
		return SQL_ERROR;
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1064 1065 1066
	}
}

1067

Byron Nikolaidis's avatar
Byron Nikolaidis committed
1068
void
Bruce Momjian's avatar
Bruce Momjian committed
1069
SC_log_error(char *func, char *desc, StatementClass *self)
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1070
{
1071 1072 1073
#ifdef PRN_NULLCHECK
#define nullcheck(a) (a ? a : "(NULL)")
#endif
1074 1075
	if (self)
	{
1076 1077
		qlog("STATEMENT ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->errornumber, nullcheck(self->errormsg));
		mylog("STATEMENT ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->errornumber, nullcheck(self->errormsg));
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1078 1079 1080 1081 1082
		qlog("                 ------------------------------------------------------------\n");
		qlog("                 hdbc=%u, stmt=%u, result=%u\n", self->hdbc, self, self->result);
		qlog("                 manual_result=%d, prepare=%d, internal=%d\n", self->manual_result, self->prepare, self->internal);
		qlog("                 bindings=%u, bindings_allocated=%d\n", self->bindings, self->bindings_allocated);
		qlog("                 parameters=%u, parameters_allocated=%d\n", self->parameters, self->parameters_allocated);
1083 1084
		qlog("                 statement_type=%d, statement='%s'\n", self->statement_type, nullcheck(self->statement));
		qlog("                 stmt_with_params='%s'\n", nullcheck(self->stmt_with_params));
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1085 1086
		qlog("                 data_at_exec=%d, current_exec_param=%d, put_data=%d\n", self->data_at_exec, self->current_exec_param, self->put_data);
		qlog("                 currTuple=%d, current_col=%d, lobj_fd=%d\n", self->currTuple, self->current_col, self->lobj_fd);
1087
		qlog("                 maxRows=%d, rowset_size=%d, keyset_size=%d, cursor_type=%d, scroll_concurrency=%d\n", self->options.maxRows, self->options.rowset_size, self->options.keyset_size, self->options.cursor_type, self->options.scroll_concurrency);
1088
		qlog("                 cursor_name='%s'\n", nullcheck(self->cursor_name));
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1089 1090 1091

		qlog("                 ----------------QResult Info -------------------------------\n");

1092 1093 1094 1095 1096 1097 1098 1099
		if (self->result)
		{
			QResultClass *res = self->result;

			qlog("                 fields=%u, manual_tuples=%u, backend_tuples=%u, tupleField=%d, conn=%u\n", res->fields, res->manual_tuples, res->backend_tuples, res->tupleField, res->conn);
			qlog("                 fetch_count=%d, fcount=%d, num_fields=%d, cursor='%s'\n", res->fetch_count, res->fcount, res->num_fields, nullcheck(res->cursor));
			qlog("                 message='%s', command='%s', notice='%s'\n", nullcheck(res->message), nullcheck(res->command), nullcheck(res->notice));
			qlog("                 status=%d, inTuples=%d\n", res->status, res->inTuples);
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1100
		}
1101

1102
		/* Log the connection error if there is one */
Byron Nikolaidis's avatar
Byron Nikolaidis committed
1103 1104 1105 1106
		CC_log_error(func, desc, self->hdbc);
	}
	else
		qlog("INVALID STATEMENT HANDLE ERROR: func=%s, desc='%s'\n", func, desc);
1107
#undef PRN_NULLCHECK
1108
}