2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2010, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.228 2010/08/14 14:20:35 tgl Exp $
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_VERBATIM, 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 not connected.\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 /* Default fetch-it-all-and-print mode */
327 char *opt = psql_scan_slash_option(scan_state,
328 OT_WHOLE_LINE, NULL, false);
331 INSTR_TIME_SET_CURRENT(before);
333 success = do_copy(opt);
335 if (pset.timing && success)
337 INSTR_TIME_SET_CURRENT(after);
338 INSTR_TIME_SUBTRACT(after, before);
339 printf(_("Time: %.3f ms\n"), INSTR_TIME_GET_MILLISEC(after));
346 else if (strcmp(cmd, "copyright") == 0)
350 else if (cmd[0] == 'd')
356 /* We don't do SQLID reduction on the pattern yet */
357 pattern = psql_scan_slash_option(scan_state,
358 OT_NORMAL, NULL, true);
360 show_verbose = strchr(cmd, '+') ? true : false;
361 show_system = strchr(cmd, 'S') ? true : false;
369 success = describeTableDetails(pattern, show_verbose, show_system);
371 /* standard listing of interesting things */
372 success = listTables("tvs", NULL, show_verbose, show_system);
375 success = describeAggregates(pattern, show_verbose, show_system);
378 success = describeTablespaces(pattern, show_verbose);
381 success = listConversions(pattern, show_system);
384 success = listCasts(pattern);
387 if (strncmp(cmd, "ddp", 3) == 0)
388 success = listDefaultACLs(pattern);
390 success = objectDescription(pattern, show_system);
393 success = listDomains(pattern, show_system);
395 case 'f': /* function subsystem */
405 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
408 status = PSQL_CMD_UNKNOWN;
413 /* no longer distinct from \du */
414 success = describeRoles(pattern, show_verbose);
417 success = do_lo_list();
420 success = listSchemas(pattern, show_verbose);
423 success = describeOperators(pattern, show_system);
426 success = permissionsList(pattern);
429 success = describeTypes(pattern, show_verbose, show_system);
435 success = listTables(&cmd[1], pattern, show_verbose, show_system);
438 if (cmd[2] == 'd' && cmd[3] == 's')
440 char *pattern2 = NULL;
443 pattern2 = psql_scan_slash_option(scan_state,
444 OT_NORMAL, NULL, true);
445 success = listDbRoleSettings(pattern, pattern2);
448 success = PSQL_CMD_UNKNOWN;
451 success = describeRoles(pattern, show_verbose);
453 case 'F': /* text search subsystem */
458 success = listTSConfigs(pattern, show_verbose);
461 success = listTSParsers(pattern, show_verbose);
464 success = listTSDictionaries(pattern, show_verbose);
467 success = listTSTemplates(pattern, show_verbose);
470 status = PSQL_CMD_UNKNOWN;
474 case 'e': /* SQL/MED subsystem */
478 success = listForeignServers(pattern, show_verbose);
481 success = listUserMappings(pattern, show_verbose);
484 success = listForeignDataWrappers(pattern, show_verbose);
487 status = PSQL_CMD_UNKNOWN;
492 status = PSQL_CMD_UNKNOWN;
501 * \e or \edit -- edit the current query buffer, or edit a file and make
502 * it the query buffer
504 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
508 psql_error("no query buffer\n");
509 status = PSQL_CMD_ERROR;
517 fname = psql_scan_slash_option(scan_state,
518 OT_NORMAL, NULL, true);
521 /* try to get separate lineno arg */
522 ln = psql_scan_slash_option(scan_state,
523 OT_NORMAL, NULL, true);
526 /* only one arg; maybe it is lineno not fname */
528 strspn(fname, "0123456789") == strlen(fname))
530 /* all digits, so assume it is lineno */
541 psql_error("invalid line number: %s\n", ln);
542 status = PSQL_CMD_ERROR;
545 if (status != PSQL_CMD_ERROR)
547 expand_tilde(&fname);
549 canonicalize_path(fname);
550 if (do_edit(fname, query_buf, lineno, NULL))
551 status = PSQL_CMD_NEWEDIT;
553 status = PSQL_CMD_ERROR;
563 * \ef -- edit the named function, or present a blank CREATE FUNCTION
564 * template if no argument is given
566 else if (strcmp(cmd, "ef") == 0)
572 psql_error("no query buffer\n");
573 status = PSQL_CMD_ERROR;
578 Oid foid = InvalidOid;
580 func = psql_scan_slash_option(scan_state,
581 OT_WHOLE_LINE, NULL, true);
582 lineno = strip_lineno_from_funcdesc(func);
585 /* error already reported */
586 status = PSQL_CMD_ERROR;
590 /* set up an empty command to fill in */
591 printfPQExpBuffer(query_buf,
592 "CREATE FUNCTION ( )\n"
595 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
599 else if (!lookup_function_oid(pset.db, func, &foid))
601 /* error already reported */
602 status = PSQL_CMD_ERROR;
604 else if (!get_create_function_cmd(pset.db, foid, query_buf))
606 /* error already reported */
607 status = PSQL_CMD_ERROR;
612 * lineno "1" should correspond to the first line of the
613 * function body. We expect that pg_get_functiondef() will
614 * emit that on a line beginning with "AS ", and that there
615 * can be no such line before the real start of the function
616 * body. Increment lineno by the number of lines before that
617 * line, so that it becomes relative to the first line of the
618 * function definition.
620 const char *lines = query_buf->data;
622 while (*lines != '\0')
624 if (strncmp(lines, "AS ", 3) == 0)
627 /* find start of next line */
628 lines = strchr(lines, '\n');
639 if (status != PSQL_CMD_ERROR)
643 if (!do_edit(NULL, query_buf, lineno, &edited))
644 status = PSQL_CMD_ERROR;
646 puts(_("No changes"));
648 status = PSQL_CMD_NEWEDIT;
652 /* \echo and \qecho */
653 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
657 bool no_newline = false;
661 if (strcmp(cmd, "qecho") == 0)
662 fout = pset.queryFout;
666 while ((value = psql_scan_slash_option(scan_state,
667 OT_NORMAL, "ed, false)))
669 if (!quoted && strcmp(value, "-n") == 0)
685 /* \encoding -- set/show client side encoding */
686 else if (strcmp(cmd, "encoding") == 0)
688 char *encoding = psql_scan_slash_option(scan_state,
689 OT_NORMAL, NULL, false);
694 puts(pg_encoding_to_char(pset.encoding));
699 if (PQsetClientEncoding(pset.db, encoding) == -1)
700 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
703 /* save encoding info into psql internal data */
704 pset.encoding = PQclientEncoding(pset.db);
705 pset.popt.topt.encoding = pset.encoding;
706 SetVariable(pset.vars, "ENCODING",
707 pg_encoding_to_char(pset.encoding));
713 /* \f -- change field separator */
714 else if (strcmp(cmd, "f") == 0)
716 char *fname = psql_scan_slash_option(scan_state,
717 OT_NORMAL, NULL, false);
719 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
723 /* \g means send query */
724 else if (strcmp(cmd, "g") == 0)
726 char *fname = psql_scan_slash_option(scan_state,
727 OT_FILEPIPE, NULL, false);
733 expand_tilde(&fname);
734 pset.gfname = pg_strdup(fname);
737 status = PSQL_CMD_SEND;
741 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
743 char *opt = psql_scan_slash_option(scan_state,
744 OT_WHOLE_LINE, NULL, false);
747 /* strip any trailing spaces and semicolons */
752 (isspace((unsigned char) opt[len - 1])
753 || opt[len - 1] == ';'))
757 helpSQL(opt, pset.popt.topt.pager);
762 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
764 if (pset.popt.topt.format != PRINT_HTML)
765 success = do_pset("format", "html", &pset.popt, pset.quiet);
767 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
771 /* \i is include file */
772 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
774 char *fname = psql_scan_slash_option(scan_state,
775 OT_NORMAL, NULL, true);
779 psql_error("\\%s: missing required argument\n", cmd);
784 expand_tilde(&fname);
785 success = (process_file(fname, false) == EXIT_SUCCESS);
790 /* \l is list databases */
791 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
792 success = listAllDbs(false);
793 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
794 success = listAllDbs(true);
797 * large object things
799 else if (strncmp(cmd, "lo_", 3) == 0)
804 opt1 = psql_scan_slash_option(scan_state,
805 OT_NORMAL, NULL, true);
806 opt2 = psql_scan_slash_option(scan_state,
807 OT_NORMAL, NULL, true);
809 if (strcmp(cmd + 3, "export") == 0)
813 psql_error("\\%s: missing required argument\n", cmd);
819 success = do_lo_export(opt1, opt2);
823 else if (strcmp(cmd + 3, "import") == 0)
827 psql_error("\\%s: missing required argument\n", cmd);
833 success = do_lo_import(opt1, opt2);
837 else if (strcmp(cmd + 3, "list") == 0)
838 success = do_lo_list();
840 else if (strcmp(cmd + 3, "unlink") == 0)
844 psql_error("\\%s: missing required argument\n", cmd);
848 success = do_lo_unlink(opt1);
852 status = PSQL_CMD_UNKNOWN;
859 /* \o -- set query output */
860 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
862 char *fname = psql_scan_slash_option(scan_state,
863 OT_FILEPIPE, NULL, true);
865 expand_tilde(&fname);
866 success = setQFout(fname);
870 /* \p prints the current query buffer */
871 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
873 if (query_buf && query_buf->len > 0)
874 puts(query_buf->data);
875 else if (!pset.quiet)
876 puts(_("Query buffer is empty."));
880 /* \password -- set user password */
881 else if (strcmp(cmd, "password") == 0)
886 pw1 = simple_prompt("Enter new password: ", 100, false);
887 pw2 = simple_prompt("Enter it again: ", 100, false);
889 if (strcmp(pw1, pw2) != 0)
891 fprintf(stderr, _("Passwords didn't match.\n"));
896 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
898 char *encrypted_password;
903 user = PQuser(pset.db);
905 encrypted_password = PQencryptPassword(pw1, user);
907 if (!encrypted_password)
909 fprintf(stderr, _("Password encryption failed.\n"));
917 initPQExpBuffer(&buf);
918 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
920 appendStringLiteralConn(&buf, encrypted_password, pset.db);
921 res = PSQLexec(buf.data, false);
922 termPQExpBuffer(&buf);
927 PQfreemem(encrypted_password);
935 /* \prompt -- prompt and set variable */
936 else if (strcmp(cmd, "prompt") == 0)
943 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
944 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
948 psql_error("\\%s: missing required argument\n", cmd);
964 result = simple_prompt(prompt_text, 4096, true);
969 fputs(prompt_text, stdout);
972 result = gets_fromFile(stdin);
975 if (!SetVariable(pset.vars, opt, result))
977 psql_error("\\%s: error\n", cmd);
988 /* \pset -- set printing parameters */
989 else if (strcmp(cmd, "pset") == 0)
991 char *opt0 = psql_scan_slash_option(scan_state,
992 OT_NORMAL, NULL, false);
993 char *opt1 = psql_scan_slash_option(scan_state,
994 OT_NORMAL, NULL, false);
998 psql_error("\\%s: missing required argument\n", cmd);
1002 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1009 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1010 status = PSQL_CMD_TERMINATE;
1012 /* reset(clear) the buffer */
1013 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1015 resetPQExpBuffer(query_buf);
1016 psql_scan_reset(scan_state);
1018 puts(_("Query buffer reset (cleared)."));
1021 /* \s save history in a file or show it on the screen */
1022 else if (strcmp(cmd, "s") == 0)
1024 char *fname = psql_scan_slash_option(scan_state,
1025 OT_NORMAL, NULL, true);
1027 expand_tilde(&fname);
1028 /* This scrolls off the screen when using /dev/tty */
1029 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
1030 if (success && !pset.quiet && fname)
1031 printf(gettext("Wrote history to file \"%s/%s\".\n"),
1032 pset.dirname ? pset.dirname : ".", fname);
1038 /* \set -- generalized set variable/option command */
1039 else if (strcmp(cmd, "set") == 0)
1041 char *opt0 = psql_scan_slash_option(scan_state,
1042 OT_NORMAL, NULL, false);
1046 /* list all variables */
1047 PrintVariables(pset.vars);
1053 * Set variable to the concatenation of the arguments.
1058 opt = psql_scan_slash_option(scan_state,
1059 OT_NORMAL, NULL, false);
1060 newval = pg_strdup(opt ? opt : "");
1063 while ((opt = psql_scan_slash_option(scan_state,
1064 OT_NORMAL, NULL, false)))
1066 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
1069 psql_error("out of memory\n");
1072 strcat(newval, opt);
1076 if (!SetVariable(pset.vars, opt0, newval))
1078 psql_error("\\%s: error\n", cmd);
1086 /* \sf -- show a function's source code */
1087 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1089 bool show_linenumbers = (strcmp(cmd, "sf+") == 0);
1090 PQExpBuffer func_buf;
1092 Oid foid = InvalidOid;
1094 func_buf = createPQExpBuffer();
1095 func = psql_scan_slash_option(scan_state,
1096 OT_WHOLE_LINE, NULL, true);
1099 psql_error("function name is required\n");
1100 status = PSQL_CMD_ERROR;
1102 else if (!lookup_function_oid(pset.db, func, &foid))
1104 /* error already reported */
1105 status = PSQL_CMD_ERROR;
1107 else if (!get_create_function_cmd(pset.db, foid, func_buf))
1109 /* error already reported */
1110 status = PSQL_CMD_ERROR;
1117 /* Select output stream: stdout, pager, or file */
1118 if (pset.queryFout == stdout)
1120 /* count lines in function to see if pager is needed */
1122 const char *lines = func_buf->data;
1124 while (*lines != '\0')
1127 /* find start of next line */
1128 lines = strchr(lines, '\n');
1134 output = PageOutput(lineno, pset.popt.topt.pager);
1139 /* use previously set output file, without pager */
1140 output = pset.queryFout;
1144 if (show_linenumbers)
1146 bool in_header = true;
1148 char *lines = func_buf->data;
1151 * lineno "1" should correspond to the first line of the
1152 * function body. We expect that pg_get_functiondef() will
1153 * emit that on a line beginning with "AS ", and that there
1154 * can be no such line before the real start of the function
1157 * Note that this loop scribbles on func_buf.
1159 while (*lines != '\0')
1163 if (in_header && strncmp(lines, "AS ", 3) == 0)
1165 /* increment lineno only for body's lines */
1169 /* find and mark end of current line */
1170 eol = strchr(lines, '\n');
1174 /* show current line as appropriate */
1176 fprintf(output, " %s\n", lines);
1178 fprintf(output, "%-7d %s\n", lineno, lines);
1180 /* advance to next line, if any */
1188 /* just send the function definition to output */
1189 fputs(func_buf->data, output);
1198 destroyPQExpBuffer(func_buf);
1201 /* \t -- turn off headers and row count */
1202 else if (strcmp(cmd, "t") == 0)
1204 char *opt = psql_scan_slash_option(scan_state,
1205 OT_NORMAL, NULL, true);
1207 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1211 /* \T -- define html <table ...> attributes */
1212 else if (strcmp(cmd, "T") == 0)
1214 char *value = psql_scan_slash_option(scan_state,
1215 OT_NORMAL, NULL, false);
1217 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1221 /* \timing -- toggle timing of queries */
1222 else if (strcmp(cmd, "timing") == 0)
1224 char *opt = psql_scan_slash_option(scan_state,
1225 OT_NORMAL, NULL, false);
1228 pset.timing = ParseVariableBool(opt);
1230 pset.timing = !pset.timing;
1234 puts(_("Timing is on."));
1236 puts(_("Timing is off."));
1242 else if (strcmp(cmd, "unset") == 0)
1244 char *opt = psql_scan_slash_option(scan_state,
1245 OT_NORMAL, NULL, false);
1249 psql_error("\\%s: missing required argument\n", cmd);
1252 else if (!SetVariable(pset.vars, opt, NULL))
1254 psql_error("\\%s: error\n", cmd);
1260 /* \w -- write query buffer to file */
1261 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1264 bool is_pipe = false;
1269 psql_error("no query buffer\n");
1270 status = PSQL_CMD_ERROR;
1274 fname = psql_scan_slash_option(scan_state,
1275 OT_FILEPIPE, NULL, true);
1276 expand_tilde(&fname);
1280 psql_error("\\%s: missing required argument\n", cmd);
1285 if (fname[0] == '|')
1288 fd = popen(&fname[1], "w");
1292 canonicalize_path(fname);
1293 fd = fopen(fname, "w");
1297 psql_error("%s: %s\n", fname, strerror(errno));
1307 if (query_buf && query_buf->len > 0)
1308 fprintf(fd, "%s\n", query_buf->data);
1311 result = pclose(fd);
1313 result = fclose(fd);
1317 psql_error("%s: %s\n", fname, strerror(errno));
1325 /* \x -- toggle expanded table representation */
1326 else if (strcmp(cmd, "x") == 0)
1328 char *opt = psql_scan_slash_option(scan_state,
1329 OT_NORMAL, NULL, true);
1331 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1335 /* \z -- list table rights (equivalent to \dp) */
1336 else if (strcmp(cmd, "z") == 0)
1338 char *pattern = psql_scan_slash_option(scan_state,
1339 OT_NORMAL, NULL, true);
1341 success = permissionsList(pattern);
1346 /* \! -- shell escape */
1347 else if (strcmp(cmd, "!") == 0)
1349 char *opt = psql_scan_slash_option(scan_state,
1350 OT_WHOLE_LINE, NULL, false);
1352 success = do_shell(opt);
1356 /* \? -- slash command help */
1357 else if (strcmp(cmd, "?") == 0)
1358 slashUsage(pset.popt.topt.pager);
1363 * These commands don't do anything. I just use them to test the parser.
1365 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1370 while ((value = psql_scan_slash_option(scan_state,
1371 OT_NORMAL, NULL, true)))
1373 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1380 status = PSQL_CMD_UNKNOWN;
1383 status = PSQL_CMD_ERROR;
1389 * Ask the user for a password; 'username' is the username the
1390 * password is for, if one has been explicitly specified. Returns a
1394 prompt_for_password(const char *username)
1398 if (username == NULL)
1399 result = simple_prompt("Password: ", 100, false);
1404 prompt_text = malloc(strlen(username) + 100);
1405 snprintf(prompt_text, strlen(username) + 100,
1406 _("Password for user %s: "), username);
1407 result = simple_prompt(prompt_text, 100, false);
1415 param_is_newly_set(const char *old_val, const char *new_val)
1417 if (new_val == NULL)
1420 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1427 * do_connect -- handler for \connect
1429 * Connects to a database with given parameters. If there exists an
1430 * established connection, NULL values will be replaced with the ones
1431 * in the current connection. Otherwise NULL will be passed for that
1432 * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1434 * In interactive mode, if connection fails with the given parameters,
1435 * the old connection will be kept.
1438 do_connect(char *dbname, char *user, char *host, char *port)
1440 PGconn *o_conn = pset.db,
1442 char *password = NULL;
1445 dbname = PQdb(o_conn);
1447 user = PQuser(o_conn);
1449 host = PQhost(o_conn);
1451 port = PQport(o_conn);
1454 * If the user asked to be prompted for a password, ask for one now. If
1455 * not, use the password from the old connection, provided the username
1456 * has not changed. Otherwise, try to connect without a password first,
1457 * and then ask for a password if needed.
1459 * XXX: this behavior leads to spurious connection attempts recorded in
1460 * the postmaster's log. But libpq offers no API that would let us obtain
1461 * a password and then continue with the first connection attempt.
1463 if (pset.getPassword == TRI_YES)
1465 password = prompt_for_password(user);
1467 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1469 password = strdup(PQpass(o_conn));
1474 #define PARAMS_ARRAY_SIZE 7
1475 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1476 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1478 keywords[0] = "host";
1480 keywords[1] = "port";
1482 keywords[2] = "user";
1484 keywords[3] = "password";
1485 values[3] = password;
1486 keywords[4] = "dbname";
1488 keywords[5] = "fallback_application_name";
1489 values[5] = pset.progname;
1493 n_conn = PQconnectdbParams(keywords, values, true);
1498 /* We can immediately discard the password -- no longer needed */
1502 if (PQstatus(n_conn) == CONNECTION_OK)
1506 * Connection attempt failed; either retry the connection attempt with
1507 * a new password, or give up.
1509 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1512 password = prompt_for_password(user);
1517 * Failed to connect to the database. In interactive mode, keep the
1518 * previous connection to the DB; in scripting mode, close our
1519 * previous connection as well.
1521 if (pset.cur_cmd_interactive)
1523 psql_error("%s", PQerrorMessage(n_conn));
1525 /* pset.db is left unmodified */
1527 fputs(_("Previous connection kept\n"), stderr);
1531 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1544 * Replace the old connection with the new one, and update
1545 * connection-dependent variables.
1547 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1550 connection_warnings(false); /* Must be after SyncVariables */
1552 /* Tell the user about the new connection */
1555 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
1556 param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1558 char *host = PQhost(pset.db);
1561 host = DEFAULT_PGSOCKET_DIR;
1562 /* If the host is an absolute path, the connection is via socket */
1563 if (is_absolute_path(host))
1564 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
1565 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1567 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
1568 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
1571 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
1572 PQdb(pset.db), PQuser(pset.db));
1582 connection_warnings(bool in_startup)
1584 if (!pset.quiet && !pset.notty)
1586 int client_ver = parse_version(PG_VERSION);
1588 if (pset.sversion != client_ver)
1590 const char *server_version;
1591 char server_ver_str[16];
1593 /* Try to get full text form, might include "devel" etc */
1594 server_version = PQparameterStatus(pset.db, "server_version");
1595 if (!server_version)
1597 snprintf(server_ver_str, sizeof(server_ver_str),
1599 pset.sversion / 10000,
1600 (pset.sversion / 100) % 100,
1601 pset.sversion % 100);
1602 server_version = server_ver_str;
1605 printf(_("%s (%s, server %s)\n"),
1606 pset.progname, PG_VERSION, server_version);
1608 /* For version match, only print psql banner on startup. */
1609 else if (in_startup)
1610 printf("%s (%s)\n", pset.progname, PG_VERSION);
1612 if (pset.sversion / 100 != client_ver / 100)
1613 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1614 " Some psql features might not work.\n"),
1615 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1616 pset.sversion / 10000, (pset.sversion / 100) % 100);
1619 checkWin32Codepage();
1629 * Prints information about the current SSL connection, if SSL is in use
1638 ssl = PQgetssl(pset.db);
1640 return; /* no SSL */
1642 SSL_get_cipher_bits(ssl, &sslbits);
1643 printf(_("SSL connection (cipher: %s, bits: %i)\n"),
1644 SSL_get_cipher(ssl), sslbits);
1648 * If psql is compiled without SSL but is using a libpq with SSL, we
1649 * cannot figure out the specifics about the connection. But we know it's
1652 if (PQgetssl(pset.db))
1653 printf(_("SSL connection (unknown cipher)\n"));
1659 * checkWin32Codepage
1661 * Prints a warning when win32 console codepage differs from Windows codepage
1665 checkWin32Codepage(void)
1671 concp = GetConsoleCP();
1674 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1675 " 8-bit characters might not work correctly. See psql reference\n"
1676 " page \"Notes for Windows users\" for details.\n"),
1686 * Make psql's internal variables agree with connection state upon
1687 * establishing a new connection.
1692 /* get stuff from connection */
1693 pset.encoding = PQclientEncoding(pset.db);
1694 pset.popt.topt.encoding = pset.encoding;
1695 pset.sversion = PQserverVersion(pset.db);
1697 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1698 SetVariable(pset.vars, "USER", PQuser(pset.db));
1699 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1700 SetVariable(pset.vars, "PORT", PQport(pset.db));
1701 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1703 /* send stuff to it, too */
1704 PQsetErrorVerbosity(pset.db, pset.verbosity);
1710 * Clear variables that should be not be set when there is no connection.
1713 UnsyncVariables(void)
1715 SetVariable(pset.vars, "DBNAME", NULL);
1716 SetVariable(pset.vars, "USER", NULL);
1717 SetVariable(pset.vars, "HOST", NULL);
1718 SetVariable(pset.vars, "PORT", NULL);
1719 SetVariable(pset.vars, "ENCODING", NULL);
1724 * do_edit -- handler for \e
1726 * If you do not specify a filename, the current query buffer will be copied
1727 * into a temporary one.
1730 editFile(const char *fname, int lineno)
1732 const char *editorName;
1733 const char *editor_lineno_switch = NULL;
1739 /* Find an editor to use */
1740 editorName = getenv("PSQL_EDITOR");
1742 editorName = getenv("EDITOR");
1744 editorName = getenv("VISUAL");
1746 editorName = DEFAULT_EDITOR;
1748 /* Get line number switch, if we need it. */
1751 editor_lineno_switch = GetVariable(pset.vars,
1752 "EDITOR_LINENUMBER_SWITCH");
1753 if (editor_lineno_switch == NULL)
1755 psql_error("EDITOR_LINENUMBER_SWITCH variable must be set to specify a line number\n");
1760 /* Allocate sufficient memory for command line. */
1762 sys = pg_malloc(strlen(editorName)
1763 + strlen(editor_lineno_switch) + 10 /* for integer */
1764 + 1 + strlen(fname) + 10 + 1);
1766 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1769 * On Unix the EDITOR value should *not* be quoted, since it might include
1770 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1771 * if necessary. But this policy is not very workable on Windows, due to
1772 * severe brain damage in their command shell plus the fact that standard
1773 * program paths include spaces.
1777 sprintf(sys, "exec %s %s%d '%s'",
1778 editorName, editor_lineno_switch, lineno, fname);
1780 sprintf(sys, "exec %s '%s'",
1784 sprintf(sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE,
1785 editorName, editor_lineno_switch, lineno, fname);
1787 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE,
1790 result = system(sys);
1792 psql_error("could not start editor \"%s\"\n", editorName);
1793 else if (result == 127)
1794 psql_error("could not start /bin/sh\n");
1803 do_edit(const char *filename_arg, PQExpBuffer query_buf,
1804 int lineno, bool *edited)
1806 char fnametmp[MAXPGPATH];
1807 FILE *stream = NULL;
1816 fname = filename_arg;
1819 /* make a temp file to edit */
1821 const char *tmpdir = getenv("TMPDIR");
1826 char tmpdir[MAXPGPATH];
1829 ret = GetTempPath(MAXPGPATH, tmpdir);
1830 if (ret == 0 || ret > MAXPGPATH)
1832 psql_error("cannot locate temporary directory: %s",
1833 !ret ? strerror(errno) : "");
1838 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1839 * current directory to the supplied path unless we use only
1840 * backslashes, so we do that.
1844 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1845 "/", (int) getpid());
1847 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1848 "" /* trailing separator already present */ , (int) getpid());
1851 fname = (const char *) fnametmp;
1853 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1855 stream = fdopen(fd, "w");
1857 if (fd == -1 || !stream)
1859 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1864 unsigned int ql = query_buf->len;
1866 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1868 appendPQExpBufferChar(query_buf, '\n');
1872 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1874 psql_error("%s: %s\n", fname, strerror(errno));
1879 else if (fclose(stream) != 0)
1881 psql_error("%s: %s\n", fname, strerror(errno));
1888 if (!error && stat(fname, &before) != 0)
1890 psql_error("%s: %s\n", fname, strerror(errno));
1896 error = !editFile(fname, lineno);
1898 if (!error && stat(fname, &after) != 0)
1900 psql_error("%s: %s\n", fname, strerror(errno));
1904 if (!error && before.st_mtime != after.st_mtime)
1906 stream = fopen(fname, PG_BINARY_R);
1909 psql_error("%s: %s\n", fname, strerror(errno));
1914 /* read file back into query_buf */
1917 resetPQExpBuffer(query_buf);
1918 while (fgets(line, sizeof(line), stream) != NULL)
1919 appendPQExpBufferStr(query_buf, line);
1923 psql_error("%s: %s\n", fname, strerror(errno));
1935 /* remove temp file */
1938 if (remove(fname) == -1)
1940 psql_error("%s: %s\n", fname, strerror(errno));
1953 * Read commands from filename and then them to the main processing loop
1954 * Handler for \i, but can be used for other things as well. Returns
1955 * MainLoop() error code.
1958 process_file(char *filename, bool single_txn)
1966 return EXIT_FAILURE;
1968 if (strcmp(filename, "-") != 0)
1970 canonicalize_path(filename);
1971 fd = fopen(filename, PG_BINARY_R);
1978 psql_error("%s: %s\n", filename, strerror(errno));
1979 return EXIT_FAILURE;
1982 oldfilename = pset.inputfile;
1983 pset.inputfile = filename;
1987 if ((res = PSQLexec("BEGIN", false)) == NULL)
1989 if (pset.on_error_stop)
1996 result = MainLoop(fd);
2000 if ((res = PSQLexec("COMMIT", false)) == NULL)
2002 if (pset.on_error_stop)
2010 pset.inputfile = oldfilename;
2021 _align2string(enum printFormat in)
2028 case PRINT_UNALIGNED:
2043 case PRINT_TROFF_MS:
2052 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
2059 vallen = strlen(value);
2062 if (strcmp(param, "format") == 0)
2066 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2067 popt->topt.format = PRINT_UNALIGNED;
2068 else if (pg_strncasecmp("aligned", value, vallen) == 0)
2069 popt->topt.format = PRINT_ALIGNED;
2070 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2071 popt->topt.format = PRINT_WRAPPED;
2072 else if (pg_strncasecmp("html", value, vallen) == 0)
2073 popt->topt.format = PRINT_HTML;
2074 else if (pg_strncasecmp("latex", value, vallen) == 0)
2075 popt->topt.format = PRINT_LATEX;
2076 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2077 popt->topt.format = PRINT_TROFF_MS;
2080 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
2085 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2088 /* set table line style */
2089 else if (strcmp(param, "linestyle") == 0)
2093 else if (pg_strncasecmp("ascii", value, vallen) == 0)
2094 popt->topt.line_style = &pg_asciiformat;
2095 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2096 popt->topt.line_style = &pg_asciiformat_old;
2097 else if (pg_strncasecmp("unicode", value, vallen) == 0)
2098 popt->topt.line_style = &pg_utf8format;
2101 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2106 printf(_("Line style is %s.\n"),
2107 get_line_style(&popt->topt)->name);
2110 /* set border style/width */
2111 else if (strcmp(param, "border") == 0)
2114 popt->topt.border = atoi(value);
2117 printf(_("Border style is %d.\n"), popt->topt.border);
2120 /* set expanded/vertical mode */
2121 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2124 popt->topt.expanded = ParseVariableBool(value);
2126 popt->topt.expanded = !popt->topt.expanded;
2128 printf(popt->topt.expanded
2129 ? _("Expanded display is on.\n")
2130 : _("Expanded display is off.\n"));
2133 /* locale-aware numeric output */
2134 else if (strcmp(param, "numericlocale") == 0)
2137 popt->topt.numericLocale = ParseVariableBool(value);
2139 popt->topt.numericLocale = !popt->topt.numericLocale;
2142 if (popt->topt.numericLocale)
2143 puts(_("Showing locale-adjusted numeric output."));
2145 puts(_("Locale-adjusted numeric output is off."));
2150 else if (strcmp(param, "null") == 0)
2154 free(popt->nullPrint);
2155 popt->nullPrint = pg_strdup(value);
2158 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
2161 /* field separator for unaligned text */
2162 else if (strcmp(param, "fieldsep") == 0)
2166 free(popt->topt.fieldSep);
2167 popt->topt.fieldSep = pg_strdup(value);
2170 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
2173 /* record separator for unaligned text */
2174 else if (strcmp(param, "recordsep") == 0)
2178 free(popt->topt.recordSep);
2179 popt->topt.recordSep = pg_strdup(value);
2183 if (strcmp(popt->topt.recordSep, "\n") == 0)
2184 printf(_("Record separator is <newline>."));
2186 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
2190 /* toggle between full and tuples-only format */
2191 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2194 popt->topt.tuples_only = ParseVariableBool(value);
2196 popt->topt.tuples_only = !popt->topt.tuples_only;
2199 if (popt->topt.tuples_only)
2200 puts(_("Showing only tuples."));
2202 puts(_("Tuples only is off."));
2206 /* set title override */
2207 else if (strcmp(param, "title") == 0)
2213 popt->title = pg_strdup(value);
2218 printf(_("Title is \"%s\".\n"), popt->title);
2220 printf(_("Title is unset.\n"));
2224 /* set HTML table tag options */
2225 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2227 free(popt->topt.tableAttr);
2229 popt->topt.tableAttr = NULL;
2231 popt->topt.tableAttr = pg_strdup(value);
2235 if (popt->topt.tableAttr)
2236 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
2238 printf(_("Table attributes unset.\n"));
2242 /* toggle use of pager */
2243 else if (strcmp(param, "pager") == 0)
2245 if (value && pg_strcasecmp(value, "always") == 0)
2246 popt->topt.pager = 2;
2248 if (ParseVariableBool(value))
2249 popt->topt.pager = 1;
2251 popt->topt.pager = 0;
2252 else if (popt->topt.pager == 1)
2253 popt->topt.pager = 0;
2255 popt->topt.pager = 1;
2258 if (popt->topt.pager == 1)
2259 puts(_("Pager is used for long output."));
2260 else if (popt->topt.pager == 2)
2261 puts(_("Pager is always used."));
2263 puts(_("Pager usage is off."));
2267 /* disable "(x rows)" footer */
2268 else if (strcmp(param, "footer") == 0)
2271 popt->default_footer = ParseVariableBool(value);
2273 popt->default_footer = !popt->default_footer;
2276 if (popt->default_footer)
2277 puts(_("Default footer is on."));
2279 puts(_("Default footer is off."));
2283 /* set border style/width */
2284 else if (strcmp(param, "columns") == 0)
2287 popt->topt.columns = atoi(value);
2290 printf(_("Target width for \"wrapped\" format is %d.\n"), popt->topt.columns);
2295 psql_error("\\pset: unknown option: %s\n", param);
2305 #define DEFAULT_SHELL "/bin/sh"
2308 * CMD.EXE is in different places in different Win32 releases so we
2309 * have to rely on the path to find it.
2311 #define DEFAULT_SHELL "cmd.exe"
2315 do_shell(const char *command)
2322 const char *shellName;
2324 shellName = getenv("SHELL");
2326 if (shellName == NULL)
2327 shellName = getenv("COMSPEC");
2329 if (shellName == NULL)
2330 shellName = DEFAULT_SHELL;
2332 sys = pg_malloc(strlen(shellName) + 16);
2335 /* See EDITOR handling comment for an explaination */
2336 "exec %s", shellName);
2338 /* See EDITOR handling comment for an explaination */
2339 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2341 result = system(sys);
2345 result = system(command);
2347 if (result == 127 || result == -1)
2349 psql_error("\\!: failed\n");
2356 * This function takes a function description, e.g. "x" or "x(int)", and
2357 * issues a query on the given connection to retrieve the function's OID
2358 * using a cast to regproc or regprocedure (as appropriate). The result,
2359 * if there is one, is returned at *foid. Note that we'll fail if the
2360 * function doesn't exist OR if there are multiple matching candidates
2361 * OR if there's something syntactically wrong with the function description;
2362 * unfortunately it can be hard to tell the difference.
2365 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2371 query = createPQExpBuffer();
2372 printfPQExpBuffer(query, "SELECT ");
2373 appendStringLiteralConn(query, desc, conn);
2374 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2375 strchr(desc, '(') ? "regprocedure" : "regproc");
2377 res = PQexec(conn, query->data);
2378 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2379 *foid = atooid(PQgetvalue(res, 0, 0));
2382 minimal_error_message(res);
2387 destroyPQExpBuffer(query);
2393 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2394 * function with the given OID. If successful, the result is stored in buf.
2397 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2403 query = createPQExpBuffer();
2404 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2406 res = PQexec(conn, query->data);
2407 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2409 resetPQExpBuffer(buf);
2410 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2414 minimal_error_message(res);
2419 destroyPQExpBuffer(query);
2425 * If the given argument of \ef ends with a line number, delete the line
2426 * number from the argument string and return it as an integer. (We need
2427 * this kluge because we're too lazy to parse \ef's function name argument
2428 * carefully --- we just slop it up in OT_WHOLE_LINE mode.)
2430 * Returns -1 if no line number is present, 0 on error, or a positive value
2434 strip_lineno_from_funcdesc(char *func)
2439 if (!func || func[0] == '\0')
2442 c = func + strlen(func) - 1;
2445 * This business of parsing backwards is dangerous as can be in a
2446 * multibyte environment: there is no reason to believe that we are
2447 * looking at the first byte of a character, nor are we necessarily
2448 * working in a "safe" encoding. Fortunately the bitpatterns we are
2449 * looking for are unlikely to occur as non-first bytes, but beware
2450 * of trying to expand the set of cases that can be recognized. We must
2451 * guard the <ctype.h> macros by using isascii() first, too.
2454 /* skip trailing whitespace */
2455 while (c > func && isascii(*c) && isspace(*c))
2458 /* must have a digit as last non-space char */
2459 if (c == func || !isascii(*c) || !isdigit(*c))
2462 /* find start of digit string */
2463 while (c > func && isascii(*c) && isdigit(*c))
2466 /* digits must be separated from func name by space or closing paren */
2467 /* notice also that we are not allowing an empty func name ... */
2468 if (c == func || !isascii(*c) || !(isspace(*c) || *c == ')'))
2471 /* parse digit string */
2476 psql_error("invalid line number: %s\n", c);
2480 /* strip digit string from func */
2487 * Report just the primary error; this is to avoid cluttering the output
2488 * with, for instance, a redisplay of the internally generated query
2491 minimal_error_message(PGresult *res)
2496 msg = createPQExpBuffer();
2498 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2500 printfPQExpBuffer(msg, "%s: ", fld);
2502 printfPQExpBuffer(msg, "ERROR: ");
2503 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2505 appendPQExpBufferStr(msg, fld);
2507 appendPQExpBufferStr(msg, "(not available)");
2508 appendPQExpBufferStr(msg, "\n");
2510 psql_error("%s", msg->data);
2512 destroyPQExpBuffer(msg);