PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/bin/psql/startup.c

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