mainloop.c 12.6 KB
Newer Older
Peter Eisentraut's avatar
Peter Eisentraut committed
1 2 3
/*
 * psql - the PostgreSQL interactive terminal
 *
4
 * Copyright 2000 by PostgreSQL Global Development Group
Peter Eisentraut's avatar
Peter Eisentraut committed
5
 *
Peter Eisentraut's avatar
Peter Eisentraut committed
6
 * $Header: /cvsroot/pgsql/src/bin/psql/mainloop.c,v 1.30 2000/05/12 16:13:44 petere Exp $
Peter Eisentraut's avatar
Peter Eisentraut committed
7
 */
8
#include "postgres.h"
9 10
#include "mainloop.h"

11
#include "pqexpbuffer.h"
12 13 14 15 16 17 18

#include "settings.h"
#include "prompt.h"
#include "input.h"
#include "common.h"
#include "command.h"

19 20 21
#ifndef WIN32
#include <setjmp.h>

22 23
sigjmp_buf	main_loop_jmp;

24
#endif
25 26


27
/*
28 29 30 31 32
 * Main processing loop for reading lines of input
 *	and sending them to the backend.
 *
 * This loop is re-entrant. May be called by \i command
 *	which reads input from a file.
33 34
 *
 * FIXME: rewrite this whole thing with flex
35 36
 */
