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 Assert(scan_state != NULL);
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 psql_error("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));
322 else if (pg_strcasecmp(cmd, "copy") == 0)
324 char *opt = psql_scan_slash_option(scan_state,
325 OT_WHOLE_LINE, NULL, false);
327 success = do_copy(opt);
332 else if (strcmp(cmd, "copyright") == 0)
336 else if (cmd[0] == 'd')
342 /* We don't do SQLID reduction on the pattern yet */
343 pattern = psql_scan_slash_option(scan_state,
344 OT_NORMAL, NULL, true);
346 show_verbose = strchr(cmd, '+') ? true : false;
347 show_system = strchr(cmd, 'S') ? true : false;
355 success = describeTableDetails(pattern, show_verbose, show_system);
357 /* standard listing of interesting things */
358 success = listTables("tvsE", NULL, show_verbose, show_system);
361 success = describeAggregates(pattern, show_verbose, show_system);
364 success = describeTablespaces(pattern, show_verbose);
367 success = listConversions(pattern, show_verbose, show_system);
370 success = listCasts(pattern, show_verbose);
373 if (strncmp(cmd, "ddp", 3) == 0)
374 success = listDefaultACLs(pattern);
376 success = objectDescription(pattern, show_system);
379 success = listDomains(pattern, show_verbose, show_system);
381 case 'f': /* function subsystem */
391 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
394 status = PSQL_CMD_UNKNOWN;
399 /* no longer distinct from \du */
400 success = describeRoles(pattern, show_verbose);
403 success = do_lo_list();
406 success = listLanguages(pattern, show_verbose, show_system);
409 success = listSchemas(pattern, show_verbose, show_system);
412 success = describeOperators(pattern, show_system);
415 success = listCollations(pattern, show_verbose, show_system);
418 success = permissionsList(pattern);
421 success = describeTypes(pattern, show_verbose, show_system);
428 success = listTables(&cmd[1], pattern, show_verbose, show_system);
431 if (cmd[2] == 'd' && cmd[3] == 's')
433 char *pattern2 = NULL;
436 pattern2 = psql_scan_slash_option(scan_state,
437 OT_NORMAL, NULL, true);
438 success = listDbRoleSettings(pattern, pattern2);
441 success = PSQL_CMD_UNKNOWN;
444 success = describeRoles(pattern, show_verbose);
446 case 'F': /* text search subsystem */
451 success = listTSConfigs(pattern, show_verbose);
454 success = listTSParsers(pattern, show_verbose);
457 success = listTSDictionaries(pattern, show_verbose);
460 success = listTSTemplates(pattern, show_verbose);
463 status = PSQL_CMD_UNKNOWN;
467 case 'e': /* SQL/MED subsystem */
471 success = listForeignServers(pattern, show_verbose);
474 success = listUserMappings(pattern, show_verbose);
477 success = listForeignDataWrappers(pattern, show_verbose);
480 success = listForeignTables(pattern, show_verbose);
483 status = PSQL_CMD_UNKNOWN;
487 case 'x': /* Extensions */
489 success = listExtensionContents(pattern);
491 success = listExtensions(pattern);
493 case 'y': /* Event Triggers */
494 success = listEventTriggers(pattern, show_verbose);
497 status = PSQL_CMD_UNKNOWN;
506 * \e or \edit -- edit the current query buffer, or edit a file and make
507 * it the query buffer
509 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
513 psql_error("no query buffer\n");
514 status = PSQL_CMD_ERROR;
522 fname = psql_scan_slash_option(scan_state,
523 OT_NORMAL, NULL, true);
526 /* try to get separate lineno arg */
527 ln = psql_scan_slash_option(scan_state,
528 OT_NORMAL, NULL, true);
531 /* only one arg; maybe it is lineno not fname */
533 strspn(fname, "0123456789") == strlen(fname))
535 /* all digits, so assume it is lineno */
546 psql_error("invalid line number: %s\n", ln);
547 status = PSQL_CMD_ERROR;
550 if (status != PSQL_CMD_ERROR)
552 expand_tilde(&fname);
554 canonicalize_path(fname);
555 if (do_edit(fname, query_buf, lineno, NULL))
556 status = PSQL_CMD_NEWEDIT;
558 status = PSQL_CMD_ERROR;
568 * \ef -- edit the named function, or present a blank CREATE FUNCTION
569 * template if no argument is given
571 else if (strcmp(cmd, "ef") == 0)
575 if (pset.sversion < 80400)
577 psql_error("The server (version %d.%d) does not support editing function source.\n",
578 pset.sversion / 10000, (pset.sversion / 100) % 100);
579 status = PSQL_CMD_ERROR;
583 psql_error("no query buffer\n");
584 status = PSQL_CMD_ERROR;
589 Oid foid = InvalidOid;
591 func = psql_scan_slash_option(scan_state,
592 OT_WHOLE_LINE, NULL, true);
593 lineno = strip_lineno_from_funcdesc(func);
596 /* error already reported */
597 status = PSQL_CMD_ERROR;
601 /* set up an empty command to fill in */
602 printfPQExpBuffer(query_buf,
603 "CREATE FUNCTION ( )\n"
606 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
610 else if (!lookup_function_oid(pset.db, func, &foid))
612 /* error already reported */
613 status = PSQL_CMD_ERROR;
615 else if (!get_create_function_cmd(pset.db, foid, query_buf))
617 /* error already reported */
618 status = PSQL_CMD_ERROR;
623 * lineno "1" should correspond to the first line of the
624 * function body. We expect that pg_get_functiondef() will
625 * emit that on a line beginning with "AS ", and that there
626 * can be no such line before the real start of the function
627 * body. Increment lineno by the number of lines before that
628 * line, so that it becomes relative to the first line of the
629 * function definition.
631 const char *lines = query_buf->data;
633 while (*lines != '\0')
635 if (strncmp(lines, "AS ", 3) == 0)
638 /* find start of next line */
639 lines = strchr(lines, '\n');
650 if (status != PSQL_CMD_ERROR)
654 if (!do_edit(NULL, query_buf, lineno, &edited))
655 status = PSQL_CMD_ERROR;
657 puts(_("No changes"));
659 status = PSQL_CMD_NEWEDIT;
663 /* \echo and \qecho */
664 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
668 bool no_newline = false;
672 if (strcmp(cmd, "qecho") == 0)
673 fout = pset.queryFout;
677 while ((value = psql_scan_slash_option(scan_state,
678 OT_NORMAL, "ed, false)))
680 if (!quoted && strcmp(value, "-n") == 0)
696 /* \encoding -- set/show client side encoding */
697 else if (strcmp(cmd, "encoding") == 0)
699 char *encoding = psql_scan_slash_option(scan_state,
700 OT_NORMAL, NULL, false);
705 puts(pg_encoding_to_char(pset.encoding));
710 if (PQsetClientEncoding(pset.db, encoding) == -1)
711 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
714 /* save encoding info into psql internal data */
715 pset.encoding = PQclientEncoding(pset.db);
716 pset.popt.topt.encoding = pset.encoding;
717 SetVariable(pset.vars, "ENCODING",
718 pg_encoding_to_char(pset.encoding));
724 /* \f -- change field separator */
725 else if (strcmp(cmd, "f") == 0)
727 char *fname = psql_scan_slash_option(scan_state,
728 OT_NORMAL, NULL, false);
730 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
734 /* \g means send query */
735 else if (strcmp(cmd, "g") == 0)
737 char *fname = psql_scan_slash_option(scan_state,
738 OT_FILEPIPE, NULL, false);
744 expand_tilde(&fname);
745 pset.gfname = pg_strdup(fname);
748 status = PSQL_CMD_SEND;
752 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
754 char *opt = psql_scan_slash_option(scan_state,
755 OT_WHOLE_LINE, NULL, false);
758 /* strip any trailing spaces and semicolons */
763 (isspace((unsigned char) opt[len - 1])
764 || opt[len - 1] == ';'))
768 helpSQL(opt, pset.popt.topt.pager);
773 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
775 if (pset.popt.topt.format != PRINT_HTML)
776 success = do_pset("format", "html", &pset.popt, pset.quiet);
778 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
782 /* \i and \ir include files */
783 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0
784 || strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
786 char *fname = psql_scan_slash_option(scan_state,
787 OT_NORMAL, NULL, true);
791 psql_error("\\%s: missing required argument\n", cmd);
796 bool include_relative;
798 include_relative = (strcmp(cmd, "ir") == 0
799 || strcmp(cmd, "include_relative") == 0);
800 expand_tilde(&fname);
801 success = (process_file(fname, false, include_relative) == EXIT_SUCCESS);
806 /* \l is list databases */
807 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
808 success = listAllDbs(false);
809 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
810 success = listAllDbs(true);
813 * large object things
815 else if (strncmp(cmd, "lo_", 3) == 0)
820 opt1 = psql_scan_slash_option(scan_state,
821 OT_NORMAL, NULL, true);
822 opt2 = psql_scan_slash_option(scan_state,
823 OT_NORMAL, NULL, true);
825 if (strcmp(cmd + 3, "export") == 0)
829 psql_error("\\%s: missing required argument\n", cmd);
835 success = do_lo_export(opt1, opt2);
839 else if (strcmp(cmd + 3, "import") == 0)
843 psql_error("\\%s: missing required argument\n", cmd);
849 success = do_lo_import(opt1, opt2);
853 else if (strcmp(cmd + 3, "list") == 0)
854 success = do_lo_list();
856 else if (strcmp(cmd + 3, "unlink") == 0)
860 psql_error("\\%s: missing required argument\n", cmd);
864 success = do_lo_unlink(opt1);
868 status = PSQL_CMD_UNKNOWN;
875 /* \o -- set query output */
876 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
878 char *fname = psql_scan_slash_option(scan_state,
879 OT_FILEPIPE, NULL, true);
881 expand_tilde(&fname);
882 success = setQFout(fname);
886 /* \p prints the current query buffer */
887 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
889 if (query_buf && query_buf->len > 0)
890 puts(query_buf->data);
891 else if (!pset.quiet)
892 puts(_("Query buffer is empty."));
896 /* \password -- set user password */
897 else if (strcmp(cmd, "password") == 0)
902 pw1 = simple_prompt("Enter new password: ", 100, false);
903 pw2 = simple_prompt("Enter it again: ", 100, false);
905 if (strcmp(pw1, pw2) != 0)
907 psql_error("Passwords didn't match.\n");
912 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
914 char *encrypted_password;
919 user = PQuser(pset.db);
921 encrypted_password = PQencryptPassword(pw1, user);
923 if (!encrypted_password)
925 psql_error("Password encryption failed.\n");
933 initPQExpBuffer(&buf);
934 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
936 appendStringLiteralConn(&buf, encrypted_password, pset.db);
937 res = PSQLexec(buf.data, false);
938 termPQExpBuffer(&buf);
943 PQfreemem(encrypted_password);
954 /* \prompt -- prompt and set variable */
955 else if (strcmp(cmd, "prompt") == 0)
962 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
963 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
967 psql_error("\\%s: missing required argument\n", cmd);
983 result = simple_prompt(prompt_text, 4096, true);
988 fputs(prompt_text, stdout);
991 result = gets_fromFile(stdin);
994 if (!SetVariable(pset.vars, opt, result))
996 psql_error("\\%s: error while setting variable\n", cmd);
1007 /* \pset -- set printing parameters */
1008 else if (strcmp(cmd, "pset") == 0)
1010 char *opt0 = psql_scan_slash_option(scan_state,
1011 OT_NORMAL, NULL, false);
1012 char *opt1 = psql_scan_slash_option(scan_state,
1013 OT_NORMAL, NULL, false);
1017 psql_error("\\%s: missing required argument\n", cmd);
1021 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1028 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1029 status = PSQL_CMD_TERMINATE;
1031 /* reset(clear) the buffer */
1032 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1034 resetPQExpBuffer(query_buf);
1035 psql_scan_reset(scan_state);
1037 puts(_("Query buffer reset (cleared)."));
1040 /* \s save history in a file or show it on the screen */
1041 else if (strcmp(cmd, "s") == 0)
1043 char *fname = psql_scan_slash_option(scan_state,
1044 OT_NORMAL, NULL, true);
1046 expand_tilde(&fname);
1047 /* This scrolls off the screen when using /dev/tty */
1048 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
1049 if (success && !pset.quiet && fname)
1050 printf(gettext("Wrote history to file \"%s/%s\".\n"),
1051 pset.dirname ? pset.dirname : ".", fname);
1057 /* \set -- generalized set variable/option command */
1058 else if (strcmp(cmd, "set") == 0)
1060 char *opt0 = psql_scan_slash_option(scan_state,
1061 OT_NORMAL, NULL, false);
1065 /* list all variables */
1066 PrintVariables(pset.vars);
1072 * Set variable to the concatenation of the arguments.
1077 opt = psql_scan_slash_option(scan_state,
1078 OT_NORMAL, NULL, false);
1079 newval = pg_strdup(opt ? opt : "");
1082 while ((opt = psql_scan_slash_option(scan_state,
1083 OT_NORMAL, NULL, false)))
1085 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
1088 psql_error("out of memory\n");
1091 strcat(newval, opt);
1095 if (!SetVariable(pset.vars, opt0, newval))
1097 psql_error("\\%s: error while setting variable\n", cmd);
1106 /* \setenv -- set environment command */
1107 else if (strcmp(cmd, "setenv") == 0)
1109 char *envvar = psql_scan_slash_option(scan_state,
1110 OT_NORMAL, NULL, false);
1111 char *envval = psql_scan_slash_option(scan_state,
1112 OT_NORMAL, NULL, false);
1116 psql_error("\\%s: missing required argument\n", cmd);
1119 else if (strchr(envvar, '=') != NULL)
1121 psql_error("\\%s: environment variable name must not contain \"=\"\n",
1127 /* No argument - unset the environment variable */
1133 /* Set variable to the value of the next argument */
1134 int len = strlen(envvar) + strlen(envval) + 1;
1135 char *newval = pg_malloc(len + 1);
1137 snprintf(newval, len + 1, "%s=%s", envvar, envval);
1142 * Do not free newval here, it will screw up the environment if
1143 * you do. See putenv man page for details. That means we leak a
1144 * bit of memory here, but not enough to worry about.
1151 /* \sf -- show a function's source code */
1152 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1154 bool show_linenumbers = (strcmp(cmd, "sf+") == 0);
1155 PQExpBuffer func_buf;
1157 Oid foid = InvalidOid;
1159 func_buf = createPQExpBuffer();
1160 func = psql_scan_slash_option(scan_state,
1161 OT_WHOLE_LINE, NULL, true);
1162 if (pset.sversion < 80400)
1164 psql_error("The server (version %d.%d) does not support showing function source.\n",
1165 pset.sversion / 10000, (pset.sversion / 100) % 100);
1166 status = PSQL_CMD_ERROR;
1170 psql_error("function name is required\n");
1171 status = PSQL_CMD_ERROR;
1173 else if (!lookup_function_oid(pset.db, func, &foid))
1175 /* error already reported */
1176 status = PSQL_CMD_ERROR;
1178 else if (!get_create_function_cmd(pset.db, foid, func_buf))
1180 /* error already reported */
1181 status = PSQL_CMD_ERROR;
1188 /* Select output stream: stdout, pager, or file */
1189 if (pset.queryFout == stdout)
1191 /* count lines in function to see if pager is needed */
1193 const char *lines = func_buf->data;
1195 while (*lines != '\0')
1198 /* find start of next line */
1199 lines = strchr(lines, '\n');
1205 output = PageOutput(lineno, pset.popt.topt.pager);
1210 /* use previously set output file, without pager */
1211 output = pset.queryFout;
1215 if (show_linenumbers)
1217 bool in_header = true;
1219 char *lines = func_buf->data;
1222 * lineno "1" should correspond to the first line of the
1223 * function body. We expect that pg_get_functiondef() will
1224 * emit that on a line beginning with "AS ", and that there
1225 * can be no such line before the real start of the function
1228 * Note that this loop scribbles on func_buf.
1230 while (*lines != '\0')
1234 if (in_header && strncmp(lines, "AS ", 3) == 0)
1236 /* increment lineno only for body's lines */
1240 /* find and mark end of current line */
1241 eol = strchr(lines, '\n');
1245 /* show current line as appropriate */
1247 fprintf(output, " %s\n", lines);
1249 fprintf(output, "%-7d %s\n", lineno, lines);
1251 /* advance to next line, if any */
1259 /* just send the function definition to output */
1260 fputs(func_buf->data, output);
1269 destroyPQExpBuffer(func_buf);
1272 /* \t -- turn off headers and row count */
1273 else if (strcmp(cmd, "t") == 0)
1275 char *opt = psql_scan_slash_option(scan_state,
1276 OT_NORMAL, NULL, true);
1278 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1282 /* \T -- define html <table ...> attributes */
1283 else if (strcmp(cmd, "T") == 0)
1285 char *value = psql_scan_slash_option(scan_state,
1286 OT_NORMAL, NULL, false);
1288 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1292 /* \timing -- toggle timing of queries */
1293 else if (strcmp(cmd, "timing") == 0)
1295 char *opt = psql_scan_slash_option(scan_state,
1296 OT_NORMAL, NULL, false);
1299 pset.timing = ParseVariableBool(opt);
1301 pset.timing = !pset.timing;
1305 puts(_("Timing is on."));
1307 puts(_("Timing is off."));
1313 else if (strcmp(cmd, "unset") == 0)
1315 char *opt = psql_scan_slash_option(scan_state,
1316 OT_NORMAL, NULL, false);
1320 psql_error("\\%s: missing required argument\n", cmd);
1323 else if (!SetVariable(pset.vars, opt, NULL))
1325 psql_error("\\%s: error while setting variable\n", cmd);
1331 /* \w -- write query buffer to file */
1332 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1335 bool is_pipe = false;
1340 psql_error("no query buffer\n");
1341 status = PSQL_CMD_ERROR;
1345 fname = psql_scan_slash_option(scan_state,
1346 OT_FILEPIPE, NULL, true);
1347 expand_tilde(&fname);
1351 psql_error("\\%s: missing required argument\n", cmd);
1356 if (fname[0] == '|')
1359 fd = popen(&fname[1], "w");
1363 canonicalize_path(fname);
1364 fd = fopen(fname, "w");
1368 psql_error("%s: %s\n", fname, strerror(errno));
1378 if (query_buf && query_buf->len > 0)
1379 fprintf(fd, "%s\n", query_buf->data);
1382 result = pclose(fd);
1384 result = fclose(fd);
1388 psql_error("%s: %s\n", fname, strerror(errno));
1396 /* \x -- set or toggle expanded table representation */
1397 else if (strcmp(cmd, "x") == 0)
1399 char *opt = psql_scan_slash_option(scan_state,
1400 OT_NORMAL, NULL, true);
1402 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1406 /* \z -- list table rights (equivalent to \dp) */
1407 else if (strcmp(cmd, "z") == 0)
1409 char *pattern = psql_scan_slash_option(scan_state,
1410 OT_NORMAL, NULL, true);
1412 success = permissionsList(pattern);
1417 /* \! -- shell escape */
1418 else if (strcmp(cmd, "!") == 0)
1420 char *opt = psql_scan_slash_option(scan_state,
1421 OT_WHOLE_LINE, NULL, false);
1423 success = do_shell(opt);
1427 /* \? -- slash command help */
1428 else if (strcmp(cmd, "?") == 0)
1429 slashUsage(pset.popt.topt.pager);
1434 * These commands don't do anything. I just use them to test the parser.
1436 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1441 while ((value = psql_scan_slash_option(scan_state,
1442 OT_NORMAL, NULL, true)))
1444 psql_error("+ opt(%d) = |%s|\n", i++, value);
1451 status = PSQL_CMD_UNKNOWN;
1454 status = PSQL_CMD_ERROR;
1460 * Ask the user for a password; 'username' is the username the
1461 * password is for, if one has been explicitly specified. Returns a
1465 prompt_for_password(const char *username)
1469 if (username == NULL)
1470 result = simple_prompt("Password: ", 100, false);
1475 prompt_text = pg_malloc(strlen(username) + 100);
1476 snprintf(prompt_text, strlen(username) + 100,
1477 _("Password for user %s: "), username);
1478 result = simple_prompt(prompt_text, 100, false);
1486 param_is_newly_set(const char *old_val, const char *new_val)
1488 if (new_val == NULL)
1491 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1498 * do_connect -- handler for \connect
1500 * Connects to a database with given parameters. If there exists an
1501 * established connection, NULL values will be replaced with the ones
1502 * in the current connection. Otherwise NULL will be passed for that
1503 * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1505 * In interactive mode, if connection fails with the given parameters,
1506 * the old connection will be kept.
1509 do_connect(char *dbname, char *user, char *host, char *port)
1511 PGconn *o_conn = pset.db,
1513 char *password = NULL;
1515 if (!o_conn && (!dbname || !user || !host || !port))
1518 * We don't know the supplied connection parameters and don't want
1519 * to connect to the wrong database by using defaults, so require
1520 * all parameters to be specified.
1522 psql_error("All connection parameters must be supplied because no "
1523 "database connection exists\n");
1528 dbname = PQdb(o_conn);
1530 user = PQuser(o_conn);
1532 host = PQhost(o_conn);
1534 port = PQport(o_conn);
1537 * If the user asked to be prompted for a password, ask for one now. If
1538 * not, use the password from the old connection, provided the username
1539 * has not changed. Otherwise, try to connect without a password first,
1540 * and then ask for a password if needed.
1542 * XXX: this behavior leads to spurious connection attempts recorded in
1543 * the postmaster's log. But libpq offers no API that would let us obtain
1544 * a password and then continue with the first connection attempt.
1546 if (pset.getPassword == TRI_YES)
1548 password = prompt_for_password(user);
1550 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1552 password = pg_strdup(PQpass(o_conn));
1557 #define PARAMS_ARRAY_SIZE 8
1558 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1559 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1561 keywords[0] = "host";
1563 keywords[1] = "port";
1565 keywords[2] = "user";
1567 keywords[3] = "password";
1568 values[3] = password;
1569 keywords[4] = "dbname";
1571 keywords[5] = "fallback_application_name";
1572 values[5] = pset.progname;
1573 keywords[6] = "client_encoding";
1574 values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
1578 n_conn = PQconnectdbParams(keywords, values, true);
1583 /* We can immediately discard the password -- no longer needed */
1587 if (PQstatus(n_conn) == CONNECTION_OK)
1591 * Connection attempt failed; either retry the connection attempt with
1592 * a new password, or give up.
1594 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1597 password = prompt_for_password(user);
1602 * Failed to connect to the database. In interactive mode, keep the
1603 * previous connection to the DB; in scripting mode, close our
1604 * previous connection as well.
1606 if (pset.cur_cmd_interactive)
1608 psql_error("%s", PQerrorMessage(n_conn));
1610 /* pset.db is left unmodified */
1612 psql_error("Previous connection kept\n");
1616 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1629 * Replace the old connection with the new one, and update
1630 * connection-dependent variables.
1632 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1635 connection_warnings(false); /* Must be after SyncVariables */
1637 /* Tell the user about the new connection */
1640 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
1641 param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1643 char *host = PQhost(pset.db);
1646 host = DEFAULT_PGSOCKET_DIR;
1647 /* If the host is an absolute path, the connection is via socket */
1648 if (is_absolute_path(host))
1649 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
1650 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1652 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
1653 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1656 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
1657 PQdb(pset.db), PQuser(pset.db));
1667 connection_warnings(bool in_startup)
1669 if (!pset.quiet && !pset.notty)
1671 int client_ver = parse_version(PG_VERSION);
1673 if (pset.sversion != client_ver)
1675 const char *server_version;
1676 char server_ver_str[16];
1678 /* Try to get full text form, might include "devel" etc */
1679 server_version = PQparameterStatus(pset.db, "server_version");
1680 if (!server_version)
1682 snprintf(server_ver_str, sizeof(server_ver_str),
1684 pset.sversion / 10000,
1685 (pset.sversion / 100) % 100,
1686 pset.sversion % 100);
1687 server_version = server_ver_str;
1690 printf(_("%s (%s, server %s)\n"),
1691 pset.progname, PG_VERSION, server_version);
1693 /* For version match, only print psql banner on startup. */
1694 else if (in_startup)
1695 printf("%s (%s)\n", pset.progname, PG_VERSION);
1697 if (pset.sversion / 100 > client_ver / 100)
1698 printf(_("WARNING: %s major version %d.%d, server major version %d.%d.\n"
1699 " Some psql features might not work.\n"),
1700 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1701 pset.sversion / 10000, (pset.sversion / 100) % 100);
1704 checkWin32Codepage();
1714 * Prints information about the current SSL connection, if SSL is in use
1723 ssl = PQgetssl(pset.db);
1725 return; /* no SSL */
1727 SSL_get_cipher_bits(ssl, &sslbits);
1728 printf(_("SSL connection (cipher: %s, bits: %d)\n"),
1729 SSL_get_cipher(ssl), sslbits);
1733 * If psql is compiled without SSL but is using a libpq with SSL, we
1734 * cannot figure out the specifics about the connection. But we know it's
1737 if (PQgetssl(pset.db))
1738 printf(_("SSL connection (unknown cipher)\n"));
1744 * checkWin32Codepage
1746 * Prints a warning when win32 console codepage differs from Windows codepage
1750 checkWin32Codepage(void)
1756 concp = GetConsoleCP();
1759 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1760 " 8-bit characters might not work correctly. See psql reference\n"
1761 " page \"Notes for Windows users\" for details.\n"),
1771 * Make psql's internal variables agree with connection state upon
1772 * establishing a new connection.
1777 /* get stuff from connection */
1778 pset.encoding = PQclientEncoding(pset.db);
1779 pset.popt.topt.encoding = pset.encoding;
1780 pset.sversion = PQserverVersion(pset.db);
1782 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1783 SetVariable(pset.vars, "USER", PQuser(pset.db));
1784 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1785 SetVariable(pset.vars, "PORT", PQport(pset.db));
1786 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1788 /* send stuff to it, too */
1789 PQsetErrorVerbosity(pset.db, pset.verbosity);
1795 * Clear variables that should be not be set when there is no connection.
1798 UnsyncVariables(void)
1800 SetVariable(pset.vars, "DBNAME", NULL);
1801 SetVariable(pset.vars, "USER", NULL);
1802 SetVariable(pset.vars, "HOST", NULL);
1803 SetVariable(pset.vars, "PORT", NULL);
1804 SetVariable(pset.vars, "ENCODING", NULL);
1809 * do_edit -- handler for \e
1811 * If you do not specify a filename, the current query buffer will be copied
1812 * into a temporary one.
1815 editFile(const char *fname, int lineno)
1817 const char *editorName;
1818 const char *editor_lineno_arg = NULL;
1822 Assert(fname != NULL);
1824 /* Find an editor to use */
1825 editorName = getenv("PSQL_EDITOR");
1827 editorName = getenv("EDITOR");
1829 editorName = getenv("VISUAL");
1831 editorName = DEFAULT_EDITOR;
1833 /* Get line number argument, if we need it. */
1836 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
1837 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
1838 if (!editor_lineno_arg)
1839 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
1841 if (!editor_lineno_arg)
1843 psql_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number\n");
1848 /* Allocate sufficient memory for command line. */
1850 sys = pg_malloc(strlen(editorName)
1851 + strlen(editor_lineno_arg) + 10 /* for integer */
1852 + 1 + strlen(fname) + 10 + 1);
1854 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1857 * On Unix the EDITOR value should *not* be quoted, since it might include
1858 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1859 * if necessary. But this policy is not very workable on Windows, due to
1860 * severe brain damage in their command shell plus the fact that standard
1861 * program paths include spaces.
1865 sprintf(sys, "exec %s %s%d '%s'",
1866 editorName, editor_lineno_arg, lineno, fname);
1868 sprintf(sys, "exec %s '%s'",
1872 sprintf(sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE,
1873 editorName, editor_lineno_arg, lineno, fname);
1875 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE,
1878 result = system(sys);
1880 psql_error("could not start editor \"%s\"\n", editorName);
1881 else if (result == 127)
1882 psql_error("could not start /bin/sh\n");
1891 do_edit(const char *filename_arg, PQExpBuffer query_buf,
1892 int lineno, bool *edited)
1894 char fnametmp[MAXPGPATH];
1895 FILE *stream = NULL;
1904 fname = filename_arg;
1907 /* make a temp file to edit */
1909 const char *tmpdir = getenv("TMPDIR");
1914 char tmpdir[MAXPGPATH];
1917 ret = GetTempPath(MAXPGPATH, tmpdir);
1918 if (ret == 0 || ret > MAXPGPATH)
1920 psql_error("could not locate temporary directory: %s\n",
1921 !ret ? strerror(errno) : "");
1926 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1927 * current directory to the supplied path unless we use only
1928 * backslashes, so we do that.
1932 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1933 "/", (int) getpid());
1935 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
1936 "" /* trailing separator already present */ , (int) getpid());
1939 fname = (const char *) fnametmp;
1941 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1943 stream = fdopen(fd, "w");
1945 if (fd == -1 || !stream)
1947 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1952 unsigned int ql = query_buf->len;
1954 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1956 appendPQExpBufferChar(query_buf, '\n');
1960 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1962 psql_error("%s: %s\n", fname, strerror(errno));
1967 else if (fclose(stream) != 0)
1969 psql_error("%s: %s\n", fname, strerror(errno));
1976 if (!error && stat(fname, &before) != 0)
1978 psql_error("%s: %s\n", fname, strerror(errno));
1984 error = !editFile(fname, lineno);
1986 if (!error && stat(fname, &after) != 0)
1988 psql_error("%s: %s\n", fname, strerror(errno));
1992 if (!error && before.st_mtime != after.st_mtime)
1994 stream = fopen(fname, PG_BINARY_R);
1997 psql_error("%s: %s\n", fname, strerror(errno));
2002 /* read file back into query_buf */
2005 resetPQExpBuffer(query_buf);
2006 while (fgets(line, sizeof(line), stream) != NULL)
2007 appendPQExpBufferStr(query_buf, line);
2011 psql_error("%s: %s\n", fname, strerror(errno));
2023 /* remove temp file */
2026 if (remove(fname) == -1)
2028 psql_error("%s: %s\n", fname, strerror(errno));
2041 * Read commands from filename and then them to the main processing loop
2042 * Handler for \i and \ir, but can be used for other things as well. Returns
2043 * MainLoop() error code.
2045 * If use_relative_path is true and filename is not an absolute path, then open
2046 * the file from where the currently processed file (if any) is located.
2049 process_file(char *filename, bool single_txn, bool use_relative_path)
2054 char relpath[MAXPGPATH];
2062 else if (strcmp(filename, "-") != 0)
2064 canonicalize_path(filename);
2067 * If we were asked to resolve the pathname relative to the location
2068 * of the currently executing script, and there is one, and this is a
2069 * relative pathname, then prepend all but the last pathname component
2070 * of the current script to this pathname.
2072 if (use_relative_path && pset.inputfile &&
2073 !is_absolute_path(filename) && !has_drive_prefix(filename))
2075 strlcpy(relpath, pset.inputfile, sizeof(relpath));
2076 get_parent_directory(relpath);
2077 join_path_components(relpath, relpath, filename);
2078 canonicalize_path(relpath);
2083 fd = fopen(filename, PG_BINARY_R);
2087 psql_error("%s: %s\n", filename, strerror(errno));
2088 return EXIT_FAILURE;
2094 filename = "<stdin>"; /* for future error messages */
2097 oldfilename = pset.inputfile;
2098 pset.inputfile = filename;
2102 if ((res = PSQLexec("BEGIN", false)) == NULL)
2104 if (pset.on_error_stop)
2114 result = MainLoop(fd);
2118 if ((res = PSQLexec("COMMIT", false)) == NULL)
2120 if (pset.on_error_stop)
2134 pset.inputfile = oldfilename;
2145 _align2string(enum printFormat in)
2152 case PRINT_UNALIGNED:
2167 case PRINT_TROFF_MS:
2176 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
2180 Assert(param != NULL);
2183 vallen = strlen(value);
2186 if (strcmp(param, "format") == 0)
2190 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2191 popt->topt.format = PRINT_UNALIGNED;
2192 else if (pg_strncasecmp("aligned", value, vallen) == 0)
2193 popt->topt.format = PRINT_ALIGNED;
2194 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2195 popt->topt.format = PRINT_WRAPPED;
2196 else if (pg_strncasecmp("html", value, vallen) == 0)
2197 popt->topt.format = PRINT_HTML;
2198 else if (pg_strncasecmp("latex", value, vallen) == 0)
2199 popt->topt.format = PRINT_LATEX;
2200 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2201 popt->topt.format = PRINT_TROFF_MS;
2204 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
2209 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2212 /* set table line style */
2213 else if (strcmp(param, "linestyle") == 0)
2217 else if (pg_strncasecmp("ascii", value, vallen) == 0)
2218 popt->topt.line_style = &pg_asciiformat;
2219 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2220 popt->topt.line_style = &pg_asciiformat_old;
2221 else if (pg_strncasecmp("unicode", value, vallen) == 0)
2222 popt->topt.line_style = &pg_utf8format;
2225 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2230 printf(_("Line style is %s.\n"),
2231 get_line_style(&popt->topt)->name);
2234 /* set border style/width */
2235 else if (strcmp(param, "border") == 0)
2238 popt->topt.border = atoi(value);
2241 printf(_("Border style is %d.\n"), popt->topt.border);
2244 /* set expanded/vertical mode */
2245 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2247 if (value && pg_strcasecmp(value, "auto") == 0)
2248 popt->topt.expanded = 2;
2250 popt->topt.expanded = ParseVariableBool(value);
2252 popt->topt.expanded = !popt->topt.expanded;
2255 if (popt->topt.expanded == 1)
2256 printf(_("Expanded display is on.\n"));
2257 else if (popt->topt.expanded == 2)
2258 printf(_("Expanded display is used automatically.\n"));
2260 printf(_("Expanded display is off.\n"));
2264 /* locale-aware numeric output */
2265 else if (strcmp(param, "numericlocale") == 0)
2268 popt->topt.numericLocale = ParseVariableBool(value);
2270 popt->topt.numericLocale = !popt->topt.numericLocale;
2273 if (popt->topt.numericLocale)
2274 puts(_("Showing locale-adjusted numeric output."));
2276 puts(_("Locale-adjusted numeric output is off."));
2281 else if (strcmp(param, "null") == 0)
2285 free(popt->nullPrint);
2286 popt->nullPrint = pg_strdup(value);
2289 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
2292 /* field separator for unaligned text */
2293 else if (strcmp(param, "fieldsep") == 0)
2297 free(popt->topt.fieldSep.separator);
2298 popt->topt.fieldSep.separator = pg_strdup(value);
2299 popt->topt.fieldSep.separator_zero = false;
2303 if (popt->topt.fieldSep.separator_zero)
2304 printf(_("Field separator is zero byte.\n"));
2306 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep.separator);
2310 else if (strcmp(param, "fieldsep_zero") == 0)
2312 free(popt->topt.fieldSep.separator);
2313 popt->topt.fieldSep.separator = NULL;
2314 popt->topt.fieldSep.separator_zero = true;
2316 printf(_("Field separator is zero byte.\n"));
2319 /* record separator for unaligned text */
2320 else if (strcmp(param, "recordsep") == 0)
2324 free(popt->topt.recordSep.separator);
2325 popt->topt.recordSep.separator = pg_strdup(value);
2326 popt->topt.recordSep.separator_zero = false;
2330 if (popt->topt.recordSep.separator_zero)
2331 printf(_("Record separator is zero byte.\n"));
2332 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
2333 printf(_("Record separator is <newline>."));
2335 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep.separator);
2339 else if (strcmp(param, "recordsep_zero") == 0)
2341 free(popt->topt.recordSep.separator);
2342 popt->topt.recordSep.separator = NULL;
2343 popt->topt.recordSep.separator_zero = true;
2345 printf(_("Record separator is zero byte.\n"));
2348 /* toggle between full and tuples-only format */
2349 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2352 popt->topt.tuples_only = ParseVariableBool(value);
2354 popt->topt.tuples_only = !popt->topt.tuples_only;
2357 if (popt->topt.tuples_only)
2358 puts(_("Showing only tuples."));
2360 puts(_("Tuples only is off."));
2364 /* set title override */
2365 else if (strcmp(param, "title") == 0)
2371 popt->title = pg_strdup(value);
2376 printf(_("Title is \"%s\".\n"), popt->title);
2378 printf(_("Title is unset.\n"));
2382 /* set HTML table tag options */
2383 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2385 free(popt->topt.tableAttr);
2387 popt->topt.tableAttr = NULL;
2389 popt->topt.tableAttr = pg_strdup(value);
2393 if (popt->topt.tableAttr)
2394 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
2396 printf(_("Table attributes unset.\n"));
2400 /* toggle use of pager */
2401 else if (strcmp(param, "pager") == 0)
2403 if (value && pg_strcasecmp(value, "always") == 0)
2404 popt->topt.pager = 2;
2406 if (ParseVariableBool(value))
2407 popt->topt.pager = 1;
2409 popt->topt.pager = 0;
2410 else if (popt->topt.pager == 1)
2411 popt->topt.pager = 0;
2413 popt->topt.pager = 1;
2416 if (popt->topt.pager == 1)
2417 puts(_("Pager is used for long output."));
2418 else if (popt->topt.pager == 2)
2419 puts(_("Pager is always used."));
2421 puts(_("Pager usage is off."));
2425 /* disable "(x rows)" footer */
2426 else if (strcmp(param, "footer") == 0)
2429 popt->topt.default_footer = ParseVariableBool(value);
2431 popt->topt.default_footer = !popt->topt.default_footer;
2434 if (popt->topt.default_footer)
2435 puts(_("Default footer is on."));
2437 puts(_("Default footer is off."));
2441 /* set border style/width */
2442 else if (strcmp(param, "columns") == 0)
2445 popt->topt.columns = atoi(value);
2448 printf(_("Target width is %d.\n"), popt->topt.columns);
2453 psql_error("\\pset: unknown option: %s\n", param);
2463 #define DEFAULT_SHELL "/bin/sh"
2466 * CMD.EXE is in different places in different Win32 releases so we
2467 * have to rely on the path to find it.
2469 #define DEFAULT_SHELL "cmd.exe"
2473 do_shell(const char *command)
2480 const char *shellName;
2482 shellName = getenv("SHELL");
2484 if (shellName == NULL)
2485 shellName = getenv("COMSPEC");
2487 if (shellName == NULL)
2488 shellName = DEFAULT_SHELL;
2490 sys = pg_malloc(strlen(shellName) + 16);
2493 /* See EDITOR handling comment for an explanation */
2494 "exec %s", shellName);
2496 /* See EDITOR handling comment for an explanation */
2497 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2499 result = system(sys);
2503 result = system(command);
2505 if (result == 127 || result == -1)
2507 psql_error("\\!: failed\n");
2514 * This function takes a function description, e.g. "x" or "x(int)", and
2515 * issues a query on the given connection to retrieve the function's OID
2516 * using a cast to regproc or regprocedure (as appropriate). The result,
2517 * if there is one, is returned at *foid. Note that we'll fail if the
2518 * function doesn't exist OR if there are multiple matching candidates
2519 * OR if there's something syntactically wrong with the function description;
2520 * unfortunately it can be hard to tell the difference.
2523 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2529 query = createPQExpBuffer();
2530 printfPQExpBuffer(query, "SELECT ");
2531 appendStringLiteralConn(query, desc, conn);
2532 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2533 strchr(desc, '(') ? "regprocedure" : "regproc");
2535 res = PQexec(conn, query->data);
2536 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2537 *foid = atooid(PQgetvalue(res, 0, 0));
2540 minimal_error_message(res);
2545 destroyPQExpBuffer(query);
2551 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2552 * function with the given OID. If successful, the result is stored in buf.
2555 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2561 query = createPQExpBuffer();
2562 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2564 res = PQexec(conn, query->data);
2565 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2567 resetPQExpBuffer(buf);
2568 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2572 minimal_error_message(res);
2577 destroyPQExpBuffer(query);
2583 * If the given argument of \ef ends with a line number, delete the line
2584 * number from the argument string and return it as an integer. (We need
2585 * this kluge because we're too lazy to parse \ef's function name argument
2586 * carefully --- we just slop it up in OT_WHOLE_LINE mode.)
2588 * Returns -1 if no line number is present, 0 on error, or a positive value
2592 strip_lineno_from_funcdesc(char *func)
2597 if (!func || func[0] == '\0')
2600 c = func + strlen(func) - 1;
2603 * This business of parsing backwards is dangerous as can be in a
2604 * multibyte environment: there is no reason to believe that we are
2605 * looking at the first byte of a character, nor are we necessarily
2606 * working in a "safe" encoding. Fortunately the bitpatterns we are
2607 * looking for are unlikely to occur as non-first bytes, but beware of
2608 * trying to expand the set of cases that can be recognized. We must
2609 * guard the <ctype.h> macros by using isascii() first, too.
2612 /* skip trailing whitespace */
2613 while (c > func && isascii((unsigned char) *c) && isspace((unsigned char) *c))
2616 /* must have a digit as last non-space char */
2617 if (c == func || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
2620 /* find start of digit string */
2621 while (c > func && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
2624 /* digits must be separated from func name by space or closing paren */
2625 /* notice also that we are not allowing an empty func name ... */
2626 if (c == func || !isascii((unsigned char) *c) ||
2627 !(isspace((unsigned char) *c) || *c == ')'))
2630 /* parse digit string */
2635 psql_error("invalid line number: %s\n", c);
2639 /* strip digit string from func */
2646 * Report just the primary error; this is to avoid cluttering the output
2647 * with, for instance, a redisplay of the internally generated query
2650 minimal_error_message(PGresult *res)
2655 msg = createPQExpBuffer();
2657 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2659 printfPQExpBuffer(msg, "%s: ", fld);
2661 printfPQExpBuffer(msg, "ERROR: ");
2662 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2664 appendPQExpBufferStr(msg, fld);
2666 appendPQExpBufferStr(msg, "(not available)");
2667 appendPQExpBufferStr(msg, "\n");
2669 psql_error("%s", msg->data);
2671 destroyPQExpBuffer(msg);