]> granicus.if.org Git - postgresql/blob - src/bin/psql/startup.c
Add psql variables showing server version and psql version.
[postgresql] / src / bin / psql / startup.c
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright (c) 2000-2017, PostgreSQL Global Development Group
5  *
6  * src/bin/psql/startup.c
7  */
8 #include "postgres_fe.h"
9
10 #ifndef WIN32
11 #include <unistd.h>
12 #else                                                   /* WIN32 */
13 #include <io.h>
14 #include <win32.h>
15 #endif                                                  /* WIN32 */
16
17 #include "getopt_long.h"
18
19 #include "command.h"
20 #include "common.h"
21 #include "describe.h"
22 #include "help.h"
23 #include "input.h"
24 #include "mainloop.h"
25 #include "fe_utils/print.h"
26 #include "settings.h"
27
28
29
30 /*
31  * Global psql options
32  */
33 PsqlSettings pset;
34
35 #ifndef WIN32
36 #define SYSPSQLRC       "psqlrc"
37 #define PSQLRC          ".psqlrc"
38 #else
39 #define SYSPSQLRC       "psqlrc"
40 #define PSQLRC          "psqlrc.conf"
41 #endif
42
43 /*
44  * Structures to pass information between the option parsing routine
45  * and the main function
46  */
47 enum _actions
48 {
49         ACT_SINGLE_QUERY,
50         ACT_SINGLE_SLASH,
51         ACT_FILE
52 };
53
54 typedef struct SimpleActionListCell
55 {
56         struct SimpleActionListCell *next;
57         enum _actions action;
58         char       *val;
59 } SimpleActionListCell;
60
61 typedef struct SimpleActionList
62 {
63         SimpleActionListCell *head;
64         SimpleActionListCell *tail;
65 } SimpleActionList;
66
67 struct adhoc_opts
68 {
69         char       *dbname;
70         char       *host;
71         char       *port;
72         char       *username;
73         char       *logfilename;
74         bool            no_readline;
75         bool            no_psqlrc;
76         bool            single_txn;
77         bool            list_dbs;
78         SimpleActionList actions;
79 };
80
81 static void parse_psql_options(int argc, char *argv[],
82                                    struct adhoc_opts *options);
83 static void simple_action_list_append(SimpleActionList *list,
84                                                   enum _actions action, const char *val);
85 static void process_psqlrc(char *argv0);
86 static void process_psqlrc_file(char *filename);
87 static void showVersion(void);
88 static void EstablishVariableSpace(void);
89
90 #define NOPAGER         0
91
92 /*
93  *
94  * main
95  *
96  */
97 int
98 main(int argc, char *argv[])
99 {
100         struct adhoc_opts options;
101         int                     successResult;
102         bool            have_password = false;
103         char            password[100];
104         char       *password_prompt = NULL;
105         bool            new_pass;
106
107         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("psql"));
108
109         if (argc > 1)
110         {
111                 if ((strcmp(argv[1], "-?") == 0) || (argc == 2 && (strcmp(argv[1], "--help") == 0)))
112                 {
113                         usage(NOPAGER);
114                         exit(EXIT_SUCCESS);
115                 }
116                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
117                 {
118                         showVersion();
119                         exit(EXIT_SUCCESS);
120                 }
121         }
122
123 #ifdef WIN32
124         setvbuf(stderr, NULL, _IONBF, 0);
125 #endif
126
127         pset.progname = get_progname(argv[0]);
128
129         pset.db = NULL;
130         setDecimalLocale();
131         pset.encoding = PQenv2encoding();
132         pset.queryFout = stdout;
133         pset.queryFoutPipe = false;
134         pset.copyStream = NULL;
135         pset.last_error_result = NULL;
136         pset.cur_cmd_source = stdin;
137         pset.cur_cmd_interactive = false;
138
139         /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
140         pset.popt.topt.format = PRINT_ALIGNED;
141         pset.popt.topt.border = 1;
142         pset.popt.topt.pager = 1;
143         pset.popt.topt.pager_min_lines = 0;
144         pset.popt.topt.start_table = true;
145         pset.popt.topt.stop_table = true;
146         pset.popt.topt.default_footer = true;
147
148         pset.popt.topt.unicode_border_linestyle = UNICODE_LINESTYLE_SINGLE;
149         pset.popt.topt.unicode_column_linestyle = UNICODE_LINESTYLE_SINGLE;
150         pset.popt.topt.unicode_header_linestyle = UNICODE_LINESTYLE_SINGLE;
151
152         refresh_utf8format(&(pset.popt.topt));
153
154         /* We must get COLUMNS here before readline() sets it */
155         pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;
156
157         pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
158
159         pset.getPassword = TRI_DEFAULT;
160
161         EstablishVariableSpace();
162
163         /* Create variables showing psql version number */
164         SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
165         SetVariable(pset.vars, "VERSION_NAME", PG_VERSION);
166         SetVariable(pset.vars, "VERSION_NUM", CppAsString2(PG_VERSION_NUM));
167
168         /* Default values for variables (that don't match the result of \unset) */
169         SetVariableBool(pset.vars, "AUTOCOMMIT");
170         SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
171         SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
172         SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
173
174         parse_psql_options(argc, argv, &options);
175
176         /*
177          * If no action was specified and we're in non-interactive mode, treat it
178          * as if the user had specified "-f -".  This lets single-transaction mode
179          * work in this case.
180          */
181         if (options.actions.head == NULL && pset.notty)
182                 simple_action_list_append(&options.actions, ACT_FILE, NULL);
183
184         /* Bail out if -1 was specified but will be ignored. */
185         if (options.single_txn && options.actions.head == NULL)
186         {
187                 fprintf(stderr, _("%s: -1 can only be used in non-interactive mode\n"), pset.progname);
188                 exit(EXIT_FAILURE);
189         }
190
191         if (!pset.popt.topt.fieldSep.separator &&
192                 !pset.popt.topt.fieldSep.separator_zero)
193         {
194                 pset.popt.topt.fieldSep.separator = pg_strdup(DEFAULT_FIELD_SEP);
195                 pset.popt.topt.fieldSep.separator_zero = false;
196         }
197         if (!pset.popt.topt.recordSep.separator &&
198                 !pset.popt.topt.recordSep.separator_zero)
199         {
200                 pset.popt.topt.recordSep.separator = pg_strdup(DEFAULT_RECORD_SEP);
201                 pset.popt.topt.recordSep.separator_zero = false;
202         }
203
204         if (options.username == NULL)
205                 password_prompt = pg_strdup(_("Password: "));
206         else
207                 password_prompt = psprintf(_("Password for user %s: "),
208                                                                    options.username);
209
210         if (pset.getPassword == TRI_YES)
211         {
212                 simple_prompt(password_prompt, password, sizeof(password), false);
213                 have_password = true;
214         }
215
216         /* loop until we have a password if requested by backend */
217         do
218         {
219 #define PARAMS_ARRAY_SIZE       8
220                 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
221                 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
222
223                 keywords[0] = "host";
224                 values[0] = options.host;
225                 keywords[1] = "port";
226                 values[1] = options.port;
227                 keywords[2] = "user";
228                 values[2] = options.username;
229                 keywords[3] = "password";
230                 values[3] = have_password ? password : NULL;
231                 keywords[4] = "dbname"; /* see do_connect() */
232                 values[4] = (options.list_dbs && options.dbname == NULL) ?
233                         "postgres" : options.dbname;
234                 keywords[5] = "fallback_application_name";
235                 values[5] = pset.progname;
236                 keywords[6] = "client_encoding";
237                 values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
238                 keywords[7] = NULL;
239                 values[7] = NULL;
240
241                 new_pass = false;
242                 pset.db = PQconnectdbParams(keywords, values, true);
243                 free(keywords);
244                 free(values);
245
246                 if (PQstatus(pset.db) == CONNECTION_BAD &&
247                         PQconnectionNeedsPassword(pset.db) &&
248                         !have_password &&
249                         pset.getPassword != TRI_NO)
250                 {
251                         PQfinish(pset.db);
252                         simple_prompt(password_prompt, password, sizeof(password), false);
253                         have_password = true;
254                         new_pass = true;
255                 }
256         } while (new_pass);
257
258         free(password_prompt);
259
260         if (PQstatus(pset.db) == CONNECTION_BAD)
261         {
262                 fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db));
263                 PQfinish(pset.db);
264                 exit(EXIT_BADCONN);
265         }
266
267         setup_cancel_handler();
268
269         PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);
270
271         SyncVariables();
272
273         if (options.list_dbs)
274         {
275                 int                     success;
276
277                 if (!options.no_psqlrc)
278                         process_psqlrc(argv[0]);
279
280                 success = listAllDbs(NULL, false);
281                 PQfinish(pset.db);
282                 exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
283         }
284
285         if (options.logfilename)
286         {
287                 pset.logfile = fopen(options.logfilename, "a");
288                 if (!pset.logfile)
289                 {
290                         fprintf(stderr, _("%s: could not open log file \"%s\": %s\n"),
291                                         pset.progname, options.logfilename, strerror(errno));
292                         exit(EXIT_FAILURE);
293                 }
294         }
295
296         if (!options.no_psqlrc)
297                 process_psqlrc(argv[0]);
298
299         /*
300          * If any actions were given by user, process them in the order in which
301          * they were specified.  Note single_txn is only effective in this mode.
302          */
303         if (options.actions.head != NULL)
304         {
305                 PGresult   *res;
306                 SimpleActionListCell *cell;
307
308                 successResult = EXIT_SUCCESS;   /* silence compiler */
309
310                 if (options.single_txn)
311                 {
312                         if ((res = PSQLexec("BEGIN")) == NULL)
313                         {
314                                 if (pset.on_error_stop)
315                                 {
316                                         successResult = EXIT_USER;
317                                         goto error;
318                                 }
319                         }
320                         else
321                                 PQclear(res);
322                 }
323
324                 for (cell = options.actions.head; cell; cell = cell->next)
325                 {
326                         if (cell->action == ACT_SINGLE_QUERY)
327                         {
328                                 if (pset.echo == PSQL_ECHO_ALL)
329                                         puts(cell->val);
330
331                                 successResult = SendQuery(cell->val)
332                                         ? EXIT_SUCCESS : EXIT_FAILURE;
333                         }
334                         else if (cell->action == ACT_SINGLE_SLASH)
335                         {
336                                 PsqlScanState scan_state;
337                                 ConditionalStack cond_stack;
338
339                                 if (pset.echo == PSQL_ECHO_ALL)
340                                         puts(cell->val);
341
342                                 scan_state = psql_scan_create(&psqlscan_callbacks);
343                                 psql_scan_setup(scan_state,
344                                                                 cell->val, strlen(cell->val),
345                                                                 pset.encoding, standard_strings());
346                                 cond_stack = conditional_stack_create();
347                                 psql_scan_set_passthrough(scan_state, (void *) cond_stack);
348
349                                 successResult = HandleSlashCmds(scan_state,
350                                                                                                 cond_stack,
351                                                                                                 NULL,
352                                                                                                 NULL) != PSQL_CMD_ERROR
353                                         ? EXIT_SUCCESS : EXIT_FAILURE;
354
355                                 psql_scan_destroy(scan_state);
356                                 conditional_stack_destroy(cond_stack);
357                         }
358                         else if (cell->action == ACT_FILE)
359                         {
360                                 successResult = process_file(cell->val, false);
361                         }
362                         else
363                         {
364                                 /* should never come here */
365                                 Assert(false);
366                         }
367
368                         if (successResult != EXIT_SUCCESS && pset.on_error_stop)
369                                 break;
370                 }
371
372                 if (options.single_txn)
373                 {
374                         if ((res = PSQLexec("COMMIT")) == NULL)
375                         {
376                                 if (pset.on_error_stop)
377                                 {
378                                         successResult = EXIT_USER;
379                                         goto error;
380                                 }
381                         }
382                         else
383                                 PQclear(res);
384                 }
385
386 error:
387                 ;
388         }
389
390         /*
391          * or otherwise enter interactive main loop
392          */
393         else
394         {
395                 connection_warnings(true);
396                 if (!pset.quiet)
397                         printf(_("Type \"help\" for help.\n\n"));
398                 initializeInput(options.no_readline ? 0 : 1);
399                 successResult = MainLoop(stdin);
400         }
401
402         /* clean up */
403         if (pset.logfile)
404                 fclose(pset.logfile);
405         PQfinish(pset.db);
406         setQFout(NULL);
407
408         return successResult;
409 }
410
411
412 /*
413  * Parse command line options
414  */
415
416 static void
417 parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
418 {
419         static struct option long_options[] =
420         {
421                 {"echo-all", no_argument, NULL, 'a'},
422                 {"no-align", no_argument, NULL, 'A'},
423                 {"command", required_argument, NULL, 'c'},
424                 {"dbname", required_argument, NULL, 'd'},
425                 {"echo-queries", no_argument, NULL, 'e'},
426                 {"echo-errors", no_argument, NULL, 'b'},
427                 {"echo-hidden", no_argument, NULL, 'E'},
428                 {"file", required_argument, NULL, 'f'},
429                 {"field-separator", required_argument, NULL, 'F'},
430                 {"field-separator-zero", no_argument, NULL, 'z'},
431                 {"host", required_argument, NULL, 'h'},
432                 {"html", no_argument, NULL, 'H'},
433                 {"list", no_argument, NULL, 'l'},
434                 {"log-file", required_argument, NULL, 'L'},
435                 {"no-readline", no_argument, NULL, 'n'},
436                 {"single-transaction", no_argument, NULL, '1'},
437                 {"output", required_argument, NULL, 'o'},
438                 {"port", required_argument, NULL, 'p'},
439                 {"pset", required_argument, NULL, 'P'},
440                 {"quiet", no_argument, NULL, 'q'},
441                 {"record-separator", required_argument, NULL, 'R'},
442                 {"record-separator-zero", no_argument, NULL, '0'},
443                 {"single-step", no_argument, NULL, 's'},
444                 {"single-line", no_argument, NULL, 'S'},
445                 {"tuples-only", no_argument, NULL, 't'},
446                 {"table-attr", required_argument, NULL, 'T'},
447                 {"username", required_argument, NULL, 'U'},
448                 {"set", required_argument, NULL, 'v'},
449                 {"variable", required_argument, NULL, 'v'},
450                 {"version", no_argument, NULL, 'V'},
451                 {"no-password", no_argument, NULL, 'w'},
452                 {"password", no_argument, NULL, 'W'},
453                 {"expanded", no_argument, NULL, 'x'},
454                 {"no-psqlrc", no_argument, NULL, 'X'},
455                 {"help", optional_argument, NULL, 1},
456                 {NULL, 0, NULL, 0}
457         };
458
459         int                     optindex;
460         int                     c;
461
462         memset(options, 0, sizeof *options);
463
464         while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
465                                                         long_options, &optindex)) != -1)
466         {
467                 switch (c)
468                 {
469                         case 'a':
470                                 SetVariable(pset.vars, "ECHO", "all");
471                                 break;
472                         case 'A':
473                                 pset.popt.topt.format = PRINT_UNALIGNED;
474                                 break;
475                         case 'b':
476                                 SetVariable(pset.vars, "ECHO", "errors");
477                                 break;
478                         case 'c':
479                                 if (optarg[0] == '\\')
480                                         simple_action_list_append(&options->actions,
481                                                                                           ACT_SINGLE_SLASH,
482                                                                                           optarg + 1);
483                                 else
484                                         simple_action_list_append(&options->actions,
485                                                                                           ACT_SINGLE_QUERY,
486                                                                                           optarg);
487                                 break;
488                         case 'd':
489                                 options->dbname = pg_strdup(optarg);
490                                 break;
491                         case 'e':
492                                 SetVariable(pset.vars, "ECHO", "queries");
493                                 break;
494                         case 'E':
495                                 SetVariableBool(pset.vars, "ECHO_HIDDEN");
496                                 break;
497                         case 'f':
498                                 simple_action_list_append(&options->actions,
499                                                                                   ACT_FILE,
500                                                                                   optarg);
501                                 break;
502                         case 'F':
503                                 pset.popt.topt.fieldSep.separator = pg_strdup(optarg);
504                                 pset.popt.topt.fieldSep.separator_zero = false;
505                                 break;
506                         case 'h':
507                                 options->host = pg_strdup(optarg);
508                                 break;
509                         case 'H':
510                                 pset.popt.topt.format = PRINT_HTML;
511                                 break;
512                         case 'l':
513                                 options->list_dbs = true;
514                                 break;
515                         case 'L':
516                                 options->logfilename = pg_strdup(optarg);
517                                 break;
518                         case 'n':
519                                 options->no_readline = true;
520                                 break;
521                         case 'o':
522                                 if (!setQFout(optarg))
523                                         exit(EXIT_FAILURE);
524                                 break;
525                         case 'p':
526                                 options->port = pg_strdup(optarg);
527                                 break;
528                         case 'P':
529                                 {
530                                         char       *value;
531                                         char       *equal_loc;
532                                         bool            result;
533
534                                         value = pg_strdup(optarg);
535                                         equal_loc = strchr(value, '=');
536                                         if (!equal_loc)
537                                                 result = do_pset(value, NULL, &pset.popt, true);
538                                         else
539                                         {
540                                                 *equal_loc = '\0';
541                                                 result = do_pset(value, equal_loc + 1, &pset.popt, true);
542                                         }
543
544                                         if (!result)
545                                         {
546                                                 fprintf(stderr, _("%s: could not set printing parameter \"%s\"\n"), pset.progname, value);
547                                                 exit(EXIT_FAILURE);
548                                         }
549
550                                         free(value);
551                                         break;
552                                 }
553                         case 'q':
554                                 SetVariableBool(pset.vars, "QUIET");
555                                 break;
556                         case 'R':
557                                 pset.popt.topt.recordSep.separator = pg_strdup(optarg);
558                                 pset.popt.topt.recordSep.separator_zero = false;
559                                 break;
560                         case 's':
561                                 SetVariableBool(pset.vars, "SINGLESTEP");
562                                 break;
563                         case 'S':
564                                 SetVariableBool(pset.vars, "SINGLELINE");
565                                 break;
566                         case 't':
567                                 pset.popt.topt.tuples_only = true;
568                                 break;
569                         case 'T':
570                                 pset.popt.topt.tableAttr = pg_strdup(optarg);
571                                 break;
572                         case 'U':
573                                 options->username = pg_strdup(optarg);
574                                 break;
575                         case 'v':
576                                 {
577                                         char       *value;
578                                         char       *equal_loc;
579
580                                         value = pg_strdup(optarg);
581                                         equal_loc = strchr(value, '=');
582                                         if (!equal_loc)
583                                         {
584                                                 if (!DeleteVariable(pset.vars, value))
585                                                         exit(EXIT_FAILURE); /* error already printed */
586                                         }
587                                         else
588                                         {
589                                                 *equal_loc = '\0';
590                                                 if (!SetVariable(pset.vars, value, equal_loc + 1))
591                                                         exit(EXIT_FAILURE); /* error already printed */
592                                         }
593
594                                         free(value);
595                                         break;
596                                 }
597                         case 'V':
598                                 showVersion();
599                                 exit(EXIT_SUCCESS);
600                         case 'w':
601                                 pset.getPassword = TRI_NO;
602                                 break;
603                         case 'W':
604                                 pset.getPassword = TRI_YES;
605                                 break;
606                         case 'x':
607                                 pset.popt.topt.expanded = true;
608                                 break;
609                         case 'X':
610                                 options->no_psqlrc = true;
611                                 break;
612                         case 'z':
613                                 pset.popt.topt.fieldSep.separator_zero = true;
614                                 break;
615                         case '0':
616                                 pset.popt.topt.recordSep.separator_zero = true;
617                                 break;
618                         case '1':
619                                 options->single_txn = true;
620                                 break;
621                         case '?':
622                                 /* Actual help option given */
623                                 if (strcmp(argv[optind - 1], "-?") == 0)
624                                 {
625                                         usage(NOPAGER);
626                                         exit(EXIT_SUCCESS);
627                                 }
628                                 /* unknown option reported by getopt */
629                                 else
630                                         goto unknown_option;
631                                 break;
632                         case 1:
633                                 {
634                                         if (!optarg || strcmp(optarg, "options") == 0)
635                                                 usage(NOPAGER);
636                                         else if (optarg && strcmp(optarg, "commands") == 0)
637                                                 slashUsage(NOPAGER);
638                                         else if (optarg && strcmp(optarg, "variables") == 0)
639                                                 helpVariables(NOPAGER);
640                                         else
641                                                 goto unknown_option;
642
643                                         exit(EXIT_SUCCESS);
644                                 }
645                                 break;
646                         default:
647                 unknown_option:
648                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
649                                                 pset.progname);
650                                 exit(EXIT_FAILURE);
651                                 break;
652                 }
653         }
654
655         /*
656          * if we still have arguments, use it as the database name and username
657          */
658         while (argc - optind >= 1)
659         {
660                 if (!options->dbname)
661                         options->dbname = argv[optind];
662                 else if (!options->username)
663                         options->username = argv[optind];
664                 else if (!pset.quiet)
665                         fprintf(stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"),
666                                         pset.progname, argv[optind]);
667
668                 optind++;
669         }
670 }
671
672
673 /*
674  * Append a new item to the end of the SimpleActionList.
675  * Note that "val" is copied if it's not NULL.
676  */
677 static void
678 simple_action_list_append(SimpleActionList *list,
679                                                   enum _actions action, const char *val)
680 {
681         SimpleActionListCell *cell;
682
683         cell = (SimpleActionListCell *) pg_malloc(sizeof(SimpleActionListCell));
684
685         cell->next = NULL;
686         cell->action = action;
687         if (val)
688                 cell->val = pg_strdup(val);
689         else
690                 cell->val = NULL;
691
692         if (list->tail)
693                 list->tail->next = cell;
694         else
695                 list->head = cell;
696         list->tail = cell;
697 }
698
699
700 /*
701  * Load .psqlrc file, if found.
702  */
703 static void
704 process_psqlrc(char *argv0)
705 {
706         char            home[MAXPGPATH];
707         char            rc_file[MAXPGPATH];
708         char            my_exec_path[MAXPGPATH];
709         char            etc_path[MAXPGPATH];
710         char       *envrc = getenv("PSQLRC");
711
712         if (find_my_exec(argv0, my_exec_path) < 0)
713         {
714                 fprintf(stderr, _("%s: could not find own program executable\n"), argv0);
715                 exit(EXIT_FAILURE);
716         }
717
718         get_etc_path(my_exec_path, etc_path);
719
720         snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
721         process_psqlrc_file(rc_file);
722
723         if (envrc != NULL && strlen(envrc) > 0)
724         {
725                 /* might need to free() this */
726                 char       *envrc_alloc = pstrdup(envrc);
727
728                 expand_tilde(&envrc_alloc);
729                 process_psqlrc_file(envrc_alloc);
730         }
731         else if (get_home_path(home))
732         {
733                 snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
734                 process_psqlrc_file(rc_file);
735         }
736 }
737
738
739
740 static void
741 process_psqlrc_file(char *filename)
742 {
743         char       *psqlrc_minor,
744                            *psqlrc_major;
745
746 #if defined(WIN32) && (!defined(__MINGW32__))
747 #define R_OK 4
748 #endif
749
750         psqlrc_minor = psprintf("%s-%s", filename, PG_VERSION);
751         psqlrc_major = psprintf("%s-%s", filename, PG_MAJORVERSION);
752
753         /* check for minor version first, then major, then no version */
754         if (access(psqlrc_minor, R_OK) == 0)
755                 (void) process_file(psqlrc_minor, false);
756         else if (access(psqlrc_major, R_OK) == 0)
757                 (void) process_file(psqlrc_major, false);
758         else if (access(filename, R_OK) == 0)
759                 (void) process_file(filename, false);
760
761         free(psqlrc_minor);
762         free(psqlrc_major);
763 }
764
765
766
767 /* showVersion
768  *
769  * This output format is intended to match GNU standards.
770  */
771 static void
772 showVersion(void)
773 {
774         puts("psql (PostgreSQL) " PG_VERSION);
775 }
776
777
778
779 /*
780  * Substitute hooks and assign hooks for psql variables.
781  *
782  * This isn't an amazingly good place for them, but neither is anywhere else.
783  *
784  * By policy, every special variable that controls any psql behavior should
785  * have one or both hooks, even if they're just no-ops.  This ensures that
786  * the variable will remain present in variables.c's list even when unset,
787  * which ensures that it's known to tab completion.
788  */
789
790 static char *
791 bool_substitute_hook(char *newval)
792 {
793         if (newval == NULL)
794         {
795                 /* "\unset FOO" becomes "\set FOO off" */
796                 newval = pg_strdup("off");
797         }
798         else if (newval[0] == '\0')
799         {
800                 /* "\set FOO" becomes "\set FOO on" */
801                 pg_free(newval);
802                 newval = pg_strdup("on");
803         }
804         return newval;
805 }
806
807 static bool
808 autocommit_hook(const char *newval)
809 {
810         return ParseVariableBool(newval, "AUTOCOMMIT", &pset.autocommit);
811 }
812
813 static bool
814 on_error_stop_hook(const char *newval)
815 {
816         return ParseVariableBool(newval, "ON_ERROR_STOP", &pset.on_error_stop);
817 }
818
819 static bool
820 quiet_hook(const char *newval)
821 {
822         return ParseVariableBool(newval, "QUIET", &pset.quiet);
823 }
824
825 static bool
826 singleline_hook(const char *newval)
827 {
828         return ParseVariableBool(newval, "SINGLELINE", &pset.singleline);
829 }
830
831 static bool
832 singlestep_hook(const char *newval)
833 {
834         return ParseVariableBool(newval, "SINGLESTEP", &pset.singlestep);
835 }
836
837 static char *
838 fetch_count_substitute_hook(char *newval)
839 {
840         if (newval == NULL)
841                 newval = pg_strdup("0");
842         return newval;
843 }
844
845 static bool
846 fetch_count_hook(const char *newval)
847 {
848         return ParseVariableNum(newval, "FETCH_COUNT", &pset.fetch_count);
849 }
850
851 static bool
852 histfile_hook(const char *newval)
853 {
854         /*
855          * Someday we might try to validate the filename, but for now, this is
856          * just a placeholder to ensure HISTFILE is known to tab completion.
857          */
858         return true;
859 }
860
861 static char *
862 histsize_substitute_hook(char *newval)
863 {
864         if (newval == NULL)
865                 newval = pg_strdup("500");
866         return newval;
867 }
868
869 static bool
870 histsize_hook(const char *newval)
871 {
872         return ParseVariableNum(newval, "HISTSIZE", &pset.histsize);
873 }
874
875 static char *
876 ignoreeof_substitute_hook(char *newval)
877 {
878         int                     dummy;
879
880         /*
881          * This tries to mimic the behavior of bash, to wit "If set, the value is
882          * the number of consecutive EOF characters which must be typed as the
883          * first characters on an input line before bash exits.  If the variable
884          * exists but does not have a numeric value, or has no value, the default
885          * value is 10.  If it does not exist, EOF signifies the end of input to
886          * the shell."  Unlike bash, however, we insist on the stored value
887          * actually being a valid integer.
888          */
889         if (newval == NULL)
890                 newval = pg_strdup("0");
891         else if (!ParseVariableNum(newval, NULL, &dummy))
892                 newval = pg_strdup("10");
893         return newval;
894 }
895
896 static bool
897 ignoreeof_hook(const char *newval)
898 {
899         return ParseVariableNum(newval, "IGNOREEOF", &pset.ignoreeof);
900 }
901
902 static char *
903 echo_substitute_hook(char *newval)
904 {
905         if (newval == NULL)
906                 newval = pg_strdup("none");
907         return newval;
908 }
909
910 static bool
911 echo_hook(const char *newval)
912 {
913         Assert(newval != NULL);         /* else substitute hook messed up */
914         if (pg_strcasecmp(newval, "queries") == 0)
915                 pset.echo = PSQL_ECHO_QUERIES;
916         else if (pg_strcasecmp(newval, "errors") == 0)
917                 pset.echo = PSQL_ECHO_ERRORS;
918         else if (pg_strcasecmp(newval, "all") == 0)
919                 pset.echo = PSQL_ECHO_ALL;
920         else if (pg_strcasecmp(newval, "none") == 0)
921                 pset.echo = PSQL_ECHO_NONE;
922         else
923         {
924                 PsqlVarEnumError("ECHO", newval, "none, errors, queries, all");
925                 return false;
926         }
927         return true;
928 }
929
930 static bool
931 echo_hidden_hook(const char *newval)
932 {
933         Assert(newval != NULL);         /* else substitute hook messed up */
934         if (pg_strcasecmp(newval, "noexec") == 0)
935                 pset.echo_hidden = PSQL_ECHO_HIDDEN_NOEXEC;
936         else
937         {
938                 bool            on_off;
939
940                 if (ParseVariableBool(newval, NULL, &on_off))
941                         pset.echo_hidden = on_off ? PSQL_ECHO_HIDDEN_ON : PSQL_ECHO_HIDDEN_OFF;
942                 else
943                 {
944                         PsqlVarEnumError("ECHO_HIDDEN", newval, "on, off, noexec");
945                         return false;
946                 }
947         }
948         return true;
949 }
950
951 static bool
952 on_error_rollback_hook(const char *newval)
953 {
954         Assert(newval != NULL);         /* else substitute hook messed up */
955         if (pg_strcasecmp(newval, "interactive") == 0)
956                 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_INTERACTIVE;
957         else
958         {
959                 bool            on_off;
960
961                 if (ParseVariableBool(newval, NULL, &on_off))
962                         pset.on_error_rollback = on_off ? PSQL_ERROR_ROLLBACK_ON : PSQL_ERROR_ROLLBACK_OFF;
963                 else
964                 {
965                         PsqlVarEnumError("ON_ERROR_ROLLBACK", newval, "on, off, interactive");
966                         return false;
967                 }
968         }
969         return true;
970 }
971
972 static char *
973 comp_keyword_case_substitute_hook(char *newval)
974 {
975         if (newval == NULL)
976                 newval = pg_strdup("preserve-upper");
977         return newval;
978 }
979
980 static bool
981 comp_keyword_case_hook(const char *newval)
982 {
983         Assert(newval != NULL);         /* else substitute hook messed up */
984         if (pg_strcasecmp(newval, "preserve-upper") == 0)
985                 pset.comp_case = PSQL_COMP_CASE_PRESERVE_UPPER;
986         else if (pg_strcasecmp(newval, "preserve-lower") == 0)
987                 pset.comp_case = PSQL_COMP_CASE_PRESERVE_LOWER;
988         else if (pg_strcasecmp(newval, "upper") == 0)
989                 pset.comp_case = PSQL_COMP_CASE_UPPER;
990         else if (pg_strcasecmp(newval, "lower") == 0)
991                 pset.comp_case = PSQL_COMP_CASE_LOWER;
992         else
993         {
994                 PsqlVarEnumError("COMP_KEYWORD_CASE", newval,
995                                                  "lower, upper, preserve-lower, preserve-upper");
996                 return false;
997         }
998         return true;
999 }
1000
1001 static char *
1002 histcontrol_substitute_hook(char *newval)
1003 {
1004         if (newval == NULL)
1005                 newval = pg_strdup("none");
1006         return newval;
1007 }
1008
1009 static bool
1010 histcontrol_hook(const char *newval)
1011 {
1012         Assert(newval != NULL);         /* else substitute hook messed up */
1013         if (pg_strcasecmp(newval, "ignorespace") == 0)
1014                 pset.histcontrol = hctl_ignorespace;
1015         else if (pg_strcasecmp(newval, "ignoredups") == 0)
1016                 pset.histcontrol = hctl_ignoredups;
1017         else if (pg_strcasecmp(newval, "ignoreboth") == 0)
1018                 pset.histcontrol = hctl_ignoreboth;
1019         else if (pg_strcasecmp(newval, "none") == 0)
1020                 pset.histcontrol = hctl_none;
1021         else
1022         {
1023                 PsqlVarEnumError("HISTCONTROL", newval,
1024                                                  "none, ignorespace, ignoredups, ignoreboth");
1025                 return false;
1026         }
1027         return true;
1028 }
1029
1030 static bool
1031 prompt1_hook(const char *newval)
1032 {
1033         pset.prompt1 = newval ? newval : "";
1034         return true;
1035 }
1036
1037 static bool
1038 prompt2_hook(const char *newval)
1039 {
1040         pset.prompt2 = newval ? newval : "";
1041         return true;
1042 }
1043
1044 static bool
1045 prompt3_hook(const char *newval)
1046 {
1047         pset.prompt3 = newval ? newval : "";
1048         return true;
1049 }
1050
1051 static char *
1052 verbosity_substitute_hook(char *newval)
1053 {
1054         if (newval == NULL)
1055                 newval = pg_strdup("default");
1056         return newval;
1057 }
1058
1059 static bool
1060 verbosity_hook(const char *newval)
1061 {
1062         Assert(newval != NULL);         /* else substitute hook messed up */
1063         if (pg_strcasecmp(newval, "default") == 0)
1064                 pset.verbosity = PQERRORS_DEFAULT;
1065         else if (pg_strcasecmp(newval, "terse") == 0)
1066                 pset.verbosity = PQERRORS_TERSE;
1067         else if (pg_strcasecmp(newval, "verbose") == 0)
1068                 pset.verbosity = PQERRORS_VERBOSE;
1069         else
1070         {
1071                 PsqlVarEnumError("VERBOSITY", newval, "default, terse, verbose");
1072                 return false;
1073         }
1074
1075         if (pset.db)
1076                 PQsetErrorVerbosity(pset.db, pset.verbosity);
1077         return true;
1078 }
1079
1080 static char *
1081 show_context_substitute_hook(char *newval)
1082 {
1083         if (newval == NULL)
1084                 newval = pg_strdup("errors");
1085         return newval;
1086 }
1087
1088 static bool
1089 show_context_hook(const char *newval)
1090 {
1091         Assert(newval != NULL);         /* else substitute hook messed up */
1092         if (pg_strcasecmp(newval, "never") == 0)
1093                 pset.show_context = PQSHOW_CONTEXT_NEVER;
1094         else if (pg_strcasecmp(newval, "errors") == 0)
1095                 pset.show_context = PQSHOW_CONTEXT_ERRORS;
1096         else if (pg_strcasecmp(newval, "always") == 0)
1097                 pset.show_context = PQSHOW_CONTEXT_ALWAYS;
1098         else
1099         {
1100                 PsqlVarEnumError("SHOW_CONTEXT", newval, "never, errors, always");
1101                 return false;
1102         }
1103
1104         if (pset.db)
1105                 PQsetErrorContextVisibility(pset.db, pset.show_context);
1106         return true;
1107 }
1108
1109
1110 static void
1111 EstablishVariableSpace(void)
1112 {
1113         pset.vars = CreateVariableSpace();
1114
1115         SetVariableHooks(pset.vars, "AUTOCOMMIT",
1116                                          bool_substitute_hook,
1117                                          autocommit_hook);
1118         SetVariableHooks(pset.vars, "ON_ERROR_STOP",
1119                                          bool_substitute_hook,
1120                                          on_error_stop_hook);
1121         SetVariableHooks(pset.vars, "QUIET",
1122                                          bool_substitute_hook,
1123                                          quiet_hook);
1124         SetVariableHooks(pset.vars, "SINGLELINE",
1125                                          bool_substitute_hook,
1126                                          singleline_hook);
1127         SetVariableHooks(pset.vars, "SINGLESTEP",
1128                                          bool_substitute_hook,
1129                                          singlestep_hook);
1130         SetVariableHooks(pset.vars, "FETCH_COUNT",
1131                                          fetch_count_substitute_hook,
1132                                          fetch_count_hook);
1133         SetVariableHooks(pset.vars, "HISTFILE",
1134                                          NULL,
1135                                          histfile_hook);
1136         SetVariableHooks(pset.vars, "HISTSIZE",
1137                                          histsize_substitute_hook,
1138                                          histsize_hook);
1139         SetVariableHooks(pset.vars, "IGNOREEOF",
1140                                          ignoreeof_substitute_hook,
1141                                          ignoreeof_hook);
1142         SetVariableHooks(pset.vars, "ECHO",
1143                                          echo_substitute_hook,
1144                                          echo_hook);
1145         SetVariableHooks(pset.vars, "ECHO_HIDDEN",
1146                                          bool_substitute_hook,
1147                                          echo_hidden_hook);
1148         SetVariableHooks(pset.vars, "ON_ERROR_ROLLBACK",
1149                                          bool_substitute_hook,
1150                                          on_error_rollback_hook);
1151         SetVariableHooks(pset.vars, "COMP_KEYWORD_CASE",
1152                                          comp_keyword_case_substitute_hook,
1153                                          comp_keyword_case_hook);
1154         SetVariableHooks(pset.vars, "HISTCONTROL",
1155                                          histcontrol_substitute_hook,
1156                                          histcontrol_hook);
1157         SetVariableHooks(pset.vars, "PROMPT1",
1158                                          NULL,
1159                                          prompt1_hook);
1160         SetVariableHooks(pset.vars, "PROMPT2",
1161                                          NULL,
1162                                          prompt2_hook);
1163         SetVariableHooks(pset.vars, "PROMPT3",
1164                                          NULL,
1165                                          prompt3_hook);
1166         SetVariableHooks(pset.vars, "VERBOSITY",
1167                                          verbosity_substitute_hook,
1168                                          verbosity_hook);
1169         SetVariableHooks(pset.vars, "SHOW_CONTEXT",
1170                                          show_context_substitute_hook,
1171                                          show_context_hook);
1172 }