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.15 2000/02/20 02:37:40 tgl Exp $
21 #include <unistd.h> /* for write() */
23 #include <io.h> /* for _write() */
28 #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).
173 simple_prompt(const char *prompt, int maxlen, bool echo)
178 #ifdef HAVE_TERMIOS_H
179 struct termios t_orig,
183 destination = (char *) malloc(maxlen + 2);
187 fputs(prompt, stdout);
189 #ifdef HAVE_TERMIOS_H
195 tcsetattr(0, TCSADRAIN, &t);
199 fgets(destination, maxlen, stdin);
201 #ifdef HAVE_TERMIOS_H
204 tcsetattr(0, TCSADRAIN, &t_orig);
209 length = strlen(destination);
210 if (length > 0 && destination[length - 1] != '\n')
212 /* eat rest of the line */
217 fgets(buf, 512, stdin);
218 } while (buf[strlen(buf) - 1] != '\n');
221 if (length > 0 && destination[length - 1] == '\n')
222 /* remove trailing newline */
223 destination[length - 1] = '\0';
231 * Code to support query cancellation
233 * Before we start a query, we enable a SIGINT signal catcher that sends a
234 * cancel request to the backend. Note that sending the cancel directly from
235 * the signal handler is safe because PQrequestCancel() is written to make it
236 * so. We use write() to print to stdout because it's better to use simple
237 * facilities in a signal handler.
240 static PGconn *cancelConn;
242 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
245 handle_sigint(SIGNAL_ARGS)
247 if (cancelConn == NULL)
249 /* Try to send cancel request */
250 if (PQrequestCancel(cancelConn))
251 write_stderr("\nCancel request sent\n");
254 write_stderr("\nCould not send cancel request: ");
255 write_stderr(PQerrorMessage(cancelConn));
264 * This is the way to send "backdoor" queries (those not directly entered
265 * by the user). It is subject to -E but not -e.
268 PSQLexec(const char *query)
275 psql_error("You are currently not connected to a database.\n");
279 var = GetVariable(pset.vars, "ECHO_HIDDEN");
282 printf("********* QUERY *********\n%s\n*************************\n\n", query);
286 if (var && strcmp(var, "noexec") == 0)
289 cancelConn = pset.db;
291 pqsignal(SIGINT, handle_sigint); /* control-C => cancel */
294 res = PQexec(pset.db, query);
297 pqsignal(SIGINT, SIG_DFL); /* now control-C is back to normal */
300 if (PQstatus(pset.db) == CONNECTION_BAD)
302 if (!pset.cur_cmd_interactive)
304 psql_error("connection to server was lost\n");
307 fputs("The connection to the server was lost. Attempting reset: ", stderr);
309 if (PQstatus(pset.db) == CONNECTION_BAD)
311 fputs("Failed.\n", stderr);
315 SetVariable(pset.vars, "DBNAME", NULL);
316 SetVariable(pset.vars, "HOST", NULL);
317 SetVariable(pset.vars, "PORT", NULL);
318 SetVariable(pset.vars, "USER", NULL);
322 fputs("Succeeded.\n", stderr);
325 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
326 PQresultStatus(res) == PGRES_TUPLES_OK ||
327 PQresultStatus(res) == PGRES_COPY_IN ||
328 PQresultStatus(res) == PGRES_COPY_OUT)
333 psql_error("%s", PQerrorMessage(pset.db));
342 * SendQuery: send the query string to the backend
343 * (and print out results)
345 * Note: This is the "front door" way to send a query. That is, use it to
346 * send queries actually entered by the user. These queries will be subject to
348 * To send "back door" queries (generated by slash commands, etc.) in a
349 * controlled way, use PSQLexec().
351 * Returns true if the query executed successfully, false otherwise.
354 SendQuery(const char *query)
356 bool success = false;
362 psql_error("you are currently not connected to a database.\n");
366 if (GetVariableBool(pset.vars, "SINGLESTEP"))
370 printf("***(Single step mode: Verify query)*********************************************\n"
372 "***(press return to proceed or enter x and return to cancel)********************\n",
375 fgets(buf, 3, stdin);
381 const char * var = GetVariable(pset.vars, "ECHO");
382 if (var && strncmp(var, "queries", strlen(var))==0)
386 cancelConn = pset.db;
388 pqsignal(SIGINT, handle_sigint);
391 results = PQexec(pset.db, query);
394 pqsignal(SIGINT, SIG_DFL);
399 fputs(PQerrorMessage(pset.db), pset.queryFout);
404 switch (PQresultStatus(results))
406 case PGRES_TUPLES_OK:
407 /* write output to \g argument, if any */
410 FILE * queryFout_copy = pset.queryFout;
411 bool queryFoutPipe_copy = pset.queryFoutPipe;
412 pset.queryFout = NULL; /* so it doesn't get closed */
415 if (!setQFout(pset.gfname))
421 printQuery(results, &pset.popt, pset.queryFout);
423 /* close file/pipe */
429 pset.queryFout = queryFout_copy;
430 pset.queryFoutPipe = queryFoutPipe_copy;
438 printQuery(results, &pset.popt, pset.queryFout);
441 case PGRES_EMPTY_QUERY:
444 case PGRES_COMMAND_OK:
449 sprintf(buf, "%u", (unsigned int)PQoidValue(results));
451 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
452 SetVariable(pset.vars, "LASTOID", buf);
456 success = handleCopyOut(pset.db, pset.queryFout);
460 if (pset.cur_cmd_interactive && !QUIET())
461 puts("Enter data to be copied followed by a newline.\n"
462 "End with a backslash and a period on a line by itself.");
464 success = handleCopyIn(pset.db, pset.cur_cmd_source,
465 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
468 case PGRES_NONFATAL_ERROR:
469 case PGRES_FATAL_ERROR:
470 case PGRES_BAD_RESPONSE:
472 psql_error("%s", PQerrorMessage(pset.db));
476 fflush(pset.queryFout);
478 if (PQstatus(pset.db) == CONNECTION_BAD)
480 if (!pset.cur_cmd_interactive)
482 psql_error("connection to server was lost\n");
485 fputs("The connection to the server was lost. Attempting reset: ", stderr);
487 if (PQstatus(pset.db) == CONNECTION_BAD)
489 fputs("Failed.\n", stderr);
493 SetVariable(pset.vars, "DBNAME", NULL);
494 SetVariable(pset.vars, "HOST", NULL);
495 SetVariable(pset.vars, "PORT", NULL);
496 SetVariable(pset.vars, "USER", NULL);
500 fputs("Succeeded.\n", stderr);
503 /* check for asynchronous notification returns */
504 while ((notify = PQnotifies(pset.db)) != NULL)
506 fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
507 notify->relname, notify->be_pid);
509 fflush(pset.queryFout);