]> granicus.if.org Git - postgresql/blob - src/bin/psql/command.c
Provide Assert() for frontend code.
[postgresql] / src / bin / psql / command.c
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright (c) 2000-2012, PostgreSQL Global Development Group
5  *
6  * src/bin/psql/command.c
7  */
8 #include "postgres_fe.h"
9 #include "command.h"
10
11 #ifdef __BORLANDC__                             /* needed for BCC */
12 #undef mkdir
13 #endif
14
15 #include <ctype.h>
16 #ifdef HAVE_PWD_H
17 #include <pwd.h>
18 #endif
19 #ifndef WIN32
20 #include <sys/types.h>                  /* for umask() */
21 #include <sys/stat.h>                   /* for stat() */
22 #include <fcntl.h>                              /* open() flags */
23 #include <unistd.h>                             /* for geteuid(), getpid(), stat() */
24 #else
25 #include <win32.h>
26 #include <io.h>
27 #include <fcntl.h>
28 #include <direct.h>
29 #include <sys/types.h>                  /* for umask() */
30 #include <sys/stat.h>                   /* for stat() */
31 #endif
32 #ifdef USE_SSL
33 #include <openssl/ssl.h>
34 #endif
35
36 #include "portability/instr_time.h"
37
38 #include "libpq-fe.h"
39 #include "pqexpbuffer.h"
40 #include "dumputils.h"
41
42 #include "common.h"
43 #include "copy.h"
44 #include "describe.h"
45 #include "help.h"
46 #include "input.h"
47 #include "large_obj.h"
48 #include "mainloop.h"
49 #include "print.h"
50 #include "psqlscan.h"
51 #include "settings.h"
52 #include "variables.h"
53
54
55 /* functions for use in this file */
56 static backslashResult exec_command(const char *cmd,
57                          PsqlScanState scan_state,
58                          PQExpBuffer query_buf);
59 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
60                 int lineno, bool *edited);
61 static bool do_connect(char *dbname, char *user, char *host, char *port);
62 static bool do_shell(const char *command);
63 static bool lookup_function_oid(PGconn *conn, const char *desc, Oid *foid);
64 static bool get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf);
65 static int      strip_lineno_from_funcdesc(char *func);
66 static void minimal_error_message(PGresult *res);
67
68 static void printSSLInfo(void);
69
70 #ifdef WIN32
71 static void checkWin32Codepage(void);
72 #endif
73
74
75
76 /*----------
77  * HandleSlashCmds:
78  *
79  * Handles all the different commands that start with '\'.
80  * Ordinarily called by MainLoop().
81  *
82  * scan_state is a lexer working state that is set to continue scanning
83  * just after the '\'.  The lexer is advanced past the command and all
84  * arguments on return.
85  *
86  * 'query_buf' contains the query-so-far, which may be modified by
87  * execution of the backslash command (for example, \r clears it).
88  * query_buf can be NULL if there is no query so far.
89  *
90  * Returns a status code indicating what action is desired, see command.h.
91  *----------
92  */
93
94 backslashResult
95 HandleSlashCmds(PsqlScanState scan_state,
96                                 PQExpBuffer query_buf)
97 {
98         backslashResult status = PSQL_CMD_SKIP_LINE;
99         char       *cmd;
100         char       *arg;
101
102         Assert(scan_state != NULL);
103
104         /* Parse off the command name */
105         cmd = psql_scan_slash_command(scan_state);
106
107         /* And try to execute it */
108         status = exec_command(cmd, scan_state, query_buf);
109
110         if (status == PSQL_CMD_UNKNOWN)
111         {
112                 if (pset.cur_cmd_interactive)
113                         psql_error("Invalid command \\%s. Try \\? for help.\n", cmd);
114                 else
115                         psql_error("invalid command \\%s\n", cmd);
116                 status = PSQL_CMD_ERROR;
117         }
118
119         if (status != PSQL_CMD_ERROR)
120         {
121                 /* eat any remaining arguments after a valid command */
122                 /* note we suppress evaluation of backticks here */
123                 while ((arg = psql_scan_slash_option(scan_state,
124                                                                                          OT_NO_EVAL, NULL, false)))
125                 {
126                         psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
127                         free(arg);
128                 }
129         }
130         else
131         {
132                 /* silently throw away rest of line after an erroneous command */
133                 while ((arg = psql_scan_slash_option(scan_state,
134                                                                                          OT_WHOLE_LINE, NULL, false)))
135                         free(arg);
136         }
137
138         /* if there is a trailing \\, swallow it */
139         psql_scan_slash_command_end(scan_state);
140
141         free(cmd);
142
143         /* some commands write to queryFout, so make sure output is sent */
144         fflush(pset.queryFout);
145
146         return status;
147 }
148
149 /*
150  * Read and interpret an argument to the \connect slash command.
151  */
152 static char *
153 read_connect_arg(PsqlScanState scan_state)
154 {
155         char       *result;
156         char            quote;
157
158         /*
159          * Ideally we should treat the arguments as SQL identifiers.  But for
160          * backwards compatibility with 7.2 and older pg_dump files, we have to
161          * take unquoted arguments verbatim (don't downcase them). For now,
162          * double-quoted arguments may be stripped of double quotes (as if SQL
163          * identifiers).  By 7.4 or so, pg_dump files can be expected to
164          * double-quote all mixed-case \connect arguments, and then we can get rid
165          * of OT_SQLIDHACK.
166          */
167         result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
168
169         if (!result)
170                 return NULL;
171
172         if (quote)
173                 return result;
174
175         if (*result == '\0' || strcmp(result, "-") == 0)
176                 return NULL;
177
178         return result;
179 }
180
181
182 /*
183  * Subroutine to actually try to execute a backslash command.
184  */
185 static backslashResult
186 exec_command(const char *cmd,
187                          PsqlScanState scan_state,
188                          PQExpBuffer query_buf)
189 {
190         bool            success = true; /* indicate here if the command ran ok or
191                                                                  * failed */
192         backslashResult status = PSQL_CMD_SKIP_LINE;
193
194         /*
195          * \a -- toggle field alignment This makes little sense but we keep it
196          * around.
197          */
198         if (strcmp(cmd, "a") == 0)
199         {
200                 if (pset.popt.topt.format != PRINT_ALIGNED)
201                         success = do_pset("format", "aligned", &pset.popt, pset.quiet);
202                 else
203                         success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
204         }
205
206         /* \C -- override table title (formerly change HTML caption) */
207         else if (strcmp(cmd, "C") == 0)
208         {
209                 char       *opt = psql_scan_slash_option(scan_state,
210                                                                                                  OT_NORMAL, NULL, true);
211
212                 success = do_pset("title", opt, &pset.popt, pset.quiet);
213                 free(opt);
214         }
215
216         /*
217          * \c or \connect -- connect to database using the specified parameters.
218          *
219          * \c dbname user host port
220          *
221          * If any of these parameters are omitted or specified as '-', the current
222          * value of the parameter will be used instead. If the parameter has no
223          * current value, the default value for that parameter will be used. Some
224          * examples:
225          *
226          * \c - - hst           Connect to current database on current port of host
227          * "hst" as current user. \c - usr - prt   Connect to current database on
228          * "prt" port of current host as user "usr". \c dbs                       Connect to
229          * "dbs" database on current port of current host as current user.
230          */
231         else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
232         {
233                 char       *opt1,
234                                    *opt2,
235                                    *opt3,
236                                    *opt4;
237
238                 opt1 = read_connect_arg(scan_state);
239                 opt2 = read_connect_arg(scan_state);
240                 opt3 = read_connect_arg(scan_state);
241                 opt4 = read_connect_arg(scan_state);
242
243                 success = do_connect(opt1, opt2, opt3, opt4);
244
245                 free(opt1);
246                 free(opt2);
247                 free(opt3);
248                 free(opt4);
249         }
250
251         /* \cd */
252         else if (strcmp(cmd, "cd") == 0)
253         {
254                 char       *opt = psql_scan_slash_option(scan_state,
255                                                                                                  OT_NORMAL, NULL, true);
256                 char       *dir;
257
258                 if (opt)
259                         dir = opt;
260                 else
261                 {
262 #ifndef WIN32
263                         struct passwd *pw;
264
265                         pw = getpwuid(geteuid());
266                         if (!pw)
267                         {
268                                 psql_error("could not get home directory: %s\n", strerror(errno));
269                                 exit(EXIT_FAILURE);
270                         }
271                         dir = pw->pw_dir;
272 #else                                                   /* WIN32 */
273
274                         /*
275                          * On Windows, 'cd' without arguments prints the current
276                          * directory, so if someone wants to code this here instead...
277                          */
278                         dir = "/";
279 #endif   /* WIN32 */
280                 }
281
282                 if (chdir(dir) == -1)
283                 {
284                         psql_error("\\%s: could not change directory to \"%s\": %s\n",
285                                            cmd, dir, strerror(errno));
286                         success = false;
287                 }
288
289                 if (pset.dirname)
290                         free(pset.dirname);
291                 pset.dirname = pg_strdup(dir);
292                 canonicalize_path(pset.dirname);
293
294                 if (opt)
295                         free(opt);
296         }
297
298         /* \conninfo -- display information about the current connection */
299         else if (strcmp(cmd, "conninfo") == 0)
300         {
301                 char       *db = PQdb(pset.db);
302                 char       *host = PQhost(pset.db);
303
304                 if (db == NULL)
305                         printf(_("You are currently not connected to a database.\n"));
306                 else
307                 {
308                         if (host == NULL)
309                                 host = DEFAULT_PGSOCKET_DIR;
310                         /* If the host is an absolute path, the connection is via socket */
311                         if (is_absolute_path(host))
312                                 printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
313                                            db, PQuser(pset.db), host, PQport(pset.db));
314                         else
315                                 printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
316                                            db, PQuser(pset.db), host, PQport(pset.db));
317                         printSSLInfo();
318                 }
319         }
320
321         /* \copy */
322         else if (pg_strcasecmp(cmd, "copy") == 0)
323         {
324                 char       *opt = psql_scan_slash_option(scan_state,
325                                                                                                  OT_WHOLE_LINE, NULL, false);
326
327                 success = do_copy(opt);
328                 free(opt);
329         }
330
331         /* \copyright */
332         else if (strcmp(cmd, "copyright") == 0)
333                 print_copyright();
334
335         /* \d* commands */
336         else if (cmd[0] == 'd')
337         {
338                 char       *pattern;
339                 bool            show_verbose,
340                                         show_system;
341
342                 /* We don't do SQLID reduction on the pattern yet */
343                 pattern = psql_scan_slash_option(scan_state,
344                                                                                  OT_NORMAL, NULL, true);
345
346                 show_verbose = strchr(cmd, '+') ? true : false;
347                 show_system = strchr(cmd, 'S') ? true : false;
348
349                 switch (cmd[1])
350                 {
351                         case '\0':
352                         case '+':
353                         case 'S':
354                                 if (pattern)
355                                         success = describeTableDetails(pattern, show_verbose, show_system);
356                                 else
357                                         /* standard listing of interesting things */
358                                         success = listTables("tvsE", NULL, show_verbose, show_system);
359                                 break;
360                         case 'a':
361                                 success = describeAggregates(pattern, show_verbose, show_system);
362                                 break;
363                         case 'b':
364                                 success = describeTablespaces(pattern, show_verbose);
365                                 break;
366                         case 'c':
367                                 success = listConversions(pattern, show_verbose, show_system);
368                                 break;
369                         case 'C':
370                                 success = listCasts(pattern, show_verbose);
371                                 break;
372                         case 'd':
373                                 if (strncmp(cmd, "ddp", 3) == 0)
374                                         success = listDefaultACLs(pattern);
375                                 else
376                                         success = objectDescription(pattern, show_system);
377                                 break;
378                         case 'D':
379                                 success = listDomains(pattern, show_verbose, show_system);
380                                 break;
381                         case 'f':                       /* function subsystem */
382                                 switch (cmd[2])
383                                 {
384                                         case '\0':
385                                         case '+':
386                                         case 'S':
387                                         case 'a':
388                                         case 'n':
389                                         case 't':
390                                         case 'w':
391                                                 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
392                                                 break;
393                                         default:
394                                                 status = PSQL_CMD_UNKNOWN;
395                                                 break;
396                                 }
397                                 break;
398                         case 'g':
399                                 /* no longer distinct from \du */
400                                 success = describeRoles(pattern, show_verbose);
401                                 break;
402                         case 'l':
403                                 success = do_lo_list();
404                                 break;
405                         case 'L':
406                                 success = listLanguages(pattern, show_verbose, show_system);
407                                 break;
408                         case 'n':
409                                 success = listSchemas(pattern, show_verbose, show_system);
410                                 break;
411                         case 'o':
412                                 success = describeOperators(pattern, show_system);
413                                 break;
414                         case 'O':
415                                 success = listCollations(pattern, show_verbose, show_system);
416                                 break;
417                         case 'p':
418                                 success = permissionsList(pattern);
419                                 break;
420                         case 'T':
421                                 success = describeTypes(pattern, show_verbose, show_system);
422                                 break;
423                         case 't':
424                         case 'v':
425                         case 'i':
426                         case 's':
427                         case 'E':
428                                 success = listTables(&cmd[1], pattern, show_verbose, show_system);
429                                 break;
430                         case 'r':
431                                 if (cmd[2] == 'd' && cmd[3] == 's')
432                                 {
433                                         char       *pattern2 = NULL;
434
435                                         if (pattern)
436                                                 pattern2 = psql_scan_slash_option(scan_state,
437                                                                                                           OT_NORMAL, NULL, true);
438                                         success = listDbRoleSettings(pattern, pattern2);
439                                 }
440                                 else
441                                         success = PSQL_CMD_UNKNOWN;
442                                 break;
443                         case 'u':
444                                 success = describeRoles(pattern, show_verbose);
445                                 break;
446                         case 'F':                       /* text search subsystem */
447                                 switch (cmd[2])
448                                 {
449                                         case '\0':
450                                         case '+':
451                                                 success = listTSConfigs(pattern, show_verbose);
452                                                 break;
453                                         case 'p':
454                                                 success = listTSParsers(pattern, show_verbose);
455                                                 break;
456                                         case 'd':
457                                                 success = listTSDictionaries(pattern, show_verbose);
458                                                 break;
459                                         case 't':
460                                                 success = listTSTemplates(pattern, show_verbose);
461                                                 break;
462                                         default:
463                                                 status = PSQL_CMD_UNKNOWN;
464                                                 break;
465                                 }
466                                 break;
467                         case 'e':                       /* SQL/MED subsystem */
468                                 switch (cmd[2])
469                                 {
470                                         case 's':
471                                                 success = listForeignServers(pattern, show_verbose);
472                                                 break;
473                                         case 'u':
474                                                 success = listUserMappings(pattern, show_verbose);
475                                                 break;
476                                         case 'w':
477                                                 success = listForeignDataWrappers(pattern, show_verbose);
478                                                 break;
479                                         case 't':
480                                                 success = listForeignTables(pattern, show_verbose);
481                                                 break;
482                                         default:
483                                                 status = PSQL_CMD_UNKNOWN;
484                                                 break;
485                                 }
486                                 break;
487                         case 'x':                       /* Extensions */
488                                 if (show_verbose)
489                                         success = listExtensionContents(pattern);
490                                 else
491                                         success = listExtensions(pattern);
492                                 break;
493                         case 'y':                       /* Event Triggers */
494                                 success = listEventTriggers(pattern, show_verbose);
495                                 break;
496                         default:
497                                 status = PSQL_CMD_UNKNOWN;
498                 }
499
500                 if (pattern)
501                         free(pattern);
502         }
503
504
505         /*
506          * \e or \edit -- edit the current query buffer, or edit a file and make
507          * it the query buffer
508          */
509         else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
510         {
511                 if (!query_buf)
512                 {
513                         psql_error("no query buffer\n");
514                         status = PSQL_CMD_ERROR;
515                 }
516                 else
517                 {
518                         char       *fname;
519                         char       *ln = NULL;
520                         int                     lineno = -1;
521
522                         fname = psql_scan_slash_option(scan_state,
523                                                                                    OT_NORMAL, NULL, true);
524                         if (fname)
525                         {
526                                 /* try to get separate lineno arg */
527                                 ln = psql_scan_slash_option(scan_state,
528                                                                                         OT_NORMAL, NULL, true);
529                                 if (ln == NULL)
530                                 {
531                                         /* only one arg; maybe it is lineno not fname */
532                                         if (fname[0] &&
533                                                 strspn(fname, "0123456789") == strlen(fname))
534                                         {
535                                                 /* all digits, so assume it is lineno */
536                                                 ln = fname;
537                                                 fname = NULL;
538                                         }
539                                 }
540                         }
541                         if (ln)
542                         {
543                                 lineno = atoi(ln);
544                                 if (lineno < 1)
545                                 {
546                                         psql_error("invalid line number: %s\n", ln);
547                                         status = PSQL_CMD_ERROR;
548                                 }
549                         }
550                         if (status != PSQL_CMD_ERROR)
551                         {
552                                 expand_tilde(&fname);
553                                 if (fname)
554                                         canonicalize_path(fname);
555                                 if (do_edit(fname, query_buf, lineno, NULL))
556                                         status = PSQL_CMD_NEWEDIT;
557                                 else
558                                         status = PSQL_CMD_ERROR;
559                         }
560                         if (fname)
561                                 free(fname);
562                         if (ln)
563                                 free(ln);
564                 }
565         }
566
567         /*
568          * \ef -- edit the named function, or present a blank CREATE FUNCTION
569          * template if no argument is given
570          */
571         else if (strcmp(cmd, "ef") == 0)
572         {
573                 int                     lineno = -1;
574
575                 if (pset.sversion < 80400)
576                 {
577                         psql_error("The server (version %d.%d) does not support editing function source.\n",
578                                            pset.sversion / 10000, (pset.sversion / 100) % 100);
579                         status = PSQL_CMD_ERROR;
580                 }
581                 else if (!query_buf)
582                 {
583                         psql_error("no query buffer\n");
584                         status = PSQL_CMD_ERROR;
585                 }
586                 else
587                 {
588                         char       *func;
589                         Oid                     foid = InvalidOid;
590
591                         func = psql_scan_slash_option(scan_state,
592                                                                                   OT_WHOLE_LINE, NULL, true);
593                         lineno = strip_lineno_from_funcdesc(func);
594                         if (lineno == 0)
595                         {
596                                 /* error already reported */
597                                 status = PSQL_CMD_ERROR;
598                         }
599                         else if (!func)
600                         {
601                                 /* set up an empty command to fill in */
602                                 printfPQExpBuffer(query_buf,
603                                                                   "CREATE FUNCTION ( )\n"
604                                                                   " RETURNS \n"
605                                                                   " LANGUAGE \n"
606                                                                   " -- common options:  IMMUTABLE  STABLE  STRICT  SECURITY DEFINER\n"
607                                                                   "AS $function$\n"
608                                                                   "\n$function$\n");
609                         }
610                         else if (!lookup_function_oid(pset.db, func, &foid))
611                         {
612                                 /* error already reported */
613                                 status = PSQL_CMD_ERROR;
614                         }
615                         else if (!get_create_function_cmd(pset.db, foid, query_buf))
616                         {
617                                 /* error already reported */
618                                 status = PSQL_CMD_ERROR;
619                         }
620                         else if (lineno > 0)
621                         {
622                                 /*
623                                  * lineno "1" should correspond to the first line of the
624                                  * function body.  We expect that pg_get_functiondef() will
625                                  * emit that on a line beginning with "AS ", and that there
626                                  * can be no such line before the real start of the function
627                                  * body.  Increment lineno by the number of lines before that
628                                  * line, so that it becomes relative to the first line of the
629                                  * function definition.
630                                  */
631                                 const char *lines = query_buf->data;
632
633                                 while (*lines != '\0')
634                                 {
635                                         if (strncmp(lines, "AS ", 3) == 0)
636                                                 break;
637                                         lineno++;
638                                         /* find start of next line */
639                                         lines = strchr(lines, '\n');
640                                         if (!lines)
641                                                 break;
642                                         lines++;
643                                 }
644                         }
645
646                         if (func)
647                                 free(func);
648                 }
649
650                 if (status != PSQL_CMD_ERROR)
651                 {
652                         bool            edited = false;
653
654                         if (!do_edit(NULL, query_buf, lineno, &edited))
655                                 status = PSQL_CMD_ERROR;
656                         else if (!edited)
657                                 puts(_("No changes"));
658                         else
659                                 status = PSQL_CMD_NEWEDIT;
660                 }
661         }
662
663         /* \echo and \qecho */
664         else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
665         {
666                 char       *value;
667                 char            quoted;
668                 bool            no_newline = false;
669                 bool            first = true;
670                 FILE       *fout;
671
672                 if (strcmp(cmd, "qecho") == 0)
673                         fout = pset.queryFout;
674                 else
675                         fout = stdout;
676
677                 while ((value = psql_scan_slash_option(scan_state,
678                                                                                            OT_NORMAL, &quoted, false)))
679                 {
680                         if (!quoted && strcmp(value, "-n") == 0)
681                                 no_newline = true;
682                         else
683                         {
684                                 if (first)
685                                         first = false;
686                                 else
687                                         fputc(' ', fout);
688                                 fputs(value, fout);
689                         }
690                         free(value);
691                 }
692                 if (!no_newline)
693                         fputs("\n", fout);
694         }
695
696         /* \encoding -- set/show client side encoding */
697         else if (strcmp(cmd, "encoding") == 0)
698         {
699                 char       *encoding = psql_scan_slash_option(scan_state,
700                                                                                                           OT_NORMAL, NULL, false);
701
702                 if (!encoding)
703                 {
704                         /* show encoding */
705                         puts(pg_encoding_to_char(pset.encoding));
706                 }
707                 else
708                 {
709                         /* set encoding */
710                         if (PQsetClientEncoding(pset.db, encoding) == -1)
711                                 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
712                         else
713                         {
714                                 /* save encoding info into psql internal data */
715                                 pset.encoding = PQclientEncoding(pset.db);
716                                 pset.popt.topt.encoding = pset.encoding;
717                                 SetVariable(pset.vars, "ENCODING",
718                                                         pg_encoding_to_char(pset.encoding));
719                         }
720                         free(encoding);
721                 }
722         }
723
724         /* \f -- change field separator */
725         else if (strcmp(cmd, "f") == 0)
726         {
727                 char       *fname = psql_scan_slash_option(scan_state,
728                                                                                                    OT_NORMAL, NULL, false);
729
730                 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
731                 free(fname);
732         }
733
734         /* \g means send query */
735         else if (strcmp(cmd, "g") == 0)
736         {
737                 char       *fname = psql_scan_slash_option(scan_state,
738                                                                                                    OT_FILEPIPE, NULL, false);
739
740                 if (!fname)
741                         pset.gfname = NULL;
742                 else
743                 {
744                         expand_tilde(&fname);
745                         pset.gfname = pg_strdup(fname);
746                 }
747                 free(fname);
748                 status = PSQL_CMD_SEND;
749         }
750
751         /* help */
752         else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
753         {
754                 char       *opt = psql_scan_slash_option(scan_state,
755                                                                                                  OT_WHOLE_LINE, NULL, false);
756                 size_t          len;
757
758                 /* strip any trailing spaces and semicolons */
759                 if (opt)
760                 {
761                         len = strlen(opt);
762                         while (len > 0 &&
763                                    (isspace((unsigned char) opt[len - 1])
764                                         || opt[len - 1] == ';'))
765                                 opt[--len] = '\0';
766                 }
767
768                 helpSQL(opt, pset.popt.topt.pager);
769                 free(opt);
770         }
771
772         /* HTML mode */
773         else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
774         {
775                 if (pset.popt.topt.format != PRINT_HTML)
776                         success = do_pset("format", "html", &pset.popt, pset.quiet);
777                 else
778                         success = do_pset("format", "aligned", &pset.popt, pset.quiet);
779         }
780
781
782         /* \i and \ir include files */
783         else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0
784                    || strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
785         {
786                 char       *fname = psql_scan_slash_option(scan_state,
787                                                                                                    OT_NORMAL, NULL, true);
788
789                 if (!fname)
790                 {
791                         psql_error("\\%s: missing required argument\n", cmd);
792                         success = false;
793                 }
794                 else
795                 {
796                         bool            include_relative;
797
798                         include_relative = (strcmp(cmd, "ir") == 0
799                                                                 || strcmp(cmd, "include_relative") == 0);
800                         expand_tilde(&fname);
801                         success = (process_file(fname, false, include_relative) == EXIT_SUCCESS);
802                         free(fname);
803                 }
804         }
805
806         /* \l is list databases */
807         else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
808                 success = listAllDbs(false);
809         else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
810                 success = listAllDbs(true);
811
812         /*
813          * large object things
814          */
815         else if (strncmp(cmd, "lo_", 3) == 0)
816         {
817                 char       *opt1,
818                                    *opt2;
819
820                 opt1 = psql_scan_slash_option(scan_state,
821                                                                           OT_NORMAL, NULL, true);
822                 opt2 = psql_scan_slash_option(scan_state,
823                                                                           OT_NORMAL, NULL, true);
824
825                 if (strcmp(cmd + 3, "export") == 0)
826                 {
827                         if (!opt2)
828                         {
829                                 psql_error("\\%s: missing required argument\n", cmd);
830                                 success = false;
831                         }
832                         else
833                         {
834                                 expand_tilde(&opt2);
835                                 success = do_lo_export(opt1, opt2);
836                         }
837                 }
838
839                 else if (strcmp(cmd + 3, "import") == 0)
840                 {
841                         if (!opt1)
842                         {
843                                 psql_error("\\%s: missing required argument\n", cmd);
844                                 success = false;
845                         }
846                         else
847                         {
848                                 expand_tilde(&opt1);
849                                 success = do_lo_import(opt1, opt2);
850                         }
851                 }
852
853                 else if (strcmp(cmd + 3, "list") == 0)
854                         success = do_lo_list();
855
856                 else if (strcmp(cmd + 3, "unlink") == 0)
857                 {
858                         if (!opt1)
859                         {
860                                 psql_error("\\%s: missing required argument\n", cmd);
861                                 success = false;
862                         }
863                         else
864                                 success = do_lo_unlink(opt1);
865                 }
866
867                 else
868                         status = PSQL_CMD_UNKNOWN;
869
870                 free(opt1);
871                 free(opt2);
872         }
873
874
875         /* \o -- set query output */
876         else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
877         {
878                 char       *fname = psql_scan_slash_option(scan_state,
879                                                                                                    OT_FILEPIPE, NULL, true);
880
881                 expand_tilde(&fname);
882                 success = setQFout(fname);
883                 free(fname);
884         }
885
886         /* \p prints the current query buffer */
887         else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
888         {
889                 if (query_buf && query_buf->len > 0)
890                         puts(query_buf->data);
891                 else if (!pset.quiet)
892                         puts(_("Query buffer is empty."));
893                 fflush(stdout);
894         }
895
896         /* \password -- set user password */
897         else if (strcmp(cmd, "password") == 0)
898         {
899                 char       *pw1;
900                 char       *pw2;
901
902                 pw1 = simple_prompt("Enter new password: ", 100, false);
903                 pw2 = simple_prompt("Enter it again: ", 100, false);
904
905                 if (strcmp(pw1, pw2) != 0)
906                 {
907                         psql_error("Passwords didn't match.\n");
908                         success = false;
909                 }
910                 else
911                 {
912                         char       *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
913                         char       *user;
914                         char       *encrypted_password;
915
916                         if (opt0)
917                                 user = opt0;
918                         else
919                                 user = PQuser(pset.db);
920
921                         encrypted_password = PQencryptPassword(pw1, user);
922
923                         if (!encrypted_password)
924                         {
925                                 psql_error("Password encryption failed.\n");
926                                 success = false;
927                         }
928                         else
929                         {
930                                 PQExpBufferData buf;
931                                 PGresult   *res;
932
933                                 initPQExpBuffer(&buf);
934                                 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
935                                                                   fmtId(user));
936                                 appendStringLiteralConn(&buf, encrypted_password, pset.db);
937                                 res = PSQLexec(buf.data, false);
938                                 termPQExpBuffer(&buf);
939                                 if (!res)
940                                         success = false;
941                                 else
942                                         PQclear(res);
943                                 PQfreemem(encrypted_password);
944                         }
945
946                         if (opt0)
947                                 free(opt0);
948                 }
949
950                 free(pw1);
951                 free(pw2);
952         }
953
954         /* \prompt -- prompt and set variable */
955         else if (strcmp(cmd, "prompt") == 0)
956         {
957                 char       *opt,
958                                    *prompt_text = NULL;
959                 char       *arg1,
960                                    *arg2;
961
962                 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
963                 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
964
965                 if (!arg1)
966                 {
967                         psql_error("\\%s: missing required argument\n", cmd);
968                         success = false;
969                 }
970                 else
971                 {
972                         char       *result;
973
974                         if (arg2)
975                         {
976                                 prompt_text = arg1;
977                                 opt = arg2;
978                         }
979                         else
980                                 opt = arg1;
981
982                         if (!pset.inputfile)
983                                 result = simple_prompt(prompt_text, 4096, true);
984                         else
985                         {
986                                 if (prompt_text)
987                                 {
988                                         fputs(prompt_text, stdout);
989                                         fflush(stdout);
990                                 }
991                                 result = gets_fromFile(stdin);
992                         }
993
994                         if (!SetVariable(pset.vars, opt, result))
995                         {
996                                 psql_error("\\%s: error while setting variable\n", cmd);
997                                 success = false;
998                         }
999
1000                         free(result);
1001                         if (prompt_text)
1002                                 free(prompt_text);
1003                         free(opt);
1004                 }
1005         }
1006
1007         /* \pset -- set printing parameters */
1008         else if (strcmp(cmd, "pset") == 0)
1009         {
1010                 char       *opt0 = psql_scan_slash_option(scan_state,
1011                                                                                                   OT_NORMAL, NULL, false);
1012                 char       *opt1 = psql_scan_slash_option(scan_state,
1013                                                                                                   OT_NORMAL, NULL, false);
1014
1015                 if (!opt0)
1016                 {
1017                         psql_error("\\%s: missing required argument\n", cmd);
1018                         success = false;
1019                 }
1020                 else
1021                         success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1022
1023                 free(opt0);
1024                 free(opt1);
1025         }
1026
1027         /* \q or \quit */
1028         else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1029                 status = PSQL_CMD_TERMINATE;
1030
1031         /* reset(clear) the buffer */
1032         else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1033         {
1034                 resetPQExpBuffer(query_buf);
1035                 psql_scan_reset(scan_state);
1036                 if (!pset.quiet)
1037                         puts(_("Query buffer reset (cleared)."));
1038         }
1039
1040         /* \s save history in a file or show it on the screen */
1041         else if (strcmp(cmd, "s") == 0)
1042         {
1043                 char       *fname = psql_scan_slash_option(scan_state,
1044                                                                                                    OT_NORMAL, NULL, true);
1045
1046                 expand_tilde(&fname);
1047                 /* This scrolls off the screen when using /dev/tty */
1048                 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
1049                 if (success && !pset.quiet && fname)
1050                         printf(gettext("Wrote history to file \"%s/%s\".\n"),
1051                                    pset.dirname ? pset.dirname : ".", fname);
1052                 if (!fname)
1053                         putchar('\n');
1054                 free(fname);
1055         }
1056
1057         /* \set -- generalized set variable/option command */
1058         else if (strcmp(cmd, "set") == 0)
1059         {
1060                 char       *opt0 = psql_scan_slash_option(scan_state,
1061                                                                                                   OT_NORMAL, NULL, false);
1062
1063                 if (!opt0)
1064                 {
1065                         /* list all variables */
1066                         PrintVariables(pset.vars);
1067                         success = true;
1068                 }
1069                 else
1070                 {
1071                         /*
1072                          * Set variable to the concatenation of the arguments.
1073                          */
1074                         char       *newval;
1075                         char       *opt;
1076
1077                         opt = psql_scan_slash_option(scan_state,
1078                                                                                  OT_NORMAL, NULL, false);
1079                         newval = pg_strdup(opt ? opt : "");
1080                         free(opt);
1081
1082                         while ((opt = psql_scan_slash_option(scan_state,
1083                                                                                                  OT_NORMAL, NULL, false)))
1084                         {
1085                                 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
1086                                 if (!newval)
1087                                 {
1088                                         psql_error("out of memory\n");
1089                                         exit(EXIT_FAILURE);
1090                                 }
1091                                 strcat(newval, opt);
1092                                 free(opt);
1093                         }
1094
1095                         if (!SetVariable(pset.vars, opt0, newval))
1096                         {
1097                                 psql_error("\\%s: error while setting variable\n", cmd);
1098                                 success = false;
1099                         }
1100                         free(newval);
1101                 }
1102                 free(opt0);
1103         }
1104
1105
1106         /* \setenv -- set environment command */
1107         else if (strcmp(cmd, "setenv") == 0)
1108         {
1109                 char       *envvar = psql_scan_slash_option(scan_state,
1110                                                                                                         OT_NORMAL, NULL, false);
1111                 char       *envval = psql_scan_slash_option(scan_state,
1112                                                                                                         OT_NORMAL, NULL, false);
1113
1114                 if (!envvar)
1115                 {
1116                         psql_error("\\%s: missing required argument\n", cmd);
1117                         success = false;
1118                 }
1119                 else if (strchr(envvar, '=') != NULL)
1120                 {
1121                         psql_error("\\%s: environment variable name must not contain \"=\"\n",
1122                                            cmd);
1123                         success = false;
1124                 }
1125                 else if (!envval)
1126                 {
1127                         /* No argument - unset the environment variable */
1128                         unsetenv(envvar);
1129                         success = true;
1130                 }
1131                 else
1132                 {
1133                         /* Set variable to the value of the next argument */
1134                         int                     len = strlen(envvar) + strlen(envval) + 1;
1135                         char       *newval = pg_malloc(len + 1);
1136
1137                         snprintf(newval, len + 1, "%s=%s", envvar, envval);
1138                         putenv(newval);
1139                         success = true;
1140
1141                         /*
1142                          * Do not free newval here, it will screw up the environment if
1143                          * you do. See putenv man page for details. That means we leak a
1144                          * bit of memory here, but not enough to worry about.
1145                          */
1146                 }
1147                 free(envvar);
1148                 free(envval);
1149         }
1150
1151         /* \sf -- show a function's source code */
1152         else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1153         {
1154                 bool            show_linenumbers = (strcmp(cmd, "sf+") == 0);
1155                 PQExpBuffer func_buf;
1156                 char       *func;
1157                 Oid                     foid = InvalidOid;
1158
1159                 func_buf = createPQExpBuffer();
1160                 func = psql_scan_slash_option(scan_state,
1161                                                                           OT_WHOLE_LINE, NULL, true);
1162                 if (pset.sversion < 80400)
1163                 {
1164                         psql_error("The server (version %d.%d) does not support showing function source.\n",
1165                                            pset.sversion / 10000, (pset.sversion / 100) % 100);
1166                         status = PSQL_CMD_ERROR;
1167                 }
1168                 else if (!func)
1169                 {
1170                         psql_error("function name is required\n");
1171                         status = PSQL_CMD_ERROR;
1172                 }
1173                 else if (!lookup_function_oid(pset.db, func, &foid))
1174                 {
1175                         /* error already reported */
1176                         status = PSQL_CMD_ERROR;
1177                 }
1178                 else if (!get_create_function_cmd(pset.db, foid, func_buf))
1179                 {
1180                         /* error already reported */
1181                         status = PSQL_CMD_ERROR;
1182                 }
1183                 else
1184                 {
1185                         FILE       *output;
1186                         bool            is_pager;
1187
1188                         /* Select output stream: stdout, pager, or file */
1189                         if (pset.queryFout == stdout)
1190                         {
1191                                 /* count lines in function to see if pager is needed */
1192                                 int                     lineno = 0;
1193                                 const char *lines = func_buf->data;
1194
1195                                 while (*lines != '\0')
1196                                 {
1197                                         lineno++;
1198                                         /* find start of next line */
1199                                         lines = strchr(lines, '\n');
1200                                         if (!lines)
1201                                                 break;
1202                                         lines++;
1203                                 }
1204
1205                                 output = PageOutput(lineno, pset.popt.topt.pager);
1206                                 is_pager = true;
1207                         }
1208                         else
1209                         {
1210                                 /* use previously set output file, without pager */
1211                                 output = pset.queryFout;
1212                                 is_pager = false;
1213                         }
1214
1215                         if (show_linenumbers)
1216                         {
1217                                 bool            in_header = true;
1218                                 int                     lineno = 0;
1219                                 char       *lines = func_buf->data;
1220
1221                                 /*
1222                                  * lineno "1" should correspond to the first line of the
1223                                  * function body.  We expect that pg_get_functiondef() will
1224                                  * emit that on a line beginning with "AS ", and that there
1225                                  * can be no such line before the real start of the function
1226                                  * body.
1227                                  *
1228                                  * Note that this loop scribbles on func_buf.
1229                                  */
1230                                 while (*lines != '\0')
1231                                 {
1232                                         char       *eol;
1233
1234                                         if (in_header && strncmp(lines, "AS ", 3) == 0)
1235                                                 in_header = false;
1236                                         /* increment lineno only for body's lines */
1237                                         if (!in_header)
1238                                                 lineno++;
1239
1240                                         /* find and mark end of current line */
1241                                         eol = strchr(lines, '\n');
1242                                         if (eol != NULL)
1243                                                 *eol = '\0';
1244
1245                                         /* show current line as appropriate */
1246                                         if (in_header)
1247                                                 fprintf(output, "        %s\n", lines);
1248                                         else
1249                                                 fprintf(output, "%-7d %s\n", lineno, lines);
1250
1251                                         /* advance to next line, if any */
1252                                         if (eol == NULL)
1253                                                 break;
1254                                         lines = ++eol;
1255                                 }
1256                         }
1257                         else
1258                         {
1259                                 /* just send the function definition to output */
1260                                 fputs(func_buf->data, output);
1261                         }
1262
1263                         if (is_pager)
1264                                 ClosePager(output);
1265                 }
1266
1267                 if (func)
1268                         free(func);
1269                 destroyPQExpBuffer(func_buf);
1270         }
1271
1272         /* \t -- turn off headers and row count */
1273         else if (strcmp(cmd, "t") == 0)
1274         {
1275                 char       *opt = psql_scan_slash_option(scan_state,
1276                                                                                                  OT_NORMAL, NULL, true);
1277
1278                 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1279                 free(opt);
1280         }
1281
1282         /* \T -- define html <table ...> attributes */
1283         else if (strcmp(cmd, "T") == 0)
1284         {
1285                 char       *value = psql_scan_slash_option(scan_state,
1286                                                                                                    OT_NORMAL, NULL, false);
1287
1288                 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1289                 free(value);
1290         }
1291
1292         /* \timing -- toggle timing of queries */
1293         else if (strcmp(cmd, "timing") == 0)
1294         {
1295                 char       *opt = psql_scan_slash_option(scan_state,
1296                                                                                                  OT_NORMAL, NULL, false);
1297
1298                 if (opt)
1299                         pset.timing = ParseVariableBool(opt);
1300                 else
1301                         pset.timing = !pset.timing;
1302                 if (!pset.quiet)
1303                 {
1304                         if (pset.timing)
1305                                 puts(_("Timing is on."));
1306                         else
1307                                 puts(_("Timing is off."));
1308                 }
1309                 free(opt);
1310         }
1311
1312         /* \unset */
1313         else if (strcmp(cmd, "unset") == 0)
1314         {
1315                 char       *opt = psql_scan_slash_option(scan_state,
1316                                                                                                  OT_NORMAL, NULL, false);
1317
1318                 if (!opt)
1319                 {
1320                         psql_error("\\%s: missing required argument\n", cmd);
1321                         success = false;
1322                 }
1323                 else if (!SetVariable(pset.vars, opt, NULL))
1324                 {
1325                         psql_error("\\%s: error while setting variable\n", cmd);
1326                         success = false;
1327                 }
1328                 free(opt);
1329         }
1330
1331         /* \w -- write query buffer to file */
1332         else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1333         {
1334                 FILE       *fd = NULL;
1335                 bool            is_pipe = false;
1336                 char       *fname = NULL;
1337
1338                 if (!query_buf)
1339                 {
1340                         psql_error("no query buffer\n");
1341                         status = PSQL_CMD_ERROR;
1342                 }
1343                 else
1344                 {
1345                         fname = psql_scan_slash_option(scan_state,
1346                                                                                    OT_FILEPIPE, NULL, true);
1347                         expand_tilde(&fname);
1348
1349                         if (!fname)
1350                         {
1351                                 psql_error("\\%s: missing required argument\n", cmd);
1352                                 success = false;
1353                         }
1354                         else
1355                         {
1356                                 if (fname[0] == '|')
1357                                 {
1358                                         is_pipe = true;
1359                                         fd = popen(&fname[1], "w");
1360                                 }
1361                                 else
1362                                 {
1363                                         canonicalize_path(fname);
1364                                         fd = fopen(fname, "w");
1365                                 }
1366                                 if (!fd)
1367                                 {
1368                                         psql_error("%s: %s\n", fname, strerror(errno));
1369                                         success = false;
1370                                 }
1371                         }
1372                 }
1373
1374                 if (fd)
1375                 {
1376                         int                     result;
1377
1378                         if (query_buf && query_buf->len > 0)
1379                                 fprintf(fd, "%s\n", query_buf->data);
1380
1381                         if (is_pipe)
1382                                 result = pclose(fd);
1383                         else
1384                                 result = fclose(fd);
1385
1386                         if (result == EOF)
1387                         {
1388                                 psql_error("%s: %s\n", fname, strerror(errno));
1389                                 success = false;
1390                         }
1391                 }
1392
1393                 free(fname);
1394         }
1395
1396         /* \x -- set or toggle expanded table representation */
1397         else if (strcmp(cmd, "x") == 0)
1398         {
1399                 char       *opt = psql_scan_slash_option(scan_state,
1400                                                                                                  OT_NORMAL, NULL, true);
1401
1402                 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1403                 free(opt);
1404         }
1405
1406         /* \z -- list table rights (equivalent to \dp) */
1407         else if (strcmp(cmd, "z") == 0)
1408         {
1409                 char       *pattern = psql_scan_slash_option(scan_state,
1410                                                                                                          OT_NORMAL, NULL, true);
1411
1412                 success = permissionsList(pattern);
1413                 if (pattern)
1414                         free(pattern);
1415         }
1416
1417         /* \! -- shell escape */
1418         else if (strcmp(cmd, "!") == 0)
1419         {
1420                 char       *opt = psql_scan_slash_option(scan_state,
1421                                                                                                  OT_WHOLE_LINE, NULL, false);
1422
1423                 success = do_shell(opt);
1424                 free(opt);
1425         }
1426
1427         /* \? -- slash command help */
1428         else if (strcmp(cmd, "?") == 0)
1429                 slashUsage(pset.popt.topt.pager);
1430
1431 #if 0
1432
1433         /*
1434          * These commands don't do anything. I just use them to test the parser.
1435          */
1436         else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1437         {
1438                 int                     i = 0;
1439                 char       *value;
1440
1441                 while ((value = psql_scan_slash_option(scan_state,
1442                                                                                            OT_NORMAL, NULL, true)))
1443                 {
1444                         psql_error("+ opt(%d) = |%s|\n", i++, value);
1445                         free(value);
1446                 }
1447         }
1448 #endif
1449
1450         else
1451                 status = PSQL_CMD_UNKNOWN;
1452
1453         if (!success)
1454                 status = PSQL_CMD_ERROR;
1455
1456         return status;
1457 }
1458
1459 /*
1460  * Ask the user for a password; 'username' is the username the
1461  * password is for, if one has been explicitly specified. Returns a
1462  * malloc'd string.
1463  */
1464 static char *
1465 prompt_for_password(const char *username)
1466 {
1467         char       *result;
1468
1469         if (username == NULL)
1470                 result = simple_prompt("Password: ", 100, false);
1471         else
1472         {
1473                 char       *prompt_text;
1474
1475                 prompt_text = pg_malloc(strlen(username) + 100);
1476                 snprintf(prompt_text, strlen(username) + 100,
1477                                  _("Password for user %s: "), username);
1478                 result = simple_prompt(prompt_text, 100, false);
1479                 free(prompt_text);
1480         }
1481
1482         return result;
1483 }
1484
1485 static bool
1486 param_is_newly_set(const char *old_val, const char *new_val)
1487 {
1488         if (new_val == NULL)
1489                 return false;
1490
1491         if (old_val == NULL || strcmp(old_val, new_val) != 0)
1492                 return true;
1493
1494         return false;
1495 }
1496
1497 /*
1498  * do_connect -- handler for \connect
1499  *
1500  * Connects to a database with given parameters. If there exists an
1501  * established connection, NULL values will be replaced with the ones
1502  * in the current connection. Otherwise NULL will be passed for that
1503  * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1504  *
1505  * In interactive mode, if connection fails with the given parameters,
1506  * the old connection will be kept.
1507  */
1508 static bool
1509 do_connect(char *dbname, char *user, char *host, char *port)
1510 {
1511         PGconn     *o_conn = pset.db,
1512                            *n_conn;
1513         char       *password = NULL;
1514
1515         if (!o_conn && (!dbname || !user || !host || !port))
1516         {
1517                 /*
1518                  *      We don't know the supplied connection parameters and don't want
1519                  *      to connect to the wrong database by using defaults, so require
1520                  *      all parameters to be specified.
1521                  */
1522                 psql_error("All connection parameters must be supplied because no "
1523                                    "database connection exists\n");
1524                 return false;
1525         }
1526
1527         if (!dbname)
1528                 dbname = PQdb(o_conn);
1529         if (!user)
1530                 user = PQuser(o_conn);
1531         if (!host)
1532                 host = PQhost(o_conn);
1533         if (!port)
1534                 port = PQport(o_conn);
1535
1536         /*
1537          * If the user asked to be prompted for a password, ask for one now. If
1538          * not, use the password from the old connection, provided the username
1539          * has not changed. Otherwise, try to connect without a password first,
1540          * and then ask for a password if needed.
1541          *
1542          * XXX: this behavior leads to spurious connection attempts recorded in
1543          * the postmaster's log.  But libpq offers no API that would let us obtain
1544          * a password and then continue with the first connection attempt.
1545          */
1546         if (pset.getPassword == TRI_YES)
1547         {
1548                 password = prompt_for_password(user);
1549         }
1550         else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1551         {
1552                 password = pg_strdup(PQpass(o_conn));
1553         }
1554
1555         while (true)
1556         {
1557 #define PARAMS_ARRAY_SIZE       8
1558                 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1559                 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1560
1561                 keywords[0] = "host";
1562                 values[0] = host;
1563                 keywords[1] = "port";
1564                 values[1] = port;
1565                 keywords[2] = "user";
1566                 values[2] = user;
1567                 keywords[3] = "password";
1568                 values[3] = password;
1569                 keywords[4] = "dbname";
1570                 values[4] = dbname;
1571                 keywords[5] = "fallback_application_name";
1572                 values[5] = pset.progname;
1573                 keywords[6] = "client_encoding";
1574                 values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
1575                 keywords[7] = NULL;
1576                 values[7] = NULL;
1577
1578                 n_conn = PQconnectdbParams(keywords, values, true);
1579
1580                 free(keywords);
1581                 free(values);
1582
1583                 /* We can immediately discard the password -- no longer needed */
1584                 if (password)
1585                         free(password);
1586
1587                 if (PQstatus(n_conn) == CONNECTION_OK)
1588                         break;
1589
1590                 /*
1591                  * Connection attempt failed; either retry the connection attempt with
1592                  * a new password, or give up.
1593                  */
1594                 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1595                 {
1596                         PQfinish(n_conn);
1597                         password = prompt_for_password(user);
1598                         continue;
1599                 }
1600
1601                 /*
1602                  * Failed to connect to the database. In interactive mode, keep the
1603                  * previous connection to the DB; in scripting mode, close our
1604                  * previous connection as well.
1605                  */
1606                 if (pset.cur_cmd_interactive)
1607                 {
1608                         psql_error("%s", PQerrorMessage(n_conn));
1609
1610                         /* pset.db is left unmodified */
1611                         if (o_conn)
1612                                 psql_error("Previous connection kept\n");
1613                 }
1614                 else
1615                 {
1616                         psql_error("\\connect: %s", PQerrorMessage(n_conn));
1617                         if (o_conn)
1618                         {
1619                                 PQfinish(o_conn);
1620                                 pset.db = NULL;
1621                         }
1622                 }
1623
1624                 PQfinish(n_conn);
1625                 return false;
1626         }
1627
1628         /*
1629          * Replace the old connection with the new one, and update
1630          * connection-dependent variables.
1631          */
1632         PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1633         pset.db = n_conn;
1634         SyncVariables();
1635         connection_warnings(false); /* Must be after SyncVariables */
1636
1637         /* Tell the user about the new connection */
1638         if (!pset.quiet)
1639         {
1640                 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
1641                         param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1642                 {
1643                         char       *host = PQhost(pset.db);
1644
1645                         if (host == NULL)
1646                                 host = DEFAULT_PGSOCKET_DIR;
1647                         /* If the host is an absolute path, the connection is via socket */
1648                         if (is_absolute_path(host))
1649                                 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
1650                                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1651                         else
1652                                 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
1653                                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1654                 }
1655                 else
1656                         printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
1657                                    PQdb(pset.db), PQuser(pset.db));
1658         }
1659
1660         if (o_conn)
1661                 PQfinish(o_conn);
1662         return true;
1663 }
1664
1665
1666 void
1667 connection_warnings(bool in_startup)
1668 {
1669         if (!pset.quiet && !pset.notty)
1670         {
1671                 int                     client_ver = parse_version(PG_VERSION);
1672
1673                 if (pset.sversion != client_ver)
1674                 {
1675                         const char *server_version;
1676                         char            server_ver_str[16];
1677
1678                         /* Try to get full text form, might include "devel" etc */
1679                         server_version = PQparameterStatus(pset.db, "server_version");
1680                         if (!server_version)
1681                         {
1682                                 snprintf(server_ver_str, sizeof(server_ver_str),
1683                                                  "%d.%d.%d",
1684                                                  pset.sversion / 10000,
1685                                                  (pset.sversion / 100) % 100,
1686                                                  pset.sversion % 100);
1687                                 server_version = server_ver_str;
1688                         }
1689
1690                         printf(_("%s (%s, server %s)\n"),
1691                                    pset.progname, PG_VERSION, server_version);
1692                 }
1693                 /* For version match, only print psql banner on startup. */
1694                 else if (in_startup)
1695                         printf("%s (%s)\n", pset.progname, PG_VERSION);
1696
1697                 if (pset.sversion / 100 > client_ver / 100)
1698                         printf(_("WARNING: %s major version %d.%d, server major version %d.%d.\n"
1699                                          "         Some psql features might not work.\n"),
1700                                  pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1701                                    pset.sversion / 10000, (pset.sversion / 100) % 100);
1702
1703 #ifdef WIN32
1704                 checkWin32Codepage();
1705 #endif
1706                 printSSLInfo();
1707         }
1708 }
1709
1710
1711 /*
1712  * printSSLInfo
1713  *
1714  * Prints information about the current SSL connection, if SSL is in use
1715  */
1716 static void
1717 printSSLInfo(void)
1718 {
1719 #ifdef USE_SSL
1720         int                     sslbits = -1;
1721         SSL                *ssl;
1722
1723         ssl = PQgetssl(pset.db);
1724         if (!ssl)
1725                 return;                                 /* no SSL */
1726
1727         SSL_get_cipher_bits(ssl, &sslbits);
1728         printf(_("SSL connection (cipher: %s, bits: %d)\n"),
1729                    SSL_get_cipher(ssl), sslbits);
1730 #else
1731
1732         /*
1733          * If psql is compiled without SSL but is using a libpq with SSL, we
1734          * cannot figure out the specifics about the connection. But we know it's
1735          * SSL secured.
1736          */
1737         if (PQgetssl(pset.db))
1738                 printf(_("SSL connection (unknown cipher)\n"));
1739 #endif
1740 }
1741
1742
1743 /*
1744  * checkWin32Codepage
1745  *
1746  * Prints a warning when win32 console codepage differs from Windows codepage
1747  */
1748 #ifdef WIN32
1749 static void
1750 checkWin32Codepage(void)
1751 {
1752         unsigned int wincp,
1753                                 concp;
1754
1755         wincp = GetACP();
1756         concp = GetConsoleCP();
1757         if (wincp != concp)
1758         {
1759                 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1760                                  "         8-bit characters might not work correctly. See psql reference\n"
1761                                  "         page \"Notes for Windows users\" for details.\n"),
1762                            concp, wincp);
1763         }
1764 }
1765 #endif
1766
1767
1768 /*
1769  * SyncVariables
1770  *
1771  * Make psql's internal variables agree with connection state upon
1772  * establishing a new connection.
1773  */
1774 void
1775 SyncVariables(void)
1776 {
1777         /* get stuff from connection */
1778         pset.encoding = PQclientEncoding(pset.db);
1779         pset.popt.topt.encoding = pset.encoding;
1780         pset.sversion = PQserverVersion(pset.db);
1781
1782         SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1783         SetVariable(pset.vars, "USER", PQuser(pset.db));
1784         SetVariable(pset.vars, "HOST", PQhost(pset.db));
1785         SetVariable(pset.vars, "PORT", PQport(pset.db));
1786         SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1787
1788         /* send stuff to it, too */
1789         PQsetErrorVerbosity(pset.db, pset.verbosity);
1790 }
1791
1792 /*
1793  * UnsyncVariables
1794  *
1795  * Clear variables that should be not be set when there is no connection.
1796  */
1797 void
1798 UnsyncVariables(void)
1799 {
1800         SetVariable(pset.vars, "DBNAME", NULL);
1801         SetVariable(pset.vars, "USER", NULL);
1802         SetVariable(pset.vars, "HOST", NULL);
1803         SetVariable(pset.vars, "PORT", NULL);
1804         SetVariable(pset.vars, "ENCODING", NULL);
1805 }
1806
1807
1808 /*
1809  * do_edit -- handler for \e
1810  *
1811  * If you do not specify a filename, the current query buffer will be copied
1812  * into a temporary one.
1813  */
1814 static bool
1815 editFile(const char *fname, int lineno)
1816 {
1817         const char *editorName;
1818         const char *editor_lineno_arg = NULL;
1819         char       *sys;
1820         int                     result;
1821
1822         Assert(fname != NULL);
1823
1824         /* Find an editor to use */
1825         editorName = getenv("PSQL_EDITOR");
1826         if (!editorName)
1827                 editorName = getenv("EDITOR");
1828         if (!editorName)
1829                 editorName = getenv("VISUAL");
1830         if (!editorName)
1831                 editorName = DEFAULT_EDITOR;
1832
1833         /* Get line number argument, if we need it. */
1834         if (lineno > 0)
1835         {
1836                 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
1837 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
1838                 if (!editor_lineno_arg)
1839                         editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
1840 #endif
1841                 if (!editor_lineno_arg)
1842                 {
1843                         psql_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number\n");
1844                         return false;
1845                 }
1846         }
1847
1848         /* Allocate sufficient memory for command line. */
1849         if (lineno > 0)
1850                 sys = pg_malloc(strlen(editorName)
1851                                                 + strlen(editor_lineno_arg) + 10                /* for integer */
1852                                                 + 1 + strlen(fname) + 10 + 1);
1853         else
1854                 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1855
1856         /*
1857          * On Unix the EDITOR value should *not* be quoted, since it might include
1858          * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1859          * if necessary.  But this policy is not very workable on Windows, due to
1860          * severe brain damage in their command shell plus the fact that standard
1861          * program paths include spaces.
1862          */
1863 #ifndef WIN32
1864         if (lineno > 0)
1865                 sprintf(sys, "exec %s %s%d '%s'",
1866                                 editorName, editor_lineno_arg, lineno, fname);
1867         else
1868                 sprintf(sys, "exec %s '%s'",
1869                                 editorName, fname);
1870 #else
1871         if (lineno > 0)
1872                 sprintf(sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE,
1873                                 editorName, editor_lineno_arg, lineno, fname);
1874         else
1875                 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE,
1876                                 editorName, fname);
1877 #endif
1878         result = system(sys);
1879         if (result == -1)
1880                 psql_error("could not start editor \"%s\"\n", editorName);
1881         else if (result == 127)
1882                 psql_error("could not start /bin/sh\n");
1883         free(sys);
1884
1885         return result == 0;
1886 }
1887
1888
1889 /* call this one */
1890 static bool
1891 do_edit(const char *filename_arg, PQExpBuffer query_buf,
1892                 int lineno, bool *edited)
1893 {
1894         char            fnametmp[MAXPGPATH];
1895         FILE       *stream = NULL;
1896         const char *fname;
1897         bool            error = false;
1898         int                     fd;
1899
1900         struct stat before,
1901                                 after;
1902
1903         if (filename_arg)
1904                 fname = filename_arg;
1905         else
1906         {
1907                 /* make a temp file to edit */
1908 #ifndef WIN32
1909                 const char *tmpdir = getenv("TMPDIR");
1910
1911                 if (!tmpdir)
1912                         tmpdir = "/tmp";
1913 #else
1914                 char            tmpdir[MAXPGPATH];
1915                 int                     ret;
1916
1917                 ret = GetTempPath(MAXPGPATH, tmpdir);
1918                 if (ret == 0 || ret > MAXPGPATH)
1919                 {
1920                         psql_error("could not locate temporary directory: %s\n",
1921                                            !ret ? strerror(errno) : "");
1922                         return false;
1923                 }
1924
1925                 /*
1926                  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1927                  * current directory to the supplied path unless we use only
1928                  * backslashes, so we do that.
1929                  */
1930 #endif
1931 #ifndef WIN32
1932                 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1933                                  "/", (int) getpid());
1934 #else
1935                 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1936                            "" /* trailing separator already present */ , (int) getpid());
1937 #endif
1938
1939                 fname = (const char *) fnametmp;
1940
1941                 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1942                 if (fd != -1)
1943                         stream = fdopen(fd, "w");
1944
1945                 if (fd == -1 || !stream)
1946                 {
1947                         psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1948                         error = true;
1949                 }
1950                 else
1951                 {
1952                         unsigned int ql = query_buf->len;
1953
1954                         if (ql == 0 || query_buf->data[ql - 1] != '\n')
1955                         {
1956                                 appendPQExpBufferChar(query_buf, '\n');
1957                                 ql++;
1958                         }
1959
1960                         if (fwrite(query_buf->data, 1, ql, stream) != ql)
1961                         {
1962                                 psql_error("%s: %s\n", fname, strerror(errno));
1963                                 fclose(stream);
1964                                 remove(fname);
1965                                 error = true;
1966                         }
1967                         else if (fclose(stream) != 0)
1968                         {
1969                                 psql_error("%s: %s\n", fname, strerror(errno));
1970                                 remove(fname);
1971                                 error = true;
1972                         }
1973                 }
1974         }
1975
1976         if (!error && stat(fname, &before) != 0)
1977         {
1978                 psql_error("%s: %s\n", fname, strerror(errno));
1979                 error = true;
1980         }
1981
1982         /* call editor */
1983         if (!error)
1984                 error = !editFile(fname, lineno);
1985
1986         if (!error && stat(fname, &after) != 0)
1987         {
1988                 psql_error("%s: %s\n", fname, strerror(errno));
1989                 error = true;
1990         }
1991
1992         if (!error && before.st_mtime != after.st_mtime)
1993         {
1994                 stream = fopen(fname, PG_BINARY_R);
1995                 if (!stream)
1996                 {
1997                         psql_error("%s: %s\n", fname, strerror(errno));
1998                         error = true;
1999                 }
2000                 else
2001                 {
2002                         /* read file back into query_buf */
2003                         char            line[1024];
2004
2005                         resetPQExpBuffer(query_buf);
2006                         while (fgets(line, sizeof(line), stream) != NULL)
2007                                 appendPQExpBufferStr(query_buf, line);
2008
2009                         if (ferror(stream))
2010                         {
2011                                 psql_error("%s: %s\n", fname, strerror(errno));
2012                                 error = true;
2013                         }
2014                         else if (edited)
2015                         {
2016                                 *edited = true;
2017                         }
2018
2019                         fclose(stream);
2020                 }
2021         }
2022
2023         /* remove temp file */
2024         if (!filename_arg)
2025         {
2026                 if (remove(fname) == -1)
2027                 {
2028                         psql_error("%s: %s\n", fname, strerror(errno));
2029                         error = true;
2030                 }
2031         }
2032
2033         return !error;
2034 }
2035
2036
2037
2038 /*
2039  * process_file
2040  *
2041  * Read commands from filename and then them to the main processing loop
2042  * Handler for \i and \ir, but can be used for other things as well.  Returns
2043  * MainLoop() error code.
2044  *
2045  * If use_relative_path is true and filename is not an absolute path, then open
2046  * the file from where the currently processed file (if any) is located.
2047  */
2048 int
2049 process_file(char *filename, bool single_txn, bool use_relative_path)
2050 {
2051         FILE       *fd;
2052         int                     result;
2053         char       *oldfilename;
2054         char            relpath[MAXPGPATH];
2055         PGresult   *res;
2056
2057         if (!filename)
2058         {
2059                 fd = stdin;
2060                 filename = NULL;
2061         }
2062         else if (strcmp(filename, "-") != 0)
2063         {
2064                 canonicalize_path(filename);
2065
2066                 /*
2067                  * If we were asked to resolve the pathname relative to the location
2068                  * of the currently executing script, and there is one, and this is a
2069                  * relative pathname, then prepend all but the last pathname component
2070                  * of the current script to this pathname.
2071                  */
2072                 if (use_relative_path && pset.inputfile &&
2073                         !is_absolute_path(filename) && !has_drive_prefix(filename))
2074                 {
2075                         strlcpy(relpath, pset.inputfile, sizeof(relpath));
2076                         get_parent_directory(relpath);
2077                         join_path_components(relpath, relpath, filename);
2078                         canonicalize_path(relpath);
2079
2080                         filename = relpath;
2081                 }
2082
2083                 fd = fopen(filename, PG_BINARY_R);
2084
2085                 if (!fd)
2086                 {
2087                         psql_error("%s: %s\n", filename, strerror(errno));
2088                         return EXIT_FAILURE;
2089                 }
2090         }
2091         else
2092         {
2093                 fd = stdin;
2094                 filename = "<stdin>";   /* for future error messages */
2095         }
2096
2097         oldfilename = pset.inputfile;
2098         pset.inputfile = filename;
2099
2100         if (single_txn)
2101         {
2102                 if ((res = PSQLexec("BEGIN", false)) == NULL)
2103                 {
2104                         if (pset.on_error_stop)
2105                         {
2106                                 result = EXIT_USER;
2107                                 goto error;
2108                         }
2109                 }
2110                 else
2111                         PQclear(res);
2112         }
2113
2114         result = MainLoop(fd);
2115
2116         if (single_txn)
2117         {
2118                 if ((res = PSQLexec("COMMIT", false)) == NULL)
2119                 {
2120                         if (pset.on_error_stop)
2121                         {
2122                                 result = EXIT_USER;
2123                                 goto error;
2124                         }
2125                 }
2126                 else
2127                         PQclear(res);
2128         }
2129
2130 error:
2131         if (fd != stdin)
2132                 fclose(fd);
2133
2134         pset.inputfile = oldfilename;
2135         return result;
2136 }
2137
2138
2139
2140 /*
2141  * do_pset
2142  *
2143  */
2144 static const char *
2145 _align2string(enum printFormat in)
2146 {
2147         switch (in)
2148         {
2149                 case PRINT_NOTHING:
2150                         return "nothing";
2151                         break;
2152                 case PRINT_UNALIGNED:
2153                         return "unaligned";
2154                         break;
2155                 case PRINT_ALIGNED:
2156                         return "aligned";
2157                         break;
2158                 case PRINT_WRAPPED:
2159                         return "wrapped";
2160                         break;
2161                 case PRINT_HTML:
2162                         return "html";
2163                         break;
2164                 case PRINT_LATEX:
2165                         return "latex";
2166                         break;
2167                 case PRINT_TROFF_MS:
2168                         return "troff-ms";
2169                         break;
2170         }
2171         return "unknown";
2172 }
2173
2174
2175 bool
2176 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
2177 {
2178         size_t          vallen = 0;
2179
2180         Assert(param != NULL);
2181
2182         if (value)
2183                 vallen = strlen(value);
2184
2185         /* set format */
2186         if (strcmp(param, "format") == 0)
2187         {
2188                 if (!value)
2189                         ;
2190                 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2191                         popt->topt.format = PRINT_UNALIGNED;
2192                 else if (pg_strncasecmp("aligned", value, vallen) == 0)
2193                         popt->topt.format = PRINT_ALIGNED;
2194                 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2195                         popt->topt.format = PRINT_WRAPPED;
2196                 else if (pg_strncasecmp("html", value, vallen) == 0)
2197                         popt->topt.format = PRINT_HTML;
2198                 else if (pg_strncasecmp("latex", value, vallen) == 0)
2199                         popt->topt.format = PRINT_LATEX;
2200                 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2201                         popt->topt.format = PRINT_TROFF_MS;
2202                 else
2203                 {
2204                         psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
2205                         return false;
2206                 }
2207
2208                 if (!quiet)
2209                         printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2210         }
2211
2212         /* set table line style */
2213         else if (strcmp(param, "linestyle") == 0)
2214         {
2215                 if (!value)
2216                         ;
2217                 else if (pg_strncasecmp("ascii", value, vallen) == 0)
2218                         popt->topt.line_style = &pg_asciiformat;
2219                 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2220                         popt->topt.line_style = &pg_asciiformat_old;
2221                 else if (pg_strncasecmp("unicode", value, vallen) == 0)
2222                         popt->topt.line_style = &pg_utf8format;
2223                 else
2224                 {
2225                         psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2226                         return false;
2227                 }
2228
2229                 if (!quiet)
2230                         printf(_("Line style is %s.\n"),
2231                                    get_line_style(&popt->topt)->name);
2232         }
2233
2234         /* set border style/width */
2235         else if (strcmp(param, "border") == 0)
2236         {
2237                 if (value)
2238                         popt->topt.border = atoi(value);
2239
2240                 if (!quiet)
2241                         printf(_("Border style is %d.\n"), popt->topt.border);
2242         }
2243
2244         /* set expanded/vertical mode */
2245         else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2246         {
2247                 if (value && pg_strcasecmp(value, "auto") == 0)
2248                         popt->topt.expanded = 2;
2249                 else if (value)
2250                         popt->topt.expanded = ParseVariableBool(value);
2251                 else
2252                         popt->topt.expanded = !popt->topt.expanded;
2253                 if (!quiet)
2254                 {
2255                         if (popt->topt.expanded == 1)
2256                                 printf(_("Expanded display is on.\n"));
2257                         else if (popt->topt.expanded == 2)
2258                                 printf(_("Expanded display is used automatically.\n"));
2259                         else
2260                                 printf(_("Expanded display is off.\n"));
2261                 }
2262         }
2263
2264         /* locale-aware numeric output */
2265         else if (strcmp(param, "numericlocale") == 0)
2266         {
2267                 if (value)
2268                         popt->topt.numericLocale = ParseVariableBool(value);
2269                 else
2270                         popt->topt.numericLocale = !popt->topt.numericLocale;
2271                 if (!quiet)
2272                 {
2273                         if (popt->topt.numericLocale)
2274                                 puts(_("Showing locale-adjusted numeric output."));
2275                         else
2276                                 puts(_("Locale-adjusted numeric output is off."));
2277                 }
2278         }
2279
2280         /* null display */
2281         else if (strcmp(param, "null") == 0)
2282         {
2283                 if (value)
2284                 {
2285                         free(popt->nullPrint);
2286                         popt->nullPrint = pg_strdup(value);
2287                 }
2288                 if (!quiet)
2289                         printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
2290         }
2291
2292         /* field separator for unaligned text */
2293         else if (strcmp(param, "fieldsep") == 0)
2294         {
2295                 if (value)
2296                 {
2297                         free(popt->topt.fieldSep.separator);
2298                         popt->topt.fieldSep.separator = pg_strdup(value);
2299                         popt->topt.fieldSep.separator_zero = false;
2300                 }
2301                 if (!quiet)
2302                 {
2303                         if (popt->topt.fieldSep.separator_zero)
2304                                 printf(_("Field separator is zero byte.\n"));
2305                         else
2306                                 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep.separator);
2307                 }
2308         }
2309
2310         else if (strcmp(param, "fieldsep_zero") == 0)
2311         {
2312                 free(popt->topt.fieldSep.separator);
2313                 popt->topt.fieldSep.separator = NULL;
2314                 popt->topt.fieldSep.separator_zero = true;
2315                 if (!quiet)
2316                         printf(_("Field separator is zero byte.\n"));
2317         }
2318
2319         /* record separator for unaligned text */
2320         else if (strcmp(param, "recordsep") == 0)
2321         {
2322                 if (value)
2323                 {
2324                         free(popt->topt.recordSep.separator);
2325                         popt->topt.recordSep.separator = pg_strdup(value);
2326                         popt->topt.recordSep.separator_zero = false;
2327                 }
2328                 if (!quiet)
2329                 {
2330                         if (popt->topt.recordSep.separator_zero)
2331                                 printf(_("Record separator is zero byte.\n"));
2332                         else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
2333                                 printf(_("Record separator is <newline>."));
2334                         else
2335                                 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep.separator);
2336                 }
2337         }
2338
2339         else if (strcmp(param, "recordsep_zero") == 0)
2340         {
2341                 free(popt->topt.recordSep.separator);
2342                 popt->topt.recordSep.separator = NULL;
2343                 popt->topt.recordSep.separator_zero = true;
2344                 if (!quiet)
2345                         printf(_("Record separator is zero byte.\n"));
2346         }
2347
2348         /* toggle between full and tuples-only format */
2349         else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2350         {
2351                 if (value)
2352                         popt->topt.tuples_only = ParseVariableBool(value);
2353                 else
2354                         popt->topt.tuples_only = !popt->topt.tuples_only;
2355                 if (!quiet)
2356                 {
2357                         if (popt->topt.tuples_only)
2358                                 puts(_("Showing only tuples."));
2359                         else
2360                                 puts(_("Tuples only is off."));
2361                 }
2362         }
2363
2364         /* set title override */
2365         else if (strcmp(param, "title") == 0)
2366         {
2367                 free(popt->title);
2368                 if (!value)
2369                         popt->title = NULL;
2370                 else
2371                         popt->title = pg_strdup(value);
2372
2373                 if (!quiet)
2374                 {
2375                         if (popt->title)
2376                                 printf(_("Title is \"%s\".\n"), popt->title);
2377                         else
2378                                 printf(_("Title is unset.\n"));
2379                 }
2380         }
2381
2382         /* set HTML table tag options */
2383         else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2384         {
2385                 free(popt->topt.tableAttr);
2386                 if (!value)
2387                         popt->topt.tableAttr = NULL;
2388                 else
2389                         popt->topt.tableAttr = pg_strdup(value);
2390
2391                 if (!quiet)
2392                 {
2393                         if (popt->topt.tableAttr)
2394                                 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
2395                         else
2396                                 printf(_("Table attributes unset.\n"));
2397                 }
2398         }
2399
2400         /* toggle use of pager */
2401         else if (strcmp(param, "pager") == 0)
2402         {
2403                 if (value && pg_strcasecmp(value, "always") == 0)
2404                         popt->topt.pager = 2;
2405                 else if (value)
2406                         if (ParseVariableBool(value))
2407                                 popt->topt.pager = 1;
2408                         else
2409                                 popt->topt.pager = 0;
2410                 else if (popt->topt.pager == 1)
2411                         popt->topt.pager = 0;
2412                 else
2413                         popt->topt.pager = 1;
2414                 if (!quiet)
2415                 {
2416                         if (popt->topt.pager == 1)
2417                                 puts(_("Pager is used for long output."));
2418                         else if (popt->topt.pager == 2)
2419                                 puts(_("Pager is always used."));
2420                         else
2421                                 puts(_("Pager usage is off."));
2422                 }
2423         }
2424
2425         /* disable "(x rows)" footer */
2426         else if (strcmp(param, "footer") == 0)
2427         {
2428                 if (value)
2429                         popt->topt.default_footer = ParseVariableBool(value);
2430                 else
2431                         popt->topt.default_footer = !popt->topt.default_footer;
2432                 if (!quiet)
2433                 {
2434                         if (popt->topt.default_footer)
2435                                 puts(_("Default footer is on."));
2436                         else
2437                                 puts(_("Default footer is off."));
2438                 }
2439         }
2440
2441         /* set border style/width */
2442         else if (strcmp(param, "columns") == 0)
2443         {
2444                 if (value)
2445                         popt->topt.columns = atoi(value);
2446
2447                 if (!quiet)
2448                         printf(_("Target width is %d.\n"), popt->topt.columns);
2449         }
2450
2451         else
2452         {
2453                 psql_error("\\pset: unknown option: %s\n", param);
2454                 return false;
2455         }
2456
2457         return true;
2458 }
2459
2460
2461
2462 #ifndef WIN32
2463 #define DEFAULT_SHELL "/bin/sh"
2464 #else
2465 /*
2466  *      CMD.EXE is in different places in different Win32 releases so we
2467  *      have to rely on the path to find it.
2468  */
2469 #define DEFAULT_SHELL "cmd.exe"
2470 #endif
2471
2472 static bool
2473 do_shell(const char *command)
2474 {
2475         int                     result;
2476
2477         if (!command)
2478         {
2479                 char       *sys;
2480                 const char *shellName;
2481
2482                 shellName = getenv("SHELL");
2483 #ifdef WIN32
2484                 if (shellName == NULL)
2485                         shellName = getenv("COMSPEC");
2486 #endif
2487                 if (shellName == NULL)
2488                         shellName = DEFAULT_SHELL;
2489
2490                 sys = pg_malloc(strlen(shellName) + 16);
2491 #ifndef WIN32
2492                 sprintf(sys,
2493                 /* See EDITOR handling comment for an explanation */
2494                                 "exec %s", shellName);
2495 #else
2496                 /* See EDITOR handling comment for an explanation */
2497                 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2498 #endif
2499                 result = system(sys);
2500                 free(sys);
2501         }
2502         else
2503                 result = system(command);
2504
2505         if (result == 127 || result == -1)
2506         {
2507                 psql_error("\\!: failed\n");
2508                 return false;
2509         }
2510         return true;
2511 }
2512
2513 /*
2514  * This function takes a function description, e.g. "x" or "x(int)", and
2515  * issues a query on the given connection to retrieve the function's OID
2516  * using a cast to regproc or regprocedure (as appropriate). The result,
2517  * if there is one, is returned at *foid.  Note that we'll fail if the
2518  * function doesn't exist OR if there are multiple matching candidates
2519  * OR if there's something syntactically wrong with the function description;
2520  * unfortunately it can be hard to tell the difference.
2521  */
2522 static bool
2523 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2524 {
2525         bool            result = true;
2526         PQExpBuffer query;
2527         PGresult   *res;
2528
2529         query = createPQExpBuffer();
2530         printfPQExpBuffer(query, "SELECT ");
2531         appendStringLiteralConn(query, desc, conn);
2532         appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2533                                           strchr(desc, '(') ? "regprocedure" : "regproc");
2534
2535         res = PQexec(conn, query->data);
2536         if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2537                 *foid = atooid(PQgetvalue(res, 0, 0));
2538         else
2539         {
2540                 minimal_error_message(res);
2541                 result = false;
2542         }
2543
2544         PQclear(res);
2545         destroyPQExpBuffer(query);
2546
2547         return result;
2548 }
2549
2550 /*
2551  * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2552  * function with the given OID.  If successful, the result is stored in buf.
2553  */
2554 static bool
2555 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2556 {
2557         bool            result = true;
2558         PQExpBuffer query;
2559         PGresult   *res;
2560
2561         query = createPQExpBuffer();
2562         printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2563
2564         res = PQexec(conn, query->data);
2565         if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2566         {
2567                 resetPQExpBuffer(buf);
2568                 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2569         }
2570         else
2571         {
2572                 minimal_error_message(res);
2573                 result = false;
2574         }
2575
2576         PQclear(res);
2577         destroyPQExpBuffer(query);
2578
2579         return result;
2580 }
2581
2582 /*
2583  * If the given argument of \ef ends with a line number, delete the line
2584  * number from the argument string and return it as an integer.  (We need
2585  * this kluge because we're too lazy to parse \ef's function name argument
2586  * carefully --- we just slop it up in OT_WHOLE_LINE mode.)
2587  *
2588  * Returns -1 if no line number is present, 0 on error, or a positive value
2589  * on success.
2590  */
2591 static int
2592 strip_lineno_from_funcdesc(char *func)
2593 {
2594         char       *c;
2595         int                     lineno;
2596
2597         if (!func || func[0] == '\0')
2598                 return -1;
2599
2600         c = func + strlen(func) - 1;
2601
2602         /*
2603          * This business of parsing backwards is dangerous as can be in a
2604          * multibyte environment: there is no reason to believe that we are
2605          * looking at the first byte of a character, nor are we necessarily
2606          * working in a "safe" encoding.  Fortunately the bitpatterns we are
2607          * looking for are unlikely to occur as non-first bytes, but beware of
2608          * trying to expand the set of cases that can be recognized.  We must
2609          * guard the <ctype.h> macros by using isascii() first, too.
2610          */
2611
2612         /* skip trailing whitespace */
2613         while (c > func && isascii((unsigned char) *c) && isspace((unsigned char) *c))
2614                 c--;
2615
2616         /* must have a digit as last non-space char */
2617         if (c == func || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
2618                 return -1;
2619
2620         /* find start of digit string */
2621         while (c > func && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
2622                 c--;
2623
2624         /* digits must be separated from func name by space or closing paren */
2625         /* notice also that we are not allowing an empty func name ... */
2626         if (c == func || !isascii((unsigned char) *c) ||
2627                 !(isspace((unsigned char) *c) || *c == ')'))
2628                 return -1;
2629
2630         /* parse digit string */
2631         c++;
2632         lineno = atoi(c);
2633         if (lineno < 1)
2634         {
2635                 psql_error("invalid line number: %s\n", c);
2636                 return 0;
2637         }
2638
2639         /* strip digit string from func */
2640         *c = '\0';
2641
2642         return lineno;
2643 }
2644
2645 /*
2646  * Report just the primary error; this is to avoid cluttering the output
2647  * with, for instance, a redisplay of the internally generated query
2648  */
2649 static void
2650 minimal_error_message(PGresult *res)
2651 {
2652         PQExpBuffer msg;
2653         const char *fld;
2654
2655         msg = createPQExpBuffer();
2656
2657         fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2658         if (fld)
2659                 printfPQExpBuffer(msg, "%s:  ", fld);
2660         else
2661                 printfPQExpBuffer(msg, "ERROR:  ");
2662         fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2663         if (fld)
2664                 appendPQExpBufferStr(msg, fld);
2665         else
2666                 appendPQExpBufferStr(msg, "(not available)");
2667         appendPQExpBufferStr(msg, "\n");
2668
2669         psql_error("%s", msg->data);
2670
2671         destroyPQExpBuffer(msg);
2672 }