]> granicus.if.org Git - postgresql/blob - src/bin/psql/common.c
Page \h output and centralize psql paging code in PageOutput().
[postgresql] / src / bin / psql / common.c
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright 2000 by PostgreSQL Global Development Group
5  *
6  * $Header: /cvsroot/pgsql/src/bin/psql/common.c,v 1.49 2002/10/23 19:23:56 momjian Exp $
7  */
8 #include "postgres_fe.h"
9
10 #include "common.h"
11
12 #include <errno.h>
13 #include <stdarg.h>
14 #ifndef HAVE_STRDUP
15 #include <strdup.h>
16 #endif
17 #include <signal.h>
18 #ifndef WIN32
19 #include <sys/time.h>
20 #include <unistd.h>                             /* for write() */
21 #include <setjmp.h>
22 #else
23 #include <io.h>                                 /* for _write() */
24 #include <win32.h>
25 #include <sys/timeb.h>                  /* for _ftime() */
26 #endif
27
28 #include "libpq-fe.h"
29 #include "pqsignal.h"
30
31 #include "settings.h"
32 #include "variables.h"
33 #include "copy.h"
34 #include "prompt.h"
35 #include "print.h"
36 #include "mainloop.h"
37
38 extern bool prompt_state;
39
40 /*
41  * "Safe" wrapper around strdup()
42  */
43 char *
44 xstrdup(const char *string)
45 {
46         char       *tmp;
47
48         if (!string)
49         {
50                 fprintf(stderr, gettext("%s: xstrdup: cannot duplicate null pointer (internal error)\n"),
51                                 pset.progname);
52                 exit(EXIT_FAILURE);
53         }
54         tmp = strdup(string);
55         if (!tmp)
56         {
57                 psql_error("out of memory\n");
58                 exit(EXIT_FAILURE);
59         }
60         return tmp;
61 }
62
63
64
65 /*
66  * setQFout
67  * -- handler for -o command line option and \o command
68  *
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.
72  */
73 bool
74 setQFout(const char *fname)
75 {
76         bool            status = true;
77
78         /* Close old file/pipe */
79         if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
80         {
81                 if (pset.queryFoutPipe)
82                         pclose(pset.queryFout);
83                 else
84                         fclose(pset.queryFout);
85         }
86
87         /* If no filename, set stdout */
88         if (!fname || fname[0] == '\0')
89         {
90                 pset.queryFout = stdout;
91                 pset.queryFoutPipe = false;
92         }
93         else if (*fname == '|')
94         {
95                 pset.queryFout = popen(fname + 1, "w");
96                 pset.queryFoutPipe = true;
97         }
98         else
99         {
100                 pset.queryFout = fopen(fname, "w");
101                 pset.queryFoutPipe = false;
102         }
103
104         if (!(pset.queryFout))
105         {
106                 psql_error("%s: %s\n", fname, strerror(errno));
107                 pset.queryFout = stdout;
108                 pset.queryFoutPipe = false;
109                 status = false;
110         }
111
112         /* Direct signals */
113 #ifndef WIN32
114         if (pset.queryFoutPipe)
115                 pqsignal(SIGPIPE, SIG_IGN);
116         else
117                 pqsignal(SIGPIPE, SIG_DFL);
118 #endif
119
120         return status;
121 }
122
123
124
125 /*
126  * Error reporting for scripts. Errors should look like
127  *       psql:filename:lineno: message
128  *
129  */
130 void
131 psql_error(const char *fmt,...)
132 {
133         va_list         ap;
134
135         fflush(stdout);
136         if (pset.queryFout != stdout)
137                 fflush(pset.queryFout);
138
139         if (pset.inputfile)
140                 fprintf(stderr, "%s:%s:%u: ", pset.progname, pset.inputfile, pset.lineno);
141         va_start(ap, fmt);
142         vfprintf(stderr, gettext(fmt), ap);
143         va_end(ap);
144 }
145
146
147
148 /*
149  * for backend INFO, WARNING, ERROR
150  */
151 void
152 NoticeProcessor(void *arg, const char *message)
153 {
154         (void) arg;                                     /* not used */
155         psql_error("%s", message);
156 }
157
158
159
160 /*
161  * Code to support query cancellation
162  *
163  * Before we start a query, we enable a SIGINT signal catcher that sends a
164  * cancel request to the backend. Note that sending the cancel directly from
165  * the signal handler is safe because PQrequestCancel() is written to make it
166  * so. We use write() to print to stdout because it's better to use simple
167  * facilities in a signal handler.
168  */
169 PGconn     *cancelConn;
170 volatile bool cancel_pressed;
171
172 #ifndef WIN32
173
174 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
175
176 void
177 handle_sigint(SIGNAL_ARGS)
178 {
179         int                     save_errno = errno;
180
181         /* Don't muck around if copying in or prompting for a password. */
182         if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
183                 return;
184
185         if (cancelConn == NULL)
186                 siglongjmp(main_loop_jmp, 1);
187
188         cancel_pressed = true;
189
190         if (PQrequestCancel(cancelConn))
191                 write_stderr("Cancel request sent\n");
192         else
193         {
194                 write_stderr("Could not send cancel request: ");
195                 write_stderr(PQerrorMessage(cancelConn));
196         }
197         errno = save_errno;                     /* just in case the write changed it */
198 }
199 #endif   /* not WIN32 */
200
201
202 /*
203  * PSQLexec
204  *
205  * This is the way to send "backdoor" queries (those not directly entered
206  * by the user). It is subject to -E but not -e.
207  *
208  * If the given querystring generates multiple PGresults, normally the last
209  * one is returned to the caller.  However, if ignore_command_ok is TRUE,
210  * then PGresults with status PGRES_COMMAND_OK are ignored.  This is intended
211  * mainly to allow locutions such as "begin; select ...; commit".
212  */
213 PGresult *
214 PSQLexec(const char *query, bool ignore_command_ok)
215 {
216         PGresult   *res = NULL;
217         PGresult   *newres;
218         const char *var;
219         ExecStatusType rstatus;
220
221         if (!pset.db)
222         {
223                 psql_error("You are currently not connected to a database.\n");
224                 return NULL;
225         }
226
227         var = GetVariable(pset.vars, "ECHO_HIDDEN");
228         if (var)
229         {
230                 printf("********* QUERY **********\n"
231                            "%s\n"
232                            "**************************\n\n", query);
233                 fflush(stdout);
234         }
235
236         if (var && strcmp(var, "noexec") == 0)
237                 return NULL;
238
239         /* discard any uneaten results of past queries */
240         while ((newres = PQgetResult(pset.db)) != NULL)
241                 PQclear(newres);
242
243         cancelConn = pset.db;
244         if (PQsendQuery(pset.db, query))
245         {
246                 while ((newres = PQgetResult(pset.db)) != NULL)
247                 {
248                         rstatus = PQresultStatus(newres);
249                         if (ignore_command_ok && rstatus == PGRES_COMMAND_OK)
250                         {
251                                 PQclear(newres);
252                                 continue;
253                         }
254                         PQclear(res);
255                         res = newres;
256                         if (rstatus == PGRES_COPY_IN ||
257                                 rstatus == PGRES_COPY_OUT)
258                                 break;
259                 }
260         }
261         rstatus = PQresultStatus(res);
262         /* keep cancel connection for copy out state */
263         if (rstatus != PGRES_COPY_OUT)
264                 cancelConn = NULL;
265         if (rstatus == PGRES_COPY_IN)
266                 copy_in_state = true;
267
268         if (res && (rstatus == PGRES_COMMAND_OK ||
269                                 rstatus == PGRES_TUPLES_OK ||
270                                 rstatus == PGRES_COPY_IN ||
271                                 rstatus == PGRES_COPY_OUT))
272                 return res;
273         else
274         {
275                 psql_error("%s", PQerrorMessage(pset.db));
276                 PQclear(res);
277
278                 if (PQstatus(pset.db) == CONNECTION_BAD)
279                 {
280                         if (!pset.cur_cmd_interactive)
281                         {
282                                 psql_error("connection to server was lost\n");
283                                 exit(EXIT_BADCONN);
284                         }
285                         fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
286                         PQreset(pset.db);
287                         if (PQstatus(pset.db) == CONNECTION_BAD)
288                         {
289                                 fputs(gettext("Failed.\n"), stderr);
290                                 PQfinish(pset.db);
291                                 pset.db = NULL;
292                                 SetVariable(pset.vars, "DBNAME", NULL);
293                                 SetVariable(pset.vars, "HOST", NULL);
294                                 SetVariable(pset.vars, "PORT", NULL);
295                                 SetVariable(pset.vars, "USER", NULL);
296                                 SetVariable(pset.vars, "ENCODING", NULL);
297                         }
298                         else
299                                 fputs(gettext("Succeeded.\n"), stderr);
300                 }
301
302                 return NULL;
303         }
304 }
305
306
307
308 /*
309  * SendQuery: send the query string to the backend
310  * (and print out results)
311  *
312  * Note: This is the "front door" way to send a query. That is, use it to
313  * send queries actually entered by the user. These queries will be subject to
314  * single step mode.
315  * To send "back door" queries (generated by slash commands, etc.) in a
316  * controlled way, use PSQLexec().
317  *
318  * Returns true if the query executed successfully, false otherwise.
319  */
320 bool
321 SendQuery(const char *query)
322 {
323         bool            success = false;
324         PGresult   *results;
325         PGnotify   *notify;
326 #ifndef WIN32
327         struct timeval before,
328                                 after;
329 #else
330         struct _timeb before,
331                                 after;
332 #endif
333
334         if (!pset.db)
335         {
336                 psql_error("You are currently not connected to a database.\n");
337                 return false;
338         }
339
340         if (GetVariableBool(pset.vars, "SINGLESTEP"))
341         {
342                 char            buf[3];
343
344                 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
345                                            "%s\n"
346                                            "***(press return to proceed or enter x and return to cancel)********************\n"),
347                            query);
348                 fflush(stdout);
349                 if (fgets(buf, sizeof(buf), stdin) != NULL)
350                         if (buf[0] == 'x')
351                                 return false;
352         }
353         else
354         {
355                 const char *var = GetVariable(pset.vars, "ECHO");
356
357                 if (var && strncmp(var, "queries", strlen(var)) == 0)
358                         puts(query);
359         }
360
361         cancelConn = pset.db;
362
363 #ifndef WIN32
364         if (pset.timing)
365                 gettimeofday(&before, NULL);
366         results = PQexec(pset.db, query);
367         if (pset.timing)
368                 gettimeofday(&after, NULL);
369 #else
370         if (pset.timing)
371                 _ftime(&before);
372         results = PQexec(pset.db, query);
373         if (pset.timing)
374                 _ftime(&after);
375 #endif
376
377         if (PQresultStatus(results) == PGRES_COPY_IN)
378                 copy_in_state = true;
379         /* keep cancel connection for copy out state */
380         if (PQresultStatus(results) != PGRES_COPY_OUT)
381                 cancelConn = NULL;
382
383         if (results == NULL)
384         {
385                 fputs(PQerrorMessage(pset.db), pset.queryFout);
386                 success = false;
387         }
388         else
389         {
390                 switch (PQresultStatus(results))
391                 {
392                         case PGRES_TUPLES_OK:
393                                 /* write output to \g argument, if any */
394                                 if (pset.gfname)
395                                 {
396                                         FILE       *queryFout_copy = pset.queryFout;
397                                         bool            queryFoutPipe_copy = pset.queryFoutPipe;
398
399                                         pset.queryFout = stdout;        /* so it doesn't get
400                                                                                                  * closed */
401
402                                         /* open file/pipe */
403                                         if (!setQFout(pset.gfname))
404                                         {
405                                                 pset.queryFout = queryFout_copy;
406                                                 pset.queryFoutPipe = queryFoutPipe_copy;
407                                                 success = false;
408                                                 break;
409                                         }
410
411                                         printQuery(results, &pset.popt, pset.queryFout);
412
413                                         /* close file/pipe, restore old setting */
414                                         setQFout(NULL);
415
416                                         pset.queryFout = queryFout_copy;
417                                         pset.queryFoutPipe = queryFoutPipe_copy;
418
419                                         free(pset.gfname);
420                                         pset.gfname = NULL;
421
422                                         success = true;
423                                 }
424                                 else
425                                 {
426                                         printQuery(results, &pset.popt, pset.queryFout);
427                                         success = true;
428                                 }
429                                 break;
430                         case PGRES_EMPTY_QUERY:
431                                 success = true;
432                                 break;
433                         case PGRES_COMMAND_OK:
434                                 {
435                                         char            buf[10];
436
437                                         success = true;
438                                         sprintf(buf, "%u", (unsigned int) PQoidValue(results));
439                                         if (!QUIET())
440                                                 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
441                                         SetVariable(pset.vars, "LASTOID", buf);
442                                         break;
443                                 }
444                         case PGRES_COPY_OUT:
445                                 success = handleCopyOut(pset.db, pset.queryFout);
446                                 break;
447
448                         case PGRES_COPY_IN:
449                                 if (pset.cur_cmd_interactive && !QUIET())
450                                         puts(gettext("Enter data to be copied followed by a newline.\n"
451                                                                  "End with a backslash and a period on a line by itself."));
452
453                                 success = handleCopyIn(pset.db, pset.cur_cmd_source,
454                                                                            pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
455                                 break;
456
457                         case PGRES_NONFATAL_ERROR:
458                         case PGRES_FATAL_ERROR:
459                         case PGRES_BAD_RESPONSE:
460                                 success = false;
461                                 psql_error("%s", PQerrorMessage(pset.db));
462                                 break;
463                 }
464
465                 fflush(pset.queryFout);
466
467                 if (PQstatus(pset.db) == CONNECTION_BAD)
468                 {
469                         if (!pset.cur_cmd_interactive)
470                         {
471                                 psql_error("connection to server was lost\n");
472                                 exit(EXIT_BADCONN);
473                         }
474                         fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
475                         PQreset(pset.db);
476                         if (PQstatus(pset.db) == CONNECTION_BAD)
477                         {
478                                 fputs(gettext("Failed.\n"), stderr);
479                                 PQfinish(pset.db);
480                                 PQclear(results);
481                                 pset.db = NULL;
482                                 SetVariable(pset.vars, "DBNAME", NULL);
483                                 SetVariable(pset.vars, "HOST", NULL);
484                                 SetVariable(pset.vars, "PORT", NULL);
485                                 SetVariable(pset.vars, "USER", NULL);
486                                 SetVariable(pset.vars, "ENCODING", NULL);
487                                 return false;
488                         }
489                         else
490                                 fputs(gettext("Succeeded.\n"), stderr);
491                 }
492
493                 /* check for asynchronous notification returns */
494                 while ((notify = PQnotifies(pset.db)) != NULL)
495                 {
496                         fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
497                                         notify->relname, notify->be_pid);
498                         free(notify);
499                         fflush(pset.queryFout);
500                 }
501
502                 if (results)
503                         PQclear(results);
504         }
505
506         /* Possible microtiming output */
507         if (pset.timing && success)
508 #ifndef WIN32
509                 printf(gettext("Time: %.2f ms\n"),
510                            ((after.tv_sec - before.tv_sec) * 1000000.0 + after.tv_usec - before.tv_usec) / 1000.0);
511 #else
512                 printf(gettext("Time: %.2f ms\n"),
513                            ((after.time - before.time) * 1000.0 + after.millitm - before.millitm));
514 #endif
515
516         return success;
517 }
518
519
520 /*
521  * PageOutput
522  *
523  * Tests if pager is needed and returns appropriate FILE pointer.
524  */
525 FILE *
526 PageOutput(int lines, bool pager)
527 {
528         /* check whether we need / can / are supposed to use pager */
529         if (pager
530 #ifndef WIN32
531                 &&
532                 isatty(fileno(stdin)) &&
533                 isatty(fileno(stdout))
534 #endif
535                 )
536         {
537                 const char *pagerprog;
538
539 #ifdef TIOCGWINSZ
540                 int                     result;
541                 struct winsize screen_size;
542
543                 result = ioctl(fileno(stdout), TIOCGWINSZ, &screen_size);
544                 if (result == -1 || lines > screen_size.ws_row)
545                 {
546 #endif
547                         pagerprog = getenv("PAGER");
548                         if (!pagerprog)
549                                 pagerprog = DEFAULT_PAGER;
550 #ifndef WIN32
551                         pqsignal(SIGPIPE, SIG_IGN);
552 #endif
553                         return popen(pagerprog, "w");
554 #ifdef TIOCGWINSZ
555                 }
556 #endif
557         }
558
559         return stdout;
560 }