2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2017, PostgreSQL Global Development Group
6 * src/bin/psql/command.c
8 #include "postgres_fe.h"
11 #ifdef __BORLANDC__ /* needed for BCC */
19 #include <sys/stat.h> /* for stat() */
20 #include <fcntl.h> /* open() flags */
21 #include <unistd.h> /* for geteuid(), getpid(), stat() */
27 #include <sys/stat.h> /* for stat() */
30 #include "catalog/pg_class.h"
31 #include "portability/instr_time.h"
34 #include "pqexpbuffer.h"
35 #include "fe_utils/string_utils.h"
39 #include "crosstabview.h"
43 #include "large_obj.h"
45 #include "fe_utils/print.h"
46 #include "psqlscanslash.h"
48 #include "variables.h"
51 * Editable database object types.
53 typedef enum EditableObjectType
59 /* functions for use in this file */
60 static backslashResult exec_command(const char *cmd,
61 PsqlScanState scan_state,
62 PQExpBuffer query_buf);
63 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
64 int lineno, bool *edited);
65 static bool do_connect(enum trivalue reuse_previous_specification,
66 char *dbname, char *user, char *host, char *port);
67 static bool do_shell(const char *command);
68 static bool do_watch(PQExpBuffer query_buf, double sleep);
69 static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
71 static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
73 static int strip_lineno_from_objdesc(char *obj);
74 static int count_lines_in_buf(PQExpBuffer buf);
75 static void print_with_linenumbers(FILE *output, char *lines,
76 const char *header_keyword);
77 static void minimal_error_message(PGresult *res);
79 static void printSSLInfo(void);
80 static bool printPsetInfo(const char *param, struct printQueryOpt *popt);
81 static char *pset_value_string(const char *param, struct printQueryOpt *popt);
84 static void checkWin32Codepage(void);
92 * Handles all the different commands that start with '\'.
93 * Ordinarily called by MainLoop().
95 * scan_state is a lexer working state that is set to continue scanning
96 * just after the '\'. The lexer is advanced past the command and all
97 * arguments on return.
99 * 'query_buf' contains the query-so-far, which may be modified by
100 * execution of the backslash command (for example, \r clears it).
101 * query_buf can be NULL if there is no query so far.
103 * Returns a status code indicating what action is desired, see command.h.
108 HandleSlashCmds(PsqlScanState scan_state,
109 PQExpBuffer query_buf)
111 backslashResult status = PSQL_CMD_SKIP_LINE;
115 Assert(scan_state != NULL);
117 /* Parse off the command name */
118 cmd = psql_scan_slash_command(scan_state);
120 /* And try to execute it */
121 status = exec_command(cmd, scan_state, query_buf);
123 if (status == PSQL_CMD_UNKNOWN)
125 if (pset.cur_cmd_interactive)
126 psql_error("Invalid command \\%s. Try \\? for help.\n", cmd);
128 psql_error("invalid command \\%s\n", cmd);
129 status = PSQL_CMD_ERROR;
132 if (status != PSQL_CMD_ERROR)
134 /* eat any remaining arguments after a valid command */
135 /* note we suppress evaluation of backticks here */
136 while ((arg = psql_scan_slash_option(scan_state,
137 OT_NO_EVAL, NULL, false)))
139 psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
145 /* silently throw away rest of line after an erroneous command */
146 while ((arg = psql_scan_slash_option(scan_state,
147 OT_WHOLE_LINE, NULL, false)))
151 /* if there is a trailing \\, swallow it */
152 psql_scan_slash_command_end(scan_state);
156 /* some commands write to queryFout, so make sure output is sent */
157 fflush(pset.queryFout);
163 * Read and interpret an argument to the \connect slash command.
166 read_connect_arg(PsqlScanState scan_state)
172 * Ideally we should treat the arguments as SQL identifiers. But for
173 * backwards compatibility with 7.2 and older pg_dump files, we have to
174 * take unquoted arguments verbatim (don't downcase them). For now,
175 * double-quoted arguments may be stripped of double quotes (as if SQL
176 * identifiers). By 7.4 or so, pg_dump files can be expected to
177 * double-quote all mixed-case \connect arguments, and then we can get rid
180 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
188 if (*result == '\0' || strcmp(result, "-") == 0)
196 * Subroutine to actually try to execute a backslash command.
198 static backslashResult
199 exec_command(const char *cmd,
200 PsqlScanState scan_state,
201 PQExpBuffer query_buf)
203 bool success = true; /* indicate here if the command ran ok or
205 backslashResult status = PSQL_CMD_SKIP_LINE;
208 * \a -- toggle field alignment This makes little sense but we keep it
211 if (strcmp(cmd, "a") == 0)
213 if (pset.popt.topt.format != PRINT_ALIGNED)
214 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
216 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
219 /* \C -- override table title (formerly change HTML caption) */
220 else if (strcmp(cmd, "C") == 0)
222 char *opt = psql_scan_slash_option(scan_state,
223 OT_NORMAL, NULL, true);
225 success = do_pset("title", opt, &pset.popt, pset.quiet);
230 * \c or \connect -- connect to database using the specified parameters.
232 * \c [-reuse-previous=BOOL] dbname user host port
234 * Specifying a parameter as '-' is equivalent to omitting it. Examples:
236 * \c - - hst Connect to current database on current port of host
237 * "hst" as current user. \c - usr - prt Connect to current database on
238 * "prt" port of current host as user "usr". \c dbs Connect to
239 * "dbs" database on current port of current host as current user.
241 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
243 static const char prefix[] = "-reuse-previous=";
248 enum trivalue reuse_previous = TRI_DEFAULT;
250 opt1 = read_connect_arg(scan_state);
251 if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
255 success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
260 reuse_previous = on_off ? TRI_YES : TRI_NO;
262 opt1 = read_connect_arg(scan_state);
266 if (success) /* give up if reuse_previous was invalid */
268 opt2 = read_connect_arg(scan_state);
269 opt3 = read_connect_arg(scan_state);
270 opt4 = read_connect_arg(scan_state);
272 success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
282 else if (strcmp(cmd, "cd") == 0)
284 char *opt = psql_scan_slash_option(scan_state,
285 OT_NORMAL, NULL, true);
294 uid_t user_id = geteuid();
296 errno = 0; /* clear errno before call */
297 pw = getpwuid(user_id);
300 psql_error("could not get home directory for user ID %ld: %s\n",
302 errno ? strerror(errno) : _("user does not exist"));
309 * On Windows, 'cd' without arguments prints the current
310 * directory, so if someone wants to code this here instead...
316 if (chdir(dir) == -1)
318 psql_error("\\%s: could not change directory to \"%s\": %s\n",
319 cmd, dir, strerror(errno));
327 /* \conninfo -- display information about the current connection */
328 else if (strcmp(cmd, "conninfo") == 0)
330 char *db = PQdb(pset.db);
333 printf(_("You are currently not connected to a database.\n"));
337 PQconninfoOption *connOptions;
338 PQconninfoOption *option;
340 host = PQhost(pset.db);
341 /* A usable "hostaddr" overrides the basic sense of host. */
342 connOptions = PQconninfo(pset.db);
343 if (connOptions == NULL)
345 psql_error("out of memory\n");
348 for (option = connOptions; option && option->keyword; option++)
349 if (strcmp(option->keyword, "hostaddr") == 0)
351 if (option->val != NULL && option->val[0] != '\0')
356 /* If the host is an absolute path, the connection is via socket */
357 if (is_absolute_path(host))
358 printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
359 db, PQuser(pset.db), host, PQport(pset.db));
361 printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
362 db, PQuser(pset.db), host, PQport(pset.db));
365 PQconninfoFree(connOptions);
370 else if (pg_strcasecmp(cmd, "copy") == 0)
372 char *opt = psql_scan_slash_option(scan_state,
373 OT_WHOLE_LINE, NULL, false);
375 success = do_copy(opt);
380 else if (strcmp(cmd, "copyright") == 0)
383 /* \crosstabview -- execute a query and display results in crosstab */
384 else if (strcmp(cmd, "crosstabview") == 0)
388 for (i = 0; i < lengthof(pset.ctv_args); i++)
389 pset.ctv_args[i] = psql_scan_slash_option(scan_state,
390 OT_NORMAL, NULL, true);
391 pset.crosstab_flag = true;
392 status = PSQL_CMD_SEND;
396 else if (cmd[0] == 'd')
402 /* We don't do SQLID reduction on the pattern yet */
403 pattern = psql_scan_slash_option(scan_state,
404 OT_NORMAL, NULL, true);
406 show_verbose = strchr(cmd, '+') ? true : false;
407 show_system = strchr(cmd, 'S') ? true : false;
415 success = describeTableDetails(pattern, show_verbose, show_system);
417 /* standard listing of interesting things */
418 success = listTables("tvmsE", NULL, show_verbose, show_system);
421 success = describeAccessMethods(pattern, show_verbose);
424 success = describeAggregates(pattern, show_verbose, show_system);
427 success = describeTablespaces(pattern, show_verbose);
430 success = listConversions(pattern, show_verbose, show_system);
433 success = listCasts(pattern, show_verbose);
436 if (strncmp(cmd, "ddp", 3) == 0)
437 success = listDefaultACLs(pattern);
439 success = objectDescription(pattern, show_system);
442 success = listDomains(pattern, show_verbose, show_system);
444 case 'f': /* function subsystem */
454 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
457 status = PSQL_CMD_UNKNOWN;
462 /* no longer distinct from \du */
463 success = describeRoles(pattern, show_verbose, show_system);
466 success = do_lo_list();
469 success = listLanguages(pattern, show_verbose, show_system);
472 success = listSchemas(pattern, show_verbose, show_system);
475 success = describeOperators(pattern, show_verbose, show_system);
478 success = listCollations(pattern, show_verbose, show_system);
481 success = permissionsList(pattern);
484 success = describeTypes(pattern, show_verbose, show_system);
492 success = listTables(&cmd[1], pattern, show_verbose, show_system);
495 if (cmd[2] == 'd' && cmd[3] == 's')
497 char *pattern2 = NULL;
500 pattern2 = psql_scan_slash_option(scan_state,
501 OT_NORMAL, NULL, true);
502 success = listDbRoleSettings(pattern, pattern2);
505 success = PSQL_CMD_UNKNOWN;
512 success = describePublications(pattern);
514 success = listPublications(pattern);
517 success = describeSubscriptions(pattern, show_verbose);
520 status = PSQL_CMD_UNKNOWN;
524 success = describeRoles(pattern, show_verbose, show_system);
526 case 'F': /* text search subsystem */
531 success = listTSConfigs(pattern, show_verbose);
534 success = listTSParsers(pattern, show_verbose);
537 success = listTSDictionaries(pattern, show_verbose);
540 success = listTSTemplates(pattern, show_verbose);
543 status = PSQL_CMD_UNKNOWN;
547 case 'e': /* SQL/MED subsystem */
551 success = listForeignServers(pattern, show_verbose);
554 success = listUserMappings(pattern, show_verbose);
557 success = listForeignDataWrappers(pattern, show_verbose);
560 success = listForeignTables(pattern, show_verbose);
563 status = PSQL_CMD_UNKNOWN;
567 case 'x': /* Extensions */
569 success = listExtensionContents(pattern);
571 success = listExtensions(pattern);
573 case 'y': /* Event Triggers */
574 success = listEventTriggers(pattern, show_verbose);
577 status = PSQL_CMD_UNKNOWN;
586 * \e or \edit -- edit the current query buffer, or edit a file and make
587 * it the query buffer
589 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
593 psql_error("no query buffer\n");
594 status = PSQL_CMD_ERROR;
602 fname = psql_scan_slash_option(scan_state,
603 OT_NORMAL, NULL, true);
606 /* try to get separate lineno arg */
607 ln = psql_scan_slash_option(scan_state,
608 OT_NORMAL, NULL, true);
611 /* only one arg; maybe it is lineno not fname */
613 strspn(fname, "0123456789") == strlen(fname))
615 /* all digits, so assume it is lineno */
626 psql_error("invalid line number: %s\n", ln);
627 status = PSQL_CMD_ERROR;
630 if (status != PSQL_CMD_ERROR)
632 expand_tilde(&fname);
634 canonicalize_path(fname);
635 if (do_edit(fname, query_buf, lineno, NULL))
636 status = PSQL_CMD_NEWEDIT;
638 status = PSQL_CMD_ERROR;
648 * \ef -- edit the named function, or present a blank CREATE FUNCTION
649 * template if no argument is given
651 else if (strcmp(cmd, "ef") == 0)
655 if (pset.sversion < 80400)
659 psql_error("The server (version %s) does not support editing function source.\n",
660 formatPGVersionNumber(pset.sversion, false,
661 sverbuf, sizeof(sverbuf)));
662 status = PSQL_CMD_ERROR;
666 psql_error("no query buffer\n");
667 status = PSQL_CMD_ERROR;
672 Oid foid = InvalidOid;
674 func = psql_scan_slash_option(scan_state,
675 OT_WHOLE_LINE, NULL, true);
676 lineno = strip_lineno_from_objdesc(func);
679 /* error already reported */
680 status = PSQL_CMD_ERROR;
684 /* set up an empty command to fill in */
685 printfPQExpBuffer(query_buf,
686 "CREATE FUNCTION ( )\n"
689 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
693 else if (!lookup_object_oid(EditableFunction, func, &foid))
695 /* error already reported */
696 status = PSQL_CMD_ERROR;
698 else if (!get_create_object_cmd(EditableFunction, foid, query_buf))
700 /* error already reported */
701 status = PSQL_CMD_ERROR;
706 * lineno "1" should correspond to the first line of the
707 * function body. We expect that pg_get_functiondef() will
708 * emit that on a line beginning with "AS ", and that there
709 * can be no such line before the real start of the function
710 * body. Increment lineno by the number of lines before that
711 * line, so that it becomes relative to the first line of the
712 * function definition.
714 const char *lines = query_buf->data;
716 while (*lines != '\0')
718 if (strncmp(lines, "AS ", 3) == 0)
721 /* find start of next line */
722 lines = strchr(lines, '\n');
733 if (status != PSQL_CMD_ERROR)
737 if (!do_edit(NULL, query_buf, lineno, &edited))
738 status = PSQL_CMD_ERROR;
740 puts(_("No changes"));
742 status = PSQL_CMD_NEWEDIT;
747 * \ev -- edit the named view, or present a blank CREATE VIEW template if
748 * no argument is given
750 else if (strcmp(cmd, "ev") == 0)
754 if (pset.sversion < 70400)
758 psql_error("The server (version %s) does not support editing view definitions.\n",
759 formatPGVersionNumber(pset.sversion, false,
760 sverbuf, sizeof(sverbuf)));
761 status = PSQL_CMD_ERROR;
765 psql_error("no query buffer\n");
766 status = PSQL_CMD_ERROR;
771 Oid view_oid = InvalidOid;
773 view = psql_scan_slash_option(scan_state,
774 OT_WHOLE_LINE, NULL, true);
775 lineno = strip_lineno_from_objdesc(view);
778 /* error already reported */
779 status = PSQL_CMD_ERROR;
783 /* set up an empty command to fill in */
784 printfPQExpBuffer(query_buf,
787 " -- something...\n");
789 else if (!lookup_object_oid(EditableView, view, &view_oid))
791 /* error already reported */
792 status = PSQL_CMD_ERROR;
794 else if (!get_create_object_cmd(EditableView, view_oid, query_buf))
796 /* error already reported */
797 status = PSQL_CMD_ERROR;
804 if (status != PSQL_CMD_ERROR)
808 if (!do_edit(NULL, query_buf, lineno, &edited))
809 status = PSQL_CMD_ERROR;
811 puts(_("No changes"));
813 status = PSQL_CMD_NEWEDIT;
817 /* \echo and \qecho */
818 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
822 bool no_newline = false;
826 if (strcmp(cmd, "qecho") == 0)
827 fout = pset.queryFout;
831 while ((value = psql_scan_slash_option(scan_state,
832 OT_NORMAL, "ed, false)))
834 if (!quoted && strcmp(value, "-n") == 0)
850 /* \encoding -- set/show client side encoding */
851 else if (strcmp(cmd, "encoding") == 0)
853 char *encoding = psql_scan_slash_option(scan_state,
854 OT_NORMAL, NULL, false);
859 puts(pg_encoding_to_char(pset.encoding));
864 if (PQsetClientEncoding(pset.db, encoding) == -1)
865 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
868 /* save encoding info into psql internal data */
869 pset.encoding = PQclientEncoding(pset.db);
870 pset.popt.topt.encoding = pset.encoding;
871 SetVariable(pset.vars, "ENCODING",
872 pg_encoding_to_char(pset.encoding));
878 /* \errverbose -- display verbose message from last failed query */
879 else if (strcmp(cmd, "errverbose") == 0)
881 if (pset.last_error_result)
885 msg = PQresultVerboseErrorMessage(pset.last_error_result,
887 PQSHOW_CONTEXT_ALWAYS);
890 psql_error("%s", msg);
894 puts(_("out of memory"));
897 puts(_("There is no previous error."));
900 /* \f -- change field separator */
901 else if (strcmp(cmd, "f") == 0)
903 char *fname = psql_scan_slash_option(scan_state,
904 OT_NORMAL, NULL, false);
906 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
911 * \g [filename] -- send query, optionally with output to file/pipe
912 * \gx [filename] -- same as \g, with expanded mode forced
914 else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
916 char *fname = psql_scan_slash_option(scan_state,
917 OT_FILEPIPE, NULL, false);
923 expand_tilde(&fname);
924 pset.gfname = pg_strdup(fname);
927 if (strcmp(cmd, "gx") == 0)
928 pset.g_expanded = true;
929 status = PSQL_CMD_SEND;
932 /* \gexec -- send query and execute each field of result */
933 else if (strcmp(cmd, "gexec") == 0)
935 pset.gexec_flag = true;
936 status = PSQL_CMD_SEND;
939 /* \gset [prefix] -- send query and store result into variables */
940 else if (strcmp(cmd, "gset") == 0)
942 char *prefix = psql_scan_slash_option(scan_state,
943 OT_NORMAL, NULL, false);
946 pset.gset_prefix = prefix;
949 /* we must set a non-NULL prefix to trigger storing */
950 pset.gset_prefix = pg_strdup("");
952 /* gset_prefix is freed later */
953 status = PSQL_CMD_SEND;
957 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
959 char *opt = psql_scan_slash_option(scan_state,
960 OT_WHOLE_LINE, NULL, false);
963 /* strip any trailing spaces and semicolons */
968 (isspace((unsigned char) opt[len - 1])
969 || opt[len - 1] == ';'))
973 helpSQL(opt, pset.popt.topt.pager);
978 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
980 if (pset.popt.topt.format != PRINT_HTML)
981 success = do_pset("format", "html", &pset.popt, pset.quiet);
983 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
987 /* \i and \ir include files */
988 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0
989 || strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
991 char *fname = psql_scan_slash_option(scan_state,
992 OT_NORMAL, NULL, true);
996 psql_error("\\%s: missing required argument\n", cmd);
1001 bool include_relative;
1003 include_relative = (strcmp(cmd, "ir") == 0
1004 || strcmp(cmd, "include_relative") == 0);
1005 expand_tilde(&fname);
1006 success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1011 /* \l is list databases */
1012 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
1013 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
1018 pattern = psql_scan_slash_option(scan_state,
1019 OT_NORMAL, NULL, true);
1021 show_verbose = strchr(cmd, '+') ? true : false;
1023 success = listAllDbs(pattern, show_verbose);
1030 * large object things
1032 else if (strncmp(cmd, "lo_", 3) == 0)
1037 opt1 = psql_scan_slash_option(scan_state,
1038 OT_NORMAL, NULL, true);
1039 opt2 = psql_scan_slash_option(scan_state,
1040 OT_NORMAL, NULL, true);
1042 if (strcmp(cmd + 3, "export") == 0)
1046 psql_error("\\%s: missing required argument\n", cmd);
1051 expand_tilde(&opt2);
1052 success = do_lo_export(opt1, opt2);
1056 else if (strcmp(cmd + 3, "import") == 0)
1060 psql_error("\\%s: missing required argument\n", cmd);
1065 expand_tilde(&opt1);
1066 success = do_lo_import(opt1, opt2);
1070 else if (strcmp(cmd + 3, "list") == 0)
1071 success = do_lo_list();
1073 else if (strcmp(cmd + 3, "unlink") == 0)
1077 psql_error("\\%s: missing required argument\n", cmd);
1081 success = do_lo_unlink(opt1);
1085 status = PSQL_CMD_UNKNOWN;
1092 /* \o -- set query output */
1093 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
1095 char *fname = psql_scan_slash_option(scan_state,
1096 OT_FILEPIPE, NULL, true);
1098 expand_tilde(&fname);
1099 success = setQFout(fname);
1103 /* \p prints the current query buffer */
1104 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
1106 if (query_buf && query_buf->len > 0)
1107 puts(query_buf->data);
1108 else if (!pset.quiet)
1109 puts(_("Query buffer is empty."));
1113 /* \password -- set user password */
1114 else if (strcmp(cmd, "password") == 0)
1119 simple_prompt("Enter new password: ", pw1, sizeof(pw1), false);
1120 simple_prompt("Enter it again: ", pw2, sizeof(pw2), false);
1122 if (strcmp(pw1, pw2) != 0)
1124 psql_error("Passwords didn't match.\n");
1129 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
1131 char *encrypted_password;
1136 user = PQuser(pset.db);
1138 encrypted_password = PQencryptPassword(pw1, user);
1140 if (!encrypted_password)
1142 psql_error("Password encryption failed.\n");
1147 PQExpBufferData buf;
1150 initPQExpBuffer(&buf);
1151 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
1153 appendStringLiteralConn(&buf, encrypted_password, pset.db);
1154 res = PSQLexec(buf.data);
1155 termPQExpBuffer(&buf);
1160 PQfreemem(encrypted_password);
1168 /* \prompt -- prompt and set variable */
1169 else if (strcmp(cmd, "prompt") == 0)
1172 *prompt_text = NULL;
1176 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1177 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1181 psql_error("\\%s: missing required argument\n", cmd);
1196 if (!pset.inputfile)
1198 result = (char *) pg_malloc(4096);
1199 simple_prompt(prompt_text, result, 4096, true);
1205 fputs(prompt_text, stdout);
1208 result = gets_fromFile(stdin);
1211 psql_error("\\%s: could not read value for variable\n",
1218 !SetVariable(pset.vars, opt, result))
1229 /* \pset -- set printing parameters */
1230 else if (strcmp(cmd, "pset") == 0)
1232 char *opt0 = psql_scan_slash_option(scan_state,
1233 OT_NORMAL, NULL, false);
1234 char *opt1 = psql_scan_slash_option(scan_state,
1235 OT_NORMAL, NULL, false);
1239 /* list all variables */
1242 static const char *const my_list[] = {
1243 "border", "columns", "expanded", "fieldsep", "fieldsep_zero",
1244 "footer", "format", "linestyle", "null",
1245 "numericlocale", "pager", "pager_min_lines",
1246 "recordsep", "recordsep_zero",
1247 "tableattr", "title", "tuples_only",
1248 "unicode_border_linestyle",
1249 "unicode_column_linestyle",
1250 "unicode_header_linestyle",
1254 for (i = 0; my_list[i] != NULL; i++)
1256 char *val = pset_value_string(my_list[i], &pset.popt);
1258 printf("%-24s %s\n", my_list[i], val);
1265 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1272 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1273 status = PSQL_CMD_TERMINATE;
1275 /* reset(clear) the buffer */
1276 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1278 resetPQExpBuffer(query_buf);
1279 psql_scan_reset(scan_state);
1281 puts(_("Query buffer reset (cleared)."));
1284 /* \s save history in a file or show it on the screen */
1285 else if (strcmp(cmd, "s") == 0)
1287 char *fname = psql_scan_slash_option(scan_state,
1288 OT_NORMAL, NULL, true);
1290 expand_tilde(&fname);
1291 success = printHistory(fname, pset.popt.topt.pager);
1292 if (success && !pset.quiet && fname)
1293 printf(_("Wrote history to file \"%s\".\n"), fname);
1299 /* \set -- generalized set variable/option command */
1300 else if (strcmp(cmd, "set") == 0)
1302 char *opt0 = psql_scan_slash_option(scan_state,
1303 OT_NORMAL, NULL, false);
1307 /* list all variables */
1308 PrintVariables(pset.vars);
1314 * Set variable to the concatenation of the arguments.
1319 opt = psql_scan_slash_option(scan_state,
1320 OT_NORMAL, NULL, false);
1321 newval = pg_strdup(opt ? opt : "");
1324 while ((opt = psql_scan_slash_option(scan_state,
1325 OT_NORMAL, NULL, false)))
1327 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
1328 strcat(newval, opt);
1332 if (!SetVariable(pset.vars, opt0, newval))
1341 /* \setenv -- set environment command */
1342 else if (strcmp(cmd, "setenv") == 0)
1344 char *envvar = psql_scan_slash_option(scan_state,
1345 OT_NORMAL, NULL, false);
1346 char *envval = psql_scan_slash_option(scan_state,
1347 OT_NORMAL, NULL, false);
1351 psql_error("\\%s: missing required argument\n", cmd);
1354 else if (strchr(envvar, '=') != NULL)
1356 psql_error("\\%s: environment variable name must not contain \"=\"\n",
1362 /* No argument - unset the environment variable */
1368 /* Set variable to the value of the next argument */
1371 newval = psprintf("%s=%s", envvar, envval);
1376 * Do not free newval here, it will screw up the environment if
1377 * you do. See putenv man page for details. That means we leak a
1378 * bit of memory here, but not enough to worry about.
1385 /* \sf -- show a function's source code */
1386 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1388 bool show_linenumbers = (strcmp(cmd, "sf+") == 0);
1389 PQExpBuffer func_buf;
1391 Oid foid = InvalidOid;
1393 func_buf = createPQExpBuffer();
1394 func = psql_scan_slash_option(scan_state,
1395 OT_WHOLE_LINE, NULL, true);
1396 if (pset.sversion < 80400)
1400 psql_error("The server (version %s) does not support showing function source.\n",
1401 formatPGVersionNumber(pset.sversion, false,
1402 sverbuf, sizeof(sverbuf)));
1403 status = PSQL_CMD_ERROR;
1407 psql_error("function name is required\n");
1408 status = PSQL_CMD_ERROR;
1410 else if (!lookup_object_oid(EditableFunction, func, &foid))
1412 /* error already reported */
1413 status = PSQL_CMD_ERROR;
1415 else if (!get_create_object_cmd(EditableFunction, foid, func_buf))
1417 /* error already reported */
1418 status = PSQL_CMD_ERROR;
1425 /* Select output stream: stdout, pager, or file */
1426 if (pset.queryFout == stdout)
1428 /* count lines in function to see if pager is needed */
1429 int lineno = count_lines_in_buf(func_buf);
1431 output = PageOutput(lineno, &(pset.popt.topt));
1436 /* use previously set output file, without pager */
1437 output = pset.queryFout;
1441 if (show_linenumbers)
1444 * lineno "1" should correspond to the first line of the
1445 * function body. We expect that pg_get_functiondef() will
1446 * emit that on a line beginning with "AS ", and that there
1447 * can be no such line before the real start of the function
1450 print_with_linenumbers(output, func_buf->data, "AS ");
1454 /* just send the function definition to output */
1455 fputs(func_buf->data, output);
1464 destroyPQExpBuffer(func_buf);
1467 /* \sv -- show a view's source code */
1468 else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
1470 bool show_linenumbers = (strcmp(cmd, "sv+") == 0);
1471 PQExpBuffer view_buf;
1473 Oid view_oid = InvalidOid;
1475 view_buf = createPQExpBuffer();
1476 view = psql_scan_slash_option(scan_state,
1477 OT_WHOLE_LINE, NULL, true);
1478 if (pset.sversion < 70400)
1482 psql_error("The server (version %s) does not support showing view definitions.\n",
1483 formatPGVersionNumber(pset.sversion, false,
1484 sverbuf, sizeof(sverbuf)));
1485 status = PSQL_CMD_ERROR;
1489 psql_error("view name is required\n");
1490 status = PSQL_CMD_ERROR;
1492 else if (!lookup_object_oid(EditableView, view, &view_oid))
1494 /* error already reported */
1495 status = PSQL_CMD_ERROR;
1497 else if (!get_create_object_cmd(EditableView, view_oid, view_buf))
1499 /* error already reported */
1500 status = PSQL_CMD_ERROR;
1507 /* Select output stream: stdout, pager, or file */
1508 if (pset.queryFout == stdout)
1510 /* count lines in view to see if pager is needed */
1511 int lineno = count_lines_in_buf(view_buf);
1513 output = PageOutput(lineno, &(pset.popt.topt));
1518 /* use previously set output file, without pager */
1519 output = pset.queryFout;
1523 if (show_linenumbers)
1525 /* add line numbers, numbering all lines */
1526 print_with_linenumbers(output, view_buf->data, NULL);
1530 /* just send the view definition to output */
1531 fputs(view_buf->data, output);
1540 destroyPQExpBuffer(view_buf);
1543 /* \t -- turn off headers and row count */
1544 else if (strcmp(cmd, "t") == 0)
1546 char *opt = psql_scan_slash_option(scan_state,
1547 OT_NORMAL, NULL, true);
1549 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1553 /* \T -- define html <table ...> attributes */
1554 else if (strcmp(cmd, "T") == 0)
1556 char *value = psql_scan_slash_option(scan_state,
1557 OT_NORMAL, NULL, false);
1559 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1563 /* \timing -- toggle timing of queries */
1564 else if (strcmp(cmd, "timing") == 0)
1566 char *opt = psql_scan_slash_option(scan_state,
1567 OT_NORMAL, NULL, false);
1570 success = ParseVariableBool(opt, "\\timing", &pset.timing);
1572 pset.timing = !pset.timing;
1576 puts(_("Timing is on."));
1578 puts(_("Timing is off."));
1584 else if (strcmp(cmd, "unset") == 0)
1586 char *opt = psql_scan_slash_option(scan_state,
1587 OT_NORMAL, NULL, false);
1591 psql_error("\\%s: missing required argument\n", cmd);
1594 else if (!SetVariable(pset.vars, opt, NULL))
1600 /* \w -- write query buffer to file */
1601 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1604 bool is_pipe = false;
1609 psql_error("no query buffer\n");
1610 status = PSQL_CMD_ERROR;
1614 fname = psql_scan_slash_option(scan_state,
1615 OT_FILEPIPE, NULL, true);
1616 expand_tilde(&fname);
1620 psql_error("\\%s: missing required argument\n", cmd);
1625 if (fname[0] == '|')
1628 disable_sigpipe_trap();
1629 fd = popen(&fname[1], "w");
1633 canonicalize_path(fname);
1634 fd = fopen(fname, "w");
1638 psql_error("%s: %s\n", fname, strerror(errno));
1648 if (query_buf && query_buf->len > 0)
1649 fprintf(fd, "%s\n", query_buf->data);
1652 result = pclose(fd);
1654 result = fclose(fd);
1658 psql_error("%s: %s\n", fname, strerror(errno));
1664 restore_sigpipe_trap();
1669 /* \watch -- execute a query every N seconds */
1670 else if (strcmp(cmd, "watch") == 0)
1672 char *opt = psql_scan_slash_option(scan_state,
1673 OT_NORMAL, NULL, true);
1676 /* Convert optional sleep-length argument */
1679 sleep = strtod(opt, NULL);
1685 success = do_watch(query_buf, sleep);
1687 /* Reset the query buffer as though for \r */
1688 resetPQExpBuffer(query_buf);
1689 psql_scan_reset(scan_state);
1692 /* \x -- set or toggle expanded table representation */
1693 else if (strcmp(cmd, "x") == 0)
1695 char *opt = psql_scan_slash_option(scan_state,
1696 OT_NORMAL, NULL, true);
1698 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1702 /* \z -- list table rights (equivalent to \dp) */
1703 else if (strcmp(cmd, "z") == 0)
1705 char *pattern = psql_scan_slash_option(scan_state,
1706 OT_NORMAL, NULL, true);
1708 success = permissionsList(pattern);
1713 /* \! -- shell escape */
1714 else if (strcmp(cmd, "!") == 0)
1716 char *opt = psql_scan_slash_option(scan_state,
1717 OT_WHOLE_LINE, NULL, false);
1719 success = do_shell(opt);
1723 /* \? -- slash command help */
1724 else if (strcmp(cmd, "?") == 0)
1726 char *opt0 = psql_scan_slash_option(scan_state,
1727 OT_NORMAL, NULL, false);
1729 if (!opt0 || strcmp(opt0, "commands") == 0)
1730 slashUsage(pset.popt.topt.pager);
1731 else if (strcmp(opt0, "options") == 0)
1732 usage(pset.popt.topt.pager);
1733 else if (strcmp(opt0, "variables") == 0)
1734 helpVariables(pset.popt.topt.pager);
1736 slashUsage(pset.popt.topt.pager);
1742 * These commands don't do anything. I just use them to test the parser.
1744 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1749 while ((value = psql_scan_slash_option(scan_state,
1750 OT_NORMAL, NULL, true)))
1752 psql_error("+ opt(%d) = |%s|\n", i++, value);
1759 status = PSQL_CMD_UNKNOWN;
1762 status = PSQL_CMD_ERROR;
1768 * Ask the user for a password; 'username' is the username the
1769 * password is for, if one has been explicitly specified. Returns a
1773 prompt_for_password(const char *username)
1777 if (username == NULL)
1778 simple_prompt("Password: ", buf, sizeof(buf), false);
1783 prompt_text = psprintf(_("Password for user %s: "), username);
1784 simple_prompt(prompt_text, buf, sizeof(buf), false);
1787 return pg_strdup(buf);
1791 param_is_newly_set(const char *old_val, const char *new_val)
1793 if (new_val == NULL)
1796 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1803 * do_connect -- handler for \connect
1805 * Connects to a database with given parameters. Absent an established
1806 * connection, all parameters are required. Given -reuse-previous=off or a
1807 * connection string without -reuse-previous=on, NULL values will pass through
1808 * to PQconnectdbParams(), so the libpq defaults will be used. Otherwise, NULL
1809 * values will be replaced with the ones in the current connection.
1811 * In interactive mode, if connection fails with the given parameters,
1812 * the old connection will be kept.
1815 do_connect(enum trivalue reuse_previous_specification,
1816 char *dbname, char *user, char *host, char *port)
1818 PGconn *o_conn = pset.db,
1820 char *password = NULL;
1822 bool has_connection_string;
1823 bool reuse_previous;
1824 PQExpBufferData connstr;
1826 if (!o_conn && (!dbname || !user || !host || !port))
1829 * We don't know the supplied connection parameters and don't want to
1830 * connect to the wrong database by using defaults, so require all
1831 * parameters to be specified.
1833 psql_error("All connection parameters must be supplied because no "
1834 "database connection exists\n");
1838 has_connection_string = dbname ?
1839 recognized_connection_string(dbname) : false;
1840 switch (reuse_previous_specification)
1843 reuse_previous = true;
1846 reuse_previous = false;
1849 reuse_previous = !has_connection_string;
1852 /* Silently ignore arguments subsequent to a connection string. */
1853 if (has_connection_string)
1860 /* grab missing values from the old connection */
1861 if (!user && reuse_previous)
1862 user = PQuser(o_conn);
1863 if (!host && reuse_previous)
1864 host = PQhost(o_conn);
1865 if (!port && reuse_previous)
1866 port = PQport(o_conn);
1869 * Any change in the parameters read above makes us discard the password.
1870 * We also discard it if we're to use a conninfo rather than the
1871 * positional syntax.
1873 if (has_connection_string)
1874 keep_password = false;
1877 (user && PQuser(o_conn) && strcmp(user, PQuser(o_conn)) == 0) &&
1878 (host && PQhost(o_conn) && strcmp(host, PQhost(o_conn)) == 0) &&
1879 (port && PQport(o_conn) && strcmp(port, PQport(o_conn)) == 0);
1882 * Grab missing dbname from old connection. No password discard if this
1883 * changes: passwords aren't (usually) database-specific.
1885 if (!dbname && reuse_previous)
1887 initPQExpBuffer(&connstr);
1888 appendPQExpBuffer(&connstr, "dbname=");
1889 appendConnStrVal(&connstr, PQdb(o_conn));
1890 dbname = connstr.data;
1891 /* has_connection_string=true would be a dead store */
1894 connstr.data = NULL;
1897 * If the user asked to be prompted for a password, ask for one now. If
1898 * not, use the password from the old connection, provided the username
1899 * etc have not changed. Otherwise, try to connect without a password
1900 * first, and then ask for a password if needed.
1902 * XXX: this behavior leads to spurious connection attempts recorded in
1903 * the postmaster's log. But libpq offers no API that would let us obtain
1904 * a password and then continue with the first connection attempt.
1906 if (pset.getPassword == TRI_YES)
1908 password = prompt_for_password(user);
1910 else if (o_conn && keep_password)
1912 password = PQpass(o_conn);
1913 if (password && *password)
1914 password = pg_strdup(password);
1921 #define PARAMS_ARRAY_SIZE 8
1922 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1923 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1926 keywords[++paramnum] = "host";
1927 values[paramnum] = host;
1928 keywords[++paramnum] = "port";
1929 values[paramnum] = port;
1930 keywords[++paramnum] = "user";
1931 values[paramnum] = user;
1934 * Position in the array matters when the dbname is a connection
1935 * string, because settings in a connection string override earlier
1936 * array entries only. Thus, user= in the connection string always
1937 * takes effect, but client_encoding= often will not.
1939 * If you change this code, also change the initial-connection code in
1940 * main(). For no good reason, a connection string password= takes
1941 * precedence in main() but not here.
1943 keywords[++paramnum] = "dbname";
1944 values[paramnum] = dbname;
1945 keywords[++paramnum] = "password";
1946 values[paramnum] = password;
1947 keywords[++paramnum] = "fallback_application_name";
1948 values[paramnum] = pset.progname;
1949 keywords[++paramnum] = "client_encoding";
1950 values[paramnum] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
1952 /* add array terminator */
1953 keywords[++paramnum] = NULL;
1954 values[paramnum] = NULL;
1956 n_conn = PQconnectdbParams(keywords, values, true);
1961 /* We can immediately discard the password -- no longer needed */
1965 if (PQstatus(n_conn) == CONNECTION_OK)
1969 * Connection attempt failed; either retry the connection attempt with
1970 * a new password, or give up.
1972 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1975 password = prompt_for_password(user);
1980 * Failed to connect to the database. In interactive mode, keep the
1981 * previous connection to the DB; in scripting mode, close our
1982 * previous connection as well.
1984 if (pset.cur_cmd_interactive)
1986 psql_error("%s", PQerrorMessage(n_conn));
1988 /* pset.db is left unmodified */
1990 psql_error("Previous connection kept\n");
1994 psql_error("\\connect: %s", PQerrorMessage(n_conn));
2004 termPQExpBuffer(&connstr);
2008 termPQExpBuffer(&connstr);
2011 * Replace the old connection with the new one, and update
2012 * connection-dependent variables.
2014 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
2017 connection_warnings(false); /* Must be after SyncVariables */
2019 /* Tell the user about the new connection */
2023 param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
2024 param_is_newly_set(PQport(o_conn), PQport(pset.db)))
2026 char *host = PQhost(pset.db);
2028 /* If the host is an absolute path, the connection is via socket */
2029 if (is_absolute_path(host))
2030 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
2031 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
2033 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
2034 PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
2037 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
2038 PQdb(pset.db), PQuser(pset.db));
2048 connection_warnings(bool in_startup)
2050 if (!pset.quiet && !pset.notty)
2052 int client_ver = PG_VERSION_NUM;
2056 if (pset.sversion != client_ver)
2058 const char *server_version;
2060 /* Try to get full text form, might include "devel" etc */
2061 server_version = PQparameterStatus(pset.db, "server_version");
2062 /* Otherwise fall back on pset.sversion */
2063 if (!server_version)
2065 formatPGVersionNumber(pset.sversion, true,
2066 sverbuf, sizeof(sverbuf));
2067 server_version = sverbuf;
2070 printf(_("%s (%s, server %s)\n"),
2071 pset.progname, PG_VERSION, server_version);
2073 /* For version match, only print psql banner on startup. */
2074 else if (in_startup)
2075 printf("%s (%s)\n", pset.progname, PG_VERSION);
2077 if (pset.sversion / 100 > client_ver / 100)
2078 printf(_("WARNING: %s major version %s, server major version %s.\n"
2079 " Some psql features might not work.\n"),
2081 formatPGVersionNumber(client_ver, false,
2082 cverbuf, sizeof(cverbuf)),
2083 formatPGVersionNumber(pset.sversion, false,
2084 sverbuf, sizeof(sverbuf)));
2087 checkWin32Codepage();
2097 * Prints information about the current SSL connection, if SSL is in use
2102 const char *protocol;
2105 const char *compression;
2107 if (!PQsslInUse(pset.db))
2108 return; /* no SSL */
2110 protocol = PQsslAttribute(pset.db, "protocol");
2111 cipher = PQsslAttribute(pset.db, "cipher");
2112 bits = PQsslAttribute(pset.db, "key_bits");
2113 compression = PQsslAttribute(pset.db, "compression");
2115 printf(_("SSL connection (protocol: %s, cipher: %s, bits: %s, compression: %s)\n"),
2116 protocol ? protocol : _("unknown"),
2117 cipher ? cipher : _("unknown"),
2118 bits ? bits : _("unknown"),
2119 (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"));
2124 * checkWin32Codepage
2126 * Prints a warning when win32 console codepage differs from Windows codepage
2130 checkWin32Codepage(void)
2136 concp = GetConsoleCP();
2139 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
2140 " 8-bit characters might not work correctly. See psql reference\n"
2141 " page \"Notes for Windows users\" for details.\n"),
2151 * Make psql's internal variables agree with connection state upon
2152 * establishing a new connection.
2157 /* get stuff from connection */
2158 pset.encoding = PQclientEncoding(pset.db);
2159 pset.popt.topt.encoding = pset.encoding;
2160 pset.sversion = PQserverVersion(pset.db);
2162 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
2163 SetVariable(pset.vars, "USER", PQuser(pset.db));
2164 SetVariable(pset.vars, "HOST", PQhost(pset.db));
2165 SetVariable(pset.vars, "PORT", PQport(pset.db));
2166 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
2168 /* send stuff to it, too */
2169 PQsetErrorVerbosity(pset.db, pset.verbosity);
2170 PQsetErrorContextVisibility(pset.db, pset.show_context);
2176 * Clear variables that should be not be set when there is no connection.
2179 UnsyncVariables(void)
2181 SetVariable(pset.vars, "DBNAME", NULL);
2182 SetVariable(pset.vars, "USER", NULL);
2183 SetVariable(pset.vars, "HOST", NULL);
2184 SetVariable(pset.vars, "PORT", NULL);
2185 SetVariable(pset.vars, "ENCODING", NULL);
2190 * do_edit -- handler for \e
2192 * If you do not specify a filename, the current query buffer will be copied
2193 * into a temporary one.
2196 editFile(const char *fname, int lineno)
2198 const char *editorName;
2199 const char *editor_lineno_arg = NULL;
2203 Assert(fname != NULL);
2205 /* Find an editor to use */
2206 editorName = getenv("PSQL_EDITOR");
2208 editorName = getenv("EDITOR");
2210 editorName = getenv("VISUAL");
2212 editorName = DEFAULT_EDITOR;
2214 /* Get line number argument, if we need it. */
2217 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
2218 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
2219 if (!editor_lineno_arg)
2220 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
2222 if (!editor_lineno_arg)
2224 psql_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number\n");
2230 * On Unix the EDITOR value should *not* be quoted, since it might include
2231 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
2232 * if necessary. But this policy is not very workable on Windows, due to
2233 * severe brain damage in their command shell plus the fact that standard
2234 * program paths include spaces.
2238 sys = psprintf("exec %s %s%d '%s'",
2239 editorName, editor_lineno_arg, lineno, fname);
2241 sys = psprintf("exec %s '%s'",
2245 sys = psprintf("\"%s\" %s%d \"%s\"",
2246 editorName, editor_lineno_arg, lineno, fname);
2248 sys = psprintf("\"%s\" \"%s\"",
2251 result = system(sys);
2253 psql_error("could not start editor \"%s\"\n", editorName);
2254 else if (result == 127)
2255 psql_error("could not start /bin/sh\n");
2264 do_edit(const char *filename_arg, PQExpBuffer query_buf,
2265 int lineno, bool *edited)
2267 char fnametmp[MAXPGPATH];
2268 FILE *stream = NULL;
2277 fname = filename_arg;
2280 /* make a temp file to edit */
2282 const char *tmpdir = getenv("TMPDIR");
2287 char tmpdir[MAXPGPATH];
2290 ret = GetTempPath(MAXPGPATH, tmpdir);
2291 if (ret == 0 || ret > MAXPGPATH)
2293 psql_error("could not locate temporary directory: %s\n",
2294 !ret ? strerror(errno) : "");
2299 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
2300 * current directory to the supplied path unless we use only
2301 * backslashes, so we do that.
2305 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
2306 "/", (int) getpid());
2308 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
2309 "" /* trailing separator already present */ , (int) getpid());
2312 fname = (const char *) fnametmp;
2314 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
2316 stream = fdopen(fd, "w");
2318 if (fd == -1 || !stream)
2320 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
2325 unsigned int ql = query_buf->len;
2327 if (ql == 0 || query_buf->data[ql - 1] != '\n')
2329 appendPQExpBufferChar(query_buf, '\n');
2333 if (fwrite(query_buf->data, 1, ql, stream) != ql)
2335 psql_error("%s: %s\n", fname, strerror(errno));
2337 if (fclose(stream) != 0)
2338 psql_error("%s: %s\n", fname, strerror(errno));
2340 if (remove(fname) != 0)
2341 psql_error("%s: %s\n", fname, strerror(errno));
2345 else if (fclose(stream) != 0)
2347 psql_error("%s: %s\n", fname, strerror(errno));
2348 if (remove(fname) != 0)
2349 psql_error("%s: %s\n", fname, strerror(errno));
2355 if (!error && stat(fname, &before) != 0)
2357 psql_error("%s: %s\n", fname, strerror(errno));
2363 error = !editFile(fname, lineno);
2365 if (!error && stat(fname, &after) != 0)
2367 psql_error("%s: %s\n", fname, strerror(errno));
2371 if (!error && before.st_mtime != after.st_mtime)
2373 stream = fopen(fname, PG_BINARY_R);
2376 psql_error("%s: %s\n", fname, strerror(errno));
2381 /* read file back into query_buf */
2384 resetPQExpBuffer(query_buf);
2385 while (fgets(line, sizeof(line), stream) != NULL)
2386 appendPQExpBufferStr(query_buf, line);
2390 psql_error("%s: %s\n", fname, strerror(errno));
2402 /* remove temp file */
2405 if (remove(fname) == -1)
2407 psql_error("%s: %s\n", fname, strerror(errno));
2420 * Reads commands from filename and passes them to the main processing loop.
2421 * Handler for \i and \ir, but can be used for other things as well. Returns
2422 * MainLoop() error code.
2424 * If use_relative_path is true and filename is not an absolute path, then open
2425 * the file from where the currently processed file (if any) is located.
2428 process_file(char *filename, bool use_relative_path)
2433 char relpath[MAXPGPATH];
2440 else if (strcmp(filename, "-") != 0)
2442 canonicalize_path(filename);
2445 * If we were asked to resolve the pathname relative to the location
2446 * of the currently executing script, and there is one, and this is a
2447 * relative pathname, then prepend all but the last pathname component
2448 * of the current script to this pathname.
2450 if (use_relative_path && pset.inputfile &&
2451 !is_absolute_path(filename) && !has_drive_prefix(filename))
2453 strlcpy(relpath, pset.inputfile, sizeof(relpath));
2454 get_parent_directory(relpath);
2455 join_path_components(relpath, relpath, filename);
2456 canonicalize_path(relpath);
2461 fd = fopen(filename, PG_BINARY_R);
2465 psql_error("%s: %s\n", filename, strerror(errno));
2466 return EXIT_FAILURE;
2472 filename = "<stdin>"; /* for future error messages */
2475 oldfilename = pset.inputfile;
2476 pset.inputfile = filename;
2478 result = MainLoop(fd);
2483 pset.inputfile = oldfilename;
2490 _align2string(enum printFormat in)
2497 case PRINT_UNALIGNED:
2509 case PRINT_ASCIIDOC:
2515 case PRINT_LATEX_LONGTABLE:
2516 return "latex-longtable";
2518 case PRINT_TROFF_MS:
2526 * Parse entered Unicode linestyle. If ok, update *linestyle and return
2527 * true, else return false.
2530 set_unicode_line_style(const char *value, size_t vallen,
2531 unicode_linestyle *linestyle)
2533 if (pg_strncasecmp("single", value, vallen) == 0)
2534 *linestyle = UNICODE_LINESTYLE_SINGLE;
2535 else if (pg_strncasecmp("double", value, vallen) == 0)
2536 *linestyle = UNICODE_LINESTYLE_DOUBLE;
2543 _unicode_linestyle2string(int linestyle)
2547 case UNICODE_LINESTYLE_SINGLE:
2550 case UNICODE_LINESTYLE_DOUBLE:
2562 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
2566 Assert(param != NULL);
2569 vallen = strlen(value);
2572 if (strcmp(param, "format") == 0)
2576 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2577 popt->topt.format = PRINT_UNALIGNED;
2578 else if (pg_strncasecmp("aligned", value, vallen) == 0)
2579 popt->topt.format = PRINT_ALIGNED;
2580 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2581 popt->topt.format = PRINT_WRAPPED;
2582 else if (pg_strncasecmp("html", value, vallen) == 0)
2583 popt->topt.format = PRINT_HTML;
2584 else if (pg_strncasecmp("asciidoc", value, vallen) == 0)
2585 popt->topt.format = PRINT_ASCIIDOC;
2586 else if (pg_strncasecmp("latex", value, vallen) == 0)
2587 popt->topt.format = PRINT_LATEX;
2588 else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
2589 popt->topt.format = PRINT_LATEX_LONGTABLE;
2590 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2591 popt->topt.format = PRINT_TROFF_MS;
2594 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, asciidoc, latex, latex-longtable, troff-ms\n");
2599 /* set table line style */
2600 else if (strcmp(param, "linestyle") == 0)
2604 else if (pg_strncasecmp("ascii", value, vallen) == 0)
2605 popt->topt.line_style = &pg_asciiformat;
2606 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2607 popt->topt.line_style = &pg_asciiformat_old;
2608 else if (pg_strncasecmp("unicode", value, vallen) == 0)
2609 popt->topt.line_style = &pg_utf8format;
2612 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2617 /* set unicode border line style */
2618 else if (strcmp(param, "unicode_border_linestyle") == 0)
2622 else if (set_unicode_line_style(value, vallen,
2623 &popt->topt.unicode_border_linestyle))
2624 refresh_utf8format(&(popt->topt));
2627 psql_error("\\pset: allowed Unicode border line styles are single, double\n");
2632 /* set unicode column line style */
2633 else if (strcmp(param, "unicode_column_linestyle") == 0)
2637 else if (set_unicode_line_style(value, vallen,
2638 &popt->topt.unicode_column_linestyle))
2639 refresh_utf8format(&(popt->topt));
2642 psql_error("\\pset: allowed Unicode column line styles are single, double\n");
2647 /* set unicode header line style */
2648 else if (strcmp(param, "unicode_header_linestyle") == 0)
2652 else if (set_unicode_line_style(value, vallen,
2653 &popt->topt.unicode_header_linestyle))
2654 refresh_utf8format(&(popt->topt));
2657 psql_error("\\pset: allowed Unicode header line styles are single, double\n");
2662 /* set border style/width */
2663 else if (strcmp(param, "border") == 0)
2666 popt->topt.border = atoi(value);
2669 /* set expanded/vertical mode */
2670 else if (strcmp(param, "x") == 0 ||
2671 strcmp(param, "expanded") == 0 ||
2672 strcmp(param, "vertical") == 0)
2674 if (value && pg_strcasecmp(value, "auto") == 0)
2675 popt->topt.expanded = 2;
2680 if (ParseVariableBool(value, NULL, &on_off))
2681 popt->topt.expanded = on_off ? 1 : 0;
2684 PsqlVarEnumError(param, value, "on, off, auto");
2689 popt->topt.expanded = !popt->topt.expanded;
2692 /* locale-aware numeric output */
2693 else if (strcmp(param, "numericlocale") == 0)
2696 return ParseVariableBool(value, param, &popt->topt.numericLocale);
2698 popt->topt.numericLocale = !popt->topt.numericLocale;
2702 else if (strcmp(param, "null") == 0)
2706 free(popt->nullPrint);
2707 popt->nullPrint = pg_strdup(value);
2711 /* field separator for unaligned text */
2712 else if (strcmp(param, "fieldsep") == 0)
2716 free(popt->topt.fieldSep.separator);
2717 popt->topt.fieldSep.separator = pg_strdup(value);
2718 popt->topt.fieldSep.separator_zero = false;
2722 else if (strcmp(param, "fieldsep_zero") == 0)
2724 free(popt->topt.fieldSep.separator);
2725 popt->topt.fieldSep.separator = NULL;
2726 popt->topt.fieldSep.separator_zero = true;
2729 /* record separator for unaligned text */
2730 else if (strcmp(param, "recordsep") == 0)
2734 free(popt->topt.recordSep.separator);
2735 popt->topt.recordSep.separator = pg_strdup(value);
2736 popt->topt.recordSep.separator_zero = false;
2740 else if (strcmp(param, "recordsep_zero") == 0)
2742 free(popt->topt.recordSep.separator);
2743 popt->topt.recordSep.separator = NULL;
2744 popt->topt.recordSep.separator_zero = true;
2747 /* toggle between full and tuples-only format */
2748 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2751 return ParseVariableBool(value, param, &popt->topt.tuples_only);
2753 popt->topt.tuples_only = !popt->topt.tuples_only;
2756 /* set title override */
2757 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
2763 popt->title = pg_strdup(value);
2766 /* set HTML table tag options */
2767 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2769 free(popt->topt.tableAttr);
2771 popt->topt.tableAttr = NULL;
2773 popt->topt.tableAttr = pg_strdup(value);
2776 /* toggle use of pager */
2777 else if (strcmp(param, "pager") == 0)
2779 if (value && pg_strcasecmp(value, "always") == 0)
2780 popt->topt.pager = 2;
2785 if (!ParseVariableBool(value, NULL, &on_off))
2787 PsqlVarEnumError(param, value, "on, off, always");
2790 popt->topt.pager = on_off ? 1 : 0;
2792 else if (popt->topt.pager == 1)
2793 popt->topt.pager = 0;
2795 popt->topt.pager = 1;
2798 /* set minimum lines for pager use */
2799 else if (strcmp(param, "pager_min_lines") == 0)
2802 popt->topt.pager_min_lines = atoi(value);
2805 /* disable "(x rows)" footer */
2806 else if (strcmp(param, "footer") == 0)
2809 return ParseVariableBool(value, param, &popt->topt.default_footer);
2811 popt->topt.default_footer = !popt->topt.default_footer;
2814 /* set border style/width */
2815 else if (strcmp(param, "columns") == 0)
2818 popt->topt.columns = atoi(value);
2822 psql_error("\\pset: unknown option: %s\n", param);
2827 printPsetInfo(param, &pset.popt);
2834 printPsetInfo(const char *param, struct printQueryOpt *popt)
2836 Assert(param != NULL);
2838 /* show border style/width */
2839 if (strcmp(param, "border") == 0)
2840 printf(_("Border style is %d.\n"), popt->topt.border);
2842 /* show the target width for the wrapped format */
2843 else if (strcmp(param, "columns") == 0)
2845 if (!popt->topt.columns)
2846 printf(_("Target width is unset.\n"));
2848 printf(_("Target width is %d.\n"), popt->topt.columns);
2851 /* show expanded/vertical mode */
2852 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2854 if (popt->topt.expanded == 1)
2855 printf(_("Expanded display is on.\n"));
2856 else if (popt->topt.expanded == 2)
2857 printf(_("Expanded display is used automatically.\n"));
2859 printf(_("Expanded display is off.\n"));
2862 /* show field separator for unaligned text */
2863 else if (strcmp(param, "fieldsep") == 0)
2865 if (popt->topt.fieldSep.separator_zero)
2866 printf(_("Field separator is zero byte.\n"));
2868 printf(_("Field separator is \"%s\".\n"),
2869 popt->topt.fieldSep.separator);
2872 else if (strcmp(param, "fieldsep_zero") == 0)
2874 printf(_("Field separator is zero byte.\n"));
2877 /* show disable "(x rows)" footer */
2878 else if (strcmp(param, "footer") == 0)
2880 if (popt->topt.default_footer)
2881 printf(_("Default footer is on.\n"));
2883 printf(_("Default footer is off.\n"));
2887 else if (strcmp(param, "format") == 0)
2889 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2892 /* show table line style */
2893 else if (strcmp(param, "linestyle") == 0)
2895 printf(_("Line style is %s.\n"),
2896 get_line_style(&popt->topt)->name);
2899 /* show null display */
2900 else if (strcmp(param, "null") == 0)
2902 printf(_("Null display is \"%s\".\n"),
2903 popt->nullPrint ? popt->nullPrint : "");
2906 /* show locale-aware numeric output */
2907 else if (strcmp(param, "numericlocale") == 0)
2909 if (popt->topt.numericLocale)
2910 printf(_("Locale-adjusted numeric output is on.\n"));
2912 printf(_("Locale-adjusted numeric output is off.\n"));
2915 /* show toggle use of pager */
2916 else if (strcmp(param, "pager") == 0)
2918 if (popt->topt.pager == 1)
2919 printf(_("Pager is used for long output.\n"));
2920 else if (popt->topt.pager == 2)
2921 printf(_("Pager is always used.\n"));
2923 printf(_("Pager usage is off.\n"));
2926 /* show minimum lines for pager use */
2927 else if (strcmp(param, "pager_min_lines") == 0)
2929 printf(ngettext("Pager won't be used for less than %d line.\n",
2930 "Pager won't be used for less than %d lines.\n",
2931 popt->topt.pager_min_lines),
2932 popt->topt.pager_min_lines);
2935 /* show record separator for unaligned text */
2936 else if (strcmp(param, "recordsep") == 0)
2938 if (popt->topt.recordSep.separator_zero)
2939 printf(_("Record separator is zero byte.\n"));
2940 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
2941 printf(_("Record separator is <newline>.\n"));
2943 printf(_("Record separator is \"%s\".\n"),
2944 popt->topt.recordSep.separator);
2947 else if (strcmp(param, "recordsep_zero") == 0)
2949 printf(_("Record separator is zero byte.\n"));
2952 /* show HTML table tag options */
2953 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2955 if (popt->topt.tableAttr)
2956 printf(_("Table attributes are \"%s\".\n"),
2957 popt->topt.tableAttr);
2959 printf(_("Table attributes unset.\n"));
2962 /* show title override */
2963 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
2966 printf(_("Title is \"%s\".\n"), popt->title);
2968 printf(_("Title is unset.\n"));
2971 /* show toggle between full and tuples-only format */
2972 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2974 if (popt->topt.tuples_only)
2975 printf(_("Tuples only is on.\n"));
2977 printf(_("Tuples only is off.\n"));
2980 /* Unicode style formatting */
2981 else if (strcmp(param, "unicode_border_linestyle") == 0)
2983 printf(_("Unicode border line style is \"%s\".\n"),
2984 _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
2987 else if (strcmp(param, "unicode_column_linestyle") == 0)
2989 printf(_("Unicode column line style is \"%s\".\n"),
2990 _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
2993 else if (strcmp(param, "unicode_header_linestyle") == 0)
2995 printf(_("Unicode header line style is \"%s\".\n"),
2996 _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
3001 psql_error("\\pset: unknown option: %s\n", param);
3010 pset_bool_string(bool val)
3012 return val ? "on" : "off";
3017 pset_quoted_string(const char *str)
3019 char *ret = pg_malloc(strlen(str) * 2 + 3);
3031 else if (*str == '\'')
3048 * Return a malloc'ed string for the \pset value.
3050 * Note that for some string parameters, print.c distinguishes between unset
3051 * and empty string, but for others it doesn't. This function should produce
3052 * output that produces the correct setting when fed back into \pset.
3055 pset_value_string(const char *param, struct printQueryOpt *popt)
3057 Assert(param != NULL);
3059 if (strcmp(param, "border") == 0)
3060 return psprintf("%d", popt->topt.border);
3061 else if (strcmp(param, "columns") == 0)
3062 return psprintf("%d", popt->topt.columns);
3063 else if (strcmp(param, "expanded") == 0)
3064 return pstrdup(popt->topt.expanded == 2
3066 : pset_bool_string(popt->topt.expanded));
3067 else if (strcmp(param, "fieldsep") == 0)
3068 return pset_quoted_string(popt->topt.fieldSep.separator
3069 ? popt->topt.fieldSep.separator
3071 else if (strcmp(param, "fieldsep_zero") == 0)
3072 return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
3073 else if (strcmp(param, "footer") == 0)
3074 return pstrdup(pset_bool_string(popt->topt.default_footer));
3075 else if (strcmp(param, "format") == 0)
3076 return psprintf("%s", _align2string(popt->topt.format));
3077 else if (strcmp(param, "linestyle") == 0)
3078 return psprintf("%s", get_line_style(&popt->topt)->name);
3079 else if (strcmp(param, "null") == 0)
3080 return pset_quoted_string(popt->nullPrint
3083 else if (strcmp(param, "numericlocale") == 0)
3084 return pstrdup(pset_bool_string(popt->topt.numericLocale));
3085 else if (strcmp(param, "pager") == 0)
3086 return psprintf("%d", popt->topt.pager);
3087 else if (strcmp(param, "pager_min_lines") == 0)
3088 return psprintf("%d", popt->topt.pager_min_lines);
3089 else if (strcmp(param, "recordsep") == 0)
3090 return pset_quoted_string(popt->topt.recordSep.separator
3091 ? popt->topt.recordSep.separator
3093 else if (strcmp(param, "recordsep_zero") == 0)
3094 return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
3095 else if (strcmp(param, "tableattr") == 0)
3096 return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
3097 else if (strcmp(param, "title") == 0)
3098 return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
3099 else if (strcmp(param, "tuples_only") == 0)
3100 return pstrdup(pset_bool_string(popt->topt.tuples_only));
3101 else if (strcmp(param, "unicode_border_linestyle") == 0)
3102 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
3103 else if (strcmp(param, "unicode_column_linestyle") == 0)
3104 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
3105 else if (strcmp(param, "unicode_header_linestyle") == 0)
3106 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
3108 return pstrdup("ERROR");
3114 #define DEFAULT_SHELL "/bin/sh"
3117 * CMD.EXE is in different places in different Win32 releases so we
3118 * have to rely on the path to find it.
3120 #define DEFAULT_SHELL "cmd.exe"
3124 do_shell(const char *command)
3131 const char *shellName;
3133 shellName = getenv("SHELL");
3135 if (shellName == NULL)
3136 shellName = getenv("COMSPEC");
3138 if (shellName == NULL)
3139 shellName = DEFAULT_SHELL;
3141 /* See EDITOR handling comment for an explanation */
3143 sys = psprintf("exec %s", shellName);
3145 sys = psprintf("\"%s\"", shellName);
3147 result = system(sys);
3151 result = system(command);
3153 if (result == 127 || result == -1)
3155 psql_error("\\!: failed\n");
3162 * do_watch -- handler for \watch
3164 * We break this out of exec_command to avoid having to plaster "volatile"
3165 * onto a bunch of exec_command's variables to silence stupider compilers.
3168 do_watch(PQExpBuffer query_buf, double sleep)
3170 long sleep_ms = (long) (sleep * 1000);
3171 printQueryOpt myopt = pset.popt;
3172 const char *strftime_fmt;
3173 const char *user_title;
3178 if (!query_buf || query_buf->len <= 0)
3180 psql_error(_("\\watch cannot be used with an empty query\n"));
3185 * Choose format for timestamps. We might eventually make this a \pset
3186 * option. In the meantime, using a variable for the format suppresses
3187 * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
3189 strftime_fmt = "%c";
3192 * Set up rendering options, in particular, disable the pager, because
3193 * nobody wants to be prompted while watching the output of 'watch'.
3195 myopt.topt.pager = 0;
3198 * If there's a title in the user configuration, make sure we have room
3199 * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
3200 * bytes for the rest.
3202 user_title = myopt.title;
3203 title_len = (user_title ? strlen(user_title) : 0) + 256;
3204 title = pg_malloc(title_len);
3213 * Prepare title for output. Note that we intentionally include a
3214 * newline at the end of the title; this is somewhat historical but it
3215 * makes for reasonably nicely formatted output in simple cases.
3218 strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
3221 snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
3222 user_title, timebuf, sleep);
3224 snprintf(title, title_len, _("%s (every %gs)\n"),
3226 myopt.title = title;
3228 /* Run the query and print out the results */
3229 res = PSQLexecWatch(query_buf->data, &myopt);
3232 * PSQLexecWatch handles the case where we can no longer repeat the
3233 * query, and returns 0 or -1.
3239 * Set up cancellation of 'watch' via SIGINT. We redo this each time
3240 * through the loop since it's conceivable something inside
3241 * PSQLexecWatch could change sigint_interrupt_jmp.
3243 if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
3247 * Enable 'watch' cancellations and wait a while before running the
3248 * query again. Break the sleep into short intervals (at most 1s)
3249 * since pg_usleep isn't interruptible on some platforms.
3251 sigint_interrupt_enabled = true;
3255 long s = Min(i, 1000L);
3257 pg_usleep(s * 1000L);
3262 sigint_interrupt_enabled = false;
3270 * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
3271 * returns true unless we have ECHO_HIDDEN_NOEXEC.
3274 echo_hidden_command(const char *query)
3276 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
3278 printf(_("********* QUERY **********\n"
3280 "**************************\n\n"), query);
3284 fprintf(pset.logfile,
3285 _("********* QUERY **********\n"
3287 "**************************\n\n"), query);
3288 fflush(pset.logfile);
3291 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
3298 * Look up the object identified by obj_type and desc. If successful,
3299 * store its OID in *obj_oid and return TRUE, else return FALSE.
3301 * Note that we'll fail if the object doesn't exist OR if there are multiple
3302 * matching candidates OR if there's something syntactically wrong with the
3303 * object description; unfortunately it can be hard to tell the difference.
3306 lookup_object_oid(EditableObjectType obj_type, const char *desc,
3310 PQExpBuffer query = createPQExpBuffer();
3315 case EditableFunction:
3318 * We have a function description, e.g. "x" or "x(int)". Issue a
3319 * query to retrieve the function's OID using a cast to regproc or
3320 * regprocedure (as appropriate).
3322 appendPQExpBufferStr(query, "SELECT ");
3323 appendStringLiteralConn(query, desc, pset.db);
3324 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
3325 strchr(desc, '(') ? "regprocedure" : "regproc");
3331 * Convert view name (possibly schema-qualified) to OID. Note:
3332 * this code doesn't check if the relation is actually a view.
3333 * We'll detect that in get_create_object_cmd().
3335 appendPQExpBufferStr(query, "SELECT ");
3336 appendStringLiteralConn(query, desc, pset.db);
3337 appendPQExpBuffer(query, "::pg_catalog.regclass::pg_catalog.oid");
3341 if (!echo_hidden_command(query->data))
3343 destroyPQExpBuffer(query);
3346 res = PQexec(pset.db, query->data);
3347 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
3348 *obj_oid = atooid(PQgetvalue(res, 0, 0));
3351 minimal_error_message(res);
3356 destroyPQExpBuffer(query);
3362 * Construct a "CREATE OR REPLACE ..." command that describes the specified
3363 * database object. If successful, the result is stored in buf.
3366 get_create_object_cmd(EditableObjectType obj_type, Oid oid,
3370 PQExpBuffer query = createPQExpBuffer();
3375 case EditableFunction:
3376 printfPQExpBuffer(query,
3377 "SELECT pg_catalog.pg_get_functiondef(%u)",
3384 * pg_get_viewdef() just prints the query, so we must prepend
3385 * CREATE for ourselves. We must fully qualify the view name to
3386 * ensure the right view gets replaced. Also, check relation kind
3387 * to be sure it's a view.
3389 * Starting with 9.2, views may have reloptions (security_barrier)
3390 * and from 9.4 onwards they may also have WITH [LOCAL|CASCADED]
3391 * CHECK OPTION. These are not part of the view definition
3392 * returned by pg_get_viewdef() and so need to be retrieved
3393 * separately. Materialized views (introduced in 9.3) may have
3394 * arbitrary storage parameter reloptions.
3396 if (pset.sversion >= 90400)
3398 printfPQExpBuffer(query,
3399 "SELECT nspname, relname, relkind, "
3400 "pg_catalog.pg_get_viewdef(c.oid, true), "
3401 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
3402 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
3403 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
3404 "FROM pg_catalog.pg_class c "
3405 "LEFT JOIN pg_catalog.pg_namespace n "
3406 "ON c.relnamespace = n.oid WHERE c.oid = %u",
3409 else if (pset.sversion >= 90200)
3411 printfPQExpBuffer(query,
3412 "SELECT nspname, relname, relkind, "
3413 "pg_catalog.pg_get_viewdef(c.oid, true), "
3414 "c.reloptions AS reloptions, "
3415 "NULL AS checkoption "
3416 "FROM pg_catalog.pg_class c "
3417 "LEFT JOIN pg_catalog.pg_namespace n "
3418 "ON c.relnamespace = n.oid WHERE c.oid = %u",
3423 printfPQExpBuffer(query,
3424 "SELECT nspname, relname, relkind, "
3425 "pg_catalog.pg_get_viewdef(c.oid, true), "
3426 "NULL AS reloptions, "
3427 "NULL AS checkoption "
3428 "FROM pg_catalog.pg_class c "
3429 "LEFT JOIN pg_catalog.pg_namespace n "
3430 "ON c.relnamespace = n.oid WHERE c.oid = %u",
3436 if (!echo_hidden_command(query->data))
3438 destroyPQExpBuffer(query);
3441 res = PQexec(pset.db, query->data);
3442 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
3444 resetPQExpBuffer(buf);
3447 case EditableFunction:
3448 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
3453 char *nspname = PQgetvalue(res, 0, 0);
3454 char *relname = PQgetvalue(res, 0, 1);
3455 char *relkind = PQgetvalue(res, 0, 2);
3456 char *viewdef = PQgetvalue(res, 0, 3);
3457 char *reloptions = PQgetvalue(res, 0, 4);
3458 char *checkoption = PQgetvalue(res, 0, 5);
3461 * If the backend ever supports CREATE OR REPLACE
3462 * MATERIALIZED VIEW, allow that here; but as of today it
3463 * does not, so editing a matview definition in this way
3469 case RELKIND_MATVIEW:
3470 appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
3474 appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
3477 psql_error("\"%s.%s\" is not a view\n",
3482 appendPQExpBuffer(buf, "%s.", fmtId(nspname));
3483 appendPQExpBufferStr(buf, fmtId(relname));
3485 /* reloptions, if not an empty array "{}" */
3486 if (reloptions != NULL && strlen(reloptions) > 2)
3488 appendPQExpBufferStr(buf, "\n WITH (");
3489 if (!appendReloptionsArray(buf, reloptions, "",
3491 standard_strings()))
3493 psql_error("could not parse reloptions array\n");
3496 appendPQExpBufferStr(buf, ")");
3499 /* View definition from pg_get_viewdef (a SELECT query) */
3500 appendPQExpBuffer(buf, " AS\n%s", viewdef);
3502 /* Get rid of the semicolon that pg_get_viewdef appends */
3503 if (buf->len > 0 && buf->data[buf->len - 1] == ';')
3504 buf->data[--(buf->len)] = '\0';
3506 /* WITH [LOCAL|CASCADED] CHECK OPTION */
3507 if (checkoption && checkoption[0] != '\0')
3508 appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
3513 /* Make sure result ends with a newline */
3514 if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
3515 appendPQExpBufferChar(buf, '\n');
3519 minimal_error_message(res);
3524 destroyPQExpBuffer(query);
3530 * If the given argument of \ef or \ev ends with a line number, delete the line
3531 * number from the argument string and return it as an integer. (We need
3532 * this kluge because we're too lazy to parse \ef's function or \ev's view
3533 * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
3535 * Returns -1 if no line number is present, 0 on error, or a positive value
3539 strip_lineno_from_objdesc(char *obj)
3544 if (!obj || obj[0] == '\0')
3547 c = obj + strlen(obj) - 1;
3550 * This business of parsing backwards is dangerous as can be in a
3551 * multibyte environment: there is no reason to believe that we are
3552 * looking at the first byte of a character, nor are we necessarily
3553 * working in a "safe" encoding. Fortunately the bitpatterns we are
3554 * looking for are unlikely to occur as non-first bytes, but beware of
3555 * trying to expand the set of cases that can be recognized. We must
3556 * guard the <ctype.h> macros by using isascii() first, too.
3559 /* skip trailing whitespace */
3560 while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
3563 /* must have a digit as last non-space char */
3564 if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
3567 /* find start of digit string */
3568 while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
3571 /* digits must be separated from object name by space or closing paren */
3572 /* notice also that we are not allowing an empty object name ... */
3573 if (c == obj || !isascii((unsigned char) *c) ||
3574 !(isspace((unsigned char) *c) || *c == ')'))
3577 /* parse digit string */
3582 psql_error("invalid line number: %s\n", c);
3586 /* strip digit string from object name */
3593 * Count number of lines in the buffer.
3594 * This is used to test if pager is needed or not.
3597 count_lines_in_buf(PQExpBuffer buf)
3600 const char *lines = buf->data;
3602 while (*lines != '\0')
3605 /* find start of next line */
3606 lines = strchr(lines, '\n');
3616 * Write text at *lines to output with line numbers.
3618 * If header_keyword isn't NULL, then line 1 should be the first line beginning
3619 * with header_keyword; lines before that are unnumbered.
3621 * Caution: this scribbles on *lines.
3624 print_with_linenumbers(FILE *output, char *lines,
3625 const char *header_keyword)
3627 bool in_header = (header_keyword != NULL);
3628 size_t header_sz = in_header ? strlen(header_keyword) : 0;
3631 while (*lines != '\0')
3635 if (in_header && strncmp(lines, header_keyword, header_sz) == 0)
3638 /* increment lineno only for body's lines */
3642 /* find and mark end of current line */
3643 eol = strchr(lines, '\n');
3647 /* show current line as appropriate */
3649 fprintf(output, " %s\n", lines);
3651 fprintf(output, "%-7d %s\n", lineno, lines);
3653 /* advance to next line, if any */
3661 * Report just the primary error; this is to avoid cluttering the output
3662 * with, for instance, a redisplay of the internally generated query
3665 minimal_error_message(PGresult *res)
3670 msg = createPQExpBuffer();
3672 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
3674 printfPQExpBuffer(msg, "%s: ", fld);
3676 printfPQExpBuffer(msg, "ERROR: ");
3677 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
3679 appendPQExpBufferStr(msg, fld);
3681 appendPQExpBufferStr(msg, "(not available)");
3682 appendPQExpBufferStr(msg, "\n");
3684 psql_error("%s", msg->data);
3686 destroyPQExpBuffer(msg);