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.11 2000/01/29 16:58:48 petere Exp $
24 #include <unistd.h> /* for write() */
26 #include <io.h> /* for _write() */
30 #include <postgres_ext.h>
35 #include "variables.h"
41 #define popen(x,y) _popen(x,y)
42 #define pclose(x) _pclose(x)
43 #define write(a,b,c) _write(a,b,c)
50 * "Safe" wrapper around strdup()
51 * (Using this also avoids writing #ifdef HAVE_STRDUP in every file :)
54 xstrdup(const char *string)
60 fprintf(stderr, "%s: xstrdup: cannot duplicate null pointer\n", pset.progname);
66 psql_error("out of memory\n");
76 * -- handler for -o command line option and \o command
78 * Tries to open file fname (or pipe if fname starts with '|')
79 * and stores the file handle in pset)
80 * Upon failure, sets stdout and returns false.
83 setQFout(const char *fname)
87 /* Close old file/pipe */
88 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
90 if (pset.queryFoutPipe)
91 pclose(pset.queryFout);
93 fclose(pset.queryFout);
96 /* If no filename, set stdout */
97 if (!fname || fname[0] == '\0')
99 pset.queryFout = stdout;
100 pset.queryFoutPipe = false;
102 else if (*fname == '|')
104 pset.queryFout = popen(fname + 1, "w");
105 pset.queryFoutPipe = true;
109 pset.queryFout = fopen(fname, "w");
110 pset.queryFoutPipe = false;
113 if (!(pset.queryFout))
115 psql_error("%s: %s\n", fname, strerror(errno));
116 pset.queryFout = stdout;
117 pset.queryFoutPipe = false;
123 if (pset.queryFoutPipe)
124 pqsignal(SIGPIPE, SIG_IGN);
126 pqsignal(SIGPIPE, SIG_DFL);
135 * Error reporting for scripts. Errors should look like
136 * filename:lineno: message
140 psql_error(const char *fmt, ...)
145 if (pset.queryFout!=stdout)
146 fflush(pset.queryFout);
149 fprintf(stderr, "%s:%s:%u: ", pset.progname, pset.inputfile, pset.lineno);
151 vfprintf(stderr, fmt, ap);
155 /* for backend NOTICES */
158 NoticeProcessor(void * arg, const char * message)
160 (void)arg; /* not used */
161 psql_error("%s", message);
169 * Generalized function especially intended for reading in usernames and
170 * password interactively. Reads from stdin.
172 * prompt: The prompt to print
173 * maxlen: How many characters to accept
174 * echo: Set to false if you want to hide what is entered (for passwords)
176 * Returns a malloc()'ed string with the input (w/o trailing newline).
179 simple_prompt(const char *prompt, int maxlen, bool echo)
184 #ifdef HAVE_TERMIOS_H
185 struct termios t_orig,
190 destination = (char *) malloc(maxlen + 2);
194 fputs(prompt, stdout);
196 #ifdef HAVE_TERMIOS_H
202 tcsetattr(0, TCSADRAIN, &t);
206 fgets(destination, maxlen, stdin);
208 #ifdef HAVE_TERMIOS_H
211 tcsetattr(0, TCSADRAIN, &t_orig);
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 have to be very careful what else we do in the signal handler. This
244 * includes using write() for output.
247 static PGconn *cancelConn;
249 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
252 handle_sigint(SIGNAL_ARGS)
254 if (cancelConn == NULL)
256 /* Try to send cancel request */
257 if (PQrequestCancel(cancelConn))
258 write_stderr("\nCancel request sent\n");
261 write_stderr("\nCould not send cancel request: ");
262 write_stderr(PQerrorMessage(cancelConn));
271 * This is the way to send "backdoor" queries (those not directly entered
272 * by the user). It is subject to -E but not -e.
275 PSQLexec(const char *query)
282 psql_error("You are currently not connected to a database.\n");
286 var = GetVariable(pset.vars, "ECHO_HIDDEN");
289 printf("********* QUERY *********\n%s\n*************************\n\n", query);
293 if (var && strcmp(var, "noexec") == 0)
296 cancelConn = pset.db;
298 pqsignal(SIGINT, handle_sigint); /* control-C => cancel */
301 res = PQexec(pset.db, query);
304 pqsignal(SIGINT, SIG_DFL); /* now control-C is back to normal */
307 if (PQstatus(pset.db) == CONNECTION_BAD)
309 if (!pset.cur_cmd_interactive)
311 psql_error("connection to server was lost");
314 fputs("The connection to the server was lost. Attempting reset: ", stderr);
316 if (PQstatus(pset.db) == CONNECTION_BAD)
318 fputs("Failed.\n", stderr);
322 SetVariable(pset.vars, "DBNAME", NULL);
323 SetVariable(pset.vars, "HOST", NULL);
324 SetVariable(pset.vars, "PORT", NULL);
325 SetVariable(pset.vars, "USER", NULL);
329 fputs("Succeeded.\n", stderr);
332 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
333 PQresultStatus(res) == PGRES_TUPLES_OK ||
334 PQresultStatus(res) == PGRES_COPY_IN ||
335 PQresultStatus(res) == PGRES_COPY_OUT)
340 psql_error("%s", PQerrorMessage(pset.db));
349 * SendQuery: send the query string to the backend
350 * (and print out results)
352 * Note: This is the "front door" way to send a query. That is, use it to
353 * send queries actually entered by the user. These queries will be subject to
355 * To send "back door" queries (generated by slash commands, etc.) in a
356 * controlled way, use PSQLexec().
358 * Returns true if the query executed successfully, false otherwise.
361 SendQuery(const char *query)
363 bool success = false;
369 psql_error("you are currently not connected to a database.\n");
373 if (GetVariableBool(pset.vars, "SINGLESTEP"))
377 printf("***(Single step mode: Verify query)*********************************************\n"
379 "***(press return to proceed or enter x and return to cancel)********************\n",
382 fgets(buf, 3, stdin);
388 const char * var = GetVariable(pset.vars, "ECHO");
389 if (var && strcmp(var, "brief")==0)
393 cancelConn = pset.db;
395 pqsignal(SIGINT, handle_sigint);
398 results = PQexec(pset.db, query);
401 pqsignal(SIGINT, SIG_DFL);
406 fputs(PQerrorMessage(pset.db), pset.queryFout);
411 switch (PQresultStatus(results))
413 case PGRES_TUPLES_OK:
414 /* write output to \g argument, if any */
417 FILE * queryFout_copy = pset.queryFout;
418 bool queryFoutPipe_copy = pset.queryFoutPipe;
419 pset.queryFout = NULL; /* so it doesn't get closed */
422 if (!setQFout(pset.gfname))
428 printQuery(results, &pset.popt, pset.queryFout);
430 /* close file/pipe */
436 pset.queryFout = queryFout_copy;
437 pset.queryFoutPipe = queryFoutPipe_copy;
445 printQuery(results, &pset.popt, pset.queryFout);
448 case PGRES_EMPTY_QUERY:
451 case PGRES_COMMAND_OK:
456 sprintf(buf, "%u", (unsigned int)PQoidValue(results));
458 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
459 SetVariable(pset.vars, "LASTOID", buf);
463 success = handleCopyOut(pset.db, pset.queryFout);
467 if (pset.cur_cmd_interactive && !QUIET())
468 puts("Enter data to be copied followed by a newline.\n"
469 "End with a backslash and a period on a line by itself.");
471 success = handleCopyIn(pset.db, pset.cur_cmd_source,
472 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
475 case PGRES_NONFATAL_ERROR:
476 case PGRES_FATAL_ERROR:
477 case PGRES_BAD_RESPONSE:
479 psql_error("%s", PQerrorMessage(pset.db));
483 fflush(pset.queryFout);
485 if (PQstatus(pset.db) == CONNECTION_BAD)
487 if (!pset.cur_cmd_interactive)
489 psql_error("connection to server was lost");
492 fputs("The connection to the server was lost. Attempting reset: ", stderr);
494 if (PQstatus(pset.db) == CONNECTION_BAD)
496 fputs("Failed.\n", stderr);
500 SetVariable(pset.vars, "DBNAME", NULL);
501 SetVariable(pset.vars, "HOST", NULL);
502 SetVariable(pset.vars, "PORT", NULL);
503 SetVariable(pset.vars, "USER", NULL);
507 fputs("Succeeded.\n", stderr);
510 /* check for asynchronous notification returns */
511 while ((notify = PQnotifies(pset.db)) != NULL)
513 fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
514 notify->relname, notify->be_pid);
516 fflush(pset.queryFout);