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.49 2002/10/23 19:23:56 momjian Exp $
8 #include "postgres_fe.h"
20 #include <unistd.h> /* for write() */
23 #include <io.h> /* for _write() */
25 #include <sys/timeb.h> /* for _ftime() */
32 #include "variables.h"
38 extern bool prompt_state;
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 INFO, WARNING, ERROR
152 NoticeProcessor(void *arg, const char *message)
154 (void) arg; /* not used */
155 psql_error("%s", message);
161 * Code to support query cancellation
163 * Before we start a query, we enable a SIGINT signal catcher that sends a
164 * cancel request to the backend. Note that sending the cancel directly from
165 * the signal handler is safe because PQrequestCancel() is written to make it
166 * so. We use write() to print to stdout because it's better to use simple
167 * facilities in a signal handler.
170 volatile bool cancel_pressed;
174 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
177 handle_sigint(SIGNAL_ARGS)
179 int save_errno = errno;
181 /* Don't muck around if copying in or prompting for a password. */
182 if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
185 if (cancelConn == NULL)
186 siglongjmp(main_loop_jmp, 1);
188 cancel_pressed = true;
190 if (PQrequestCancel(cancelConn))
191 write_stderr("Cancel request sent\n");
194 write_stderr("Could not send cancel request: ");
195 write_stderr(PQerrorMessage(cancelConn));
197 errno = save_errno; /* just in case the write changed it */
199 #endif /* not WIN32 */
205 * This is the way to send "backdoor" queries (those not directly entered
206 * by the user). It is subject to -E but not -e.
208 * If the given querystring generates multiple PGresults, normally the last
209 * one is returned to the caller. However, if ignore_command_ok is TRUE,
210 * then PGresults with status PGRES_COMMAND_OK are ignored. This is intended
211 * mainly to allow locutions such as "begin; select ...; commit".
214 PSQLexec(const char *query, bool ignore_command_ok)
216 PGresult *res = NULL;
219 ExecStatusType rstatus;
223 psql_error("You are currently not connected to a database.\n");
227 var = GetVariable(pset.vars, "ECHO_HIDDEN");
230 printf("********* QUERY **********\n"
232 "**************************\n\n", query);
236 if (var && strcmp(var, "noexec") == 0)
239 /* discard any uneaten results of past queries */
240 while ((newres = PQgetResult(pset.db)) != NULL)
243 cancelConn = pset.db;
244 if (PQsendQuery(pset.db, query))
246 while ((newres = PQgetResult(pset.db)) != NULL)
248 rstatus = PQresultStatus(newres);
249 if (ignore_command_ok && rstatus == PGRES_COMMAND_OK)
256 if (rstatus == PGRES_COPY_IN ||
257 rstatus == PGRES_COPY_OUT)
261 rstatus = PQresultStatus(res);
262 /* keep cancel connection for copy out state */
263 if (rstatus != PGRES_COPY_OUT)
265 if (rstatus == PGRES_COPY_IN)
266 copy_in_state = true;
268 if (res && (rstatus == PGRES_COMMAND_OK ||
269 rstatus == PGRES_TUPLES_OK ||
270 rstatus == PGRES_COPY_IN ||
271 rstatus == PGRES_COPY_OUT))
275 psql_error("%s", PQerrorMessage(pset.db));
278 if (PQstatus(pset.db) == CONNECTION_BAD)
280 if (!pset.cur_cmd_interactive)
282 psql_error("connection to server was lost\n");
285 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
287 if (PQstatus(pset.db) == CONNECTION_BAD)
289 fputs(gettext("Failed.\n"), stderr);
292 SetVariable(pset.vars, "DBNAME", NULL);
293 SetVariable(pset.vars, "HOST", NULL);
294 SetVariable(pset.vars, "PORT", NULL);
295 SetVariable(pset.vars, "USER", NULL);
296 SetVariable(pset.vars, "ENCODING", NULL);
299 fputs(gettext("Succeeded.\n"), stderr);
309 * SendQuery: send the query string to the backend
310 * (and print out results)
312 * Note: This is the "front door" way to send a query. That is, use it to
313 * send queries actually entered by the user. These queries will be subject to
315 * To send "back door" queries (generated by slash commands, etc.) in a
316 * controlled way, use PSQLexec().
318 * Returns true if the query executed successfully, false otherwise.
321 SendQuery(const char *query)
323 bool success = false;
327 struct timeval before,
330 struct _timeb before,
336 psql_error("You are currently not connected to a database.\n");
340 if (GetVariableBool(pset.vars, "SINGLESTEP"))
344 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
346 "***(press return to proceed or enter x and return to cancel)********************\n"),
349 if (fgets(buf, sizeof(buf), stdin) != NULL)
355 const char *var = GetVariable(pset.vars, "ECHO");
357 if (var && strncmp(var, "queries", strlen(var)) == 0)
361 cancelConn = pset.db;
365 gettimeofday(&before, NULL);
366 results = PQexec(pset.db, query);
368 gettimeofday(&after, NULL);
372 results = PQexec(pset.db, query);
377 if (PQresultStatus(results) == PGRES_COPY_IN)
378 copy_in_state = true;
379 /* keep cancel connection for copy out state */
380 if (PQresultStatus(results) != PGRES_COPY_OUT)
385 fputs(PQerrorMessage(pset.db), pset.queryFout);
390 switch (PQresultStatus(results))
392 case PGRES_TUPLES_OK:
393 /* write output to \g argument, if any */
396 FILE *queryFout_copy = pset.queryFout;
397 bool queryFoutPipe_copy = pset.queryFoutPipe;
399 pset.queryFout = stdout; /* so it doesn't get
403 if (!setQFout(pset.gfname))
405 pset.queryFout = queryFout_copy;
406 pset.queryFoutPipe = queryFoutPipe_copy;
411 printQuery(results, &pset.popt, pset.queryFout);
413 /* close file/pipe, restore old setting */
416 pset.queryFout = queryFout_copy;
417 pset.queryFoutPipe = queryFoutPipe_copy;
426 printQuery(results, &pset.popt, pset.queryFout);
430 case PGRES_EMPTY_QUERY:
433 case PGRES_COMMAND_OK:
438 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
440 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
441 SetVariable(pset.vars, "LASTOID", buf);
445 success = handleCopyOut(pset.db, pset.queryFout);
449 if (pset.cur_cmd_interactive && !QUIET())
450 puts(gettext("Enter data to be copied followed by a newline.\n"
451 "End with a backslash and a period on a line by itself."));
453 success = handleCopyIn(pset.db, pset.cur_cmd_source,
454 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
457 case PGRES_NONFATAL_ERROR:
458 case PGRES_FATAL_ERROR:
459 case PGRES_BAD_RESPONSE:
461 psql_error("%s", PQerrorMessage(pset.db));
465 fflush(pset.queryFout);
467 if (PQstatus(pset.db) == CONNECTION_BAD)
469 if (!pset.cur_cmd_interactive)
471 psql_error("connection to server was lost\n");
474 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
476 if (PQstatus(pset.db) == CONNECTION_BAD)
478 fputs(gettext("Failed.\n"), stderr);
482 SetVariable(pset.vars, "DBNAME", NULL);
483 SetVariable(pset.vars, "HOST", NULL);
484 SetVariable(pset.vars, "PORT", NULL);
485 SetVariable(pset.vars, "USER", NULL);
486 SetVariable(pset.vars, "ENCODING", NULL);
490 fputs(gettext("Succeeded.\n"), stderr);
493 /* check for asynchronous notification returns */
494 while ((notify = PQnotifies(pset.db)) != NULL)
496 fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
497 notify->relname, notify->be_pid);
499 fflush(pset.queryFout);
506 /* Possible microtiming output */
507 if (pset.timing && success)
509 printf(gettext("Time: %.2f ms\n"),
510 ((after.tv_sec - before.tv_sec) * 1000000.0 + after.tv_usec - before.tv_usec) / 1000.0);
512 printf(gettext("Time: %.2f ms\n"),
513 ((after.time - before.time) * 1000.0 + after.millitm - before.millitm));
523 * Tests if pager is needed and returns appropriate FILE pointer.
526 PageOutput(int lines, bool pager)
528 /* check whether we need / can / are supposed to use pager */
532 isatty(fileno(stdin)) &&
533 isatty(fileno(stdout))
537 const char *pagerprog;
541 struct winsize screen_size;
543 result = ioctl(fileno(stdout), TIOCGWINSZ, &screen_size);
544 if (result == -1 || lines > screen_size.ws_row)
547 pagerprog = getenv("PAGER");
549 pagerprog = DEFAULT_PAGER;
551 pqsignal(SIGPIPE, SIG_IGN);
553 return popen(pagerprog, "w");