PageRenderTime 34ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/bin/psql/command.c

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