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