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.24 2000/11/13 15:18:14 momjian Exp $
21 #include <unistd.h> /* for write() */
24 #include <io.h> /* for _write() */
29 #include "postgres_ext.h"
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 fgets(destination, maxlen, stdin);
206 #ifdef HAVE_TERMIOS_H
209 tcsetattr(0, TCSADRAIN, &t_orig);
214 prompt_state = false;
216 length = strlen(destination);
217 if (length > 0 && destination[length - 1] != '\n')
219 /* eat rest of the line */
224 fgets(buf, 512, stdin);
225 } while (buf[strlen(buf) - 1] != '\n');
228 if (length > 0 && destination[length - 1] == '\n')
229 /* remove trailing newline */
230 destination[length - 1] = '\0';
238 * Code to support query cancellation
240 * Before we start a query, we enable a SIGINT signal catcher that sends a
241 * cancel request to the backend. Note that sending the cancel directly from
242 * the signal handler is safe because PQrequestCancel() is written to make it
243 * so. We use write() to print to stdout because it's better to use simple
244 * facilities in a signal handler.
248 volatile bool cancel_pressed;
252 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
255 handle_sigint(SIGNAL_ARGS)
257 /* Don't muck around if copying in or prompting for a password. */
258 if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
261 if (cancelConn == NULL)
262 siglongjmp(main_loop_jmp, 1);
264 cancel_pressed = true;
266 if (PQrequestCancel(cancelConn))
267 write_stderr("Cancel request sent\n");
270 write_stderr("Could not send cancel request: ");
271 write_stderr(PQerrorMessage(cancelConn));
275 #endif /* not WIN32 */
281 * This is the way to send "backdoor" queries (those not directly entered
282 * by the user). It is subject to -E but not -e.
285 PSQLexec(const char *query)
292 psql_error("You are currently not connected to a database.\n");
296 var = GetVariable(pset.vars, "ECHO_HIDDEN");
299 printf("********* QUERY *********\n%s\n*************************\n\n", query);
303 if (var && strcmp(var, "noexec") == 0)
306 cancelConn = pset.db;
307 res = PQexec(pset.db, query);
308 if (PQresultStatus(res) == PGRES_COPY_IN)
309 copy_in_state = true;
310 /* keep cancel connection for copy out state */
311 if (PQresultStatus(res) != PGRES_COPY_OUT)
314 if (PQstatus(pset.db) == CONNECTION_BAD)
316 if (!pset.cur_cmd_interactive)
318 psql_error("connection to server was lost\n");
321 fputs("The connection to the server was lost. Attempting reset: ", stderr);
323 if (PQstatus(pset.db) == CONNECTION_BAD)
325 fputs("Failed.\n", stderr);
329 SetVariable(pset.vars, "DBNAME", NULL);
330 SetVariable(pset.vars, "HOST", NULL);
331 SetVariable(pset.vars, "PORT", NULL);
332 SetVariable(pset.vars, "UNIXSOCKET", NULL);
333 SetVariable(pset.vars, "USER", NULL);
334 SetVariable(pset.vars, "ENCODING", NULL);
338 fputs("Succeeded.\n", stderr);
341 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
342 PQresultStatus(res) == PGRES_TUPLES_OK ||
343 PQresultStatus(res) == PGRES_COPY_IN ||
344 PQresultStatus(res) == PGRES_COPY_OUT)
349 psql_error("%s", PQerrorMessage(pset.db));
358 * SendQuery: send the query string to the backend
359 * (and print out results)
361 * Note: This is the "front door" way to send a query. That is, use it to
362 * send queries actually entered by the user. These queries will be subject to
364 * To send "back door" queries (generated by slash commands, etc.) in a
365 * controlled way, use PSQLexec().
367 * Returns true if the query executed successfully, false otherwise.
370 SendQuery(const char *query)
372 bool success = false;
378 psql_error("You are currently not connected to a database.\n");
382 if (GetVariableBool(pset.vars, "SINGLESTEP"))
386 printf("***(Single step mode: Verify query)*********************************************\n"
388 "***(press return to proceed or enter x and return to cancel)********************\n",
391 fgets(buf, 3, stdin);
397 const char *var = GetVariable(pset.vars, "ECHO");
399 if (var && strncmp(var, "queries", strlen(var)) == 0)
403 cancelConn = pset.db;
404 results = PQexec(pset.db, query);
405 if (PQresultStatus(results) == PGRES_COPY_IN)
406 copy_in_state = true;
407 /* keep cancel connection for copy out state */
408 if (PQresultStatus(results) != PGRES_COPY_OUT)
413 fputs(PQerrorMessage(pset.db), pset.queryFout);
418 switch (PQresultStatus(results))
420 case PGRES_TUPLES_OK:
421 /* write output to \g argument, if any */
424 FILE *queryFout_copy = pset.queryFout;
425 bool queryFoutPipe_copy = pset.queryFoutPipe;
427 pset.queryFout = NULL; /* so it doesn't get
431 if (!setQFout(pset.gfname))
437 printQuery(results, &pset.popt, pset.queryFout);
439 /* close file/pipe */
445 pset.queryFout = queryFout_copy;
446 pset.queryFoutPipe = queryFoutPipe_copy;
454 printQuery(results, &pset.popt, pset.queryFout);
457 case PGRES_EMPTY_QUERY:
460 case PGRES_COMMAND_OK:
465 sprintf(buf, "%u", (unsigned int) PQoidValue(results));
467 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
468 SetVariable(pset.vars, "LASTOID", buf);
472 success = handleCopyOut(pset.db, pset.queryFout);
476 if (pset.cur_cmd_interactive && !QUIET())
477 puts("Enter data to be copied followed by a newline.\n"
478 "End with a backslash and a period on a line by itself.");
480 success = handleCopyIn(pset.db, pset.cur_cmd_source,
481 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
484 case PGRES_NONFATAL_ERROR:
485 case PGRES_FATAL_ERROR:
486 case PGRES_BAD_RESPONSE:
488 psql_error("%s", PQerrorMessage(pset.db));
492 fflush(pset.queryFout);
494 if (PQstatus(pset.db) == CONNECTION_BAD)
496 if (!pset.cur_cmd_interactive)
498 psql_error("connection to server was lost\n");
501 fputs("The connection to the server was lost. Attempting reset: ", stderr);
503 if (PQstatus(pset.db) == CONNECTION_BAD)
505 fputs("Failed.\n", stderr);
509 SetVariable(pset.vars, "DBNAME", NULL);
510 SetVariable(pset.vars, "HOST", NULL);
511 SetVariable(pset.vars, "PORT", NULL);
512 SetVariable(pset.vars, "UNIXSOCKET", NULL);
513 SetVariable(pset.vars, "USER", NULL);
514 SetVariable(pset.vars, "ENCODING", NULL);
518 fputs("Succeeded.\n", stderr);
521 /* check for asynchronous notification returns */
522 while ((notify = PQnotifies(pset.db)) != NULL)
524 fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
525 notify->relname, notify->be_pid);
527 fflush(pset.queryFout);