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.43 2002/08/27 20:16:48 petere 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,after;
303 psql_error("You are currently not connected to a database.\n");
307 if (GetVariableBool(pset.vars, "SINGLESTEP"))
311 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
313 "***(press return to proceed or enter x and return to cancel)********************\n"),
316 if (fgets(buf, sizeof(buf), stdin) != NULL)
322 const char *var = GetVariable(pset.vars, "ECHO");
324 if (var && strncmp(var, "queries", strlen(var)) == 0)
328 cancelConn = pset.db;
331 gettimeofday(&before, &tz);
333 results = PQexec(pset.db, query);
336 gettimeofday(&after, &tz);
338 if (PQresultStatus(results) == PGRES_COPY_IN)
339 copy_in_state = true;
340 /* keep cancel connection for copy out state */
341 if (PQresultStatus(results) != PGRES_COPY_OUT)
346 fputs(PQerrorMessage(pset.db), pset.queryFout);
351 switch (PQresultStatus(results))
353 case PGRES_TUPLES_OK:
354 /* write output to \g argument, if any */
357 FILE *queryFout_copy = pset.queryFout;
358 bool queryFoutPipe_copy = pset.queryFoutPipe;
360 pset.queryFout = stdout; /* so it doesn't get
364 if (!setQFout(pset.gfname))
366 pset.queryFout = queryFout_copy;
367 pset.queryFoutPipe = queryFoutPipe_copy;
372 printQuery(results, &pset.popt, pset.queryFout);
374 /* close file/pipe, restore old setting */
377 pset.queryFout = queryFout_copy;
378 pset.queryFoutPipe = queryFoutPipe_copy;
387 printQuery(results, &pset.popt, pset.queryFout);
391 case PGRES_EMPTY_QUERY:
394 case PGRES_COMMAND_OK:
399 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
401 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
402 SetVariable(pset.vars, "LASTOID", buf);
406 success = handleCopyOut(pset.db, pset.queryFout);
410 if (pset.cur_cmd_interactive && !QUIET())
411 puts(gettext("Enter data to be copied followed by a newline.\n"
412 "End with a backslash and a period on a line by itself."));
414 success = handleCopyIn(pset.db, pset.cur_cmd_source,
415 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
418 case PGRES_NONFATAL_ERROR:
419 case PGRES_FATAL_ERROR:
420 case PGRES_BAD_RESPONSE:
422 psql_error("%s", PQerrorMessage(pset.db));
426 fflush(pset.queryFout);
428 if (PQstatus(pset.db) == CONNECTION_BAD)
430 if (!pset.cur_cmd_interactive)
432 psql_error("connection to server was lost\n");
435 fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
437 if (PQstatus(pset.db) == CONNECTION_BAD)
439 fputs(gettext("Failed.\n"), stderr);
443 SetVariable(pset.vars, "DBNAME", NULL);
444 SetVariable(pset.vars, "HOST", NULL);
445 SetVariable(pset.vars, "PORT", NULL);
446 SetVariable(pset.vars, "USER", NULL);
447 SetVariable(pset.vars, "ENCODING", NULL);
451 fputs(gettext("Succeeded.\n"), stderr);
454 /* check for asynchronous notification returns */
455 while ((notify = PQnotifies(pset.db)) != NULL)
457 fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
458 notify->relname, notify->be_pid);
460 fflush(pset.queryFout);
467 /* Possible microtiming output */
468 if (pset.timing && success)
469 printf(gettext("Time: %.2f ms\n"),
470 ((after.tv_sec-before.tv_sec)*1000000 + after.tv_usec - before.tv_usec) / 1000.0);