2 * psql - the PostgreSQL interactive terminal
4 * Copyright 2000 by PostgreSQL Global Development Group
6 * $Header: /cvsroot/pgsql/src/bin/psql/common.c,v 1.38 2001/11/05 17:46:30 momjian Exp $
8 #include "postgres_fe.h"
22 #include <unistd.h> /* for write() */
25 #include <io.h> /* for _write() */
33 #include "variables.h"
41 * "Safe" wrapper around strdup()
44 xstrdup(const char *string)
50 fprintf(stderr, gettext("%s: xstrdup: cannot duplicate null pointer (internal error)\n"),
57 psql_error("out of memory\n");
67 * -- handler for -o command line option and \o command
69 * Tries to open file fname (or pipe if fname starts with '|')
70 * and stores the file handle in pset)
71 * Upon failure, sets stdout and returns false.
74 setQFout(const char *fname)
78 /* Close old file/pipe */
79 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
81 if (pset.queryFoutPipe)
82 pclose(pset.queryFout);
84 fclose(pset.queryFout);
87 /* If no filename, set stdout */
88 if (!fname || fname[0] == '\0')
90 pset.queryFout = stdout;
91 pset.queryFoutPipe = false;
93 else if (*fname == '|')
95 pset.queryFout = popen(fname + 1, "w");
96 pset.queryFoutPipe = true;
100 pset.queryFout = fopen(fname, "w");
101 pset.queryFoutPipe = false;
104 if (!(pset.queryFout))
106 psql_error("%s: %s\n", fname, strerror(errno));
107 pset.queryFout = stdout;
108 pset.queryFoutPipe = false;
114 if (pset.queryFoutPipe)
115 pqsignal(SIGPIPE, SIG_IGN);
117 pqsignal(SIGPIPE, SIG_DFL);
126 * Error reporting for scripts. Errors should look like
127 * psql:filename:lineno: message
131 psql_error(const char *fmt,...)
136 if (pset.queryFout != stdout)
137 fflush(pset.queryFout);
140 fprintf(stderr, "%s:%s:%u: ", pset.progname, pset.inputfile, pset.lineno);
142 vfprintf(stderr, gettext(fmt), ap);
149 * for backend NOTICES
152 NoticeProcessor(void *arg, const char *message)
154 (void) arg; /* not used */
155 psql_error("%s", message);
163 * Generalized function especially intended for reading in usernames and
164 * password interactively. Reads from /dev/tty or stdin/stderr.
166 * prompt: The prompt to print
167 * maxlen: How many characters to accept
168 * echo: Set to false if you want to hide what is entered (for passwords)
170 * Returns a malloc()'ed string with the input (w/o trailing newline).
172 static bool prompt_state = false;
175 simple_prompt(const char *prompt, int maxlen, bool echo)
182 #ifdef HAVE_TERMIOS_H
183 struct termios t_orig,
187 destination = (char *) malloc(maxlen + 2);
191 prompt_state = true; /* disable SIGINT */
194 * Do not try to collapse these into one "w+" mode file. Doesn't work
195 * on some platforms (eg, HPUX 10.20).
197 termin = fopen("/dev/tty", "r");
198 termout = fopen("/dev/tty", "w");
199 if (!termin || !termout)
209 #ifdef HAVE_TERMIOS_H
212 tcgetattr(fileno(termin), &t);
215 tcsetattr(fileno(termin), TCSAFLUSH, &t);
221 fputs(gettext(prompt), termout);
225 if (fgets(destination, maxlen, termin) == NULL)
226 destination[0] = '\0';
228 length = strlen(destination);
229 if (length > 0 && destination[length - 1] != '\n')
231 /* eat rest of the line */
237 if (fgets(buf, sizeof(buf), termin) == NULL)
239 buflen = strlen(buf);
240 } while (buflen > 0 && buf[buflen - 1] != '\n');
243 if (length > 0 && destination[length - 1] == '\n')
244 /* remove trailing newline */
245 destination[length - 1] = '\0';
247 #ifdef HAVE_TERMIOS_H
250 tcsetattr(fileno(termin), TCSAFLUSH, &t_orig);
251 fputs("\n", termout);
262 prompt_state = false; /* SIGINT okay again */
270 * Code to support query cancellation
272 * Before we start a query, we enable a SIGINT signal catcher that sends a
273 * cancel request to the backend. Note that sending the cancel directly from
274 * the signal handler is safe because PQrequestCancel() is written to make it
275 * so. We use write() to print to stdout because it's better to use simple
276 * facilities in a signal handler.
280 volatile bool cancel_pressed;
284 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
287 handle_sigint(SIGNAL_ARGS)
289 int save_errno = errno;
291 /* Don't muck around if copying in or prompting for a password. */
292 if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
295 if (cancelConn == NULL)
296 siglongjmp(main_loop_jmp, 1);
298 cancel_pressed = true;
300 if (PQrequestCancel(cancelConn))
301 write_stderr("Cancel request sent\n");
304 write_stderr("Could not send cancel request: ");
305 write_stderr(PQerrorMessage(cancelConn));
307 errno = save_errno; /* just in case the write changed it */
309 #endif /* not WIN32 */
315 * This is the way to send "backdoor" queries (those not directly entered
316 * by the user). It is subject to -E but not -e.
319 PSQLexec(const char *query)
326 psql_error("You are currently not connected to a database.\n");
330 var = GetVariable(pset.vars, "ECHO_HIDDEN");
333 printf("********* QUERY **********\n"
335 "**************************\n\n", query);
339 if (var && strcmp(var, "noexec") == 0)
342 cancelConn = pset.db;
343 res = PQexec(pset.db, query);
344 if (PQresultStatus(res) == PGRES_COPY_IN)
345 copy_in_state = true;
346 /* keep cancel connection for copy out state */
347 if (PQresultStatus(res) != PGRES_COPY_OUT)
350 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
351 PQresultStatus(res) == PGRES_TUPLES_OK ||
352 PQresultStatus(res) == PGRES_COPY_IN ||
353 PQresultStatus(res) == PGRES_COPY_OUT)
358 psql_error("%s", PQerrorMessage(pset.db));
361 if (PQstatus(pset.db) == CONNECTION_BAD)
363 if (!pset.cur_cmd_interactive)
365 psql_error("connection to server was lost\n");
368 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
370 if (PQstatus(pset.db) == CONNECTION_BAD)
372 fputs(gettext("Failed.\n"), stderr);
375 SetVariable(pset.vars, "DBNAME", NULL);
376 SetVariable(pset.vars, "HOST", NULL);
377 SetVariable(pset.vars, "PORT", NULL);
378 SetVariable(pset.vars, "USER", NULL);
379 SetVariable(pset.vars, "ENCODING", NULL);
382 fputs(gettext("Succeeded.\n"), stderr);
392 * SendQuery: send the query string to the backend
393 * (and print out results)
395 * Note: This is the "front door" way to send a query. That is, use it to
396 * send queries actually entered by the user. These queries will be subject to
398 * To send "back door" queries (generated by slash commands, etc.) in a
399 * controlled way, use PSQLexec().
401 * Returns true if the query executed successfully, false otherwise.
404 SendQuery(const char *query)
406 bool success = false;
412 psql_error("You are currently not connected to a database.\n");
416 if (GetVariableBool(pset.vars, "SINGLESTEP"))
420 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
422 "***(press return to proceed or enter x and return to cancel)********************\n"),
425 if (fgets(buf, sizeof(buf), stdin) != NULL)
431 const char *var = GetVariable(pset.vars, "ECHO");
433 if (var && strncmp(var, "queries", strlen(var)) == 0)
437 cancelConn = pset.db;
438 results = PQexec(pset.db, query);
439 if (PQresultStatus(results) == PGRES_COPY_IN)
440 copy_in_state = true;
441 /* keep cancel connection for copy out state */
442 if (PQresultStatus(results) != PGRES_COPY_OUT)
447 fputs(PQerrorMessage(pset.db), pset.queryFout);
452 switch (PQresultStatus(results))
454 case PGRES_TUPLES_OK:
455 /* write output to \g argument, if any */
458 FILE *queryFout_copy = pset.queryFout;
459 bool queryFoutPipe_copy = pset.queryFoutPipe;
461 pset.queryFout = stdout; /* so it doesn't get
465 if (!setQFout(pset.gfname))
467 pset.queryFout = queryFout_copy;
468 pset.queryFoutPipe = queryFoutPipe_copy;
473 printQuery(results, &pset.popt, pset.queryFout);
475 /* close file/pipe, restore old setting */
478 pset.queryFout = queryFout_copy;
479 pset.queryFoutPipe = queryFoutPipe_copy;
488 printQuery(results, &pset.popt, pset.queryFout);
492 case PGRES_EMPTY_QUERY:
495 case PGRES_COMMAND_OK:
500 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
502 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
503 SetVariable(pset.vars, "LASTOID", buf);
507 success = handleCopyOut(pset.db, pset.queryFout);
511 if (pset.cur_cmd_interactive && !QUIET())
512 puts(gettext("Enter data to be copied followed by a newline.\n"
513 "End with a backslash and a period on a line by itself."));
515 success = handleCopyIn(pset.db, pset.cur_cmd_source,
516 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
519 case PGRES_NONFATAL_ERROR:
520 case PGRES_FATAL_ERROR:
521 case PGRES_BAD_RESPONSE:
523 psql_error("%s", PQerrorMessage(pset.db));
527 fflush(pset.queryFout);
529 if (PQstatus(pset.db) == CONNECTION_BAD)
531 if (!pset.cur_cmd_interactive)
533 psql_error("connection to server was lost\n");
536 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
538 if (PQstatus(pset.db) == CONNECTION_BAD)
540 fputs(gettext("Failed.\n"), stderr);
544 SetVariable(pset.vars, "DBNAME", NULL);
545 SetVariable(pset.vars, "HOST", NULL);
546 SetVariable(pset.vars, "PORT", NULL);
547 SetVariable(pset.vars, "USER", NULL);
548 SetVariable(pset.vars, "ENCODING", NULL);
552 fputs(gettext("Succeeded.\n"), stderr);
555 /* check for asynchronous notification returns */
556 while ((notify = PQnotifies(pset.db)) != NULL)
558 fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
559 notify->relname, notify->be_pid);
561 fflush(pset.queryFout);