int
Peter Eisentraut's avatar
Peter Eisentraut committed
37
MainLoop(FILE *source)
38
{
Bruce Momjian's avatar
Bruce Momjian committed
39
	PQExpBuffer query_buf;		/* buffer for query being accumulated */
40 41
	PQExpBuffer previous_buf;	/* if there isn't anything in the new
								 * buffer yet, use this one for \e, etc. */
Bruce Momjian's avatar
Bruce Momjian committed
42 43
	char	   *line;			/* current line of input */
	int			len;			/* length of the line */
44 45
	volatile int successResult = EXIT_SUCCESS;
	volatile backslashResult slashCmdStatus;
46

Bruce Momjian's avatar
Bruce Momjian committed
47
	bool		success;
48 49 50
	volatile char in_quote;		/* == 0 for no in_quote */
	volatile bool xcomment;		/* in extended comment */
	volatile int paren_level;
Bruce Momjian's avatar
Bruce Momjian committed
51
	unsigned int query_start;
52 53 54
	volatile int count_eof = 0;
	const char *var;
	volatile unsigned int bslash_count = 0;
55

Bruce Momjian's avatar
Bruce Momjian committed
56 57 58
	int			i,
				prevlen,
				thislen;
59

Bruce Momjian's avatar
Bruce Momjian committed
60 61 62
	/* Save the prior command source */
	FILE	   *prev_cmd_source;
	bool		prev_cmd_interactive;
63

64
	unsigned int prev_lineno;
65
	volatile bool die_on_error = false;
66 67


Bruce Momjian's avatar
Bruce Momjian committed
68
	/* Save old settings */
69 70
	prev_cmd_source = pset.cur_cmd_source;
	prev_cmd_interactive = pset.cur_cmd_interactive;
71

Bruce Momjian's avatar
Bruce Momjian committed
72
	/* Establish new source */
73 74
	pset.cur_cmd_source = source;
	pset.cur_cmd_interactive = ((source == stdin) && !pset.notty);
75 76


Bruce Momjian's avatar
Bruce Momjian committed
77
	query_buf = createPQExpBuffer();
78
	previous_buf = createPQExpBuffer();
79
	if (!query_buf || !previous_buf)
Bruce Momjian's avatar
Bruce Momjian committed
80
	{
81
		psql_error("out of memory\n");
Bruce Momjian's avatar
Bruce Momjian committed
82 83
		exit(EXIT_FAILURE);
	}
84

85
	xcomment = false;
Bruce Momjian's avatar
Bruce Momjian committed
86 87 88
	in_quote = 0;
	paren_level = 0;
	slashCmdStatus = CMD_UNKNOWN;		/* set default */
89 90
	prev_lineno = pset.lineno;
	pset.lineno = 0;
91 92


Bruce Momjian's avatar
Bruce Momjian committed
93
	/* main loop to get queries and execute them */
94
	while (1)
95
	{
96
#ifndef WIN32
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

		/*
		 * Welcome code for Control-C
		 */
		if (cancel_pressed)
		{
			if (!pset.cur_cmd_interactive)
			{

				/*
				 * You get here if you stopped a script with Ctrl-C and a
				 * query cancel was issued. In that case we don't do the
				 * longjmp, so the query routine can finish nicely.
				 */
				successResult = EXIT_USER;
				break;
			}

			cancel_pressed = false;
		}

		if (sigsetjmp(main_loop_jmp, 1) != 0)
		{
			/* got here with longjmp */

			if (pset.cur_cmd_interactive)
			{
				fputc('\n', stdout);
				resetPQExpBuffer(query_buf);

				/* reset parsing state */
				xcomment = false;
				in_quote = 0;
				paren_level = 0;
				count_eof = 0;
				slashCmdStatus = CMD_UNKNOWN;
			}
			else
			{
				successResult = EXIT_USER;
				break;
			}
		}
#endif	 /* not WIN32 */
141

Bruce Momjian's avatar
Bruce Momjian committed
142 143
		if (slashCmdStatus == CMD_NEWEDIT)
		{
144

Bruce Momjian's avatar
Bruce Momjian committed
145 146 147 148
			/*
			 * just returned from editing the line? then just copy to the
			 * input buffer
			 */
149
			line = xstrdup(query_buf->data);
Bruce Momjian's avatar
Bruce Momjian committed
150
			resetPQExpBuffer(query_buf);
151
			/* reset parsing state since we are rescanning whole line */
152
			xcomment = false;
Bruce Momjian's avatar
Bruce Momjian committed
153 154
			in_quote = 0;
			paren_level = 0;
155
			slashCmdStatus = CMD_UNKNOWN;
Bruce Momjian's avatar
Bruce Momjian committed
156
		}
157
		else
Bruce Momjian's avatar
Bruce Momjian committed
158
		{
159 160
			fflush(stdout);

Bruce Momjian's avatar
Bruce Momjian committed
161 162 163 164
			/*
			 * otherwise, set interactive prompt if necessary and get
			 * another line
			 */
165
			if (pset.cur_cmd_interactive)
Bruce Momjian's avatar
Bruce Momjian committed
166 167 168 169 170 171 172
			{
				int			prompt_status;

				if (in_quote && in_quote == '\'')
					prompt_status = PROMPT_SINGLEQUOTE;
				else if (in_quote && in_quote == '"')
					prompt_status = PROMPT_DOUBLEQUOTE;
173
				else if (xcomment)
Bruce Momjian's avatar
Bruce Momjian committed
174
					prompt_status = PROMPT_COMMENT;
175 176
				else if (paren_level)
					prompt_status = PROMPT_PAREN;
Bruce Momjian's avatar
Bruce Momjian committed
177 178 179 180 181
				else if (query_buf->len > 0)
					prompt_status = PROMPT_CONTINUE;
				else
					prompt_status = PROMPT_READY;

182
				line = gets_interactive(get_prompt(prompt_status));
Bruce Momjian's avatar
Bruce Momjian committed
183 184 185 186
			}
			else
				line = gets_fromFile(source);
		}
187 188


189
		/* Setting this will not have effect until next line. */
190
		die_on_error = GetVariableBool(pset.vars, "ON_ERROR_STOP");
191

Bruce Momjian's avatar
Bruce Momjian committed
192 193 194 195 196 197
		/*
		 * query_buf holds query already accumulated.  line is the
		 * malloc'd new line of input (note it must be freed before
		 * looping around!) query_start is the next command start location
		 * within the line.
		 */
198

Bruce Momjian's avatar
Bruce Momjian committed
199
		/* No more input.  Time to quit, or \i done */
200
		if (line == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
201
		{
202
			if (pset.cur_cmd_interactive)
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
			{
				bool		getout = true;

				/* This tries to mimic bash's IGNOREEOF feature. */
				const char *val = GetVariable(pset.vars, "IGNOREEOF");

				if (val)
				{
					long int	maxeof;
					char	   *endptr;

					if (*val == '\0')
						maxeof = 10;
					else
					{
						maxeof = strtol(val, &endptr, 0);
						if (*endptr != '\0')	/* string not valid as a
												 * number */
							maxeof = 10;
					}

					if (count_eof++ != maxeof)
						getout = false; /* not quite there yet */
				}

				if (getout)
				{
					if (QUIET())
						putc('\n', stdout);
					else
						puts("\\q");
					break;
				}
				else
				{
					if (!QUIET())
						printf("Use \"\\q\" to leave %s.\n", pset.progname);
					continue;
				}
			}
			else
/* not interactive */
				break;
Bruce Momjian's avatar
Bruce Momjian committed
246
		}
247 248
		else
			count_eof = 0;
249

250
		pset.lineno++;
Peter Eisentraut's avatar
Peter Eisentraut committed
251

Bruce Momjian's avatar
Bruce Momjian committed
252 253 254 255
		/* strip trailing backslashes, they don't have a clear meaning */
		while (1)
		{
			char	   *cp = strrchr(line, '\\');
256

Bruce Momjian's avatar
Bruce Momjian committed
257 258 259 260
			if (cp && (*(cp + 1) == '\0'))
				*cp = '\0';
			else
				break;
261 262
		}

Bruce Momjian's avatar
Bruce Momjian committed
263 264 265 266 267 268
		/* nothing left on line? then ignore */
		if (line[0] == '\0')
		{
			free(line);
			continue;
		}
269

270
		/* echo back if flag is set */
271 272 273 274
		var = GetVariable(pset.vars, "ECHO");
		if (!pset.cur_cmd_interactive && var && strcmp(var, "all") == 0)
			puts(line);
		fflush(stdout);
275

Bruce Momjian's avatar
Bruce Momjian committed
276 277
		len = strlen(line);
		query_start = 0;
278

Bruce Momjian's avatar
Bruce Momjian committed
279 280 281 282 283 284
		/*
		 * Parse line, looking for command separators.
		 *
		 * The current character is at line[i], the prior character at line[i
		 * - prevlen], the next character at line[i + thislen].
		 */
Peter Eisentraut's avatar
Peter Eisentraut committed
285
#define ADVANCE_1 (prevlen = thislen, i += thislen, thislen = PQmblen(line+i, pset.encoding))
286

Bruce Momjian's avatar
Bruce Momjian committed
287
		success = true;
Peter Eisentraut's avatar
Peter Eisentraut committed
288
		for (i = 0, prevlen = 0, thislen = (len > 0) ? PQmblen(line, pset.encoding) : 0;
289 290
			 i < len;
			 ADVANCE_1)
Bruce Momjian's avatar
Bruce Momjian committed
291 292
		{
			/* was the previous character a backslash? */
293 294 295 296 297 298
			bool		was_bslash = (i > 0 && line[i - prevlen] == '\\');

			if (was_bslash)
				bslash_count++;
			else
				bslash_count = 0;
Bruce Momjian's avatar
Bruce Momjian committed
299

Peter Eisentraut's avatar
Peter Eisentraut committed
300
		rescan:
Bruce Momjian's avatar
Bruce Momjian committed
301 302 303 304
			/* in quote? */
			if (in_quote)
			{
				/* end of quote */
305
				if (line[i] == in_quote && bslash_count % 2 == 0)
Bruce Momjian's avatar
Bruce Momjian committed
306 307 308 309
					in_quote = '\0';
			}

			/* start of quote */
310
			else if (!was_bslash && (line[i] == '\'' || line[i] == '"'))
Bruce Momjian's avatar
Bruce Momjian committed
311 312 313
				in_quote = line[i];

			/* in extended comment? */
314
			else if (xcomment)
Bruce Momjian's avatar
Bruce Momjian committed
315 316 317
			{
				if (line[i] == '*' && line[i + thislen] == '/')
				{
318
					xcomment = false;
Bruce Momjian's avatar
Bruce Momjian committed
319 320 321 322 323 324 325
					ADVANCE_1;
				}
			}

			/* start of extended comment? */
			else if (line[i] == '/' && line[i + thislen] == '*')
			{
326
				xcomment = true;
Bruce Momjian's avatar
Bruce Momjian committed
327 328 329 330
				ADVANCE_1;
			}

			/* single-line comment? truncate line */
331
			else if (line[i] == '-' && line[i + thislen] == '-')
Bruce Momjian's avatar
Bruce Momjian committed
332 333 334 335 336 337 338 339 340 341 342 343
			{
				line[i] = '\0'; /* remove comment */
				break;
			}

			/* count nested parentheses */
			else if (line[i] == '(')
				paren_level++;

			else if (line[i] == ')' && paren_level > 0)
				paren_level--;

344 345 346 347 348 349 350
			/* colon -> substitute variable */
			/* we need to be on the watch for the '::' operator */
			else if (line[i] == ':' && !was_bslash
				  && strspn(line + i + thislen, VALID_VARIABLE_CHARS) > 0
					 && !(prevlen > 0 && line[i - prevlen] == ':')
				)
			{
351 352 353 354
				size_t		in_length,
							out_length;
				const char *value;
				char	   *new;
355 356 357
				char		after;		/* the character after the
										 * variable name will be
										 * temporarily overwritten */
358 359 360 361 362

				in_length = strspn(&line[i + thislen], VALID_VARIABLE_CHARS);
				after = line[i + thislen + in_length];
				line[i + thislen + in_length] = '\0';

363 364 365 366
				/*
				 * if the variable doesn't exist we'll leave the string as
				 * is
				 */
367
				value = GetVariable(pset.vars, &line[i + thislen]);
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
				if (value)
				{
					out_length = strlen(value);

					new = malloc(len + out_length - (1 + in_length) + 1);
					if (!new)
					{
						psql_error("out of memory\n");
						exit(EXIT_FAILURE);
					}

					sprintf(new, "%.*s%s%c", i, line, value, after);
					if (after)
						strcat(new, line + i + 1 + in_length + 1);

					free(line);
					line = new;
					len = strlen(new);
Peter Eisentraut's avatar
Peter Eisentraut committed
386 387

					goto rescan;	/* reparse the just substituted */
388 389 390 391 392 393 394 395
				}
				else
				{
					/* restore overwritten character */
					line[i + thislen + in_length] = after;
					/* move on ... */
				}
			}
396

Bruce Momjian's avatar
Bruce Momjian committed
397
			/* semicolon? then send query */
Bruce Momjian's avatar
Bruce Momjian committed
398
			else if (line[i] == ';' && !was_bslash && !paren_level)
Bruce Momjian's avatar
Bruce Momjian committed
399 400 401
			{
				line[i] = '\0';
				/* is there anything else on the line? */
402
				if (line[query_start + strspn(line + query_start, " \t\n\r")] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
403
				{
404

Bruce Momjian's avatar
Bruce Momjian committed
405 406 407 408 409 410 411 412
					/*
					 * insert a cosmetic newline, if this is not the first
					 * line in the buffer
					 */
					if (query_buf->len > 0)
						appendPQExpBufferChar(query_buf, '\n');
					/* append the line to the query buffer */
					appendPQExpBufferStr(query_buf, line + query_start);
413
					appendPQExpBufferChar(query_buf, ';');
Bruce Momjian's avatar
Bruce Momjian committed
414 415 416
				}

				/* execute query */
417
				success = SendQuery(query_buf->data);
418
				slashCmdStatus = success ? CMD_SEND : CMD_ERROR;
Bruce Momjian's avatar
Bruce Momjian committed
419

420 421 422
				resetPQExpBuffer(previous_buf);
				appendPQExpBufferStr(previous_buf, query_buf->data);
				resetPQExpBuffer(query_buf);
Bruce Momjian's avatar
Bruce Momjian committed
423 424 425
				query_start = i + thislen;
			}

426 427 428 429 430 431 432 433 434 435
			/*
			 * if you have a burning need to send a semicolon or colon to
			 * the backend ...
			 */
			else if (was_bslash && (line[i] == ';' || line[i] == ':'))
			{
				/* remove the backslash */
				memmove(line + i - prevlen, line + i, len - i + 1);
				len--;
			}
436

Bruce Momjian's avatar
Bruce Momjian committed
437 438 439 440 441
			/* backslash command */
			else if (was_bslash)
			{
				const char *end_of_cmd = NULL;

442
				paren_level = 0;
Bruce Momjian's avatar
Bruce Momjian committed
443 444
				line[i - prevlen] = '\0';		/* overwrites backslash */

445
				/* is there anything else on the line for the command? */
446
				if (line[query_start + strspn(line + query_start, " \t\n\r")] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
447
				{
448

Bruce Momjian's avatar
Bruce Momjian committed
449 450 451 452 453 454 455 456 457 458
					/*
					 * insert a cosmetic newline, if this is not the first
					 * line in the buffer
					 */
					if (query_buf->len > 0)
						appendPQExpBufferChar(query_buf, '\n');
					/* append the line to the query buffer */
					appendPQExpBufferStr(query_buf, line + query_start);
				}

459 460 461 462
				/* handle backslash command */
				slashCmdStatus = HandleSlashCmds(&line[i],
						   query_buf->len > 0 ? query_buf : previous_buf,
												 &end_of_cmd);
Bruce Momjian's avatar
Bruce Momjian committed
463 464 465

				success = slashCmdStatus != CMD_ERROR;

466 467 468 469 470 471
				if ((slashCmdStatus == CMD_SEND || slashCmdStatus == CMD_NEWEDIT) &&
					query_buf->len == 0)
				{
					/* copy previous buffer to current for for handling */
					appendPQExpBufferStr(query_buf, previous_buf->data);
				}
472

Bruce Momjian's avatar
Bruce Momjian committed
473 474
				if (slashCmdStatus == CMD_SEND)
				{
475
					success = SendQuery(query_buf->data);
Bruce Momjian's avatar
Bruce Momjian committed
476
					query_start = i + thislen;
477

478 479 480
					resetPQExpBuffer(previous_buf);
					appendPQExpBufferStr(previous_buf, query_buf->data);
					resetPQExpBuffer(query_buf);
Bruce Momjian's avatar
Bruce Momjian committed
481 482
				}

483
				/* process anything left after the backslash command */
484 485
				i += end_of_cmd - &line[i];
				query_start = i;
Bruce Momjian's avatar
Bruce Momjian committed
486
			}
487 488


489
			/* stop the script after error */
490 491 492
			if (!success && die_on_error)
				break;

493
		}						/* for (line) */
494 495


Bruce Momjian's avatar
Bruce Momjian committed
496 497 498 499
		if (slashCmdStatus == CMD_TERMINATE)
		{
			successResult = EXIT_SUCCESS;
			break;
500 501 502
		}


Bruce Momjian's avatar
Bruce Momjian committed
503
		/* Put the rest of the line in the query buffer. */
504
		if (line[query_start + strspn(line + query_start, " \t\n\r")] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
505 506 507 508 509
		{
			if (query_buf->len > 0)
				appendPQExpBufferChar(query_buf, '\n');
			appendPQExpBufferStr(query_buf, line + query_start);
		}
510

Bruce Momjian's avatar
Bruce Momjian committed
511
		free(line);
512 513


Bruce Momjian's avatar
Bruce Momjian committed
514
		/* In single line mode, send off the query if any */
515
		if (query_buf->data[0] != '\0' && GetVariableBool(pset.vars, "SINGLELINE"))
Bruce Momjian's avatar
Bruce Momjian committed
516
		{
517
			success = SendQuery(query_buf->data);
518 519 520 521
			slashCmdStatus = success ? CMD_SEND : CMD_ERROR;
			resetPQExpBuffer(previous_buf);
			appendPQExpBufferStr(previous_buf, query_buf->data);
			resetPQExpBuffer(query_buf);
522 523 524
		}


525
		if (!success && die_on_error && !pset.cur_cmd_interactive)
526 527 528
		{
			successResult = EXIT_USER;
			break;
Bruce Momjian's avatar
Bruce Momjian committed
529
		}
530 531


Bruce Momjian's avatar
Bruce Momjian committed
532
		/* Have we lost the db connection? */
533
		if (pset.db == NULL && !pset.cur_cmd_interactive)
Bruce Momjian's avatar
Bruce Momjian committed
534 535 536 537
		{
			successResult = EXIT_BADCONN;
			break;
		}
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	}							/* while !endoffile/session */

	/*
	 * Process query at the end of file without a semicolon
	 */
	if (query_buf->len > 0 && !pset.cur_cmd_interactive)
	{
		success = SendQuery(query_buf->data);

		if (!success && die_on_error)
			successResult = EXIT_USER;
		else if (pset.db == NULL)
			successResult = EXIT_BADCONN;
	}

Bruce Momjian's avatar
Bruce Momjian committed
553
	destroyPQExpBuffer(query_buf);
554
	destroyPQExpBuffer(previous_buf);
555

556 557
	pset.cur_cmd_source = prev_cmd_source;
	pset.cur_cmd_interactive = prev_cmd_interactive;
558
	pset.lineno = prev_lineno;
559

Bruce Momjian's avatar
Bruce Momjian committed
560
	return successResult;
561
}	/* MainLoop() */