Branch data Line data Source code
1 : : /*
2 : : * psql - the PostgreSQL interactive terminal
3 : : *
4 : : * Copyright (c) 2000-2026, PostgreSQL Global Development Group
5 : : *
6 : : * src/bin/psql/command.c
7 : : */
8 : : #include "postgres_fe.h"
9 : :
10 : : #include <ctype.h>
11 : : #include <time.h>
12 : : #include <pwd.h>
13 : : #include <utime.h>
14 : : #ifndef WIN32
15 : : #include <sys/stat.h> /* for stat() */
16 : : #include <sys/time.h> /* for setitimer() */
17 : : #include <fcntl.h> /* open() flags */
18 : : #include <unistd.h> /* for geteuid(), getpid(), stat() */
19 : : #else
20 : : #include <win32.h>
21 : : #include <io.h>
22 : : #include <fcntl.h>
23 : : #include <direct.h>
24 : : #include <sys/stat.h> /* for stat() */
25 : : #endif
26 : :
27 : : #include "catalog/pg_class_d.h"
28 : : #include "command.h"
29 : : #include "common.h"
30 : : #include "common/logging.h"
31 : : #include "common/string.h"
32 : : #include "copy.h"
33 : : #include "describe.h"
34 : : #include "fe_utils/cancel.h"
35 : : #include "fe_utils/print.h"
36 : : #include "fe_utils/string_utils.h"
37 : : #include "help.h"
38 : : #include "input.h"
39 : : #include "large_obj.h"
40 : : #include "libpq/pqcomm.h"
41 : : #include "mainloop.h"
42 : : #include "pqexpbuffer.h"
43 : : #include "psqlscanslash.h"
44 : : #include "settings.h"
45 : : #include "variables.h"
46 : :
47 : : /*
48 : : * Editable database object types.
49 : : */
50 : : typedef enum EditableObjectType
51 : : {
52 : : EditableFunction,
53 : : EditableView,
54 : : } EditableObjectType;
55 : :
56 : : /* local function declarations */
57 : : static backslashResult exec_command(const char *cmd,
58 : : PsqlScanState scan_state,
59 : : ConditionalStack cstack,
60 : : PQExpBuffer query_buf,
61 : : PQExpBuffer previous_buf);
62 : : static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch);
63 : : static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch);
64 : : static backslashResult exec_command_bind_named(PsqlScanState scan_state, bool active_branch,
65 : : const char *cmd);
66 : : static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch);
67 : : static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch);
68 : : static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch,
69 : : const char *cmd);
70 : : static backslashResult exec_command_close_prepared(PsqlScanState scan_state,
71 : : bool active_branch, const char *cmd);
72 : : static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch);
73 : : static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch);
74 : : static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch);
75 : : static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch);
76 : : static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch,
77 : : const char *cmd);
78 : : static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd,
79 : : const char *pattern,
80 : : bool show_verbose, bool show_system);
81 : : static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch,
82 : : PQExpBuffer query_buf, PQExpBuffer previous_buf);
83 : : static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
84 : : PQExpBuffer query_buf, bool is_func);
85 : : static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch,
86 : : const char *cmd);
87 : : static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
88 : : PQExpBuffer query_buf);
89 : : static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
90 : : PQExpBuffer query_buf);
91 : : static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
92 : : PQExpBuffer query_buf);
93 : : static backslashResult exec_command_endpipeline(PsqlScanState scan_state, bool active_branch);
94 : : static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch);
95 : : static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch);
96 : : static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch);
97 : : static backslashResult exec_command_flush(PsqlScanState scan_state, bool active_branch);
98 : : static backslashResult exec_command_flushrequest(PsqlScanState scan_state, bool active_branch);
99 : : static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch,
100 : : const char *cmd);
101 : : static backslashResult process_command_g_options(char *first_option,
102 : : PsqlScanState scan_state,
103 : : bool active_branch,
104 : : const char *cmd);
105 : : static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch);
106 : : static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch,
107 : : const char *cmd);
108 : : static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch);
109 : : static backslashResult exec_command_getresults(PsqlScanState scan_state, bool active_branch);
110 : : static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch);
111 : : static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch);
112 : : static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch);
113 : : static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch,
114 : : const char *cmd);
115 : : static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
116 : : PQExpBuffer query_buf);
117 : : static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch,
118 : : const char *cmd);
119 : : static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch,
120 : : const char *cmd);
121 : : static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch);
122 : : static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch,
123 : : PQExpBuffer query_buf, PQExpBuffer previous_buf);
124 : : static backslashResult exec_command_parse(PsqlScanState scan_state, bool active_branch,
125 : : const char *cmd);
126 : : static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch);
127 : : static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch,
128 : : const char *cmd);
129 : : static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch);
130 : : static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch);
131 : : static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch,
132 : : PQExpBuffer query_buf);
133 : : static backslashResult exec_command_restrict(PsqlScanState scan_state, bool active_branch,
134 : : const char *cmd);
135 : : static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch);
136 : : static backslashResult exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch);
137 : : static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch);
138 : : static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch,
139 : : const char *cmd);
140 : : static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
141 : : const char *cmd, bool is_func);
142 : : static backslashResult exec_command_startpipeline(PsqlScanState scan_state, bool active_branch);
143 : : static backslashResult exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch);
144 : : static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch);
145 : : static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch);
146 : : static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch);
147 : : static backslashResult exec_command_unrestrict(PsqlScanState scan_state, bool active_branch,
148 : : const char *cmd);
149 : : static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch,
150 : : const char *cmd);
151 : : static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch,
152 : : const char *cmd,
153 : : PQExpBuffer query_buf, PQExpBuffer previous_buf);
154 : : static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch,
155 : : PQExpBuffer query_buf, PQExpBuffer previous_buf);
156 : : static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch);
157 : : static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch,
158 : : const char *cmd);
159 : : static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch);
160 : : static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch);
161 : : static char *read_connect_arg(PsqlScanState scan_state);
162 : : static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state);
163 : : static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name);
164 : : static void ignore_boolean_expression(PsqlScanState scan_state);
165 : : static void ignore_slash_options(PsqlScanState scan_state);
166 : : static void ignore_slash_filepipe(PsqlScanState scan_state);
167 : : static void ignore_slash_whole_line(PsqlScanState scan_state);
168 : : static bool is_branching_command(const char *cmd);
169 : : static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
170 : : PQExpBuffer query_buf);
171 : : static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
172 : : PQExpBuffer query_buf);
173 : : static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf);
174 : : static bool do_connect(enum trivalue reuse_previous_specification,
175 : : char *dbname, char *user, char *host, char *port);
176 : : static void wait_until_connected(PGconn *conn);
177 : : static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
178 : : int lineno, bool discard_on_quit, bool *edited);
179 : : static bool do_shell(const char *command);
180 : : static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows);
181 : : static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
182 : : Oid *obj_oid);
183 : : static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
184 : : PQExpBuffer buf);
185 : : static int strip_lineno_from_objdesc(char *obj);
186 : : static int count_lines_in_buf(PQExpBuffer buf);
187 : : static void print_with_linenumbers(FILE *output, char *lines, bool is_func);
188 : : static void minimal_error_message(PGresult *res);
189 : :
190 : : static void printSSLInfo(void);
191 : : static void printGSSInfo(void);
192 : : static bool printPsetInfo(const char *param, printQueryOpt *popt);
193 : : static char *pset_value_string(const char *param, printQueryOpt *popt);
194 : :
195 : : #ifdef WIN32
196 : : static void checkWin32Codepage(void);
197 : : #endif
198 : :
199 : : static bool restricted;
200 : : static char *restrict_key;
201 : :
202 : :
203 : : /*----------
204 : : * HandleSlashCmds:
205 : : *
206 : : * Handles all the different commands that start with '\'.
207 : : * Ordinarily called by MainLoop().
208 : : *
209 : : * scan_state is a lexer working state that is set to continue scanning
210 : : * just after the '\'. The lexer is advanced past the command and all
211 : : * arguments on return.
212 : : *
213 : : * cstack is the current \if stack state. This will be examined, and
214 : : * possibly modified by conditional commands.
215 : : *
216 : : * query_buf contains the query-so-far, which may be modified by
217 : : * execution of the backslash command (for example, \r clears it).
218 : : *
219 : : * previous_buf contains the query most recently sent to the server
220 : : * (empty if none yet). This should not be modified here, but some
221 : : * commands copy its content into query_buf.
222 : : *
223 : : * query_buf and previous_buf will be NULL when executing a "-c"
224 : : * command-line option.
225 : : *
226 : : * Returns a status code indicating what action is desired, see command.h.
227 : : *----------
228 : : */
229 : :
230 : : backslashResult
231 : 32471 : HandleSlashCmds(PsqlScanState scan_state,
232 : : ConditionalStack cstack,
233 : : PQExpBuffer query_buf,
234 : : PQExpBuffer previous_buf)
235 : : {
236 : : backslashResult status;
237 : : char *cmd;
238 : : char *arg;
239 : :
240 : : Assert(scan_state != NULL);
241 : : Assert(cstack != NULL);
242 : :
243 : : /* Parse off the command name */
244 : 32471 : cmd = psql_scan_slash_command(scan_state);
245 : :
246 : : /*
247 : : * And try to execute it.
248 : : *
249 : : * If we are in "restricted" mode, the only allowable backslash command is
250 : : * \unrestrict (to exit restricted mode).
251 : : */
252 [ + + + + ]: 32471 : if (restricted && strcmp(cmd, "unrestrict") != 0)
253 : : {
254 : 1 : pg_log_error("backslash commands are restricted; only \\unrestrict is allowed");
255 : 1 : status = PSQL_CMD_ERROR;
256 : : }
257 : : else
258 : 32470 : status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
259 : :
260 [ + + ]: 32469 : if (status == PSQL_CMD_UNKNOWN)
261 : : {
262 : 4 : pg_log_error("invalid command \\%s", cmd);
263 [ - + ]: 4 : if (pset.cur_cmd_interactive)
264 : 0 : pg_log_error_hint("Try \\? for help.");
265 : 4 : status = PSQL_CMD_ERROR;
266 : : }
267 : :
268 [ + + ]: 32469 : if (status != PSQL_CMD_ERROR)
269 : : {
270 : : /*
271 : : * Eat any remaining arguments after a valid command. We want to
272 : : * suppress evaluation of backticks in this situation, so transiently
273 : : * push an inactive conditional-stack entry.
274 : : */
275 : 31680 : bool active_branch = conditional_active(cstack);
276 : :
277 : 31680 : conditional_stack_push(cstack, IFSTATE_IGNORED);
278 [ + + ]: 31700 : while ((arg = psql_scan_slash_option(scan_state,
279 : : OT_NORMAL, NULL, false)))
280 : : {
281 [ + - ]: 20 : if (active_branch)
282 : 20 : pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
283 : 20 : free(arg);
284 : : }
285 : 31680 : conditional_stack_pop(cstack);
286 : : }
287 : : else
288 : : {
289 : : /* silently throw away rest of line after an erroneous command */
290 [ + + ]: 802 : while ((arg = psql_scan_slash_option(scan_state,
291 : : OT_WHOLE_LINE, NULL, false)))
292 : 13 : free(arg);
293 : : }
294 : :
295 : : /* if there is a trailing \\, swallow it */
296 : 32469 : psql_scan_slash_command_end(scan_state);
297 : :
298 : 32469 : free(cmd);
299 : :
300 : : /* some commands write to queryFout, so make sure output is sent */
301 : 32469 : fflush(pset.queryFout);
302 : :
303 : 32469 : return status;
304 : : }
305 : :
306 : :
307 : : /*
308 : : * Subroutine to actually try to execute a backslash command.
309 : : *
310 : : * The typical "success" result code is PSQL_CMD_SKIP_LINE, although some
311 : : * commands return something else. Failure result code is PSQL_CMD_ERROR,
312 : : * unless PSQL_CMD_UNKNOWN is more appropriate.
313 : : */
314 : : static backslashResult
315 : 32470 : exec_command(const char *cmd,
316 : : PsqlScanState scan_state,
317 : : ConditionalStack cstack,
318 : : PQExpBuffer query_buf,
319 : : PQExpBuffer previous_buf)
320 : : {
321 : : backslashResult status;
322 : 32470 : bool active_branch = conditional_active(cstack);
323 : :
324 : : /*
325 : : * In interactive mode, warn when we're ignoring a command within a false
326 : : * \if-branch. But we continue on, so as to parse and discard the right
327 : : * amount of parameter text. Each individual backslash command subroutine
328 : : * is responsible for doing nothing after discarding appropriate
329 : : * arguments, if !active_branch.
330 : : */
331 [ + + - + ]: 32470 : if (pset.cur_cmd_interactive && !active_branch &&
332 [ # # ]: 0 : !is_branching_command(cmd))
333 : : {
334 : 0 : pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
335 : : cmd);
336 : : }
337 : :
338 [ + + ]: 32470 : if (strcmp(cmd, "a") == 0)
339 : 52 : status = exec_command_a(scan_state, active_branch);
340 [ + + ]: 32418 : else if (strcmp(cmd, "bind") == 0)
341 : 532 : status = exec_command_bind(scan_state, active_branch);
342 [ + + ]: 31886 : else if (strcmp(cmd, "bind_named") == 0)
343 : 116 : status = exec_command_bind_named(scan_state, active_branch, cmd);
344 [ + + ]: 31770 : else if (strcmp(cmd, "C") == 0)
345 : 4 : status = exec_command_C(scan_state, active_branch);
346 [ + + + + ]: 31766 : else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
347 : 226 : status = exec_command_connect(scan_state, active_branch);
348 [ + + ]: 31540 : else if (strcmp(cmd, "cd") == 0)
349 : 4 : status = exec_command_cd(scan_state, active_branch, cmd);
350 [ + + ]: 31536 : else if (strcmp(cmd, "close_prepared") == 0)
351 : 33 : status = exec_command_close_prepared(scan_state, active_branch, cmd);
352 [ + + ]: 31503 : else if (strcmp(cmd, "conninfo") == 0)
353 : 4 : status = exec_command_conninfo(scan_state, active_branch);
354 [ + + ]: 31499 : else if (pg_strcasecmp(cmd, "copy") == 0)
355 : 103 : status = exec_command_copy(scan_state, active_branch);
356 [ + + ]: 31396 : else if (strcmp(cmd, "copyright") == 0)
357 : 5 : status = exec_command_copyright(scan_state, active_branch);
358 [ + + ]: 31391 : else if (strcmp(cmd, "crosstabview") == 0)
359 : 100 : status = exec_command_crosstabview(scan_state, active_branch);
360 [ + + ]: 31291 : else if (cmd[0] == 'd')
361 : 4793 : status = exec_command_d(scan_state, active_branch, cmd);
362 [ + + - + ]: 26498 : else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
363 : 4 : status = exec_command_edit(scan_state, active_branch,
364 : : query_buf, previous_buf);
365 [ + + ]: 26494 : else if (strcmp(cmd, "ef") == 0)
366 : 4 : status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
367 [ + + ]: 26490 : else if (strcmp(cmd, "ev") == 0)
368 : 4 : status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
369 [ + + + + ]: 26486 : else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
370 [ + + ]: 15868 : strcmp(cmd, "warn") == 0)
371 : 20619 : status = exec_command_echo(scan_state, active_branch, cmd);
372 [ + + ]: 5867 : else if (strcmp(cmd, "elif") == 0)
373 : 32 : status = exec_command_elif(scan_state, cstack, query_buf);
374 [ + + ]: 5835 : else if (strcmp(cmd, "else") == 0)
375 : 88 : status = exec_command_else(scan_state, cstack, query_buf);
376 [ + + ]: 5747 : else if (strcmp(cmd, "endif") == 0)
377 : 145 : status = exec_command_endif(scan_state, cstack, query_buf);
378 [ + + ]: 5602 : else if (strcmp(cmd, "endpipeline") == 0)
379 : 225 : status = exec_command_endpipeline(scan_state, active_branch);
380 [ + + ]: 5377 : else if (strcmp(cmd, "encoding") == 0)
381 : 12 : status = exec_command_encoding(scan_state, active_branch);
382 [ + + ]: 5365 : else if (strcmp(cmd, "errverbose") == 0)
383 : 8 : status = exec_command_errverbose(scan_state, active_branch);
384 [ + + ]: 5357 : else if (strcmp(cmd, "f") == 0)
385 : 4 : status = exec_command_f(scan_state, active_branch);
386 [ + + ]: 5353 : else if (strcmp(cmd, "flush") == 0)
387 : 16 : status = exec_command_flush(scan_state, active_branch);
388 [ + + ]: 5337 : else if (strcmp(cmd, "flushrequest") == 0)
389 : 40 : status = exec_command_flushrequest(scan_state, active_branch);
390 [ + + + + ]: 5297 : else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
391 : 302 : status = exec_command_g(scan_state, active_branch, cmd);
392 [ + + ]: 4995 : else if (strcmp(cmd, "gdesc") == 0)
393 : 57 : status = exec_command_gdesc(scan_state, active_branch);
394 [ + + ]: 4938 : else if (strcmp(cmd, "getenv") == 0)
395 : 227 : status = exec_command_getenv(scan_state, active_branch, cmd);
396 [ + + ]: 4711 : else if (strcmp(cmd, "getresults") == 0)
397 : 128 : status = exec_command_getresults(scan_state, active_branch);
398 [ + + ]: 4583 : else if (strcmp(cmd, "gexec") == 0)
399 : 37 : status = exec_command_gexec(scan_state, active_branch);
400 [ + + ]: 4546 : else if (strcmp(cmd, "gset") == 0)
401 : 599 : status = exec_command_gset(scan_state, active_branch);
402 [ + + + + ]: 3947 : else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
403 : 6 : status = exec_command_help(scan_state, active_branch);
404 [ + - + + ]: 3941 : else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
405 : 4 : status = exec_command_html(scan_state, active_branch);
406 [ + + + - ]: 3937 : else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
407 [ + + - + ]: 3933 : strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
408 : 8 : status = exec_command_include(scan_state, active_branch, cmd);
409 [ + + ]: 3929 : else if (strcmp(cmd, "if") == 0)
410 : 156 : status = exec_command_if(scan_state, cstack, query_buf);
411 [ + + + - ]: 3773 : else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
412 [ + - + - ]: 3769 : strcmp(cmd, "lx") == 0 || strcmp(cmd, "listx") == 0 ||
413 [ + - + - ]: 3769 : strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0 ||
414 [ + - + - ]: 3769 : strcmp(cmd, "lx+") == 0 || strcmp(cmd, "listx+") == 0 ||
415 [ + - - + ]: 3769 : strcmp(cmd, "l+x") == 0 || strcmp(cmd, "list+x") == 0)
416 : 4 : status = exec_command_list(scan_state, active_branch, cmd);
417 [ + + ]: 3769 : else if (strncmp(cmd, "lo_", 3) == 0)
418 : 41 : status = exec_command_lo(scan_state, active_branch, cmd);
419 [ + + - + ]: 3728 : else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
420 : 28 : status = exec_command_out(scan_state, active_branch);
421 [ + + - + ]: 3700 : else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
422 : 28 : status = exec_command_print(scan_state, active_branch,
423 : : query_buf, previous_buf);
424 [ + + ]: 3672 : else if (strcmp(cmd, "parse") == 0)
425 : 75 : status = exec_command_parse(scan_state, active_branch, cmd);
426 [ + + ]: 3597 : else if (strcmp(cmd, "password") == 0)
427 : 5 : status = exec_command_password(scan_state, active_branch);
428 [ + + ]: 3592 : else if (strcmp(cmd, "prompt") == 0)
429 : 4 : status = exec_command_prompt(scan_state, active_branch, cmd);
430 [ + + ]: 3588 : else if (strcmp(cmd, "pset") == 0)
431 : 1246 : status = exec_command_pset(scan_state, active_branch);
432 [ + + + + ]: 2342 : else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
433 : 287 : status = exec_command_quit(scan_state, active_branch);
434 [ + + + + ]: 2055 : else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
435 : 56 : status = exec_command_reset(scan_state, active_branch, query_buf);
436 [ + + ]: 1999 : else if (strcmp(cmd, "restrict") == 0)
437 : 38 : status = exec_command_restrict(scan_state, active_branch, cmd);
438 [ + + ]: 1961 : else if (strcmp(cmd, "s") == 0)
439 : 4 : status = exec_command_s(scan_state, active_branch);
440 [ + + ]: 1957 : else if (strcmp(cmd, "sendpipeline") == 0)
441 : 481 : status = exec_command_sendpipeline(scan_state, active_branch);
442 [ + + ]: 1476 : else if (strcmp(cmd, "set") == 0)
443 : 718 : status = exec_command_set(scan_state, active_branch);
444 [ + + ]: 758 : else if (strcmp(cmd, "setenv") == 0)
445 : 12 : status = exec_command_setenv(scan_state, active_branch, cmd);
446 [ + + + + ]: 746 : else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
447 : 62 : status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
448 [ + + - + ]: 684 : else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
449 : 116 : status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
450 [ + + ]: 568 : else if (strcmp(cmd, "startpipeline") == 0)
451 : 225 : status = exec_command_startpipeline(scan_state, active_branch);
452 [ + + ]: 343 : else if (strcmp(cmd, "syncpipeline") == 0)
453 : 99 : status = exec_command_syncpipeline(scan_state, active_branch);
454 [ + + ]: 244 : else if (strcmp(cmd, "t") == 0)
455 : 52 : status = exec_command_t(scan_state, active_branch);
456 [ + + ]: 192 : else if (strcmp(cmd, "T") == 0)
457 : 4 : status = exec_command_T(scan_state, active_branch);
458 [ + + ]: 188 : else if (strcmp(cmd, "timing") == 0)
459 : 6 : status = exec_command_timing(scan_state, active_branch);
460 [ + + ]: 182 : else if (strcmp(cmd, "unrestrict") == 0)
461 : 37 : status = exec_command_unrestrict(scan_state, active_branch, cmd);
462 [ + + ]: 145 : else if (strcmp(cmd, "unset") == 0)
463 : 34 : status = exec_command_unset(scan_state, active_branch, cmd);
464 [ + + - + ]: 111 : else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
465 : 8 : status = exec_command_write(scan_state, active_branch, cmd,
466 : : query_buf, previous_buf);
467 [ + + ]: 103 : else if (strcmp(cmd, "watch") == 0)
468 : 22 : status = exec_command_watch(scan_state, active_branch,
469 : : query_buf, previous_buf);
470 [ + + ]: 81 : else if (strcmp(cmd, "x") == 0)
471 : 49 : status = exec_command_x(scan_state, active_branch);
472 [ + + ]: 32 : else if (strcmp(cmd, "z") == 0 ||
473 [ + - + + ]: 16 : strcmp(cmd, "zS") == 0 || strcmp(cmd, "zx") == 0 ||
474 [ + - - + ]: 12 : strcmp(cmd, "zSx") == 0 || strcmp(cmd, "zxS") == 0)
475 : 20 : status = exec_command_z(scan_state, active_branch, cmd);
476 [ + + ]: 12 : else if (strcmp(cmd, "!") == 0)
477 : 4 : status = exec_command_shell_escape(scan_state, active_branch);
478 [ + + ]: 8 : else if (strcmp(cmd, "?") == 0)
479 : 4 : status = exec_command_slash_command_help(scan_state, active_branch);
480 : : else
481 : 4 : status = PSQL_CMD_UNKNOWN;
482 : :
483 : : /*
484 : : * All the commands that return PSQL_CMD_SEND want to execute previous_buf
485 : : * if query_buf is empty. For convenience we implement that here, not in
486 : : * the individual command subroutines.
487 : : */
488 [ + + ]: 32468 : if (status == PSQL_CMD_SEND)
489 : 2289 : (void) copy_previous_query(query_buf, previous_buf);
490 : :
491 : 32468 : return status;
492 : : }
493 : :
494 : :
495 : : /*
496 : : * \a -- toggle field alignment
497 : : *
498 : : * This makes little sense but we keep it around.
499 : : */
500 : : static backslashResult
501 : 52 : exec_command_a(PsqlScanState scan_state, bool active_branch)
502 : : {
503 : 52 : bool success = true;
504 : :
505 [ + + ]: 52 : if (active_branch)
506 : : {
507 [ + + ]: 48 : if (pset.popt.topt.format != PRINT_ALIGNED)
508 : 24 : success = do_pset("format", "aligned", &pset.popt, pset.quiet);
509 : : else
510 : 24 : success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
511 : : }
512 : :
513 [ + - ]: 52 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
514 : : }
515 : :
516 : : /*
517 : : * \bind -- set query parameters
518 : : */
519 : : static backslashResult
520 : 532 : exec_command_bind(PsqlScanState scan_state, bool active_branch)
521 : : {
522 : 532 : backslashResult status = PSQL_CMD_SKIP_LINE;
523 : :
524 [ + + ]: 532 : if (active_branch)
525 : : {
526 : : char *opt;
527 : 528 : int nparams = 0;
528 : 528 : int nalloc = 0;
529 : :
530 : 528 : clean_extended_state();
531 : :
532 [ + + ]: 961 : while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
533 : : {
534 : 433 : nparams++;
535 [ + + ]: 433 : if (nparams > nalloc)
536 : : {
537 [ + + ]: 428 : nalloc = nalloc ? nalloc * 2 : 1;
538 : 428 : pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
539 : : }
540 : 433 : pset.bind_params[nparams - 1] = opt;
541 : : }
542 : :
543 : 528 : pset.bind_nparams = nparams;
544 : 528 : pset.send_mode = PSQL_SEND_EXTENDED_QUERY_PARAMS;
545 : : }
546 : : else
547 : 4 : ignore_slash_options(scan_state);
548 : :
549 : 532 : return status;
550 : : }
551 : :
552 : : /*
553 : : * \bind_named -- set query parameters for an existing prepared statement
554 : : */
555 : : static backslashResult
556 : 116 : exec_command_bind_named(PsqlScanState scan_state, bool active_branch,
557 : : const char *cmd)
558 : : {
559 : 116 : backslashResult status = PSQL_CMD_SKIP_LINE;
560 : :
561 [ + + ]: 116 : if (active_branch)
562 : : {
563 : : char *opt;
564 : 112 : int nparams = 0;
565 : 112 : int nalloc = 0;
566 : :
567 : 112 : clean_extended_state();
568 : :
569 : : /* get the mandatory prepared statement name */
570 : 112 : opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
571 [ + + ]: 112 : if (!opt)
572 : : {
573 : 8 : pg_log_error("\\%s: missing required argument", cmd);
574 : 8 : status = PSQL_CMD_ERROR;
575 : : }
576 : : else
577 : : {
578 : 104 : pset.stmtName = opt;
579 : 104 : pset.send_mode = PSQL_SEND_EXTENDED_QUERY_PREPARED;
580 : :
581 : : /* set of parameters */
582 [ + + ]: 218 : while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
583 : : {
584 : 114 : nparams++;
585 [ + - ]: 114 : if (nparams > nalloc)
586 : : {
587 [ + + ]: 114 : nalloc = nalloc ? nalloc * 2 : 1;
588 : 114 : pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
589 : : }
590 : 114 : pset.bind_params[nparams - 1] = opt;
591 : : }
592 : 104 : pset.bind_nparams = nparams;
593 : : }
594 : : }
595 : : else
596 : 4 : ignore_slash_options(scan_state);
597 : :
598 : 116 : return status;
599 : : }
600 : :
601 : : /*
602 : : * \C -- override table title (formerly change HTML caption)
603 : : */
604 : : static backslashResult
605 : 4 : exec_command_C(PsqlScanState scan_state, bool active_branch)
606 : : {
607 : 4 : bool success = true;
608 : :
609 [ - + ]: 4 : if (active_branch)
610 : : {
611 : 0 : char *opt = psql_scan_slash_option(scan_state,
612 : : OT_NORMAL, NULL, true);
613 : :
614 : 0 : success = do_pset("title", opt, &pset.popt, pset.quiet);
615 : 0 : free(opt);
616 : : }
617 : : else
618 : 4 : ignore_slash_options(scan_state);
619 : :
620 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
621 : : }
622 : :
623 : : /*
624 : : * \c or \connect -- connect to database using the specified parameters.
625 : : *
626 : : * \c [-reuse-previous=BOOL] dbname user host port
627 : : *
628 : : * Specifying a parameter as '-' is equivalent to omitting it. Examples:
629 : : *
630 : : * \c - - hst Connect to current database on current port of
631 : : * host "hst" as current user.
632 : : * \c - usr - prt Connect to current database on port "prt" of current host
633 : : * as user "usr".
634 : : * \c dbs Connect to database "dbs" on current port of current host
635 : : * as current user.
636 : : */
637 : : static backslashResult
638 : 226 : exec_command_connect(PsqlScanState scan_state, bool active_branch)
639 : : {
640 : 226 : bool success = true;
641 : :
642 [ + + ]: 226 : if (active_branch)
643 : : {
644 : : static const char prefix[] = "-reuse-previous=";
645 : : char *opt1,
646 : : *opt2,
647 : : *opt3,
648 : : *opt4;
649 : 222 : enum trivalue reuse_previous = TRI_DEFAULT;
650 : :
651 : 222 : opt1 = read_connect_arg(scan_state);
652 [ + + + + ]: 222 : if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
653 : : {
654 : : bool on_off;
655 : :
656 : 11 : success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
657 : : "-reuse-previous",
658 : : &on_off);
659 [ + - ]: 11 : if (success)
660 : : {
661 [ + - ]: 11 : reuse_previous = on_off ? TRI_YES : TRI_NO;
662 : 11 : free(opt1);
663 : 11 : opt1 = read_connect_arg(scan_state);
664 : : }
665 : : }
666 : :
667 [ + - ]: 222 : if (success) /* give up if reuse_previous was invalid */
668 : : {
669 : 222 : opt2 = read_connect_arg(scan_state);
670 : 222 : opt3 = read_connect_arg(scan_state);
671 : 222 : opt4 = read_connect_arg(scan_state);
672 : :
673 : 222 : success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
674 : :
675 : 222 : free(opt2);
676 : 222 : free(opt3);
677 : 222 : free(opt4);
678 : : }
679 : 222 : free(opt1);
680 : : }
681 : : else
682 : 4 : ignore_slash_options(scan_state);
683 : :
684 [ + - ]: 226 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
685 : : }
686 : :
687 : : /*
688 : : * \cd -- change directory
689 : : */
690 : : static backslashResult
691 : 4 : exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
692 : : {
693 : 4 : bool success = true;
694 : :
695 [ - + ]: 4 : if (active_branch)
696 : : {
697 : 0 : char *opt = psql_scan_slash_option(scan_state,
698 : : OT_NORMAL, NULL, true);
699 : : char *dir;
700 : :
701 [ # # ]: 0 : if (opt)
702 : 0 : dir = opt;
703 : : else
704 : : {
705 : : #ifndef WIN32
706 : : /* This should match get_home_path() */
707 : 0 : dir = getenv("HOME");
708 [ # # # # ]: 0 : if (dir == NULL || dir[0] == '\0')
709 : : {
710 : 0 : uid_t user_id = geteuid();
711 : : struct passwd *pw;
712 : :
713 : 0 : errno = 0; /* clear errno before call */
714 : 0 : pw = getpwuid(user_id);
715 [ # # ]: 0 : if (pw)
716 : 0 : dir = pw->pw_dir;
717 : : else
718 : : {
719 [ # # ]: 0 : pg_log_error("could not get home directory for user ID %ld: %s",
720 : : (long) user_id,
721 : : errno ? strerror(errno) : _("user does not exist"));
722 : 0 : success = false;
723 : : }
724 : : }
725 : : #else /* WIN32 */
726 : :
727 : : /*
728 : : * On Windows, 'cd' without arguments prints the current
729 : : * directory, so if someone wants to code this here instead...
730 : : */
731 : : dir = "/";
732 : : #endif /* WIN32 */
733 : : }
734 : :
735 [ # # # # ]: 0 : if (success &&
736 : 0 : chdir(dir) < 0)
737 : : {
738 : 0 : pg_log_error("\\%s: could not change directory to \"%s\": %m",
739 : : cmd, dir);
740 : 0 : success = false;
741 : : }
742 : :
743 : 0 : free(opt);
744 : : }
745 : : else
746 : 4 : ignore_slash_options(scan_state);
747 : :
748 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
749 : : }
750 : :
751 : : /*
752 : : * \close_prepared -- close a previously prepared statement
753 : : */
754 : : static backslashResult
755 : 33 : exec_command_close_prepared(PsqlScanState scan_state, bool active_branch, const char *cmd)
756 : : {
757 : 33 : backslashResult status = PSQL_CMD_SKIP_LINE;
758 : :
759 [ + + ]: 33 : if (active_branch)
760 : : {
761 : 29 : char *opt = psql_scan_slash_option(scan_state,
762 : : OT_NORMAL, NULL, false);
763 : :
764 : 29 : clean_extended_state();
765 : :
766 [ + + ]: 29 : if (!opt)
767 : : {
768 : 4 : pg_log_error("\\%s: missing required argument", cmd);
769 : 4 : status = PSQL_CMD_ERROR;
770 : : }
771 : : else
772 : : {
773 : 25 : pset.stmtName = opt;
774 : 25 : pset.send_mode = PSQL_SEND_EXTENDED_CLOSE;
775 : 25 : status = PSQL_CMD_SEND;
776 : : }
777 : : }
778 : : else
779 : 4 : ignore_slash_options(scan_state);
780 : :
781 : 33 : return status;
782 : : }
783 : :
784 : : /*
785 : : * \conninfo -- display information about the current connection
786 : : */
787 : : static backslashResult
788 : 4 : exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
789 : : {
790 : : printTableContent cont;
791 : : int rows,
792 : : cols;
793 : : char *db;
794 : : char *host;
795 : : bool print_hostaddr;
796 : : char *hostaddr;
797 : : char *protocol_version,
798 : : *backend_pid;
799 : : int ssl_in_use,
800 : : password_used,
801 : : gssapi_used;
802 : : int version_num;
803 : : const char *paramval;
804 : :
805 [ + - ]: 4 : if (!active_branch)
806 : 4 : return PSQL_CMD_SKIP_LINE;
807 : :
808 : 0 : db = PQdb(pset.db);
809 [ # # ]: 0 : if (db == NULL)
810 : : {
811 : 0 : printf(_("You are currently not connected to a database.\n"));
812 : 0 : return PSQL_CMD_SKIP_LINE;
813 : : }
814 : :
815 : : /* Get values for the parameters */
816 : 0 : host = PQhost(pset.db);
817 : 0 : hostaddr = PQhostaddr(pset.db);
818 : 0 : version_num = PQfullProtocolVersion(pset.db);
819 : 0 : protocol_version = psprintf("%d.%d", version_num / 10000,
820 : : version_num % 10000);
821 : 0 : ssl_in_use = PQsslInUse(pset.db);
822 : 0 : password_used = PQconnectionUsedPassword(pset.db);
823 : 0 : gssapi_used = PQconnectionUsedGSSAPI(pset.db);
824 : 0 : backend_pid = psprintf("%d", PQbackendPID(pset.db));
825 : :
826 : : /* Only print hostaddr if it differs from host, and not if unixsock */
827 [ # # ]: 0 : print_hostaddr = (!is_unixsock_path(host) &&
828 [ # # # # : 0 : hostaddr && *hostaddr && strcmp(host, hostaddr) != 0);
# # ]
829 : :
830 : : /* Determine the exact number of rows to print */
831 : 0 : rows = 12;
832 : 0 : cols = 2;
833 [ # # ]: 0 : if (ssl_in_use)
834 : 0 : rows += 6;
835 [ # # ]: 0 : if (print_hostaddr)
836 : 0 : rows++;
837 : :
838 : : /* Set it all up */
839 : 0 : printTableInit(&cont, &pset.popt.topt, _("Connection Information"), cols, rows);
840 : 0 : printTableAddHeader(&cont, _("Parameter"), true, 'l');
841 : 0 : printTableAddHeader(&cont, _("Value"), true, 'l');
842 : :
843 : : /* Database */
844 : 0 : printTableAddCell(&cont, _("Database"), false, false);
845 : 0 : printTableAddCell(&cont, db, false, false);
846 : :
847 : : /* Client User */
848 : 0 : printTableAddCell(&cont, _("Client User"), false, false);
849 : 0 : printTableAddCell(&cont, PQuser(pset.db), false, false);
850 : :
851 : : /* Host/hostaddr/socket */
852 [ # # ]: 0 : if (is_unixsock_path(host))
853 : : {
854 : : /* hostaddr if specified overrides socket, so suppress the latter */
855 [ # # # # ]: 0 : if (hostaddr && *hostaddr)
856 : : {
857 : 0 : printTableAddCell(&cont, _("Host Address"), false, false);
858 : 0 : printTableAddCell(&cont, hostaddr, false, false);
859 : : }
860 : : else
861 : : {
862 : 0 : printTableAddCell(&cont, _("Socket Directory"), false, false);
863 : 0 : printTableAddCell(&cont, host, false, false);
864 : : }
865 : : }
866 : : else
867 : : {
868 : 0 : printTableAddCell(&cont, _("Host"), false, false);
869 : 0 : printTableAddCell(&cont, host, false, false);
870 [ # # ]: 0 : if (print_hostaddr)
871 : : {
872 : 0 : printTableAddCell(&cont, _("Host Address"), false, false);
873 : 0 : printTableAddCell(&cont, hostaddr, false, false);
874 : : }
875 : : }
876 : :
877 : : /* Server Port */
878 : 0 : printTableAddCell(&cont, _("Server Port"), false, false);
879 : 0 : printTableAddCell(&cont, PQport(pset.db), false, false);
880 : :
881 : : /* Options */
882 : 0 : printTableAddCell(&cont, _("Options"), false, false);
883 : 0 : printTableAddCell(&cont, PQoptions(pset.db), false, false);
884 : :
885 : : /* Protocol Version */
886 : 0 : printTableAddCell(&cont, _("Protocol Version"), false, false);
887 : 0 : printTableAddCell(&cont, protocol_version, false, false);
888 : :
889 : : /* Password Used */
890 : 0 : printTableAddCell(&cont, _("Password Used"), false, false);
891 [ # # ]: 0 : printTableAddCell(&cont, password_used ? _("true") : _("false"), false, false);
892 : :
893 : : /* GSSAPI Authenticated */
894 : 0 : printTableAddCell(&cont, _("GSSAPI Authenticated"), false, false);
895 [ # # ]: 0 : printTableAddCell(&cont, gssapi_used ? _("true") : _("false"), false, false);
896 : :
897 : : /* Backend PID */
898 : 0 : printTableAddCell(&cont, _("Backend PID"), false, false);
899 : 0 : printTableAddCell(&cont, backend_pid, false, false);
900 : :
901 : : /* SSL Connection */
902 : 0 : printTableAddCell(&cont, _("SSL Connection"), false, false);
903 [ # # ]: 0 : printTableAddCell(&cont, ssl_in_use ? _("true") : _("false"), false, false);
904 : :
905 : : /* SSL Information */
906 [ # # ]: 0 : if (ssl_in_use)
907 : : {
908 : : const char *library,
909 : : *protocol,
910 : : *key_bits,
911 : : *cipher,
912 : : *compression,
913 : : *alpn;
914 : :
915 : 0 : library = PQsslAttribute(pset.db, "library");
916 : 0 : protocol = PQsslAttribute(pset.db, "protocol");
917 : 0 : key_bits = PQsslAttribute(pset.db, "key_bits");
918 : 0 : cipher = PQsslAttribute(pset.db, "cipher");
919 : 0 : compression = PQsslAttribute(pset.db, "compression");
920 : 0 : alpn = PQsslAttribute(pset.db, "alpn");
921 : :
922 : 0 : printTableAddCell(&cont, _("SSL Library"), false, false);
923 [ # # ]: 0 : printTableAddCell(&cont, library ? library : _("unknown"), false, false);
924 : :
925 : 0 : printTableAddCell(&cont, _("SSL Protocol"), false, false);
926 [ # # ]: 0 : printTableAddCell(&cont, protocol ? protocol : _("unknown"), false, false);
927 : :
928 : 0 : printTableAddCell(&cont, _("SSL Key Bits"), false, false);
929 [ # # ]: 0 : printTableAddCell(&cont, key_bits ? key_bits : _("unknown"), false, false);
930 : :
931 : 0 : printTableAddCell(&cont, _("SSL Cipher"), false, false);
932 [ # # ]: 0 : printTableAddCell(&cont, cipher ? cipher : _("unknown"), false, false);
933 : :
934 : 0 : printTableAddCell(&cont, _("SSL Compression"), false, false);
935 [ # # # # ]: 0 : printTableAddCell(&cont, (compression && strcmp(compression, "off") != 0) ?
936 : 0 : _("true") : _("false"), false, false);
937 : :
938 : 0 : printTableAddCell(&cont, _("ALPN"), false, false);
939 [ # # # # ]: 0 : printTableAddCell(&cont, (alpn && alpn[0] != '\0') ? alpn : _("none"), false, false);
940 : : }
941 : :
942 : 0 : paramval = PQparameterStatus(pset.db, "is_superuser");
943 : 0 : printTableAddCell(&cont, "Superuser", false, false);
944 [ # # ]: 0 : printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
945 : :
946 : 0 : paramval = PQparameterStatus(pset.db, "in_hot_standby");
947 : 0 : printTableAddCell(&cont, "Hot Standby", false, false);
948 [ # # ]: 0 : printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
949 : :
950 : 0 : printTable(&cont, pset.queryFout, false, pset.logfile);
951 : 0 : printTableCleanup(&cont);
952 : :
953 : 0 : pfree(protocol_version);
954 : 0 : pfree(backend_pid);
955 : :
956 : 0 : return PSQL_CMD_SKIP_LINE;
957 : : }
958 : :
959 : : /*
960 : : * \copy -- run a COPY command
961 : : */
962 : : static backslashResult
963 : 103 : exec_command_copy(PsqlScanState scan_state, bool active_branch)
964 : : {
965 : 103 : bool success = true;
966 : :
967 [ + + ]: 103 : if (active_branch)
968 : : {
969 : 99 : char *opt = psql_scan_slash_option(scan_state,
970 : : OT_WHOLE_LINE, NULL, false);
971 : :
972 : 99 : success = do_copy(opt);
973 : 99 : free(opt);
974 : : }
975 : : else
976 : 4 : ignore_slash_whole_line(scan_state);
977 : :
978 [ + + ]: 103 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
979 : : }
980 : :
981 : : /*
982 : : * \copyright -- print copyright notice
983 : : */
984 : : static backslashResult
985 : 5 : exec_command_copyright(PsqlScanState scan_state, bool active_branch)
986 : : {
987 [ + + ]: 5 : if (active_branch)
988 : 1 : print_copyright();
989 : :
990 : 5 : return PSQL_CMD_SKIP_LINE;
991 : : }
992 : :
993 : : /*
994 : : * \crosstabview -- execute a query and display result in crosstab
995 : : */
996 : : static backslashResult
997 : 100 : exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
998 : : {
999 : 100 : backslashResult status = PSQL_CMD_SKIP_LINE;
1000 : :
1001 [ + + ]: 100 : if (active_branch)
1002 : : {
1003 [ + + ]: 480 : for (size_t i = 0; i < lengthof(pset.ctv_args); i++)
1004 : 384 : pset.ctv_args[i] = psql_scan_slash_option(scan_state,
1005 : : OT_NORMAL, NULL, true);
1006 : 96 : pset.crosstab_flag = true;
1007 : 96 : status = PSQL_CMD_SEND;
1008 : : }
1009 : : else
1010 : 4 : ignore_slash_options(scan_state);
1011 : :
1012 : 100 : return status;
1013 : : }
1014 : :
1015 : : /*
1016 : : * \d* commands
1017 : : */
1018 : : static backslashResult
1019 : 4793 : exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
1020 : : {
1021 : 4793 : backslashResult status = PSQL_CMD_SKIP_LINE;
1022 : 4793 : bool success = true;
1023 : :
1024 [ + + ]: 4793 : if (active_branch)
1025 : : {
1026 : : char *pattern;
1027 : : bool show_verbose,
1028 : : show_system;
1029 : : unsigned short int save_expanded;
1030 : :
1031 : : /* We don't do SQLID reduction on the pattern yet */
1032 : 4789 : pattern = psql_scan_slash_option(scan_state,
1033 : : OT_NORMAL, NULL, true);
1034 : :
1035 : 4789 : show_verbose = strchr(cmd, '+') ? true : false;
1036 : 4789 : show_system = strchr(cmd, 'S') ? true : false;
1037 : :
1038 : : /*
1039 : : * The 'x' option turns expanded mode on for this command only. This
1040 : : * is allowed in all \d* commands, except \d by itself, since \dx is a
1041 : : * separate command. So the 'x' option cannot appear immediately after
1042 : : * \d, but it can appear after \d followed by other options.
1043 : : */
1044 : 4789 : save_expanded = pset.popt.topt.expanded;
1045 [ + + + + ]: 4789 : if (cmd[1] != '\0' && strchr(&cmd[2], 'x'))
1046 : 20 : pset.popt.topt.expanded = 1;
1047 : :
1048 [ + + + + : 4789 : switch (cmd[1])
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
1049 : : {
1050 : 2782 : case '\0':
1051 : : case '+':
1052 : : case 'S':
1053 [ + + ]: 2782 : if (pattern)
1054 : 2770 : success = describeTableDetails(pattern, show_verbose, show_system);
1055 : : else
1056 : : /* standard listing of interesting things */
1057 : 12 : success = listTables("tvmsEG", NULL, show_verbose, show_system);
1058 : 2782 : break;
1059 : 148 : case 'A':
1060 : : {
1061 : 148 : char *pattern2 = NULL;
1062 : :
1063 [ + + + + : 148 : if (pattern && cmd[2] != '\0' && cmd[2] != '+' && cmd[2] != 'x')
+ + + - ]
1064 : 96 : pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
1065 : :
1066 [ + + + + : 148 : switch (cmd[2])
+ - ]
1067 : : {
1068 : 52 : case '\0':
1069 : : case '+':
1070 : : case 'x':
1071 : 52 : success = describeAccessMethods(pattern, show_verbose);
1072 : 52 : break;
1073 : 20 : case 'c':
1074 : 20 : success = listOperatorClasses(pattern, pattern2, show_verbose);
1075 : 20 : break;
1076 : 24 : case 'f':
1077 : 24 : success = listOperatorFamilies(pattern, pattern2, show_verbose);
1078 : 24 : break;
1079 : 24 : case 'o':
1080 : 24 : success = listOpFamilyOperators(pattern, pattern2, show_verbose);
1081 : 24 : break;
1082 : 28 : case 'p':
1083 : 28 : success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
1084 : 28 : break;
1085 : 0 : default:
1086 : 0 : status = PSQL_CMD_UNKNOWN;
1087 : 0 : break;
1088 : : }
1089 : :
1090 : 148 : free(pattern2);
1091 : : }
1092 : 148 : break;
1093 : 36 : case 'a':
1094 : 36 : success = describeAggregates(pattern, show_verbose, show_system);
1095 : 36 : break;
1096 : 16 : case 'b':
1097 : 16 : success = describeTablespaces(pattern, show_verbose);
1098 : 16 : break;
1099 : 36 : case 'c':
1100 [ + + ]: 36 : if (strncmp(cmd, "dconfig", 7) == 0)
1101 : 8 : success = describeConfigurationParameters(pattern,
1102 : : show_verbose,
1103 : : show_system);
1104 : : else
1105 : 28 : success = listConversions(pattern,
1106 : : show_verbose,
1107 : : show_system);
1108 : 36 : break;
1109 : 28 : case 'C':
1110 : 28 : success = listCasts(pattern, show_verbose);
1111 : 28 : break;
1112 : 52 : case 'd':
1113 [ + + ]: 52 : if (strncmp(cmd, "ddp", 3) == 0)
1114 : 24 : success = listDefaultACLs(pattern);
1115 : : else
1116 : 28 : success = objectDescription(pattern, show_system);
1117 : 52 : break;
1118 : 40 : case 'D':
1119 : 40 : success = listDomains(pattern, show_verbose, show_system);
1120 : 40 : break;
1121 : 205 : case 'f': /* function subsystem */
1122 [ + - ]: 205 : switch (cmd[2])
1123 : : {
1124 : 205 : case '\0':
1125 : : case '+':
1126 : : case 'S':
1127 : : case 'a':
1128 : : case 'n':
1129 : : case 'p':
1130 : : case 't':
1131 : : case 'w':
1132 : : case 'x':
1133 : 205 : success = exec_command_dfo(scan_state, cmd, pattern,
1134 : : show_verbose, show_system);
1135 : 205 : break;
1136 : 0 : default:
1137 : 0 : status = PSQL_CMD_UNKNOWN;
1138 : 0 : break;
1139 : : }
1140 : 205 : break;
1141 : 16 : case 'g':
1142 : : /* no longer distinct from \du */
1143 : 16 : success = describeRoles(pattern, show_verbose, show_system);
1144 : 16 : break;
1145 : 4 : case 'l':
1146 : 4 : success = listLargeObjects(show_verbose);
1147 : 4 : break;
1148 : 20 : case 'L':
1149 : 20 : success = listLanguages(pattern, show_verbose, show_system);
1150 : 20 : break;
1151 : 20 : case 'n':
1152 : 20 : success = listSchemas(pattern, show_verbose, show_system);
1153 : 20 : break;
1154 : 44 : case 'o':
1155 : 44 : success = exec_command_dfo(scan_state, cmd, pattern,
1156 : : show_verbose, show_system);
1157 : 44 : break;
1158 : 32 : case 'O':
1159 : 32 : success = listCollations(pattern, show_verbose, show_system);
1160 : 32 : break;
1161 : 52 : case 'p':
1162 : 52 : success = permissionsList(pattern, show_system);
1163 : 52 : break;
1164 : 72 : case 'P':
1165 : : {
1166 [ + - ]: 72 : switch (cmd[2])
1167 : : {
1168 : 72 : case '\0':
1169 : : case '+':
1170 : : case 't':
1171 : : case 'i':
1172 : : case 'n':
1173 : : case 'x':
1174 : 72 : success = listPartitionedTables(&cmd[2], pattern, show_verbose);
1175 : 72 : break;
1176 : 0 : default:
1177 : 0 : status = PSQL_CMD_UNKNOWN;
1178 : 0 : break;
1179 : : }
1180 : : }
1181 : 72 : break;
1182 : 47 : case 'T':
1183 : 47 : success = describeTypes(pattern, show_verbose, show_system);
1184 : 47 : break;
1185 : 244 : case 't':
1186 : : case 'v':
1187 : : case 'm':
1188 : : case 'i':
1189 : : case 's':
1190 : : case 'E':
1191 : : case 'G':
1192 : 244 : success = listTables(&cmd[1], pattern, show_verbose, show_system);
1193 : 244 : break;
1194 : 21 : case 'r':
1195 [ + + + - ]: 21 : if (cmd[2] == 'd' && cmd[3] == 's')
1196 : 17 : {
1197 : 17 : char *pattern2 = NULL;
1198 : :
1199 [ + + ]: 17 : if (pattern)
1200 : 16 : pattern2 = psql_scan_slash_option(scan_state,
1201 : : OT_NORMAL, NULL, true);
1202 : 17 : success = listDbRoleSettings(pattern, pattern2);
1203 : :
1204 : 17 : free(pattern2);
1205 : : }
1206 [ + - ]: 4 : else if (cmd[2] == 'g')
1207 : 4 : success = describeRoleGrants(pattern, show_system);
1208 : : else
1209 : 0 : status = PSQL_CMD_UNKNOWN;
1210 : 21 : break;
1211 : 420 : case 'R':
1212 [ + + - ]: 420 : switch (cmd[2])
1213 : : {
1214 : 308 : case 'p':
1215 [ + + ]: 308 : if (show_verbose)
1216 : 276 : success = describePublications(pattern);
1217 : : else
1218 : 32 : success = listPublications(pattern);
1219 : 308 : break;
1220 : 112 : case 's':
1221 : 112 : success = describeSubscriptions(pattern, show_verbose);
1222 : 112 : break;
1223 : 0 : default:
1224 : 0 : status = PSQL_CMD_UNKNOWN;
1225 : : }
1226 : 420 : break;
1227 : 4 : case 'u':
1228 : 4 : success = describeRoles(pattern, show_verbose, show_system);
1229 : 4 : break;
1230 : 128 : case 'F': /* text search subsystem */
1231 [ + + + + : 128 : switch (cmd[2])
- ]
1232 : : {
1233 : 32 : case '\0':
1234 : : case '+':
1235 : : case 'x':
1236 : 32 : success = listTSConfigs(pattern, show_verbose);
1237 : 32 : break;
1238 : 32 : case 'p':
1239 : 32 : success = listTSParsers(pattern, show_verbose);
1240 : 32 : break;
1241 : 32 : case 'd':
1242 : 32 : success = listTSDictionaries(pattern, show_verbose);
1243 : 32 : break;
1244 : 32 : case 't':
1245 : 32 : success = listTSTemplates(pattern, show_verbose);
1246 : 32 : break;
1247 : 0 : default:
1248 : 0 : status = PSQL_CMD_UNKNOWN;
1249 : 0 : break;
1250 : : }
1251 : 128 : break;
1252 : 206 : case 'e': /* SQL/MED subsystem */
1253 [ + + + + : 206 : switch (cmd[2])
- ]
1254 : : {
1255 : 80 : case 's':
1256 : 80 : success = listForeignServers(pattern, show_verbose);
1257 : 80 : break;
1258 : 40 : case 'u':
1259 : 40 : success = listUserMappings(pattern, show_verbose);
1260 : 40 : break;
1261 : 76 : case 'w':
1262 : 76 : success = listForeignDataWrappers(pattern, show_verbose);
1263 : 76 : break;
1264 : 10 : case 't':
1265 : 10 : success = listForeignTables(pattern, show_verbose);
1266 : 10 : break;
1267 : 0 : default:
1268 : 0 : status = PSQL_CMD_UNKNOWN;
1269 : 0 : break;
1270 : : }
1271 : 206 : break;
1272 : 32 : case 'x': /* Extensions */
1273 [ + + ]: 32 : if (show_verbose)
1274 : 16 : success = listExtensionContents(pattern);
1275 : : else
1276 : 16 : success = listExtensions(pattern);
1277 : 32 : break;
1278 : 68 : case 'X': /* Extended Statistics */
1279 : 68 : success = listExtendedStats(pattern, show_verbose);
1280 : 68 : break;
1281 : 16 : case 'y': /* Event Triggers */
1282 : 16 : success = listEventTriggers(pattern, show_verbose);
1283 : 16 : break;
1284 : 0 : default:
1285 : 0 : status = PSQL_CMD_UNKNOWN;
1286 : : }
1287 : :
1288 : : /* Restore original expanded mode */
1289 : 4789 : pset.popt.topt.expanded = save_expanded;
1290 : :
1291 : 4789 : free(pattern);
1292 : : }
1293 : : else
1294 : 4 : ignore_slash_options(scan_state);
1295 : :
1296 [ + + ]: 4793 : if (!success)
1297 : 620 : status = PSQL_CMD_ERROR;
1298 : :
1299 : 4793 : return status;
1300 : : }
1301 : :
1302 : : /* \df and \do; messy enough to split out of exec_command_d */
1303 : : static bool
1304 : 249 : exec_command_dfo(PsqlScanState scan_state, const char *cmd,
1305 : : const char *pattern,
1306 : : bool show_verbose, bool show_system)
1307 : : {
1308 : : bool success;
1309 : : char *arg_patterns[FUNC_MAX_ARGS];
1310 : 249 : int num_arg_patterns = 0;
1311 : :
1312 : : /* Collect argument-type patterns too */
1313 [ + + ]: 249 : if (pattern) /* otherwise it was just \df or \do */
1314 : : {
1315 : : char *ap;
1316 : :
1317 : 303 : while ((ap = psql_scan_slash_option(scan_state,
1318 [ + + ]: 303 : OT_NORMAL, NULL, true)) != NULL)
1319 : : {
1320 : 56 : arg_patterns[num_arg_patterns++] = ap;
1321 [ - + ]: 56 : if (num_arg_patterns >= FUNC_MAX_ARGS)
1322 : 0 : break; /* protect limited-size array */
1323 : : }
1324 : : }
1325 : :
1326 [ + + ]: 249 : if (cmd[1] == 'f')
1327 : 205 : success = describeFunctions(&cmd[2], pattern,
1328 : : arg_patterns, num_arg_patterns,
1329 : : show_verbose, show_system);
1330 : : else
1331 : 44 : success = describeOperators(pattern,
1332 : : arg_patterns, num_arg_patterns,
1333 : : show_verbose, show_system);
1334 : :
1335 [ + + ]: 305 : while (--num_arg_patterns >= 0)
1336 : 56 : free(arg_patterns[num_arg_patterns]);
1337 : :
1338 : 249 : return success;
1339 : : }
1340 : :
1341 : : /*
1342 : : * \e or \edit -- edit the current query buffer, or edit a file and
1343 : : * make it the query buffer
1344 : : */
1345 : : static backslashResult
1346 : 4 : exec_command_edit(PsqlScanState scan_state, bool active_branch,
1347 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
1348 : : {
1349 : 4 : backslashResult status = PSQL_CMD_SKIP_LINE;
1350 : :
1351 [ - + ]: 4 : if (active_branch)
1352 : : {
1353 [ # # ]: 0 : if (!query_buf)
1354 : : {
1355 : 0 : pg_log_error("no query buffer");
1356 : 0 : status = PSQL_CMD_ERROR;
1357 : : }
1358 : : else
1359 : : {
1360 : : char *fname;
1361 : 0 : char *ln = NULL;
1362 : 0 : int lineno = -1;
1363 : :
1364 : 0 : fname = psql_scan_slash_option(scan_state,
1365 : : OT_NORMAL, NULL, true);
1366 [ # # ]: 0 : if (fname)
1367 : : {
1368 : : /* try to get separate lineno arg */
1369 : 0 : ln = psql_scan_slash_option(scan_state,
1370 : : OT_NORMAL, NULL, true);
1371 [ # # ]: 0 : if (ln == NULL)
1372 : : {
1373 : : /* only one arg; maybe it is lineno not fname */
1374 [ # # ]: 0 : if (fname[0] &&
1375 [ # # ]: 0 : strspn(fname, "0123456789") == strlen(fname))
1376 : : {
1377 : : /* all digits, so assume it is lineno */
1378 : 0 : ln = fname;
1379 : 0 : fname = NULL;
1380 : : }
1381 : : }
1382 : : }
1383 [ # # ]: 0 : if (ln)
1384 : : {
1385 : 0 : lineno = atoi(ln);
1386 [ # # ]: 0 : if (lineno < 1)
1387 : : {
1388 : 0 : pg_log_error("invalid line number: %s", ln);
1389 : 0 : status = PSQL_CMD_ERROR;
1390 : : }
1391 : : }
1392 [ # # ]: 0 : if (status != PSQL_CMD_ERROR)
1393 : : {
1394 : : bool discard_on_quit;
1395 : :
1396 : 0 : expand_tilde(&fname);
1397 [ # # ]: 0 : if (fname)
1398 : : {
1399 : 0 : canonicalize_path_enc(fname, pset.encoding);
1400 : : /* Always clear buffer if the file isn't modified */
1401 : 0 : discard_on_quit = true;
1402 : : }
1403 : : else
1404 : : {
1405 : : /*
1406 : : * If query_buf is empty, recall previous query for
1407 : : * editing. But in that case, the query buffer should be
1408 : : * emptied if editing doesn't modify the file.
1409 : : */
1410 : 0 : discard_on_quit = copy_previous_query(query_buf,
1411 : : previous_buf);
1412 : : }
1413 : :
1414 [ # # ]: 0 : if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1415 : 0 : status = PSQL_CMD_NEWEDIT;
1416 : : else
1417 : 0 : status = PSQL_CMD_ERROR;
1418 : : }
1419 : :
1420 : : /*
1421 : : * On error while editing or if specifying an incorrect line
1422 : : * number, reset the query buffer.
1423 : : */
1424 [ # # ]: 0 : if (status == PSQL_CMD_ERROR)
1425 : 0 : resetPQExpBuffer(query_buf);
1426 : :
1427 : 0 : free(fname);
1428 : 0 : free(ln);
1429 : : }
1430 : : }
1431 : : else
1432 : 4 : ignore_slash_options(scan_state);
1433 : :
1434 : 4 : return status;
1435 : : }
1436 : :
1437 : : /*
1438 : : * \ef/\ev -- edit the named function/view, or
1439 : : * present a blank CREATE FUNCTION/VIEW template if no argument is given
1440 : : */
1441 : : static backslashResult
1442 : 8 : exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
1443 : : PQExpBuffer query_buf, bool is_func)
1444 : : {
1445 : 8 : backslashResult status = PSQL_CMD_SKIP_LINE;
1446 : :
1447 [ - + ]: 8 : if (active_branch)
1448 : : {
1449 : 0 : char *obj_desc = psql_scan_slash_option(scan_state,
1450 : : OT_WHOLE_LINE,
1451 : : NULL, true);
1452 : 0 : int lineno = -1;
1453 : :
1454 [ # # ]: 0 : if (!query_buf)
1455 : : {
1456 : 0 : pg_log_error("no query buffer");
1457 : 0 : status = PSQL_CMD_ERROR;
1458 : : }
1459 : : else
1460 : : {
1461 : 0 : Oid obj_oid = InvalidOid;
1462 : 0 : EditableObjectType eot = is_func ? EditableFunction : EditableView;
1463 : :
1464 : 0 : lineno = strip_lineno_from_objdesc(obj_desc);
1465 [ # # ]: 0 : if (lineno == 0)
1466 : : {
1467 : : /* error already reported */
1468 : 0 : status = PSQL_CMD_ERROR;
1469 : : }
1470 [ # # ]: 0 : else if (!obj_desc)
1471 : : {
1472 : : /* set up an empty command to fill in */
1473 : 0 : resetPQExpBuffer(query_buf);
1474 [ # # ]: 0 : if (is_func)
1475 : 0 : appendPQExpBufferStr(query_buf,
1476 : : "CREATE FUNCTION ( )\n"
1477 : : " RETURNS \n"
1478 : : " LANGUAGE \n"
1479 : : " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1480 : : "AS $function$\n"
1481 : : "\n$function$\n");
1482 : : else
1483 : 0 : appendPQExpBufferStr(query_buf,
1484 : : "CREATE VIEW AS\n"
1485 : : " SELECT \n"
1486 : : " -- something...\n");
1487 : : }
1488 [ # # ]: 0 : else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1489 : : {
1490 : : /* error already reported */
1491 : 0 : status = PSQL_CMD_ERROR;
1492 : : }
1493 [ # # ]: 0 : else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1494 : : {
1495 : : /* error already reported */
1496 : 0 : status = PSQL_CMD_ERROR;
1497 : : }
1498 [ # # # # ]: 0 : else if (is_func && lineno > 0)
1499 : : {
1500 : : /*
1501 : : * lineno "1" should correspond to the first line of the
1502 : : * function body. We expect that pg_get_functiondef() will
1503 : : * emit that on a line beginning with "AS ", "BEGIN ", or
1504 : : * "RETURN ", and that there can be no such line before the
1505 : : * real start of the function body. Increment lineno by the
1506 : : * number of lines before that line, so that it becomes
1507 : : * relative to the first line of the function definition.
1508 : : */
1509 : 0 : const char *lines = query_buf->data;
1510 : :
1511 [ # # ]: 0 : while (*lines != '\0')
1512 : : {
1513 [ # # ]: 0 : if (strncmp(lines, "AS ", 3) == 0 ||
1514 [ # # ]: 0 : strncmp(lines, "BEGIN ", 6) == 0 ||
1515 [ # # ]: 0 : strncmp(lines, "RETURN ", 7) == 0)
1516 : : break;
1517 : 0 : lineno++;
1518 : : /* find start of next line */
1519 : 0 : lines = strchr(lines, '\n');
1520 [ # # ]: 0 : if (!lines)
1521 : 0 : break;
1522 : 0 : lines++;
1523 : : }
1524 : : }
1525 : : }
1526 : :
1527 [ # # ]: 0 : if (status != PSQL_CMD_ERROR)
1528 : : {
1529 : 0 : bool edited = false;
1530 : :
1531 [ # # ]: 0 : if (!do_edit(NULL, query_buf, lineno, true, &edited))
1532 : 0 : status = PSQL_CMD_ERROR;
1533 [ # # ]: 0 : else if (!edited)
1534 : 0 : puts(_("No changes"));
1535 : : else
1536 : 0 : status = PSQL_CMD_NEWEDIT;
1537 : : }
1538 : :
1539 : : /*
1540 : : * On error while doing object lookup or while editing, or if
1541 : : * specifying an incorrect line number, reset the query buffer.
1542 : : */
1543 [ # # ]: 0 : if (status == PSQL_CMD_ERROR)
1544 : 0 : resetPQExpBuffer(query_buf);
1545 : :
1546 : 0 : free(obj_desc);
1547 : : }
1548 : : else
1549 : 8 : ignore_slash_whole_line(scan_state);
1550 : :
1551 : 8 : return status;
1552 : : }
1553 : :
1554 : : /*
1555 : : * \echo, \qecho, and \warn -- echo arguments to stdout, query output, or stderr
1556 : : */
1557 : : static backslashResult
1558 : 20619 : exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
1559 : : {
1560 [ + + ]: 20619 : if (active_branch)
1561 : : {
1562 : : char *value;
1563 : : char quoted;
1564 : 20523 : bool no_newline = false;
1565 : 20523 : bool first = true;
1566 : : FILE *fout;
1567 : :
1568 [ + + ]: 20523 : if (strcmp(cmd, "qecho") == 0)
1569 : 20 : fout = pset.queryFout;
1570 [ + + ]: 20503 : else if (strcmp(cmd, "warn") == 0)
1571 : 10001 : fout = stderr;
1572 : : else
1573 : 10502 : fout = stdout;
1574 : :
1575 [ + + ]: 41368 : while ((value = psql_scan_slash_option(scan_state,
1576 : : OT_NORMAL, "ed, false)))
1577 : : {
1578 [ + + + + : 20845 : if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
+ + + + ]
1579 : 4 : no_newline = true;
1580 : : else
1581 : : {
1582 [ + + ]: 20841 : if (first)
1583 : 20523 : first = false;
1584 : : else
1585 : 318 : fputc(' ', fout);
1586 : 20841 : fputs(value, fout);
1587 : : }
1588 : 20845 : free(value);
1589 : : }
1590 [ + + ]: 20523 : if (!no_newline)
1591 : 20519 : fputs("\n", fout);
1592 : : }
1593 : : else
1594 : 96 : ignore_slash_options(scan_state);
1595 : :
1596 : 20619 : return PSQL_CMD_SKIP_LINE;
1597 : : }
1598 : :
1599 : : /*
1600 : : * \encoding -- set/show client side encoding
1601 : : */
1602 : : static backslashResult
1603 : 12 : exec_command_encoding(PsqlScanState scan_state, bool active_branch)
1604 : : {
1605 [ + + ]: 12 : if (active_branch)
1606 : : {
1607 : 8 : char *encoding = psql_scan_slash_option(scan_state,
1608 : : OT_NORMAL, NULL, false);
1609 : :
1610 [ - + ]: 8 : if (!encoding)
1611 : : {
1612 : : /* show encoding */
1613 : 0 : puts(pg_encoding_to_char(pset.encoding));
1614 : : }
1615 : : else
1616 : : {
1617 : : /* set encoding */
1618 [ - + ]: 8 : if (PQsetClientEncoding(pset.db, encoding) == -1)
1619 : 0 : pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1620 : : else
1621 : : {
1622 : : /* save encoding info into psql internal data */
1623 : 8 : pset.encoding = PQclientEncoding(pset.db);
1624 : 8 : pset.popt.topt.encoding = pset.encoding;
1625 : 8 : setFmtEncoding(pset.encoding);
1626 : 8 : SetVariable(pset.vars, "ENCODING",
1627 : : pg_encoding_to_char(pset.encoding));
1628 : : }
1629 : 8 : free(encoding);
1630 : : }
1631 : : }
1632 : : else
1633 : 4 : ignore_slash_options(scan_state);
1634 : :
1635 : 12 : return PSQL_CMD_SKIP_LINE;
1636 : : }
1637 : :
1638 : : /*
1639 : : * \errverbose -- display verbose message from last failed query
1640 : : */
1641 : : static backslashResult
1642 : 8 : exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
1643 : : {
1644 [ + + ]: 8 : if (active_branch)
1645 : : {
1646 [ + + ]: 4 : if (pset.last_error_result)
1647 : : {
1648 : : char *msg;
1649 : :
1650 : 3 : msg = PQresultVerboseErrorMessage(pset.last_error_result,
1651 : : PQERRORS_VERBOSE,
1652 : : PQSHOW_CONTEXT_ALWAYS);
1653 [ + - ]: 3 : if (msg)
1654 : : {
1655 : 3 : pg_log_error("%s", msg);
1656 : 3 : PQfreemem(msg);
1657 : : }
1658 : : else
1659 : 0 : puts(_("out of memory"));
1660 : : }
1661 : : else
1662 : 1 : puts(_("There is no previous error."));
1663 : : }
1664 : :
1665 : 8 : return PSQL_CMD_SKIP_LINE;
1666 : : }
1667 : :
1668 : : /*
1669 : : * \f -- change field separator
1670 : : */
1671 : : static backslashResult
1672 : 4 : exec_command_f(PsqlScanState scan_state, bool active_branch)
1673 : : {
1674 : 4 : bool success = true;
1675 : :
1676 [ - + ]: 4 : if (active_branch)
1677 : : {
1678 : 0 : char *fname = psql_scan_slash_option(scan_state,
1679 : : OT_NORMAL, NULL, false);
1680 : :
1681 : 0 : success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1682 : 0 : free(fname);
1683 : : }
1684 : : else
1685 : 4 : ignore_slash_options(scan_state);
1686 : :
1687 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1688 : : }
1689 : :
1690 : : /*
1691 : : * \flush -- call PQflush() on the connection
1692 : : */
1693 : : static backslashResult
1694 : 16 : exec_command_flush(PsqlScanState scan_state, bool active_branch)
1695 : : {
1696 : 16 : backslashResult status = PSQL_CMD_SKIP_LINE;
1697 : :
1698 [ + + ]: 16 : if (active_branch)
1699 : : {
1700 : 12 : pset.send_mode = PSQL_SEND_FLUSH;
1701 : 12 : status = PSQL_CMD_SEND;
1702 : : }
1703 : : else
1704 : 4 : ignore_slash_options(scan_state);
1705 : :
1706 : 16 : return status;
1707 : : }
1708 : :
1709 : : /*
1710 : : * \flushrequest -- call PQsendFlushRequest() on the connection
1711 : : */
1712 : : static backslashResult
1713 : 40 : exec_command_flushrequest(PsqlScanState scan_state, bool active_branch)
1714 : : {
1715 : 40 : backslashResult status = PSQL_CMD_SKIP_LINE;
1716 : :
1717 [ + + ]: 40 : if (active_branch)
1718 : : {
1719 : 36 : pset.send_mode = PSQL_SEND_FLUSH_REQUEST;
1720 : 36 : status = PSQL_CMD_SEND;
1721 : : }
1722 : : else
1723 : 4 : ignore_slash_options(scan_state);
1724 : :
1725 : 40 : return status;
1726 : : }
1727 : :
1728 : : /*
1729 : : * \g [(pset-option[=pset-value] ...)] [filename/shell-command]
1730 : : * \gx [(pset-option[=pset-value] ...)] [filename/shell-command]
1731 : : *
1732 : : * Send the current query. If pset options are specified, they are made
1733 : : * active just for this query. If a filename or pipe command is given,
1734 : : * the query output goes there. \gx implicitly sets "expanded=on" along
1735 : : * with any other pset options that are specified.
1736 : : */
1737 : : static backslashResult
1738 : 302 : exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
1739 : : {
1740 : 302 : backslashResult status = PSQL_CMD_SKIP_LINE;
1741 : : char *fname;
1742 : :
1743 : : /*
1744 : : * Because the option processing for this is fairly complicated, we do it
1745 : : * and then decide whether the branch is active.
1746 : : */
1747 : 302 : fname = psql_scan_slash_option(scan_state,
1748 : : OT_FILEPIPE, NULL, false);
1749 : :
1750 [ + + + + ]: 302 : if (fname && fname[0] == '(')
1751 : : {
1752 : : /* Consume pset options through trailing ')' ... */
1753 : 16 : status = process_command_g_options(fname + 1, scan_state,
1754 : : active_branch, cmd);
1755 : 16 : free(fname);
1756 : : /* ... and again attempt to scan the filename. */
1757 : 16 : fname = psql_scan_slash_option(scan_state,
1758 : : OT_FILEPIPE, NULL, false);
1759 : : }
1760 : :
1761 [ + - + + ]: 302 : if (status == PSQL_CMD_SKIP_LINE && active_branch)
1762 : : {
1763 [ + + ]: 286 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1764 : : {
1765 : 24 : pg_log_error("\\%s not allowed in pipeline mode", cmd);
1766 : 24 : clean_extended_state();
1767 : 24 : free(fname);
1768 : 24 : return PSQL_CMD_ERROR;
1769 : : }
1770 : :
1771 [ + + ]: 262 : if (!fname)
1772 : 242 : pset.gfname = NULL;
1773 : : else
1774 : : {
1775 : 20 : expand_tilde(&fname);
1776 : 20 : pset.gfname = pg_strdup(fname);
1777 : : }
1778 [ + + ]: 262 : if (strcmp(cmd, "gx") == 0)
1779 : : {
1780 : : /* save settings if not done already, then force expanded=on */
1781 [ + + ]: 86 : if (pset.gsavepopt == NULL)
1782 : 82 : pset.gsavepopt = savePsetInfo(&pset.popt);
1783 : 86 : pset.popt.topt.expanded = 1;
1784 : : }
1785 : 262 : status = PSQL_CMD_SEND;
1786 : : }
1787 : :
1788 : 278 : free(fname);
1789 : :
1790 : 278 : return status;
1791 : : }
1792 : :
1793 : : /*
1794 : : * Process parenthesized pset options for \g
1795 : : *
1796 : : * Note: okay to modify first_option, but not to free it; caller does that
1797 : : */
1798 : : static backslashResult
1799 : 16 : process_command_g_options(char *first_option, PsqlScanState scan_state,
1800 : : bool active_branch, const char *cmd)
1801 : : {
1802 : 16 : bool success = true;
1803 : 16 : bool found_r_paren = false;
1804 : :
1805 : : do
1806 : : {
1807 : : char *option;
1808 : : size_t optlen;
1809 : :
1810 : : /* If not first time through, collect a new option */
1811 [ + + ]: 28 : if (first_option)
1812 : 16 : option = first_option;
1813 : : else
1814 : : {
1815 : 12 : option = psql_scan_slash_option(scan_state,
1816 : : OT_NORMAL, NULL, false);
1817 [ - + ]: 12 : if (!option)
1818 : : {
1819 [ # # ]: 0 : if (active_branch)
1820 : : {
1821 : 0 : pg_log_error("\\%s: missing right parenthesis", cmd);
1822 : 0 : success = false;
1823 : : }
1824 : 0 : break;
1825 : : }
1826 : : }
1827 : :
1828 : : /* Check for terminating right paren, and remove it from string */
1829 : 28 : optlen = strlen(option);
1830 [ + - + + ]: 28 : if (optlen > 0 && option[optlen - 1] == ')')
1831 : : {
1832 : 16 : option[--optlen] = '\0';
1833 : 16 : found_r_paren = true;
1834 : : }
1835 : :
1836 : : /* If there was anything besides parentheses, parse/execute it */
1837 [ + - ]: 28 : if (optlen > 0)
1838 : : {
1839 : : /* We can have either "name" or "name=value" */
1840 : 28 : char *valptr = strchr(option, '=');
1841 : :
1842 [ + - ]: 28 : if (valptr)
1843 : 28 : *valptr++ = '\0';
1844 [ + - ]: 28 : if (active_branch)
1845 : : {
1846 : : /* save settings if not done already, then apply option */
1847 [ + + ]: 28 : if (pset.gsavepopt == NULL)
1848 : 12 : pset.gsavepopt = savePsetInfo(&pset.popt);
1849 : 28 : success &= do_pset(option, valptr, &pset.popt, true);
1850 : : }
1851 : : }
1852 : :
1853 : : /* Clean up after this option. We should not free first_option. */
1854 [ + + ]: 28 : if (first_option)
1855 : 16 : first_option = NULL;
1856 : : else
1857 : 12 : free(option);
1858 [ + + ]: 28 : } while (!found_r_paren);
1859 : :
1860 : : /* If we failed after already changing some options, undo side-effects */
1861 [ - + - - : 16 : if (!success && active_branch && pset.gsavepopt)
- - ]
1862 : : {
1863 : 0 : restorePsetInfo(&pset.popt, pset.gsavepopt);
1864 : 0 : pset.gsavepopt = NULL;
1865 : : }
1866 : :
1867 [ + - ]: 16 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1868 : : }
1869 : :
1870 : : /*
1871 : : * \gdesc -- describe query result
1872 : : */
1873 : : static backslashResult
1874 : 57 : exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
1875 : : {
1876 : 57 : backslashResult status = PSQL_CMD_SKIP_LINE;
1877 : :
1878 [ + - ]: 57 : if (active_branch)
1879 : : {
1880 : 57 : pset.gdesc_flag = true;
1881 : 57 : status = PSQL_CMD_SEND;
1882 : : }
1883 : :
1884 : 57 : return status;
1885 : : }
1886 : :
1887 : : /*
1888 : : * \getenv -- set variable from environment variable
1889 : : */
1890 : : static backslashResult
1891 : 227 : exec_command_getenv(PsqlScanState scan_state, bool active_branch,
1892 : : const char *cmd)
1893 : : {
1894 : 227 : bool success = true;
1895 : :
1896 [ + - ]: 227 : if (active_branch)
1897 : : {
1898 : 227 : char *myvar = psql_scan_slash_option(scan_state,
1899 : : OT_NORMAL, NULL, false);
1900 : 227 : char *envvar = psql_scan_slash_option(scan_state,
1901 : : OT_NORMAL, NULL, false);
1902 : :
1903 [ + - - + ]: 227 : if (!myvar || !envvar)
1904 : : {
1905 : 0 : pg_log_error("\\%s: missing required argument", cmd);
1906 : 0 : success = false;
1907 : : }
1908 : : else
1909 : : {
1910 : 227 : char *envval = getenv(envvar);
1911 : :
1912 [ + + - + ]: 227 : if (envval && !SetVariable(pset.vars, myvar, envval))
1913 : 0 : success = false;
1914 : : }
1915 : 227 : free(myvar);
1916 : 227 : free(envvar);
1917 : : }
1918 : : else
1919 : 0 : ignore_slash_options(scan_state);
1920 : :
1921 [ + - ]: 227 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1922 : : }
1923 : :
1924 : : /*
1925 : : * \getresults -- read results
1926 : : */
1927 : : static backslashResult
1928 : 128 : exec_command_getresults(PsqlScanState scan_state, bool active_branch)
1929 : : {
1930 : 128 : backslashResult status = PSQL_CMD_SKIP_LINE;
1931 : :
1932 [ + + ]: 128 : if (active_branch)
1933 : : {
1934 : : char *opt;
1935 : : int num_results;
1936 : :
1937 : 124 : pset.send_mode = PSQL_SEND_GET_RESULTS;
1938 : 124 : status = PSQL_CMD_SEND;
1939 : 124 : opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1940 : :
1941 : 124 : pset.requested_results = 0;
1942 [ + + ]: 124 : if (opt != NULL)
1943 : : {
1944 : 56 : num_results = atoi(opt);
1945 [ + + ]: 56 : if (num_results < 0)
1946 : : {
1947 : 4 : pg_log_error("\\getresults: invalid number of requested results");
1948 : 4 : return PSQL_CMD_ERROR;
1949 : : }
1950 : 52 : pset.requested_results = num_results;
1951 : : }
1952 : : }
1953 : : else
1954 : 4 : ignore_slash_options(scan_state);
1955 : :
1956 : 124 : return status;
1957 : : }
1958 : :
1959 : :
1960 : : /*
1961 : : * \gexec -- send query and execute each field of result
1962 : : */
1963 : : static backslashResult
1964 : 37 : exec_command_gexec(PsqlScanState scan_state, bool active_branch)
1965 : : {
1966 : 37 : backslashResult status = PSQL_CMD_SKIP_LINE;
1967 : :
1968 [ + + ]: 37 : if (active_branch)
1969 : : {
1970 [ + + ]: 33 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1971 : : {
1972 : 4 : pg_log_error("\\%s not allowed in pipeline mode", "gexec");
1973 : 4 : clean_extended_state();
1974 : 4 : return PSQL_CMD_ERROR;
1975 : : }
1976 : 29 : pset.gexec_flag = true;
1977 : 29 : status = PSQL_CMD_SEND;
1978 : : }
1979 : :
1980 : 33 : return status;
1981 : : }
1982 : :
1983 : : /*
1984 : : * \gset [prefix] -- send query and store result into variables
1985 : : */
1986 : : static backslashResult
1987 : 599 : exec_command_gset(PsqlScanState scan_state, bool active_branch)
1988 : : {
1989 : 599 : backslashResult status = PSQL_CMD_SKIP_LINE;
1990 : :
1991 [ + + ]: 599 : if (active_branch)
1992 : : {
1993 : 595 : char *prefix = psql_scan_slash_option(scan_state,
1994 : : OT_NORMAL, NULL, false);
1995 : :
1996 [ + + ]: 595 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1997 : : {
1998 : 8 : pg_log_error("\\%s not allowed in pipeline mode", "gset");
1999 : 8 : clean_extended_state();
2000 : 8 : return PSQL_CMD_ERROR;
2001 : : }
2002 : :
2003 [ + + ]: 587 : if (prefix)
2004 : 72 : pset.gset_prefix = prefix;
2005 : : else
2006 : : {
2007 : : /* we must set a non-NULL prefix to trigger storing */
2008 : 515 : pset.gset_prefix = pg_strdup("");
2009 : : }
2010 : : /* gset_prefix is freed later */
2011 : 587 : status = PSQL_CMD_SEND;
2012 : : }
2013 : : else
2014 : 4 : ignore_slash_options(scan_state);
2015 : :
2016 : 591 : return status;
2017 : : }
2018 : :
2019 : : /*
2020 : : * \help [topic] -- print help about SQL commands
2021 : : */
2022 : : static backslashResult
2023 : 6 : exec_command_help(PsqlScanState scan_state, bool active_branch)
2024 : : {
2025 [ + + ]: 6 : if (active_branch)
2026 : : {
2027 : 2 : char *opt = psql_scan_slash_option(scan_state,
2028 : : OT_WHOLE_LINE, NULL, true);
2029 : :
2030 : 2 : helpSQL(opt, pset.popt.topt.pager);
2031 : 2 : free(opt);
2032 : : }
2033 : : else
2034 : 4 : ignore_slash_whole_line(scan_state);
2035 : :
2036 : 6 : return PSQL_CMD_SKIP_LINE;
2037 : : }
2038 : :
2039 : : /*
2040 : : * \H and \html -- toggle HTML formatting
2041 : : */
2042 : : static backslashResult
2043 : 4 : exec_command_html(PsqlScanState scan_state, bool active_branch)
2044 : : {
2045 : 4 : bool success = true;
2046 : :
2047 [ - + ]: 4 : if (active_branch)
2048 : : {
2049 [ # # ]: 0 : if (pset.popt.topt.format != PRINT_HTML)
2050 : 0 : success = do_pset("format", "html", &pset.popt, pset.quiet);
2051 : : else
2052 : 0 : success = do_pset("format", "aligned", &pset.popt, pset.quiet);
2053 : : }
2054 : :
2055 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2056 : : }
2057 : :
2058 : : /*
2059 : : * \i and \ir -- include a file
2060 : : */
2061 : : static backslashResult
2062 : 8 : exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
2063 : : {
2064 : 8 : bool success = true;
2065 : :
2066 [ - + ]: 8 : if (active_branch)
2067 : : {
2068 : 0 : char *fname = psql_scan_slash_option(scan_state,
2069 : : OT_NORMAL, NULL, true);
2070 : :
2071 [ # # ]: 0 : if (!fname)
2072 : : {
2073 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2074 : 0 : success = false;
2075 : : }
2076 : : else
2077 : : {
2078 : : bool include_relative;
2079 : :
2080 : 0 : include_relative = (strcmp(cmd, "ir") == 0
2081 [ # # # # ]: 0 : || strcmp(cmd, "include_relative") == 0);
2082 : 0 : expand_tilde(&fname);
2083 : 0 : success = (process_file(fname, include_relative) == EXIT_SUCCESS);
2084 : 0 : free(fname);
2085 : : }
2086 : : }
2087 : : else
2088 : 8 : ignore_slash_options(scan_state);
2089 : :
2090 [ + - ]: 8 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2091 : : }
2092 : :
2093 : : /*
2094 : : * \if <expr> -- beginning of an \if..\endif block
2095 : : *
2096 : : * <expr> is parsed as a boolean expression. Invalid expressions will emit a
2097 : : * warning and be treated as false. Statements that follow a false expression
2098 : : * will be parsed but ignored. Note that in the case where an \if statement
2099 : : * is itself within an inactive section of a block, then the entire inner
2100 : : * \if..\endif block will be parsed but ignored.
2101 : : */
2102 : : static backslashResult
2103 : 156 : exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
2104 : : PQExpBuffer query_buf)
2105 : : {
2106 [ + + ]: 156 : if (conditional_active(cstack))
2107 : : {
2108 : : /*
2109 : : * First, push a new active stack entry; this ensures that the lexer
2110 : : * will perform variable substitution and backtick evaluation while
2111 : : * scanning the expression. (That should happen anyway, since we know
2112 : : * we're in an active outer branch, but let's be sure.)
2113 : : */
2114 : 152 : conditional_stack_push(cstack, IFSTATE_TRUE);
2115 : :
2116 : : /* Remember current query state in case we need to restore later */
2117 : 152 : save_query_text_state(scan_state, cstack, query_buf);
2118 : :
2119 : : /*
2120 : : * Evaluate the expression; if it's false, change to inactive state.
2121 : : */
2122 [ + + ]: 152 : if (!is_true_boolean_expression(scan_state, "\\if expression"))
2123 : 97 : conditional_stack_poke(cstack, IFSTATE_FALSE);
2124 : : }
2125 : : else
2126 : : {
2127 : : /*
2128 : : * We're within an inactive outer branch, so this entire \if block
2129 : : * will be ignored. We don't want to evaluate the expression, so push
2130 : : * the "ignored" stack state before scanning it.
2131 : : */
2132 : 4 : conditional_stack_push(cstack, IFSTATE_IGNORED);
2133 : :
2134 : : /* Remember current query state in case we need to restore later */
2135 : 4 : save_query_text_state(scan_state, cstack, query_buf);
2136 : :
2137 : 4 : ignore_boolean_expression(scan_state);
2138 : : }
2139 : :
2140 : 156 : return PSQL_CMD_SKIP_LINE;
2141 : : }
2142 : :
2143 : : /*
2144 : : * \elif <expr> -- alternative branch in an \if..\endif block
2145 : : *
2146 : : * <expr> is evaluated the same as in \if <expr>.
2147 : : */
2148 : : static backslashResult
2149 : 32 : exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
2150 : : PQExpBuffer query_buf)
2151 : : {
2152 : 32 : bool success = true;
2153 : :
2154 [ + + + + : 32 : switch (conditional_stack_peek(cstack))
+ - ]
2155 : : {
2156 : 4 : case IFSTATE_TRUE:
2157 : :
2158 : : /*
2159 : : * Just finished active branch of this \if block. Update saved
2160 : : * state so we will keep whatever data was put in query_buf by the
2161 : : * active branch.
2162 : : */
2163 : 4 : save_query_text_state(scan_state, cstack, query_buf);
2164 : :
2165 : : /*
2166 : : * Discard \elif expression and ignore the rest until \endif.
2167 : : * Switch state before reading expression to ensure proper lexer
2168 : : * behavior.
2169 : : */
2170 : 4 : conditional_stack_poke(cstack, IFSTATE_IGNORED);
2171 : 4 : ignore_boolean_expression(scan_state);
2172 : 4 : break;
2173 : 16 : case IFSTATE_FALSE:
2174 : :
2175 : : /*
2176 : : * Discard any query text added by the just-skipped branch.
2177 : : */
2178 : 16 : discard_query_text(scan_state, cstack, query_buf);
2179 : :
2180 : : /*
2181 : : * Have not yet found a true expression in this \if block, so this
2182 : : * might be the first. We have to change state before examining
2183 : : * the expression, or the lexer won't do the right thing.
2184 : : */
2185 : 16 : conditional_stack_poke(cstack, IFSTATE_TRUE);
2186 [ + + ]: 16 : if (!is_true_boolean_expression(scan_state, "\\elif expression"))
2187 : 12 : conditional_stack_poke(cstack, IFSTATE_FALSE);
2188 : 16 : break;
2189 : 4 : case IFSTATE_IGNORED:
2190 : :
2191 : : /*
2192 : : * Discard any query text added by the just-skipped branch.
2193 : : */
2194 : 4 : discard_query_text(scan_state, cstack, query_buf);
2195 : :
2196 : : /*
2197 : : * Skip expression and move on. Either the \if block already had
2198 : : * an active section, or whole block is being skipped.
2199 : : */
2200 : 4 : ignore_boolean_expression(scan_state);
2201 : 4 : break;
2202 : 4 : case IFSTATE_ELSE_TRUE:
2203 : : case IFSTATE_ELSE_FALSE:
2204 : 4 : pg_log_error("\\elif: cannot occur after \\else");
2205 : 4 : success = false;
2206 : 4 : break;
2207 : 4 : case IFSTATE_NONE:
2208 : : /* no \if to elif from */
2209 : 4 : pg_log_error("\\elif: no matching \\if");
2210 : 4 : success = false;
2211 : 4 : break;
2212 : : }
2213 : :
2214 [ + + ]: 32 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2215 : : }
2216 : :
2217 : : /*
2218 : : * \else -- final alternative in an \if..\endif block
2219 : : *
2220 : : * Statements within an \else branch will only be executed if
2221 : : * all previous \if and \elif expressions evaluated to false
2222 : : * and the block was not itself being ignored.
2223 : : */
2224 : : static backslashResult
2225 : 88 : exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
2226 : : PQExpBuffer query_buf)
2227 : : {
2228 : 88 : bool success = true;
2229 : :
2230 [ + + + + : 88 : switch (conditional_stack_peek(cstack))
+ - ]
2231 : : {
2232 : 40 : case IFSTATE_TRUE:
2233 : :
2234 : : /*
2235 : : * Just finished active branch of this \if block. Update saved
2236 : : * state so we will keep whatever data was put in query_buf by the
2237 : : * active branch.
2238 : : */
2239 : 40 : save_query_text_state(scan_state, cstack, query_buf);
2240 : :
2241 : : /* Now skip the \else branch */
2242 : 40 : conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
2243 : 40 : break;
2244 : 32 : case IFSTATE_FALSE:
2245 : :
2246 : : /*
2247 : : * Discard any query text added by the just-skipped branch.
2248 : : */
2249 : 32 : discard_query_text(scan_state, cstack, query_buf);
2250 : :
2251 : : /*
2252 : : * We've not found any true \if or \elif expression, so execute
2253 : : * the \else branch.
2254 : : */
2255 : 32 : conditional_stack_poke(cstack, IFSTATE_ELSE_TRUE);
2256 : 32 : break;
2257 : 8 : case IFSTATE_IGNORED:
2258 : :
2259 : : /*
2260 : : * Discard any query text added by the just-skipped branch.
2261 : : */
2262 : 8 : discard_query_text(scan_state, cstack, query_buf);
2263 : :
2264 : : /*
2265 : : * Either we previously processed the active branch of this \if,
2266 : : * or the whole \if block is being skipped. Either way, skip the
2267 : : * \else branch.
2268 : : */
2269 : 8 : conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
2270 : 8 : break;
2271 : 4 : case IFSTATE_ELSE_TRUE:
2272 : : case IFSTATE_ELSE_FALSE:
2273 : 4 : pg_log_error("\\else: cannot occur after \\else");
2274 : 4 : success = false;
2275 : 4 : break;
2276 : 4 : case IFSTATE_NONE:
2277 : : /* no \if to else from */
2278 : 4 : pg_log_error("\\else: no matching \\if");
2279 : 4 : success = false;
2280 : 4 : break;
2281 : : }
2282 : :
2283 [ + + ]: 88 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2284 : : }
2285 : :
2286 : : /*
2287 : : * \endif -- ends an \if...\endif block
2288 : : */
2289 : : static backslashResult
2290 : 145 : exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
2291 : : PQExpBuffer query_buf)
2292 : : {
2293 : 145 : bool success = true;
2294 : :
2295 [ + + + - ]: 145 : switch (conditional_stack_peek(cstack))
2296 : : {
2297 : 32 : case IFSTATE_TRUE:
2298 : : case IFSTATE_ELSE_TRUE:
2299 : : /* Close the \if block, keeping the query text */
2300 : 32 : success = conditional_stack_pop(cstack);
2301 : : Assert(success);
2302 : 32 : break;
2303 : 109 : case IFSTATE_FALSE:
2304 : : case IFSTATE_IGNORED:
2305 : : case IFSTATE_ELSE_FALSE:
2306 : :
2307 : : /*
2308 : : * Discard any query text added by the just-skipped branch.
2309 : : */
2310 : 109 : discard_query_text(scan_state, cstack, query_buf);
2311 : :
2312 : : /* Close the \if block */
2313 : 109 : success = conditional_stack_pop(cstack);
2314 : : Assert(success);
2315 : 109 : break;
2316 : 4 : case IFSTATE_NONE:
2317 : : /* no \if to end */
2318 : 4 : pg_log_error("\\endif: no matching \\if");
2319 : 4 : success = false;
2320 : 4 : break;
2321 : : }
2322 : :
2323 [ + + ]: 145 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2324 : : }
2325 : :
2326 : : /*
2327 : : * \l -- list databases
2328 : : */
2329 : : static backslashResult
2330 : 4 : exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
2331 : : {
2332 : 4 : bool success = true;
2333 : :
2334 [ - + ]: 4 : if (active_branch)
2335 : : {
2336 : : char *pattern;
2337 : : bool show_verbose;
2338 : : unsigned short int save_expanded;
2339 : :
2340 : 0 : pattern = psql_scan_slash_option(scan_state,
2341 : : OT_NORMAL, NULL, true);
2342 : :
2343 : 0 : show_verbose = strchr(cmd, '+') ? true : false;
2344 : :
2345 : : /* if 'x' option specified, force expanded mode */
2346 : 0 : save_expanded = pset.popt.topt.expanded;
2347 [ # # ]: 0 : if (strchr(cmd, 'x'))
2348 : 0 : pset.popt.topt.expanded = 1;
2349 : :
2350 : 0 : success = listAllDbs(pattern, show_verbose);
2351 : :
2352 : : /* restore original expanded mode */
2353 : 0 : pset.popt.topt.expanded = save_expanded;
2354 : :
2355 : 0 : free(pattern);
2356 : : }
2357 : : else
2358 : 4 : ignore_slash_options(scan_state);
2359 : :
2360 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2361 : : }
2362 : :
2363 : : /*
2364 : : * \lo_* -- large object operations
2365 : : */
2366 : : static backslashResult
2367 : 41 : exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
2368 : : {
2369 : 41 : backslashResult status = PSQL_CMD_SKIP_LINE;
2370 : 41 : bool success = true;
2371 : :
2372 [ + + ]: 41 : if (active_branch)
2373 : : {
2374 : : char *opt1,
2375 : : *opt2;
2376 : :
2377 : 37 : opt1 = psql_scan_slash_option(scan_state,
2378 : : OT_NORMAL, NULL, true);
2379 : 37 : opt2 = psql_scan_slash_option(scan_state,
2380 : : OT_NORMAL, NULL, true);
2381 : :
2382 [ + + ]: 37 : if (strcmp(cmd + 3, "export") == 0)
2383 : : {
2384 [ - + ]: 4 : if (!opt2)
2385 : : {
2386 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2387 : 0 : success = false;
2388 : : }
2389 : : else
2390 : : {
2391 : 4 : expand_tilde(&opt2);
2392 : 4 : success = do_lo_export(opt1, opt2);
2393 : : }
2394 : : }
2395 : :
2396 [ + + ]: 33 : else if (strcmp(cmd + 3, "import") == 0)
2397 : : {
2398 [ - + ]: 9 : if (!opt1)
2399 : : {
2400 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2401 : 0 : success = false;
2402 : : }
2403 : : else
2404 : : {
2405 : 9 : expand_tilde(&opt1);
2406 : 9 : success = do_lo_import(opt1, opt2);
2407 : : }
2408 : : }
2409 : :
2410 [ + + ]: 24 : else if (strncmp(cmd + 3, "list", 4) == 0)
2411 : : {
2412 : : bool show_verbose;
2413 : : unsigned short int save_expanded;
2414 : :
2415 : 8 : show_verbose = strchr(cmd, '+') ? true : false;
2416 : :
2417 : : /* if 'x' option specified, force expanded mode */
2418 : 8 : save_expanded = pset.popt.topt.expanded;
2419 [ - + ]: 8 : if (strchr(cmd, 'x'))
2420 : 0 : pset.popt.topt.expanded = 1;
2421 : :
2422 : 8 : success = listLargeObjects(show_verbose);
2423 : :
2424 : : /* restore original expanded mode */
2425 : 8 : pset.popt.topt.expanded = save_expanded;
2426 : : }
2427 : :
2428 [ + - ]: 16 : else if (strcmp(cmd + 3, "unlink") == 0)
2429 : : {
2430 [ - + ]: 16 : if (!opt1)
2431 : : {
2432 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2433 : 0 : success = false;
2434 : : }
2435 : : else
2436 : 16 : success = do_lo_unlink(opt1);
2437 : : }
2438 : :
2439 : : else
2440 : 0 : status = PSQL_CMD_UNKNOWN;
2441 : :
2442 : 37 : free(opt1);
2443 : 37 : free(opt2);
2444 : : }
2445 : : else
2446 : 4 : ignore_slash_options(scan_state);
2447 : :
2448 [ - + ]: 41 : if (!success)
2449 : 0 : status = PSQL_CMD_ERROR;
2450 : :
2451 : 41 : return status;
2452 : : }
2453 : :
2454 : : /*
2455 : : * \o -- set query output
2456 : : */
2457 : : static backslashResult
2458 : 28 : exec_command_out(PsqlScanState scan_state, bool active_branch)
2459 : : {
2460 : 28 : bool success = true;
2461 : :
2462 [ + + ]: 28 : if (active_branch)
2463 : : {
2464 : 24 : char *fname = psql_scan_slash_option(scan_state,
2465 : : OT_FILEPIPE, NULL, true);
2466 : :
2467 : 24 : expand_tilde(&fname);
2468 : 24 : success = setQFout(fname);
2469 : 24 : free(fname);
2470 : : }
2471 : : else
2472 : 4 : ignore_slash_filepipe(scan_state);
2473 : :
2474 [ + - ]: 28 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2475 : : }
2476 : :
2477 : : /*
2478 : : * \p -- print the current query buffer
2479 : : */
2480 : : static backslashResult
2481 : 28 : exec_command_print(PsqlScanState scan_state, bool active_branch,
2482 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
2483 : : {
2484 [ + + ]: 28 : if (active_branch)
2485 : : {
2486 : : /*
2487 : : * We want to print the same thing \g would execute, but not to change
2488 : : * the query buffer state; so we can't use copy_previous_query().
2489 : : * Also, beware of possibility that buffer pointers are NULL.
2490 : : */
2491 [ + - + + ]: 24 : if (query_buf && query_buf->len > 0)
2492 : 12 : puts(query_buf->data);
2493 [ + - + - ]: 12 : else if (previous_buf && previous_buf->len > 0)
2494 : 12 : puts(previous_buf->data);
2495 [ # # ]: 0 : else if (!pset.quiet)
2496 : 0 : puts(_("Query buffer is empty."));
2497 : 24 : fflush(stdout);
2498 : : }
2499 : :
2500 : 28 : return PSQL_CMD_SKIP_LINE;
2501 : : }
2502 : :
2503 : : /*
2504 : : * \parse -- parse query
2505 : : */
2506 : : static backslashResult
2507 : 75 : exec_command_parse(PsqlScanState scan_state, bool active_branch,
2508 : : const char *cmd)
2509 : : {
2510 : 75 : backslashResult status = PSQL_CMD_SKIP_LINE;
2511 : :
2512 [ + + ]: 75 : if (active_branch)
2513 : : {
2514 : 71 : char *opt = psql_scan_slash_option(scan_state,
2515 : : OT_NORMAL, NULL, false);
2516 : :
2517 : 71 : clean_extended_state();
2518 : :
2519 [ + + ]: 71 : if (!opt)
2520 : : {
2521 : 4 : pg_log_error("\\%s: missing required argument", cmd);
2522 : 4 : status = PSQL_CMD_ERROR;
2523 : : }
2524 : : else
2525 : : {
2526 : 67 : pset.stmtName = opt;
2527 : 67 : pset.send_mode = PSQL_SEND_EXTENDED_PARSE;
2528 : 67 : status = PSQL_CMD_SEND;
2529 : : }
2530 : : }
2531 : : else
2532 : 4 : ignore_slash_options(scan_state);
2533 : :
2534 : 75 : return status;
2535 : : }
2536 : :
2537 : : /*
2538 : : * \password -- set user password
2539 : : */
2540 : : static backslashResult
2541 : 5 : exec_command_password(PsqlScanState scan_state, bool active_branch)
2542 : : {
2543 : 5 : bool success = true;
2544 : :
2545 [ + + ]: 5 : if (active_branch)
2546 : : {
2547 : 1 : char *user = psql_scan_slash_option(scan_state,
2548 : : OT_SQLID, NULL, true);
2549 : 1 : char *pw1 = NULL;
2550 : 1 : char *pw2 = NULL;
2551 : : PQExpBufferData buf;
2552 : : PromptInterruptContext prompt_ctx;
2553 : :
2554 [ - + ]: 1 : if (user == NULL)
2555 : : {
2556 : : /* By default, the command applies to CURRENT_USER */
2557 : : PGresult *res;
2558 : :
2559 : 0 : res = PSQLexec("SELECT CURRENT_USER");
2560 [ # # ]: 0 : if (!res)
2561 : 0 : return PSQL_CMD_ERROR;
2562 : :
2563 : 0 : user = pg_strdup(PQgetvalue(res, 0, 0));
2564 : 0 : PQclear(res);
2565 : : }
2566 : :
2567 : : /* Set up to let SIGINT cancel simple_prompt_extended() */
2568 : 1 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2569 : 1 : prompt_ctx.enabled = &sigint_interrupt_enabled;
2570 : 1 : prompt_ctx.canceled = false;
2571 : :
2572 : 1 : initPQExpBuffer(&buf);
2573 : 1 : printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2574 : :
2575 : 1 : pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2576 [ + - ]: 1 : if (!prompt_ctx.canceled)
2577 : 1 : pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2578 : :
2579 [ - + ]: 1 : if (prompt_ctx.canceled)
2580 : : {
2581 : : /* fail silently */
2582 : 0 : success = false;
2583 : : }
2584 [ - + ]: 1 : else if (strcmp(pw1, pw2) != 0)
2585 : : {
2586 : 0 : pg_log_error("Passwords didn't match.");
2587 : 0 : success = false;
2588 : : }
2589 : : else
2590 : : {
2591 : 1 : PGresult *res = PQchangePassword(pset.db, user, pw1);
2592 : :
2593 [ - + ]: 1 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
2594 : : {
2595 : 0 : pg_log_info("%s", PQerrorMessage(pset.db));
2596 : 0 : success = false;
2597 : : }
2598 : :
2599 : 1 : PQclear(res);
2600 : : }
2601 : :
2602 : 1 : pg_free(user);
2603 : 1 : free(pw1);
2604 : 1 : free(pw2);
2605 : 1 : termPQExpBuffer(&buf);
2606 : : }
2607 : : else
2608 : 4 : ignore_slash_options(scan_state);
2609 : :
2610 [ + - ]: 5 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2611 : : }
2612 : :
2613 : : /*
2614 : : * \prompt -- prompt and set variable
2615 : : */
2616 : : static backslashResult
2617 : 4 : exec_command_prompt(PsqlScanState scan_state, bool active_branch,
2618 : : const char *cmd)
2619 : : {
2620 : 4 : bool success = true;
2621 : :
2622 [ - + ]: 4 : if (active_branch)
2623 : : {
2624 : : char *opt,
2625 : 0 : *prompt_text = NULL;
2626 : : char *arg1,
2627 : : *arg2;
2628 : :
2629 : 0 : arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2630 : 0 : arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2631 : :
2632 [ # # ]: 0 : if (!arg1)
2633 : : {
2634 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2635 : 0 : success = false;
2636 : : }
2637 : : else
2638 : : {
2639 : : char *result;
2640 : : PromptInterruptContext prompt_ctx;
2641 : :
2642 : : /* Set up to let SIGINT cancel simple_prompt_extended() */
2643 : 0 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2644 : 0 : prompt_ctx.enabled = &sigint_interrupt_enabled;
2645 : 0 : prompt_ctx.canceled = false;
2646 : :
2647 [ # # ]: 0 : if (arg2)
2648 : : {
2649 : 0 : prompt_text = arg1;
2650 : 0 : opt = arg2;
2651 : : }
2652 : : else
2653 : 0 : opt = arg1;
2654 : :
2655 [ # # ]: 0 : if (!pset.inputfile)
2656 : : {
2657 : 0 : result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2658 : : }
2659 : : else
2660 : : {
2661 [ # # ]: 0 : if (prompt_text)
2662 : : {
2663 : 0 : fputs(prompt_text, stdout);
2664 : 0 : fflush(stdout);
2665 : : }
2666 : 0 : result = gets_fromFile(stdin);
2667 [ # # ]: 0 : if (!result)
2668 : : {
2669 : 0 : pg_log_error("\\%s: could not read value for variable",
2670 : : cmd);
2671 : 0 : success = false;
2672 : : }
2673 : : }
2674 : :
2675 [ # # # # ]: 0 : if (prompt_ctx.canceled ||
2676 [ # # ]: 0 : (result && !SetVariable(pset.vars, opt, result)))
2677 : 0 : success = false;
2678 : :
2679 : 0 : free(result);
2680 : 0 : free(prompt_text);
2681 : 0 : free(opt);
2682 : : }
2683 : : }
2684 : : else
2685 : 4 : ignore_slash_options(scan_state);
2686 : :
2687 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2688 : : }
2689 : :
2690 : : /*
2691 : : * \pset -- set printing parameters
2692 : : */
2693 : : static backslashResult
2694 : 1246 : exec_command_pset(PsqlScanState scan_state, bool active_branch)
2695 : : {
2696 : 1246 : bool success = true;
2697 : :
2698 [ + + ]: 1246 : if (active_branch)
2699 : : {
2700 : 1238 : char *opt0 = psql_scan_slash_option(scan_state,
2701 : : OT_NORMAL, NULL, false);
2702 : 1238 : char *opt1 = psql_scan_slash_option(scan_state,
2703 : : OT_NORMAL, NULL, false);
2704 : :
2705 [ + + ]: 1238 : if (!opt0)
2706 : : {
2707 : : /* list all variables */
2708 : :
2709 : : int i;
2710 : : static const char *const my_list[] = {
2711 : : "border", "columns", "csv_fieldsep",
2712 : : "display_false", "display_true", "expanded", "fieldsep",
2713 : : "fieldsep_zero", "footer", "format", "linestyle", "null",
2714 : : "numericlocale", "pager", "pager_min_lines",
2715 : : "recordsep", "recordsep_zero",
2716 : : "tableattr", "title", "tuples_only",
2717 : : "unicode_border_linestyle",
2718 : : "unicode_column_linestyle",
2719 : : "unicode_header_linestyle",
2720 : : "xheader_width",
2721 : : NULL
2722 : : };
2723 : :
2724 [ + + ]: 100 : for (i = 0; my_list[i] != NULL; i++)
2725 : : {
2726 : 96 : char *val = pset_value_string(my_list[i], &pset.popt);
2727 : :
2728 : 96 : printf("%-24s %s\n", my_list[i], val);
2729 : 96 : free(val);
2730 : : }
2731 : :
2732 : 4 : success = true;
2733 : : }
2734 : : else
2735 : 1234 : success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2736 : :
2737 : 1238 : free(opt0);
2738 : 1238 : free(opt1);
2739 : : }
2740 : : else
2741 : 8 : ignore_slash_options(scan_state);
2742 : :
2743 [ + + ]: 1246 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2744 : : }
2745 : :
2746 : : /*
2747 : : * \q or \quit -- exit psql
2748 : : */
2749 : : static backslashResult
2750 : 287 : exec_command_quit(PsqlScanState scan_state, bool active_branch)
2751 : : {
2752 : 287 : backslashResult status = PSQL_CMD_SKIP_LINE;
2753 : :
2754 [ + + ]: 287 : if (active_branch)
2755 : 226 : status = PSQL_CMD_TERMINATE;
2756 : :
2757 : 287 : return status;
2758 : : }
2759 : :
2760 : : /*
2761 : : * \r -- reset (clear) the query buffer
2762 : : */
2763 : : static backslashResult
2764 : 56 : exec_command_reset(PsqlScanState scan_state, bool active_branch,
2765 : : PQExpBuffer query_buf)
2766 : : {
2767 [ + + ]: 56 : if (active_branch)
2768 : : {
2769 : 52 : resetPQExpBuffer(query_buf);
2770 : 52 : psql_scan_reset(scan_state);
2771 [ + + ]: 52 : if (!pset.quiet)
2772 : 32 : puts(_("Query buffer reset (cleared)."));
2773 : : }
2774 : :
2775 : 56 : return PSQL_CMD_SKIP_LINE;
2776 : : }
2777 : :
2778 : : /*
2779 : : * \restrict -- enter "restricted mode" with the provided key
2780 : : */
2781 : : static backslashResult
2782 : 38 : exec_command_restrict(PsqlScanState scan_state, bool active_branch,
2783 : : const char *cmd)
2784 : : {
2785 [ + + ]: 38 : if (active_branch)
2786 : : {
2787 : : char *opt;
2788 : :
2789 : : Assert(!restricted);
2790 : :
2791 : : /*
2792 : : * Unlike \unrestrict, this argument may safely undergo backquote and
2793 : : * variable expansion: HandleSlashCmds() rejects \restrict in
2794 : : * restricted mode before its argument is scanned, so we only get here
2795 : : * when the input could execute such things anyway.
2796 : : */
2797 : 34 : opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
2798 [ + - - + ]: 34 : if (opt == NULL || opt[0] == '\0')
2799 : : {
2800 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2801 : 0 : return PSQL_CMD_ERROR;
2802 : : }
2803 : :
2804 : 34 : restrict_key = pstrdup(opt);
2805 : 34 : restricted = true;
2806 : : }
2807 : : else
2808 : 4 : ignore_slash_options(scan_state);
2809 : :
2810 : 38 : return PSQL_CMD_SKIP_LINE;
2811 : : }
2812 : :
2813 : : /*
2814 : : * \s -- save history in a file or show it on the screen
2815 : : */
2816 : : static backslashResult
2817 : 4 : exec_command_s(PsqlScanState scan_state, bool active_branch)
2818 : : {
2819 : 4 : bool success = true;
2820 : :
2821 [ - + ]: 4 : if (active_branch)
2822 : : {
2823 : 0 : char *fname = psql_scan_slash_option(scan_state,
2824 : : OT_NORMAL, NULL, true);
2825 : :
2826 : 0 : expand_tilde(&fname);
2827 : 0 : success = printHistory(fname, pset.popt.topt.pager);
2828 [ # # # # : 0 : if (success && !pset.quiet && fname)
# # ]
2829 : 0 : printf(_("Wrote history to file \"%s\".\n"), fname);
2830 [ # # ]: 0 : if (!fname)
2831 : 0 : putchar('\n');
2832 : 0 : free(fname);
2833 : : }
2834 : : else
2835 : 4 : ignore_slash_options(scan_state);
2836 : :
2837 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2838 : : }
2839 : :
2840 : : /*
2841 : : * \sendpipeline -- send an extended query to an ongoing pipeline
2842 : : */
2843 : : static backslashResult
2844 : 481 : exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch)
2845 : : {
2846 : 481 : backslashResult status = PSQL_CMD_SKIP_LINE;
2847 : :
2848 [ + + ]: 481 : if (active_branch)
2849 : : {
2850 [ + + ]: 477 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
2851 : : {
2852 [ + + ]: 469 : if (pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PREPARED ||
2853 [ + + ]: 437 : pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PARAMS)
2854 : : {
2855 : 461 : status = PSQL_CMD_SEND;
2856 : : }
2857 : : else
2858 : : {
2859 : 8 : pg_log_error("\\sendpipeline must be used after \\bind or \\bind_named");
2860 : 8 : clean_extended_state();
2861 : 8 : return PSQL_CMD_ERROR;
2862 : : }
2863 : : }
2864 : : else
2865 : : {
2866 : 8 : pg_log_error("\\sendpipeline not allowed outside of pipeline mode");
2867 : 8 : clean_extended_state();
2868 : 8 : return PSQL_CMD_ERROR;
2869 : : }
2870 : : }
2871 : : else
2872 : 4 : ignore_slash_options(scan_state);
2873 : :
2874 : 465 : return status;
2875 : : }
2876 : :
2877 : : /*
2878 : : * \set -- set variable
2879 : : */
2880 : : static backslashResult
2881 : 718 : exec_command_set(PsqlScanState scan_state, bool active_branch)
2882 : : {
2883 : 718 : bool success = true;
2884 : :
2885 [ + + ]: 718 : if (active_branch)
2886 : : {
2887 : 714 : char *opt0 = psql_scan_slash_option(scan_state,
2888 : : OT_NORMAL, NULL, false);
2889 : :
2890 [ - + ]: 714 : if (!opt0)
2891 : : {
2892 : : /* list all variables */
2893 : 0 : PrintVariables(pset.vars);
2894 : 0 : success = true;
2895 : : }
2896 : : else
2897 : : {
2898 : : /*
2899 : : * Set variable to the concatenation of the arguments.
2900 : : */
2901 : : char *newval;
2902 : : char *opt;
2903 : :
2904 : 714 : opt = psql_scan_slash_option(scan_state,
2905 : : OT_NORMAL, NULL, false);
2906 [ + + ]: 714 : newval = pg_strdup(opt ? opt : "");
2907 : 714 : free(opt);
2908 : :
2909 [ + + ]: 1064 : while ((opt = psql_scan_slash_option(scan_state,
2910 : : OT_NORMAL, NULL, false)))
2911 : : {
2912 : 350 : newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2913 : 350 : strcat(newval, opt);
2914 : 350 : free(opt);
2915 : : }
2916 : :
2917 [ + + ]: 714 : if (!SetVariable(pset.vars, opt0, newval))
2918 : 17 : success = false;
2919 : :
2920 : 714 : pg_free(newval);
2921 : : }
2922 : 714 : free(opt0);
2923 : : }
2924 : : else
2925 : 4 : ignore_slash_options(scan_state);
2926 : :
2927 [ + + ]: 718 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2928 : : }
2929 : :
2930 : : /*
2931 : : * \setenv -- set environment variable
2932 : : */
2933 : : static backslashResult
2934 : 12 : exec_command_setenv(PsqlScanState scan_state, bool active_branch,
2935 : : const char *cmd)
2936 : : {
2937 : 12 : bool success = true;
2938 : :
2939 [ + + ]: 12 : if (active_branch)
2940 : : {
2941 : 8 : char *envvar = psql_scan_slash_option(scan_state,
2942 : : OT_NORMAL, NULL, false);
2943 : 8 : char *envval = psql_scan_slash_option(scan_state,
2944 : : OT_NORMAL, NULL, false);
2945 : :
2946 [ - + ]: 8 : if (!envvar)
2947 : : {
2948 : 0 : pg_log_error("\\%s: missing required argument", cmd);
2949 : 0 : success = false;
2950 : : }
2951 [ - + ]: 8 : else if (strchr(envvar, '=') != NULL)
2952 : : {
2953 : 0 : pg_log_error("\\%s: environment variable name must not contain \"=\"",
2954 : : cmd);
2955 : 0 : success = false;
2956 : : }
2957 [ + + ]: 8 : else if (!envval)
2958 : : {
2959 : : /* No argument - unset the environment variable */
2960 : 4 : unsetenv(envvar);
2961 : 4 : success = true;
2962 : : }
2963 : : else
2964 : : {
2965 : : /* Set variable to the value of the next argument */
2966 : 4 : setenv(envvar, envval, 1);
2967 : 4 : success = true;
2968 : : }
2969 : 8 : free(envvar);
2970 : 8 : free(envval);
2971 : : }
2972 : : else
2973 : 4 : ignore_slash_options(scan_state);
2974 : :
2975 [ + - ]: 12 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2976 : : }
2977 : :
2978 : : /*
2979 : : * \sf/\sv -- show a function/view's source code
2980 : : */
2981 : : static backslashResult
2982 : 178 : exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
2983 : : const char *cmd, bool is_func)
2984 : : {
2985 : 178 : backslashResult status = PSQL_CMD_SKIP_LINE;
2986 : :
2987 [ + + ]: 178 : if (active_branch)
2988 : : {
2989 : 170 : bool show_linenumbers = (strchr(cmd, '+') != NULL);
2990 : : PQExpBuffer buf;
2991 : : char *obj_desc;
2992 : 170 : Oid obj_oid = InvalidOid;
2993 : 170 : EditableObjectType eot = is_func ? EditableFunction : EditableView;
2994 : :
2995 : 170 : buf = createPQExpBuffer();
2996 : 170 : obj_desc = psql_scan_slash_option(scan_state,
2997 : : OT_WHOLE_LINE, NULL, true);
2998 [ - + ]: 170 : if (!obj_desc)
2999 : : {
3000 [ # # ]: 0 : if (is_func)
3001 : 0 : pg_log_error("function name is required");
3002 : : else
3003 : 0 : pg_log_error("view name is required");
3004 : 0 : status = PSQL_CMD_ERROR;
3005 : : }
3006 [ - + ]: 170 : else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
3007 : : {
3008 : : /* error already reported */
3009 : 0 : status = PSQL_CMD_ERROR;
3010 : : }
3011 [ - + ]: 170 : else if (!get_create_object_cmd(eot, obj_oid, buf))
3012 : : {
3013 : : /* error already reported */
3014 : 0 : status = PSQL_CMD_ERROR;
3015 : : }
3016 : : else
3017 : : {
3018 : : FILE *output;
3019 : : bool is_pager;
3020 : :
3021 : : /* Select output stream: stdout, pager, or file */
3022 [ + - ]: 170 : if (pset.queryFout == stdout)
3023 : : {
3024 : : /* count lines in function to see if pager is needed */
3025 : 170 : int lineno = count_lines_in_buf(buf);
3026 : :
3027 : 170 : output = PageOutput(lineno, &(pset.popt.topt));
3028 : 170 : is_pager = true;
3029 : : }
3030 : : else
3031 : : {
3032 : : /* use previously set output file, without pager */
3033 : 0 : output = pset.queryFout;
3034 : 0 : is_pager = false;
3035 : : }
3036 : :
3037 [ + + ]: 170 : if (show_linenumbers)
3038 : : {
3039 : : /* add line numbers */
3040 : 28 : print_with_linenumbers(output, buf->data, is_func);
3041 : : }
3042 : : else
3043 : : {
3044 : : /* just send the definition to output */
3045 : 142 : fputs(buf->data, output);
3046 : : }
3047 : :
3048 [ + - ]: 170 : if (is_pager)
3049 : 170 : ClosePager(output);
3050 : : }
3051 : :
3052 : 170 : free(obj_desc);
3053 : 170 : destroyPQExpBuffer(buf);
3054 : : }
3055 : : else
3056 : 8 : ignore_slash_whole_line(scan_state);
3057 : :
3058 : 178 : return status;
3059 : : }
3060 : :
3061 : : /*
3062 : : * \startpipeline -- enter pipeline mode
3063 : : */
3064 : : static backslashResult
3065 : 225 : exec_command_startpipeline(PsqlScanState scan_state, bool active_branch)
3066 : : {
3067 : 225 : backslashResult status = PSQL_CMD_SKIP_LINE;
3068 : :
3069 [ + + ]: 225 : if (active_branch)
3070 : : {
3071 : 221 : pset.send_mode = PSQL_SEND_START_PIPELINE_MODE;
3072 : 221 : status = PSQL_CMD_SEND;
3073 : : }
3074 : : else
3075 : 4 : ignore_slash_options(scan_state);
3076 : :
3077 : 225 : return status;
3078 : : }
3079 : :
3080 : : /*
3081 : : * \syncpipeline -- send a sync message to an active pipeline
3082 : : */
3083 : : static backslashResult
3084 : 99 : exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch)
3085 : : {
3086 : 99 : backslashResult status = PSQL_CMD_SKIP_LINE;
3087 : :
3088 [ + + ]: 99 : if (active_branch)
3089 : : {
3090 : 95 : pset.send_mode = PSQL_SEND_PIPELINE_SYNC;
3091 : 95 : status = PSQL_CMD_SEND;
3092 : : }
3093 : : else
3094 : 4 : ignore_slash_options(scan_state);
3095 : :
3096 : 99 : return status;
3097 : : }
3098 : :
3099 : : /*
3100 : : * \endpipeline -- end pipeline mode
3101 : : */
3102 : : static backslashResult
3103 : 225 : exec_command_endpipeline(PsqlScanState scan_state, bool active_branch)
3104 : : {
3105 : 225 : backslashResult status = PSQL_CMD_SKIP_LINE;
3106 : :
3107 [ + + ]: 225 : if (active_branch)
3108 : : {
3109 : 221 : pset.send_mode = PSQL_SEND_END_PIPELINE_MODE;
3110 : 221 : status = PSQL_CMD_SEND;
3111 : : }
3112 : : else
3113 : 4 : ignore_slash_options(scan_state);
3114 : :
3115 : 225 : return status;
3116 : : }
3117 : :
3118 : : /*
3119 : : * \t -- turn off table headers and row count
3120 : : */
3121 : : static backslashResult
3122 : 52 : exec_command_t(PsqlScanState scan_state, bool active_branch)
3123 : : {
3124 : 52 : bool success = true;
3125 : :
3126 [ + + ]: 52 : if (active_branch)
3127 : : {
3128 : 48 : char *opt = psql_scan_slash_option(scan_state,
3129 : : OT_NORMAL, NULL, true);
3130 : :
3131 : 48 : success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
3132 : 48 : free(opt);
3133 : : }
3134 : : else
3135 : 4 : ignore_slash_options(scan_state);
3136 : :
3137 [ + - ]: 52 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3138 : : }
3139 : :
3140 : : /*
3141 : : * \T -- define html <table ...> attributes
3142 : : */
3143 : : static backslashResult
3144 : 4 : exec_command_T(PsqlScanState scan_state, bool active_branch)
3145 : : {
3146 : 4 : bool success = true;
3147 : :
3148 [ - + ]: 4 : if (active_branch)
3149 : : {
3150 : 0 : char *value = psql_scan_slash_option(scan_state,
3151 : : OT_NORMAL, NULL, false);
3152 : :
3153 : 0 : success = do_pset("tableattr", value, &pset.popt, pset.quiet);
3154 : 0 : free(value);
3155 : : }
3156 : : else
3157 : 4 : ignore_slash_options(scan_state);
3158 : :
3159 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3160 : : }
3161 : :
3162 : : /*
3163 : : * \timing -- enable/disable timing of queries
3164 : : */
3165 : : static backslashResult
3166 : 6 : exec_command_timing(PsqlScanState scan_state, bool active_branch)
3167 : : {
3168 : 6 : bool success = true;
3169 : :
3170 [ + + ]: 6 : if (active_branch)
3171 : : {
3172 : 2 : char *opt = psql_scan_slash_option(scan_state,
3173 : : OT_NORMAL, NULL, false);
3174 : :
3175 [ + - ]: 2 : if (opt)
3176 : 2 : success = ParseVariableBool(opt, "\\timing", &pset.timing);
3177 : : else
3178 : 0 : pset.timing = !pset.timing;
3179 [ - + ]: 2 : if (!pset.quiet)
3180 : : {
3181 [ # # ]: 0 : if (pset.timing)
3182 : 0 : puts(_("Timing is on."));
3183 : : else
3184 : 0 : puts(_("Timing is off."));
3185 : : }
3186 : 2 : free(opt);
3187 : : }
3188 : : else
3189 : 4 : ignore_slash_options(scan_state);
3190 : :
3191 [ + - ]: 6 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3192 : : }
3193 : :
3194 : : /*
3195 : : * \unrestrict -- exit "restricted mode" if provided key matches
3196 : : */
3197 : : static backslashResult
3198 : 37 : exec_command_unrestrict(PsqlScanState scan_state, bool active_branch,
3199 : : const char *cmd)
3200 : : {
3201 [ + + ]: 37 : if (active_branch)
3202 : : {
3203 : : char *opt;
3204 : :
3205 : 33 : opt = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, true);
3206 [ + - - + ]: 33 : if (opt == NULL || opt[0] == '\0')
3207 : : {
3208 : 0 : pg_log_error("\\%s: missing required argument", cmd);
3209 : 0 : return PSQL_CMD_ERROR;
3210 : : }
3211 : :
3212 [ - + ]: 33 : if (!restricted)
3213 : : {
3214 : 0 : pg_log_error("\\%s: not currently in restricted mode", cmd);
3215 : 0 : return PSQL_CMD_ERROR;
3216 : : }
3217 [ + + ]: 33 : else if (strcmp(opt, restrict_key) == 0)
3218 : : {
3219 : 32 : pfree(restrict_key);
3220 : 32 : restricted = false;
3221 : : }
3222 : : else
3223 : : {
3224 : 1 : pg_log_error("\\%s: wrong key", cmd);
3225 : 1 : return PSQL_CMD_ERROR;
3226 : : }
3227 : : }
3228 : : else
3229 : 4 : ignore_slash_whole_line(scan_state);
3230 : :
3231 : 36 : return PSQL_CMD_SKIP_LINE;
3232 : : }
3233 : :
3234 : : /*
3235 : : * \unset -- unset variable
3236 : : */
3237 : : static backslashResult
3238 : 34 : exec_command_unset(PsqlScanState scan_state, bool active_branch,
3239 : : const char *cmd)
3240 : : {
3241 : 34 : bool success = true;
3242 : :
3243 [ + + ]: 34 : if (active_branch)
3244 : : {
3245 : 30 : char *opt = psql_scan_slash_option(scan_state,
3246 : : OT_NORMAL, NULL, false);
3247 : :
3248 [ - + ]: 30 : if (!opt)
3249 : : {
3250 : 0 : pg_log_error("\\%s: missing required argument", cmd);
3251 : 0 : success = false;
3252 : : }
3253 [ - + ]: 30 : else if (!SetVariable(pset.vars, opt, NULL))
3254 : 0 : success = false;
3255 : :
3256 : 30 : free(opt);
3257 : : }
3258 : : else
3259 : 4 : ignore_slash_options(scan_state);
3260 : :
3261 [ + - ]: 34 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3262 : : }
3263 : :
3264 : : /*
3265 : : * \w -- write query buffer to file
3266 : : */
3267 : : static backslashResult
3268 : 8 : exec_command_write(PsqlScanState scan_state, bool active_branch,
3269 : : const char *cmd,
3270 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
3271 : : {
3272 : 8 : backslashResult status = PSQL_CMD_SKIP_LINE;
3273 : :
3274 [ - + ]: 8 : if (active_branch)
3275 : : {
3276 : 0 : char *fname = psql_scan_slash_option(scan_state,
3277 : : OT_FILEPIPE, NULL, true);
3278 : 0 : FILE *fd = NULL;
3279 : 0 : bool is_pipe = false;
3280 : :
3281 [ # # ]: 0 : if (!query_buf)
3282 : : {
3283 : 0 : pg_log_error("no query buffer");
3284 : 0 : status = PSQL_CMD_ERROR;
3285 : : }
3286 : : else
3287 : : {
3288 [ # # ]: 0 : if (!fname)
3289 : : {
3290 : 0 : pg_log_error("\\%s: missing required argument", cmd);
3291 : 0 : status = PSQL_CMD_ERROR;
3292 : : }
3293 : : else
3294 : : {
3295 : 0 : expand_tilde(&fname);
3296 [ # # ]: 0 : if (fname[0] == '|')
3297 : : {
3298 : 0 : is_pipe = true;
3299 : 0 : fflush(NULL);
3300 : 0 : disable_sigpipe_trap();
3301 : 0 : fd = popen(&fname[1], "w");
3302 : : }
3303 : : else
3304 : : {
3305 : 0 : canonicalize_path_enc(fname, pset.encoding);
3306 : 0 : fd = fopen(fname, "w");
3307 : : }
3308 [ # # ]: 0 : if (!fd)
3309 : : {
3310 : 0 : pg_log_error("%s: %m", fname);
3311 : 0 : status = PSQL_CMD_ERROR;
3312 : : }
3313 : : }
3314 : : }
3315 : :
3316 [ # # ]: 0 : if (fd)
3317 : : {
3318 : : int result;
3319 : :
3320 : : /*
3321 : : * We want to print the same thing \g would execute, but not to
3322 : : * change the query buffer state; so we can't use
3323 : : * copy_previous_query(). Also, beware of possibility that buffer
3324 : : * pointers are NULL.
3325 : : */
3326 [ # # # # ]: 0 : if (query_buf && query_buf->len > 0)
3327 : 0 : fprintf(fd, "%s\n", query_buf->data);
3328 [ # # # # ]: 0 : else if (previous_buf && previous_buf->len > 0)
3329 : 0 : fprintf(fd, "%s\n", previous_buf->data);
3330 : :
3331 [ # # ]: 0 : if (is_pipe)
3332 : : {
3333 : 0 : result = pclose(fd);
3334 : :
3335 [ # # ]: 0 : if (result != 0)
3336 : : {
3337 : 0 : pg_log_error("%s: %s", fname, wait_result_to_str(result));
3338 : 0 : status = PSQL_CMD_ERROR;
3339 : : }
3340 : 0 : SetShellResultVariables(result);
3341 : : }
3342 : : else
3343 : : {
3344 : 0 : result = fclose(fd);
3345 : :
3346 [ # # ]: 0 : if (result == EOF)
3347 : : {
3348 : 0 : pg_log_error("%s: %m", fname);
3349 : 0 : status = PSQL_CMD_ERROR;
3350 : : }
3351 : : }
3352 : : }
3353 : :
3354 [ # # ]: 0 : if (is_pipe)
3355 : 0 : restore_sigpipe_trap();
3356 : :
3357 : 0 : free(fname);
3358 : : }
3359 : : else
3360 : 8 : ignore_slash_filepipe(scan_state);
3361 : :
3362 : 8 : return status;
3363 : : }
3364 : :
3365 : : /*
3366 : : * \watch -- execute a query every N seconds.
3367 : : * Optionally, stop after M iterations.
3368 : : */
3369 : : static backslashResult
3370 : 22 : exec_command_watch(PsqlScanState scan_state, bool active_branch,
3371 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
3372 : : {
3373 : 22 : bool success = true;
3374 : :
3375 [ + + ]: 22 : if (active_branch)
3376 : : {
3377 : 18 : bool have_sleep = false;
3378 : 18 : bool have_iter = false;
3379 : 18 : bool have_min_rows = false;
3380 : 18 : double sleep = pset.watch_interval;
3381 : 18 : int iter = 0;
3382 : 18 : int min_rows = 0;
3383 : :
3384 [ + + ]: 18 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
3385 : : {
3386 : 4 : pg_log_error("\\%s not allowed in pipeline mode", "watch");
3387 : 4 : clean_extended_state();
3388 : 4 : success = false;
3389 : : }
3390 : :
3391 : : /*
3392 : : * Parse arguments. We allow either an unlabeled interval or
3393 : : * "name=value", where name is from the set ('i', 'interval', 'c',
3394 : : * 'count', 'm', 'min_rows'). The parsing of interval value should be
3395 : : * kept in sync with ParseVariableDouble which is used for setting the
3396 : : * default interval value.
3397 : : */
3398 [ + + ]: 38 : while (success)
3399 : : {
3400 : 27 : char *opt = psql_scan_slash_option(scan_state,
3401 : : OT_NORMAL, NULL, true);
3402 : : char *valptr;
3403 : : char *opt_end;
3404 : :
3405 [ + + ]: 27 : if (!opt)
3406 : 7 : break; /* no more arguments */
3407 : :
3408 : 20 : valptr = strchr(opt, '=');
3409 [ + + ]: 20 : if (valptr)
3410 : : {
3411 : : /* Labeled argument */
3412 : 12 : valptr++;
3413 [ + + ]: 12 : if (strncmp("i=", opt, strlen("i=")) == 0 ||
3414 [ - + ]: 9 : strncmp("interval=", opt, strlen("interval=")) == 0)
3415 : : {
3416 [ - + ]: 3 : if (have_sleep)
3417 : : {
3418 : 0 : pg_log_error("\\watch: interval value is specified more than once");
3419 : 0 : success = false;
3420 : : }
3421 : : else
3422 : : {
3423 : 3 : have_sleep = true;
3424 : 3 : errno = 0;
3425 : 3 : sleep = strtod(valptr, &opt_end);
3426 [ + - + - : 3 : if (sleep < 0 || *opt_end || errno == ERANGE)
- + ]
3427 : : {
3428 : 0 : pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
3429 : 0 : success = false;
3430 : : }
3431 : : }
3432 : : }
3433 [ + + ]: 9 : else if (strncmp("c=", opt, strlen("c=")) == 0 ||
3434 [ - + ]: 4 : strncmp("count=", opt, strlen("count=")) == 0)
3435 : : {
3436 [ + + ]: 5 : if (have_iter)
3437 : : {
3438 : 1 : pg_log_error("\\watch: iteration count is specified more than once");
3439 : 1 : success = false;
3440 : : }
3441 : : else
3442 : : {
3443 : 4 : have_iter = true;
3444 : 4 : errno = 0;
3445 : 4 : iter = strtoint(valptr, &opt_end, 10);
3446 [ + - + - : 4 : if (iter <= 0 || *opt_end || errno == ERANGE)
- + ]
3447 : : {
3448 : 0 : pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
3449 : 0 : success = false;
3450 : : }
3451 : : }
3452 : : }
3453 [ + + ]: 4 : else if (strncmp("m=", opt, strlen("m=")) == 0 ||
3454 [ + - ]: 1 : strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
3455 : : {
3456 [ + + ]: 4 : if (have_min_rows)
3457 : : {
3458 : 1 : pg_log_error("\\watch: minimum row count specified more than once");
3459 : 1 : success = false;
3460 : : }
3461 : : else
3462 : : {
3463 : 3 : have_min_rows = true;
3464 : 3 : errno = 0;
3465 : 3 : min_rows = strtoint(valptr, &opt_end, 10);
3466 [ + + + - : 3 : if (min_rows <= 0 || *opt_end || errno == ERANGE)
- + ]
3467 : : {
3468 : 1 : pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
3469 : 1 : success = false;
3470 : : }
3471 : : }
3472 : : }
3473 : : else
3474 : : {
3475 : 0 : pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
3476 : 0 : success = false;
3477 : : }
3478 : : }
3479 : : else
3480 : : {
3481 : : /* Unlabeled argument: take it as interval */
3482 [ + + ]: 8 : if (have_sleep)
3483 : : {
3484 : 1 : pg_log_error("\\watch: interval value is specified more than once");
3485 : 1 : success = false;
3486 : : }
3487 : : else
3488 : : {
3489 : 7 : have_sleep = true;
3490 : 7 : errno = 0;
3491 : 7 : sleep = strtod(opt, &opt_end);
3492 [ + + + + : 7 : if (sleep < 0 || *opt_end || errno == ERANGE)
+ + ]
3493 : : {
3494 : 3 : pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3495 : 3 : success = false;
3496 : : }
3497 : : }
3498 : : }
3499 : :
3500 : 20 : free(opt);
3501 : : }
3502 : :
3503 : : /* If we parsed arguments successfully, do the command */
3504 [ + + ]: 18 : if (success)
3505 : : {
3506 : : /* If query_buf is empty, recall and execute previous query */
3507 : 7 : (void) copy_previous_query(query_buf, previous_buf);
3508 : :
3509 : 7 : success = do_watch(query_buf, sleep, iter, min_rows);
3510 : : }
3511 : :
3512 : : /* Reset the query buffer as though for \r */
3513 : 16 : resetPQExpBuffer(query_buf);
3514 : 16 : psql_scan_reset(scan_state);
3515 : : }
3516 : : else
3517 : 4 : ignore_slash_options(scan_state);
3518 : :
3519 [ + + ]: 20 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3520 : : }
3521 : :
3522 : : /*
3523 : : * \x -- set or toggle expanded table representation
3524 : : */
3525 : : static backslashResult
3526 : 49 : exec_command_x(PsqlScanState scan_state, bool active_branch)
3527 : : {
3528 : 49 : bool success = true;
3529 : :
3530 [ + + ]: 49 : if (active_branch)
3531 : : {
3532 : 45 : char *opt = psql_scan_slash_option(scan_state,
3533 : : OT_NORMAL, NULL, true);
3534 : :
3535 : 45 : success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3536 : 45 : free(opt);
3537 : : }
3538 : : else
3539 : 4 : ignore_slash_options(scan_state);
3540 : :
3541 [ + - ]: 49 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3542 : : }
3543 : :
3544 : : /*
3545 : : * \z -- list table privileges (equivalent to \dp)
3546 : : */
3547 : : static backslashResult
3548 : 20 : exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
3549 : : {
3550 : 20 : bool success = true;
3551 : :
3552 [ + + ]: 20 : if (active_branch)
3553 : : {
3554 : : char *pattern;
3555 : : bool show_system;
3556 : : unsigned short int save_expanded;
3557 : :
3558 : 16 : pattern = psql_scan_slash_option(scan_state,
3559 : : OT_NORMAL, NULL, true);
3560 : :
3561 : 16 : show_system = strchr(cmd, 'S') ? true : false;
3562 : :
3563 : : /* if 'x' option specified, force expanded mode */
3564 : 16 : save_expanded = pset.popt.topt.expanded;
3565 [ + + ]: 16 : if (strchr(cmd, 'x'))
3566 : 4 : pset.popt.topt.expanded = 1;
3567 : :
3568 : 16 : success = permissionsList(pattern, show_system);
3569 : :
3570 : : /* restore original expanded mode */
3571 : 16 : pset.popt.topt.expanded = save_expanded;
3572 : :
3573 : 16 : free(pattern);
3574 : : }
3575 : : else
3576 : 4 : ignore_slash_options(scan_state);
3577 : :
3578 [ + - ]: 20 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3579 : : }
3580 : :
3581 : : /*
3582 : : * \! -- execute shell command
3583 : : */
3584 : : static backslashResult
3585 : 4 : exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
3586 : : {
3587 : 4 : bool success = true;
3588 : :
3589 [ - + ]: 4 : if (active_branch)
3590 : : {
3591 : 0 : char *opt = psql_scan_slash_option(scan_state,
3592 : : OT_WHOLE_LINE, NULL, false);
3593 : :
3594 : 0 : success = do_shell(opt);
3595 : 0 : free(opt);
3596 : : }
3597 : : else
3598 : 4 : ignore_slash_whole_line(scan_state);
3599 : :
3600 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3601 : : }
3602 : :
3603 : : /*
3604 : : * \? -- print help about backslash commands
3605 : : */
3606 : : static backslashResult
3607 : 4 : exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
3608 : : {
3609 [ - + ]: 4 : if (active_branch)
3610 : : {
3611 : 0 : char *opt0 = psql_scan_slash_option(scan_state,
3612 : : OT_NORMAL, NULL, false);
3613 : :
3614 [ # # # # ]: 0 : if (!opt0 || strcmp(opt0, "commands") == 0)
3615 : 0 : slashUsage(pset.popt.topt.pager);
3616 [ # # ]: 0 : else if (strcmp(opt0, "options") == 0)
3617 : 0 : usage(pset.popt.topt.pager);
3618 [ # # ]: 0 : else if (strcmp(opt0, "variables") == 0)
3619 : 0 : helpVariables(pset.popt.topt.pager);
3620 : : else
3621 : 0 : slashUsage(pset.popt.topt.pager);
3622 : :
3623 : 0 : free(opt0);
3624 : : }
3625 : : else
3626 : 4 : ignore_slash_options(scan_state);
3627 : :
3628 : 4 : return PSQL_CMD_SKIP_LINE;
3629 : : }
3630 : :
3631 : :
3632 : : /*
3633 : : * Read and interpret an argument to the \connect slash command.
3634 : : *
3635 : : * Returns a malloc'd string, or NULL if no/empty argument.
3636 : : */
3637 : : static char *
3638 : 899 : read_connect_arg(PsqlScanState scan_state)
3639 : : {
3640 : : char *result;
3641 : : char quote;
3642 : :
3643 : : /*
3644 : : * Ideally we should treat the arguments as SQL identifiers. But for
3645 : : * backwards compatibility with 7.2 and older pg_dump files, we have to
3646 : : * take unquoted arguments verbatim (don't downcase them). For now,
3647 : : * double-quoted arguments may be stripped of double quotes (as if SQL
3648 : : * identifiers). By 7.4 or so, pg_dump files can be expected to
3649 : : * double-quote all mixed-case \connect arguments, and then we can get rid
3650 : : * of OT_SQLIDHACK.
3651 : : */
3652 : 899 : result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
3653 : :
3654 [ + + ]: 899 : if (!result)
3655 : 726 : return NULL;
3656 : :
3657 [ + + ]: 173 : if (quote)
3658 : 12 : return result;
3659 : :
3660 [ + - + + ]: 161 : if (*result == '\0' || strcmp(result, "-") == 0)
3661 : : {
3662 : 141 : free(result);
3663 : 141 : return NULL;
3664 : : }
3665 : :
3666 : 20 : return result;
3667 : : }
3668 : :
3669 : : /*
3670 : : * Read a boolean expression, return it as a PQExpBuffer string.
3671 : : *
3672 : : * Note: anything more or less than one token will certainly fail to be
3673 : : * parsed by ParseVariableBool, so we don't worry about complaining here.
3674 : : * This routine's return data structure will need to be rethought anyway
3675 : : * to support likely future extensions such as "\if defined VARNAME".
3676 : : */
3677 : : static PQExpBuffer
3678 : 180 : gather_boolean_expression(PsqlScanState scan_state)
3679 : : {
3680 : 180 : PQExpBuffer exp_buf = createPQExpBuffer();
3681 : 180 : int num_options = 0;
3682 : : char *value;
3683 : :
3684 : : /* collect all arguments for the conditional command into exp_buf */
3685 : 368 : while ((value = psql_scan_slash_option(scan_state,
3686 [ + + ]: 368 : OT_NORMAL, NULL, false)) != NULL)
3687 : : {
3688 : : /* add spaces between tokens */
3689 [ + + ]: 188 : if (num_options > 0)
3690 : 8 : appendPQExpBufferChar(exp_buf, ' ');
3691 : 188 : appendPQExpBufferStr(exp_buf, value);
3692 : 188 : num_options++;
3693 : 188 : free(value);
3694 : : }
3695 : :
3696 : 180 : return exp_buf;
3697 : : }
3698 : :
3699 : : /*
3700 : : * Read a boolean expression, return true if the expression
3701 : : * was a valid boolean expression that evaluated to true.
3702 : : * Otherwise return false.
3703 : : *
3704 : : * Note: conditional stack's top state must be active, else lexer will
3705 : : * fail to expand variables and backticks.
3706 : : */
3707 : : static bool
3708 : 168 : is_true_boolean_expression(PsqlScanState scan_state, const char *name)
3709 : : {
3710 : 168 : PQExpBuffer buf = gather_boolean_expression(scan_state);
3711 : 168 : bool value = false;
3712 : 168 : bool success = ParseVariableBool(buf->data, name, &value);
3713 : :
3714 : 168 : destroyPQExpBuffer(buf);
3715 [ + + + + ]: 168 : return success && value;
3716 : : }
3717 : :
3718 : : /*
3719 : : * Read a boolean expression, but do nothing with it.
3720 : : *
3721 : : * Note: conditional stack's top state must be INACTIVE, else lexer will
3722 : : * expand variables and backticks, which we do not want here.
3723 : : */
3724 : : static void
3725 : 12 : ignore_boolean_expression(PsqlScanState scan_state)
3726 : : {
3727 : 12 : PQExpBuffer buf = gather_boolean_expression(scan_state);
3728 : :
3729 : 12 : destroyPQExpBuffer(buf);
3730 : 12 : }
3731 : :
3732 : : /*
3733 : : * Read and discard "normal" slash command options.
3734 : : *
3735 : : * This should be used for inactive-branch processing of any slash command
3736 : : * that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
3737 : : * We don't need to worry about exactly how many it would eat, since the
3738 : : * cleanup logic in HandleSlashCmds would silently discard any extras anyway.
3739 : : */
3740 : : static void
3741 : 256 : ignore_slash_options(PsqlScanState scan_state)
3742 : : {
3743 : : char *arg;
3744 : :
3745 : 572 : while ((arg = psql_scan_slash_option(scan_state,
3746 [ + + ]: 572 : OT_NORMAL, NULL, false)) != NULL)
3747 : 316 : free(arg);
3748 : 256 : }
3749 : :
3750 : : /*
3751 : : * Read and discard FILEPIPE slash command argument.
3752 : : *
3753 : : * This *MUST* be used for inactive-branch processing of any slash command
3754 : : * that takes an OT_FILEPIPE option. Otherwise we might consume a different
3755 : : * amount of option text in active and inactive cases.
3756 : : */
3757 : : static void
3758 : 12 : ignore_slash_filepipe(PsqlScanState scan_state)
3759 : : {
3760 : 12 : char *arg = psql_scan_slash_option(scan_state,
3761 : : OT_FILEPIPE, NULL, false);
3762 : :
3763 : 12 : free(arg);
3764 : 12 : }
3765 : :
3766 : : /*
3767 : : * Read and discard whole-line slash command argument.
3768 : : *
3769 : : * This *MUST* be used for inactive-branch processing of any slash command
3770 : : * that takes an OT_WHOLE_LINE option. Otherwise we might consume a different
3771 : : * amount of option text in active and inactive cases.
3772 : : *
3773 : : * Note: although callers might pass "semicolon" as either true or false,
3774 : : * we need not duplicate that here, since it doesn't affect the amount of
3775 : : * input text consumed.
3776 : : */
3777 : : static void
3778 : 32 : ignore_slash_whole_line(PsqlScanState scan_state)
3779 : : {
3780 : 32 : char *arg = psql_scan_slash_option(scan_state,
3781 : : OT_WHOLE_LINE, NULL, false);
3782 : :
3783 : 32 : free(arg);
3784 : 32 : }
3785 : :
3786 : : /*
3787 : : * Return true if the command given is a branching command.
3788 : : */
3789 : : static bool
3790 : 0 : is_branching_command(const char *cmd)
3791 : : {
3792 : 0 : return (strcmp(cmd, "if") == 0 ||
3793 [ # # ]: 0 : strcmp(cmd, "elif") == 0 ||
3794 [ # # # # ]: 0 : strcmp(cmd, "else") == 0 ||
3795 [ # # ]: 0 : strcmp(cmd, "endif") == 0);
3796 : : }
3797 : :
3798 : : /*
3799 : : * Prepare to possibly restore query buffer to its current state
3800 : : * (cf. discard_query_text).
3801 : : *
3802 : : * We need to remember the length of the query buffer, and assorted
3803 : : * lexer internal state such as parenthesis nesting depth.
3804 : : */
3805 : : static void
3806 : 200 : save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
3807 : : PQExpBuffer query_buf)
3808 : : {
3809 [ + - ]: 200 : if (query_buf)
3810 : 200 : conditional_stack_set_query_len(cstack, query_buf->len);
3811 : 200 : conditional_stack_set_lex_state(cstack,
3812 : : psql_scan_get_lex_state(scan_state));
3813 : 200 : }
3814 : :
3815 : : /*
3816 : : * Discard any query text absorbed during an inactive conditional branch.
3817 : : *
3818 : : * We must discard data that was appended to query_buf during an inactive
3819 : : * \if branch. We don't have to do anything there if there's no query_buf.
3820 : : *
3821 : : * Also, reset the lexer's state to what it was before.
3822 : : */
3823 : : static void
3824 : 169 : discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
3825 : : PQExpBuffer query_buf)
3826 : : {
3827 [ + - ]: 169 : if (query_buf)
3828 : : {
3829 : 169 : int new_len = conditional_stack_get_query_len(cstack);
3830 : :
3831 : : Assert(new_len >= 0 && new_len <= query_buf->len);
3832 : 169 : query_buf->len = new_len;
3833 : 169 : query_buf->data[new_len] = '\0';
3834 : : }
3835 : 169 : psql_scan_set_lex_state(scan_state,
3836 : 169 : conditional_stack_get_lex_state(cstack));
3837 : 169 : }
3838 : :
3839 : : /*
3840 : : * If query_buf is empty, copy previous_buf into it.
3841 : : *
3842 : : * This is used by various slash commands for which re-execution of a
3843 : : * previous query is a common usage. For convenience, we allow the
3844 : : * case of query_buf == NULL (and do nothing).
3845 : : *
3846 : : * Returns "true" if the previous query was copied into the query
3847 : : * buffer, else "false".
3848 : : */
3849 : : static bool
3850 : 2296 : copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
3851 : : {
3852 [ + - + + ]: 2296 : if (query_buf && query_buf->len == 0)
3853 : : {
3854 : 880 : appendPQExpBufferStr(query_buf, previous_buf->data);
3855 : 880 : return true;
3856 : : }
3857 : 1416 : return false;
3858 : : }
3859 : :
3860 : : /*
3861 : : * Ask the user for a password; 'username' is the username the
3862 : : * password is for, if one has been explicitly specified.
3863 : : * Returns a malloc'd string.
3864 : : * If 'canceled' is provided, *canceled will be set to true if the prompt
3865 : : * is canceled via SIGINT, and to false otherwise.
3866 : : */
3867 : : static char *
3868 : 0 : prompt_for_password(const char *username, bool *canceled)
3869 : : {
3870 : : char *result;
3871 : : PromptInterruptContext prompt_ctx;
3872 : :
3873 : : /* Set up to let SIGINT cancel simple_prompt_extended() */
3874 : 0 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3875 : 0 : prompt_ctx.enabled = &sigint_interrupt_enabled;
3876 : 0 : prompt_ctx.canceled = false;
3877 : :
3878 [ # # # # ]: 0 : if (username == NULL || username[0] == '\0')
3879 : 0 : result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3880 : : else
3881 : : {
3882 : : char *prompt_text;
3883 : :
3884 : 0 : prompt_text = psprintf(_("Password for user %s: "), username);
3885 : 0 : result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3886 : 0 : pfree(prompt_text);
3887 : : }
3888 : :
3889 [ # # ]: 0 : if (canceled)
3890 : 0 : *canceled = prompt_ctx.canceled;
3891 : :
3892 : 0 : return result;
3893 : : }
3894 : :
3895 : : static bool
3896 : 24 : param_is_newly_set(const char *old_val, const char *new_val)
3897 : : {
3898 [ - + ]: 24 : if (new_val == NULL)
3899 : 0 : return false;
3900 : :
3901 [ + - - + ]: 24 : if (old_val == NULL || strcmp(old_val, new_val) != 0)
3902 : 0 : return true;
3903 : :
3904 : 24 : return false;
3905 : : }
3906 : :
3907 : : /*
3908 : : * do_connect -- handler for \connect
3909 : : *
3910 : : * Connects to a database with given parameters. If we are told to re-use
3911 : : * parameters, parameters from the previous connection are used where the
3912 : : * command's own options do not supply a value. Otherwise, libpq defaults
3913 : : * are used.
3914 : : *
3915 : : * In interactive mode, if connection fails with the given parameters,
3916 : : * the old connection will be kept.
3917 : : */
3918 : : static bool
3919 : 222 : do_connect(enum trivalue reuse_previous_specification,
3920 : : char *dbname, char *user, char *host, char *port)
3921 : : {
3922 : 222 : PGconn *o_conn = pset.db,
3923 : 222 : *n_conn = NULL;
3924 : : PQconninfoOption *cinfo;
3925 : 222 : int nconnopts = 0;
3926 : 222 : bool same_host = false;
3927 : 222 : char *password = NULL;
3928 : : char *client_encoding;
3929 : 222 : bool success = true;
3930 : 222 : bool keep_password = true;
3931 : : bool has_connection_string;
3932 : : bool reuse_previous;
3933 : :
3934 : 222 : has_connection_string = dbname ?
3935 [ + + + + ]: 222 : recognized_connection_string(dbname) : false;
3936 : :
3937 : : /* Complain if we have additional arguments after a connection string. */
3938 [ + + + - : 222 : if (has_connection_string && (user || host || port))
+ - - + ]
3939 : : {
3940 : 0 : pg_log_error("Do not give user, host, or port separately when using a connection string");
3941 : 0 : return false;
3942 : : }
3943 : :
3944 [ + - + ]: 222 : switch (reuse_previous_specification)
3945 : : {
3946 : 11 : case TRI_YES:
3947 : 11 : reuse_previous = true;
3948 : 11 : break;
3949 : 0 : case TRI_NO:
3950 : 0 : reuse_previous = false;
3951 : 0 : break;
3952 : 211 : default:
3953 : 211 : reuse_previous = !has_connection_string;
3954 : 211 : break;
3955 : : }
3956 : :
3957 : : /*
3958 : : * If we intend to re-use connection parameters, collect them out of the
3959 : : * old connection, then replace individual values as necessary. (We may
3960 : : * need to resort to looking at pset.dead_conn, if the connection died
3961 : : * previously.) Otherwise, obtain a PQconninfoOption array containing
3962 : : * libpq's defaults, and modify that. Note this function assumes that
3963 : : * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3964 : : * containing the same options in the same order.
3965 : : */
3966 [ + - ]: 222 : if (reuse_previous)
3967 : : {
3968 [ + - ]: 222 : if (o_conn)
3969 : 222 : cinfo = PQconninfo(o_conn);
3970 [ # # ]: 0 : else if (pset.dead_conn)
3971 : 0 : cinfo = PQconninfo(pset.dead_conn);
3972 : : else
3973 : : {
3974 : : /* This is reachable after a non-interactive \connect failure */
3975 : 0 : pg_log_error("No database connection exists to re-use parameters from");
3976 : 0 : return false;
3977 : : }
3978 : : }
3979 : : else
3980 : 0 : cinfo = PQconndefaults();
3981 : :
3982 [ + - ]: 222 : if (cinfo)
3983 : : {
3984 [ + + ]: 222 : if (has_connection_string)
3985 : : {
3986 : : /* Parse the connstring and insert values into cinfo */
3987 : : PQconninfoOption *replcinfo;
3988 : : char *errmsg;
3989 : :
3990 : 11 : replcinfo = PQconninfoParse(dbname, &errmsg);
3991 [ + - ]: 11 : if (replcinfo)
3992 : : {
3993 : : PQconninfoOption *ci;
3994 : : PQconninfoOption *replci;
3995 : 11 : bool have_password = false;
3996 : :
3997 : 11 : for (ci = cinfo, replci = replcinfo;
3998 [ + + + - ]: 583 : ci->keyword && replci->keyword;
3999 : 572 : ci++, replci++)
4000 : : {
4001 : : Assert(strcmp(ci->keyword, replci->keyword) == 0);
4002 : : /* Insert value from connstring if one was provided */
4003 [ + + ]: 572 : if (replci->val)
4004 : : {
4005 : : /*
4006 : : * We know that both val strings were allocated by
4007 : : * libpq, so the least messy way to avoid memory leaks
4008 : : * is to swap them.
4009 : : */
4010 : 14 : char *swap = replci->val;
4011 : :
4012 : 14 : replci->val = ci->val;
4013 : 14 : ci->val = swap;
4014 : :
4015 : : /*
4016 : : * Check whether connstring provides options affecting
4017 : : * password re-use. While any change in user, host,
4018 : : * hostaddr, or port causes us to ignore the old
4019 : : * connection's password, we don't force that for
4020 : : * dbname, since passwords aren't database-specific.
4021 : : */
4022 [ + - ]: 14 : if (replci->val == NULL ||
4023 [ + - ]: 14 : strcmp(ci->val, replci->val) != 0)
4024 : : {
4025 [ + + ]: 14 : if (strcmp(replci->keyword, "user") == 0 ||
4026 [ + - ]: 11 : strcmp(replci->keyword, "host") == 0 ||
4027 [ + - ]: 11 : strcmp(replci->keyword, "hostaddr") == 0 ||
4028 [ - + ]: 11 : strcmp(replci->keyword, "port") == 0)
4029 : 3 : keep_password = false;
4030 : : }
4031 : : /* Also note whether connstring contains a password. */
4032 [ - + ]: 14 : if (strcmp(replci->keyword, "password") == 0)
4033 : 0 : have_password = true;
4034 : : }
4035 [ - + ]: 558 : else if (!reuse_previous)
4036 : : {
4037 : : /*
4038 : : * When we have a connstring and are not re-using
4039 : : * parameters, swap *all* entries, even those not set
4040 : : * by the connstring. This avoids absorbing
4041 : : * environment-dependent defaults from the result of
4042 : : * PQconndefaults(). We don't want to do that because
4043 : : * they'd override service-file entries if the
4044 : : * connstring specifies a service parameter, whereas
4045 : : * the priority should be the other way around. libpq
4046 : : * can certainly recompute any defaults we don't pass
4047 : : * here. (In this situation, it's a bit wasteful to
4048 : : * have called PQconndefaults() at all, but not doing
4049 : : * so would require yet another major code path here.)
4050 : : */
4051 : 0 : replci->val = ci->val;
4052 : 0 : ci->val = NULL;
4053 : : }
4054 : : }
4055 : : Assert(ci->keyword == NULL && replci->keyword == NULL);
4056 : :
4057 : : /* While here, determine how many option slots there are */
4058 : 11 : nconnopts = ci - cinfo;
4059 : :
4060 : 11 : PQconninfoFree(replcinfo);
4061 : :
4062 : : /*
4063 : : * If the connstring contains a password, tell the loop below
4064 : : * that we may use it, regardless of other settings (i.e.,
4065 : : * cinfo's password is no longer an "old" password).
4066 : : */
4067 [ - + ]: 11 : if (have_password)
4068 : 0 : keep_password = true;
4069 : :
4070 : : /* Don't let code below try to inject dbname into params. */
4071 : 11 : dbname = NULL;
4072 : : }
4073 : : else
4074 : : {
4075 : : /* PQconninfoParse failed */
4076 [ # # ]: 0 : if (errmsg)
4077 : : {
4078 : 0 : pg_log_error("%s", errmsg);
4079 : 0 : PQfreemem(errmsg);
4080 : : }
4081 : : else
4082 : 0 : pg_log_error("out of memory");
4083 : 0 : success = false;
4084 : : }
4085 : : }
4086 : : else
4087 : : {
4088 : : /*
4089 : : * If dbname isn't a connection string, then we'll inject it and
4090 : : * the other parameters into the keyword array below. (We can't
4091 : : * easily insert them into the cinfo array because of memory
4092 : : * management issues: PQconninfoFree would misbehave on Windows.)
4093 : : * However, to avoid dependencies on the order in which parameters
4094 : : * appear in the array, make a preliminary scan to set
4095 : : * keep_password and same_host correctly.
4096 : : *
4097 : : * While any change in user, host, or port causes us to ignore the
4098 : : * old connection's password, we don't force that for dbname,
4099 : : * since passwords aren't database-specific.
4100 : : */
4101 : : PQconninfoOption *ci;
4102 : :
4103 [ + + ]: 11183 : for (ci = cinfo; ci->keyword; ci++)
4104 : : {
4105 [ + + + + ]: 10972 : if (user && strcmp(ci->keyword, "user") == 0)
4106 : : {
4107 [ + - + - ]: 4 : if (!(ci->val && strcmp(user, ci->val) == 0))
4108 : 4 : keep_password = false;
4109 : : }
4110 [ - + - - ]: 10968 : else if (host && strcmp(ci->keyword, "host") == 0)
4111 : : {
4112 [ # # # # ]: 0 : if (ci->val && strcmp(host, ci->val) == 0)
4113 : 0 : same_host = true;
4114 : : else
4115 : 0 : keep_password = false;
4116 : : }
4117 [ - + - - ]: 10968 : else if (port && strcmp(ci->keyword, "port") == 0)
4118 : : {
4119 [ # # # # ]: 0 : if (!(ci->val && strcmp(port, ci->val) == 0))
4120 : 0 : keep_password = false;
4121 : : }
4122 : : }
4123 : :
4124 : : /* While here, determine how many option slots there are */
4125 : 211 : nconnopts = ci - cinfo;
4126 : : }
4127 : : }
4128 : : else
4129 : : {
4130 : : /* We failed to create the cinfo structure */
4131 : 0 : pg_log_error("out of memory");
4132 : 0 : success = false;
4133 : : }
4134 : :
4135 : : /*
4136 : : * If the user asked to be prompted for a password, ask for one now. If
4137 : : * not, use the password from the old connection, provided the username
4138 : : * etc have not changed. Otherwise, try to connect without a password
4139 : : * first, and then ask for a password if needed.
4140 : : *
4141 : : * XXX: this behavior leads to spurious connection attempts recorded in
4142 : : * the postmaster's log. But libpq offers no API that would let us obtain
4143 : : * a password and then continue with the first connection attempt.
4144 : : */
4145 [ - + - - ]: 222 : if (pset.getPassword == TRI_YES && success)
4146 : : {
4147 : 0 : bool canceled = false;
4148 : :
4149 : : /*
4150 : : * If a connstring or URI is provided, we don't know which username
4151 : : * will be used, since we haven't dug that out of the connstring.
4152 : : * Don't risk issuing a misleading prompt. As in startup.c, it does
4153 : : * not seem worth working harder, since this getPassword setting is
4154 : : * normally only used in noninteractive cases.
4155 : : */
4156 [ # # ]: 0 : password = prompt_for_password(has_connection_string ? NULL : user,
4157 : : &canceled);
4158 : 0 : success = !canceled;
4159 : : }
4160 : :
4161 : : /*
4162 : : * Consider whether to force client_encoding to "auto" (overriding
4163 : : * anything in the connection string). We do so if we have a terminal
4164 : : * connection and there is no PGCLIENTENCODING environment setting.
4165 : : */
4166 [ - + - - ]: 222 : if (pset.notty || getenv("PGCLIENTENCODING"))
4167 : 222 : client_encoding = NULL;
4168 : : else
4169 : 0 : client_encoding = "auto";
4170 : :
4171 : : /* Loop till we have a connection or fail, which we might've already */
4172 [ + - ]: 222 : while (success)
4173 : : {
4174 : 222 : const char **keywords = pg_malloc_array(const char *, nconnopts + 1);
4175 : 222 : const char **values = pg_malloc_array(const char *, nconnopts + 1);
4176 : 222 : int paramnum = 0;
4177 : : PQconninfoOption *ci;
4178 : :
4179 : : /*
4180 : : * Copy non-default settings into the PQconnectdbParams parameter
4181 : : * arrays; but inject any values specified old-style, as well as any
4182 : : * interactively-obtained password, and a couple of fields we want to
4183 : : * set forcibly.
4184 : : *
4185 : : * If you change this code, see also the initial-connection code in
4186 : : * main().
4187 : : */
4188 [ + + ]: 11766 : for (ci = cinfo; ci->keyword; ci++)
4189 : : {
4190 : 11544 : keywords[paramnum] = ci->keyword;
4191 : :
4192 [ + + + + ]: 11544 : if (dbname && strcmp(ci->keyword, "dbname") == 0)
4193 : 6 : values[paramnum++] = dbname;
4194 [ + + + + ]: 11538 : else if (user && strcmp(ci->keyword, "user") == 0)
4195 : 4 : values[paramnum++] = user;
4196 [ - + - - ]: 11534 : else if (host && strcmp(ci->keyword, "host") == 0)
4197 : 0 : values[paramnum++] = host;
4198 [ - + - - : 11534 : else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
- - ]
4199 : : {
4200 : : /* If we're changing the host value, drop any old hostaddr */
4201 : 0 : values[paramnum++] = NULL;
4202 : : }
4203 [ - + - - ]: 11534 : else if (port && strcmp(ci->keyword, "port") == 0)
4204 : 0 : values[paramnum++] = port;
4205 : : /* If !keep_password, we unconditionally drop old password */
4206 [ + - + + ]: 11534 : else if ((password || !keep_password) &&
4207 [ + + ]: 360 : strcmp(ci->keyword, "password") == 0)
4208 : 7 : values[paramnum++] = password;
4209 [ + + ]: 11527 : else if (strcmp(ci->keyword, "fallback_application_name") == 0)
4210 : 222 : values[paramnum++] = pset.progname;
4211 [ - + ]: 11305 : else if (client_encoding &&
4212 [ # # ]: 0 : strcmp(ci->keyword, "client_encoding") == 0)
4213 : 0 : values[paramnum++] = client_encoding;
4214 [ + + ]: 11305 : else if (ci->val)
4215 : 4220 : values[paramnum++] = ci->val;
4216 : : /* else, don't bother making libpq parse this keyword */
4217 : : }
4218 : : /* add array terminator */
4219 : 222 : keywords[paramnum] = NULL;
4220 : 222 : values[paramnum] = NULL;
4221 : :
4222 : : /* Note we do not want libpq to re-expand the dbname parameter */
4223 : 222 : n_conn = PQconnectStartParams(keywords, values, false);
4224 : :
4225 : 222 : pg_free(keywords);
4226 : 222 : pg_free(values);
4227 : :
4228 : 222 : wait_until_connected(n_conn);
4229 [ + - ]: 222 : if (PQstatus(n_conn) == CONNECTION_OK)
4230 : 222 : break;
4231 : :
4232 : : /*
4233 : : * Connection attempt failed; either retry the connection attempt with
4234 : : * a new password, or give up.
4235 : : */
4236 [ # # # # : 0 : if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
# # ]
4237 : 0 : {
4238 : 0 : bool canceled = false;
4239 : :
4240 : : /*
4241 : : * Prompt for password using the username we actually connected
4242 : : * with --- it might've come out of "dbname" rather than "user".
4243 : : */
4244 : 0 : password = prompt_for_password(PQuser(n_conn), &canceled);
4245 : 0 : PQfinish(n_conn);
4246 : 0 : n_conn = NULL;
4247 : 0 : success = !canceled;
4248 : 0 : continue;
4249 : : }
4250 : :
4251 : : /*
4252 : : * We'll report the error below ... unless n_conn is NULL, indicating
4253 : : * that libpq didn't have enough memory to make a PGconn.
4254 : : */
4255 [ # # ]: 0 : if (n_conn == NULL)
4256 : 0 : pg_log_error("out of memory");
4257 : :
4258 : 0 : success = false;
4259 : : } /* end retry loop */
4260 : :
4261 : : /* Release locally allocated data, whether we succeeded or not */
4262 : 222 : pg_free(password);
4263 : 222 : PQconninfoFree(cinfo);
4264 : :
4265 [ - + ]: 222 : if (!success)
4266 : : {
4267 : : /*
4268 : : * Failed to connect to the database. In interactive mode, keep the
4269 : : * previous connection to the DB; in scripting mode, close our
4270 : : * previous connection as well.
4271 : : */
4272 [ # # ]: 0 : if (pset.cur_cmd_interactive)
4273 : : {
4274 [ # # ]: 0 : if (n_conn)
4275 : : {
4276 : 0 : pg_log_info("%s", PQerrorMessage(n_conn));
4277 : 0 : PQfinish(n_conn);
4278 : : }
4279 : :
4280 : : /* pset.db is left unmodified */
4281 [ # # ]: 0 : if (o_conn)
4282 : 0 : pg_log_info("Previous connection kept");
4283 : : }
4284 : : else
4285 : : {
4286 [ # # ]: 0 : if (n_conn)
4287 : : {
4288 : 0 : pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
4289 : 0 : PQfinish(n_conn);
4290 : : }
4291 : :
4292 [ # # ]: 0 : if (o_conn)
4293 : : {
4294 : : /*
4295 : : * Transition to having no connection.
4296 : : *
4297 : : * Unlike CheckConnection(), we close the old connection
4298 : : * immediately to prevent its parameters from being re-used.
4299 : : * This is so that a script cannot accidentally reuse
4300 : : * parameters it did not expect to. Otherwise, the state
4301 : : * cleanup should be the same as in CheckConnection().
4302 : : */
4303 : 0 : PQfinish(o_conn);
4304 : 0 : pset.db = NULL;
4305 : 0 : ResetCancelConn();
4306 : 0 : UnsyncVariables();
4307 : : }
4308 : :
4309 : : /* On the same reasoning, release any dead_conn to prevent reuse */
4310 [ # # ]: 0 : if (pset.dead_conn)
4311 : : {
4312 : 0 : PQfinish(pset.dead_conn);
4313 : 0 : pset.dead_conn = NULL;
4314 : : }
4315 : : }
4316 : :
4317 : 0 : return false;
4318 : : }
4319 : :
4320 : : /*
4321 : : * Replace the old connection with the new one, and update
4322 : : * connection-dependent variables. Keep the resynchronization logic in
4323 : : * sync with CheckConnection().
4324 : : */
4325 : 222 : PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
4326 : 222 : pset.db = n_conn;
4327 : 222 : SyncVariables();
4328 : 222 : connection_warnings(false); /* Must be after SyncVariables */
4329 : :
4330 : : /* Tell the user about the new connection */
4331 [ + + ]: 222 : if (!pset.quiet)
4332 : : {
4333 [ + - + - ]: 24 : if (!o_conn ||
4334 [ - + ]: 24 : param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
4335 : 12 : param_is_newly_set(PQport(o_conn), PQport(pset.db)))
4336 : 0 : {
4337 : 0 : char *connhost = PQhost(pset.db);
4338 : 0 : char *hostaddr = PQhostaddr(pset.db);
4339 : :
4340 [ # # ]: 0 : if (is_unixsock_path(connhost))
4341 : : {
4342 : : /* hostaddr overrides connhost */
4343 [ # # # # ]: 0 : if (hostaddr && *hostaddr)
4344 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
4345 : : PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
4346 : : else
4347 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
4348 : : PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4349 : : }
4350 : : else
4351 : : {
4352 [ # # # # : 0 : if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
# # ]
4353 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
4354 : : PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
4355 : : else
4356 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
4357 : : PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4358 : : }
4359 : : }
4360 : : else
4361 : 12 : printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
4362 : : PQdb(pset.db), PQuser(pset.db));
4363 : : }
4364 : :
4365 : : /* Drop no-longer-needed connection(s) */
4366 [ + - ]: 222 : if (o_conn)
4367 : 222 : PQfinish(o_conn);
4368 [ - + ]: 222 : if (pset.dead_conn)
4369 : : {
4370 : 0 : PQfinish(pset.dead_conn);
4371 : 0 : pset.dead_conn = NULL;
4372 : : }
4373 : :
4374 : 222 : return true;
4375 : : }
4376 : :
4377 : : /*
4378 : : * Processes the connection sequence described by PQconnectStartParams(). Don't
4379 : : * worry about reporting errors in this function. Our caller will check the
4380 : : * connection's status, and report appropriately.
4381 : : */
4382 : : static void
4383 : 222 : wait_until_connected(PGconn *conn)
4384 : : {
4385 : 222 : bool forRead = false;
4386 : :
4387 : : while (true)
4388 : 225 : {
4389 : : int rc;
4390 : : int sock;
4391 : : pg_usec_time_t end_time;
4392 : :
4393 : : /*
4394 : : * On every iteration of the connection sequence, let's check if the
4395 : : * user has requested a cancellation.
4396 : : */
4397 [ - + ]: 447 : if (cancel_pressed)
4398 : 0 : break;
4399 : :
4400 : : /*
4401 : : * Do not assume that the socket remains the same across
4402 : : * PQconnectPoll() calls.
4403 : : */
4404 : 447 : sock = PQsocket(conn);
4405 [ - + ]: 447 : if (sock == -1)
4406 : 0 : break;
4407 : :
4408 : : /*
4409 : : * If the user sends SIGINT between the cancel_pressed check, and
4410 : : * polling of the socket, it will not be recognized. Instead, we will
4411 : : * just wait until the next step in the connection sequence or
4412 : : * forever, which might require users to send SIGTERM or SIGQUIT.
4413 : : *
4414 : : * Some solutions would include the "self-pipe trick," using
4415 : : * pselect(2) and ppoll(2), or using a timeout.
4416 : : *
4417 : : * The self-pipe trick requires a bit of code to setup. pselect(2) and
4418 : : * ppoll(2) are not on all the platforms we support. The simplest
4419 : : * solution happens to just be adding a timeout, so let's wait for 1
4420 : : * second and check cancel_pressed again.
4421 : : */
4422 : 447 : end_time = PQgetCurrentTimeUSec() + 1000000;
4423 : 447 : rc = PQsocketPoll(sock, forRead, !forRead, end_time);
4424 [ - + ]: 447 : if (rc == -1)
4425 : 0 : return;
4426 : :
4427 [ + + - - ]: 447 : switch (PQconnectPoll(conn))
4428 : : {
4429 : 222 : case PGRES_POLLING_OK:
4430 : : case PGRES_POLLING_FAILED:
4431 : 222 : return;
4432 : 225 : case PGRES_POLLING_READING:
4433 : 225 : forRead = true;
4434 : 225 : continue;
4435 : 0 : case PGRES_POLLING_WRITING:
4436 : 0 : forRead = false;
4437 : 0 : continue;
4438 : : case PGRES_POLLING_ACTIVE:
4439 : : pg_unreachable();
4440 : : }
4441 : : }
4442 : : }
4443 : :
4444 : : void
4445 : 225 : connection_warnings(bool in_startup)
4446 : : {
4447 [ + + + + ]: 225 : if (!pset.quiet && !pset.notty)
4448 : : {
4449 : 3 : int client_ver = PG_VERSION_NUM;
4450 : : char cverbuf[32];
4451 : : char sverbuf[32];
4452 : :
4453 [ - + ]: 3 : if (pset.sversion != client_ver)
4454 : : {
4455 : : const char *server_version;
4456 : :
4457 : : /* Try to get full text form, might include "devel" etc */
4458 : 0 : server_version = PQparameterStatus(pset.db, "server_version");
4459 : : /* Otherwise fall back on pset.sversion */
4460 [ # # ]: 0 : if (!server_version)
4461 : : {
4462 : 0 : formatPGVersionNumber(pset.sversion, true,
4463 : : sverbuf, sizeof(sverbuf));
4464 : 0 : server_version = sverbuf;
4465 : : }
4466 : :
4467 : 0 : printf(_("%s (%s, server %s)\n"),
4468 : : pset.progname, PG_VERSION, server_version);
4469 : : }
4470 : : /* For version match, only print psql banner on startup. */
4471 [ + - ]: 3 : else if (in_startup)
4472 : 3 : printf("%s (%s)\n", pset.progname, PG_VERSION);
4473 : :
4474 : : /*
4475 : : * Warn if server's major version is newer than ours, or if server
4476 : : * predates our support cutoff (currently 10).
4477 : : */
4478 [ + - ]: 3 : if (pset.sversion / 100 > client_ver / 100 ||
4479 [ - + ]: 3 : pset.sversion < 100000)
4480 : 0 : printf(_("WARNING: %s major version %s, server major version %s.\n"
4481 : : " Some psql features might not work.\n"),
4482 : : pset.progname,
4483 : : formatPGVersionNumber(client_ver, false,
4484 : : cverbuf, sizeof(cverbuf)),
4485 : : formatPGVersionNumber(pset.sversion, false,
4486 : : sverbuf, sizeof(sverbuf)));
4487 : :
4488 : : #ifdef WIN32
4489 : : if (in_startup)
4490 : : checkWin32Codepage();
4491 : : #endif
4492 : 3 : printSSLInfo();
4493 : 3 : printGSSInfo();
4494 : : }
4495 : 225 : }
4496 : :
4497 : :
4498 : : /*
4499 : : * printSSLInfo
4500 : : *
4501 : : * Prints information about the current SSL connection, if SSL is in use
4502 : : */
4503 : : static void
4504 : 3 : printSSLInfo(void)
4505 : : {
4506 : : const char *protocol;
4507 : : const char *cipher;
4508 : : const char *compression;
4509 : : const char *alpn;
4510 : :
4511 [ + - ]: 3 : if (!PQsslInUse(pset.db))
4512 : 3 : return; /* no SSL */
4513 : :
4514 : 0 : protocol = PQsslAttribute(pset.db, "protocol");
4515 : 0 : cipher = PQsslAttribute(pset.db, "cipher");
4516 : 0 : compression = PQsslAttribute(pset.db, "compression");
4517 : 0 : alpn = PQsslAttribute(pset.db, "alpn");
4518 : :
4519 [ # # # # : 0 : printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
# # # # #
# # # ]
4520 : : protocol ? protocol : _("unknown"),
4521 : : cipher ? cipher : _("unknown"),
4522 : : (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4523 : : (alpn && alpn[0] != '\0') ? alpn : _("none"));
4524 : : }
4525 : :
4526 : : /*
4527 : : * printGSSInfo
4528 : : *
4529 : : * Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
4530 : : */
4531 : : static void
4532 : 3 : printGSSInfo(void)
4533 : : {
4534 [ + - ]: 3 : if (!PQgssEncInUse(pset.db))
4535 : 3 : return; /* no GSSAPI encryption in use */
4536 : :
4537 : 0 : printf(_("GSSAPI-encrypted connection\n"));
4538 : : }
4539 : :
4540 : :
4541 : : /*
4542 : : * checkWin32Codepage
4543 : : *
4544 : : * Prints a warning when win32 console codepage differs from Windows codepage
4545 : : */
4546 : : #ifdef WIN32
4547 : : static void
4548 : : checkWin32Codepage(void)
4549 : : {
4550 : : unsigned int wincp,
4551 : : concp;
4552 : :
4553 : : wincp = GetACP();
4554 : : concp = GetConsoleCP();
4555 : : if (wincp != concp)
4556 : : {
4557 : : printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
4558 : : " 8-bit characters might not work correctly. See psql reference\n"
4559 : : " page \"Notes for Windows users\" for details.\n"),
4560 : : concp, wincp);
4561 : : }
4562 : : }
4563 : : #endif
4564 : :
4565 : :
4566 : : /*
4567 : : * SyncVariables
4568 : : *
4569 : : * Make psql's internal variables agree with connection state upon
4570 : : * establishing a new connection.
4571 : : */
4572 : : void
4573 : 10873 : SyncVariables(void)
4574 : : {
4575 : : char vbuf[32];
4576 : : const char *server_version;
4577 : : char *service_name;
4578 : : char *service_file;
4579 : :
4580 : : /* get stuff from connection */
4581 : 10873 : pset.encoding = PQclientEncoding(pset.db);
4582 : 10873 : pset.popt.topt.encoding = pset.encoding;
4583 : 10873 : pset.sversion = PQserverVersion(pset.db);
4584 : :
4585 : 10873 : setFmtEncoding(pset.encoding);
4586 : :
4587 : 10873 : SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4588 : 10873 : SetVariable(pset.vars, "USER", PQuser(pset.db));
4589 : 10873 : SetVariable(pset.vars, "HOST", PQhost(pset.db));
4590 : 10873 : SetVariable(pset.vars, "PORT", PQport(pset.db));
4591 : 10873 : SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
4592 : :
4593 : 10873 : service_name = get_conninfo_value("service");
4594 : 10873 : SetVariable(pset.vars, "SERVICE", service_name);
4595 [ + + ]: 10873 : if (service_name)
4596 : 18 : pg_free(service_name);
4597 : :
4598 : 10873 : service_file = get_conninfo_value("servicefile");
4599 : 10873 : SetVariable(pset.vars, "SERVICEFILE", service_file);
4600 [ + + ]: 10873 : if (service_file)
4601 : 18 : pg_free(service_file);
4602 : :
4603 : : /* this bit should match connection_warnings(): */
4604 : : /* Try to get full text form of version, might include "devel" etc */
4605 : 10873 : server_version = PQparameterStatus(pset.db, "server_version");
4606 : : /* Otherwise fall back on pset.sversion */
4607 [ - + ]: 10873 : if (!server_version)
4608 : : {
4609 : 0 : formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4610 : 0 : server_version = vbuf;
4611 : : }
4612 : 10873 : SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4613 : :
4614 : 10873 : snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4615 : 10873 : SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4616 : :
4617 : : /* send stuff to it, too */
4618 : 10873 : PQsetErrorVerbosity(pset.db, pset.verbosity);
4619 : 10873 : PQsetErrorContextVisibility(pset.db, pset.show_context);
4620 : 10873 : }
4621 : :
4622 : : /*
4623 : : * UnsyncVariables
4624 : : *
4625 : : * Clear variables that should be not be set when there is no connection.
4626 : : */
4627 : : void
4628 : 0 : UnsyncVariables(void)
4629 : : {
4630 : 0 : SetVariable(pset.vars, "DBNAME", NULL);
4631 : 0 : SetVariable(pset.vars, "SERVICE", NULL);
4632 : 0 : SetVariable(pset.vars, "SERVICEFILE", NULL);
4633 : 0 : SetVariable(pset.vars, "USER", NULL);
4634 : 0 : SetVariable(pset.vars, "HOST", NULL);
4635 : 0 : SetVariable(pset.vars, "PORT", NULL);
4636 : 0 : SetVariable(pset.vars, "ENCODING", NULL);
4637 : 0 : SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4638 : 0 : SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
4639 : 0 : }
4640 : :
4641 : :
4642 : : /*
4643 : : * helper for do_edit(): actually invoke the editor
4644 : : *
4645 : : * Returns true on success, false if we failed to invoke the editor or
4646 : : * it returned nonzero status. (An error message is printed for failed-
4647 : : * to-invoke cases, but not if the editor returns nonzero status.)
4648 : : */
4649 : : static bool
4650 : 0 : editFile(const char *fname, int lineno)
4651 : : {
4652 : : const char *editorName;
4653 : 0 : const char *editor_lineno_arg = NULL;
4654 : : char *sys;
4655 : : int result;
4656 : :
4657 : : Assert(fname != NULL);
4658 : :
4659 : : /* Find an editor to use */
4660 : 0 : editorName = getenv("PSQL_EDITOR");
4661 [ # # ]: 0 : if (!editorName)
4662 : 0 : editorName = getenv("EDITOR");
4663 [ # # ]: 0 : if (!editorName)
4664 : 0 : editorName = getenv("VISUAL");
4665 [ # # ]: 0 : if (!editorName)
4666 : 0 : editorName = DEFAULT_EDITOR;
4667 : :
4668 : : /* Get line number argument, if we need it. */
4669 [ # # ]: 0 : if (lineno > 0)
4670 : : {
4671 : 0 : editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4672 : : #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4673 [ # # ]: 0 : if (!editor_lineno_arg)
4674 : 0 : editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4675 : : #endif
4676 [ # # ]: 0 : if (!editor_lineno_arg)
4677 : : {
4678 : 0 : pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4679 : 0 : return false;
4680 : : }
4681 : : }
4682 : :
4683 : : /*
4684 : : * On Unix the EDITOR value should *not* be quoted, since it might include
4685 : : * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4686 : : * if necessary. But this policy is not very workable on Windows, due to
4687 : : * severe brain damage in their command shell plus the fact that standard
4688 : : * program paths include spaces.
4689 : : */
4690 : : #ifndef WIN32
4691 [ # # ]: 0 : if (lineno > 0)
4692 : 0 : sys = psprintf("exec %s %s%d '%s'",
4693 : : editorName, editor_lineno_arg, lineno, fname);
4694 : : else
4695 : 0 : sys = psprintf("exec %s '%s'",
4696 : : editorName, fname);
4697 : : #else
4698 : : if (lineno > 0)
4699 : : sys = psprintf("\"%s\" %s%d \"%s\"",
4700 : : editorName, editor_lineno_arg, lineno, fname);
4701 : : else
4702 : : sys = psprintf("\"%s\" \"%s\"",
4703 : : editorName, fname);
4704 : : #endif
4705 : 0 : fflush(NULL);
4706 : 0 : result = system(sys);
4707 [ # # ]: 0 : if (result == -1)
4708 : 0 : pg_log_error("could not start editor \"%s\"", editorName);
4709 [ # # ]: 0 : else if (result == 127)
4710 : 0 : pg_log_error("could not start /bin/sh");
4711 : 0 : pfree(sys);
4712 : :
4713 : 0 : return result == 0;
4714 : : }
4715 : :
4716 : :
4717 : : /*
4718 : : * do_edit -- handler for \e
4719 : : *
4720 : : * If you do not specify a filename, the current query buffer will be copied
4721 : : * into a temporary file.
4722 : : *
4723 : : * After this function is done, the resulting file will be copied back into the
4724 : : * query buffer. As an exception to this, the query buffer will be emptied
4725 : : * if the file was not modified (or the editor failed) and the caller passes
4726 : : * "discard_on_quit" = true.
4727 : : *
4728 : : * If "edited" isn't NULL, *edited will be set to true if the query buffer
4729 : : * is successfully replaced.
4730 : : */
4731 : : static bool
4732 : 0 : do_edit(const char *filename_arg, PQExpBuffer query_buf,
4733 : : int lineno, bool discard_on_quit, bool *edited)
4734 : : {
4735 : : char fnametmp[MAXPGPATH];
4736 : 0 : FILE *stream = NULL;
4737 : : const char *fname;
4738 : 0 : bool error = false;
4739 : : int fd;
4740 : : struct stat before,
4741 : : after;
4742 : :
4743 [ # # ]: 0 : if (filename_arg)
4744 : 0 : fname = filename_arg;
4745 : : else
4746 : : {
4747 : : /* make a temp file to edit */
4748 : : #ifndef WIN32
4749 : 0 : const char *tmpdir = getenv("TMPDIR");
4750 : :
4751 [ # # ]: 0 : if (!tmpdir)
4752 : 0 : tmpdir = "/tmp";
4753 : : #else
4754 : : char tmpdir[MAXPGPATH];
4755 : : int ret;
4756 : :
4757 : : ret = GetTempPath(MAXPGPATH, tmpdir);
4758 : : if (ret == 0 || ret > MAXPGPATH)
4759 : : {
4760 : : pg_log_error("could not locate temporary directory: %s",
4761 : : !ret ? strerror(errno) : "");
4762 : : return false;
4763 : : }
4764 : : #endif
4765 : :
4766 : : /*
4767 : : * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4768 : : * current directory to the supplied path unless we use only
4769 : : * backslashes, so we do that.
4770 : : */
4771 : : #ifndef WIN32
4772 : 0 : snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4773 : 0 : "/", (int) getpid());
4774 : : #else
4775 : : snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4776 : : "" /* trailing separator already present */ , (int) getpid());
4777 : : #endif
4778 : :
4779 : 0 : fname = (const char *) fnametmp;
4780 : :
4781 : 0 : fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4782 [ # # ]: 0 : if (fd != -1)
4783 : 0 : stream = fdopen(fd, "w");
4784 : :
4785 [ # # # # ]: 0 : if (fd == -1 || !stream)
4786 : : {
4787 : 0 : pg_log_error("could not open temporary file \"%s\": %m", fname);
4788 : 0 : error = true;
4789 : : }
4790 : : else
4791 : : {
4792 : 0 : unsigned int ql = query_buf->len;
4793 : :
4794 : : /* force newline-termination of what we send to editor */
4795 [ # # # # ]: 0 : if (ql > 0 && query_buf->data[ql - 1] != '\n')
4796 : : {
4797 : 0 : appendPQExpBufferChar(query_buf, '\n');
4798 : 0 : ql++;
4799 : : }
4800 : :
4801 [ # # ]: 0 : if (fwrite(query_buf->data, 1, ql, stream) != ql)
4802 : : {
4803 : 0 : pg_log_error("%s: %m", fname);
4804 : :
4805 [ # # ]: 0 : if (fclose(stream) != 0)
4806 : 0 : pg_log_error("%s: %m", fname);
4807 : :
4808 [ # # ]: 0 : if (remove(fname) != 0)
4809 : 0 : pg_log_error("%s: %m", fname);
4810 : :
4811 : 0 : error = true;
4812 : : }
4813 [ # # ]: 0 : else if (fclose(stream) != 0)
4814 : : {
4815 : 0 : pg_log_error("%s: %m", fname);
4816 [ # # ]: 0 : if (remove(fname) != 0)
4817 : 0 : pg_log_error("%s: %m", fname);
4818 : 0 : error = true;
4819 : : }
4820 : : else
4821 : : {
4822 : : struct utimbuf ut;
4823 : :
4824 : : /*
4825 : : * Try to set the file modification time of the temporary file
4826 : : * a few seconds in the past. Otherwise, the low granularity
4827 : : * (one second, or even worse on some filesystems) that we can
4828 : : * portably measure with stat(2) could lead us to not
4829 : : * recognize a modification, if the user typed very quickly.
4830 : : *
4831 : : * This is a rather unlikely race condition, so don't error
4832 : : * out if the utime(2) call fails --- that would make the cure
4833 : : * worse than the disease.
4834 : : */
4835 : 0 : ut.modtime = ut.actime = time(NULL) - 2;
4836 : 0 : (void) utime(fname, &ut);
4837 : : }
4838 : : }
4839 : : }
4840 : :
4841 [ # # # # ]: 0 : if (!error && stat(fname, &before) != 0)
4842 : : {
4843 : 0 : pg_log_error("%s: %m", fname);
4844 : 0 : error = true;
4845 : : }
4846 : :
4847 : : /* call editor */
4848 [ # # ]: 0 : if (!error)
4849 : 0 : error = !editFile(fname, lineno);
4850 : :
4851 [ # # # # ]: 0 : if (!error && stat(fname, &after) != 0)
4852 : : {
4853 : 0 : pg_log_error("%s: %m", fname);
4854 : 0 : error = true;
4855 : : }
4856 : :
4857 : : /* file was edited if the size or modification time has changed */
4858 [ # # ]: 0 : if (!error &&
4859 [ # # ]: 0 : (before.st_size != after.st_size ||
4860 [ # # ]: 0 : before.st_mtime != after.st_mtime))
4861 : : {
4862 : 0 : stream = fopen(fname, PG_BINARY_R);
4863 [ # # ]: 0 : if (!stream)
4864 : : {
4865 : 0 : pg_log_error("%s: %m", fname);
4866 : 0 : error = true;
4867 : : }
4868 : : else
4869 : : {
4870 : : /* read file back into query_buf */
4871 : : char line[1024];
4872 : :
4873 : 0 : resetPQExpBuffer(query_buf);
4874 [ # # ]: 0 : while (fgets(line, sizeof(line), stream) != NULL)
4875 : 0 : appendPQExpBufferStr(query_buf, line);
4876 : :
4877 [ # # ]: 0 : if (ferror(stream))
4878 : : {
4879 : 0 : pg_log_error("%s: %m", fname);
4880 : 0 : error = true;
4881 : 0 : resetPQExpBuffer(query_buf);
4882 : : }
4883 [ # # ]: 0 : else if (edited)
4884 : : {
4885 : 0 : *edited = true;
4886 : : }
4887 : :
4888 : 0 : fclose(stream);
4889 : : }
4890 : : }
4891 : : else
4892 : : {
4893 : : /*
4894 : : * If the file was not modified, and the caller requested it, discard
4895 : : * the query buffer.
4896 : : */
4897 [ # # ]: 0 : if (discard_on_quit)
4898 : 0 : resetPQExpBuffer(query_buf);
4899 : : }
4900 : :
4901 : : /* remove temp file */
4902 [ # # ]: 0 : if (!filename_arg)
4903 : : {
4904 [ # # ]: 0 : if (remove(fname) == -1)
4905 : : {
4906 : 0 : pg_log_error("%s: %m", fname);
4907 : 0 : error = true;
4908 : : }
4909 : : }
4910 : :
4911 : 0 : return !error;
4912 : : }
4913 : :
4914 : :
4915 : :
4916 : : /*
4917 : : * process_file
4918 : : *
4919 : : * Reads commands from filename and passes them to the main processing loop.
4920 : : * Handler for \i and \ir, but can be used for other things as well. Returns
4921 : : * MainLoop() error code.
4922 : : *
4923 : : * If use_relative_path is true and filename is not an absolute path, then open
4924 : : * the file from where the currently processed file (if any) is located.
4925 : : */
4926 : : int
4927 : 10373 : process_file(char *filename, bool use_relative_path)
4928 : : {
4929 : : FILE *fd;
4930 : : int result;
4931 : : char *oldfilename;
4932 : : char relpath[MAXPGPATH];
4933 : :
4934 [ + + ]: 10373 : if (!filename)
4935 : : {
4936 : 2550 : fd = stdin;
4937 : 2550 : filename = NULL;
4938 : : }
4939 [ + + ]: 7823 : else if (strcmp(filename, "-") != 0)
4940 : : {
4941 : 22 : canonicalize_path_enc(filename, pset.encoding);
4942 : :
4943 : : /*
4944 : : * If we were asked to resolve the pathname relative to the location
4945 : : * of the currently executing script, and there is one, and this is a
4946 : : * relative pathname, then prepend all but the last pathname component
4947 : : * of the current script to this pathname.
4948 : : */
4949 [ - + - - ]: 22 : if (use_relative_path && pset.inputfile &&
4950 [ # # # # ]: 0 : !is_absolute_path(filename) && !has_drive_prefix(filename))
4951 : : {
4952 : 0 : strlcpy(relpath, pset.inputfile, sizeof(relpath));
4953 : 0 : get_parent_directory(relpath);
4954 : 0 : join_path_components(relpath, relpath, filename);
4955 : 0 : canonicalize_path_enc(relpath, pset.encoding);
4956 : :
4957 : 0 : filename = relpath;
4958 : : }
4959 : :
4960 : 22 : fd = fopen(filename, PG_BINARY_R);
4961 : :
4962 [ - + ]: 22 : if (!fd)
4963 : : {
4964 : 0 : pg_log_error("%s: %m", filename);
4965 : 0 : return EXIT_FAILURE;
4966 : : }
4967 : : }
4968 : : else
4969 : : {
4970 : 7801 : fd = stdin;
4971 : 7801 : filename = "<stdin>"; /* for future error messages */
4972 : : }
4973 : :
4974 : 10373 : oldfilename = pset.inputfile;
4975 : 10373 : pset.inputfile = filename;
4976 : :
4977 : 10373 : pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4978 : :
4979 : 10373 : result = MainLoop(fd);
4980 : :
4981 [ + + ]: 10358 : if (fd != stdin)
4982 : 22 : fclose(fd);
4983 : :
4984 : 10358 : pset.inputfile = oldfilename;
4985 : :
4986 : 10358 : pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4987 : :
4988 : 10358 : return result;
4989 : : }
4990 : :
4991 : :
4992 : :
4993 : : static const char *
4994 : 5 : _align2string(enum printFormat in)
4995 : : {
4996 [ - + - - : 5 : switch (in)
- - - - -
+ - ]
4997 : : {
4998 : 0 : case PRINT_NOTHING:
4999 : 0 : return "nothing";
5000 : : break;
5001 : 4 : case PRINT_ALIGNED:
5002 : 4 : return "aligned";
5003 : : break;
5004 : 0 : case PRINT_ASCIIDOC:
5005 : 0 : return "asciidoc";
5006 : : break;
5007 : 0 : case PRINT_CSV:
5008 : 0 : return "csv";
5009 : : break;
5010 : 0 : case PRINT_HTML:
5011 : 0 : return "html";
5012 : : break;
5013 : 0 : case PRINT_LATEX:
5014 : 0 : return "latex";
5015 : : break;
5016 : 0 : case PRINT_LATEX_LONGTABLE:
5017 : 0 : return "latex-longtable";
5018 : : break;
5019 : 0 : case PRINT_TROFF_MS:
5020 : 0 : return "troff-ms";
5021 : : break;
5022 : 0 : case PRINT_UNALIGNED:
5023 : 0 : return "unaligned";
5024 : : break;
5025 : 1 : case PRINT_WRAPPED:
5026 : 1 : return "wrapped";
5027 : : break;
5028 : : }
5029 : 0 : return "unknown";
5030 : : }
5031 : :
5032 : : /*
5033 : : * Parse entered Unicode linestyle. If ok, update *linestyle and return
5034 : : * true, else return false.
5035 : : */
5036 : : static bool
5037 : 0 : set_unicode_line_style(const char *value, size_t vallen,
5038 : : unicode_linestyle *linestyle)
5039 : : {
5040 [ # # ]: 0 : if (pg_strncasecmp("single", value, vallen) == 0)
5041 : 0 : *linestyle = UNICODE_LINESTYLE_SINGLE;
5042 [ # # ]: 0 : else if (pg_strncasecmp("double", value, vallen) == 0)
5043 : 0 : *linestyle = UNICODE_LINESTYLE_DOUBLE;
5044 : : else
5045 : 0 : return false;
5046 : 0 : return true;
5047 : : }
5048 : :
5049 : : static const char *
5050 : 12 : _unicode_linestyle2string(int linestyle)
5051 : : {
5052 [ + - - ]: 12 : switch (linestyle)
5053 : : {
5054 : 12 : case UNICODE_LINESTYLE_SINGLE:
5055 : 12 : return "single";
5056 : : break;
5057 : 0 : case UNICODE_LINESTYLE_DOUBLE:
5058 : 0 : return "double";
5059 : : break;
5060 : : }
5061 : 0 : return "unknown";
5062 : : }
5063 : :
5064 : : /*
5065 : : * do_pset
5066 : : *
5067 : : * Performs the assignment "param = value", where value could be NULL;
5068 : : * for some params that has an effect such as inversion, for others
5069 : : * it does nothing.
5070 : : *
5071 : : * Adjusts the state of the formatting options at *popt. (In practice that
5072 : : * is always pset.popt, but maybe someday it could be different.)
5073 : : *
5074 : : * If successful and quiet is false, then invokes printPsetInfo() to report
5075 : : * the change.
5076 : : *
5077 : : * Returns true if successful, else false (eg for invalid param or value).
5078 : : */
5079 : : bool
5080 : 1405 : do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
5081 : : {
5082 : 1405 : size_t vallen = 0;
5083 : :
5084 : : Assert(param != NULL);
5085 : :
5086 [ + + ]: 1405 : if (value)
5087 : 1299 : vallen = strlen(value);
5088 : :
5089 : : /* set format */
5090 [ + + ]: 1405 : if (strcmp(param, "format") == 0)
5091 : : {
5092 : : static const struct fmt
5093 : : {
5094 : : const char *name;
5095 : : enum printFormat number;
5096 : : } formats[] =
5097 : : {
5098 : : /* remember to update error message below when adding more */
5099 : : {"aligned", PRINT_ALIGNED},
5100 : : {"asciidoc", PRINT_ASCIIDOC},
5101 : : {"csv", PRINT_CSV},
5102 : : {"html", PRINT_HTML},
5103 : : {"latex", PRINT_LATEX},
5104 : : {"troff-ms", PRINT_TROFF_MS},
5105 : : {"unaligned", PRINT_UNALIGNED},
5106 : : {"wrapped", PRINT_WRAPPED}
5107 : : };
5108 : :
5109 [ + - ]: 449 : if (!value)
5110 : : ;
5111 : : else
5112 : : {
5113 : 449 : int match_pos = -1;
5114 : :
5115 [ + + ]: 4013 : for (size_t i = 0; i < lengthof(formats); i++)
5116 : : {
5117 [ + + ]: 3568 : if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
5118 : : {
5119 [ + + ]: 449 : if (match_pos < 0)
5120 : 445 : match_pos = i;
5121 : : else
5122 : : {
5123 : 4 : pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
5124 : : value,
5125 : : formats[match_pos].name, formats[i].name);
5126 : 4 : return false;
5127 : : }
5128 : : }
5129 : : }
5130 [ + + ]: 445 : if (match_pos >= 0)
5131 : 441 : popt->topt.format = formats[match_pos].number;
5132 [ + - ]: 4 : else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
5133 : : {
5134 : : /*
5135 : : * We must treat latex-longtable specially because latex is a
5136 : : * prefix of it; if both were in the table above, we'd think
5137 : : * "latex" is ambiguous.
5138 : : */
5139 : 4 : popt->topt.format = PRINT_LATEX_LONGTABLE;
5140 : : }
5141 : : else
5142 : : {
5143 : 0 : pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
5144 : 0 : return false;
5145 : : }
5146 : : }
5147 : : }
5148 : :
5149 : : /* set table line style */
5150 [ + + ]: 956 : else if (strcmp(param, "linestyle") == 0)
5151 : : {
5152 [ + - ]: 20 : if (!value)
5153 : : ;
5154 [ + + ]: 20 : else if (pg_strncasecmp("ascii", value, vallen) == 0)
5155 : 12 : popt->topt.line_style = &pg_asciiformat;
5156 [ + - ]: 8 : else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
5157 : 8 : popt->topt.line_style = &pg_asciiformat_old;
5158 [ # # ]: 0 : else if (pg_strncasecmp("unicode", value, vallen) == 0)
5159 : 0 : popt->topt.line_style = &pg_utf8format;
5160 : : else
5161 : : {
5162 : 0 : pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
5163 : 0 : return false;
5164 : : }
5165 : : }
5166 : :
5167 : : /* set unicode border line style */
5168 [ - + ]: 936 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5169 : : {
5170 [ # # ]: 0 : if (!value)
5171 : : ;
5172 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5173 : : &popt->topt.unicode_border_linestyle))
5174 : 0 : refresh_utf8format(&(popt->topt));
5175 : : else
5176 : : {
5177 : 0 : pg_log_error("\\pset: allowed Unicode border line styles are single, double");
5178 : 0 : return false;
5179 : : }
5180 : : }
5181 : :
5182 : : /* set unicode column line style */
5183 [ - + ]: 936 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5184 : : {
5185 [ # # ]: 0 : if (!value)
5186 : : ;
5187 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5188 : : &popt->topt.unicode_column_linestyle))
5189 : 0 : refresh_utf8format(&(popt->topt));
5190 : : else
5191 : : {
5192 : 0 : pg_log_error("\\pset: allowed Unicode column line styles are single, double");
5193 : 0 : return false;
5194 : : }
5195 : : }
5196 : :
5197 : : /* set unicode header line style */
5198 [ - + ]: 936 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5199 : : {
5200 [ # # ]: 0 : if (!value)
5201 : : ;
5202 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5203 : : &popt->topt.unicode_header_linestyle))
5204 : 0 : refresh_utf8format(&(popt->topt));
5205 : : else
5206 : : {
5207 : 0 : pg_log_error("\\pset: allowed Unicode header line styles are single, double");
5208 : 0 : return false;
5209 : : }
5210 : : }
5211 : :
5212 : : /* set border style/width */
5213 [ + + ]: 936 : else if (strcmp(param, "border") == 0)
5214 : : {
5215 [ + - ]: 272 : if (value)
5216 : 272 : popt->topt.border = atoi(value);
5217 : : }
5218 : :
5219 : : /* set expanded/vertical mode */
5220 [ + - ]: 664 : else if (strcmp(param, "x") == 0 ||
5221 [ + + ]: 664 : strcmp(param, "expanded") == 0 ||
5222 [ - + ]: 440 : strcmp(param, "vertical") == 0)
5223 : : {
5224 [ + + - + ]: 224 : if (value && pg_strcasecmp(value, "auto") == 0)
5225 : 0 : popt->topt.expanded = 2;
5226 [ + + ]: 224 : else if (value)
5227 : : {
5228 : : bool on_off;
5229 : :
5230 [ + - ]: 178 : if (ParseVariableBool(value, NULL, &on_off))
5231 : 178 : popt->topt.expanded = on_off ? 1 : 0;
5232 : : else
5233 : : {
5234 : 0 : PsqlVarEnumError(param, value, "on, off, auto");
5235 : 0 : return false;
5236 : : }
5237 : : }
5238 : : else
5239 : 46 : popt->topt.expanded = !popt->topt.expanded;
5240 : : }
5241 : :
5242 : : /* header line width in expanded mode */
5243 [ - + ]: 440 : else if (strcmp(param, "xheader_width") == 0)
5244 : : {
5245 [ # # ]: 0 : if (!value)
5246 : : ;
5247 [ # # ]: 0 : else if (pg_strcasecmp(value, "full") == 0)
5248 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_FULL;
5249 [ # # ]: 0 : else if (pg_strcasecmp(value, "column") == 0)
5250 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_COLUMN;
5251 [ # # ]: 0 : else if (pg_strcasecmp(value, "page") == 0)
5252 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_PAGE;
5253 : : else
5254 : : {
5255 : 0 : int intval = atoi(value);
5256 : :
5257 [ # # ]: 0 : if (intval == 0)
5258 : : {
5259 : 0 : pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
5260 : 0 : return false;
5261 : : }
5262 : :
5263 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_EXACT_WIDTH;
5264 : 0 : popt->topt.expanded_header_exact_width = intval;
5265 : : }
5266 : : }
5267 : :
5268 : : /* field separator for CSV format */
5269 [ + + ]: 440 : else if (strcmp(param, "csv_fieldsep") == 0)
5270 : : {
5271 [ + - ]: 40 : if (value)
5272 : : {
5273 : : /* CSV separator has to be a one-byte character */
5274 [ + + ]: 40 : if (strlen(value) != 1)
5275 : : {
5276 : 12 : pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
5277 : 12 : return false;
5278 : : }
5279 [ + + + + : 28 : if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
+ + ]
5280 : : {
5281 : 12 : pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
5282 : 12 : return false;
5283 : : }
5284 : 16 : popt->topt.csvFieldSep[0] = value[0];
5285 : : }
5286 : : }
5287 : :
5288 : : /* locale-aware numeric output */
5289 [ + + ]: 400 : else if (strcmp(param, "numericlocale") == 0)
5290 : : {
5291 [ + - ]: 8 : if (value)
5292 : 8 : return ParseVariableBool(value, param, &popt->topt.numericLocale);
5293 : : else
5294 : 0 : popt->topt.numericLocale = !popt->topt.numericLocale;
5295 : : }
5296 : :
5297 : : /* null display */
5298 [ + + ]: 392 : else if (strcmp(param, "null") == 0)
5299 : : {
5300 [ + + ]: 79 : if (value)
5301 : : {
5302 : 75 : free(popt->nullPrint);
5303 : 75 : popt->nullPrint = pg_strdup(value);
5304 : : }
5305 : : }
5306 : :
5307 : : /* 'false' display */
5308 [ + + ]: 313 : else if (strcmp(param, "display_false") == 0)
5309 : : {
5310 [ + + ]: 20 : if (value)
5311 : : {
5312 : 16 : free(popt->falsePrint);
5313 : 16 : popt->falsePrint = pg_strdup(value);
5314 : : }
5315 : : }
5316 : :
5317 : : /* 'true' display */
5318 [ + + ]: 293 : else if (strcmp(param, "display_true") == 0)
5319 : : {
5320 [ + + ]: 20 : if (value)
5321 : : {
5322 : 16 : free(popt->truePrint);
5323 : 16 : popt->truePrint = pg_strdup(value);
5324 : : }
5325 : : }
5326 : :
5327 : : /* field separator for unaligned text */
5328 [ + + ]: 273 : else if (strcmp(param, "fieldsep") == 0)
5329 : : {
5330 [ + - ]: 4 : if (value)
5331 : : {
5332 : 4 : free(popt->topt.fieldSep.separator);
5333 : 4 : popt->topt.fieldSep.separator = pg_strdup(value);
5334 : 4 : popt->topt.fieldSep.separator_zero = false;
5335 : : }
5336 : : }
5337 : :
5338 [ - + ]: 269 : else if (strcmp(param, "fieldsep_zero") == 0)
5339 : : {
5340 : 0 : free(popt->topt.fieldSep.separator);
5341 : 0 : popt->topt.fieldSep.separator = NULL;
5342 : 0 : popt->topt.fieldSep.separator_zero = true;
5343 : : }
5344 : :
5345 : : /* record separator for unaligned text */
5346 [ - + ]: 269 : else if (strcmp(param, "recordsep") == 0)
5347 : : {
5348 [ # # ]: 0 : if (value)
5349 : : {
5350 : 0 : free(popt->topt.recordSep.separator);
5351 : 0 : popt->topt.recordSep.separator = pg_strdup(value);
5352 : 0 : popt->topt.recordSep.separator_zero = false;
5353 : : }
5354 : : }
5355 : :
5356 [ - + ]: 269 : else if (strcmp(param, "recordsep_zero") == 0)
5357 : : {
5358 : 0 : free(popt->topt.recordSep.separator);
5359 : 0 : popt->topt.recordSep.separator = NULL;
5360 : 0 : popt->topt.recordSep.separator_zero = true;
5361 : : }
5362 : :
5363 : : /* toggle between full and tuples-only format */
5364 [ + - + + ]: 269 : else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5365 : : {
5366 [ + + ]: 201 : if (value)
5367 : 169 : return ParseVariableBool(value, param, &popt->topt.tuples_only);
5368 : : else
5369 : 32 : popt->topt.tuples_only = !popt->topt.tuples_only;
5370 : : }
5371 : :
5372 : : /* set title override */
5373 [ + - + + ]: 68 : else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5374 : : {
5375 : 4 : free(popt->title);
5376 [ - + ]: 4 : if (!value)
5377 : 0 : popt->title = NULL;
5378 : : else
5379 : 4 : popt->title = pg_strdup(value);
5380 : : }
5381 : :
5382 : : /* set HTML table tag options */
5383 [ + - + + ]: 64 : else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5384 : : {
5385 : 32 : free(popt->topt.tableAttr);
5386 [ + + ]: 32 : if (!value)
5387 : 16 : popt->topt.tableAttr = NULL;
5388 : : else
5389 : 16 : popt->topt.tableAttr = pg_strdup(value);
5390 : : }
5391 : :
5392 : : /* toggle use of pager */
5393 [ - + ]: 32 : else if (strcmp(param, "pager") == 0)
5394 : : {
5395 [ # # # # ]: 0 : if (value && pg_strcasecmp(value, "always") == 0)
5396 : 0 : popt->topt.pager = 2;
5397 [ # # ]: 0 : else if (value)
5398 : : {
5399 : : bool on_off;
5400 : :
5401 [ # # ]: 0 : if (!ParseVariableBool(value, NULL, &on_off))
5402 : : {
5403 : 0 : PsqlVarEnumError(param, value, "on, off, always");
5404 : 0 : return false;
5405 : : }
5406 : 0 : popt->topt.pager = on_off ? 1 : 0;
5407 : : }
5408 [ # # ]: 0 : else if (popt->topt.pager == 1)
5409 : 0 : popt->topt.pager = 0;
5410 : : else
5411 : 0 : popt->topt.pager = 1;
5412 : : }
5413 : :
5414 : : /* set minimum lines for pager use */
5415 [ - + ]: 32 : else if (strcmp(param, "pager_min_lines") == 0)
5416 : : {
5417 [ # # ]: 0 : if (value &&
5418 [ # # ]: 0 : !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
5419 : 0 : return false;
5420 : : }
5421 : :
5422 : : /* disable "(x rows)" footer */
5423 [ - + ]: 32 : else if (strcmp(param, "footer") == 0)
5424 : : {
5425 [ # # ]: 0 : if (value)
5426 : 0 : return ParseVariableBool(value, param, &popt->topt.default_footer);
5427 : : else
5428 : 0 : popt->topt.default_footer = !popt->topt.default_footer;
5429 : : }
5430 : :
5431 : : /* set border style/width */
5432 [ + - ]: 32 : else if (strcmp(param, "columns") == 0)
5433 : : {
5434 [ + - ]: 32 : if (value)
5435 : 32 : popt->topt.columns = atoi(value);
5436 : : }
5437 : : else
5438 : : {
5439 : 0 : pg_log_error("\\pset: unknown option: %s", param);
5440 : 0 : return false;
5441 : : }
5442 : :
5443 [ + + ]: 1200 : if (!quiet)
5444 : 3 : printPsetInfo(param, &pset.popt);
5445 : :
5446 : 1200 : return true;
5447 : : }
5448 : :
5449 : : /*
5450 : : * printPsetInfo: print the state of the "param" formatting parameter in popt.
5451 : : */
5452 : : static bool
5453 : 3 : printPsetInfo(const char *param, printQueryOpt *popt)
5454 : : {
5455 : : Assert(param != NULL);
5456 : :
5457 : : /* show border style/width */
5458 [ - + ]: 3 : if (strcmp(param, "border") == 0)
5459 : 0 : printf(_("Border style is %d.\n"), popt->topt.border);
5460 : :
5461 : : /* show the target width for the wrapped format */
5462 [ - + ]: 3 : else if (strcmp(param, "columns") == 0)
5463 : : {
5464 [ # # ]: 0 : if (!popt->topt.columns)
5465 : 0 : printf(_("Target width is unset.\n"));
5466 : : else
5467 : 0 : printf(_("Target width is %d.\n"), popt->topt.columns);
5468 : : }
5469 : :
5470 : : /* show expanded/vertical mode */
5471 [ + - + + : 3 : else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
- + ]
5472 : : {
5473 [ + - ]: 2 : if (popt->topt.expanded == 1)
5474 : 2 : printf(_("Expanded display is on.\n"));
5475 [ # # ]: 0 : else if (popt->topt.expanded == 2)
5476 : 0 : printf(_("Expanded display is used automatically.\n"));
5477 : : else
5478 : 0 : printf(_("Expanded display is off.\n"));
5479 : : }
5480 : :
5481 : : /* show xheader width value */
5482 [ - + ]: 1 : else if (strcmp(param, "xheader_width") == 0)
5483 : : {
5484 [ # # ]: 0 : if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
5485 : 0 : printf(_("Expanded header width is \"%s\".\n"), "full");
5486 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
5487 : 0 : printf(_("Expanded header width is \"%s\".\n"), "column");
5488 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
5489 : 0 : printf(_("Expanded header width is \"%s\".\n"), "page");
5490 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_EXACT_WIDTH)
5491 : 0 : printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
5492 : : }
5493 : :
5494 : : /* show field separator for CSV format */
5495 [ - + ]: 1 : else if (strcmp(param, "csv_fieldsep") == 0)
5496 : : {
5497 : 0 : printf(_("Field separator for CSV is \"%s\".\n"),
5498 : : popt->topt.csvFieldSep);
5499 : : }
5500 : :
5501 : : /* show boolean 'false' display */
5502 [ - + ]: 1 : else if (strcmp(param, "display_false") == 0)
5503 : : {
5504 [ # # ]: 0 : printf(_("Boolean false display is \"%s\".\n"),
5505 : : popt->falsePrint ? popt->falsePrint : "f");
5506 : : }
5507 : :
5508 : : /* show boolean 'true' display */
5509 [ - + ]: 1 : else if (strcmp(param, "display_true") == 0)
5510 : : {
5511 [ # # ]: 0 : printf(_("Boolean true display is \"%s\".\n"),
5512 : : popt->truePrint ? popt->truePrint : "t");
5513 : : }
5514 : :
5515 : : /* show field separator for unaligned text */
5516 [ - + ]: 1 : else if (strcmp(param, "fieldsep") == 0)
5517 : : {
5518 [ # # ]: 0 : if (popt->topt.fieldSep.separator_zero)
5519 : 0 : printf(_("Field separator is zero byte.\n"));
5520 : : else
5521 : 0 : printf(_("Field separator is \"%s\".\n"),
5522 : : popt->topt.fieldSep.separator);
5523 : : }
5524 : :
5525 [ - + ]: 1 : else if (strcmp(param, "fieldsep_zero") == 0)
5526 : : {
5527 : 0 : printf(_("Field separator is zero byte.\n"));
5528 : : }
5529 : :
5530 : : /* show disable "(x rows)" footer */
5531 [ - + ]: 1 : else if (strcmp(param, "footer") == 0)
5532 : : {
5533 [ # # ]: 0 : if (popt->topt.default_footer)
5534 : 0 : printf(_("Default footer is on.\n"));
5535 : : else
5536 : 0 : printf(_("Default footer is off.\n"));
5537 : : }
5538 : :
5539 : : /* show format */
5540 [ + - ]: 1 : else if (strcmp(param, "format") == 0)
5541 : : {
5542 : 1 : printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
5543 : : }
5544 : :
5545 : : /* show table line style */
5546 [ # # ]: 0 : else if (strcmp(param, "linestyle") == 0)
5547 : : {
5548 : 0 : printf(_("Line style is %s.\n"),
5549 : : get_line_style(&popt->topt)->name);
5550 : : }
5551 : :
5552 : : /* show null display */
5553 [ # # ]: 0 : else if (strcmp(param, "null") == 0)
5554 : : {
5555 [ # # ]: 0 : printf(_("Null display is \"%s\".\n"),
5556 : : popt->nullPrint ? popt->nullPrint : "");
5557 : : }
5558 : :
5559 : : /* show locale-aware numeric output */
5560 [ # # ]: 0 : else if (strcmp(param, "numericlocale") == 0)
5561 : : {
5562 [ # # ]: 0 : if (popt->topt.numericLocale)
5563 : 0 : printf(_("Locale-adjusted numeric output is on.\n"));
5564 : : else
5565 : 0 : printf(_("Locale-adjusted numeric output is off.\n"));
5566 : : }
5567 : :
5568 : : /* show toggle use of pager */
5569 [ # # ]: 0 : else if (strcmp(param, "pager") == 0)
5570 : : {
5571 [ # # ]: 0 : if (popt->topt.pager == 1)
5572 : 0 : printf(_("Pager is used for long output.\n"));
5573 [ # # ]: 0 : else if (popt->topt.pager == 2)
5574 : 0 : printf(_("Pager is always used.\n"));
5575 : : else
5576 : 0 : printf(_("Pager usage is off.\n"));
5577 : : }
5578 : :
5579 : : /* show minimum lines for pager use */
5580 [ # # ]: 0 : else if (strcmp(param, "pager_min_lines") == 0)
5581 : : {
5582 : 0 : printf(ngettext("Pager won't be used for less than %d line.\n",
5583 : : "Pager won't be used for less than %d lines.\n",
5584 : : popt->topt.pager_min_lines),
5585 : : popt->topt.pager_min_lines);
5586 : : }
5587 : :
5588 : : /* show record separator for unaligned text */
5589 [ # # ]: 0 : else if (strcmp(param, "recordsep") == 0)
5590 : : {
5591 [ # # ]: 0 : if (popt->topt.recordSep.separator_zero)
5592 : 0 : printf(_("Record separator is zero byte.\n"));
5593 [ # # ]: 0 : else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
5594 : 0 : printf(_("Record separator is <newline>.\n"));
5595 : : else
5596 : 0 : printf(_("Record separator is \"%s\".\n"),
5597 : : popt->topt.recordSep.separator);
5598 : : }
5599 : :
5600 [ # # ]: 0 : else if (strcmp(param, "recordsep_zero") == 0)
5601 : : {
5602 : 0 : printf(_("Record separator is zero byte.\n"));
5603 : : }
5604 : :
5605 : : /* show HTML table tag options */
5606 [ # # # # ]: 0 : else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5607 : : {
5608 [ # # ]: 0 : if (popt->topt.tableAttr)
5609 : 0 : printf(_("Table attributes are \"%s\".\n"),
5610 : : popt->topt.tableAttr);
5611 : : else
5612 : 0 : printf(_("Table attributes unset.\n"));
5613 : : }
5614 : :
5615 : : /* show title override */
5616 [ # # # # ]: 0 : else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5617 : : {
5618 [ # # ]: 0 : if (popt->title)
5619 : 0 : printf(_("Title is \"%s\".\n"), popt->title);
5620 : : else
5621 : 0 : printf(_("Title is unset.\n"));
5622 : : }
5623 : :
5624 : : /* show toggle between full and tuples-only format */
5625 [ # # # # ]: 0 : else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5626 : : {
5627 [ # # ]: 0 : if (popt->topt.tuples_only)
5628 : 0 : printf(_("Tuples only is on.\n"));
5629 : : else
5630 : 0 : printf(_("Tuples only is off.\n"));
5631 : : }
5632 : :
5633 : : /* Unicode style formatting */
5634 [ # # ]: 0 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5635 : : {
5636 : 0 : printf(_("Unicode border line style is \"%s\".\n"),
5637 : : _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5638 : : }
5639 : :
5640 [ # # ]: 0 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5641 : : {
5642 : 0 : printf(_("Unicode column line style is \"%s\".\n"),
5643 : : _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5644 : : }
5645 : :
5646 [ # # ]: 0 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5647 : : {
5648 : 0 : printf(_("Unicode header line style is \"%s\".\n"),
5649 : : _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
5650 : : }
5651 : :
5652 : : else
5653 : : {
5654 : 0 : pg_log_error("\\pset: unknown option: %s", param);
5655 : 0 : return false;
5656 : : }
5657 : :
5658 : 3 : return true;
5659 : : }
5660 : :
5661 : : /*
5662 : : * savePsetInfo: make a malloc'd copy of the data in *popt.
5663 : : *
5664 : : * Possibly this should be somewhere else, but it's a bit specific to psql.
5665 : : */
5666 : : printQueryOpt *
5667 : 94 : savePsetInfo(const printQueryOpt *popt)
5668 : : {
5669 : : printQueryOpt *save;
5670 : :
5671 : 94 : save = pg_malloc_object(printQueryOpt);
5672 : :
5673 : : /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5674 : 94 : memcpy(save, popt, sizeof(printQueryOpt));
5675 : :
5676 : : /* topt.line_style points to const data that need not be duplicated */
5677 [ + - ]: 94 : if (popt->topt.fieldSep.separator)
5678 : 94 : save->topt.fieldSep.separator = pg_strdup(popt->topt.fieldSep.separator);
5679 [ + - ]: 94 : if (popt->topt.recordSep.separator)
5680 : 94 : save->topt.recordSep.separator = pg_strdup(popt->topt.recordSep.separator);
5681 [ - + ]: 94 : if (popt->topt.tableAttr)
5682 : 0 : save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5683 [ - + ]: 94 : if (popt->nullPrint)
5684 : 0 : save->nullPrint = pg_strdup(popt->nullPrint);
5685 [ - + ]: 94 : if (popt->truePrint)
5686 : 0 : save->truePrint = pg_strdup(popt->truePrint);
5687 [ - + ]: 94 : if (popt->falsePrint)
5688 : 0 : save->falsePrint = pg_strdup(popt->falsePrint);
5689 [ - + ]: 94 : if (popt->title)
5690 : 0 : save->title = pg_strdup(popt->title);
5691 : :
5692 : : /*
5693 : : * footers and translate_columns are never set in psql's print settings,
5694 : : * so we needn't write code to duplicate them.
5695 : : */
5696 : : Assert(popt->footers == NULL);
5697 : : Assert(popt->translate_columns == NULL);
5698 : :
5699 : 94 : return save;
5700 : : }
5701 : :
5702 : : /*
5703 : : * restorePsetInfo: restore *popt from the previously-saved copy *save,
5704 : : * then free *save.
5705 : : */
5706 : : void
5707 : 94 : restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
5708 : : {
5709 : : /* Free all the old data we're about to overwrite the pointers to. */
5710 : :
5711 : : /* topt.line_style points to const data that need not be duplicated */
5712 : 94 : free(popt->topt.fieldSep.separator);
5713 : 94 : free(popt->topt.recordSep.separator);
5714 : 94 : free(popt->topt.tableAttr);
5715 : 94 : free(popt->nullPrint);
5716 : 94 : free(popt->truePrint);
5717 : 94 : free(popt->falsePrint);
5718 : 94 : free(popt->title);
5719 : :
5720 : : /*
5721 : : * footers and translate_columns are never set in psql's print settings,
5722 : : * so we needn't write code to duplicate them.
5723 : : */
5724 : : Assert(popt->footers == NULL);
5725 : : Assert(popt->translate_columns == NULL);
5726 : :
5727 : : /* Now we may flat-copy all the fields, including pointers. */
5728 : 94 : memcpy(popt, save, sizeof(printQueryOpt));
5729 : :
5730 : : /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5731 : 94 : free(save);
5732 : 94 : }
5733 : :
5734 : : static const char *
5735 : 24 : pset_bool_string(bool val)
5736 : : {
5737 [ + + ]: 24 : return val ? "on" : "off";
5738 : : }
5739 : :
5740 : :
5741 : : static char *
5742 : 24 : pset_quoted_string(const char *str)
5743 : : {
5744 : 24 : char *ret = pg_malloc(strlen(str) * 2 + 3);
5745 : 24 : char *r = ret;
5746 : :
5747 : 24 : *r++ = '\'';
5748 : :
5749 [ + + ]: 44 : for (; *str; str++)
5750 : : {
5751 [ + + ]: 20 : if (*str == '\n')
5752 : : {
5753 : 4 : *r++ = '\\';
5754 : 4 : *r++ = 'n';
5755 : : }
5756 [ - + ]: 16 : else if (*str == '\'')
5757 : : {
5758 : 0 : *r++ = '\\';
5759 : 0 : *r++ = '\'';
5760 : : }
5761 : : else
5762 : 16 : *r++ = *str;
5763 : : }
5764 : :
5765 : 24 : *r++ = '\'';
5766 : 24 : *r = '\0';
5767 : :
5768 : 24 : return ret;
5769 : : }
5770 : :
5771 : :
5772 : : /*
5773 : : * Return a malloc'ed string for the \pset value.
5774 : : *
5775 : : * Note that for some string parameters, print.c distinguishes between unset
5776 : : * and empty string, but for others it doesn't. This function should produce
5777 : : * output that produces the correct setting when fed back into \pset.
5778 : : */
5779 : : static char *
5780 : 96 : pset_value_string(const char *param, printQueryOpt *popt)
5781 : : {
5782 : : Assert(param != NULL);
5783 : :
5784 [ + + ]: 96 : if (strcmp(param, "border") == 0)
5785 : 4 : return psprintf("%d", popt->topt.border);
5786 [ + + ]: 92 : else if (strcmp(param, "columns") == 0)
5787 : 4 : return psprintf("%d", popt->topt.columns);
5788 [ + + ]: 88 : else if (strcmp(param, "csv_fieldsep") == 0)
5789 : 4 : return pset_quoted_string(popt->topt.csvFieldSep);
5790 [ + + ]: 84 : else if (strcmp(param, "display_false") == 0)
5791 [ - + ]: 4 : return pset_quoted_string(popt->falsePrint ? popt->falsePrint : "f");
5792 [ + + ]: 80 : else if (strcmp(param, "display_true") == 0)
5793 [ - + ]: 4 : return pset_quoted_string(popt->truePrint ? popt->truePrint : "t");
5794 [ + + ]: 76 : else if (strcmp(param, "expanded") == 0)
5795 [ + - ]: 8 : return pstrdup(popt->topt.expanded == 2
5796 : : ? "auto"
5797 : 4 : : pset_bool_string(popt->topt.expanded));
5798 [ + + ]: 72 : else if (strcmp(param, "fieldsep") == 0)
5799 [ + - ]: 4 : return pset_quoted_string(popt->topt.fieldSep.separator
5800 : : ? popt->topt.fieldSep.separator
5801 : : : "");
5802 [ + + ]: 68 : else if (strcmp(param, "fieldsep_zero") == 0)
5803 : 4 : return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
5804 [ + + ]: 64 : else if (strcmp(param, "footer") == 0)
5805 : 4 : return pstrdup(pset_bool_string(popt->topt.default_footer));
5806 [ + + ]: 60 : else if (strcmp(param, "format") == 0)
5807 : 4 : return pstrdup(_align2string(popt->topt.format));
5808 [ + + ]: 56 : else if (strcmp(param, "linestyle") == 0)
5809 : 4 : return pstrdup(get_line_style(&popt->topt)->name);
5810 [ + + ]: 52 : else if (strcmp(param, "null") == 0)
5811 [ - + ]: 4 : return pset_quoted_string(popt->nullPrint
5812 : : ? popt->nullPrint
5813 : : : "");
5814 [ + + ]: 48 : else if (strcmp(param, "numericlocale") == 0)
5815 : 4 : return pstrdup(pset_bool_string(popt->topt.numericLocale));
5816 [ + + ]: 44 : else if (strcmp(param, "pager") == 0)
5817 : 4 : return psprintf("%d", popt->topt.pager);
5818 [ + + ]: 40 : else if (strcmp(param, "pager_min_lines") == 0)
5819 : 4 : return psprintf("%d", popt->topt.pager_min_lines);
5820 [ + + ]: 36 : else if (strcmp(param, "recordsep") == 0)
5821 [ + - ]: 4 : return pset_quoted_string(popt->topt.recordSep.separator
5822 : : ? popt->topt.recordSep.separator
5823 : : : "");
5824 [ + + ]: 32 : else if (strcmp(param, "recordsep_zero") == 0)
5825 : 4 : return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
5826 [ + + ]: 28 : else if (strcmp(param, "tableattr") == 0)
5827 [ - + ]: 4 : return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5828 [ + + ]: 24 : else if (strcmp(param, "title") == 0)
5829 [ - + ]: 4 : return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5830 [ + + ]: 20 : else if (strcmp(param, "tuples_only") == 0)
5831 : 4 : return pstrdup(pset_bool_string(popt->topt.tuples_only));
5832 [ + + ]: 16 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5833 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5834 [ + + ]: 12 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5835 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5836 [ + + ]: 8 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5837 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
5838 [ + - ]: 4 : else if (strcmp(param, "xheader_width") == 0)
5839 : : {
5840 [ + - ]: 4 : if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
5841 : 4 : return pstrdup("full");
5842 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
5843 : 0 : return pstrdup("column");
5844 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
5845 : 0 : return pstrdup("page");
5846 : : else
5847 : : {
5848 : : /* must be PRINT_XHEADER_EXACT_WIDTH */
5849 : : char wbuff[32];
5850 : :
5851 : 0 : snprintf(wbuff, sizeof(wbuff), "%d",
5852 : : popt->topt.expanded_header_exact_width);
5853 : 0 : return pstrdup(wbuff);
5854 : : }
5855 : : }
5856 : : else
5857 : 0 : return pstrdup("ERROR");
5858 : : }
5859 : :
5860 : :
5861 : :
5862 : : #ifndef WIN32
5863 : : #define DEFAULT_SHELL "/bin/sh"
5864 : : #else
5865 : : /*
5866 : : * CMD.EXE is in different places in different Win32 releases so we
5867 : : * have to rely on the path to find it.
5868 : : */
5869 : : #define DEFAULT_SHELL "cmd.exe"
5870 : : #endif
5871 : :
5872 : : static bool
5873 : 0 : do_shell(const char *command)
5874 : : {
5875 : : int result;
5876 : :
5877 : 0 : fflush(NULL);
5878 [ # # ]: 0 : if (!command)
5879 : : {
5880 : : char *sys;
5881 : : const char *shellName;
5882 : :
5883 : 0 : shellName = getenv("SHELL");
5884 : : #ifdef WIN32
5885 : : if (shellName == NULL)
5886 : : shellName = getenv("COMSPEC");
5887 : : #endif
5888 [ # # ]: 0 : if (shellName == NULL)
5889 : 0 : shellName = DEFAULT_SHELL;
5890 : :
5891 : : /* See EDITOR handling comment for an explanation */
5892 : : #ifndef WIN32
5893 : 0 : sys = psprintf("exec %s", shellName);
5894 : : #else
5895 : : sys = psprintf("\"%s\"", shellName);
5896 : : #endif
5897 : 0 : result = system(sys);
5898 : 0 : pfree(sys);
5899 : : }
5900 : : else
5901 : 0 : result = system(command);
5902 : :
5903 : 0 : SetShellResultVariables(result);
5904 : :
5905 [ # # # # ]: 0 : if (result == 127 || result == -1)
5906 : : {
5907 : 0 : pg_log_error("\\!: failed");
5908 : 0 : return false;
5909 : : }
5910 : 0 : return true;
5911 : : }
5912 : :
5913 : : /*
5914 : : * do_watch -- handler for \watch
5915 : : *
5916 : : * We break this out of exec_command to avoid having to plaster "volatile"
5917 : : * onto a bunch of exec_command's variables to silence stupider compilers.
5918 : : *
5919 : : * "sleep" is the amount of time to sleep during each loop, measured in
5920 : : * seconds. The internals of this function should use "sleep_ms" for
5921 : : * precise sleep time calculations.
5922 : : */
5923 : : static bool
5924 : 7 : do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
5925 : : {
5926 : 7 : long sleep_ms = (long) (sleep * 1000);
5927 : 7 : printQueryOpt myopt = pset.popt;
5928 : : const char *strftime_fmt;
5929 : : const char *user_title;
5930 : : char *title;
5931 : 7 : const char *pagerprog = NULL;
5932 : 7 : FILE *pagerpipe = NULL;
5933 : : int title_len;
5934 : 7 : int res = 0;
5935 : 7 : bool done = false;
5936 : : #ifndef WIN32
5937 : : sigset_t sigalrm_sigchld_sigint;
5938 : : sigset_t sigalrm_sigchld;
5939 : : sigset_t sigint;
5940 : : struct itimerval interval;
5941 : : #endif
5942 : :
5943 [ + - - + ]: 7 : if (!query_buf || query_buf->len <= 0)
5944 : : {
5945 : 0 : pg_log_error("\\watch cannot be used with an empty query");
5946 : 0 : return false;
5947 : : }
5948 : :
5949 : : #ifndef WIN32
5950 : 7 : sigemptyset(&sigalrm_sigchld_sigint);
5951 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5952 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5953 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5954 : :
5955 : 7 : sigemptyset(&sigalrm_sigchld);
5956 : 7 : sigaddset(&sigalrm_sigchld, SIGCHLD);
5957 : 7 : sigaddset(&sigalrm_sigchld, SIGALRM);
5958 : :
5959 : 7 : sigemptyset(&sigint);
5960 : 7 : sigaddset(&sigint, SIGINT);
5961 : :
5962 : : /*
5963 : : * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5964 : : * configured), to avoid races. sigwait() will receive them.
5965 : : */
5966 : 7 : sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5967 : :
5968 : : /*
5969 : : * Set a timer to interrupt sigwait() so we can run the query at the
5970 : : * requested intervals.
5971 : : */
5972 : 7 : interval.it_value.tv_sec = sleep_ms / 1000;
5973 : 7 : interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5974 : 7 : interval.it_interval = interval.it_value;
5975 [ - + ]: 7 : if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5976 : : {
5977 : 0 : pg_log_error("could not set timer: %m");
5978 : 0 : done = true;
5979 : : }
5980 : : #endif
5981 : :
5982 : : /*
5983 : : * For \watch, we ignore the size of the result and always use the pager
5984 : : * as long as we're talking to a terminal and "\pset pager" is enabled.
5985 : : * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5986 : : * ignore the regular PSQL_PAGER or PAGER environment variables, because
5987 : : * traditional pagers probably won't be very useful for showing a stream
5988 : : * of results.
5989 : : */
5990 : : #ifndef WIN32
5991 : 7 : pagerprog = getenv("PSQL_WATCH_PAGER");
5992 : : /* if variable is empty or all-white-space, don't use pager */
5993 [ - + - - ]: 7 : if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5994 : 0 : pagerprog = NULL;
5995 : : #endif
5996 [ - + - - : 7 : if (pagerprog && myopt.topt.pager &&
- - ]
5997 [ # # ]: 0 : isatty(fileno(stdin)) && isatty(fileno(stdout)))
5998 : : {
5999 : 0 : fflush(NULL);
6000 : 0 : disable_sigpipe_trap();
6001 : 0 : pagerpipe = popen(pagerprog, "w");
6002 : :
6003 [ # # ]: 0 : if (!pagerpipe)
6004 : : /* silently proceed without pager */
6005 : 0 : restore_sigpipe_trap();
6006 : : }
6007 : :
6008 : : /*
6009 : : * Choose format for timestamps. We might eventually make this a \pset
6010 : : * option. In the meantime, using a variable for the format suppresses
6011 : : * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
6012 : : */
6013 : 7 : strftime_fmt = "%c";
6014 : :
6015 : : /*
6016 : : * Set up rendering options, in particular, disable the pager unless
6017 : : * PSQL_WATCH_PAGER was successfully launched.
6018 : : */
6019 [ + - ]: 7 : if (!pagerpipe)
6020 : 7 : myopt.topt.pager = 0;
6021 : :
6022 : : /*
6023 : : * If there's a title in the user configuration, make sure we have room
6024 : : * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
6025 : : * bytes for the rest.
6026 : : */
6027 : 7 : user_title = myopt.title;
6028 [ - + ]: 7 : title_len = (user_title ? strlen(user_title) : 0) + 256;
6029 : 7 : title = pg_malloc(title_len);
6030 : :
6031 : : /* Loop to run query and then sleep awhile */
6032 [ + - ]: 84 : while (!done)
6033 : : {
6034 : : time_t timer;
6035 : : char timebuf[128];
6036 : :
6037 : : /*
6038 : : * Prepare title for output. Note that we intentionally include a
6039 : : * newline at the end of the title; this is somewhat historical but it
6040 : : * makes for reasonably nicely formatted output in simple cases.
6041 : : */
6042 : 84 : timer = time(NULL);
6043 : 84 : strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
6044 : :
6045 [ - + ]: 84 : if (user_title)
6046 : 0 : snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
6047 : : user_title, timebuf, sleep_ms / 1000.0);
6048 : : else
6049 : 84 : snprintf(title, title_len, _("%s (every %gs)\n"),
6050 : : timebuf, sleep_ms / 1000.0);
6051 : 84 : myopt.title = title;
6052 : :
6053 : : /* Run the query and print out the result */
6054 : 84 : res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
6055 : :
6056 : : /*
6057 : : * PSQLexecWatch handles the case where we can no longer repeat the
6058 : : * query, and returns 0 or -1.
6059 : : */
6060 [ + + ]: 82 : if (res <= 0)
6061 : 5 : break;
6062 : :
6063 : : /* If we have iteration count, check that it's not exceeded yet */
6064 [ + + + + ]: 80 : if (iter && (--iter <= 0))
6065 : 3 : break;
6066 : :
6067 : : /* Quit if error on pager pipe (probably pager has quit) */
6068 [ - + - - ]: 77 : if (pagerpipe && ferror(pagerpipe))
6069 : 0 : break;
6070 : :
6071 : : /* Tight loop, no wait needed */
6072 [ + + ]: 77 : if (sleep_ms == 0)
6073 : 4 : continue;
6074 : :
6075 : : #ifdef WIN32
6076 : :
6077 : : /*
6078 : : * Wait a while before running the query again. Break the sleep into
6079 : : * short intervals (at most 1s); that's probably unnecessary since
6080 : : * pg_usleep is interruptible on Windows, but it's cheap insurance.
6081 : : */
6082 : : for (long i = sleep_ms; i > 0;)
6083 : : {
6084 : : long s = Min(i, 1000L);
6085 : :
6086 : : pg_usleep(s * 1000L);
6087 : : if (cancel_pressed)
6088 : : {
6089 : : done = true;
6090 : : break;
6091 : : }
6092 : : i -= s;
6093 : : }
6094 : : #else
6095 : : /* sigwait() will handle SIGINT. */
6096 : 73 : sigprocmask(SIG_BLOCK, &sigint, NULL);
6097 [ - + ]: 73 : if (cancel_pressed)
6098 : 0 : done = true;
6099 : :
6100 : : /* Wait for SIGINT, SIGCHLD or SIGALRM. */
6101 [ + - ]: 73 : while (!done)
6102 : : {
6103 : : int signal_received;
6104 : :
6105 : 73 : errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
6106 [ - + ]: 73 : if (errno != 0)
6107 : : {
6108 : : /* Some other signal arrived? */
6109 [ # # ]: 0 : if (errno == EINTR)
6110 : 0 : continue;
6111 : : else
6112 : : {
6113 : 0 : pg_log_error("could not wait for signals: %m");
6114 : 0 : done = true;
6115 : 73 : break;
6116 : : }
6117 : : }
6118 : : /* On ^C or pager exit, it's time to stop running the query. */
6119 [ + - - + ]: 73 : if (signal_received == SIGINT || signal_received == SIGCHLD)
6120 : 0 : done = true;
6121 : : /* Otherwise, we must have SIGALRM. Time to run the query again. */
6122 : 73 : break;
6123 : : }
6124 : :
6125 : : /* Unblock SIGINT so that slow queries can be interrupted. */
6126 : 73 : sigprocmask(SIG_UNBLOCK, &sigint, NULL);
6127 : : #endif
6128 : : }
6129 : :
6130 [ - + ]: 5 : if (pagerpipe)
6131 : : {
6132 : 0 : pclose(pagerpipe);
6133 : 0 : restore_sigpipe_trap();
6134 : : }
6135 : : else
6136 : : {
6137 : : /*
6138 : : * If the terminal driver echoed "^C", libedit/libreadline might be
6139 : : * confused about the cursor position. Therefore, inject a newline
6140 : : * before the next prompt is displayed. We only do this when not
6141 : : * using a pager, because pagers are expected to restore the screen to
6142 : : * a sane state on exit.
6143 : : */
6144 : 5 : fprintf(stdout, "\n");
6145 : 5 : fflush(stdout);
6146 : : }
6147 : :
6148 : : #ifndef WIN32
6149 : : /* Disable the interval timer. */
6150 : 5 : memset(&interval, 0, sizeof(interval));
6151 : 5 : setitimer(ITIMER_REAL, &interval, NULL);
6152 : : /* Unblock SIGINT, SIGCHLD and SIGALRM. */
6153 : 5 : sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
6154 : : #endif
6155 : :
6156 : 5 : pg_free(title);
6157 : 5 : return (res >= 0);
6158 : : }
6159 : :
6160 : : /*
6161 : : * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
6162 : : * returns true unless we have ECHO_HIDDEN_NOEXEC.
6163 : : */
6164 : : static bool
6165 : 340 : echo_hidden_command(const char *query)
6166 : : {
6167 [ - + ]: 340 : if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
6168 : : {
6169 : 0 : printf(_("/**** INTERNAL QUERY ****/\n"
6170 : : "%s\n"
6171 : : "/************************/\n\n"), query);
6172 : 0 : fflush(stdout);
6173 [ # # ]: 0 : if (pset.logfile)
6174 : : {
6175 : 0 : fprintf(pset.logfile,
6176 : 0 : _("/**** INTERNAL QUERY ****/\n"
6177 : : "%s\n"
6178 : : "/************************/\n\n"), query);
6179 : 0 : fflush(pset.logfile);
6180 : : }
6181 : :
6182 [ # # ]: 0 : if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
6183 : 0 : return false;
6184 : : }
6185 : 340 : return true;
6186 : : }
6187 : :
6188 : : /*
6189 : : * Look up the object identified by obj_type and desc. If successful,
6190 : : * store its OID in *obj_oid and return true, else return false.
6191 : : *
6192 : : * Note that we'll fail if the object doesn't exist OR if there are multiple
6193 : : * matching candidates OR if there's something syntactically wrong with the
6194 : : * object description; unfortunately it can be hard to tell the difference.
6195 : : */
6196 : : static bool
6197 : 170 : lookup_object_oid(EditableObjectType obj_type, const char *desc,
6198 : : Oid *obj_oid)
6199 : : {
6200 : 170 : bool result = true;
6201 : 170 : PQExpBuffer query = createPQExpBuffer();
6202 : : PGresult *res;
6203 : :
6204 [ + + - ]: 170 : switch (obj_type)
6205 : : {
6206 : 58 : case EditableFunction:
6207 : :
6208 : : /*
6209 : : * We have a function description, e.g. "x" or "x(int)". Issue a
6210 : : * query to retrieve the function's OID using a cast to regproc or
6211 : : * regprocedure (as appropriate).
6212 : : */
6213 : 58 : printfPQExpBuffer(query, "/* %s */\n", _("Get function's OID"));
6214 : 58 : appendPQExpBufferStr(query, "SELECT ");
6215 : 58 : appendStringLiteralConn(query, desc, pset.db);
6216 : 58 : appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
6217 [ + + ]: 58 : strchr(desc, '(') ? "regprocedure" : "regproc");
6218 : 58 : break;
6219 : :
6220 : 112 : case EditableView:
6221 : :
6222 : : /*
6223 : : * Convert view name (possibly schema-qualified) to OID. Note:
6224 : : * this code doesn't check if the relation is actually a view.
6225 : : * We'll detect that in get_create_object_cmd().
6226 : : */
6227 : 112 : printfPQExpBuffer(query, "/* %s */\n", _("Get view's OID"));
6228 : 112 : appendPQExpBufferStr(query, "SELECT ");
6229 : 112 : appendStringLiteralConn(query, desc, pset.db);
6230 : 112 : appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
6231 : 112 : break;
6232 : : }
6233 : :
6234 [ - + ]: 170 : if (!echo_hidden_command(query->data))
6235 : : {
6236 : 0 : destroyPQExpBuffer(query);
6237 : 0 : return false;
6238 : : }
6239 : 170 : res = PQexec(pset.db, query->data);
6240 [ + - + - ]: 170 : if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6241 : 170 : *obj_oid = atooid(PQgetvalue(res, 0, 0));
6242 : : else
6243 : : {
6244 : 0 : minimal_error_message(res);
6245 : 0 : result = false;
6246 : : }
6247 : :
6248 : 170 : PQclear(res);
6249 : 170 : destroyPQExpBuffer(query);
6250 : :
6251 : 170 : return result;
6252 : : }
6253 : :
6254 : : /*
6255 : : * Construct a "CREATE OR REPLACE ..." command that describes the specified
6256 : : * database object. If successful, the result is stored in buf.
6257 : : */
6258 : : static bool
6259 : 170 : get_create_object_cmd(EditableObjectType obj_type, Oid oid,
6260 : : PQExpBuffer buf)
6261 : : {
6262 : 170 : bool result = true;
6263 : 170 : PQExpBuffer query = createPQExpBuffer();
6264 : : PGresult *res;
6265 : :
6266 [ + + - ]: 170 : switch (obj_type)
6267 : : {
6268 : 58 : case EditableFunction:
6269 : 58 : printfPQExpBuffer(query, "/* %s */\n", _("Get function's definition"));
6270 : 58 : appendPQExpBuffer(query,
6271 : : "SELECT pg_catalog.pg_get_functiondef(%u)",
6272 : : oid);
6273 : 58 : break;
6274 : :
6275 : 112 : case EditableView:
6276 : :
6277 : : /*
6278 : : * pg_get_viewdef() just prints the query, so we must prepend
6279 : : * CREATE for ourselves. We must fully qualify the view name to
6280 : : * ensure the right view gets replaced. Also, check relation kind
6281 : : * to be sure it's a view.
6282 : : *
6283 : : * Views may have WITH [LOCAL|CASCADED] CHECK OPTION. These are
6284 : : * not part of the view definition returned by pg_get_viewdef()
6285 : : * and so need to be retrieved separately. Materialized views may
6286 : : * have arbitrary storage parameter reloptions.
6287 : : */
6288 : 112 : printfPQExpBuffer(query, "/* %s */\n", _("Get view's definition and details"));
6289 : 112 : appendPQExpBuffer(query,
6290 : : "SELECT nspname, relname, relkind, "
6291 : : "pg_catalog.pg_get_viewdef(c.oid, true), "
6292 : : "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6293 : : "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6294 : : "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
6295 : : "FROM pg_catalog.pg_class c "
6296 : : "LEFT JOIN pg_catalog.pg_namespace n "
6297 : : "ON c.relnamespace = n.oid WHERE c.oid = %u",
6298 : : oid);
6299 : 112 : break;
6300 : : }
6301 : :
6302 [ - + ]: 170 : if (!echo_hidden_command(query->data))
6303 : : {
6304 : 0 : destroyPQExpBuffer(query);
6305 : 0 : return false;
6306 : : }
6307 : 170 : res = PQexec(pset.db, query->data);
6308 [ + - + - ]: 170 : if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6309 : : {
6310 : 170 : resetPQExpBuffer(buf);
6311 [ + + - ]: 170 : switch (obj_type)
6312 : : {
6313 : 58 : case EditableFunction:
6314 : 58 : appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
6315 : 58 : break;
6316 : :
6317 : 112 : case EditableView:
6318 : : {
6319 : 112 : char *nspname = PQgetvalue(res, 0, 0);
6320 : 112 : char *relname = PQgetvalue(res, 0, 1);
6321 : 112 : char *relkind = PQgetvalue(res, 0, 2);
6322 : 112 : char *viewdef = PQgetvalue(res, 0, 3);
6323 : 112 : char *reloptions = PQgetvalue(res, 0, 4);
6324 : 112 : char *checkoption = PQgetvalue(res, 0, 5);
6325 : :
6326 : : /*
6327 : : * If the backend ever supports CREATE OR REPLACE
6328 : : * MATERIALIZED VIEW, allow that here; but as of today it
6329 : : * does not, so editing a matview definition in this way
6330 : : * is impossible.
6331 : : */
6332 [ + - ]: 112 : switch (relkind[0])
6333 : : {
6334 : : #ifdef NOT_USED
6335 : : case RELKIND_MATVIEW:
6336 : : appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
6337 : : break;
6338 : : #endif
6339 : 112 : case RELKIND_VIEW:
6340 : 112 : appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
6341 : 112 : break;
6342 : 0 : default:
6343 : 0 : pg_log_error("\"%s.%s\" is not a view",
6344 : : nspname, relname);
6345 : 0 : result = false;
6346 : 0 : break;
6347 : : }
6348 : 112 : appendPQExpBuffer(buf, "%s.", fmtId(nspname));
6349 : 112 : appendPQExpBufferStr(buf, fmtId(relname));
6350 : :
6351 : : /* reloptions, if not an empty array "{}" */
6352 [ + - - + ]: 112 : if (reloptions != NULL && strlen(reloptions) > 2)
6353 : : {
6354 : 0 : appendPQExpBufferStr(buf, "\n WITH (");
6355 [ # # ]: 0 : if (!appendReloptionsArray(buf, reloptions, "",
6356 : : pset.encoding,
6357 : 0 : standard_strings()))
6358 : : {
6359 : 0 : pg_log_error("could not parse reloptions array");
6360 : 0 : result = false;
6361 : : }
6362 : 0 : appendPQExpBufferChar(buf, ')');
6363 : : }
6364 : :
6365 : : /* View definition from pg_get_viewdef (a SELECT query) */
6366 : 112 : appendPQExpBuffer(buf, " AS\n%s", viewdef);
6367 : :
6368 : : /* Get rid of the semicolon that pg_get_viewdef appends */
6369 [ + - + - ]: 112 : if (buf->len > 0 && buf->data[buf->len - 1] == ';')
6370 : 112 : buf->data[--(buf->len)] = '\0';
6371 : :
6372 : : /* WITH [LOCAL|CASCADED] CHECK OPTION */
6373 [ + - - + ]: 112 : if (checkoption && checkoption[0] != '\0')
6374 : 0 : appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
6375 : : checkoption);
6376 : : }
6377 : 112 : break;
6378 : : }
6379 : : /* Make sure result ends with a newline */
6380 [ + - + + ]: 170 : if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
6381 : 112 : appendPQExpBufferChar(buf, '\n');
6382 : : }
6383 : : else
6384 : : {
6385 : 0 : minimal_error_message(res);
6386 : 0 : result = false;
6387 : : }
6388 : :
6389 : 170 : PQclear(res);
6390 : 170 : destroyPQExpBuffer(query);
6391 : :
6392 : 170 : return result;
6393 : : }
6394 : :
6395 : : /*
6396 : : * If the given argument of \ef or \ev ends with a line number, delete the line
6397 : : * number from the argument string and return it as an integer. (We need
6398 : : * this kluge because we're too lazy to parse \ef's function or \ev's view
6399 : : * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
6400 : : *
6401 : : * Returns -1 if no line number is present, 0 on error, or a positive value
6402 : : * on success.
6403 : : */
6404 : : static int
6405 : 0 : strip_lineno_from_objdesc(char *obj)
6406 : : {
6407 : : char *c;
6408 : : int lineno;
6409 : :
6410 [ # # # # ]: 0 : if (!obj || obj[0] == '\0')
6411 : 0 : return -1;
6412 : :
6413 : 0 : c = obj + strlen(obj) - 1;
6414 : :
6415 : : /*
6416 : : * This business of parsing backwards is dangerous as can be in a
6417 : : * multibyte environment: there is no reason to believe that we are
6418 : : * looking at the first byte of a character, nor are we necessarily
6419 : : * working in a "safe" encoding. Fortunately the bitpatterns we are
6420 : : * looking for are unlikely to occur as non-first bytes, but beware of
6421 : : * trying to expand the set of cases that can be recognized. We must
6422 : : * guard the <ctype.h> macros by using isascii() first, too.
6423 : : */
6424 : :
6425 : : /* skip trailing whitespace */
6426 [ # # # # : 0 : while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
# # ]
6427 : 0 : c--;
6428 : :
6429 : : /* must have a digit as last non-space char */
6430 [ # # # # : 0 : if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
# # ]
6431 : 0 : return -1;
6432 : :
6433 : : /* find start of digit string */
6434 [ # # # # : 0 : while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
# # ]
6435 : 0 : c--;
6436 : :
6437 : : /* digits must be separated from object name by space or closing paren */
6438 : : /* notice also that we are not allowing an empty object name ... */
6439 [ # # # # ]: 0 : if (c == obj || !isascii((unsigned char) *c) ||
6440 [ # # # # ]: 0 : !(isspace((unsigned char) *c) || *c == ')'))
6441 : 0 : return -1;
6442 : :
6443 : : /* parse digit string */
6444 : 0 : c++;
6445 : 0 : lineno = atoi(c);
6446 [ # # ]: 0 : if (lineno < 1)
6447 : : {
6448 : 0 : pg_log_error("invalid line number: %s", c);
6449 : 0 : return 0;
6450 : : }
6451 : :
6452 : : /* strip digit string from object name */
6453 : 0 : *c = '\0';
6454 : :
6455 : 0 : return lineno;
6456 : : }
6457 : :
6458 : : /*
6459 : : * Count number of lines in the buffer.
6460 : : * This is used to test if pager is needed or not.
6461 : : */
6462 : : static int
6463 : 170 : count_lines_in_buf(PQExpBuffer buf)
6464 : : {
6465 : 170 : int lineno = 0;
6466 : 170 : const char *lines = buf->data;
6467 : :
6468 [ + + ]: 2279 : while (*lines != '\0')
6469 : : {
6470 : 2109 : lineno++;
6471 : : /* find start of next line */
6472 : 2109 : lines = strchr(lines, '\n');
6473 [ - + ]: 2109 : if (!lines)
6474 : 0 : break;
6475 : 2109 : lines++;
6476 : : }
6477 : :
6478 : 170 : return lineno;
6479 : : }
6480 : :
6481 : : /*
6482 : : * Write text at *lines to output with line numbers.
6483 : : *
6484 : : * For functions, lineno "1" should correspond to the first line of the
6485 : : * function body; lines before that are unnumbered. We expect that
6486 : : * pg_get_functiondef() will emit that on a line beginning with "AS ",
6487 : : * "BEGIN ", or "RETURN ", and that there can be no such line before
6488 : : * the real start of the function body.
6489 : : *
6490 : : * Caution: this scribbles on *lines.
6491 : : */
6492 : : static void
6493 : 28 : print_with_linenumbers(FILE *output, char *lines, bool is_func)
6494 : : {
6495 : 28 : bool in_header = is_func;
6496 : 28 : int lineno = 0;
6497 : :
6498 [ + + ]: 256 : while (*lines != '\0')
6499 : : {
6500 : : char *eol;
6501 : :
6502 [ + + ]: 228 : if (in_header &&
6503 [ + - ]: 124 : (strncmp(lines, "AS ", 3) == 0 ||
6504 [ + + ]: 124 : strncmp(lines, "BEGIN ", 6) == 0 ||
6505 [ + + ]: 100 : strncmp(lines, "RETURN ", 7) == 0))
6506 : 28 : in_header = false;
6507 : :
6508 : : /* increment lineno only for body's lines */
6509 [ + + ]: 228 : if (!in_header)
6510 : 132 : lineno++;
6511 : :
6512 : : /* find and mark end of current line */
6513 : 228 : eol = strchr(lines, '\n');
6514 [ + - ]: 228 : if (eol != NULL)
6515 : 228 : *eol = '\0';
6516 : :
6517 : : /* show current line as appropriate */
6518 [ + + ]: 228 : if (in_header)
6519 : 96 : fprintf(output, " %s\n", lines);
6520 : : else
6521 : 132 : fprintf(output, "%-7d %s\n", lineno, lines);
6522 : :
6523 : : /* advance to next line, if any */
6524 [ - + ]: 228 : if (eol == NULL)
6525 : 0 : break;
6526 : 228 : lines = ++eol;
6527 : : }
6528 : 28 : }
6529 : :
6530 : : /*
6531 : : * Report just the primary error; this is to avoid cluttering the output
6532 : : * with, for instance, a redisplay of the internally generated query
6533 : : */
6534 : : static void
6535 : 0 : minimal_error_message(PGresult *res)
6536 : : {
6537 : : PQExpBuffer msg;
6538 : : const char *fld;
6539 : :
6540 : 0 : msg = createPQExpBuffer();
6541 : :
6542 : 0 : fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
6543 [ # # ]: 0 : if (fld)
6544 : 0 : printfPQExpBuffer(msg, "%s: ", fld);
6545 : : else
6546 : 0 : printfPQExpBuffer(msg, "ERROR: ");
6547 : 0 : fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
6548 [ # # ]: 0 : if (fld)
6549 : 0 : appendPQExpBufferStr(msg, fld);
6550 : : else
6551 : 0 : appendPQExpBufferStr(msg, "(not available)");
6552 : 0 : appendPQExpBufferChar(msg, '\n');
6553 : :
6554 : 0 : pg_log_error("%s", msg->data);
6555 : :
6556 : 0 : destroyPQExpBuffer(msg);
6557 : 0 : }
|