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.44 2002/09/04 20:31:35 momjian Exp $
8 #include "postgres_fe.h"
20 #include <unistd.h> /* for write() */
23 #include <io.h> /* for _write() */
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 INFO, WARNING, ERROR
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.
208 PSQLexec(const char *query)
215 psql_error("You are currently not connected to a database.\n");
219 var = GetVariable(pset.vars, "ECHO_HIDDEN");
222 printf("********* QUERY **********\n"
224 "**************************\n\n", query);
228 if (var && strcmp(var, "noexec") == 0)
231 cancelConn = pset.db;
232 res = PQexec(pset.db, query);
233 if (PQresultStatus(res) == PGRES_COPY_IN)
234 copy_in_state = true;
235 /* keep cancel connection for copy out state */
236 if (PQresultStatus(res) != PGRES_COPY_OUT)
239 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
240 PQresultStatus(res) == PGRES_TUPLES_OK ||
241 PQresultStatus(res) == PGRES_COPY_IN ||
242 PQresultStatus(res) == PGRES_COPY_OUT)
247 psql_error("%s", PQerrorMessage(pset.db));
250 if (PQstatus(pset.db) == CONNECTION_BAD)
252 if (!pset.cur_cmd_interactive)
254 psql_error("connection to server was lost\n");
257 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
259 if (PQstatus(pset.db) == CONNECTION_BAD)
261 fputs(gettext("Failed.\n"), stderr);
264 SetVariable(pset.vars, "DBNAME", NULL);
265 SetVariable(pset.vars, "HOST", NULL);
266 SetVariable(pset.vars, "PORT", NULL);
267 SetVariable(pset.vars, "USER", NULL);
268 SetVariable(pset.vars, "ENCODING", NULL);
271 fputs(gettext("Succeeded.\n"), stderr);
281 * SendQuery: send the query string to the backend
282 * (and print out results)
284 * Note: This is the "front door" way to send a query. That is, use it to
285 * send queries actually entered by the user. These queries will be subject to
287 * To send "back door" queries (generated by slash commands, etc.) in a
288 * controlled way, use PSQLexec().
290 * Returns true if the query executed successfully, false otherwise.
293 SendQuery(const char *query)
295 bool success = false;
298 struct timeval before,
304 psql_error("You are currently not connected to a database.\n");
308 if (GetVariableBool(pset.vars, "SINGLESTEP"))
312 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
314 "***(press return to proceed or enter x and return to cancel)********************\n"),
317 if (fgets(buf, sizeof(buf), stdin) != NULL)
323 const char *var = GetVariable(pset.vars, "ECHO");
325 if (var && strncmp(var, "queries", strlen(var)) == 0)
329 cancelConn = pset.db;
331 gettimeofday(&before, &tz);
332 results = PQexec(pset.db, query);
334 gettimeofday(&after, &tz);
335 if (PQresultStatus(results) == PGRES_COPY_IN)
336 copy_in_state = true;
337 /* keep cancel connection for copy out state */
338 if (PQresultStatus(results) != PGRES_COPY_OUT)
343 fputs(PQerrorMessage(pset.db), pset.queryFout);
348 switch (PQresultStatus(results))
350 case PGRES_TUPLES_OK:
351 /* write output to \g argument, if any */
354 FILE *queryFout_copy = pset.queryFout;
355 bool queryFoutPipe_copy = pset.queryFoutPipe;
357 pset.queryFout = stdout; /* so it doesn't get
361 if (!setQFout(pset.gfname))
363 pset.queryFout = queryFout_copy;
364 pset.queryFoutPipe = queryFoutPipe_copy;
369 printQuery(results, &pset.popt, pset.queryFout);
371 /* close file/pipe, restore old setting */
374 pset.queryFout = queryFout_copy;
375 pset.queryFoutPipe = queryFoutPipe_copy;
384 printQuery(results, &pset.popt, pset.queryFout);
388 case PGRES_EMPTY_QUERY:
391 case PGRES_COMMAND_OK:
396 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
398 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
399 SetVariable(pset.vars, "LASTOID", buf);
403 success = handleCopyOut(pset.db, pset.queryFout);
407 if (pset.cur_cmd_interactive && !QUIET())
408 puts(gettext("Enter data to be copied followed by a newline.\n"
409 "End with a backslash and a period on a line by itself."));
411 success = handleCopyIn(pset.db, pset.cur_cmd_source,
412 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
415 case PGRES_NONFATAL_ERROR:
416 case PGRES_FATAL_ERROR:
417 case PGRES_BAD_RESPONSE:
419 psql_error("%s", PQerrorMessage(pset.db));
423 fflush(pset.queryFout);
425 if (PQstatus(pset.db) == CONNECTION_BAD)
427 if (!pset.cur_cmd_interactive)
429 psql_error("connection to server was lost\n");
432 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
434 if (PQstatus(pset.db) == CONNECTION_BAD)
436 fputs(gettext("Failed.\n"), stderr);
440 SetVariable(pset.vars, "DBNAME", NULL);
441 SetVariable(pset.vars, "HOST", NULL);
442 SetVariable(pset.vars, "PORT", NULL);
443 SetVariable(pset.vars, "USER", NULL);
444 SetVariable(pset.vars, "ENCODING", NULL);
448 fputs(gettext("Succeeded.\n"), stderr);
451 /* check for asynchronous notification returns */
452 while ((notify = PQnotifies(pset.db)) != NULL)
454 fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
455 notify->relname, notify->be_pid);
457 fflush(pset.queryFout);
464 /* Possible microtiming output */
465 if (pset.timing && success)
466 printf(gettext("Time: %.2f ms\n"),
467 ((after.tv_sec - before.tv_sec) * 1000000 + after.tv_usec - before.tv_usec) / 1000.0);