2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2012, PostgreSQL Global Development Group
6 * src/bin/psql/command.c
8 #include "postgres_fe.h"
11 #ifdef __BORLANDC__ /* needed for BCC */
20 #include <sys/types.h> /* for umask() */
21 #include <sys/stat.h> /* for stat() */
22 #include <fcntl.h> /* open() flags */
23 #include <unistd.h> /* for geteuid(), getpid(), stat() */
29 #include <sys/types.h> /* for umask() */
30 #include <sys/stat.h> /* for stat() */
33 #include <openssl/ssl.h>
36 #include "portability/instr_time.h"
39 #include "pqexpbuffer.h"
40 #include "dumputils.h"
47 #include "large_obj.h"
52 #include "variables.h"
55 /* functions for use in this file */
56 static backslashResult exec_command(const char *cmd,
57 PsqlScanState scan_state,
58 PQExpBuffer query_buf);
59 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
60 int lineno, bool *edited);
61 static bool do_connect(char *dbname, char *user, char *host, char *port);
62 static bool do_shell(const char *command);
63 static bool lookup_function_oid(PGconn *conn, const char *desc, Oid *foid);
64 static bool get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf);
65 static int strip_lineno_from_funcdesc(char *func);
66 static void minimal_error_message(PGresult *res);
68 static void printSSLInfo(void);
71 static void checkWin32Codepage(void);
79 * Handles all the different commands that start with '\'.
80 * Ordinarily called by MainLoop().
82 * scan_state is a lexer working state that is set to continue scanning
83 * just after the '\'. The lexer is advanced past the command and all
84 * arguments on return.
86 * 'query_buf' contains the query-so-far, which may be modified by
87 * execution of the backslash command (for example, \r clears it).
88 * query_buf can be NULL if there is no query so far.
90 * Returns a status code indicating what action is desired, see command.h.
95 HandleSlashCmds(PsqlScanState scan_state,
96 PQExpBuffer query_buf)
98 backslashResult status = PSQL_CMD_SKIP_LINE;
102 psql_assert(scan_state);
104 /* Parse off the command name */
105 cmd = psql_scan_slash_command(scan_state);
107 /* And try to execute it */
108 status = exec_command(cmd, scan_state, query_buf);
110 if (status == PSQL_CMD_UNKNOWN)
112 if (pset.cur_cmd_interactive)
113 fprintf(stderr, _("Invalid command \\%s. Try \\? for help.\n"), cmd);
115 psql_error("invalid command \\%s\n", cmd);
116 status = PSQL_CMD_ERROR;
119 if (status != PSQL_CMD_ERROR)
121 /* eat any remaining arguments after a valid command */
122 /* note we suppress evaluation of backticks here */
123 while ((arg = psql_scan_slash_option(scan_state,
124 OT_NO_EVAL, NULL, false)))
126 psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
132 /* silently throw away rest of line after an erroneous command */
133 while ((arg = psql_scan_slash_option(scan_state,
134 OT_WHOLE_LINE, NULL, false)))
138 /* if there is a trailing \\, swallow it */
139 psql_scan_slash_command_end(scan_state);
143 /* some commands write to queryFout, so make sure output is sent */
144 fflush(pset.queryFout);
150 * Read and interpret an argument to the \connect slash command.
153 read_connect_arg(PsqlScanState scan_state)
159 * Ideally we should treat the arguments as SQL identifiers. But for
160 * backwards compatibility with 7.2 and older pg_dump files, we have to
161 * take unquoted arguments verbatim (don't downcase them). For now,
162 * double-quoted arguments may be stripped of double quotes (as if SQL
163 * identifiers). By 7.4 or so, pg_dump files can be expected to
164 * double-quote all mixed-case \connect arguments, and then we can get rid
167 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
175 if (*result == '\0' || strcmp(result, "-") == 0)
183 * Subroutine to actually try to execute a backslash command.
185 static backslashResult
186 exec_command(const char *cmd,
187 PsqlScanState scan_state,
188 PQExpBuffer query_buf)
190 bool success = true; /* indicate here if the command ran ok or
192 backslashResult status = PSQL_CMD_SKIP_LINE;
195 * \a -- toggle field alignment This makes little sense but we keep it
198 if (strcmp(cmd, "a") == 0)
200 if (pset.popt.topt.format != PRINT_ALIGNED)
201 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
203 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
206 /* \C -- override table title (formerly change HTML caption) */
207 else if (strcmp(cmd, "C") == 0)
209 char *opt = psql_scan_slash_option(scan_state,
210 OT_NORMAL, NULL, true);
212 success = do_pset("title", opt, &pset.popt, pset.quiet);
217 * \c or \connect -- connect to database using the specified parameters.
219 * \c dbname user host port
221 * If any of these parameters are omitted or specified as '-', the current
222 * value of the parameter will be used instead. If the parameter has no
223 * current value, the default value for that parameter will be used. Some
226 * \c - - hst Connect to current database on current port of host
227 * "hst" as current user. \c - usr - prt Connect to current database on
228 * "prt" port of current host as user "usr". \c dbs Connect to
229 * "dbs" database on current port of current host as current user.
231 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
238 opt1 = read_connect_arg(scan_state);
239 opt2 = read_connect_arg(scan_state);
240 opt3 = read_connect_arg(scan_state);
241 opt4 = read_connect_arg(scan_state);
243 success = do_connect(opt1, opt2, opt3, opt4);
252 else if (strcmp(cmd, "cd") == 0)
254 char *opt = psql_scan_slash_option(scan_state,
255 OT_NORMAL, NULL, true);
265 pw = getpwuid(geteuid());
268 psql_error("could not get home directory: %s\n", strerror(errno));
275 * On Windows, 'cd' without arguments prints the current
276 * directory, so if someone wants to code this here instead...
282 if (chdir(dir) == -1)
284 psql_error("\\%s: could not change directory to \"%s\": %s\n",
285 cmd, dir, strerror(errno));
291 pset.dirname = pg_strdup(dir);
292 canonicalize_path(pset.dirname);
298 /* \conninfo -- display information about the current connection */
299 else if (strcmp(cmd, "conninfo") == 0)
301 char *db = PQdb(pset.db);
302 char *host = PQhost(pset.db);
305 printf(_("You are currently not connected to a database.\n"));
309 host = DEFAULT_PGSOCKET_DIR;
310 /* If the host is an absolute path, the connection is via socket */
311 if (is_absolute_path(host))
312 printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
313 db, PQuser(pset.db), host, PQport(pset.db));
315 printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
316 db, PQuser(pset.db), host, PQport(pset.db));
321 else if (pg_strcasecmp(cmd, "copy") == 0)
323 char *opt = psql_scan_slash_option(scan_state,
324 OT_WHOLE_LINE, NULL, false);
326 success = do_copy(opt);
331 else if (strcmp(cmd, "copyright") == 0)
335 else if (cmd[0] == 'd')
341 /* We don't do SQLID reduction on the pattern yet */
342 pattern = psql_scan_slash_option(scan_state,
343 OT_NORMAL, NULL, true);
345 show_verbose = strchr(cmd, '+') ? true : false;
346 show_system = strchr(cmd, 'S') ? true : false;
354 success = describeTableDetails(pattern, show_verbose, show_system);
356 /* standard listing of interesting things */
357 success = listTables("tvsE", NULL, show_verbose, show_system);
360 success = describeAggregates(pattern, show_verbose, show_system);
363 success = describeTablespaces(pattern, show_verbose);
366 success = listConversions(pattern, show_verbose, show_system);
369 success = listCasts(pattern, show_verbose);
372 if (strncmp(cmd, "ddp", 3) == 0)
373 success = listDefaultACLs(pattern);
375 success = objectDescription(pattern, show_system);
378 success = listDomains(pattern, show_verbose, show_system);
380 case 'f': /* function subsystem */
390 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
393 status = PSQL_CMD_UNKNOWN;
398 /* no longer distinct from \du */
399 success = describeRoles(pattern, show_verbose);
402 success = do_lo_list();
405 success = listLanguages(pattern, show_verbose, show_system);
408 success = listSchemas(pattern, show_verbose, show_system);
411 success = describeOperators(pattern, show_system);
414 success = listCollations(pattern, show_verbose, show_system);
417 success = permissionsList(pattern);
420 success = describeTypes(pattern, show_verbose, show_system);
427 success = listTables(&cmd[1], pattern, show_verbose, show_system);
430 if (cmd[2] == 'd' && cmd[3] == 's')
432 char *pattern2 = NULL;
435 pattern2 = psql_scan_slash_option(scan_state,
436 OT_NORMAL, NULL, true);
437 success = listDbRoleSettings(pattern, pattern2);
440 success = PSQL_CMD_UNKNOWN;
443 success = describeRoles(pattern, show_verbose);
445 case 'F': /* text search subsystem */
450 success = listTSConfigs(pattern, show_verbose);
453 success = listTSParsers(pattern, show_verbose);
456 success = listTSDictionaries(pattern, show_verbose);
459 success = listTSTemplates(pattern, show_verbose);
462 status = PSQL_CMD_UNKNOWN;
466 case 'e': /* SQL/MED subsystem */
470 success = listForeignServers(pattern, show_verbose);
473 success = listUserMappings(pattern, show_verbose);
476 success = listForeignDataWrappers(pattern, show_verbose);
479 success = listForeignTables(pattern, show_verbose);
482 status = PSQL_CMD_UNKNOWN;
486 case 'x': /* Extensions */
488 success = listExtensionContents(pattern);
490 success = listExtensions(pattern);
493 status = PSQL_CMD_UNKNOWN;
502 * \e or \edit -- edit the current query buffer, or edit a file and make
503 * it the query buffer
505 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
509 psql_error("no query buffer\n");
510 status = PSQL_CMD_ERROR;
518 fname = psql_scan_slash_option(scan_state,
519 OT_NORMAL, NULL, true);
522 /* try to get separate lineno arg */
523 ln = psql_scan_slash_option(scan_state,
524 OT_NORMAL, NULL, true);
527 /* only one arg; maybe it is lineno not fname */
529 strspn(fname, "0123456789") == strlen(fname))
531 /* all digits, so assume it is lineno */
542 psql_error("invalid line number: %s\n", ln);
543 status = PSQL_CMD_ERROR;
546 if (status != PSQL_CMD_ERROR)
548 expand_tilde(&fname);
550 canonicalize_path(fname);
551 if (do_edit(fname, query_buf, lineno, NULL))
552 status = PSQL_CMD_NEWEDIT;
554 status = PSQL_CMD_ERROR;
564 * \ef -- edit the named function, or present a blank CREATE FUNCTION
565 * template if no argument is given
567 else if (strcmp(cmd, "ef") == 0)
571 if (pset.sversion < 80400)
573 psql_error("The server (version %d.%d) does not support editing function source.\n",
574 pset.sversion / 10000, (pset.sversion / 100) % 100);
575 status = PSQL_CMD_ERROR;
579 psql_error("no query buffer\n");
580 status = PSQL_CMD_ERROR;
585 Oid foid = InvalidOid;
587 func = psql_scan_slash_option(scan_state,
588 OT_WHOLE_LINE, NULL, true);
589 lineno = strip_lineno_from_funcdesc(func);
592 /* error already reported */
593 status = PSQL_CMD_ERROR;
597 /* set up an empty command to fill in */
598 printfPQExpBuffer(query_buf,
599 "CREATE FUNCTION ( )\n"
602 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
606 else if (!lookup_function_oid(pset.db, func, &foid))
608 /* error already reported */
609 status = PSQL_CMD_ERROR;
611 else if (!get_create_function_cmd(pset.db, foid, query_buf))
613 /* error already reported */
614 status = PSQL_CMD_ERROR;
619 * lineno "1" should correspond to the first line of the
620 * function body. We expect that pg_get_functiondef() will
621 * emit that on a line beginning with "AS ", and that there
622 * can be no such line before the real start of the function
623 * body. Increment lineno by the number of lines before that
624 * line, so that it becomes relative to the first line of the
625 * function definition.
627 const char *lines = query_buf->data;
629 while (*lines != '\0')
631 if (strncmp(lines, "AS ", 3) == 0)
634 /* find start of next line */
635 lines = strchr(lines, '\n');
646 if (status != PSQL_CMD_ERROR)
650 if (!do_edit(NULL, query_buf, lineno, &edited))
651 status = PSQL_CMD_ERROR;
653 puts(_("No changes"));
655 status = PSQL_CMD_NEWEDIT;
659 /* \echo and \qecho */
660 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
664 bool no_newline = false;
668 if (strcmp(cmd, "qecho") == 0)
669 fout = pset.queryFout;
673 while ((value = psql_scan_slash_option(scan_state,
674 OT_NORMAL, "ed, false)))
676 if (!quoted && strcmp(value, "-n") == 0)
692 /* \encoding -- set/show client side encoding */
693 else if (strcmp(cmd, "encoding") == 0)
695 char *encoding = psql_scan_slash_option(scan_state,
696 OT_NORMAL, NULL, false);
701 puts(pg_encoding_to_char(pset.encoding));
706 if (PQsetClientEncoding(pset.db, encoding) == -1)
707 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
710 /* save encoding info into psql internal data */
711 pset.encoding = PQclientEncoding(pset.db);
712 pset.popt.topt.encoding = pset.encoding;
713 SetVariable(pset.vars, "ENCODING",
714 pg_encoding_to_char(pset.encoding));
720 /* \f -- change field separator */
721 else if (strcmp(cmd, "f") == 0)
723 char *fname = psql_scan_slash_option(scan_state,
724 OT_NORMAL, NULL, false);
726 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
730 /* \g means send query */
731 else if (strcmp(cmd, "g") == 0)
733 char *fname = psql_scan_slash_option(scan_state,
734 OT_FILEPIPE, NULL, false);
740 expand_tilde(&fname);
741 pset.gfname = pg_strdup(fname);
744 status = PSQL_CMD_SEND;
748 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
750 char *opt = psql_scan_slash_option(scan_state,
751 OT_WHOLE_LINE, NULL, false);
754 /* strip any trailing spaces and semicolons */
759 (isspace((unsigned char) opt[len - 1])
760 || opt[len - 1] == ';'))
764 helpSQL(opt, pset.popt.topt.pager);
769 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
771 if (pset.popt.topt.format != PRINT_HTML)
772 success = do_pset("format", "html", &pset.popt, pset.quiet);
774 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
778 /* \i and \ir include files */
779 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0
780 || strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
782 char *fname = psql_scan_slash_option(scan_state,
783 OT_NORMAL, NULL, true);
787 psql_error("\\%s: missing required argument\n", cmd);
792 bool include_relative;
794 include_relative = (strcmp(cmd, "ir") == 0
795 || strcmp(cmd, "include_relative") == 0);
796 expand_tilde(&fname);
797 success = (process_file(fname, false, include_relative) == EXIT_SUCCESS);
802 /* \l is list databases */
803 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
804 success = listAllDbs(false);
805 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
806 success = listAllDbs(true);
809 * large object things
811 else if (strncmp(cmd, "lo_", 3) == 0)
816 opt1 = psql_scan_slash_option(scan_state,
817 OT_NORMAL, NULL, true);
818 opt2 = psql_scan_slash_option(scan_state,
819 OT_NORMAL, NULL, true);
821 if (strcmp(cmd + 3, "export") == 0)
825 psql_error("\\%s: missing required argument\n", cmd);
831 success = do_lo_export(opt1, opt2);
835 else if (strcmp(cmd + 3, "import") == 0)
839 psql_error("\\%s: missing required argument\n", cmd);
845 success = do_lo_import(opt1, opt2);
849 else if (strcmp(cmd + 3, "list") == 0)
850 success = do_lo_list();
852 else if (strcmp(cmd + 3, "unlink") == 0)
856 psql_error("\\%s: missing required argument\n", cmd);
860 success = do_lo_unlink(opt1);
864 status = PSQL_CMD_UNKNOWN;
871 /* \o -- set query output */
872 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
874 char *fname = psql_scan_slash_option(scan_state,
875 OT_FILEPIPE, NULL, true);
877 expand_tilde(&fname);
878 success = setQFout(fname);
882 /* \p prints the current query buffer */
883 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
885 if (query_buf && query_buf->len > 0)
886 puts(query_buf->data);
887 else if (!pset.quiet)
888 puts(_("Query buffer is empty."));
892 /* \password -- set user password */
893 else if (strcmp(cmd, "password") == 0)
898 pw1 = simple_prompt("Enter new password: ", 100, false);
899 pw2 = simple_prompt("Enter it again: ", 100, false);
901 if (strcmp(pw1, pw2) != 0)
903 fprintf(stderr, _("Passwords didn't match.\n"));
908 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
910 char *encrypted_password;
915 user = PQuser(pset.db);
917 encrypted_password = PQencryptPassword(pw1, user);
919 if (!encrypted_password)
921 fprintf(stderr, _("Password encryption failed.\n"));
929 initPQExpBuffer(&buf);
930 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
932 appendStringLiteralConn(&buf, encrypted_password, pset.db);
933 res = PSQLexec(buf.data, false);
934 termPQExpBuffer(&buf);
939 PQfreemem(encrypted_password);
950 /* \prompt -- prompt and set variable */
951 else if (strcmp(cmd, "prompt") == 0)
958 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
959 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
963 psql_error("\\%s: missing required argument\n", cmd);
979 result = simple_prompt(prompt_text, 4096, true);
984 fputs(prompt_text, stdout);
987 result = gets_fromFile(stdin);
990 if (!SetVariable(pset.vars, opt, result))
992 psql_error("\\%s: error while setting variable\n", cmd);
1003 /* \pset -- set printing parameters */
1004 else if (strcmp(cmd, "pset") == 0)
1006 char *opt0 = psql_scan_slash_option(scan_state,
1007 OT_NORMAL, NULL, false);
1008 char *opt1 = psql_scan_slash_option(scan_state,
1009 OT_NORMAL, NULL, false);
1013 psql_error("\\%s: missing required argument\n", cmd);
1017 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1024 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1025 status = PSQL_CMD_TERMINATE;
1027 /* reset(clear) the buffer */
1028 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1030 resetPQExpBuffer(query_buf);
1031 psql_scan_reset(scan_state);
1033 puts(_("Query buffer reset (cleared)."));
1036 /* \s save history in a file or show it on the screen */
1037 else if (strcmp(cmd, "s") == 0)
1039 char *fname = psql_scan_slash_option(scan_state,
1040 OT_NORMAL, NULL, true);
1042 expand_tilde(&fname);
1043 /* This scrolls off the screen when using /dev/tty */
1044 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
1045 if (success && !pset.quiet && fname)
1046 printf(gettext("Wrote history to file \"%s/%s\".\n"),
1047 pset.dirname ? pset.dirname : ".", fname);
1053 /* \set -- generalized set variable/option command */
1054 else if (strcmp(cmd, "set") == 0)
1056 char *opt0 = psql_scan_slash_option(scan_state,
1057 OT_NORMAL, NULL, false);
1061 /* list all variables */
1062 PrintVariables(pset.vars);
1068 * Set variable to the concatenation of the arguments.
1073 opt = psql_scan_slash_option(scan_state,
1074 OT_NORMAL, NULL, false);
1075 newval = pg_strdup(opt ? opt : "");
1078 while ((opt = psql_scan_slash_option(scan_state,
1079 OT_NORMAL, NULL, false)))
1081 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
1084 psql_error("out of memory\n");
1087 strcat(newval, opt);
1091 if (!SetVariable(pset.vars, opt0, newval))
1093 psql_error("\\%s: error while setting variable\n", cmd);
1102 /* \setenv -- set environment command */
1103 else if (strcmp(cmd, "setenv") == 0)
1105 char *envvar = psql_scan_slash_option(scan_state,
1106 OT_NORMAL, NULL, false);
1107 char *envval = psql_scan_slash_option(scan_state,
1108 OT_NORMAL, NULL, false);
1112 psql_error("\\%s: missing required argument\n", cmd);
1115 else if (strchr(envvar,'=') != NULL)
1117 psql_error("\\%s: environment variable name must not contain '='\n",
1123 /* No argument - unset the environment variable */
1129 /* Set variable to the value of the next argument */
1130 int len = strlen(envvar) + strlen(envval) + 1;
1131 char *newval = pg_malloc(len + 1);
1133 snprintf(newval, len+1, "%s=%s", envvar, envval);
1137 * Do not free newval here, it will screw up the environment
1138 * if you do. See putenv man page for details. That means we
1139 * leak a bit of memory here, but not enough to worry about.
1146 /* \sf -- show a function's source code */
1147 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1149 bool show_linenumbers = (strcmp(cmd, "sf+") == 0);
1150 PQExpBuffer func_buf;
1152 Oid foid = InvalidOid;
1154 func_buf = createPQExpBuffer();
1155 func = psql_scan_slash_option(scan_state,
1156 OT_WHOLE_LINE, NULL, true);
1157 if (pset.sversion < 80400)
1159 psql_error("The server (version %d.%d) does not support showing function source.\n",
1160 pset.sversion / 10000, (pset.sversion / 100) % 100);
1161 status = PSQL_CMD_ERROR;
1165 psql_error("function name is required\n");
1166 status = PSQL_CMD_ERROR;
1168 else if (!lookup_function_oid(pset.db, func, &foid))
1170 /* error already reported */
1171 status = PSQL_CMD_ERROR;
1173 else if (!get_create_function_cmd(pset.db, foid, func_buf))
1175 /* error already reported */
1176 status = PSQL_CMD_ERROR;
1183 /* Select output stream: stdout, pager, or file */
1184 if (pset.queryFout == stdout)
1186 /* count lines in function to see if pager is needed */
1188 const char *lines = func_buf->data;
1190 while (*lines != '\0')
1193 /* find start of next line */
1194 lines = strchr(lines, '\n');
1200 output = PageOutput(lineno, pset.popt.topt.pager);
1205 /* use previously set output file, without pager */
1206 output = pset.queryFout;
1210 if (show_linenumbers)
1212 bool in_header = true;
1214 char *lines = func_buf->data;
1217 * lineno "1" should correspond to the first line of the
1218 * function body. We expect that pg_get_functiondef() will
1219 * emit that on a line beginning with "AS ", and that there
1220 * can be no such line before the real start of the function
1223 * Note that this loop scribbles on func_buf.
1225 while (*lines != '\0')
1229 if (in_header && strncmp(lines, "AS ", 3) == 0)
1231 /* increment lineno only for body's lines */
1235 /* find and mark end of current line */
1236 eol = strchr(lines, '\n');
1240 /* show current line as appropriate */
1242 fprintf(output, " %s\n", lines);
1244 fprintf(output, "%-7d %s\n", lineno, lines);
1246 /* advance to next line, if any */
1254 /* just send the function definition to output */
1255 fputs(func_buf->data, output);
1264 destroyPQExpBuffer(func_buf);
1267 /* \t -- turn off headers and row count */
1268 else if (strcmp(cmd, "t") == 0)
1270 char *opt = psql_scan_slash_option(scan_state,
1271 OT_NORMAL, NULL, true);
1273 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1277 /* \T -- define html <table ...> attributes */
1278 else if (strcmp(cmd, "T") == 0)
1280 char *value = psql_scan_slash_option(scan_state,
1281 OT_NORMAL, NULL, false);
1283 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1287 /* \timing -- toggle timing of queries */
1288 else if (strcmp(cmd, "timing") == 0)
1290 char *opt = psql_scan_slash_option(scan_state,
1291 OT_NORMAL, NULL, false);
1294 pset.timing = ParseVariableBool(opt);
1296 pset.timing = !pset.timing;
1300 puts(_("Timing is on."));
1302 puts(_("Timing is off."));
1308 else if (strcmp(cmd, "unset") == 0)
1310 char *opt = psql_scan_slash_option(scan_state,
1311 OT_NORMAL, NULL, false);
1315 psql_error("\\%s: missing required argument\n", cmd);
1318 else if (!SetVariable(pset.vars, opt, NULL))
1320 psql_error("\\%s: error while setting variable\n", cmd);
1326 /* \w -- write query buffer to file */
1327 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1330 bool is_pipe = false;
1335 psql_error("no query buffer\n");
1336 status = PSQL_CMD_ERROR;
1340 fname = psql_scan_slash_option(scan_state,
1341 OT_FILEPIPE, NULL, true);
1342 expand_tilde(&fname);
1346 psql_error("\\%s: missing required argument\n", cmd);
1351 if (fname[0] == '|')
1354 fd = popen(&fname[1], "w");
1358 canonicalize_path(fname);
1359 fd = fopen(fname, "w");
1363 psql_error("%s: %s\n", fname, strerror(errno));
1373 if (query_buf && query_buf->len > 0)
1374 fprintf(fd, "%s\n", query_buf->data);
1377 result = pclose(fd);
1379 result = fclose(fd);
1383 psql_error("%s: %s\n", fname, strerror(errno));
1391 /* \x -- set or toggle expanded table representation */
1392 else if (strcmp(cmd, "x") == 0)
1394 char *opt = psql_scan_slash_option(scan_state,
1395 OT_NORMAL, NULL, true);
1397 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1401 /* \z -- list table rights (equivalent to \dp) */
1402 else if (strcmp(cmd, "z") == 0)
1404 char *pattern = psql_scan_slash_option(scan_state,
1405 OT_NORMAL, NULL, true);
1407 success = permissionsList(pattern);
1412 /* \! -- shell escape */
1413 else if (strcmp(cmd, "!") == 0)
1415 char *opt = psql_scan_slash_option(scan_state,
1416 OT_WHOLE_LINE, NULL, false);
1418 success = do_shell(opt);
1422 /* \? -- slash command help */
1423 else if (strcmp(cmd, "?") == 0)
1424 slashUsage(pset.popt.topt.pager);
1429 * These commands don't do anything. I just use them to test the parser.
1431 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1436 while ((value = psql_scan_slash_option(scan_state,
1437 OT_NORMAL, NULL, true)))
1439 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1446 status = PSQL_CMD_UNKNOWN;
1449 status = PSQL_CMD_ERROR;
1455 * Ask the user for a password; 'username' is the username the
1456 * password is for, if one has been explicitly specified. Returns a
1460 prompt_for_password(const char *username)
1464 if (username == NULL)
1465 result = simple_prompt("Password: ", 100, false);
1470 prompt_text = malloc(strlen(username) + 100);
1471 snprintf(prompt_text, strlen(username) + 100,
1472 _("Password for user %s: "), username);
1473 result = simple_prompt(prompt_text, 100, false);
1481 param_is_newly_set(const char *old_val, const char *new_val)
1483 if (new_val == NULL)
1486 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1493 * do_connect -- handler for \connect
1495 * Connects to a database with given parameters. If there exists an
1496 * established connection, NULL values will be replaced with the ones
1497 * in the current connection. Otherwise NULL will be passed for that
1498 * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1500 * In interactive mode, if connection fails with the given parameters,
1501 * the old connection will be kept.
1504 do_connect(char *dbname, char *user, char *host, char *port)
1506 PGconn *o_conn = pset.db,
1508 char *password = NULL;
1511 dbname = PQdb(o_conn);
1513 user = PQuser(o_conn);
1515 host = PQhost(o_conn);
1517 port = PQport(o_conn);
1520 * If the user asked to be prompted for a password, ask for one now. If
1521 * not, use the password from the old connection, provided the username
1522 * has not changed. Otherwise, try to connect without a password first,
1523 * and then ask for a password if needed.
1525 * XXX: this behavior leads to spurious connection attempts recorded in
1526 * the postmaster's log. But libpq offers no API that would let us obtain
1527 * a password and then continue with the first connection attempt.
1529 if (pset.getPassword == TRI_YES)
1531 password = prompt_for_password(user);
1533 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1535 password = strdup(PQpass(o_conn));
1540 #define PARAMS_ARRAY_SIZE 8
1541 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1542 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1544 keywords[0] = "host";
1546 keywords[1] = "port";
1548 keywords[2] = "user";
1550 keywords[3] = "password";
1551 values[3] = password;
1552 keywords[4] = "dbname";
1554 keywords[5] = "fallback_application_name";
1555 values[5] = pset.progname;
1556 keywords[6] = "client_encoding";
1557 values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
1561 n_conn = PQconnectdbParams(keywords, values, true);
1566 /* We can immediately discard the password -- no longer needed */
1570 if (PQstatus(n_conn) == CONNECTION_OK)
1574 * Connection attempt failed; either retry the connection attempt with
1575 * a new password, or give up.
1577 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1580 password = prompt_for_password(user);
1585 * Failed to connect to the database. In interactive mode, keep the
1586 * previous connection to the DB; in scripting mode, close our
1587 * previous connection as well.
1589 if (pset.cur_cmd_interactive)
1591 psql_error("%s", PQerrorMessage(n_conn));
1593 /* pset.db is left unmodified */
1595 fputs(_("Previous connection kept\n"), stderr);
1599 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1612 * Replace the old connection with the new one, and update
1613 * connection-dependent variables.
1615 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1618 connection_warnings(false); /* Must be after SyncVariables */
1620 /* Tell the user about the new connection */
1623 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
1624 param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1626 char *host = PQhost(pset.db);
1629 host = DEFAULT_PGSOCKET_DIR;
1630 /* If the host is an absolute path, the connection is via socket */
1631 if (is_absolute_path(host))
1632 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
1633 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1635 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
1636 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1639 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
1640 PQdb(pset.db), PQuser(pset.db));
1650 connection_warnings(bool in_startup)
1652 if (!pset.quiet && !pset.notty)
1654 int client_ver = parse_version(PG_VERSION);
1656 if (pset.sversion != client_ver)
1658 const char *server_version;
1659 char server_ver_str[16];
1661 /* Try to get full text form, might include "devel" etc */
1662 server_version = PQparameterStatus(pset.db, "server_version");
1663 if (!server_version)
1665 snprintf(server_ver_str, sizeof(server_ver_str),
1667 pset.sversion / 10000,
1668 (pset.sversion / 100) % 100,
1669 pset.sversion % 100);
1670 server_version = server_ver_str;
1673 printf(_("%s (%s, server %s)\n"),
1674 pset.progname, PG_VERSION, server_version);
1676 /* For version match, only print psql banner on startup. */
1677 else if (in_startup)
1678 printf("%s (%s)\n", pset.progname, PG_VERSION);
1680 if (pset.sversion / 100 != client_ver / 100)
1681 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1682 " Some psql features might not work.\n"),
1683 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1684 pset.sversion / 10000, (pset.sversion / 100) % 100);
1687 checkWin32Codepage();
1697 * Prints information about the current SSL connection, if SSL is in use
1706 ssl = PQgetssl(pset.db);
1708 return; /* no SSL */
1710 SSL_get_cipher_bits(ssl, &sslbits);
1711 printf(_("SSL connection (cipher: %s, bits: %d)\n"),
1712 SSL_get_cipher(ssl), sslbits);
1716 * If psql is compiled without SSL but is using a libpq with SSL, we
1717 * cannot figure out the specifics about the connection. But we know it's
1720 if (PQgetssl(pset.db))
1721 printf(_("SSL connection (unknown cipher)\n"));
1727 * checkWin32Codepage
1729 * Prints a warning when win32 console codepage differs from Windows codepage
1733 checkWin32Codepage(void)
1739 concp = GetConsoleCP();
1742 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1743 " 8-bit characters might not work correctly. See psql reference\n"
1744 " page \"Notes for Windows users\" for details.\n"),
1754 * Make psql's internal variables agree with connection state upon
1755 * establishing a new connection.
1760 /* get stuff from connection */
1761 pset.encoding = PQclientEncoding(pset.db);
1762 pset.popt.topt.encoding = pset.encoding;
1763 pset.sversion = PQserverVersion(pset.db);
1765 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1766 SetVariable(pset.vars, "USER", PQuser(pset.db));
1767 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1768 SetVariable(pset.vars, "PORT", PQport(pset.db));
1769 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1771 /* send stuff to it, too */
1772 PQsetErrorVerbosity(pset.db, pset.verbosity);
1778 * Clear variables that should be not be set when there is no connection.
1781 UnsyncVariables(void)
1783 SetVariable(pset.vars, "DBNAME", NULL);
1784 SetVariable(pset.vars, "USER", NULL);
1785 SetVariable(pset.vars, "HOST", NULL);
1786 SetVariable(pset.vars, "PORT", NULL);
1787 SetVariable(pset.vars, "ENCODING", NULL);
1792 * do_edit -- handler for \e
1794 * If you do not specify a filename, the current query buffer will be copied
1795 * into a temporary one.
1798 editFile(const char *fname, int lineno)
1800 const char *editorName;
1801 const char *editor_lineno_arg = NULL;
1807 /* Find an editor to use */
1808 editorName = getenv("PSQL_EDITOR");
1810 editorName = getenv("EDITOR");
1812 editorName = getenv("VISUAL");
1814 editorName = DEFAULT_EDITOR;
1816 /* Get line number argument, if we need it. */
1819 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
1820 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
1821 if (!editor_lineno_arg)
1822 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
1824 if (!editor_lineno_arg)
1826 psql_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number\n");
1831 /* Allocate sufficient memory for command line. */
1833 sys = pg_malloc(strlen(editorName)
1834 + strlen(editor_lineno_arg) + 10 /* for integer */
1835 + 1 + strlen(fname) + 10 + 1);
1837 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1840 * On Unix the EDITOR value should *not* be quoted, since it might include
1841 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1842 * if necessary. But this policy is not very workable on Windows, due to
1843 * severe brain damage in their command shell plus the fact that standard
1844 * program paths include spaces.
1848 sprintf(sys, "exec %s %s%d '%s'",
1849 editorName, editor_lineno_arg, lineno, fname);
1851 sprintf(sys, "exec %s '%s'",
1855 sprintf(sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE,
1856 editorName, editor_lineno_arg, lineno, fname);
1858 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE,
1861 result = system(sys);
1863 psql_error("could not start editor \"%s\"\n", editorName);
1864 else if (result == 127)
1865 psql_error("could not start /bin/sh\n");
1874 do_edit(const char *filename_arg, PQExpBuffer query_buf,
1875 int lineno, bool *edited)
1877 char fnametmp[MAXPGPATH];
1878 FILE *stream = NULL;
1887 fname = filename_arg;
1890 /* make a temp file to edit */
1892 const char *tmpdir = getenv("TMPDIR");
1897 char tmpdir[MAXPGPATH];
1900 ret = GetTempPath(MAXPGPATH, tmpdir);
1901 if (ret == 0 || ret > MAXPGPATH)
1903 psql_error("could not locate temporary directory: %s\n",
1904 !ret ? strerror(errno) : "");
1909 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1910 * current directory to the supplied path unless we use only
1911 * backslashes, so we do that.
1915 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1916 "/", (int) getpid());
1918 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1919 "" /* trailing separator already present */ , (int) getpid());
1922 fname = (const char *) fnametmp;
1924 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1926 stream = fdopen(fd, "w");
1928 if (fd == -1 || !stream)
1930 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1935 unsigned int ql = query_buf->len;
1937 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1939 appendPQExpBufferChar(query_buf, '\n');
1943 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1945 psql_error("%s: %s\n", fname, strerror(errno));
1950 else if (fclose(stream) != 0)
1952 psql_error("%s: %s\n", fname, strerror(errno));
1959 if (!error && stat(fname, &before) != 0)
1961 psql_error("%s: %s\n", fname, strerror(errno));
1967 error = !editFile(fname, lineno);
1969 if (!error && stat(fname, &after) != 0)
1971 psql_error("%s: %s\n", fname, strerror(errno));
1975 if (!error && before.st_mtime != after.st_mtime)
1977 stream = fopen(fname, PG_BINARY_R);
1980 psql_error("%s: %s\n", fname, strerror(errno));
1985 /* read file back into query_buf */
1988 resetPQExpBuffer(query_buf);
1989 while (fgets(line, sizeof(line), stream) != NULL)
1990 appendPQExpBufferStr(query_buf, line);
1994 psql_error("%s: %s\n", fname, strerror(errno));
2006 /* remove temp file */
2009 if (remove(fname) == -1)
2011 psql_error("%s: %s\n", fname, strerror(errno));
2024 * Read commands from filename and then them to the main processing loop
2025 * Handler for \i and \ir, but can be used for other things as well. Returns
2026 * MainLoop() error code.
2028 * If use_relative_path is true and filename is not an absolute path, then open
2029 * the file from where the currently processed file (if any) is located.
2032 process_file(char *filename, bool single_txn, bool use_relative_path)
2037 char relpath[MAXPGPATH];
2041 return EXIT_FAILURE;
2043 if (strcmp(filename, "-") != 0)
2045 canonicalize_path(filename);
2048 * If we were asked to resolve the pathname relative to the location
2049 * of the currently executing script, and there is one, and this is
2050 * a relative pathname, then prepend all but the last pathname
2051 * component of the current script to this pathname.
2053 if (use_relative_path && pset.inputfile && !is_absolute_path(filename)
2054 && !has_drive_prefix(filename))
2056 snprintf(relpath, MAXPGPATH, "%s", pset.inputfile);
2057 get_parent_directory(relpath);
2058 join_path_components(relpath, relpath, filename);
2059 canonicalize_path(relpath);
2064 fd = fopen(filename, PG_BINARY_R);
2068 psql_error("%s: %s\n", filename, strerror(errno));
2069 return EXIT_FAILURE;
2075 filename = "<stdin>"; /* for future error messages */
2078 oldfilename = pset.inputfile;
2079 pset.inputfile = filename;
2083 if ((res = PSQLexec("BEGIN", false)) == NULL)
2085 if (pset.on_error_stop)
2095 result = MainLoop(fd);
2099 if ((res = PSQLexec("COMMIT", false)) == NULL)
2101 if (pset.on_error_stop)
2115 pset.inputfile = oldfilename;
2126 _align2string(enum printFormat in)
2133 case PRINT_UNALIGNED:
2148 case PRINT_TROFF_MS:
2157 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
2164 vallen = strlen(value);
2167 if (strcmp(param, "format") == 0)
2171 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2172 popt->topt.format = PRINT_UNALIGNED;
2173 else if (pg_strncasecmp("aligned", value, vallen) == 0)
2174 popt->topt.format = PRINT_ALIGNED;
2175 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2176 popt->topt.format = PRINT_WRAPPED;
2177 else if (pg_strncasecmp("html", value, vallen) == 0)
2178 popt->topt.format = PRINT_HTML;
2179 else if (pg_strncasecmp("latex", value, vallen) == 0)
2180 popt->topt.format = PRINT_LATEX;
2181 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2182 popt->topt.format = PRINT_TROFF_MS;
2185 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
2190 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2193 /* set table line style */
2194 else if (strcmp(param, "linestyle") == 0)
2198 else if (pg_strncasecmp("ascii", value, vallen) == 0)
2199 popt->topt.line_style = &pg_asciiformat;
2200 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2201 popt->topt.line_style = &pg_asciiformat_old;
2202 else if (pg_strncasecmp("unicode", value, vallen) == 0)
2203 popt->topt.line_style = &pg_utf8format;
2206 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2211 printf(_("Line style is %s.\n"),
2212 get_line_style(&popt->topt)->name);
2215 /* set border style/width */
2216 else if (strcmp(param, "border") == 0)
2219 popt->topt.border = atoi(value);
2222 printf(_("Border style is %d.\n"), popt->topt.border);
2225 /* set expanded/vertical mode */
2226 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2228 if (value && pg_strcasecmp(value, "auto") == 0)
2229 popt->topt.expanded = 2;
2231 popt->topt.expanded = ParseVariableBool(value);
2233 popt->topt.expanded = !popt->topt.expanded;
2236 if (popt->topt.expanded == 1)
2237 printf(_("Expanded display is on.\n"));
2238 else if (popt->topt.expanded == 2)
2239 printf(_("Expanded display is used automatically.\n"));
2241 printf(_("Expanded display is off.\n"));
2245 /* locale-aware numeric output */
2246 else if (strcmp(param, "numericlocale") == 0)
2249 popt->topt.numericLocale = ParseVariableBool(value);
2251 popt->topt.numericLocale = !popt->topt.numericLocale;
2254 if (popt->topt.numericLocale)
2255 puts(_("Showing locale-adjusted numeric output."));
2257 puts(_("Locale-adjusted numeric output is off."));
2262 else if (strcmp(param, "null") == 0)
2266 free(popt->nullPrint);
2267 popt->nullPrint = pg_strdup(value);
2270 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
2273 /* field separator for unaligned text */
2274 else if (strcmp(param, "fieldsep") == 0)
2278 free(popt->topt.fieldSep.separator);
2279 popt->topt.fieldSep.separator = pg_strdup(value);
2280 popt->topt.fieldSep.separator_zero = false;
2284 if (popt->topt.fieldSep.separator_zero)
2285 printf(_("Field separator is zero byte.\n"));
2287 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep.separator);
2291 else if (strcmp(param, "fieldsep_zero") == 0)
2293 free(popt->topt.fieldSep.separator);
2294 popt->topt.fieldSep.separator = NULL;
2295 popt->topt.fieldSep.separator_zero = true;
2297 printf(_("Field separator is zero byte.\n"));
2300 /* record separator for unaligned text */
2301 else if (strcmp(param, "recordsep") == 0)
2305 free(popt->topt.recordSep.separator);
2306 popt->topt.recordSep.separator = pg_strdup(value);
2307 popt->topt.recordSep.separator_zero = false;
2311 if (popt->topt.recordSep.separator_zero)
2312 printf(_("Record separator is zero byte.\n"));
2313 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
2314 printf(_("Record separator is <newline>."));
2316 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep.separator);
2320 else if (strcmp(param, "recordsep_zero") == 0)
2322 free(popt->topt.recordSep.separator);
2323 popt->topt.recordSep.separator = NULL;
2324 popt->topt.recordSep.separator_zero = true;
2326 printf(_("Record separator is zero byte.\n"));
2329 /* toggle between full and tuples-only format */
2330 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2333 popt->topt.tuples_only = ParseVariableBool(value);
2335 popt->topt.tuples_only = !popt->topt.tuples_only;
2338 if (popt->topt.tuples_only)
2339 puts(_("Showing only tuples."));
2341 puts(_("Tuples only is off."));
2345 /* set title override */
2346 else if (strcmp(param, "title") == 0)
2352 popt->title = pg_strdup(value);
2357 printf(_("Title is \"%s\".\n"), popt->title);
2359 printf(_("Title is unset.\n"));
2363 /* set HTML table tag options */
2364 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2366 free(popt->topt.tableAttr);
2368 popt->topt.tableAttr = NULL;
2370 popt->topt.tableAttr = pg_strdup(value);
2374 if (popt->topt.tableAttr)
2375 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
2377 printf(_("Table attributes unset.\n"));
2381 /* toggle use of pager */
2382 else if (strcmp(param, "pager") == 0)
2384 if (value && pg_strcasecmp(value, "always") == 0)
2385 popt->topt.pager = 2;
2387 if (ParseVariableBool(value))
2388 popt->topt.pager = 1;
2390 popt->topt.pager = 0;
2391 else if (popt->topt.pager == 1)
2392 popt->topt.pager = 0;
2394 popt->topt.pager = 1;
2397 if (popt->topt.pager == 1)
2398 puts(_("Pager is used for long output."));
2399 else if (popt->topt.pager == 2)
2400 puts(_("Pager is always used."));
2402 puts(_("Pager usage is off."));
2406 /* disable "(x rows)" footer */
2407 else if (strcmp(param, "footer") == 0)
2410 popt->default_footer = ParseVariableBool(value);
2412 popt->default_footer = !popt->default_footer;
2415 if (popt->default_footer)
2416 puts(_("Default footer is on."));
2418 puts(_("Default footer is off."));
2422 /* set border style/width */
2423 else if (strcmp(param, "columns") == 0)
2426 popt->topt.columns = atoi(value);
2429 printf(_("Target width is %d.\n"), popt->topt.columns);
2434 psql_error("\\pset: unknown option: %s\n", param);
2444 #define DEFAULT_SHELL "/bin/sh"
2447 * CMD.EXE is in different places in different Win32 releases so we
2448 * have to rely on the path to find it.
2450 #define DEFAULT_SHELL "cmd.exe"
2454 do_shell(const char *command)
2461 const char *shellName;
2463 shellName = getenv("SHELL");
2465 if (shellName == NULL)
2466 shellName = getenv("COMSPEC");
2468 if (shellName == NULL)
2469 shellName = DEFAULT_SHELL;
2471 sys = pg_malloc(strlen(shellName) + 16);
2474 /* See EDITOR handling comment for an explanation */
2475 "exec %s", shellName);
2477 /* See EDITOR handling comment for an explanation */
2478 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2480 result = system(sys);
2484 result = system(command);
2486 if (result == 127 || result == -1)
2488 psql_error("\\!: failed\n");
2495 * This function takes a function description, e.g. "x" or "x(int)", and
2496 * issues a query on the given connection to retrieve the function's OID
2497 * using a cast to regproc or regprocedure (as appropriate). The result,
2498 * if there is one, is returned at *foid. Note that we'll fail if the
2499 * function doesn't exist OR if there are multiple matching candidates
2500 * OR if there's something syntactically wrong with the function description;
2501 * unfortunately it can be hard to tell the difference.
2504 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2510 query = createPQExpBuffer();
2511 printfPQExpBuffer(query, "SELECT ");
2512 appendStringLiteralConn(query, desc, conn);
2513 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2514 strchr(desc, '(') ? "regprocedure" : "regproc");
2516 res = PQexec(conn, query->data);
2517 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2518 *foid = atooid(PQgetvalue(res, 0, 0));
2521 minimal_error_message(res);
2526 destroyPQExpBuffer(query);
2532 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2533 * function with the given OID. If successful, the result is stored in buf.
2536 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2542 query = createPQExpBuffer();
2543 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2545 res = PQexec(conn, query->data);
2546 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2548 resetPQExpBuffer(buf);
2549 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2553 minimal_error_message(res);
2558 destroyPQExpBuffer(query);
2564 * If the given argument of \ef ends with a line number, delete the line
2565 * number from the argument string and return it as an integer. (We need
2566 * this kluge because we're too lazy to parse \ef's function name argument
2567 * carefully --- we just slop it up in OT_WHOLE_LINE mode.)
2569 * Returns -1 if no line number is present, 0 on error, or a positive value
2573 strip_lineno_from_funcdesc(char *func)
2578 if (!func || func[0] == '\0')
2581 c = func + strlen(func) - 1;
2584 * This business of parsing backwards is dangerous as can be in a
2585 * multibyte environment: there is no reason to believe that we are
2586 * looking at the first byte of a character, nor are we necessarily
2587 * working in a "safe" encoding. Fortunately the bitpatterns we are
2588 * looking for are unlikely to occur as non-first bytes, but beware of
2589 * trying to expand the set of cases that can be recognized. We must
2590 * guard the <ctype.h> macros by using isascii() first, too.
2593 /* skip trailing whitespace */
2594 while (c > func && isascii((unsigned char) *c) && isspace((unsigned char) *c))
2597 /* must have a digit as last non-space char */
2598 if (c == func || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
2601 /* find start of digit string */
2602 while (c > func && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
2605 /* digits must be separated from func name by space or closing paren */
2606 /* notice also that we are not allowing an empty func name ... */
2607 if (c == func || !isascii((unsigned char) *c) ||
2608 !(isspace((unsigned char) *c) || *c == ')'))
2611 /* parse digit string */
2616 psql_error("invalid line number: %s\n", c);
2620 /* strip digit string from func */
2627 * Report just the primary error; this is to avoid cluttering the output
2628 * with, for instance, a redisplay of the internally generated query
2631 minimal_error_message(PGresult *res)
2636 msg = createPQExpBuffer();
2638 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2640 printfPQExpBuffer(msg, "%s: ", fld);
2642 printfPQExpBuffer(msg, "ERROR: ");
2643 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2645 appendPQExpBufferStr(msg, fld);
2647 appendPQExpBufferStr(msg, "(not available)");
2648 appendPQExpBufferStr(msg, "\n");
2650 psql_error("%s", msg->data);
2652 destroyPQExpBuffer(msg);