]> granicus.if.org Git - postgresql/blob - src/bin/psql/common.c
UUNET is looking into offering PostgreSQL as a part of a managed web
[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.24 2000/11/13 15:18:14 momjian Exp $
7  */
8 #include "postgres.h"
9 #include "common.h"
10
11 #include <errno.h>
12 #include <stdarg.h>
13 #ifdef HAVE_TERMIOS_H
14 #include <termios.h>
15 #endif
16 #ifndef HAVE_STRDUP
17 #include <strdup.h>
18 #endif
19 #include <signal.h>
20 #ifndef WIN32
21 #include <unistd.h>                             /* for write() */
22 #include <setjmp.h>
23 #else
24 #include <io.h>                                 /* for _write() */
25 #include <win32.h>
26 #endif
27
28 #include "libpq-fe.h"
29 #include "postgres_ext.h"
30 #include "pqsignal.h"
31
32 #include "settings.h"
33 #include "variables.h"
34 #include "copy.h"
35 #include "prompt.h"
36 #include "print.h"
37 #include "mainloop.h"
38
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, "%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, fmt, ap);
143         va_end(ap);
144 }
145
146
147
148 /*
149  * for backend NOTICES
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  * simple_prompt
162  *
163  * Generalized function especially intended for reading in usernames and
164  * password interactively. Reads from stdin.
165  *
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)
169  *
170  * Returns a malloc()'ed string with the input (w/o trailing newline).
171  */
172 static bool prompt_state;
173
174 char *
175 simple_prompt(const char *prompt, int maxlen, bool echo)
176 {
177         int                     length;
178         char       *destination;
179
180 #ifdef HAVE_TERMIOS_H
181         struct termios t_orig,
182                                 t;
183
184 #endif
185
186         destination = (char *) malloc(maxlen + 2);
187         if (!destination)
188                 return NULL;
189         if (prompt)
190                 fputs(prompt, stderr);
191
192         prompt_state = true;
193
194 #ifdef HAVE_TERMIOS_H
195         if (!echo)
196         {
197                 tcgetattr(0, &t);
198                 t_orig = t;
199                 t.c_lflag &= ~ECHO;
200                 tcsetattr(0, TCSADRAIN, &t);
201         }
202 #endif
203
204         fgets(destination, maxlen, stdin);
205
206 #ifdef HAVE_TERMIOS_H
207         if (!echo)
208         {
209                 tcsetattr(0, TCSADRAIN, &t_orig);
210                 puts("");
211         }
212 #endif
213
214         prompt_state = false;
215
216         length = strlen(destination);
217         if (length > 0 && destination[length - 1] != '\n')
218         {
219                 /* eat rest of the line */
220                 char            buf[512];
221
222                 do
223                 {
224                         fgets(buf, 512, stdin);
225                 } while (buf[strlen(buf) - 1] != '\n');
226         }
227
228         if (length > 0 && destination[length - 1] == '\n')
229                 /* remove trailing newline */
230                 destination[length - 1] = '\0';
231
232         return destination;
233 }
234
235
236
237 /*
238  * Code to support query cancellation
239  *
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.
245  */
246
247 PGconn     *cancelConn;
248 volatile bool cancel_pressed;
249
250 #ifndef WIN32
251
252 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
253
254 void
255 handle_sigint(SIGNAL_ARGS)
256 {
257         /* Don't muck around if copying in or prompting for a password. */
258         if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
259                 return;
260
261         if (cancelConn == NULL)
262                 siglongjmp(main_loop_jmp, 1);
263
264         cancel_pressed = true;
265
266         if (PQrequestCancel(cancelConn))
267                 write_stderr("Cancel request sent\n");
268         else
269         {
270                 write_stderr("Could not send cancel request: ");
271                 write_stderr(PQerrorMessage(cancelConn));
272         }
273 }
274
275 #endif   /* not WIN32 */
276
277
278 /*
279  * PSQLexec
280  *
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.
283  */
284 PGresult   *
285 PSQLexec(const char *query)
286 {
287         PGresult   *res;
288         const char *var;
289
290         if (!pset.db)
291         {
292                 psql_error("You are currently not connected to a database.\n");
293                 return NULL;
294         }
295
296         var = GetVariable(pset.vars, "ECHO_HIDDEN");
297         if (var)
298         {
299                 printf("********* QUERY *********\n%s\n*************************\n\n", query);
300                 fflush(stdout);
301         }
302
303         if (var && strcmp(var, "noexec") == 0)
304                 return NULL;
305
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)
312                 cancelConn = NULL;
313
314         if (PQstatus(pset.db) == CONNECTION_BAD)
315         {
316                 if (!pset.cur_cmd_interactive)
317                 {
318                         psql_error("connection to server was lost\n");
319                         exit(EXIT_BADCONN);
320                 }
321                 fputs("The connection to the server was lost. Attempting reset: ", stderr);
322                 PQreset(pset.db);
323                 if (PQstatus(pset.db) == CONNECTION_BAD)
324                 {
325                         fputs("Failed.\n", stderr);
326                         PQfinish(pset.db);
327                         PQclear(res);
328                         pset.db = NULL;
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);
335                         return NULL;
336                 }
337                 else
338                         fputs("Succeeded.\n", stderr);
339         }
340
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)
345                 )
346                 return res;
347         else
348         {
349                 psql_error("%s", PQerrorMessage(pset.db));
350                 PQclear(res);
351                 return NULL;
352         }
353 }
354
355
356
357 /*
358  * SendQuery: send the query string to the backend
359  * (and print out results)
360  *
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
363  * single step mode.
364  * To send "back door" queries (generated by slash commands, etc.) in a
365  * controlled way, use PSQLexec().
366  *
367  * Returns true if the query executed successfully, false otherwise.
368  */
369 bool
370 SendQuery(const char *query)
371 {
372         bool            success = false;
373         PGresult   *results;
374         PGnotify   *notify;
375
376         if (!pset.db)
377         {
378                 psql_error("You are currently not connected to a database.\n");
379                 return false;
380         }
381
382         if (GetVariableBool(pset.vars, "SINGLESTEP"))
383         {
384                 char            buf[3];
385
386                 printf("***(Single step mode: Verify query)*********************************************\n"
387                            "%s\n"
388                            "***(press return to proceed or enter x and return to cancel)********************\n",
389                            query);
390                 fflush(stdout);
391                 fgets(buf, 3, stdin);
392                 if (buf[0] == 'x')
393                         return false;
394         }
395         else
396         {
397                 const char *var = GetVariable(pset.vars, "ECHO");
398
399                 if (var && strncmp(var, "queries", strlen(var)) == 0)
400                         puts(query);
401         }
402
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)
409                 cancelConn = NULL;
410
411         if (results == NULL)
412         {
413                 fputs(PQerrorMessage(pset.db), pset.queryFout);
414                 success = false;
415         }
416         else
417         {
418                 switch (PQresultStatus(results))
419                 {
420                         case PGRES_TUPLES_OK:
421                                 /* write output to \g argument, if any */
422                                 if (pset.gfname)
423                                 {
424                                         FILE       *queryFout_copy = pset.queryFout;
425                                         bool            queryFoutPipe_copy = pset.queryFoutPipe;
426
427                                         pset.queryFout = NULL;          /* so it doesn't get
428                                                                                                  * closed */
429
430                                         /* open file/pipe */
431                                         if (!setQFout(pset.gfname))
432                                         {
433                                                 success = false;
434                                                 break;
435                                         }
436
437                                         printQuery(results, &pset.popt, pset.queryFout);
438
439                                         /* close file/pipe */
440                                         setQFout(NULL);
441
442                                         free(pset.gfname);
443                                         pset.gfname = NULL;
444
445                                         pset.queryFout = queryFout_copy;
446                                         pset.queryFoutPipe = queryFoutPipe_copy;
447
448                                         success = true;
449                                         break;
450                                 }
451                                 else
452                                 {
453                                         success = true;
454                                         printQuery(results, &pset.popt, pset.queryFout);
455                                 }
456                                 break;
457                         case PGRES_EMPTY_QUERY:
458                                 success = true;
459                                 break;
460                         case PGRES_COMMAND_OK:
461                                 {
462                                         char            buf[10];
463
464                                         success = true;
465                                         sprintf(buf, "%u", (unsigned int) PQoidValue(results));
466                                         if (!QUIET())
467                                                 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
468                                         SetVariable(pset.vars, "LASTOID", buf);
469                                         break;
470                                 }
471                         case PGRES_COPY_OUT:
472                                 success = handleCopyOut(pset.db, pset.queryFout);
473                                 break;
474
475                         case PGRES_COPY_IN:
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.");
479
480                                 success = handleCopyIn(pset.db, pset.cur_cmd_source,
481                                                                            pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
482                                 break;
483
484                         case PGRES_NONFATAL_ERROR:
485                         case PGRES_FATAL_ERROR:
486                         case PGRES_BAD_RESPONSE:
487                                 success = false;
488                                 psql_error("%s", PQerrorMessage(pset.db));
489                                 break;
490                 }
491
492                 fflush(pset.queryFout);
493
494                 if (PQstatus(pset.db) == CONNECTION_BAD)
495                 {
496                         if (!pset.cur_cmd_interactive)
497                         {
498                                 psql_error("connection to server was lost\n");
499                                 exit(EXIT_BADCONN);
500                         }
501                         fputs("The connection to the server was lost. Attempting reset: ", stderr);
502                         PQreset(pset.db);
503                         if (PQstatus(pset.db) == CONNECTION_BAD)
504                         {
505                                 fputs("Failed.\n", stderr);
506                                 PQfinish(pset.db);
507                                 PQclear(results);
508                                 pset.db = NULL;
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);
515                                 return false;
516                         }
517                         else
518                                 fputs("Succeeded.\n", stderr);
519                 }
520
521                 /* check for asynchronous notification returns */
522                 while ((notify = PQnotifies(pset.db)) != NULL)
523                 {
524                         fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
525                                         notify->relname, notify->be_pid);
526                         free(notify);
527                         fflush(pset.queryFout);
528                 }
529
530                 if (results)
531                         PQclear(results);
532         }
533
534         return success;
535 }