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.57 2003/03/18 22:15:44 petere Exp $
8 #include "postgres_fe.h"
19 #include <unistd.h> /* for write() */
22 #include <io.h> /* for _write() */
24 #include <sys/timeb.h> /* for _ftime() */
31 #include "variables.h"
37 extern bool prompt_state;
40 * "Safe" wrapper around strdup()
43 xstrdup(const char *string)
49 fprintf(stderr, gettext("%s: xstrdup: cannot duplicate null pointer (internal error)\n"),
56 psql_error("out of memory\n");
66 * -- handler for -o command line option and \o command
68 * Tries to open file fname (or pipe if fname starts with '|')
69 * and stores the file handle in pset)
70 * Upon failure, sets stdout and returns false.
73 setQFout(const char *fname)
77 /* Close old file/pipe */
78 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
80 if (pset.queryFoutPipe)
81 pclose(pset.queryFout);
83 fclose(pset.queryFout);
86 /* If no filename, set stdout */
87 if (!fname || fname[0] == '\0')
89 pset.queryFout = stdout;
90 pset.queryFoutPipe = false;
92 else if (*fname == '|')
94 pset.queryFout = popen(fname + 1, "w");
95 pset.queryFoutPipe = true;
99 pset.queryFout = fopen(fname, "w");
100 pset.queryFoutPipe = false;
103 if (!(pset.queryFout))
105 psql_error("%s: %s\n", fname, strerror(errno));
106 pset.queryFout = stdout;
107 pset.queryFoutPipe = false;
113 if (pset.queryFoutPipe)
114 pqsignal(SIGPIPE, SIG_IGN);
116 pqsignal(SIGPIPE, SIG_DFL);
125 * Error reporting for scripts. Errors should look like
126 * psql:filename:lineno: message
130 psql_error(const char *fmt,...)
135 if (pset.queryFout != stdout)
136 fflush(pset.queryFout);
139 fprintf(stderr, "%s:%s:%u: ", pset.progname, pset.inputfile, pset.lineno);
141 vfprintf(stderr, gettext(fmt), ap);
148 * for backend Notice messages (INFO, WARNING, etc)
151 NoticeProcessor(void *arg, const char *message)
153 (void) arg; /* not used */
154 psql_error("%s", message);
160 * Code to support query cancellation
162 * Before we start a query, we enable a SIGINT signal catcher that sends a
163 * cancel request to the backend. Note that sending the cancel directly from
164 * the signal handler is safe because PQrequestCancel() is written to make it
165 * so. We use write() to print to stdout because it's better to use simple
166 * facilities in a signal handler.
169 volatile bool cancel_pressed;
173 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
176 handle_sigint(SIGNAL_ARGS)
178 int save_errno = errno;
180 /* Don't muck around if copying in or prompting for a password. */
181 if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
184 if (cancelConn == NULL)
185 siglongjmp(main_loop_jmp, 1);
187 cancel_pressed = true;
189 if (PQrequestCancel(cancelConn))
190 write_stderr("Cancel request sent\n");
193 write_stderr("Could not send cancel request: ");
194 write_stderr(PQerrorMessage(cancelConn));
196 errno = save_errno; /* just in case the write changed it */
198 #endif /* not WIN32 */
204 * This is the way to send "backdoor" queries (those not directly entered
205 * by the user). It is subject to -E but not -e.
207 * If the given querystring generates multiple PGresults, normally the last
208 * one is returned to the caller. However, if ignore_command_ok is TRUE,
209 * then PGresults with status PGRES_COMMAND_OK are ignored. This is intended
210 * mainly to allow locutions such as "begin; select ...; commit".
213 PSQLexec(const char *query, bool ignore_command_ok)
215 PGresult *res = NULL;
218 ExecStatusType rstatus;
222 psql_error("You are currently not connected to a database.\n");
226 var = GetVariable(pset.vars, "ECHO_HIDDEN");
229 printf("********* QUERY **********\n"
231 "**************************\n\n", query);
235 if (var && strcmp(var, "noexec") == 0)
238 /* discard any uneaten results of past queries */
239 while ((newres = PQgetResult(pset.db)) != NULL)
242 cancelConn = pset.db;
243 if (PQsendQuery(pset.db, query))
245 while ((newres = PQgetResult(pset.db)) != NULL)
247 rstatus = PQresultStatus(newres);
248 if (ignore_command_ok && rstatus == PGRES_COMMAND_OK)
255 if (rstatus == PGRES_COPY_IN ||
256 rstatus == PGRES_COPY_OUT)
260 rstatus = PQresultStatus(res);
261 /* keep cancel connection for copy out state */
262 if (rstatus != PGRES_COPY_OUT)
264 if (rstatus == PGRES_COPY_IN)
265 copy_in_state = true;
267 if (res && (rstatus == PGRES_COMMAND_OK ||
268 rstatus == PGRES_TUPLES_OK ||
269 rstatus == PGRES_COPY_IN ||
270 rstatus == PGRES_COPY_OUT))
274 psql_error("%s", PQerrorMessage(pset.db));
277 if (PQstatus(pset.db) == CONNECTION_BAD)
279 if (!pset.cur_cmd_interactive)
281 psql_error("connection to server was lost\n");
284 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
286 if (PQstatus(pset.db) == CONNECTION_BAD)
288 fputs(gettext("Failed.\n"), stderr);
291 SetVariable(pset.vars, "DBNAME", NULL);
292 SetVariable(pset.vars, "HOST", NULL);
293 SetVariable(pset.vars, "PORT", NULL);
294 SetVariable(pset.vars, "USER", NULL);
295 SetVariable(pset.vars, "ENCODING", NULL);
298 fputs(gettext("Succeeded.\n"), stderr);
308 * SendQuery: send the query string to the backend
309 * (and print out results)
311 * Note: This is the "front door" way to send a query. That is, use it to
312 * send queries actually entered by the user. These queries will be subject to
314 * To send "back door" queries (generated by slash commands, etc.) in a
315 * controlled way, use PSQLexec().
317 * Returns true if the query executed successfully, false otherwise.
320 SendQuery(const char *query)
322 bool success = false;
326 struct timeval before,
329 struct _timeb before,
335 psql_error("You are currently not connected to a database.\n");
339 if (GetVariableBool(pset.vars, "SINGLESTEP"))
343 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
345 "***(press return to proceed or enter x and return to cancel)********************\n"),
348 if (fgets(buf, sizeof(buf), stdin) != NULL)
354 const char *var = GetVariable(pset.vars, "ECHO");
356 if (var && strncmp(var, "queries", strlen(var)) == 0)
360 cancelConn = pset.db;
364 gettimeofday(&before, NULL);
365 results = PQexec(pset.db, query);
367 gettimeofday(&after, NULL);
371 results = PQexec(pset.db, query);
376 if (PQresultStatus(results) == PGRES_COPY_IN)
377 copy_in_state = true;
378 /* keep cancel connection for copy out state */
379 if (PQresultStatus(results) != PGRES_COPY_OUT)
384 fputs(PQerrorMessage(pset.db), pset.queryFout);
389 switch (PQresultStatus(results))
391 case PGRES_TUPLES_OK:
392 /* write output to \g argument, if any */
395 FILE *queryFout_copy = pset.queryFout;
396 bool queryFoutPipe_copy = pset.queryFoutPipe;
398 pset.queryFout = stdout; /* so it doesn't get
402 if (!setQFout(pset.gfname))
404 pset.queryFout = queryFout_copy;
405 pset.queryFoutPipe = queryFoutPipe_copy;
410 printQuery(results, &pset.popt, pset.queryFout);
412 /* close file/pipe, restore old setting */
415 pset.queryFout = queryFout_copy;
416 pset.queryFoutPipe = queryFoutPipe_copy;
425 printQuery(results, &pset.popt, pset.queryFout);
429 case PGRES_EMPTY_QUERY:
432 case PGRES_COMMAND_OK:
437 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
439 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
440 SetVariable(pset.vars, "LASTOID", buf);
444 success = handleCopyOut(pset.db, pset.queryFout);
448 if (pset.cur_cmd_interactive && !QUIET())
449 puts(gettext("Enter data to be copied followed by a newline.\n"
450 "End with a backslash and a period on a line by itself."));
452 success = handleCopyIn(pset.db, pset.cur_cmd_source,
453 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
456 case PGRES_NONFATAL_ERROR:
457 case PGRES_FATAL_ERROR:
458 case PGRES_BAD_RESPONSE:
460 psql_error("%s", PQerrorMessage(pset.db));
464 fflush(pset.queryFout);
466 if (PQstatus(pset.db) == CONNECTION_BAD)
468 if (!pset.cur_cmd_interactive)
470 psql_error("connection to server was lost\n");
473 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
475 if (PQstatus(pset.db) == CONNECTION_BAD)
477 fputs(gettext("Failed.\n"), stderr);
481 SetVariable(pset.vars, "DBNAME", NULL);
482 SetVariable(pset.vars, "HOST", NULL);
483 SetVariable(pset.vars, "PORT", NULL);
484 SetVariable(pset.vars, "USER", NULL);
485 SetVariable(pset.vars, "ENCODING", NULL);
489 fputs(gettext("Succeeded.\n"), stderr);
492 /* check for asynchronous notification returns */
493 while ((notify = PQnotifies(pset.db)) != NULL)
495 fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
496 notify->relname, notify->be_pid);
498 fflush(pset.queryFout);
505 /* Possible microtiming output */
506 if (pset.timing && success)
508 printf(gettext("Time: %.2f ms\n"),
509 ((after.tv_sec - before.tv_sec) * 1000000.0 + after.tv_usec - before.tv_usec) / 1000.0);
511 printf(gettext("Time: %.2f ms\n"),
512 ((after.time - before.time) * 1000.0 + after.millitm - before.millitm));