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.32 2001/04/15 00:43:37 petere 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, "%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, 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 stdin.
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;
175 simple_prompt(const char *prompt, int maxlen, bool echo)
180 #ifdef HAVE_TERMIOS_H
181 struct termios t_orig,
186 destination = (char *) malloc(maxlen + 2);
190 fputs(prompt, stderr);
194 #ifdef HAVE_TERMIOS_H
200 tcsetattr(0, TCSADRAIN, &t);
204 if (fgets(destination, maxlen, stdin) == NULL)
205 destination[0] = '\0';
207 #ifdef HAVE_TERMIOS_H
210 tcsetattr(0, TCSADRAIN, &t_orig);
215 prompt_state = false;
217 length = strlen(destination);
218 if (length > 0 && destination[length - 1] != '\n')
220 /* eat rest of the line */
226 if (fgets(buf, sizeof(buf), stdin) == NULL)
228 buflen = strlen(buf);
229 } while (buflen > 0 && buf[buflen - 1] != '\n');
232 if (length > 0 && destination[length - 1] == '\n')
233 /* remove trailing newline */
234 destination[length - 1] = '\0';
242 * Code to support query cancellation
244 * Before we start a query, we enable a SIGINT signal catcher that sends a
245 * cancel request to the backend. Note that sending the cancel directly from
246 * the signal handler is safe because PQrequestCancel() is written to make it
247 * so. We use write() to print to stdout because it's better to use simple
248 * facilities in a signal handler.
252 volatile bool cancel_pressed;
256 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
259 handle_sigint(SIGNAL_ARGS)
261 int save_errno = errno;
263 /* Don't muck around if copying in or prompting for a password. */
264 if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
267 if (cancelConn == NULL)
268 siglongjmp(main_loop_jmp, 1);
270 cancel_pressed = true;
272 if (PQrequestCancel(cancelConn))
273 write_stderr("Cancel request sent\n");
276 write_stderr("Could not send cancel request: ");
277 write_stderr(PQerrorMessage(cancelConn));
279 errno = save_errno; /* just in case the write changed it */
282 #endif /* not WIN32 */
288 * This is the way to send "backdoor" queries (those not directly entered
289 * by the user). It is subject to -E but not -e.
292 PSQLexec(const char *query)
299 psql_error("You are currently not connected to a database.\n");
303 var = GetVariable(pset.vars, "ECHO_HIDDEN");
306 printf("********* QUERY *********\n%s\n*************************\n\n", query);
310 if (var && strcmp(var, "noexec") == 0)
313 cancelConn = pset.db;
314 res = PQexec(pset.db, query);
315 if (PQresultStatus(res) == PGRES_COPY_IN)
316 copy_in_state = true;
317 /* keep cancel connection for copy out state */
318 if (PQresultStatus(res) != PGRES_COPY_OUT)
321 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
322 PQresultStatus(res) == PGRES_TUPLES_OK ||
323 PQresultStatus(res) == PGRES_COPY_IN ||
324 PQresultStatus(res) == PGRES_COPY_OUT)
329 psql_error("%s", PQerrorMessage(pset.db));
332 if (PQstatus(pset.db) == CONNECTION_BAD)
334 if (!pset.cur_cmd_interactive)
336 psql_error("connection to server was lost\n");
339 fputs("The connection to the server was lost. Attempting reset: ", stderr);
341 if (PQstatus(pset.db) == CONNECTION_BAD)
343 fputs("Failed.\n", stderr);
346 SetVariable(pset.vars, "DBNAME", NULL);
347 SetVariable(pset.vars, "HOST", NULL);
348 SetVariable(pset.vars, "PORT", NULL);
349 SetVariable(pset.vars, "USER", NULL);
350 SetVariable(pset.vars, "ENCODING", NULL);
353 fputs("Succeeded.\n", stderr);
363 * SendQuery: send the query string to the backend
364 * (and print out results)
366 * Note: This is the "front door" way to send a query. That is, use it to
367 * send queries actually entered by the user. These queries will be subject to
369 * To send "back door" queries (generated by slash commands, etc.) in a
370 * controlled way, use PSQLexec().
372 * Returns true if the query executed successfully, false otherwise.
375 SendQuery(const char *query)
377 bool success = false;
383 psql_error("You are currently not connected to a database.\n");
387 if (GetVariableBool(pset.vars, "SINGLESTEP"))
391 printf("***(Single step mode: Verify query)*********************************************\n"
393 "***(press return to proceed or enter x and return to cancel)********************\n",
396 if (fgets(buf, sizeof(buf), stdin) != NULL)
402 const char *var = GetVariable(pset.vars, "ECHO");
404 if (var && strncmp(var, "queries", strlen(var)) == 0)
408 cancelConn = pset.db;
409 results = PQexec(pset.db, query);
410 if (PQresultStatus(results) == PGRES_COPY_IN)
411 copy_in_state = true;
412 /* keep cancel connection for copy out state */
413 if (PQresultStatus(results) != PGRES_COPY_OUT)
418 fputs(PQerrorMessage(pset.db), pset.queryFout);
423 switch (PQresultStatus(results))
425 case PGRES_TUPLES_OK:
426 /* write output to \g argument, if any */
429 FILE *queryFout_copy = pset.queryFout;
430 bool queryFoutPipe_copy = pset.queryFoutPipe;
432 pset.queryFout = stdout; /* so it doesn't get
436 if (!setQFout(pset.gfname))
438 pset.queryFout = queryFout_copy;
439 pset.queryFoutPipe = queryFoutPipe_copy;
444 printQuery(results, &pset.popt, pset.queryFout);
446 /* close file/pipe, restore old setting */
449 pset.queryFout = queryFout_copy;
450 pset.queryFoutPipe = queryFoutPipe_copy;
459 printQuery(results, &pset.popt, pset.queryFout);
463 case PGRES_EMPTY_QUERY:
466 case PGRES_COMMAND_OK:
471 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
473 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
474 SetVariable(pset.vars, "LASTOID", buf);
478 success = handleCopyOut(pset.db, pset.queryFout);
482 if (pset.cur_cmd_interactive && !QUIET())
483 puts("Enter data to be copied followed by a newline.\n"
484 "End with a backslash and a period on a line by itself.");
486 success = handleCopyIn(pset.db, pset.cur_cmd_source,
487 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
490 case PGRES_NONFATAL_ERROR:
491 case PGRES_FATAL_ERROR:
492 case PGRES_BAD_RESPONSE:
494 psql_error("%s", PQerrorMessage(pset.db));
498 fflush(pset.queryFout);
500 if (PQstatus(pset.db) == CONNECTION_BAD)
502 if (!pset.cur_cmd_interactive)
504 psql_error("connection to server was lost\n");
507 fputs("The connection to the server was lost. Attempting reset: ", stderr);
509 if (PQstatus(pset.db) == CONNECTION_BAD)
511 fputs("Failed.\n", stderr);
515 SetVariable(pset.vars, "DBNAME", NULL);
516 SetVariable(pset.vars, "HOST", NULL);
517 SetVariable(pset.vars, "PORT", NULL);
518 SetVariable(pset.vars, "USER", NULL);
519 SetVariable(pset.vars, "ENCODING", NULL);
523 fputs("Succeeded.\n", stderr);
526 /* check for asynchronous notification returns */
527 while ((notify = PQnotifies(pset.db)) != NULL)
529 fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
530 notify->relname, notify->be_pid);
532 fflush(pset.queryFout);