OSDN Git Service

f8bf9c9a35e7a077dab5d7d06a06b5199aedeb72
[pg-rex/syncrep.git] / 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.43 2002/08/27 20:16:48 petere 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,after;
299         struct timezone tz;
300
301         if (!pset.db)
302         {
303                 psql_error("You are currently not connected to a database.\n");
304                 return false;
305         }
306
307         if (GetVariableBool(pset.vars, "SINGLESTEP"))
308         {
309                 char            buf[3];
310
311                 printf(gettext("***(Single step mode: Verify query)*********************************************\n"
312                                            "%s\n"
313                                            "***(press return to proceed or enter x and return to cancel)********************\n"),
314                            query);
315                 fflush(stdout);
316                 if (fgets(buf, sizeof(buf), stdin) != NULL)
317                         if (buf[0] == 'x')
318                                 return false;
319         }
320         else
321         {
322                 const char *var = GetVariable(pset.vars, "ECHO");
323
324                 if (var && strncmp(var, "queries", strlen(var)) == 0)
325                         puts(query);
326         }
327
328         cancelConn = pset.db;
329         if (pset.timing)
330         {
331                 gettimeofday(&before, &tz);
332         }
333         results = PQexec(pset.db, query);
334         if (pset.timing)
335         {
336                 gettimeofday(&after, &tz);
337         }
338         if (PQresultStatus(results) == PGRES_COPY_IN)
339                 copy_in_state = true;
340         /* keep cancel connection for copy out state */
341         if (PQresultStatus(results) != PGRES_COPY_OUT)
342                 cancelConn = NULL;
343
344         if (results == NULL)
345         {
346                 fputs(PQerrorMessage(pset.db), pset.queryFout);
347                 success = false;
348         }
349         else
350         {
351                 switch (PQresultStatus(results))
352                 {
353                         case PGRES_TUPLES_OK:
354                                 /* write output to \g argument, if any */
355                                 if (pset.gfname)
356                                 {
357                                         FILE       *queryFout_copy = pset.queryFout;
358                                         bool            queryFoutPipe_copy = pset.queryFoutPipe;
359
360                                         pset.queryFout = stdout;        /* so it doesn't get
361                                                                                                  * closed */
362
363                                         /* open file/pipe */
364                                         if (!setQFout(pset.gfname))
365                                         {
366                                                 pset.queryFout = queryFout_copy;
367                                                 pset.queryFoutPipe = queryFoutPipe_copy;
368                                                 success = false;
369                                                 break;
370                                         }
371
372                                         printQuery(results, &pset.popt, pset.queryFout);
373
374                                         /* close file/pipe, restore old setting */
375                                         setQFout(NULL);
376
377                                         pset.queryFout = queryFout_copy;
378                                         pset.queryFoutPipe = queryFoutPipe_copy;
379
380                                         free(pset.gfname);
381                                         pset.gfname = NULL;
382
383                                         success = true;
384                                 }
385                                 else
386                                 {
387                                         printQuery(results, &pset.popt, pset.queryFout);
388                                         success = true;
389                                 }
390                                 break;
391                         case PGRES_EMPTY_QUERY:
392                                 success = true;
393                                 break;
394                         case PGRES_COMMAND_OK:
395                                 {
396                                         char            buf[10];
397
398                                         success = true;
399                                         sprintf(buf, "%u", (unsigned int) PQoidValue(results));
400                                         if (!QUIET())
401                                                 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
402                                         SetVariable(pset.vars, "LASTOID", buf);
403                                         break;
404                                 }
405                         case PGRES_COPY_OUT:
406                                 success = handleCopyOut(pset.db, pset.queryFout);
407                                 break;
408
409                         case PGRES_COPY_IN:
410                                 if (pset.cur_cmd_interactive && !QUIET())
411                                         puts(gettext("Enter data to be copied followed by a newline.\n"
412                                                                  "End with a backslash and a period on a line by itself."));
413
414                                 success = handleCopyIn(pset.db, pset.cur_cmd_source,
415                                                                            pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
416                                 break;
417
418                         case PGRES_NONFATAL_ERROR:
419                         case PGRES_FATAL_ERROR:
420                         case PGRES_BAD_RESPONSE:
421                                 success = false;
422                                 psql_error("%s", PQerrorMessage(pset.db));
423                                 break;
424                 }
425
426                 fflush(pset.queryFout);
427
428                 if (PQstatus(pset.db) == CONNECTION_BAD)
429                 {
430                         if (!pset.cur_cmd_interactive)
431                         {
432                                 psql_error("connection to server was lost\n");
433                                 exit(EXIT_BADCONN);
434                         }
435                         fputs(gettext("The connection to the server was lost. Attempting reset: "), stderr);
436                         PQreset(pset.db);
437                         if (PQstatus(pset.db) == CONNECTION_BAD)
438                         {
439                                 fputs(gettext("Failed.\n"), stderr);
440                                 PQfinish(pset.db);
441                                 PQclear(results);
442                                 pset.db = NULL;
443                                 SetVariable(pset.vars, "DBNAME", NULL);
444                                 SetVariable(pset.vars, "HOST", NULL);
445                                 SetVariable(pset.vars, "PORT", NULL);
446                                 SetVariable(pset.vars, "USER", NULL);
447                                 SetVariable(pset.vars, "ENCODING", NULL);
448                                 return false;
449                         }
450                         else
451                                 fputs(gettext("Succeeded.\n"), stderr);
452                 }
453
454                 /* check for asynchronous notification returns */
455                 while ((notify = PQnotifies(pset.db)) != NULL)
456                 {
457                         fprintf(pset.queryFout, gettext("Asynchronous NOTIFY '%s' from backend with pid %d received.\n"),
458                                         notify->relname, notify->be_pid);
459                         free(notify);
460                         fflush(pset.queryFout);
461                 }
462
463                 if (results)
464                         PQclear(results);
465         }
466
467         /* Possible microtiming output */
468         if (pset.timing && success)
469                 printf(gettext("Time: %.2f ms\n"),
470                            ((after.tv_sec-before.tv_sec)*1000000 + after.tv_usec - before.tv_usec) / 1000.0);
471
472         return success;
473 }