Age Owner Branch data TLA 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
8192 tgl@sss.pgh.pa.us 231 :CBC 32366 : 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 : :
4971 andrew@dunslane.net 240 [ - + ]: 32366 : Assert(scan_state != NULL);
3404 tgl@sss.pgh.pa.us 241 [ - + ]: 32366 : Assert(cstack != NULL);
242 : :
243 : : /* Parse off the command name */
8192 244 : 32366 : 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 : : */
348 nathan@postgresql.or 252 [ + + + + ]: 32366 : 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 : 32365 : status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
259 : :
7524 peter_e@gmx.net 260 [ + + ]: 32364 : if (status == PSQL_CMD_UNKNOWN)
261 : : {
2672 peter@eisentraut.org 262 : 12 : pg_log_error("invalid command \\%s", cmd);
9600 bruce@momjian.us 263 [ - + ]: 12 : if (pset.cur_cmd_interactive)
1569 tgl@sss.pgh.pa.us 264 :UBC 0 : pg_log_error_hint("Try \\? for help.");
7524 peter_e@gmx.net 265 :CBC 12 : status = PSQL_CMD_ERROR;
266 : : }
267 : :
268 [ + + ]: 32364 : 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 : : */
3404 tgl@sss.pgh.pa.us 275 : 31572 : bool active_branch = conditional_active(cstack);
276 : :
277 : 31572 : conditional_stack_push(cstack, IFSTATE_IGNORED);
7888 278 [ + + ]: 31592 : while ((arg = psql_scan_slash_option(scan_state,
279 : : OT_NORMAL, NULL, false)))
280 : : {
3404 281 [ + - ]: 20 : if (active_branch)
2672 peter@eisentraut.org 282 : 20 : pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
7888 tgl@sss.pgh.pa.us 283 : 20 : free(arg);
284 : : }
3404 285 : 31572 : conditional_stack_pop(cstack);
286 : : }
287 : : else
288 : : {
289 : : /* silently throw away rest of line after an erroneous command */
7888 290 [ + + ]: 805 : 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 */
8192 296 : 32364 : psql_scan_slash_command_end(scan_state);
297 : :
298 : 32364 : free(cmd);
299 : :
300 : : /* some commands write to queryFout, so make sure output is sent */
7149 301 : 32364 : fflush(pset.queryFout);
302 : :
9760 bruce@momjian.us 303 : 32364 : 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
3404 tgl@sss.pgh.pa.us 315 : 32365 : 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 : 32365 : 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 [ + + - + ]: 32365 : if (pset.cur_cmd_interactive && !active_branch &&
3404 tgl@sss.pgh.pa.us 332 [ # # ]:UBC 0 : !is_branching_command(cmd))
333 : : {
2672 peter@eisentraut.org 334 : 0 : pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
335 : : cmd);
336 : : }
337 : :
3404 tgl@sss.pgh.pa.us 338 [ + + ]:CBC 32365 : if (strcmp(cmd, "a") == 0)
339 : 52 : status = exec_command_a(scan_state, active_branch);
1348 peter@eisentraut.org 340 [ + + ]: 32313 : else if (strcmp(cmd, "bind") == 0)
341 : 532 : status = exec_command_bind(scan_state, active_branch);
702 michael@paquier.xyz 342 [ + + ]: 31781 : else if (strcmp(cmd, "bind_named") == 0)
343 : 116 : status = exec_command_bind_named(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 344 [ + + ]: 31665 : else if (strcmp(cmd, "C") == 0)
345 : 4 : status = exec_command_C(scan_state, active_branch);
346 [ + + + + ]: 31661 : else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
347 : 222 : status = exec_command_connect(scan_state, active_branch);
348 [ + + ]: 31439 : else if (strcmp(cmd, "cd") == 0)
349 : 4 : status = exec_command_cd(scan_state, active_branch, cmd);
396 michael@paquier.xyz 350 [ + + ]: 31435 : else if (strcmp(cmd, "close_prepared") == 0)
351 : 33 : status = exec_command_close_prepared(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 352 [ + + ]: 31402 : else if (strcmp(cmd, "conninfo") == 0)
353 : 4 : status = exec_command_conninfo(scan_state, active_branch);
354 [ + + ]: 31398 : else if (pg_strcasecmp(cmd, "copy") == 0)
355 : 99 : status = exec_command_copy(scan_state, active_branch);
356 [ + + ]: 31299 : else if (strcmp(cmd, "copyright") == 0)
357 : 5 : status = exec_command_copyright(scan_state, active_branch);
358 [ + + ]: 31294 : else if (strcmp(cmd, "crosstabview") == 0)
359 : 100 : status = exec_command_crosstabview(scan_state, active_branch);
360 [ + + ]: 31194 : else if (cmd[0] == 'd')
361 : 4769 : status = exec_command_d(scan_state, active_branch, cmd);
362 [ + + - + ]: 26425 : 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 [ + + ]: 26421 : else if (strcmp(cmd, "ef") == 0)
3244 366 : 4 : status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
3404 367 [ + + ]: 26417 : else if (strcmp(cmd, "ev") == 0)
3244 368 : 4 : status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
2577 369 [ + + + + ]: 26413 : else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
370 [ + + ]: 15826 : strcmp(cmd, "warn") == 0)
3404 371 : 20565 : status = exec_command_echo(scan_state, active_branch, cmd);
372 [ + + ]: 5848 : else if (strcmp(cmd, "elif") == 0)
373 : 32 : status = exec_command_elif(scan_state, cstack, query_buf);
374 [ + + ]: 5816 : else if (strcmp(cmd, "else") == 0)
375 : 88 : status = exec_command_else(scan_state, cstack, query_buf);
376 [ + + ]: 5728 : else if (strcmp(cmd, "endif") == 0)
377 : 141 : status = exec_command_endif(scan_state, cstack, query_buf);
519 michael@paquier.xyz 378 [ + + ]: 5587 : else if (strcmp(cmd, "endpipeline") == 0)
379 : 225 : status = exec_command_endpipeline(scan_state, active_branch);
3404 tgl@sss.pgh.pa.us 380 [ + + ]: 5362 : else if (strcmp(cmd, "encoding") == 0)
381 : 12 : status = exec_command_encoding(scan_state, active_branch);
382 [ + + ]: 5350 : else if (strcmp(cmd, "errverbose") == 0)
383 : 8 : status = exec_command_errverbose(scan_state, active_branch);
384 [ + + ]: 5342 : else if (strcmp(cmd, "f") == 0)
385 : 4 : status = exec_command_f(scan_state, active_branch);
519 michael@paquier.xyz 386 [ + + ]: 5338 : else if (strcmp(cmd, "flush") == 0)
387 : 16 : status = exec_command_flush(scan_state, active_branch);
388 [ + + ]: 5322 : else if (strcmp(cmd, "flushrequest") == 0)
389 : 40 : status = exec_command_flushrequest(scan_state, active_branch);
3404 tgl@sss.pgh.pa.us 390 [ + + + + ]: 5282 : else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
391 : 302 : status = exec_command_g(scan_state, active_branch, cmd);
3245 392 [ + + ]: 4980 : else if (strcmp(cmd, "gdesc") == 0)
393 : 57 : status = exec_command_gdesc(scan_state, active_branch);
1678 394 [ + + ]: 4923 : else if (strcmp(cmd, "getenv") == 0)
395 : 227 : status = exec_command_getenv(scan_state, active_branch, cmd);
519 michael@paquier.xyz 396 [ + + ]: 4696 : else if (strcmp(cmd, "getresults") == 0)
397 : 128 : status = exec_command_getresults(scan_state, active_branch);
3404 tgl@sss.pgh.pa.us 398 [ + + ]: 4568 : else if (strcmp(cmd, "gexec") == 0)
399 : 37 : status = exec_command_gexec(scan_state, active_branch);
400 [ + + ]: 4531 : else if (strcmp(cmd, "gset") == 0)
401 : 599 : status = exec_command_gset(scan_state, active_branch);
402 [ + + + + ]: 3932 : else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
403 : 6 : status = exec_command_help(scan_state, active_branch);
404 [ + - + + ]: 3926 : else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
405 : 4 : status = exec_command_html(scan_state, active_branch);
406 [ + + + - ]: 3922 : else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
407 [ + + - + ]: 3918 : strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
408 : 8 : status = exec_command_include(scan_state, active_branch, cmd);
409 [ + + ]: 3914 : else if (strcmp(cmd, "if") == 0)
410 : 152 : status = exec_command_if(scan_state, cstack, query_buf);
411 [ + + + - ]: 3762 : else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
557 dean.a.rasheed@gmail 412 [ + - + - ]: 3758 : strcmp(cmd, "lx") == 0 || strcmp(cmd, "listx") == 0 ||
413 [ + - + - ]: 3758 : strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0 ||
414 [ + - + - ]: 3758 : strcmp(cmd, "lx+") == 0 || strcmp(cmd, "listx+") == 0 ||
415 [ + - - + ]: 3758 : strcmp(cmd, "l+x") == 0 || strcmp(cmd, "list+x") == 0)
3404 tgl@sss.pgh.pa.us 416 : 4 : status = exec_command_list(scan_state, active_branch, cmd);
417 [ + + ]: 3758 : else if (strncmp(cmd, "lo_", 3) == 0)
418 : 41 : status = exec_command_lo(scan_state, active_branch, cmd);
419 [ + + - + ]: 3717 : else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
420 : 28 : status = exec_command_out(scan_state, active_branch);
421 [ + + - + ]: 3689 : else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
3401 422 : 28 : status = exec_command_print(scan_state, active_branch,
423 : : query_buf, previous_buf);
702 michael@paquier.xyz 424 [ + + ]: 3661 : else if (strcmp(cmd, "parse") == 0)
425 : 75 : status = exec_command_parse(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 426 [ + + ]: 3586 : else if (strcmp(cmd, "password") == 0)
427 : 5 : status = exec_command_password(scan_state, active_branch);
428 [ + + ]: 3581 : else if (strcmp(cmd, "prompt") == 0)
429 : 4 : status = exec_command_prompt(scan_state, active_branch, cmd);
430 [ + + ]: 3577 : else if (strcmp(cmd, "pset") == 0)
431 : 1246 : status = exec_command_pset(scan_state, active_branch);
432 [ + + + + ]: 2331 : else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
433 : 278 : status = exec_command_quit(scan_state, active_branch);
434 [ + + + + ]: 2053 : else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
435 : 56 : status = exec_command_reset(scan_state, active_branch, query_buf);
348 nathan@postgresql.or 436 [ + + ]: 1997 : else if (strcmp(cmd, "restrict") == 0)
437 : 37 : status = exec_command_restrict(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 438 [ + + ]: 1960 : else if (strcmp(cmd, "s") == 0)
439 : 4 : status = exec_command_s(scan_state, active_branch);
494 michael@paquier.xyz 440 [ + + ]: 1956 : else if (strcmp(cmd, "sendpipeline") == 0)
441 : 481 : status = exec_command_sendpipeline(scan_state, active_branch);
3404 tgl@sss.pgh.pa.us 442 [ + + ]: 1475 : else if (strcmp(cmd, "set") == 0)
443 : 718 : status = exec_command_set(scan_state, active_branch);
444 [ + + ]: 757 : else if (strcmp(cmd, "setenv") == 0)
445 : 12 : status = exec_command_setenv(scan_state, active_branch, cmd);
446 [ + + + + ]: 745 : else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
3244 447 : 58 : status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
3404 448 [ + + - + ]: 687 : else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
3244 449 : 112 : status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
519 michael@paquier.xyz 450 [ + + ]: 575 : else if (strcmp(cmd, "startpipeline") == 0)
451 : 225 : status = exec_command_startpipeline(scan_state, active_branch);
452 [ + + ]: 350 : else if (strcmp(cmd, "syncpipeline") == 0)
453 : 99 : status = exec_command_syncpipeline(scan_state, active_branch);
3404 tgl@sss.pgh.pa.us 454 [ + + ]: 251 : else if (strcmp(cmd, "t") == 0)
455 : 52 : status = exec_command_t(scan_state, active_branch);
456 [ + + ]: 199 : else if (strcmp(cmd, "T") == 0)
457 : 4 : status = exec_command_T(scan_state, active_branch);
458 [ + + ]: 195 : else if (strcmp(cmd, "timing") == 0)
459 : 6 : status = exec_command_timing(scan_state, active_branch);
348 nathan@postgresql.or 460 [ + + ]: 189 : else if (strcmp(cmd, "unrestrict") == 0)
461 : 36 : status = exec_command_unrestrict(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 462 [ + + ]: 153 : else if (strcmp(cmd, "unset") == 0)
463 : 34 : status = exec_command_unset(scan_state, active_branch, cmd);
464 [ + + - + ]: 119 : 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 [ + + ]: 111 : else if (strcmp(cmd, "watch") == 0)
468 : 22 : status = exec_command_watch(scan_state, active_branch,
469 : : query_buf, previous_buf);
470 [ + + ]: 89 : else if (strcmp(cmd, "x") == 0)
471 : 49 : status = exec_command_x(scan_state, active_branch);
557 dean.a.rasheed@gmail 472 [ + + ]: 40 : else if (strcmp(cmd, "z") == 0 ||
473 [ + - + + ]: 24 : strcmp(cmd, "zS") == 0 || strcmp(cmd, "zx") == 0 ||
474 [ + - - + ]: 20 : strcmp(cmd, "zSx") == 0 || strcmp(cmd, "zxS") == 0)
1295 475 : 20 : status = exec_command_z(scan_state, active_branch, cmd);
3404 tgl@sss.pgh.pa.us 476 [ + + ]: 20 : else if (strcmp(cmd, "!") == 0)
477 : 4 : status = exec_command_shell_escape(scan_state, active_branch);
478 [ + + ]: 16 : else if (strcmp(cmd, "?") == 0)
479 : 4 : status = exec_command_slash_command_help(scan_state, active_branch);
480 : : else
481 : 12 : 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 [ + + ]: 32363 : if (status == PSQL_CMD_SEND)
1939 489 : 2289 : (void) copy_previous_query(query_buf, previous_buf);
490 : :
3404 491 : 32363 : 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 : : {
9689 peter_e@gmx.net 507 [ + + ]: 48 : if (pset.popt.topt.format != PRINT_ALIGNED)
7270 tgl@sss.pgh.pa.us 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 : :
3404 513 [ + - ]: 52 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
514 : : }
515 : :
516 : : /*
517 : : * \bind -- set query parameters
518 : : */
519 : : static backslashResult
1348 peter@eisentraut.org 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 : :
674 michael@paquier.xyz 530 : 528 : clean_extended_state();
531 : :
1348 peter@eisentraut.org 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 : : }
1249 michael@paquier.xyz 540 : 433 : pset.bind_params[nparams - 1] = opt;
541 : : }
542 : :
1348 peter@eisentraut.org 543 : 528 : pset.bind_nparams = nparams;
702 michael@paquier.xyz 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 : :
674 567 : 112 : clean_extended_state();
568 : :
569 : : /* get the mandatory prepared statement name */
702 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
918 596 : 4 : ignore_slash_options(scan_state);
597 : :
1348 peter@eisentraut.org 598 : 116 : return status;
599 : : }
600 : :
601 : : /*
602 : : * \C -- override table title (formerly change HTML caption)
603 : : */
604 : : static backslashResult
3404 tgl@sss.pgh.pa.us 605 : 4 : exec_command_C(PsqlScanState scan_state, bool active_branch)
606 : : {
607 : 4 : bool success = true;
608 : :
609 [ - + ]: 4 : if (active_branch)
610 : : {
8192 tgl@sss.pgh.pa.us 611 :UBC 0 : char *opt = psql_scan_slash_option(scan_state,
612 : : OT_NORMAL, NULL, true);
613 : :
7270 614 : 0 : success = do_pset("title", opt, &pset.popt, pset.quiet);
9600 bruce@momjian.us 615 : 0 : free(opt);
616 : : }
617 : : else
3404 tgl@sss.pgh.pa.us 618 :CBC 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 : 222 : exec_command_connect(PsqlScanState scan_state, bool active_branch)
639 : : {
640 : 222 : bool success = true;
641 : :
642 [ + + ]: 222 : if (active_branch)
643 : : {
644 : : static const char prefix[] = "-reuse-previous=";
645 : : char *opt1,
646 : : *opt2,
647 : : *opt3,
648 : : *opt4;
3463 649 : 218 : enum trivalue reuse_previous = TRI_DEFAULT;
650 : :
7419 neilc@samurai.com 651 : 218 : opt1 = read_connect_arg(scan_state);
3638 noah@leadboat.com 652 [ + + + + ]: 218 : if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
653 : : {
654 : : bool on_off;
655 : :
3463 tgl@sss.pgh.pa.us 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 [ + - ]: 218 : if (success) /* give up if reuse_previous was invalid */
668 : : {
669 : 218 : opt2 = read_connect_arg(scan_state);
670 : 218 : opt3 = read_connect_arg(scan_state);
671 : 218 : opt4 = read_connect_arg(scan_state);
672 : :
673 : 218 : success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
674 : :
675 : 218 : free(opt2);
676 : 218 : free(opt3);
677 : 218 : free(opt4);
678 : : }
9600 bruce@momjian.us 679 : 218 : free(opt1);
680 : : }
681 : : else
3404 tgl@sss.pgh.pa.us 682 : 4 : ignore_slash_options(scan_state);
683 : :
684 [ + - ]: 222 : 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 : : {
8192 tgl@sss.pgh.pa.us 697 :UBC 0 : char *opt = psql_scan_slash_option(scan_state,
698 : : OT_NORMAL, NULL, true);
699 : : char *dir;
700 : :
9210 peter_e@gmx.net 701 [ # # ]: 0 : if (opt)
702 : 0 : dir = opt;
703 : : else
704 : : {
705 : : #ifndef WIN32
706 : : /* This should match get_home_path() */
1658 tgl@sss.pgh.pa.us 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 : : {
2672 peter@eisentraut.org 738 : 0 : pg_log_error("\\%s: could not change directory to \"%s\": %m",
739 : : cmd, dir);
9210 peter_e@gmx.net 740 : 0 : success = false;
741 : : }
742 : :
1500 peter@eisentraut.org 743 : 0 : free(opt);
744 : : }
745 : : else
3404 tgl@sss.pgh.pa.us 746 :CBC 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
396 michael@paquier.xyz 755 : 33 : exec_command_close_prepared(PsqlScanState scan_state, bool active_branch, const char *cmd)
756 : : {
702 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 : :
674 764 : 29 : clean_extended_state();
765 : :
702 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
3404 tgl@sss.pgh.pa.us 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 : : char *paramval;
804 : :
518 alvherre@alvh.no-ip. 805 [ + - ]: 4 : if (!active_branch)
806 : 4 : return PSQL_CMD_SKIP_LINE;
807 : :
518 alvherre@alvh.no-ip. 808 :UBC 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);
406 fujii@postgresql.org 818 : 0 : version_num = PQfullProtocolVersion(pset.db);
819 : 0 : protocol_version = psprintf("%d.%d", version_num / 10000,
820 : : version_num % 10000);
518 alvherre@alvh.no-ip. 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 */
405 peter@eisentraut.org 902 : 0 : printTableAddCell(&cont, _("SSL Connection"), false, false);
518 alvherre@alvh.no-ip. 903 [ # # ]: 0 : printTableAddCell(&cont, ssl_in_use ? _("true") : _("false"), false, false);
904 : :
905 : : /* SSL Information */
906 [ # # ]: 0 : if (ssl_in_use)
907 : : {
908 : : char *library,
909 : : *protocol,
910 : : *key_bits,
911 : : *cipher,
912 : : *compression,
913 : : *alpn;
914 : :
915 : 0 : library = (char *) PQsslAttribute(pset.db, "library");
916 : 0 : protocol = (char *) PQsslAttribute(pset.db, "protocol");
917 : 0 : key_bits = (char *) PQsslAttribute(pset.db, "key_bits");
918 : 0 : cipher = (char *) PQsslAttribute(pset.db, "cipher");
919 : 0 : compression = (char *) PQsslAttribute(pset.db, "compression");
920 : 0 : alpn = (char *) PQsslAttribute(pset.db, "alpn");
921 : :
405 peter@eisentraut.org 922 : 0 : printTableAddCell(&cont, _("SSL Library"), false, false);
518 alvherre@alvh.no-ip. 923 [ # # ]: 0 : printTableAddCell(&cont, library ? library : _("unknown"), false, false);
924 : :
405 peter@eisentraut.org 925 : 0 : printTableAddCell(&cont, _("SSL Protocol"), false, false);
518 alvherre@alvh.no-ip. 926 [ # # ]: 0 : printTableAddCell(&cont, protocol ? protocol : _("unknown"), false, false);
927 : :
405 peter@eisentraut.org 928 : 0 : printTableAddCell(&cont, _("SSL Key Bits"), false, false);
518 alvherre@alvh.no-ip. 929 [ # # ]: 0 : printTableAddCell(&cont, key_bits ? key_bits : _("unknown"), false, false);
930 : :
405 peter@eisentraut.org 931 : 0 : printTableAddCell(&cont, _("SSL Cipher"), false, false);
518 alvherre@alvh.no-ip. 932 [ # # ]: 0 : printTableAddCell(&cont, cipher ? cipher : _("unknown"), false, false);
933 : :
405 peter@eisentraut.org 934 : 0 : printTableAddCell(&cont, _("SSL Compression"), false, false);
518 alvherre@alvh.no-ip. 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 = (char *) 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 = (char *) 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 : :
3404 tgl@sss.pgh.pa.us 956 : 0 : return PSQL_CMD_SKIP_LINE;
957 : : }
958 : :
959 : : /*
960 : : * \copy -- run a COPY command
961 : : */
962 : : static backslashResult
3404 tgl@sss.pgh.pa.us 963 :CBC 99 : exec_command_copy(PsqlScanState scan_state, bool active_branch)
964 : : {
965 : 99 : bool success = true;
966 : :
967 [ + + ]: 99 : if (active_branch)
968 : : {
8192 969 : 95 : char *opt = psql_scan_slash_option(scan_state,
970 : : OT_WHOLE_LINE, NULL, false);
971 : :
972 : 95 : success = do_copy(opt);
973 : 95 : free(opt);
974 : : }
975 : : else
3404 976 : 4 : ignore_slash_whole_line(scan_state);
977 : :
978 [ + + ]: 99 : 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)
9760 bruce@momjian.us 988 : 1 : print_copyright();
989 : :
3404 tgl@sss.pgh.pa.us 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 : : {
14 peter@eisentraut.org 1003 [ + + ]:GNC 480 : for (size_t i = 0; i < lengthof(pset.ctv_args); i++)
3754 tgl@sss.pgh.pa.us 1004 :CBC 384 : pset.ctv_args[i] = psql_scan_slash_option(scan_state,
1005 : : OT_NORMAL, NULL, true);
3760 alvherre@alvh.no-ip. 1006 : 96 : pset.crosstab_flag = true;
1007 : 96 : status = PSQL_CMD_SEND;
1008 : : }
1009 : : else
3404 tgl@sss.pgh.pa.us 1010 : 4 : ignore_slash_options(scan_state);
1011 : :
1012 : 100 : return status;
1013 : : }
1014 : :
1015 : : /*
1016 : : * \d* commands
1017 : : */
1018 : : static backslashResult
1019 : 4769 : exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
1020 : : {
1021 : 4769 : backslashResult status = PSQL_CMD_SKIP_LINE;
1022 : 4769 : bool success = true;
1023 : :
1024 [ + + ]: 4769 : 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 */
8192 1032 : 4765 : pattern = psql_scan_slash_option(scan_state,
1033 : : OT_NORMAL, NULL, true);
1034 : :
9600 bruce@momjian.us 1035 : 4765 : show_verbose = strchr(cmd, '+') ? true : false;
6395 1036 : 4765 : 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 : : */
557 dean.a.rasheed@gmail 1044 : 4765 : save_expanded = pset.popt.topt.expanded;
1045 [ + + + + ]: 4765 : if (cmd[1] != '\0' && strchr(&cmd[2], 'x'))
1046 : 20 : pset.popt.topt.expanded = 1;
1047 : :
9760 bruce@momjian.us 1048 [ + + + + : 4765 : switch (cmd[1])
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
1049 : : {
1050 : 2762 : case '\0':
1051 : : case '+':
1052 : : case 'S':
8750 tgl@sss.pgh.pa.us 1053 [ + + ]: 2762 : if (pattern)
6395 bruce@momjian.us 1054 : 2750 : success = describeTableDetails(pattern, show_verbose, show_system);
1055 : : else
1056 : : /* standard listing of interesting things */
131 peter@eisentraut.org 1057 : 12 : success = listTables("tvmsEG", NULL, show_verbose, show_system);
9760 bruce@momjian.us 1058 : 2762 : break;
3700 alvherre@alvh.no-ip. 1059 : 148 : case 'A':
1060 : : {
2330 akorotkov@postgresql 1061 : 148 : char *pattern2 = NULL;
1062 : :
557 dean.a.rasheed@gmail 1063 [ + + + + : 148 : if (pattern && cmd[2] != '\0' && cmd[2] != '+' && cmd[2] != 'x')
+ + + - ]
2330 akorotkov@postgresql 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':
2205 1083 : 28 : success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
2330 1084 : 28 : break;
2330 akorotkov@postgresql 1085 :UBC 0 : default:
1086 : 0 : status = PSQL_CMD_UNKNOWN;
1087 : 0 : break;
1088 : : }
1089 : :
1500 peter@eisentraut.org 1090 :CBC 148 : free(pattern2);
1091 : : }
3700 alvherre@alvh.no-ip. 1092 : 148 : break;
9760 bruce@momjian.us 1093 : 36 : case 'a':
6409 1094 : 36 : success = describeAggregates(pattern, show_verbose, show_system);
9760 1095 : 36 : break;
8072 tgl@sss.pgh.pa.us 1096 : 16 : case 'b':
8045 bruce@momjian.us 1097 : 16 : success = describeTablespaces(pattern, show_verbose);
8072 tgl@sss.pgh.pa.us 1098 : 16 : break;
8600 1099 : 36 : case 'c':
1570 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);
8600 1108 : 36 : break;
1109 : 28 : case 'C':
5469 rhaas@postgresql.org 1110 : 28 : success = listCasts(pattern, show_verbose);
8600 tgl@sss.pgh.pa.us 1111 : 28 : break;
9760 bruce@momjian.us 1112 : 52 : case 'd':
5957 tgl@sss.pgh.pa.us 1113 [ + + ]: 52 : if (strncmp(cmd, "ddp", 3) == 0)
6137 1114 : 24 : success = listDefaultACLs(pattern);
1115 : : else
1116 : 28 : success = objectDescription(pattern, show_system);
9760 bruce@momjian.us 1117 : 52 : break;
8600 tgl@sss.pgh.pa.us 1118 : 40 : case 'D':
5465 rhaas@postgresql.org 1119 : 40 : success = listDomains(pattern, show_verbose, show_system);
8600 tgl@sss.pgh.pa.us 1120 : 40 : break;
6304 bruce@momjian.us 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':
1935 tgl@sss.pgh.pa.us 1133 : 205 : success = exec_command_dfo(scan_state, cmd, pattern,
1134 : : show_verbose, show_system);
6304 bruce@momjian.us 1135 : 205 : break;
6304 bruce@momjian.us 1136 :UBC 0 : default:
1137 : 0 : status = PSQL_CMD_UNKNOWN;
1138 : 0 : break;
1139 : : }
9760 bruce@momjian.us 1140 :CBC 205 : break;
8272 1141 : 16 : case 'g':
1142 : : /* no longer distinct from \du */
3760 sfrost@snowman.net 1143 : 16 : success = describeRoles(pattern, show_verbose, show_system);
8272 bruce@momjian.us 1144 : 16 : break;
9760 1145 : 4 : case 'l':
1661 tgl@sss.pgh.pa.us 1146 : 4 : success = listLargeObjects(show_verbose);
9760 bruce@momjian.us 1147 : 4 : break;
5665 rhaas@postgresql.org 1148 : 20 : case 'L':
1149 : 20 : success = listLanguages(pattern, show_verbose, show_system);
1150 : 20 : break;
8600 tgl@sss.pgh.pa.us 1151 : 20 : case 'n':
5740 1152 : 20 : success = listSchemas(pattern, show_verbose, show_system);
8600 1153 : 20 : break;
9760 bruce@momjian.us 1154 : 44 : case 'o':
1935 tgl@sss.pgh.pa.us 1155 : 44 : success = exec_command_dfo(scan_state, cmd, pattern,
1156 : : show_verbose, show_system);
9760 bruce@momjian.us 1157 : 44 : break;
5642 peter_e@gmx.net 1158 : 32 : case 'O':
1159 : 32 : success = listCollations(pattern, show_verbose, show_system);
1160 : 32 : break;
9760 bruce@momjian.us 1161 : 48 : case 'p':
1295 dean.a.rasheed@gmail 1162 : 48 : success = permissionsList(pattern, show_system);
9760 bruce@momjian.us 1163 : 48 : break;
2666 alvherre@alvh.no-ip. 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;
2666 alvherre@alvh.no-ip. 1176 :UBC 0 : default:
1177 : 0 : status = PSQL_CMD_UNKNOWN;
1178 : 0 : break;
1179 : : }
1180 : : }
2666 alvherre@alvh.no-ip. 1181 :CBC 72 : break;
9760 bruce@momjian.us 1182 : 47 : case 'T':
6409 1183 : 47 : success = describeTypes(pattern, show_verbose, show_system);
9760 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':
6409 1192 : 244 : success = listTables(&cmd[1], pattern, show_verbose, show_system);
9760 1193 : 244 : break;
6135 alvherre@alvh.no-ip. 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 : :
1500 peter@eisentraut.org 1204 : 17 : free(pattern2);
1205 : : }
1102 tgl@sss.pgh.pa.us 1206 [ + - ]: 4 : else if (cmd[2] == 'g')
1207 : 4 : success = describeRoleGrants(pattern, show_system);
1208 : : else
3404 tgl@sss.pgh.pa.us 1209 :UBC 0 : status = PSQL_CMD_UNKNOWN;
6135 alvherre@alvh.no-ip. 1210 :CBC 21 : break;
3474 peter_e@gmx.net 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;
3474 peter_e@gmx.net 1223 :UBC 0 : default:
1224 : 0 : status = PSQL_CMD_UNKNOWN;
1225 : : }
3474 peter_e@gmx.net 1226 :CBC 420 : break;
9208 bruce@momjian.us 1227 : 4 : case 'u':
3760 sfrost@snowman.net 1228 : 4 : success = describeRoles(pattern, show_verbose, show_system);
9039 bruce@momjian.us 1229 : 4 : break;
6913 tgl@sss.pgh.pa.us 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;
6913 tgl@sss.pgh.pa.us 1247 :UBC 0 : default:
1248 : 0 : status = PSQL_CMD_UNKNOWN;
1249 : 0 : break;
1250 : : }
6913 tgl@sss.pgh.pa.us 1251 :CBC 128 : break;
6427 peter_e@gmx.net 1252 : 206 : case 'e': /* SQL/MED subsystem */
6253 bruce@momjian.us 1253 [ + + + + : 206 : switch (cmd[2])
- ]
1254 : : {
6427 peter_e@gmx.net 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;
5684 rhaas@postgresql.org 1264 : 10 : case 't':
1265 : 10 : success = listForeignTables(pattern, show_verbose);
1266 : 10 : break;
6427 peter_e@gmx.net 1267 :UBC 0 : default:
1268 : 0 : status = PSQL_CMD_UNKNOWN;
1269 : 0 : break;
1270 : : }
6427 peter_e@gmx.net 1271 :CBC 206 : break;
5585 bruce@momjian.us 1272 : 32 : case 'x': /* Extensions */
5646 tgl@sss.pgh.pa.us 1273 [ + + ]: 32 : if (show_verbose)
1274 : 16 : success = listExtensionContents(pattern);
1275 : : else
1276 : 16 : success = listExtensions(pattern);
1277 : 32 : break;
2012 tomas.vondra@postgre 1278 : 68 : case 'X': /* Extended Statistics */
147 fujii@postgresql.org 1279 : 68 : success = listExtendedStats(pattern, show_verbose);
2012 tomas.vondra@postgre 1280 : 68 : break;
5120 rhaas@postgresql.org 1281 : 16 : case 'y': /* Event Triggers */
1282 : 16 : success = listEventTriggers(pattern, show_verbose);
1283 : 16 : break;
9760 bruce@momjian.us 1284 :UBC 0 : default:
7524 peter_e@gmx.net 1285 : 0 : status = PSQL_CMD_UNKNOWN;
1286 : : }
1287 : :
1288 : : /* Restore original expanded mode */
557 dean.a.rasheed@gmail 1289 :CBC 4765 : pset.popt.topt.expanded = save_expanded;
1290 : :
1500 peter@eisentraut.org 1291 : 4765 : free(pattern);
1292 : : }
1293 : : else
3404 tgl@sss.pgh.pa.us 1294 : 4 : ignore_slash_options(scan_state);
1295 : :
1296 [ + + ]: 4769 : if (!success)
1297 : 620 : status = PSQL_CMD_ERROR;
1298 : :
1299 : 4769 : return status;
1300 : : }
1301 : :
1302 : : /* \df and \do; messy enough to split out of exec_command_d */
1303 : : static bool
1935 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)
1935 tgl@sss.pgh.pa.us 1322 :UBC 0 : break; /* protect limited-size array */
1323 : : }
1324 : : }
1325 : :
1935 tgl@sss.pgh.pa.us 1326 [ + + ]:CBC 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
3404 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 : : {
9600 bruce@momjian.us 1353 [ # # ]:UBC 0 : if (!query_buf)
1354 : : {
2672 peter@eisentraut.org 1355 : 0 : pg_log_error("no query buffer");
7524 peter_e@gmx.net 1356 : 0 : status = PSQL_CMD_ERROR;
1357 : : }
1358 : : else
1359 : : {
1360 : : char *fname;
5826 tgl@sss.pgh.pa.us 1361 : 0 : char *ln = NULL;
1362 : 0 : int lineno = -1;
1363 : :
8192 1364 : 0 : fname = psql_scan_slash_option(scan_state,
1365 : : OT_NORMAL, NULL, true);
8016 1366 [ # # ]: 0 : if (fname)
1367 : : {
1368 : : /* try to get separate lineno arg */
5826 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 : : {
2672 peter@eisentraut.org 1388 : 0 : pg_log_error("invalid line number: %s", ln);
5826 tgl@sss.pgh.pa.us 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 : : {
542 1399 : 0 : canonicalize_path_enc(fname, pset.encoding);
1400 : : /* Always clear buffer if the file isn't modified */
1939 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))
5826 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 : : */
1039 michael@paquier.xyz 1424 [ # # ]: 0 : if (status == PSQL_CMD_ERROR)
1425 : 0 : resetPQExpBuffer(query_buf);
1426 : :
1500 peter@eisentraut.org 1427 : 0 : free(fname);
1428 : 0 : free(ln);
1429 : : }
1430 : : }
1431 : : else
3404 tgl@sss.pgh.pa.us 1432 :CBC 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
3244 1442 : 8 : exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
1443 : : PQExpBuffer query_buf, bool is_func)
1444 : : {
3404 1445 : 8 : backslashResult status = PSQL_CMD_SKIP_LINE;
1446 : :
1447 [ - + ]: 8 : if (active_branch)
1448 : : {
3244 tgl@sss.pgh.pa.us 1449 :UBC 0 : char *obj_desc = psql_scan_slash_option(scan_state,
1450 : : OT_WHOLE_LINE,
1451 : : NULL, true);
5826 1452 : 0 : int lineno = -1;
1453 : :
1682 1454 [ # # ]: 0 : if (!query_buf)
1455 : : {
2672 peter@eisentraut.org 1456 : 0 : pg_log_error("no query buffer");
6531 tgl@sss.pgh.pa.us 1457 : 0 : status = PSQL_CMD_ERROR;
1458 : : }
1459 : : else
1460 : : {
3244 1461 : 0 : Oid obj_oid = InvalidOid;
1462 : 0 : EditableObjectType eot = is_func ? EditableFunction : EditableView;
1463 : :
1464 : 0 : lineno = strip_lineno_from_objdesc(obj_desc);
5826 1465 [ # # ]: 0 : if (lineno == 0)
1466 : : {
1467 : : /* error already reported */
1468 : 0 : status = PSQL_CMD_ERROR;
1469 : : }
3244 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 */
6531 1491 : 0 : status = PSQL_CMD_ERROR;
1492 : : }
3244 1493 [ # # ]: 0 : else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1494 : : {
1495 : : /* error already reported */
6531 1496 : 0 : status = PSQL_CMD_ERROR;
1497 : : }
3244 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 : : */
5826 1509 : 0 : const char *lines = query_buf->data;
1510 : :
1511 [ # # ]: 0 : while (*lines != '\0')
1512 : : {
1331 1513 [ # # ]: 0 : if (strncmp(lines, "AS ", 3) == 0 ||
1514 [ # # ]: 0 : strncmp(lines, "BEGIN ", 6) == 0 ||
1515 [ # # ]: 0 : strncmp(lines, "RETURN ", 7) == 0)
1516 : : break;
5826 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 : :
6531 1527 [ # # ]: 0 : if (status != PSQL_CMD_ERROR)
1528 : : {
6253 bruce@momjian.us 1529 : 0 : bool edited = false;
1530 : :
1939 tgl@sss.pgh.pa.us 1531 [ # # ]: 0 : if (!do_edit(NULL, query_buf, lineno, true, &edited))
6531 1532 : 0 : status = PSQL_CMD_ERROR;
1533 [ # # ]: 0 : else if (!edited)
6331 peter_e@gmx.net 1534 : 0 : puts(_("No changes"));
1535 : : else
6531 tgl@sss.pgh.pa.us 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 : : */
1039 michael@paquier.xyz 1543 [ # # ]: 0 : if (status == PSQL_CMD_ERROR)
1544 : 0 : resetPQExpBuffer(query_buf);
1545 : :
1500 peter@eisentraut.org 1546 : 0 : free(obj_desc);
1547 : : }
1548 : : else
3404 tgl@sss.pgh.pa.us 1549 :CBC 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 : 20565 : exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
1559 : : {
1560 [ + + ]: 20565 : if (active_branch)
1561 : : {
1562 : : char *value;
1563 : : char quoted;
9600 bruce@momjian.us 1564 : 20469 : bool no_newline = false;
1565 : 20469 : bool first = true;
1566 : : FILE *fout;
1567 : :
1568 [ + + ]: 20469 : if (strcmp(cmd, "qecho") == 0)
1569 : 20 : fout = pset.queryFout;
2577 tgl@sss.pgh.pa.us 1570 [ + + ]: 20449 : else if (strcmp(cmd, "warn") == 0)
1571 : 9978 : fout = stderr;
1572 : : else
9600 bruce@momjian.us 1573 : 10471 : fout = stdout;
1574 : :
8192 tgl@sss.pgh.pa.us 1575 [ + + ]: 41248 : while ((value = psql_scan_slash_option(scan_state,
1576 : : OT_NORMAL, "ed, false)))
1577 : : {
2577 1578 [ + + + + : 20779 : if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
+ + + + ]
9600 bruce@momjian.us 1579 : 4 : no_newline = true;
1580 : : else
1581 : : {
1582 [ + + ]: 20775 : if (first)
1583 : 20469 : first = false;
1584 : : else
1585 : 306 : fputc(' ', fout);
1586 : 20775 : fputs(value, fout);
1587 : : }
1588 : 20779 : free(value);
1589 : : }
1590 [ + + ]: 20469 : if (!no_newline)
1591 : 20465 : fputs("\n", fout);
1592 : : }
1593 : : else
3404 tgl@sss.pgh.pa.us 1594 : 96 : ignore_slash_options(scan_state);
1595 : :
1596 : 20565 : 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 : : {
8192 1607 : 8 : char *encoding = psql_scan_slash_option(scan_state,
1608 : : OT_NORMAL, NULL, false);
1609 : :
9600 bruce@momjian.us 1610 [ - + ]: 8 : if (!encoding)
1611 : : {
1612 : : /* show encoding */
9651 ishii@postgresql.org 1613 :UBC 0 : puts(pg_encoding_to_char(pset.encoding));
1614 : : }
1615 : : else
1616 : : {
1617 : : /* set encoding */
9651 ishii@postgresql.org 1618 [ - + ]:CBC 8 : if (PQsetClientEncoding(pset.db, encoding) == -1)
2672 peter@eisentraut.org 1619 :UBC 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 */
9651 ishii@postgresql.org 1623 :CBC 8 : pset.encoding = PQclientEncoding(pset.db);
8428 tgl@sss.pgh.pa.us 1624 : 8 : pset.popt.topt.encoding = pset.encoding;
530 andres@anarazel.de 1625 : 8 : setFmtEncoding(pset.encoding);
8428 tgl@sss.pgh.pa.us 1626 : 8 : SetVariable(pset.vars, "ENCODING",
1627 : : pg_encoding_to_char(pset.encoding));
1628 : : }
9600 bruce@momjian.us 1629 : 8 : free(encoding);
1630 : : }
1631 : : }
1632 : : else
3404 tgl@sss.pgh.pa.us 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 : : {
3765 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 : : {
2672 peter@eisentraut.org 1655 : 3 : pg_log_error("%s", msg);
3765 tgl@sss.pgh.pa.us 1656 : 3 : PQfreemem(msg);
1657 : : }
1658 : : else
3765 tgl@sss.pgh.pa.us 1659 :UBC 0 : puts(_("out of memory"));
1660 : : }
1661 : : else
3717 peter_e@gmx.net 1662 :CBC 1 : puts(_("There is no previous error."));
1663 : : }
1664 : :
3404 tgl@sss.pgh.pa.us 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 : : {
3404 tgl@sss.pgh.pa.us 1678 :UBC 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);
9600 bruce@momjian.us 1682 : 0 : free(fname);
1683 : : }
1684 : : else
3404 tgl@sss.pgh.pa.us 1685 :CBC 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
519 michael@paquier.xyz 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
3404 tgl@sss.pgh.pa.us 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 : : */
2300 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 : : {
494 michael@paquier.xyz 1763 [ + + ]: 286 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1764 : : {
1765 : 24 : pg_log_error("\\%s not allowed in pipeline mode", cmd);
519 1766 : 24 : clean_extended_state();
507 1767 : 24 : free(fname);
519 1768 : 24 : return PSQL_CMD_ERROR;
1769 : : }
1770 : :
9665 peter_e@gmx.net 1771 [ + + ]: 262 : if (!fname)
9689 1772 : 242 : pset.gfname = NULL;
1773 : : else
1774 : : {
8233 bruce@momjian.us 1775 : 20 : expand_tilde(&fname);
8217 neilc@samurai.com 1776 : 20 : pset.gfname = pg_strdup(fname);
1777 : : }
3427 sfrost@snowman.net 1778 [ + + ]: 262 : if (strcmp(cmd, "gx") == 0)
1779 : : {
1780 : : /* save settings if not done already, then force expanded=on */
2300 tgl@sss.pgh.pa.us 1781 [ + + ]: 86 : if (pset.gsavepopt == NULL)
1782 : 82 : pset.gsavepopt = savePsetInfo(&pset.popt);
1783 : 86 : pset.popt.topt.expanded = 1;
1784 : : }
7524 peter_e@gmx.net 1785 : 262 : status = PSQL_CMD_SEND;
1786 : : }
1787 : :
2300 tgl@sss.pgh.pa.us 1788 : 278 : free(fname);
1789 : :
3404 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
2300 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 : : {
2300 tgl@sss.pgh.pa.us 1819 [ # # ]:UBC 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 */
2300 tgl@sss.pgh.pa.us 1829 :CBC 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 : : {
2300 tgl@sss.pgh.pa.us 1863 :UBC 0 : restorePsetInfo(&pset.popt, pset.gsavepopt);
1864 : 0 : pset.gsavepopt = NULL;
1865 : : }
1866 : :
2300 tgl@sss.pgh.pa.us 1867 [ + - ]:CBC 16 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1868 : : }
1869 : :
1870 : : /*
1871 : : * \gdesc -- describe query result
1872 : : */
1873 : : static backslashResult
3245 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
1678 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 : : {
1678 tgl@sss.pgh.pa.us 1905 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
1906 : 0 : success = false;
1907 : : }
1908 : : else
1909 : : {
1678 tgl@sss.pgh.pa.us 1910 :CBC 227 : char *envval = getenv(envvar);
1911 : :
1912 [ + + - + ]: 227 : if (envval && !SetVariable(pset.vars, myvar, envval))
1678 tgl@sss.pgh.pa.us 1913 :UBC 0 : success = false;
1914 : : }
1678 tgl@sss.pgh.pa.us 1915 :CBC 227 : free(myvar);
1916 : 227 : free(envvar);
1917 : : }
1918 : : else
1678 tgl@sss.pgh.pa.us 1919 :UBC 0 : ignore_slash_options(scan_state);
1920 : :
1678 tgl@sss.pgh.pa.us 1921 [ + - ]:CBC 227 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1922 : : }
1923 : :
1924 : : /*
1925 : : * \getresults -- read results
1926 : : */
1927 : : static backslashResult
519 michael@paquier.xyz 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");
461 1948 : 4 : return PSQL_CMD_ERROR;
1949 : : }
519 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
3404 tgl@sss.pgh.pa.us 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 : : {
519 michael@paquier.xyz 1970 [ + + ]: 33 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1971 : : {
404 peter@eisentraut.org 1972 : 4 : pg_log_error("\\%s not allowed in pipeline mode", "gexec");
519 michael@paquier.xyz 1973 : 4 : clean_extended_state();
1974 : 4 : return PSQL_CMD_ERROR;
1975 : : }
3764 tgl@sss.pgh.pa.us 1976 : 29 : pset.gexec_flag = true;
1977 : 29 : status = PSQL_CMD_SEND;
1978 : : }
1979 : :
3404 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 : : {
4921 1993 : 595 : char *prefix = psql_scan_slash_option(scan_state,
1994 : : OT_NORMAL, NULL, false);
1995 : :
519 michael@paquier.xyz 1996 [ + + ]: 595 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1997 : : {
404 peter@eisentraut.org 1998 : 8 : pg_log_error("\\%s not allowed in pipeline mode", "gset");
519 michael@paquier.xyz 1999 : 8 : clean_extended_state();
2000 : 8 : return PSQL_CMD_ERROR;
2001 : : }
2002 : :
4921 tgl@sss.pgh.pa.us 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
3404 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 : : {
8192 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
3404 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 : : {
9689 peter_e@gmx.net 2049 [ # # ]:UBC 0 : if (pset.popt.topt.format != PRINT_HTML)
7270 tgl@sss.pgh.pa.us 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 : :
3404 tgl@sss.pgh.pa.us 2055 [ + - ]:CBC 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 : : {
8192 tgl@sss.pgh.pa.us 2068 :UBC 0 : char *fname = psql_scan_slash_option(scan_state,
2069 : : OT_NORMAL, NULL, true);
2070 : :
9665 peter_e@gmx.net 2071 [ # # ]: 0 : if (!fname)
2072 : : {
2672 peter@eisentraut.org 2073 : 0 : pg_log_error("\\%s: missing required argument", cmd);
9760 bruce@momjian.us 2074 : 0 : success = false;
2075 : : }
2076 : : else
2077 : : {
2078 : : bool include_relative;
2079 : :
5498 rhaas@postgresql.org 2080 : 0 : include_relative = (strcmp(cmd, "ir") == 0
2081 [ # # # # ]: 0 : || strcmp(cmd, "include_relative") == 0);
8233 bruce@momjian.us 2082 : 0 : expand_tilde(&fname);
3882 rhaas@postgresql.org 2083 : 0 : success = (process_file(fname, include_relative) == EXIT_SUCCESS);
9600 bruce@momjian.us 2084 : 0 : free(fname);
2085 : : }
2086 : : }
2087 : : else
3404 tgl@sss.pgh.pa.us 2088 :CBC 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 : 152 : exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
2104 : : PQExpBuffer query_buf)
2105 : : {
2106 [ + + ]: 152 : 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 : 148 : conditional_stack_push(cstack, IFSTATE_TRUE);
2115 : :
2116 : : /* Remember current query state in case we need to restore later */
2117 : 148 : 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 [ + + ]: 148 : if (!is_true_boolean_expression(scan_state, "\\if expression"))
2123 : 93 : 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 : 152 : 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:
2672 peter@eisentraut.org 2204 : 4 : pg_log_error("\\elif: cannot occur after \\else");
3404 tgl@sss.pgh.pa.us 2205 : 4 : success = false;
2206 : 4 : break;
2207 : 4 : case IFSTATE_NONE:
2208 : : /* no \if to elif from */
2672 peter@eisentraut.org 2209 : 4 : pg_log_error("\\elif: no matching \\if");
3404 tgl@sss.pgh.pa.us 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:
2672 peter@eisentraut.org 2273 : 4 : pg_log_error("\\else: cannot occur after \\else");
3404 tgl@sss.pgh.pa.us 2274 : 4 : success = false;
2275 : 4 : break;
2276 : 4 : case IFSTATE_NONE:
2277 : : /* no \if to else from */
2672 peter@eisentraut.org 2278 : 4 : pg_log_error("\\else: no matching \\if");
3404 tgl@sss.pgh.pa.us 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 : 141 : exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
2291 : : PQExpBuffer query_buf)
2292 : : {
2293 : 141 : bool success = true;
2294 : :
2295 [ + + + - ]: 141 : 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 [ - + ]: 32 : Assert(success);
2302 : 32 : break;
2303 : 105 : 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 : 105 : discard_query_text(scan_state, cstack, query_buf);
2311 : :
2312 : : /* Close the \if block */
2313 : 105 : success = conditional_stack_pop(cstack);
2314 [ - + ]: 105 : Assert(success);
2315 : 105 : break;
2316 : 4 : case IFSTATE_NONE:
2317 : : /* no \if to end */
2672 peter@eisentraut.org 2318 : 4 : pg_log_error("\\endif: no matching \\if");
3404 tgl@sss.pgh.pa.us 2319 : 4 : success = false;
2320 : 4 : break;
2321 : : }
2322 : :
2323 [ + + ]: 141 : 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 : :
4892 peter_e@gmx.net 2340 :UBC 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 */
557 dean.a.rasheed@gmail 2346 : 0 : save_expanded = pset.popt.topt.expanded;
2347 [ # # ]: 0 : if (strchr(cmd, 'x'))
2348 : 0 : pset.popt.topt.expanded = 1;
2349 : :
4892 peter_e@gmx.net 2350 : 0 : success = listAllDbs(pattern, show_verbose);
2351 : :
2352 : : /* restore original expanded mode */
557 dean.a.rasheed@gmail 2353 : 0 : pset.popt.topt.expanded = save_expanded;
2354 : :
1500 peter@eisentraut.org 2355 : 0 : free(pattern);
2356 : : }
2357 : : else
3404 tgl@sss.pgh.pa.us 2358 :CBC 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 : :
8192 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 : :
9760 bruce@momjian.us 2382 [ + + ]: 37 : if (strcmp(cmd + 3, "export") == 0)
2383 : : {
9665 peter_e@gmx.net 2384 [ - + ]: 4 : if (!opt2)
2385 : : {
2672 peter@eisentraut.org 2386 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
9760 bruce@momjian.us 2387 : 0 : success = false;
2388 : : }
2389 : : else
2390 : : {
8233 bruce@momjian.us 2391 :CBC 4 : expand_tilde(&opt2);
9665 peter_e@gmx.net 2392 : 4 : success = do_lo_export(opt1, opt2);
2393 : : }
2394 : : }
2395 : :
9760 bruce@momjian.us 2396 [ + + ]: 33 : else if (strcmp(cmd + 3, "import") == 0)
2397 : : {
9665 peter_e@gmx.net 2398 [ - + ]: 9 : if (!opt1)
2399 : : {
2672 peter@eisentraut.org 2400 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
9760 bruce@momjian.us 2401 : 0 : success = false;
2402 : : }
2403 : : else
2404 : : {
8233 bruce@momjian.us 2405 :CBC 9 : expand_tilde(&opt1);
9256 2406 : 9 : success = do_lo_import(opt1, opt2);
2407 : : }
2408 : : }
2409 : :
557 dean.a.rasheed@gmail 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'))
557 dean.a.rasheed@gmail 2420 :UBC 0 : pset.popt.topt.expanded = 1;
2421 : :
557 dean.a.rasheed@gmail 2422 :CBC 8 : success = listLargeObjects(show_verbose);
2423 : :
2424 : : /* restore original expanded mode */
2425 : 8 : pset.popt.topt.expanded = save_expanded;
2426 : : }
2427 : :
9760 bruce@momjian.us 2428 [ + - ]: 16 : else if (strcmp(cmd + 3, "unlink") == 0)
2429 : : {
9665 peter_e@gmx.net 2430 [ - + ]: 16 : if (!opt1)
2431 : : {
2672 peter@eisentraut.org 2432 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
9760 bruce@momjian.us 2433 : 0 : success = false;
2434 : : }
2435 : : else
9665 peter_e@gmx.net 2436 :CBC 16 : success = do_lo_unlink(opt1);
2437 : : }
2438 : :
2439 : : else
7524 peter_e@gmx.net 2440 :UBC 0 : status = PSQL_CMD_UNKNOWN;
2441 : :
9600 bruce@momjian.us 2442 :CBC 37 : free(opt1);
2443 : 37 : free(opt2);
2444 : : }
2445 : : else
3404 tgl@sss.pgh.pa.us 2446 : 4 : ignore_slash_options(scan_state);
2447 : :
2448 [ - + ]: 41 : if (!success)
3404 tgl@sss.pgh.pa.us 2449 :UBC 0 : status = PSQL_CMD_ERROR;
2450 : :
3404 tgl@sss.pgh.pa.us 2451 :CBC 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 : : {
8192 2464 : 24 : char *fname = psql_scan_slash_option(scan_state,
2465 : : OT_FILEPIPE, NULL, true);
2466 : :
8233 bruce@momjian.us 2467 : 24 : expand_tilde(&fname);
9665 peter_e@gmx.net 2468 : 24 : success = setQFout(fname);
9600 bruce@momjian.us 2469 : 24 : free(fname);
2470 : : }
2471 : : else
3404 tgl@sss.pgh.pa.us 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 : : */
9760 bruce@momjian.us 2491 [ + - + + ]: 24 : if (query_buf && query_buf->len > 0)
2492 : 12 : puts(query_buf->data);
3401 tgl@sss.pgh.pa.us 2493 [ + - + - ]: 12 : else if (previous_buf && previous_buf->len > 0)
2494 : 12 : puts(previous_buf->data);
7270 tgl@sss.pgh.pa.us 2495 [ # # ]:UBC 0 : else if (!pset.quiet)
7823 bruce@momjian.us 2496 : 0 : puts(_("Query buffer is empty."));
9724 JanWieck@Yahoo.com 2497 :CBC 24 : fflush(stdout);
2498 : : }
2499 : :
3404 tgl@sss.pgh.pa.us 2500 : 28 : return PSQL_CMD_SKIP_LINE;
2501 : : }
2502 : :
2503 : : /*
2504 : : * \parse -- parse query
2505 : : */
2506 : : static backslashResult
702 michael@paquier.xyz 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 : :
674 2517 : 71 : clean_extended_state();
2518 : :
702 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
3404 tgl@sss.pgh.pa.us 2541 : 5 : exec_command_password(PsqlScanState scan_state, bool active_branch)
2542 : : {
2543 : 5 : bool success = true;
2544 : :
2545 [ + + ]: 5 : if (active_branch)
2546 : : {
1716 2547 : 1 : char *user = psql_scan_slash_option(scan_state,
2548 : : OT_SQLID, NULL, true);
1711 2549 : 1 : char *pw1 = NULL;
2550 : 1 : char *pw2 = NULL;
2551 : : PQExpBufferData buf;
2552 : : PromptInterruptContext prompt_ctx;
2553 : :
1716 2554 [ - + ]: 1 : if (user == NULL)
2555 : : {
2556 : : /* By default, the command applies to CURRENT_USER */
2557 : : PGresult *res;
2558 : :
1716 tgl@sss.pgh.pa.us 2559 :UBC 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() */
1711 tgl@sss.pgh.pa.us 2568 :CBC 1 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2569 : 1 : prompt_ctx.enabled = &sigint_interrupt_enabled;
2570 : 1 : prompt_ctx.canceled = false;
2571 : :
1716 2572 : 1 : initPQExpBuffer(&buf);
2573 : 1 : printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2574 : :
1711 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 */
1711 tgl@sss.pgh.pa.us 2582 :UBC 0 : success = false;
2583 : : }
1711 tgl@sss.pgh.pa.us 2584 [ - + ]:CBC 1 : else if (strcmp(pw1, pw2) != 0)
2585 : : {
2672 peter@eisentraut.org 2586 :UBC 0 : pg_log_error("Passwords didn't match.");
7524 peter_e@gmx.net 2587 : 0 : success = false;
2588 : : }
2589 : : else
2590 : : {
928 mail@joeconway.com 2591 :CBC 1 : PGresult *res = PQchangePassword(pset.db, user, pw1);
2592 : :
2593 [ - + ]: 1 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
2594 : : {
2672 peter@eisentraut.org 2595 :UBC 0 : pg_log_info("%s", PQerrorMessage(pset.db));
7524 peter_e@gmx.net 2596 : 0 : success = false;
2597 : : }
2598 : :
928 mail@joeconway.com 2599 :CBC 1 : PQclear(res);
2600 : : }
2601 : :
24 peter@eisentraut.org 2602 :GNC 1 : pg_free(user);
1500 peter@eisentraut.org 2603 :CBC 1 : free(pw1);
2604 : 1 : free(pw2);
1716 tgl@sss.pgh.pa.us 2605 : 1 : termPQExpBuffer(&buf);
2606 : : }
2607 : : else
3404 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,
6827 bruce@momjian.us 2625 :UBC 0 : *prompt_text = NULL;
2626 : : char *arg1,
2627 : : *arg2;
2628 : :
7092 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 : : {
2672 peter@eisentraut.org 2634 : 0 : pg_log_error("\\%s: missing required argument", cmd);
7092 bruce@momjian.us 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() */
1709 tgl@sss.pgh.pa.us 2643 : 0 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2644 : 0 : prompt_ctx.enabled = &sigint_interrupt_enabled;
2645 : 0 : prompt_ctx.canceled = false;
2646 : :
7092 bruce@momjian.us 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 : : {
1709 tgl@sss.pgh.pa.us 2657 : 0 : result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2658 : : }
2659 : : else
2660 : : {
7092 bruce@momjian.us 2661 [ # # ]: 0 : if (prompt_text)
2662 : : {
2663 : 0 : fputs(prompt_text, stdout);
2664 : 0 : fflush(stdout);
2665 : : }
2666 : 0 : result = gets_fromFile(stdin);
3616 tgl@sss.pgh.pa.us 2667 [ # # ]: 0 : if (!result)
2668 : : {
2672 peter@eisentraut.org 2669 : 0 : pg_log_error("\\%s: could not read value for variable",
2670 : : cmd);
3616 tgl@sss.pgh.pa.us 2671 : 0 : success = false;
2672 : : }
2673 : : }
2674 : :
1709 2675 [ # # # # ]: 0 : if (prompt_ctx.canceled ||
2676 [ # # ]: 0 : (result && !SetVariable(pset.vars, opt, result)))
7092 bruce@momjian.us 2677 : 0 : success = false;
2678 : :
1500 peter@eisentraut.org 2679 : 0 : free(result);
2680 : 0 : free(prompt_text);
7092 bruce@momjian.us 2681 : 0 : free(opt);
2682 : : }
2683 : : }
2684 : : else
3404 tgl@sss.pgh.pa.us 2685 :CBC 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 : : {
8192 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 : :
9665 peter_e@gmx.net 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 : :
4640 2724 [ + + ]: 100 : for (i = 0; my_list[i] != NULL; i++)
2725 : : {
4081 bruce@momjian.us 2726 : 96 : char *val = pset_value_string(my_list[i], &pset.popt);
2727 : :
4298 peter_e@gmx.net 2728 : 96 : printf("%-24s %s\n", my_list[i], val);
2729 : 96 : free(val);
2730 : : }
2731 : :
4640 2732 : 4 : success = true;
2733 : : }
2734 : : else
7270 tgl@sss.pgh.pa.us 2735 : 1234 : success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2736 : :
9600 bruce@momjian.us 2737 : 1238 : free(opt0);
2738 : 1238 : free(opt1);
2739 : : }
2740 : : else
3404 tgl@sss.pgh.pa.us 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 : 278 : exec_command_quit(PsqlScanState scan_state, bool active_branch)
2751 : : {
2752 : 278 : backslashResult status = PSQL_CMD_SKIP_LINE;
2753 : :
2754 [ + + ]: 278 : if (active_branch)
7524 peter_e@gmx.net 2755 : 217 : status = PSQL_CMD_TERMINATE;
2756 : :
3404 tgl@sss.pgh.pa.us 2757 : 278 : 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 : : {
9760 bruce@momjian.us 2769 : 52 : resetPQExpBuffer(query_buf);
8192 tgl@sss.pgh.pa.us 2770 : 52 : psql_scan_reset(scan_state);
7270 2771 [ + + ]: 52 : if (!pset.quiet)
7823 bruce@momjian.us 2772 : 32 : puts(_("Query buffer reset (cleared)."));
2773 : : }
2774 : :
3404 tgl@sss.pgh.pa.us 2775 : 56 : return PSQL_CMD_SKIP_LINE;
2776 : : }
2777 : :
2778 : : /*
2779 : : * \restrict -- enter "restricted mode" with the provided key
2780 : : */
2781 : : static backslashResult
348 nathan@postgresql.or 2782 : 37 : exec_command_restrict(PsqlScanState scan_state, bool active_branch,
2783 : : const char *cmd)
2784 : : {
2785 [ + + ]: 37 : if (active_branch)
2786 : : {
2787 : : char *opt;
2788 : :
2789 [ - + ]: 33 : Assert(!restricted);
2790 : :
2791 : 33 : opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
2792 [ + - - + ]: 33 : if (opt == NULL || opt[0] == '\0')
2793 : : {
348 nathan@postgresql.or 2794 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
2795 : 0 : return PSQL_CMD_ERROR;
2796 : : }
2797 : :
348 nathan@postgresql.or 2798 :CBC 33 : restrict_key = pstrdup(opt);
2799 : 33 : restricted = true;
2800 : : }
2801 : : else
2802 : 4 : ignore_slash_options(scan_state);
2803 : :
2804 : 37 : return PSQL_CMD_SKIP_LINE;
2805 : : }
2806 : :
2807 : : /*
2808 : : * \s -- save history in a file or show it on the screen
2809 : : */
2810 : : static backslashResult
3404 tgl@sss.pgh.pa.us 2811 : 4 : exec_command_s(PsqlScanState scan_state, bool active_branch)
2812 : : {
2813 : 4 : bool success = true;
2814 : :
2815 [ - + ]: 4 : if (active_branch)
2816 : : {
8192 tgl@sss.pgh.pa.us 2817 :UBC 0 : char *fname = psql_scan_slash_option(scan_state,
2818 : : OT_NORMAL, NULL, true);
2819 : :
8233 bruce@momjian.us 2820 : 0 : expand_tilde(&fname);
4338 tgl@sss.pgh.pa.us 2821 : 0 : success = printHistory(fname, pset.popt.topt.pager);
7270 2822 [ # # # # : 0 : if (success && !pset.quiet && fname)
# # ]
4645 2823 : 0 : printf(_("Wrote history to file \"%s\".\n"), fname);
7907 bruce@momjian.us 2824 [ # # ]: 0 : if (!fname)
2825 : 0 : putchar('\n');
9600 2826 : 0 : free(fname);
2827 : : }
2828 : : else
3404 tgl@sss.pgh.pa.us 2829 :CBC 4 : ignore_slash_options(scan_state);
2830 : :
2831 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2832 : : }
2833 : :
2834 : : /*
2835 : : * \sendpipeline -- send an extended query to an ongoing pipeline
2836 : : */
2837 : : static backslashResult
494 michael@paquier.xyz 2838 : 481 : exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch)
2839 : : {
2840 : 481 : backslashResult status = PSQL_CMD_SKIP_LINE;
2841 : :
2842 [ + + ]: 481 : if (active_branch)
2843 : : {
2844 [ + + ]: 477 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
2845 : : {
2846 [ + + ]: 469 : if (pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PREPARED ||
2847 [ + + ]: 437 : pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PARAMS)
2848 : : {
2849 : 461 : status = PSQL_CMD_SEND;
2850 : : }
2851 : : else
2852 : : {
2853 : 8 : pg_log_error("\\sendpipeline must be used after \\bind or \\bind_named");
2854 : 8 : clean_extended_state();
2855 : 8 : return PSQL_CMD_ERROR;
2856 : : }
2857 : : }
2858 : : else
2859 : : {
2860 : 8 : pg_log_error("\\sendpipeline not allowed outside of pipeline mode");
2861 : 8 : clean_extended_state();
2862 : 8 : return PSQL_CMD_ERROR;
2863 : : }
2864 : : }
2865 : : else
2866 : 4 : ignore_slash_options(scan_state);
2867 : :
2868 : 465 : return status;
2869 : : }
2870 : :
2871 : : /*
2872 : : * \set -- set variable
2873 : : */
2874 : : static backslashResult
3404 tgl@sss.pgh.pa.us 2875 : 718 : exec_command_set(PsqlScanState scan_state, bool active_branch)
2876 : : {
2877 : 718 : bool success = true;
2878 : :
2879 [ + + ]: 718 : if (active_branch)
2880 : : {
8192 2881 : 714 : char *opt0 = psql_scan_slash_option(scan_state,
2882 : : OT_NORMAL, NULL, false);
2883 : :
9665 peter_e@gmx.net 2884 [ - + ]: 714 : if (!opt0)
2885 : : {
2886 : : /* list all variables */
8528 bruce@momjian.us 2887 :UBC 0 : PrintVariables(pset.vars);
9760 2888 : 0 : success = true;
2889 : : }
2890 : : else
2891 : : {
2892 : : /*
2893 : : * Set variable to the concatenation of the arguments.
2894 : : */
2895 : : char *newval;
2896 : : char *opt;
2897 : :
8192 tgl@sss.pgh.pa.us 2898 :CBC 714 : opt = psql_scan_slash_option(scan_state,
2899 : : OT_NORMAL, NULL, false);
8217 neilc@samurai.com 2900 [ + + ]: 714 : newval = pg_strdup(opt ? opt : "");
9600 bruce@momjian.us 2901 : 714 : free(opt);
2902 : :
8192 tgl@sss.pgh.pa.us 2903 [ + + ]: 1064 : while ((opt = psql_scan_slash_option(scan_state,
2904 : : OT_NORMAL, NULL, false)))
2905 : : {
4267 2906 : 350 : newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
9600 bruce@momjian.us 2907 : 350 : strcat(newval, opt);
2908 : 350 : free(opt);
2909 : : }
2910 : :
7270 tgl@sss.pgh.pa.us 2911 [ + + ]: 714 : if (!SetVariable(pset.vars, opt0, newval))
9760 bruce@momjian.us 2912 : 17 : success = false;
2913 : :
24 peter@eisentraut.org 2914 :GNC 714 : pg_free(newval);
2915 : : }
9600 bruce@momjian.us 2916 :CBC 714 : free(opt0);
2917 : : }
2918 : : else
3404 tgl@sss.pgh.pa.us 2919 : 4 : ignore_slash_options(scan_state);
2920 : :
2921 [ + + ]: 718 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2922 : : }
2923 : :
2924 : : /*
2925 : : * \setenv -- set environment variable
2926 : : */
2927 : : static backslashResult
2928 : 12 : exec_command_setenv(PsqlScanState scan_state, bool active_branch,
2929 : : const char *cmd)
2930 : : {
2931 : 12 : bool success = true;
2932 : :
2933 [ + + ]: 12 : if (active_branch)
2934 : : {
5347 andrew@dunslane.net 2935 : 8 : char *envvar = psql_scan_slash_option(scan_state,
2936 : : OT_NORMAL, NULL, false);
2937 : 8 : char *envval = psql_scan_slash_option(scan_state,
2938 : : OT_NORMAL, NULL, false);
2939 : :
2940 [ - + ]: 8 : if (!envvar)
2941 : : {
2672 peter@eisentraut.org 2942 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
5347 andrew@dunslane.net 2943 : 0 : success = false;
2944 : : }
5158 bruce@momjian.us 2945 [ - + ]:CBC 8 : else if (strchr(envvar, '=') != NULL)
2946 : : {
2672 peter@eisentraut.org 2947 :UBC 0 : pg_log_error("\\%s: environment variable name must not contain \"=\"",
2948 : : cmd);
5347 andrew@dunslane.net 2949 : 0 : success = false;
2950 : : }
5347 andrew@dunslane.net 2951 [ + + ]:CBC 8 : else if (!envval)
2952 : : {
2953 : : /* No argument - unset the environment variable */
2954 : 4 : unsetenv(envvar);
2955 : 4 : success = true;
2956 : : }
2957 : : else
2958 : : {
2959 : : /* Set variable to the value of the next argument */
2033 tgl@sss.pgh.pa.us 2960 : 4 : setenv(envvar, envval, 1);
5347 andrew@dunslane.net 2961 : 4 : success = true;
2962 : : }
2963 : 8 : free(envvar);
2964 : 8 : free(envval);
2965 : : }
2966 : : else
3404 tgl@sss.pgh.pa.us 2967 : 4 : ignore_slash_options(scan_state);
2968 : :
2969 [ + - ]: 12 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2970 : : }
2971 : :
2972 : : /*
2973 : : * \sf/\sv -- show a function/view's source code
2974 : : */
2975 : : static backslashResult
3244 2976 : 170 : exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
2977 : : const char *cmd, bool is_func)
2978 : : {
3404 2979 : 170 : backslashResult status = PSQL_CMD_SKIP_LINE;
2980 : :
2981 [ + + ]: 170 : if (active_branch)
2982 : : {
3244 2983 : 162 : bool show_linenumbers = (strchr(cmd, '+') != NULL);
2984 : : PQExpBuffer buf;
2985 : : char *obj_desc;
2986 : 162 : Oid obj_oid = InvalidOid;
2987 : 162 : EditableObjectType eot = is_func ? EditableFunction : EditableView;
2988 : :
2989 : 162 : buf = createPQExpBuffer();
2990 : 162 : obj_desc = psql_scan_slash_option(scan_state,
2991 : : OT_WHOLE_LINE, NULL, true);
1682 2992 [ - + ]: 162 : if (!obj_desc)
2993 : : {
3244 tgl@sss.pgh.pa.us 2994 [ # # ]:UBC 0 : if (is_func)
2672 peter@eisentraut.org 2995 : 0 : pg_log_error("function name is required");
2996 : : else
2997 : 0 : pg_log_error("view name is required");
5824 tgl@sss.pgh.pa.us 2998 : 0 : status = PSQL_CMD_ERROR;
2999 : : }
3244 tgl@sss.pgh.pa.us 3000 [ - + ]:CBC 162 : else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
3001 : : {
3002 : : /* error already reported */
5824 tgl@sss.pgh.pa.us 3003 :UBC 0 : status = PSQL_CMD_ERROR;
3004 : : }
3244 tgl@sss.pgh.pa.us 3005 [ - + ]:CBC 162 : else if (!get_create_object_cmd(eot, obj_oid, buf))
3006 : : {
3007 : : /* error already reported */
5824 tgl@sss.pgh.pa.us 3008 :UBC 0 : status = PSQL_CMD_ERROR;
3009 : : }
3010 : : else
3011 : : {
3012 : : FILE *output;
3013 : : bool is_pager;
3014 : :
3015 : : /* Select output stream: stdout, pager, or file */
5824 tgl@sss.pgh.pa.us 3016 [ + - ]:CBC 162 : if (pset.queryFout == stdout)
3017 : : {
3018 : : /* count lines in function to see if pager is needed */
3244 3019 : 162 : int lineno = count_lines_in_buf(buf);
3020 : :
4137 andrew@dunslane.net 3021 : 162 : output = PageOutput(lineno, &(pset.popt.topt));
5824 tgl@sss.pgh.pa.us 3022 : 162 : is_pager = true;
3023 : : }
3024 : : else
3025 : : {
3026 : : /* use previously set output file, without pager */
5824 tgl@sss.pgh.pa.us 3027 :UBC 0 : output = pset.queryFout;
3028 : 0 : is_pager = false;
3029 : : }
3030 : :
5824 tgl@sss.pgh.pa.us 3031 [ + + ]:CBC 162 : if (show_linenumbers)
3032 : : {
3033 : : /* add line numbers */
1331 3034 : 28 : print_with_linenumbers(output, buf->data, is_func);
3035 : : }
3036 : : else
3037 : : {
3038 : : /* just send the definition to output */
3244 3039 : 134 : fputs(buf->data, output);
3040 : : }
3041 : :
4040 3042 [ + - ]: 162 : if (is_pager)
3043 : 162 : ClosePager(output);
3044 : : }
3045 : :
1500 peter@eisentraut.org 3046 : 162 : free(obj_desc);
3244 tgl@sss.pgh.pa.us 3047 : 162 : destroyPQExpBuffer(buf);
3048 : : }
3049 : : else
3404 3050 : 8 : ignore_slash_whole_line(scan_state);
3051 : :
3052 : 170 : return status;
3053 : : }
3054 : :
3055 : : /*
3056 : : * \startpipeline -- enter pipeline mode
3057 : : */
3058 : : static backslashResult
519 michael@paquier.xyz 3059 : 225 : exec_command_startpipeline(PsqlScanState scan_state, bool active_branch)
3060 : : {
3061 : 225 : backslashResult status = PSQL_CMD_SKIP_LINE;
3062 : :
3063 [ + + ]: 225 : if (active_branch)
3064 : : {
3065 : 221 : pset.send_mode = PSQL_SEND_START_PIPELINE_MODE;
3066 : 221 : status = PSQL_CMD_SEND;
3067 : : }
3068 : : else
3069 : 4 : ignore_slash_options(scan_state);
3070 : :
3071 : 225 : return status;
3072 : : }
3073 : :
3074 : : /*
3075 : : * \syncpipeline -- send a sync message to an active pipeline
3076 : : */
3077 : : static backslashResult
3078 : 99 : exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch)
3079 : : {
3080 : 99 : backslashResult status = PSQL_CMD_SKIP_LINE;
3081 : :
3082 [ + + ]: 99 : if (active_branch)
3083 : : {
3084 : 95 : pset.send_mode = PSQL_SEND_PIPELINE_SYNC;
3085 : 95 : status = PSQL_CMD_SEND;
3086 : : }
3087 : : else
3088 : 4 : ignore_slash_options(scan_state);
3089 : :
3090 : 99 : return status;
3091 : : }
3092 : :
3093 : : /*
3094 : : * \endpipeline -- end pipeline mode
3095 : : */
3096 : : static backslashResult
3097 : 225 : exec_command_endpipeline(PsqlScanState scan_state, bool active_branch)
3098 : : {
3099 : 225 : backslashResult status = PSQL_CMD_SKIP_LINE;
3100 : :
3101 [ + + ]: 225 : if (active_branch)
3102 : : {
3103 : 221 : pset.send_mode = PSQL_SEND_END_PIPELINE_MODE;
3104 : 221 : status = PSQL_CMD_SEND;
3105 : : }
3106 : : else
3107 : 4 : ignore_slash_options(scan_state);
3108 : :
3109 : 225 : return status;
3110 : : }
3111 : :
3112 : : /*
3113 : : * \t -- turn off table headers and row count
3114 : : */
3115 : : static backslashResult
3404 tgl@sss.pgh.pa.us 3116 : 52 : exec_command_t(PsqlScanState scan_state, bool active_branch)
3117 : : {
3118 : 52 : bool success = true;
3119 : :
3120 [ + + ]: 52 : if (active_branch)
3121 : : {
7084 bruce@momjian.us 3122 : 48 : char *opt = psql_scan_slash_option(scan_state,
3123 : : OT_NORMAL, NULL, true);
3124 : :
3125 : 48 : success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
3126 : 48 : free(opt);
3127 : : }
3128 : : else
3404 tgl@sss.pgh.pa.us 3129 : 4 : ignore_slash_options(scan_state);
3130 : :
3131 [ + - ]: 52 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3132 : : }
3133 : :
3134 : : /*
3135 : : * \T -- define html <table ...> attributes
3136 : : */
3137 : : static backslashResult
3138 : 4 : exec_command_T(PsqlScanState scan_state, bool active_branch)
3139 : : {
3140 : 4 : bool success = true;
3141 : :
3142 [ - + ]: 4 : if (active_branch)
3143 : : {
8192 tgl@sss.pgh.pa.us 3144 :UBC 0 : char *value = psql_scan_slash_option(scan_state,
3145 : : OT_NORMAL, NULL, false);
3146 : :
7270 3147 : 0 : success = do_pset("tableattr", value, &pset.popt, pset.quiet);
9600 bruce@momjian.us 3148 : 0 : free(value);
3149 : : }
3150 : : else
3404 tgl@sss.pgh.pa.us 3151 :CBC 4 : ignore_slash_options(scan_state);
3152 : :
3153 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3154 : : }
3155 : :
3156 : : /*
3157 : : * \timing -- enable/disable timing of queries
3158 : : */
3159 : : static backslashResult
3160 : 6 : exec_command_timing(PsqlScanState scan_state, bool active_branch)
3161 : : {
3162 : 6 : bool success = true;
3163 : :
3164 [ + + ]: 6 : if (active_branch)
3165 : : {
6618 heikki.linnakangas@i 3166 : 2 : char *opt = psql_scan_slash_option(scan_state,
3167 : : OT_NORMAL, NULL, false);
3168 : :
3169 [ + - ]: 2 : if (opt)
3463 tgl@sss.pgh.pa.us 3170 : 2 : success = ParseVariableBool(opt, "\\timing", &pset.timing);
3171 : : else
6618 heikki.linnakangas@i 3172 :UBC 0 : pset.timing = !pset.timing;
7270 tgl@sss.pgh.pa.us 3173 [ - + ]:CBC 2 : if (!pset.quiet)
3174 : : {
8908 bruce@momjian.us 3175 [ # # ]:UBC 0 : if (pset.timing)
7823 3176 : 0 : puts(_("Timing is on."));
3177 : : else
3178 : 0 : puts(_("Timing is off."));
3179 : : }
6618 heikki.linnakangas@i 3180 :CBC 2 : free(opt);
3181 : : }
3182 : : else
3404 tgl@sss.pgh.pa.us 3183 : 4 : ignore_slash_options(scan_state);
3184 : :
3185 [ + - ]: 6 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3186 : : }
3187 : :
3188 : : /*
3189 : : * \unrestrict -- exit "restricted mode" if provided key matches
3190 : : */
3191 : : static backslashResult
348 nathan@postgresql.or 3192 : 36 : exec_command_unrestrict(PsqlScanState scan_state, bool active_branch,
3193 : : const char *cmd)
3194 : : {
3195 [ + + ]: 36 : if (active_branch)
3196 : : {
3197 : : char *opt;
3198 : :
3199 : 32 : opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
3200 [ + - - + ]: 32 : if (opt == NULL || opt[0] == '\0')
3201 : : {
348 nathan@postgresql.or 3202 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
3203 : 0 : return PSQL_CMD_ERROR;
3204 : : }
3205 : :
348 nathan@postgresql.or 3206 [ - + ]:CBC 32 : if (!restricted)
3207 : : {
348 nathan@postgresql.or 3208 :UBC 0 : pg_log_error("\\%s: not currently in restricted mode", cmd);
3209 : 0 : return PSQL_CMD_ERROR;
3210 : : }
348 nathan@postgresql.or 3211 [ + - ]:CBC 32 : else if (strcmp(opt, restrict_key) == 0)
3212 : : {
3213 : 32 : pfree(restrict_key);
3214 : 32 : restricted = false;
3215 : : }
3216 : : else
3217 : : {
348 nathan@postgresql.or 3218 :UBC 0 : pg_log_error("\\%s: wrong key", cmd);
3219 : 0 : return PSQL_CMD_ERROR;
3220 : : }
3221 : : }
3222 : : else
348 nathan@postgresql.or 3223 :CBC 4 : ignore_slash_options(scan_state);
3224 : :
3225 : 36 : return PSQL_CMD_SKIP_LINE;
3226 : : }
3227 : :
3228 : : /*
3229 : : * \unset -- unset variable
3230 : : */
3231 : : static backslashResult
3404 tgl@sss.pgh.pa.us 3232 : 34 : exec_command_unset(PsqlScanState scan_state, bool active_branch,
3233 : : const char *cmd)
3234 : : {
3235 : 34 : bool success = true;
3236 : :
3237 [ + + ]: 34 : if (active_branch)
3238 : : {
8192 3239 : 30 : char *opt = psql_scan_slash_option(scan_state,
3240 : : OT_NORMAL, NULL, false);
3241 : :
9600 bruce@momjian.us 3242 [ - + ]: 30 : if (!opt)
3243 : : {
2672 peter@eisentraut.org 3244 :UBC 0 : pg_log_error("\\%s: missing required argument", cmd);
9600 bruce@momjian.us 3245 : 0 : success = false;
3246 : : }
8954 tgl@sss.pgh.pa.us 3247 [ - + ]:CBC 30 : else if (!SetVariable(pset.vars, opt, NULL))
9600 bruce@momjian.us 3248 :UBC 0 : success = false;
3249 : :
9600 bruce@momjian.us 3250 :CBC 30 : free(opt);
3251 : : }
3252 : : else
3404 tgl@sss.pgh.pa.us 3253 : 4 : ignore_slash_options(scan_state);
3254 : :
3255 [ + - ]: 34 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3256 : : }
3257 : :
3258 : : /*
3259 : : * \w -- write query buffer to file
3260 : : */
3261 : : static backslashResult
3262 : 8 : exec_command_write(PsqlScanState scan_state, bool active_branch,
3263 : : const char *cmd,
3264 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
3265 : : {
3266 : 8 : backslashResult status = PSQL_CMD_SKIP_LINE;
3267 : :
3268 [ - + ]: 8 : if (active_branch)
3269 : : {
3404 tgl@sss.pgh.pa.us 3270 :UBC 0 : char *fname = psql_scan_slash_option(scan_state,
3271 : : OT_FILEPIPE, NULL, true);
9760 bruce@momjian.us 3272 : 0 : FILE *fd = NULL;
9665 peter_e@gmx.net 3273 : 0 : bool is_pipe = false;
3274 : :
9600 bruce@momjian.us 3275 [ # # ]: 0 : if (!query_buf)
3276 : : {
2672 peter@eisentraut.org 3277 : 0 : pg_log_error("no query buffer");
7524 peter_e@gmx.net 3278 : 0 : status = PSQL_CMD_ERROR;
3279 : : }
3280 : : else
3281 : : {
9600 bruce@momjian.us 3282 [ # # ]: 0 : if (!fname)
3283 : : {
2672 peter@eisentraut.org 3284 : 0 : pg_log_error("\\%s: missing required argument", cmd);
3404 tgl@sss.pgh.pa.us 3285 : 0 : status = PSQL_CMD_ERROR;
3286 : : }
3287 : : else
3288 : : {
3289 : 0 : expand_tilde(&fname);
9600 bruce@momjian.us 3290 [ # # ]: 0 : if (fname[0] == '|')
3291 : : {
3292 : 0 : is_pipe = true;
1426 tgl@sss.pgh.pa.us 3293 : 0 : fflush(NULL);
3887 3294 : 0 : disable_sigpipe_trap();
9600 bruce@momjian.us 3295 : 0 : fd = popen(&fname[1], "w");
3296 : : }
3297 : : else
3298 : : {
542 tgl@sss.pgh.pa.us 3299 : 0 : canonicalize_path_enc(fname, pset.encoding);
9600 bruce@momjian.us 3300 : 0 : fd = fopen(fname, "w");
3301 : : }
3302 [ # # ]: 0 : if (!fd)
3303 : : {
2672 peter@eisentraut.org 3304 : 0 : pg_log_error("%s: %m", fname);
3404 tgl@sss.pgh.pa.us 3305 : 0 : status = PSQL_CMD_ERROR;
3306 : : }
3307 : : }
3308 : : }
3309 : :
9760 bruce@momjian.us 3310 [ # # ]: 0 : if (fd)
3311 : : {
3312 : : int result;
3313 : :
3314 : : /*
3315 : : * We want to print the same thing \g would execute, but not to
3316 : : * change the query buffer state; so we can't use
3317 : : * copy_previous_query(). Also, beware of possibility that buffer
3318 : : * pointers are NULL.
3319 : : */
3320 [ # # # # ]: 0 : if (query_buf && query_buf->len > 0)
3321 : 0 : fprintf(fd, "%s\n", query_buf->data);
3404 tgl@sss.pgh.pa.us 3322 [ # # # # ]: 0 : else if (previous_buf && previous_buf->len > 0)
3323 : 0 : fprintf(fd, "%s\n", previous_buf->data);
3324 : :
9665 peter_e@gmx.net 3325 [ # # ]: 0 : if (is_pipe)
3326 : : {
9760 bruce@momjian.us 3327 : 0 : result = pclose(fd);
3328 : :
1348 peter@eisentraut.org 3329 [ # # ]: 0 : if (result != 0)
3330 : : {
3331 : 0 : pg_log_error("%s: %s", fname, wait_result_to_str(result));
3332 : 0 : status = PSQL_CMD_ERROR;
3333 : : }
1206 tgl@sss.pgh.pa.us 3334 : 0 : SetShellResultVariables(result);
3335 : : }
3336 : : else
3337 : : {
9760 bruce@momjian.us 3338 : 0 : result = fclose(fd);
3339 : :
1348 peter@eisentraut.org 3340 [ # # ]: 0 : if (result == EOF)
3341 : : {
3342 : 0 : pg_log_error("%s: %m", fname);
3343 : 0 : status = PSQL_CMD_ERROR;
3344 : : }
3345 : : }
3346 : : }
3347 : :
3887 tgl@sss.pgh.pa.us 3348 [ # # ]: 0 : if (is_pipe)
3349 : 0 : restore_sigpipe_trap();
3350 : :
9600 bruce@momjian.us 3351 : 0 : free(fname);
3352 : : }
3353 : : else
3404 tgl@sss.pgh.pa.us 3354 :CBC 8 : ignore_slash_filepipe(scan_state);
3355 : :
3356 : 8 : return status;
3357 : : }
3358 : :
3359 : : /*
3360 : : * \watch -- execute a query every N seconds.
3361 : : * Optionally, stop after M iterations.
3362 : : */
3363 : : static backslashResult
3364 : 22 : exec_command_watch(PsqlScanState scan_state, bool active_branch,
3365 : : PQExpBuffer query_buf, PQExpBuffer previous_buf)
3366 : : {
3367 : 22 : bool success = true;
3368 : :
3369 [ + + ]: 22 : if (active_branch)
3370 : : {
1206 3371 : 18 : bool have_sleep = false;
3372 : 18 : bool have_iter = false;
1061 dgustafsson@postgres 3373 : 18 : bool have_min_rows = false;
487 3374 : 18 : double sleep = pset.watch_interval;
1206 tgl@sss.pgh.pa.us 3375 : 18 : int iter = 0;
1061 dgustafsson@postgres 3376 : 18 : int min_rows = 0;
3377 : :
493 michael@paquier.xyz 3378 [ + + ]: 18 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
3379 : : {
404 peter@eisentraut.org 3380 : 4 : pg_log_error("\\%s not allowed in pipeline mode", "watch");
493 michael@paquier.xyz 3381 : 4 : clean_extended_state();
3382 : 4 : success = false;
3383 : : }
3384 : :
3385 : : /*
3386 : : * Parse arguments. We allow either an unlabeled interval or
3387 : : * "name=value", where name is from the set ('i', 'interval', 'c',
3388 : : * 'count', 'm', 'min_rows'). The parsing of interval value should be
3389 : : * kept in sync with ParseVariableDouble which is used for setting the
3390 : : * default interval value.
3391 : : */
1206 tgl@sss.pgh.pa.us 3392 [ + + ]: 38 : while (success)
3393 : : {
3394 : 27 : char *opt = psql_scan_slash_option(scan_state,
3395 : : OT_NORMAL, NULL, true);
3396 : : char *valptr;
3397 : : char *opt_end;
3398 : :
3399 [ + + ]: 27 : if (!opt)
3400 : 7 : break; /* no more arguments */
3401 : :
3402 : 20 : valptr = strchr(opt, '=');
3403 [ + + ]: 20 : if (valptr)
3404 : : {
3405 : : /* Labeled argument */
3406 : 12 : valptr++;
3407 [ + + ]: 12 : if (strncmp("i=", opt, strlen("i=")) == 0 ||
3408 [ - + ]: 9 : strncmp("interval=", opt, strlen("interval=")) == 0)
3409 : : {
3410 [ - + ]: 3 : if (have_sleep)
3411 : : {
1206 tgl@sss.pgh.pa.us 3412 :UBC 0 : pg_log_error("\\watch: interval value is specified more than once");
3413 : 0 : success = false;
3414 : : }
3415 : : else
3416 : : {
1206 tgl@sss.pgh.pa.us 3417 :CBC 3 : have_sleep = true;
3418 : 3 : errno = 0;
3419 : 3 : sleep = strtod(valptr, &opt_end);
3420 [ + - + - : 3 : if (sleep < 0 || *opt_end || errno == ERANGE)
- + ]
3421 : : {
1206 tgl@sss.pgh.pa.us 3422 :UBC 0 : pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
3423 : 0 : success = false;
3424 : : }
3425 : : }
3426 : : }
1206 tgl@sss.pgh.pa.us 3427 [ + + ]:CBC 9 : else if (strncmp("c=", opt, strlen("c=")) == 0 ||
3428 [ - + ]: 4 : strncmp("count=", opt, strlen("count=")) == 0)
3429 : : {
3430 [ + + ]: 5 : if (have_iter)
3431 : : {
3432 : 1 : pg_log_error("\\watch: iteration count is specified more than once");
3433 : 1 : success = false;
3434 : : }
3435 : : else
3436 : : {
3437 : 4 : have_iter = true;
3438 : 4 : errno = 0;
3439 : 4 : iter = strtoint(valptr, &opt_end, 10);
3440 [ + - + - : 4 : if (iter <= 0 || *opt_end || errno == ERANGE)
- + ]
3441 : : {
1206 tgl@sss.pgh.pa.us 3442 :UBC 0 : pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
3443 : 0 : success = false;
3444 : : }
3445 : : }
3446 : : }
1061 dgustafsson@postgres 3447 [ + + ]:CBC 4 : else if (strncmp("m=", opt, strlen("m=")) == 0 ||
3448 [ + - ]: 1 : strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
3449 : : {
3450 [ + + ]: 4 : if (have_min_rows)
3451 : : {
3452 : 1 : pg_log_error("\\watch: minimum row count specified more than once");
3453 : 1 : success = false;
3454 : : }
3455 : : else
3456 : : {
3457 : 3 : have_min_rows = true;
3458 : 3 : errno = 0;
3459 : 3 : min_rows = strtoint(valptr, &opt_end, 10);
3460 [ + + + - : 3 : if (min_rows <= 0 || *opt_end || errno == ERANGE)
- + ]
3461 : : {
3462 : 1 : pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
3463 : 1 : success = false;
3464 : : }
3465 : : }
3466 : : }
3467 : : else
3468 : : {
1206 tgl@sss.pgh.pa.us 3469 :UBC 0 : pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
3470 : 0 : success = false;
3471 : : }
3472 : : }
3473 : : else
3474 : : {
3475 : : /* Unlabeled argument: take it as interval */
1206 tgl@sss.pgh.pa.us 3476 [ + + ]:CBC 8 : if (have_sleep)
3477 : : {
3478 : 1 : pg_log_error("\\watch: interval value is specified more than once");
3479 : 1 : success = false;
3480 : : }
3481 : : else
3482 : : {
3483 : 7 : have_sleep = true;
3484 : 7 : errno = 0;
3485 : 7 : sleep = strtod(opt, &opt_end);
3486 [ + + + + : 7 : if (sleep < 0 || *opt_end || errno == ERANGE)
+ + ]
3487 : : {
3488 : 3 : pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3489 : 3 : success = false;
3490 : : }
3491 : : }
3492 : : }
3493 : :
4860 3494 : 20 : free(opt);
3495 : : }
3496 : :
3497 : : /* If we parsed arguments successfully, do the command */
1206 3498 [ + + ]: 18 : if (success)
3499 : : {
3500 : : /* If query_buf is empty, recall and execute previous query */
3501 : 7 : (void) copy_previous_query(query_buf, previous_buf);
3502 : :
1061 dgustafsson@postgres 3503 : 7 : success = do_watch(query_buf, sleep, iter, min_rows);
3504 : : }
3505 : :
3506 : : /* Reset the query buffer as though for \r */
4860 tgl@sss.pgh.pa.us 3507 : 16 : resetPQExpBuffer(query_buf);
3508 : 16 : psql_scan_reset(scan_state);
3509 : : }
3510 : : else
3404 3511 : 4 : ignore_slash_options(scan_state);
3512 : :
3513 [ + + ]: 20 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3514 : : }
3515 : :
3516 : : /*
3517 : : * \x -- set or toggle expanded table representation
3518 : : */
3519 : : static backslashResult
3520 : 49 : exec_command_x(PsqlScanState scan_state, bool active_branch)
3521 : : {
3522 : 49 : bool success = true;
3523 : :
3524 [ + + ]: 49 : if (active_branch)
3525 : : {
7084 bruce@momjian.us 3526 : 45 : char *opt = psql_scan_slash_option(scan_state,
3527 : : OT_NORMAL, NULL, true);
3528 : :
3529 : 45 : success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3530 : 45 : free(opt);
3531 : : }
3532 : : else
3404 tgl@sss.pgh.pa.us 3533 : 4 : ignore_slash_options(scan_state);
3534 : :
3535 [ + - ]: 49 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3536 : : }
3537 : :
3538 : : /*
3539 : : * \z -- list table privileges (equivalent to \dp)
3540 : : */
3541 : : static backslashResult
1295 dean.a.rasheed@gmail 3542 : 20 : exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
3543 : : {
3404 tgl@sss.pgh.pa.us 3544 : 20 : bool success = true;
3545 : :
3546 [ + + ]: 20 : if (active_branch)
3547 : : {
3548 : : char *pattern;
3549 : : bool show_system;
3550 : : unsigned short int save_expanded;
3551 : :
1295 dean.a.rasheed@gmail 3552 : 16 : pattern = psql_scan_slash_option(scan_state,
3553 : : OT_NORMAL, NULL, true);
3554 : :
3555 : 16 : show_system = strchr(cmd, 'S') ? true : false;
3556 : :
3557 : : /* if 'x' option specified, force expanded mode */
557 3558 : 16 : save_expanded = pset.popt.topt.expanded;
3559 [ + + ]: 16 : if (strchr(cmd, 'x'))
3560 : 4 : pset.popt.topt.expanded = 1;
3561 : :
1295 3562 : 16 : success = permissionsList(pattern, show_system);
3563 : :
3564 : : /* restore original expanded mode */
557 3565 : 16 : pset.popt.topt.expanded = save_expanded;
3566 : :
1500 peter@eisentraut.org 3567 : 16 : free(pattern);
3568 : : }
3569 : : else
3404 tgl@sss.pgh.pa.us 3570 : 4 : ignore_slash_options(scan_state);
3571 : :
3572 [ + - ]: 20 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3573 : : }
3574 : :
3575 : : /*
3576 : : * \! -- execute shell command
3577 : : */
3578 : : static backslashResult
3579 : 4 : exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
3580 : : {
3581 : 4 : bool success = true;
3582 : :
3583 [ - + ]: 4 : if (active_branch)
3584 : : {
8192 tgl@sss.pgh.pa.us 3585 :UBC 0 : char *opt = psql_scan_slash_option(scan_state,
3586 : : OT_WHOLE_LINE, NULL, false);
3587 : :
3588 : 0 : success = do_shell(opt);
3589 : 0 : free(opt);
3590 : : }
3591 : : else
3404 tgl@sss.pgh.pa.us 3592 :CBC 4 : ignore_slash_whole_line(scan_state);
3593 : :
3594 [ + - ]: 4 : return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3595 : : }
3596 : :
3597 : : /*
3598 : : * \? -- print help about backslash commands
3599 : : */
3600 : : static backslashResult
3601 : 4 : exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
3602 : : {
3603 [ - + ]: 4 : if (active_branch)
3604 : : {
4337 andres@anarazel.de 3605 :UBC 0 : char *opt0 = psql_scan_slash_option(scan_state,
3606 : : OT_NORMAL, NULL, false);
3607 : :
3608 [ # # # # ]: 0 : if (!opt0 || strcmp(opt0, "commands") == 0)
3609 : 0 : slashUsage(pset.popt.topt.pager);
3610 [ # # ]: 0 : else if (strcmp(opt0, "options") == 0)
3611 : 0 : usage(pset.popt.topt.pager);
3612 [ # # ]: 0 : else if (strcmp(opt0, "variables") == 0)
3613 : 0 : helpVariables(pset.popt.topt.pager);
3614 : : else
3615 : 0 : slashUsage(pset.popt.topt.pager);
3616 : :
1500 peter@eisentraut.org 3617 : 0 : free(opt0);
3618 : : }
3619 : : else
3404 tgl@sss.pgh.pa.us 3620 :CBC 4 : ignore_slash_options(scan_state);
3621 : :
3622 : 4 : return PSQL_CMD_SKIP_LINE;
3623 : : }
3624 : :
3625 : :
3626 : : /*
3627 : : * Read and interpret an argument to the \connect slash command.
3628 : : *
3629 : : * Returns a malloc'd string, or NULL if no/empty argument.
3630 : : */
3631 : : static char *
3632 : 883 : read_connect_arg(PsqlScanState scan_state)
3633 : : {
3634 : : char *result;
3635 : : char quote;
3636 : :
3637 : : /*
3638 : : * Ideally we should treat the arguments as SQL identifiers. But for
3639 : : * backwards compatibility with 7.2 and older pg_dump files, we have to
3640 : : * take unquoted arguments verbatim (don't downcase them). For now,
3641 : : * double-quoted arguments may be stripped of double quotes (as if SQL
3642 : : * identifiers). By 7.4 or so, pg_dump files can be expected to
3643 : : * double-quote all mixed-case \connect arguments, and then we can get rid
3644 : : * of OT_SQLIDHACK.
3645 : : */
3646 : 883 : result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
3647 : :
3648 [ + + ]: 883 : if (!result)
3649 : 714 : return NULL;
3650 : :
3651 [ + + ]: 169 : if (quote)
3652 : 12 : return result;
3653 : :
3654 [ + - + + ]: 157 : if (*result == '\0' || strcmp(result, "-") == 0)
3655 : : {
3285 3656 : 137 : free(result);
3404 3657 : 137 : return NULL;
3658 : : }
3659 : :
3660 : 20 : return result;
3661 : : }
3662 : :
3663 : : /*
3664 : : * Read a boolean expression, return it as a PQExpBuffer string.
3665 : : *
3666 : : * Note: anything more or less than one token will certainly fail to be
3667 : : * parsed by ParseVariableBool, so we don't worry about complaining here.
3668 : : * This routine's return data structure will need to be rethought anyway
3669 : : * to support likely future extensions such as "\if defined VARNAME".
3670 : : */
3671 : : static PQExpBuffer
3672 : 176 : gather_boolean_expression(PsqlScanState scan_state)
3673 : : {
3674 : 176 : PQExpBuffer exp_buf = createPQExpBuffer();
3675 : 176 : int num_options = 0;
3676 : : char *value;
3677 : :
3678 : : /* collect all arguments for the conditional command into exp_buf */
3679 : 360 : while ((value = psql_scan_slash_option(scan_state,
3680 [ + + ]: 360 : OT_NORMAL, NULL, false)) != NULL)
3681 : : {
3682 : : /* add spaces between tokens */
3683 [ + + ]: 184 : if (num_options > 0)
3684 : 8 : appendPQExpBufferChar(exp_buf, ' ');
3685 : 184 : appendPQExpBufferStr(exp_buf, value);
3686 : 184 : num_options++;
3687 : 184 : free(value);
3688 : : }
3689 : :
3690 : 176 : return exp_buf;
3691 : : }
3692 : :
3693 : : /*
3694 : : * Read a boolean expression, return true if the expression
3695 : : * was a valid boolean expression that evaluated to true.
3696 : : * Otherwise return false.
3697 : : *
3698 : : * Note: conditional stack's top state must be active, else lexer will
3699 : : * fail to expand variables and backticks.
3700 : : */
3701 : : static bool
3702 : 164 : is_true_boolean_expression(PsqlScanState scan_state, const char *name)
3703 : : {
3704 : 164 : PQExpBuffer buf = gather_boolean_expression(scan_state);
3705 : 164 : bool value = false;
3706 : 164 : bool success = ParseVariableBool(buf->data, name, &value);
3707 : :
3708 : 164 : destroyPQExpBuffer(buf);
3709 [ + + + + ]: 164 : return success && value;
3710 : : }
3711 : :
3712 : : /*
3713 : : * Read a boolean expression, but do nothing with it.
3714 : : *
3715 : : * Note: conditional stack's top state must be INACTIVE, else lexer will
3716 : : * expand variables and backticks, which we do not want here.
3717 : : */
3718 : : static void
3719 : 12 : ignore_boolean_expression(PsqlScanState scan_state)
3720 : : {
3721 : 12 : PQExpBuffer buf = gather_boolean_expression(scan_state);
3722 : :
3723 : 12 : destroyPQExpBuffer(buf);
3724 : 12 : }
3725 : :
3726 : : /*
3727 : : * Read and discard "normal" slash command options.
3728 : : *
3729 : : * This should be used for inactive-branch processing of any slash command
3730 : : * that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
3731 : : * We don't need to worry about exactly how many it would eat, since the
3732 : : * cleanup logic in HandleSlashCmds would silently discard any extras anyway.
3733 : : */
3734 : : static void
3735 : 260 : ignore_slash_options(PsqlScanState scan_state)
3736 : : {
3737 : : char *arg;
3738 : :
3739 : 580 : while ((arg = psql_scan_slash_option(scan_state,
3740 [ + + ]: 580 : OT_NORMAL, NULL, false)) != NULL)
3741 : 320 : free(arg);
3742 : 260 : }
3743 : :
3744 : : /*
3745 : : * Read and discard FILEPIPE slash command argument.
3746 : : *
3747 : : * This *MUST* be used for inactive-branch processing of any slash command
3748 : : * that takes an OT_FILEPIPE option. Otherwise we might consume a different
3749 : : * amount of option text in active and inactive cases.
3750 : : */
3751 : : static void
3752 : 12 : ignore_slash_filepipe(PsqlScanState scan_state)
3753 : : {
3754 : 12 : char *arg = psql_scan_slash_option(scan_state,
3755 : : OT_FILEPIPE, NULL, false);
3756 : :
1500 peter@eisentraut.org 3757 : 12 : free(arg);
3404 tgl@sss.pgh.pa.us 3758 : 12 : }
3759 : :
3760 : : /*
3761 : : * Read and discard whole-line slash command argument.
3762 : : *
3763 : : * This *MUST* be used for inactive-branch processing of any slash command
3764 : : * that takes an OT_WHOLE_LINE option. Otherwise we might consume a different
3765 : : * amount of option text in active and inactive cases.
3766 : : *
3767 : : * Note: although callers might pass "semicolon" as either true or false,
3768 : : * we need not duplicate that here, since it doesn't affect the amount of
3769 : : * input text consumed.
3770 : : */
3771 : : static void
3772 : 28 : ignore_slash_whole_line(PsqlScanState scan_state)
3773 : : {
3774 : 28 : char *arg = psql_scan_slash_option(scan_state,
3775 : : OT_WHOLE_LINE, NULL, false);
3776 : :
1500 peter@eisentraut.org 3777 : 28 : free(arg);
3404 tgl@sss.pgh.pa.us 3778 : 28 : }
3779 : :
3780 : : /*
3781 : : * Return true if the command given is a branching command.
3782 : : */
3783 : : static bool
3404 tgl@sss.pgh.pa.us 3784 :UBC 0 : is_branching_command(const char *cmd)
3785 : : {
3786 : 0 : return (strcmp(cmd, "if") == 0 ||
3787 [ # # ]: 0 : strcmp(cmd, "elif") == 0 ||
3788 [ # # # # ]: 0 : strcmp(cmd, "else") == 0 ||
3789 [ # # ]: 0 : strcmp(cmd, "endif") == 0);
3790 : : }
3791 : :
3792 : : /*
3793 : : * Prepare to possibly restore query buffer to its current state
3794 : : * (cf. discard_query_text).
3795 : : *
3796 : : * We need to remember the length of the query buffer, and the lexer's
3797 : : * notion of the parenthesis nesting depth.
3798 : : */
3799 : : static void
3404 tgl@sss.pgh.pa.us 3800 :CBC 196 : save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
3801 : : PQExpBuffer query_buf)
3802 : : {
3803 [ + - ]: 196 : if (query_buf)
3804 : 196 : conditional_stack_set_query_len(cstack, query_buf->len);
3805 : 196 : conditional_stack_set_paren_depth(cstack,
3806 : : psql_scan_get_paren_depth(scan_state));
3807 : 196 : }
3808 : :
3809 : : /*
3810 : : * Discard any query text absorbed during an inactive conditional branch.
3811 : : *
3812 : : * We must discard data that was appended to query_buf during an inactive
3813 : : * \if branch. We don't have to do anything there if there's no query_buf.
3814 : : *
3815 : : * Also, reset the lexer state to the same paren depth there was before.
3816 : : * (The rest of its state doesn't need attention, since we could not be
3817 : : * inside a comment or literal or partial token.)
3818 : : */
3819 : : static void
3820 : 165 : discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
3821 : : PQExpBuffer query_buf)
3822 : : {
3823 [ + - ]: 165 : if (query_buf)
3824 : : {
3825 : 165 : int new_len = conditional_stack_get_query_len(cstack);
3826 : :
3827 [ + - + - ]: 165 : Assert(new_len >= 0 && new_len <= query_buf->len);
3828 : 165 : query_buf->len = new_len;
3829 : 165 : query_buf->data[new_len] = '\0';
3830 : : }
3831 : 165 : psql_scan_set_paren_depth(scan_state,
3832 : : conditional_stack_get_paren_depth(cstack));
3833 : 165 : }
3834 : :
3835 : : /*
3836 : : * If query_buf is empty, copy previous_buf into it.
3837 : : *
3838 : : * This is used by various slash commands for which re-execution of a
3839 : : * previous query is a common usage. For convenience, we allow the
3840 : : * case of query_buf == NULL (and do nothing).
3841 : : *
3842 : : * Returns "true" if the previous query was copied into the query
3843 : : * buffer, else "false".
3844 : : */
3845 : : static bool
3846 : 2296 : copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
3847 : : {
3848 [ + - + + ]: 2296 : if (query_buf && query_buf->len == 0)
3849 : : {
3850 : 880 : appendPQExpBufferStr(query_buf, previous_buf->data);
1939 3851 : 880 : return true;
3852 : : }
3853 : 1416 : return false;
3854 : : }
3855 : :
3856 : : /*
3857 : : * Ask the user for a password; 'username' is the username the
3858 : : * password is for, if one has been explicitly specified.
3859 : : * Returns a malloc'd string.
3860 : : * If 'canceled' is provided, *canceled will be set to true if the prompt
3861 : : * is canceled via SIGINT, and to false otherwise.
3862 : : */
3863 : : static char *
1709 tgl@sss.pgh.pa.us 3864 :UBC 0 : prompt_for_password(const char *username, bool *canceled)
3865 : : {
3866 : : char *result;
3867 : : PromptInterruptContext prompt_ctx;
3868 : :
3869 : : /* Set up to let SIGINT cancel simple_prompt_extended() */
3870 : 0 : prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3871 : 0 : prompt_ctx.enabled = &sigint_interrupt_enabled;
3872 : 0 : prompt_ctx.canceled = false;
3873 : :
3099 3874 [ # # # # ]: 0 : if (username == NULL || username[0] == '\0')
1709 3875 : 0 : result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3876 : : else
3877 : : {
3878 : : char *prompt_text;
3879 : :
4659 3880 : 0 : prompt_text = psprintf(_("Password for user %s: "), username);
1709 3881 : 0 : result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
24 peter@eisentraut.org 3882 :UNC 0 : pfree(prompt_text);
3883 : : }
3884 : :
1709 tgl@sss.pgh.pa.us 3885 [ # # ]:UBC 0 : if (canceled)
3886 : 0 : *canceled = prompt_ctx.canceled;
3887 : :
2151 3888 : 0 : return result;
3889 : : }
3890 : :
3891 : : static bool
7419 neilc@samurai.com 3892 :CBC 24 : param_is_newly_set(const char *old_val, const char *new_val)
3893 : : {
3894 [ - + ]: 24 : if (new_val == NULL)
7419 neilc@samurai.com 3895 :UBC 0 : return false;
3896 : :
7419 neilc@samurai.com 3897 [ + - - + ]:CBC 24 : if (old_val == NULL || strcmp(old_val, new_val) != 0)
7419 neilc@samurai.com 3898 :UBC 0 : return true;
3899 : :
7419 neilc@samurai.com 3900 :CBC 24 : return false;
3901 : : }
3902 : :
3903 : : /*
3904 : : * do_connect -- handler for \connect
3905 : : *
3906 : : * Connects to a database with given parameters. If we are told to re-use
3907 : : * parameters, parameters from the previous connection are used where the
3908 : : * command's own options do not supply a value. Otherwise, libpq defaults
3909 : : * are used.
3910 : : *
3911 : : * In interactive mode, if connection fails with the given parameters,
3912 : : * the old connection will be kept.
3913 : : */
3914 : : static bool
3638 noah@leadboat.com 3915 : 218 : do_connect(enum trivalue reuse_previous_specification,
3916 : : char *dbname, char *user, char *host, char *port)
3917 : : {
7234 bruce@momjian.us 3918 : 218 : PGconn *o_conn = pset.db,
2103 tgl@sss.pgh.pa.us 3919 : 218 : *n_conn = NULL;
3920 : : PQconninfoOption *cinfo;
3921 : 218 : int nconnopts = 0;
3922 : 218 : bool same_host = false;
7234 bruce@momjian.us 3923 : 218 : char *password = NULL;
3924 : : char *client_encoding;
2103 tgl@sss.pgh.pa.us 3925 : 218 : bool success = true;
3926 : 218 : bool keep_password = true;
3927 : : bool has_connection_string;
3928 : : bool reuse_previous;
3929 : :
2102 3930 : 218 : has_connection_string = dbname ?
3931 [ + + + + ]: 218 : recognized_connection_string(dbname) : false;
3932 : :
3933 : : /* Complain if we have additional arguments after a connection string. */
3934 [ + + + - : 218 : if (has_connection_string && (user || host || port))
+ - - + ]
3935 : : {
2102 tgl@sss.pgh.pa.us 3936 :UBC 0 : pg_log_error("Do not give user, host, or port separately when using a connection string");
5092 bruce@momjian.us 3937 : 0 : return false;
3938 : : }
3939 : :
3638 noah@leadboat.com 3940 [ + - + ]:CBC 218 : switch (reuse_previous_specification)
3941 : : {
3942 : 11 : case TRI_YES:
3943 : 11 : reuse_previous = true;
3944 : 11 : break;
3638 noah@leadboat.com 3945 :UBC 0 : case TRI_NO:
3946 : 0 : reuse_previous = false;
3947 : 0 : break;
3638 noah@leadboat.com 3948 :CBC 207 : default:
3949 : 207 : reuse_previous = !has_connection_string;
3950 : 207 : break;
3951 : : }
3952 : :
3953 : : /*
3954 : : * If we intend to re-use connection parameters, collect them out of the
3955 : : * old connection, then replace individual values as necessary. (We may
3956 : : * need to resort to looking at pset.dead_conn, if the connection died
3957 : : * previously.) Otherwise, obtain a PQconninfoOption array containing
3958 : : * libpq's defaults, and modify that. Note this function assumes that
3959 : : * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3960 : : * containing the same options in the same order.
3961 : : */
2805 alvherre@alvh.no-ip. 3962 [ + - ]: 218 : if (reuse_previous)
3963 : : {
2101 tgl@sss.pgh.pa.us 3964 [ + - ]: 218 : if (o_conn)
3965 : 218 : cinfo = PQconninfo(o_conn);
2101 tgl@sss.pgh.pa.us 3966 [ # # ]:UBC 0 : else if (pset.dead_conn)
3967 : 0 : cinfo = PQconninfo(pset.dead_conn);
3968 : : else
3969 : : {
3970 : : /* This is reachable after a non-interactive \connect failure */
3971 : 0 : pg_log_error("No database connection exists to re-use parameters from");
3972 : 0 : return false;
3973 : : }
3974 : : }
3975 : : else
2103 3976 : 0 : cinfo = PQconndefaults();
3977 : :
2103 tgl@sss.pgh.pa.us 3978 [ + - ]:CBC 218 : if (cinfo)
3979 : : {
3980 [ + + ]: 218 : if (has_connection_string)
3981 : : {
3982 : : /* Parse the connstring and insert values into cinfo */
3983 : : PQconninfoOption *replcinfo;
3984 : : char *errmsg;
3985 : :
3986 : 11 : replcinfo = PQconninfoParse(dbname, &errmsg);
3987 [ + - ]: 11 : if (replcinfo)
3988 : : {
3989 : : PQconninfoOption *ci;
3990 : : PQconninfoOption *replci;
2102 3991 : 11 : bool have_password = false;
3992 : :
2103 3993 : 11 : for (ci = cinfo, replci = replcinfo;
3994 [ + + + - ]: 583 : ci->keyword && replci->keyword;
3995 : 572 : ci++, replci++)
3996 : : {
3997 [ - + ]: 572 : Assert(strcmp(ci->keyword, replci->keyword) == 0);
3998 : : /* Insert value from connstring if one was provided */
3999 [ + + ]: 572 : if (replci->val)
4000 : : {
4001 : : /*
4002 : : * We know that both val strings were allocated by
4003 : : * libpq, so the least messy way to avoid memory leaks
4004 : : * is to swap them.
4005 : : */
4006 : 14 : char *swap = replci->val;
4007 : :
4008 : 14 : replci->val = ci->val;
4009 : 14 : ci->val = swap;
4010 : :
4011 : : /*
4012 : : * Check whether connstring provides options affecting
4013 : : * password re-use. While any change in user, host,
4014 : : * hostaddr, or port causes us to ignore the old
4015 : : * connection's password, we don't force that for
4016 : : * dbname, since passwords aren't database-specific.
4017 : : */
2102 4018 [ + - ]: 14 : if (replci->val == NULL ||
4019 [ + - ]: 14 : strcmp(ci->val, replci->val) != 0)
4020 : : {
4021 [ + + ]: 14 : if (strcmp(replci->keyword, "user") == 0 ||
4022 [ + - ]: 11 : strcmp(replci->keyword, "host") == 0 ||
4023 [ + - ]: 11 : strcmp(replci->keyword, "hostaddr") == 0 ||
4024 [ - + ]: 11 : strcmp(replci->keyword, "port") == 0)
4025 : 3 : keep_password = false;
4026 : : }
4027 : : /* Also note whether connstring contains a password. */
4028 [ - + ]: 14 : if (strcmp(replci->keyword, "password") == 0)
2102 tgl@sss.pgh.pa.us 4029 :UBC 0 : have_password = true;
4030 : : }
1950 tgl@sss.pgh.pa.us 4031 [ - + ]:CBC 558 : else if (!reuse_previous)
4032 : : {
4033 : : /*
4034 : : * When we have a connstring and are not re-using
4035 : : * parameters, swap *all* entries, even those not set
4036 : : * by the connstring. This avoids absorbing
4037 : : * environment-dependent defaults from the result of
4038 : : * PQconndefaults(). We don't want to do that because
4039 : : * they'd override service-file entries if the
4040 : : * connstring specifies a service parameter, whereas
4041 : : * the priority should be the other way around. libpq
4042 : : * can certainly recompute any defaults we don't pass
4043 : : * here. (In this situation, it's a bit wasteful to
4044 : : * have called PQconndefaults() at all, but not doing
4045 : : * so would require yet another major code path here.)
4046 : : */
1950 tgl@sss.pgh.pa.us 4047 :UBC 0 : replci->val = ci->val;
4048 : 0 : ci->val = NULL;
4049 : : }
4050 : : }
2103 tgl@sss.pgh.pa.us 4051 [ + - + - ]:CBC 11 : Assert(ci->keyword == NULL && replci->keyword == NULL);
4052 : :
4053 : : /* While here, determine how many option slots there are */
4054 : 11 : nconnopts = ci - cinfo;
4055 : :
4056 : 11 : PQconninfoFree(replcinfo);
4057 : :
4058 : : /*
4059 : : * If the connstring contains a password, tell the loop below
4060 : : * that we may use it, regardless of other settings (i.e.,
4061 : : * cinfo's password is no longer an "old" password).
4062 : : */
2102 4063 [ - + ]: 11 : if (have_password)
2102 tgl@sss.pgh.pa.us 4064 :UBC 0 : keep_password = true;
4065 : :
4066 : : /* Don't let code below try to inject dbname into params. */
2103 tgl@sss.pgh.pa.us 4067 :CBC 11 : dbname = NULL;
4068 : : }
4069 : : else
4070 : : {
4071 : : /* PQconninfoParse failed */
2103 tgl@sss.pgh.pa.us 4072 [ # # ]:UBC 0 : if (errmsg)
4073 : : {
4074 : 0 : pg_log_error("%s", errmsg);
4075 : 0 : PQfreemem(errmsg);
4076 : : }
4077 : : else
4078 : 0 : pg_log_error("out of memory");
4079 : 0 : success = false;
4080 : : }
4081 : : }
4082 : : else
4083 : : {
4084 : : /*
4085 : : * If dbname isn't a connection string, then we'll inject it and
4086 : : * the other parameters into the keyword array below. (We can't
4087 : : * easily insert them into the cinfo array because of memory
4088 : : * management issues: PQconninfoFree would misbehave on Windows.)
4089 : : * However, to avoid dependencies on the order in which parameters
4090 : : * appear in the array, make a preliminary scan to set
4091 : : * keep_password and same_host correctly.
4092 : : *
4093 : : * While any change in user, host, or port causes us to ignore the
4094 : : * old connection's password, we don't force that for dbname,
4095 : : * since passwords aren't database-specific.
4096 : : */
4097 : : PQconninfoOption *ci;
4098 : :
2103 tgl@sss.pgh.pa.us 4099 [ + + ]:CBC 10971 : for (ci = cinfo; ci->keyword; ci++)
4100 : : {
4101 [ + + + + ]: 10764 : if (user && strcmp(ci->keyword, "user") == 0)
4102 : : {
4103 [ + - + - ]: 4 : if (!(ci->val && strcmp(user, ci->val) == 0))
4104 : 4 : keep_password = false;
4105 : : }
4106 [ - + - - ]: 10760 : else if (host && strcmp(ci->keyword, "host") == 0)
4107 : : {
2103 tgl@sss.pgh.pa.us 4108 [ # # # # ]:UBC 0 : if (ci->val && strcmp(host, ci->val) == 0)
4109 : 0 : same_host = true;
4110 : : else
4111 : 0 : keep_password = false;
4112 : : }
2103 tgl@sss.pgh.pa.us 4113 [ - + - - ]:CBC 10760 : else if (port && strcmp(ci->keyword, "port") == 0)
4114 : : {
2103 tgl@sss.pgh.pa.us 4115 [ # # # # ]:UBC 0 : if (!(ci->val && strcmp(port, ci->val) == 0))
4116 : 0 : keep_password = false;
4117 : : }
4118 : : }
4119 : :
4120 : : /* While here, determine how many option slots there are */
2103 tgl@sss.pgh.pa.us 4121 :CBC 207 : nconnopts = ci - cinfo;
4122 : : }
4123 : : }
4124 : : else
4125 : : {
4126 : : /* We failed to create the cinfo structure */
2103 tgl@sss.pgh.pa.us 4127 :UBC 0 : pg_log_error("out of memory");
4128 : 0 : success = false;
4129 : : }
4130 : :
4131 : : /*
4132 : : * If the user asked to be prompted for a password, ask for one now. If
4133 : : * not, use the password from the old connection, provided the username
4134 : : * etc have not changed. Otherwise, try to connect without a password
4135 : : * first, and then ask for a password if needed.
4136 : : *
4137 : : * XXX: this behavior leads to spurious connection attempts recorded in
4138 : : * the postmaster's log. But libpq offers no API that would let us obtain
4139 : : * a password and then continue with the first connection attempt.
4140 : : */
2103 tgl@sss.pgh.pa.us 4141 [ - + - - ]:CBC 218 : if (pset.getPassword == TRI_YES && success)
4142 : : {
1709 tgl@sss.pgh.pa.us 4143 :UBC 0 : bool canceled = false;
4144 : :
4145 : : /*
4146 : : * If a connstring or URI is provided, we don't know which username
4147 : : * will be used, since we haven't dug that out of the connstring.
4148 : : * Don't risk issuing a misleading prompt. As in startup.c, it does
4149 : : * not seem worth working harder, since this getPassword setting is
4150 : : * normally only used in noninteractive cases.
4151 : : */
4152 [ # # ]: 0 : password = prompt_for_password(has_connection_string ? NULL : user,
4153 : : &canceled);
4154 : 0 : success = !canceled;
4155 : : }
4156 : :
4157 : : /*
4158 : : * Consider whether to force client_encoding to "auto" (overriding
4159 : : * anything in the connection string). We do so if we have a terminal
4160 : : * connection and there is no PGCLIENTENCODING environment setting.
4161 : : */
2064 tgl@sss.pgh.pa.us 4162 [ - + - - ]:CBC 218 : if (pset.notty || getenv("PGCLIENTENCODING"))
4163 : 218 : client_encoding = NULL;
4164 : : else
2064 tgl@sss.pgh.pa.us 4165 :UBC 0 : client_encoding = "auto";
4166 : :
4167 : : /* Loop till we have a connection or fail, which we might've already */
2103 tgl@sss.pgh.pa.us 4168 [ + - ]:CBC 218 : while (success)
4169 : : {
148 michael@paquier.xyz 4170 : 218 : const char **keywords = pg_malloc_array(const char *, nconnopts + 1);
4171 : 218 : const char **values = pg_malloc_array(const char *, nconnopts + 1);
2103 tgl@sss.pgh.pa.us 4172 : 218 : int paramnum = 0;
4173 : : PQconninfoOption *ci;
4174 : :
4175 : : /*
4176 : : * Copy non-default settings into the PQconnectdbParams parameter
4177 : : * arrays; but inject any values specified old-style, as well as any
4178 : : * interactively-obtained password, and a couple of fields we want to
4179 : : * set forcibly.
4180 : : *
4181 : : * If you change this code, see also the initial-connection code in
4182 : : * main().
4183 : : */
4184 [ + + ]: 11554 : for (ci = cinfo; ci->keyword; ci++)
4185 : : {
4186 : 11336 : keywords[paramnum] = ci->keyword;
4187 : :
4188 [ + + + + ]: 11336 : if (dbname && strcmp(ci->keyword, "dbname") == 0)
4189 : 6 : values[paramnum++] = dbname;
4190 [ + + + + ]: 11330 : else if (user && strcmp(ci->keyword, "user") == 0)
4191 : 4 : values[paramnum++] = user;
4192 [ - + - - ]: 11326 : else if (host && strcmp(ci->keyword, "host") == 0)
2103 tgl@sss.pgh.pa.us 4193 :UBC 0 : values[paramnum++] = host;
2103 tgl@sss.pgh.pa.us 4194 [ - + - - :CBC 11326 : else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
- - ]
4195 : : {
4196 : : /* If we're changing the host value, drop any old hostaddr */
2103 tgl@sss.pgh.pa.us 4197 :UBC 0 : values[paramnum++] = NULL;
4198 : : }
2103 tgl@sss.pgh.pa.us 4199 [ - + - - ]:CBC 11326 : else if (port && strcmp(ci->keyword, "port") == 0)
2103 tgl@sss.pgh.pa.us 4200 :UBC 0 : values[paramnum++] = port;
4201 : : /* If !keep_password, we unconditionally drop old password */
2102 tgl@sss.pgh.pa.us 4202 [ + - + + ]:CBC 11326 : else if ((password || !keep_password) &&
4203 [ + + ]: 360 : strcmp(ci->keyword, "password") == 0)
2103 4204 : 7 : values[paramnum++] = password;
4205 [ + + ]: 11319 : else if (strcmp(ci->keyword, "fallback_application_name") == 0)
4206 : 218 : values[paramnum++] = pset.progname;
2064 4207 [ - + ]: 11101 : else if (client_encoding &&
2064 tgl@sss.pgh.pa.us 4208 [ # # ]:UBC 0 : strcmp(ci->keyword, "client_encoding") == 0)
4209 : 0 : values[paramnum++] = client_encoding;
2103 tgl@sss.pgh.pa.us 4210 [ + + ]:CBC 11101 : else if (ci->val)
4211 : 4144 : values[paramnum++] = ci->val;
4212 : : /* else, don't bother making libpq parse this keyword */
4213 : : }
4214 : : /* add array terminator */
4215 : 218 : keywords[paramnum] = NULL;
4132 alvherre@alvh.no-ip. 4216 : 218 : values[paramnum] = NULL;
4217 : :
4218 : : /* Note we do not want libpq to re-expand the dbname parameter */
844 rhaas@postgresql.org 4219 : 218 : n_conn = PQconnectStartParams(keywords, values, false);
4220 : :
4132 alvherre@alvh.no-ip. 4221 : 218 : pg_free(keywords);
4222 : 218 : pg_free(values);
4223 : :
844 rhaas@postgresql.org 4224 : 218 : wait_until_connected(n_conn);
7419 neilc@samurai.com 4225 [ + - ]: 218 : if (PQstatus(n_conn) == CONNECTION_OK)
4226 : 218 : break;
4227 : :
4228 : : /*
4229 : : * Connection attempt failed; either retry the connection attempt with
4230 : : * a new password, or give up.
4231 : : */
6358 peter_e@gmx.net 4232 [ # # # # :UBC 0 : if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
# # ]
9760 bruce@momjian.us 4233 : 0 : {
1709 tgl@sss.pgh.pa.us 4234 : 0 : bool canceled = false;
4235 : :
4236 : : /*
4237 : : * Prompt for password using the username we actually connected
4238 : : * with --- it might've come out of "dbname" rather than "user".
4239 : : */
4240 : 0 : password = prompt_for_password(PQuser(n_conn), &canceled);
7419 neilc@samurai.com 4241 : 0 : PQfinish(n_conn);
2103 tgl@sss.pgh.pa.us 4242 : 0 : n_conn = NULL;
1709 4243 : 0 : success = !canceled;
7419 neilc@samurai.com 4244 : 0 : continue;
4245 : : }
4246 : :
4247 : : /*
4248 : : * We'll report the error below ... unless n_conn is NULL, indicating
4249 : : * that libpq didn't have enough memory to make a PGconn.
4250 : : */
2103 tgl@sss.pgh.pa.us 4251 [ # # ]: 0 : if (n_conn == NULL)
4252 : 0 : pg_log_error("out of memory");
4253 : :
4254 : 0 : success = false;
4255 : : } /* end retry loop */
4256 : :
4257 : : /* Release locally allocated data, whether we succeeded or not */
1499 peter@eisentraut.org 4258 :CBC 218 : pg_free(password);
1483 4259 : 218 : PQconninfoFree(cinfo);
4260 : :
2103 tgl@sss.pgh.pa.us 4261 [ - + ]: 218 : if (!success)
4262 : : {
4263 : : /*
4264 : : * Failed to connect to the database. In interactive mode, keep the
4265 : : * previous connection to the DB; in scripting mode, close our
4266 : : * previous connection as well.
4267 : : */
9600 bruce@momjian.us 4268 [ # # ]:UBC 0 : if (pset.cur_cmd_interactive)
4269 : : {
2103 tgl@sss.pgh.pa.us 4270 [ # # ]: 0 : if (n_conn)
4271 : : {
4272 : 0 : pg_log_info("%s", PQerrorMessage(n_conn));
4273 : 0 : PQfinish(n_conn);
4274 : : }
4275 : :
4276 : : /* pset.db is left unmodified */
7419 neilc@samurai.com 4277 [ # # ]: 0 : if (o_conn)
2672 peter@eisentraut.org 4278 : 0 : pg_log_info("Previous connection kept");
4279 : : }
4280 : : else
4281 : : {
2103 tgl@sss.pgh.pa.us 4282 [ # # ]: 0 : if (n_conn)
4283 : : {
4284 : 0 : pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
4285 : 0 : PQfinish(n_conn);
4286 : : }
4287 : :
7419 neilc@samurai.com 4288 [ # # ]: 0 : if (o_conn)
4289 : : {
4290 : : /*
4291 : : * Transition to having no connection.
4292 : : *
4293 : : * Unlike CheckConnection(), we close the old connection
4294 : : * immediately to prevent its parameters from being re-used.
4295 : : * This is so that a script cannot accidentally reuse
4296 : : * parameters it did not expect to. Otherwise, the state
4297 : : * cleanup should be the same as in CheckConnection().
4298 : : */
4299 : 0 : PQfinish(o_conn);
4300 : 0 : pset.db = NULL;
2518 tgl@sss.pgh.pa.us 4301 : 0 : ResetCancelConn();
4302 : 0 : UnsyncVariables();
4303 : : }
4304 : :
4305 : : /* On the same reasoning, release any dead_conn to prevent reuse */
2101 4306 [ # # ]: 0 : if (pset.dead_conn)
4307 : : {
4308 : 0 : PQfinish(pset.dead_conn);
4309 : 0 : pset.dead_conn = NULL;
4310 : : }
4311 : : }
4312 : :
7419 neilc@samurai.com 4313 : 0 : return false;
4314 : : }
4315 : :
4316 : : /*
4317 : : * Replace the old connection with the new one, and update
4318 : : * connection-dependent variables. Keep the resynchronization logic in
4319 : : * sync with CheckConnection().
4320 : : */
7419 neilc@samurai.com 4321 :CBC 218 : PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
4322 : 218 : pset.db = n_conn;
8428 tgl@sss.pgh.pa.us 4323 : 218 : SyncVariables();
5993 bruce@momjian.us 4324 : 218 : connection_warnings(false); /* Must be after SyncVariables */
4325 : :
4326 : : /* Tell the user about the new connection */
7270 tgl@sss.pgh.pa.us 4327 [ + + ]: 218 : if (!pset.quiet)
4328 : : {
4035 noah@leadboat.com 4329 [ + - + - ]: 24 : if (!o_conn ||
4330 [ - + ]: 24 : param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
5835 tgl@sss.pgh.pa.us 4331 : 12 : param_is_newly_set(PQport(o_conn), PQport(pset.db)))
5846 rhaas@postgresql.org 4332 :UBC 0 : {
1389 drowley@postgresql.o 4333 : 0 : char *connhost = PQhost(pset.db);
2805 alvherre@alvh.no-ip. 4334 : 0 : char *hostaddr = PQhostaddr(pset.db);
4335 : :
1389 drowley@postgresql.o 4336 [ # # ]: 0 : if (is_unixsock_path(connhost))
4337 : : {
4338 : : /* hostaddr overrides connhost */
2805 alvherre@alvh.no-ip. 4339 [ # # # # ]: 0 : if (hostaddr && *hostaddr)
4340 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
4341 : : PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
4342 : : else
4343 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
4344 : : PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4345 : : }
4346 : : else
4347 : : {
1389 drowley@postgresql.o 4348 [ # # # # : 0 : if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
# # ]
2805 alvherre@alvh.no-ip. 4349 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
4350 : : PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
4351 : : else
4352 : 0 : printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
4353 : : PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4354 : : }
4355 : : }
4356 : : else
5835 tgl@sss.pgh.pa.us 4357 :CBC 12 : printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
4358 : : PQdb(pset.db), PQuser(pset.db));
4359 : : }
4360 : :
4361 : : /* Drop no-longer-needed connection(s) */
7419 neilc@samurai.com 4362 [ + - ]: 218 : if (o_conn)
4363 : 218 : PQfinish(o_conn);
2101 tgl@sss.pgh.pa.us 4364 [ - + ]: 218 : if (pset.dead_conn)
4365 : : {
2101 tgl@sss.pgh.pa.us 4366 :UBC 0 : PQfinish(pset.dead_conn);
4367 : 0 : pset.dead_conn = NULL;
4368 : : }
4369 : :
7419 neilc@samurai.com 4370 :CBC 218 : return true;
4371 : : }
4372 : :
4373 : : /*
4374 : : * Processes the connection sequence described by PQconnectStartParams(). Don't
4375 : : * worry about reporting errors in this function. Our caller will check the
4376 : : * connection's status, and report appropriately.
4377 : : */
4378 : : static void
844 rhaas@postgresql.org 4379 : 218 : wait_until_connected(PGconn *conn)
4380 : : {
4381 : 218 : bool forRead = false;
4382 : :
4383 : : while (true)
4384 : 224 : {
4385 : : int rc;
4386 : : int sock;
4387 : : pg_usec_time_t end_time;
4388 : :
4389 : : /*
4390 : : * On every iteration of the connection sequence, let's check if the
4391 : : * user has requested a cancellation.
4392 : : */
4393 [ - + ]: 442 : if (cancel_pressed)
844 rhaas@postgresql.org 4394 :UBC 0 : break;
4395 : :
4396 : : /*
4397 : : * Do not assume that the socket remains the same across
4398 : : * PQconnectPoll() calls.
4399 : : */
844 rhaas@postgresql.org 4400 :CBC 442 : sock = PQsocket(conn);
4401 [ - + ]: 442 : if (sock == -1)
844 rhaas@postgresql.org 4402 :UBC 0 : break;
4403 : :
4404 : : /*
4405 : : * If the user sends SIGINT between the cancel_pressed check, and
4406 : : * polling of the socket, it will not be recognized. Instead, we will
4407 : : * just wait until the next step in the connection sequence or
4408 : : * forever, which might require users to send SIGTERM or SIGQUIT.
4409 : : *
4410 : : * Some solutions would include the "self-pipe trick," using
4411 : : * pselect(2) and ppoll(2), or using a timeout.
4412 : : *
4413 : : * The self-pipe trick requires a bit of code to setup. pselect(2) and
4414 : : * ppoll(2) are not on all the platforms we support. The simplest
4415 : : * solution happens to just be adding a timeout, so let's wait for 1
4416 : : * second and check cancel_pressed again.
4417 : : */
772 tgl@sss.pgh.pa.us 4418 :CBC 442 : end_time = PQgetCurrentTimeUSec() + 1000000;
844 rhaas@postgresql.org 4419 : 442 : rc = PQsocketPoll(sock, forRead, !forRead, end_time);
4420 [ - + ]: 442 : if (rc == -1)
844 rhaas@postgresql.org 4421 :UBC 0 : return;
4422 : :
844 rhaas@postgresql.org 4423 [ + + - - :CBC 442 : switch (PQconnectPoll(conn))
- ]
4424 : : {
4425 : 218 : case PGRES_POLLING_OK:
4426 : : case PGRES_POLLING_FAILED:
4427 : 218 : return;
4428 : 224 : case PGRES_POLLING_READING:
4429 : 224 : forRead = true;
4430 : 224 : continue;
844 rhaas@postgresql.org 4431 :UBC 0 : case PGRES_POLLING_WRITING:
4432 : 0 : forRead = false;
4433 : 0 : continue;
4434 : 0 : case PGRES_POLLING_ACTIVE:
4435 : 0 : pg_unreachable();
4436 : : }
4437 : : }
4438 : : }
4439 : :
4440 : : void
6003 bruce@momjian.us 4441 :CBC 221 : connection_warnings(bool in_startup)
4442 : : {
6598 4443 [ + + + + ]: 221 : if (!pset.quiet && !pset.notty)
4444 : : {
4869 heikki.linnakangas@i 4445 : 3 : int client_ver = PG_VERSION_NUM;
4446 : : char cverbuf[32];
4447 : : char sverbuf[32];
4448 : :
6598 bruce@momjian.us 4449 [ - + ]: 3 : if (pset.sversion != client_ver)
4450 : : {
4451 : : const char *server_version;
4452 : :
4453 : : /* Try to get full text form, might include "devel" etc */
6598 bruce@momjian.us 4454 :UBC 0 : server_version = PQparameterStatus(pset.db, "server_version");
4455 : : /* Otherwise fall back on pset.sversion */
4456 [ # # ]: 0 : if (!server_version)
4457 : : {
3630 tgl@sss.pgh.pa.us 4458 : 0 : formatPGVersionNumber(pset.sversion, true,
4459 : : sverbuf, sizeof(sverbuf));
4460 : 0 : server_version = sverbuf;
4461 : : }
4462 : :
6253 bruce@momjian.us 4463 : 0 : printf(_("%s (%s, server %s)\n"),
4464 : : pset.progname, PG_VERSION, server_version);
4465 : : }
4466 : : /* For version match, only print psql banner on startup. */
6003 bruce@momjian.us 4467 [ + - ]:CBC 3 : else if (in_startup)
6598 4468 : 3 : printf("%s (%s)\n", pset.progname, PG_VERSION);
4469 : :
4470 : : /*
4471 : : * Warn if server's major version is newer than ours, or if server
4472 : : * predates our support cutoff (currently 10).
4473 : : */
1682 tgl@sss.pgh.pa.us 4474 [ + - ]: 3 : if (pset.sversion / 100 > client_ver / 100 ||
23 nathan@postgresql.or 4475 [ - + ]:GNC 3 : pset.sversion < 100000)
3630 tgl@sss.pgh.pa.us 4476 :UBC 0 : printf(_("WARNING: %s major version %s, server major version %s.\n"
4477 : : " Some psql features might not work.\n"),
4478 : : pset.progname,
4479 : : formatPGVersionNumber(client_ver, false,
4480 : : cverbuf, sizeof(cverbuf)),
4481 : : formatPGVersionNumber(pset.sversion, false,
4482 : : sverbuf, sizeof(sverbuf)));
4483 : :
4484 : : #ifdef WIN32
4485 : : if (in_startup)
4486 : : checkWin32Codepage();
4487 : : #endif
6598 bruce@momjian.us 4488 :CBC 3 : printSSLInfo();
2670 sfrost@snowman.net 4489 : 3 : printGSSInfo();
4490 : : }
6598 bruce@momjian.us 4491 : 221 : }
4492 : :
4493 : :
4494 : : /*
4495 : : * printSSLInfo
4496 : : *
4497 : : * Prints information about the current SSL connection, if SSL is in use
4498 : : */
4499 : : static void
4500 : 3 : printSSLInfo(void)
4501 : : {
4502 : : const char *protocol;
4503 : : const char *cipher;
4504 : : const char *compression;
4505 : : const char *alpn;
4506 : :
4190 heikki.linnakangas@i 4507 [ + - ]: 3 : if (!PQsslInUse(pset.db))
6598 bruce@momjian.us 4508 : 3 : return; /* no SSL */
4509 : :
4190 heikki.linnakangas@i 4510 :UBC 0 : protocol = PQsslAttribute(pset.db, "protocol");
4511 : 0 : cipher = PQsslAttribute(pset.db, "cipher");
1963 michael@paquier.xyz 4512 : 0 : compression = PQsslAttribute(pset.db, "compression");
838 heikki.linnakangas@i 4513 : 0 : alpn = PQsslAttribute(pset.db, "alpn");
4514 : :
4515 [ # # # # : 0 : printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
# # # # #
# # # ]
4516 : : protocol ? protocol : _("unknown"),
4517 : : cipher ? cipher : _("unknown"),
4518 : : (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4519 : : (alpn && alpn[0] != '\0') ? alpn : _("none"));
4520 : : }
4521 : :
4522 : : /*
4523 : : * printGSSInfo
4524 : : *
4525 : : * Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
4526 : : */
4527 : : static void
2670 sfrost@snowman.net 4528 :CBC 3 : printGSSInfo(void)
4529 : : {
4530 [ + - ]: 3 : if (!PQgssEncInUse(pset.db))
4531 : 3 : return; /* no GSSAPI encryption in use */
4532 : :
2514 peter@eisentraut.org 4533 :UBC 0 : printf(_("GSSAPI-encrypted connection\n"));
4534 : : }
4535 : :
4536 : :
4537 : : /*
4538 : : * checkWin32Codepage
4539 : : *
4540 : : * Prints a warning when win32 console codepage differs from Windows codepage
4541 : : */
4542 : : #ifdef WIN32
4543 : : static void
4544 : : checkWin32Codepage(void)
4545 : : {
4546 : : unsigned int wincp,
4547 : : concp;
4548 : :
4549 : : wincp = GetACP();
4550 : : concp = GetConsoleCP();
4551 : : if (wincp != concp)
4552 : : {
4553 : : printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
4554 : : " 8-bit characters might not work correctly. See psql reference\n"
4555 : : " page \"Notes for Windows users\" for details.\n"),
4556 : : concp, wincp);
4557 : : }
4558 : : }
4559 : : #endif
4560 : :
4561 : :
4562 : : /*
4563 : : * SyncVariables
4564 : : *
4565 : : * Make psql's internal variables agree with connection state upon
4566 : : * establishing a new connection.
4567 : : */
4568 : : void
8428 tgl@sss.pgh.pa.us 4569 :CBC 10642 : SyncVariables(void)
4570 : : {
4571 : : char vbuf[32];
4572 : : const char *server_version;
4573 : : char *service_name;
4574 : : char *service_file;
4575 : :
4576 : : /* get stuff from connection */
4577 : 10642 : pset.encoding = PQclientEncoding(pset.db);
4578 : 10642 : pset.popt.topt.encoding = pset.encoding;
7270 4579 : 10642 : pset.sversion = PQserverVersion(pset.db);
4580 : :
530 andres@anarazel.de 4581 : 10642 : setFmtEncoding(pset.encoding);
4582 : :
9600 bruce@momjian.us 4583 : 10642 : SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4584 : 10642 : SetVariable(pset.vars, "USER", PQuser(pset.db));
4585 : 10642 : SetVariable(pset.vars, "HOST", PQhost(pset.db));
4586 : 10642 : SetVariable(pset.vars, "PORT", PQport(pset.db));
4587 : 10642 : SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
4588 : :
381 michael@paquier.xyz 4589 : 10642 : service_name = get_conninfo_value("service");
4590 : 10642 : SetVariable(pset.vars, "SERVICE", service_name);
4591 [ + + ]: 10642 : if (service_name)
4592 : 12 : pg_free(service_name);
4593 : :
376 4594 : 10642 : service_file = get_conninfo_value("servicefile");
4595 : 10642 : SetVariable(pset.vars, "SERVICEFILE", service_file);
4596 [ + + ]: 10642 : if (service_file)
4597 : 12 : pg_free(service_file);
4598 : :
4599 : : /* this bit should match connection_warnings(): */
4600 : : /* Try to get full text form of version, might include "devel" etc */
3245 tgl@sss.pgh.pa.us 4601 : 10642 : server_version = PQparameterStatus(pset.db, "server_version");
4602 : : /* Otherwise fall back on pset.sversion */
4603 [ - + ]: 10642 : if (!server_version)
4604 : : {
3245 tgl@sss.pgh.pa.us 4605 :UBC 0 : formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4606 : 0 : server_version = vbuf;
4607 : : }
3245 tgl@sss.pgh.pa.us 4608 :CBC 10642 : SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4609 : :
4610 : 10642 : snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4611 : 10642 : SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4612 : :
4613 : : /* send stuff to it, too */
7270 4614 : 10642 : PQsetErrorVerbosity(pset.db, pset.verbosity);
3976 4615 : 10642 : PQsetErrorContextVisibility(pset.db, pset.show_context);
9760 bruce@momjian.us 4616 : 10642 : }
4617 : :
4618 : : /*
4619 : : * UnsyncVariables
4620 : : *
4621 : : * Clear variables that should be not be set when there is no connection.
4622 : : */
4623 : : void
8428 tgl@sss.pgh.pa.us 4624 :UBC 0 : UnsyncVariables(void)
4625 : : {
4626 : 0 : SetVariable(pset.vars, "DBNAME", NULL);
584 michael@paquier.xyz 4627 : 0 : SetVariable(pset.vars, "SERVICE", NULL);
376 4628 : 0 : SetVariable(pset.vars, "SERVICEFILE", NULL);
8428 tgl@sss.pgh.pa.us 4629 : 0 : SetVariable(pset.vars, "USER", NULL);
4630 : 0 : SetVariable(pset.vars, "HOST", NULL);
4631 : 0 : SetVariable(pset.vars, "PORT", NULL);
4632 : 0 : SetVariable(pset.vars, "ENCODING", NULL);
3245 4633 : 0 : SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4634 : 0 : SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
9674 peter_e@gmx.net 4635 : 0 : }
4636 : :
4637 : :
4638 : : /*
4639 : : * helper for do_edit(): actually invoke the editor
4640 : : *
4641 : : * Returns true on success, false if we failed to invoke the editor or
4642 : : * it returned nonzero status. (An error message is printed for failed-
4643 : : * to-invoke cases, but not if the editor returns nonzero status.)
4644 : : */
4645 : : static bool
5826 tgl@sss.pgh.pa.us 4646 : 0 : editFile(const char *fname, int lineno)
4647 : : {
4648 : : const char *editorName;
5480 peter_e@gmx.net 4649 : 0 : const char *editor_lineno_arg = NULL;
4650 : : char *sys;
4651 : : int result;
4652 : :
4971 andrew@dunslane.net 4653 [ # # ]: 0 : Assert(fname != NULL);
4654 : :
4655 : : /* Find an editor to use */
9760 bruce@momjian.us 4656 : 0 : editorName = getenv("PSQL_EDITOR");
4657 [ # # ]: 0 : if (!editorName)
4658 : 0 : editorName = getenv("EDITOR");
4659 [ # # ]: 0 : if (!editorName)
4660 : 0 : editorName = getenv("VISUAL");
4661 [ # # ]: 0 : if (!editorName)
4662 : 0 : editorName = DEFAULT_EDITOR;
4663 : :
4664 : : /* Get line number argument, if we need it. */
5826 tgl@sss.pgh.pa.us 4665 [ # # ]: 0 : if (lineno > 0)
4666 : : {
5480 peter_e@gmx.net 4667 : 0 : editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4668 : : #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4669 [ # # ]: 0 : if (!editor_lineno_arg)
4670 : 0 : editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4671 : : #endif
4672 [ # # ]: 0 : if (!editor_lineno_arg)
4673 : : {
2672 peter@eisentraut.org 4674 : 0 : pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
5826 tgl@sss.pgh.pa.us 4675 : 0 : return false;
4676 : : }
4677 : : }
4678 : :
4679 : : /*
4680 : : * On Unix the EDITOR value should *not* be quoted, since it might include
4681 : : * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4682 : : * if necessary. But this policy is not very workable on Windows, due to
4683 : : * severe brain damage in their command shell plus the fact that standard
4684 : : * program paths include spaces.
4685 : : */
4686 : : #ifndef WIN32
4687 [ # # ]: 0 : if (lineno > 0)
4659 4688 : 0 : sys = psprintf("exec %s %s%d '%s'",
4689 : : editorName, editor_lineno_arg, lineno, fname);
4690 : : else
4691 : 0 : sys = psprintf("exec %s '%s'",
4692 : : editorName, fname);
4693 : : #else
4694 : : if (lineno > 0)
4695 : : sys = psprintf("\"%s\" %s%d \"%s\"",
4696 : : editorName, editor_lineno_arg, lineno, fname);
4697 : : else
4698 : : sys = psprintf("\"%s\" \"%s\"",
4699 : : editorName, fname);
4700 : : #endif
1426 4701 : 0 : fflush(NULL);
9760 bruce@momjian.us 4702 : 0 : result = system(sys);
9685 peter_e@gmx.net 4703 [ # # ]: 0 : if (result == -1)
2672 peter@eisentraut.org 4704 : 0 : pg_log_error("could not start editor \"%s\"", editorName);
9600 bruce@momjian.us 4705 [ # # ]: 0 : else if (result == 127)
2672 peter@eisentraut.org 4706 : 0 : pg_log_error("could not start /bin/sh");
24 peter@eisentraut.org 4707 :UNC 0 : pfree(sys);
4708 : :
9760 bruce@momjian.us 4709 :UBC 0 : return result == 0;
4710 : : }
4711 : :
4712 : :
4713 : : /*
4714 : : * do_edit -- handler for \e
4715 : : *
4716 : : * If you do not specify a filename, the current query buffer will be copied
4717 : : * into a temporary file.
4718 : : *
4719 : : * After this function is done, the resulting file will be copied back into the
4720 : : * query buffer. As an exception to this, the query buffer will be emptied
4721 : : * if the file was not modified (or the editor failed) and the caller passes
4722 : : * "discard_on_quit" = true.
4723 : : *
4724 : : * If "edited" isn't NULL, *edited will be set to true if the query buffer
4725 : : * is successfully replaced.
4726 : : */
4727 : : static bool
5826 tgl@sss.pgh.pa.us 4728 : 0 : do_edit(const char *filename_arg, PQExpBuffer query_buf,
4729 : : int lineno, bool discard_on_quit, bool *edited)
4730 : : {
4731 : : char fnametmp[MAXPGPATH];
9372 peter_e@gmx.net 4732 : 0 : FILE *stream = NULL;
4733 : : const char *fname;
9760 bruce@momjian.us 4734 : 0 : bool error = false;
4735 : : int fd;
4736 : : struct stat before,
4737 : : after;
4738 : :
4739 [ # # ]: 0 : if (filename_arg)
4740 : 0 : fname = filename_arg;
4741 : : else
4742 : : {
4743 : : /* make a temp file to edit */
4744 : : #ifndef WIN32
7933 4745 : 0 : const char *tmpdir = getenv("TMPDIR");
4746 : :
4747 [ # # ]: 0 : if (!tmpdir)
4748 : 0 : tmpdir = "/tmp";
4749 : : #else
4750 : : char tmpdir[MAXPGPATH];
4751 : : int ret;
4752 : :
4753 : : ret = GetTempPath(MAXPGPATH, tmpdir);
4754 : : if (ret == 0 || ret > MAXPGPATH)
4755 : : {
4756 : : pg_log_error("could not locate temporary directory: %s",
4757 : : !ret ? strerror(errno) : "");
4758 : : return false;
4759 : : }
4760 : : #endif
4761 : :
4762 : : /*
4763 : : * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4764 : : * current directory to the supplied path unless we use only
4765 : : * backslashes, so we do that.
4766 : : */
4767 : : #ifndef WIN32
5349 peter_e@gmx.net 4768 : 0 : snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
7588 bruce@momjian.us 4769 : 0 : "/", (int) getpid());
4770 : : #else
4771 : : snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4772 : : "" /* trailing separator already present */ , (int) getpid());
4773 : : #endif
4774 : :
9760 4775 : 0 : fname = (const char *) fnametmp;
4776 : :
9256 4777 : 0 : fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
9373 4778 [ # # ]: 0 : if (fd != -1)
4779 : 0 : stream = fdopen(fd, "w");
4780 : :
4781 [ # # # # ]: 0 : if (fd == -1 || !stream)
4782 : : {
2672 peter@eisentraut.org 4783 : 0 : pg_log_error("could not open temporary file \"%s\": %m", fname);
9760 bruce@momjian.us 4784 : 0 : error = true;
4785 : : }
4786 : : else
4787 : : {
4788 : 0 : unsigned int ql = query_buf->len;
4789 : :
4790 : : /* force newline-termination of what we send to editor */
2437 tgl@sss.pgh.pa.us 4791 [ # # # # ]: 0 : if (ql > 0 && query_buf->data[ql - 1] != '\n')
4792 : : {
9760 bruce@momjian.us 4793 : 0 : appendPQExpBufferChar(query_buf, '\n');
4794 : 0 : ql++;
4795 : : }
4796 : :
4797 [ # # ]: 0 : if (fwrite(query_buf->data, 1, ql, stream) != ql)
4798 : : {
2672 peter@eisentraut.org 4799 : 0 : pg_log_error("%s: %m", fname);
4800 : :
4529 sfrost@snowman.net 4801 [ # # ]: 0 : if (fclose(stream) != 0)
2672 peter@eisentraut.org 4802 : 0 : pg_log_error("%s: %m", fname);
4803 : :
4529 sfrost@snowman.net 4804 [ # # ]: 0 : if (remove(fname) != 0)
2672 peter@eisentraut.org 4805 : 0 : pg_log_error("%s: %m", fname);
4806 : :
9760 bruce@momjian.us 4807 : 0 : error = true;
4808 : : }
8216 tgl@sss.pgh.pa.us 4809 [ # # ]: 0 : else if (fclose(stream) != 0)
4810 : : {
2672 peter@eisentraut.org 4811 : 0 : pg_log_error("%s: %m", fname);
4529 sfrost@snowman.net 4812 [ # # ]: 0 : if (remove(fname) != 0)
2672 peter@eisentraut.org 4813 : 0 : pg_log_error("%s: %m", fname);
8216 tgl@sss.pgh.pa.us 4814 : 0 : error = true;
4815 : : }
4816 : : else
4817 : : {
4818 : : struct utimbuf ut;
4819 : :
4820 : : /*
4821 : : * Try to set the file modification time of the temporary file
4822 : : * a few seconds in the past. Otherwise, the low granularity
4823 : : * (one second, or even worse on some filesystems) that we can
4824 : : * portably measure with stat(2) could lead us to not
4825 : : * recognize a modification, if the user typed very quickly.
4826 : : *
4827 : : * This is a rather unlikely race condition, so don't error
4828 : : * out if the utime(2) call fails --- that would make the cure
4829 : : * worse than the disease.
4830 : : */
1961 4831 : 0 : ut.modtime = ut.actime = time(NULL) - 2;
4832 : 0 : (void) utime(fname, &ut);
4833 : : }
4834 : : }
4835 : : }
4836 : :
9760 bruce@momjian.us 4837 [ # # # # ]: 0 : if (!error && stat(fname, &before) != 0)
4838 : : {
2672 peter@eisentraut.org 4839 : 0 : pg_log_error("%s: %m", fname);
9760 bruce@momjian.us 4840 : 0 : error = true;
4841 : : }
4842 : :
4843 : : /* call editor */
4844 [ # # ]: 0 : if (!error)
5826 tgl@sss.pgh.pa.us 4845 : 0 : error = !editFile(fname, lineno);
4846 : :
9760 bruce@momjian.us 4847 [ # # # # ]: 0 : if (!error && stat(fname, &after) != 0)
4848 : : {
2672 peter@eisentraut.org 4849 : 0 : pg_log_error("%s: %m", fname);
9760 bruce@momjian.us 4850 : 0 : error = true;
4851 : : }
4852 : :
4853 : : /* file was edited if the size or modification time has changed */
1961 tgl@sss.pgh.pa.us 4854 [ # # ]: 0 : if (!error &&
4855 [ # # ]: 0 : (before.st_size != after.st_size ||
4856 [ # # ]: 0 : before.st_mtime != after.st_mtime))
4857 : : {
8049 bruce@momjian.us 4858 : 0 : stream = fopen(fname, PG_BINARY_R);
9760 4859 [ # # ]: 0 : if (!stream)
4860 : : {
2672 peter@eisentraut.org 4861 : 0 : pg_log_error("%s: %m", fname);
9760 bruce@momjian.us 4862 : 0 : error = true;
4863 : : }
4864 : : else
4865 : : {
4866 : : /* read file back into query_buf */
4867 : : char line[1024];
4868 : :
4869 : 0 : resetPQExpBuffer(query_buf);
9371 tgl@sss.pgh.pa.us 4870 [ # # ]: 0 : while (fgets(line, sizeof(line), stream) != NULL)
9616 peter_e@gmx.net 4871 : 0 : appendPQExpBufferStr(query_buf, line);
4872 : :
9600 bruce@momjian.us 4873 [ # # ]: 0 : if (ferror(stream))
4874 : : {
2672 peter@eisentraut.org 4875 : 0 : pg_log_error("%s: %m", fname);
9600 bruce@momjian.us 4876 : 0 : error = true;
1939 tgl@sss.pgh.pa.us 4877 : 0 : resetPQExpBuffer(query_buf);
4878 : : }
6531 4879 [ # # ]: 0 : else if (edited)
4880 : : {
4881 : 0 : *edited = true;
4882 : : }
4883 : :
9760 bruce@momjian.us 4884 : 0 : fclose(stream);
4885 : : }
4886 : : }
4887 : : else
4888 : : {
4889 : : /*
4890 : : * If the file was not modified, and the caller requested it, discard
4891 : : * the query buffer.
4892 : : */
1939 tgl@sss.pgh.pa.us 4893 [ # # ]: 0 : if (discard_on_quit)
4894 : 0 : resetPQExpBuffer(query_buf);
4895 : : }
4896 : :
4897 : : /* remove temp file */
9601 bruce@momjian.us 4898 [ # # ]: 0 : if (!filename_arg)
4899 : : {
9600 4900 [ # # ]: 0 : if (remove(fname) == -1)
4901 : : {
2672 peter@eisentraut.org 4902 : 0 : pg_log_error("%s: %m", fname);
9600 bruce@momjian.us 4903 : 0 : error = true;
4904 : : }
4905 : : }
4906 : :
9760 4907 : 0 : return !error;
4908 : : }
4909 : :
4910 : :
4911 : :
4912 : : /*
4913 : : * process_file
4914 : : *
4915 : : * Reads commands from filename and passes them to the main processing loop.
4916 : : * Handler for \i and \ir, but can be used for other things as well. Returns
4917 : : * MainLoop() error code.
4918 : : *
4919 : : * If use_relative_path is true and filename is not an absolute path, then open
4920 : : * the file from where the currently processed file (if any) is located.
4921 : : */
4922 : : int
3882 rhaas@postgresql.org 4923 :CBC 10152 : process_file(char *filename, bool use_relative_path)
4924 : : {
4925 : : FILE *fd;
4926 : : int result;
4927 : : char *oldfilename;
4928 : : char relpath[MAXPGPATH];
4929 : :
9760 bruce@momjian.us 4930 [ + + ]: 10152 : if (!filename)
4931 : : {
5098 rhaas@postgresql.org 4932 : 2754 : fd = stdin;
4933 : 2754 : filename = NULL;
4934 : : }
4935 [ + + ]: 7398 : else if (strcmp(filename, "-") != 0)
4936 : : {
542 tgl@sss.pgh.pa.us 4937 : 22 : canonicalize_path_enc(filename, pset.encoding);
4938 : :
4939 : : /*
4940 : : * If we were asked to resolve the pathname relative to the location
4941 : : * of the currently executing script, and there is one, and this is a
4942 : : * relative pathname, then prepend all but the last pathname component
4943 : : * of the current script to this pathname.
4944 : : */
5133 4945 [ - + - - ]: 22 : if (use_relative_path && pset.inputfile &&
5133 tgl@sss.pgh.pa.us 4946 [ # # # # ]:UBC 0 : !is_absolute_path(filename) && !has_drive_prefix(filename))
4947 : : {
4948 : 0 : strlcpy(relpath, pset.inputfile, sizeof(relpath));
5498 rhaas@postgresql.org 4949 : 0 : get_parent_directory(relpath);
4950 : 0 : join_path_components(relpath, relpath, filename);
542 tgl@sss.pgh.pa.us 4951 : 0 : canonicalize_path_enc(relpath, pset.encoding);
4952 : :
5498 rhaas@postgresql.org 4953 : 0 : filename = relpath;
4954 : : }
4955 : :
6080 bruce@momjian.us 4956 :CBC 22 : fd = fopen(filename, PG_BINARY_R);
4957 : :
5259 peter_e@gmx.net 4958 [ - + ]: 22 : if (!fd)
4959 : : {
2672 peter@eisentraut.org 4960 :UBC 0 : pg_log_error("%s: %m", filename);
5259 peter_e@gmx.net 4961 : 0 : return EXIT_FAILURE;
4962 : : }
4963 : : }
4964 : : else
4965 : : {
5259 peter_e@gmx.net 4966 :CBC 7376 : fd = stdin;
4967 : 7376 : filename = "<stdin>"; /* for future error messages */
4968 : : }
4969 : :
9600 bruce@momjian.us 4970 : 10152 : oldfilename = pset.inputfile;
4971 : 10152 : pset.inputfile = filename;
4972 : :
2672 peter@eisentraut.org 4973 : 10152 : pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4974 : :
9685 peter_e@gmx.net 4975 : 10152 : result = MainLoop(fd);
4976 : :
5751 rhaas@postgresql.org 4977 [ + + ]: 10137 : if (fd != stdin)
4978 : 22 : fclose(fd);
4979 : :
9680 peter_e@gmx.net 4980 : 10137 : pset.inputfile = oldfilename;
4981 : :
2672 peter@eisentraut.org 4982 : 10137 : pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4983 : :
9652 peter_e@gmx.net 4984 : 10137 : return result;
4985 : : }
4986 : :
4987 : :
4988 : :
4989 : : static const char *
9760 bruce@momjian.us 4990 : 5 : _align2string(enum printFormat in)
4991 : : {
4992 [ - + - - : 5 : switch (in)
- - - - -
+ - ]
4993 : : {
9039 bruce@momjian.us 4994 :UBC 0 : case PRINT_NOTHING:
9760 4995 : 0 : return "nothing";
4996 : : break;
9760 bruce@momjian.us 4997 :CBC 4 : case PRINT_ALIGNED:
4998 : 4 : return "aligned";
4999 : : break;
2818 michael@paquier.xyz 5000 :UBC 0 : case PRINT_ASCIIDOC:
5001 : 0 : return "asciidoc";
5002 : : break;
2798 tgl@sss.pgh.pa.us 5003 : 0 : case PRINT_CSV:
5004 : 0 : return "csv";
5005 : : break;
9760 bruce@momjian.us 5006 : 0 : case PRINT_HTML:
5007 : 0 : return "html";
5008 : : break;
5009 : 0 : case PRINT_LATEX:
5010 : 0 : return "latex";
5011 : : break;
4937 5012 : 0 : case PRINT_LATEX_LONGTABLE:
5013 : 0 : return "latex-longtable";
5014 : : break;
7716 5015 : 0 : case PRINT_TROFF_MS:
5016 : 0 : return "troff-ms";
5017 : : break;
2818 michael@paquier.xyz 5018 : 0 : case PRINT_UNALIGNED:
5019 : 0 : return "unaligned";
5020 : : break;
2818 michael@paquier.xyz 5021 :CBC 1 : case PRINT_WRAPPED:
5022 : 1 : return "wrapped";
5023 : : break;
5024 : : }
9760 bruce@momjian.us 5025 :UBC 0 : return "unknown";
5026 : : }
5027 : :
5028 : : /*
5029 : : * Parse entered Unicode linestyle. If ok, update *linestyle and return
5030 : : * true, else return false.
5031 : : */
5032 : : static bool
3917 tgl@sss.pgh.pa.us 5033 : 0 : set_unicode_line_style(const char *value, size_t vallen,
5034 : : unicode_linestyle *linestyle)
5035 : : {
4334 sfrost@snowman.net 5036 [ # # ]: 0 : if (pg_strncasecmp("single", value, vallen) == 0)
5037 : 0 : *linestyle = UNICODE_LINESTYLE_SINGLE;
5038 [ # # ]: 0 : else if (pg_strncasecmp("double", value, vallen) == 0)
5039 : 0 : *linestyle = UNICODE_LINESTYLE_DOUBLE;
5040 : : else
5041 : 0 : return false;
5042 : 0 : return true;
5043 : : }
5044 : :
5045 : : static const char *
4334 sfrost@snowman.net 5046 :CBC 12 : _unicode_linestyle2string(int linestyle)
5047 : : {
5048 [ + - - ]: 12 : switch (linestyle)
5049 : : {
5050 : 12 : case UNICODE_LINESTYLE_SINGLE:
5051 : 12 : return "single";
5052 : : break;
4334 sfrost@snowman.net 5053 :UBC 0 : case UNICODE_LINESTYLE_DOUBLE:
5054 : 0 : return "double";
5055 : : break;
5056 : : }
5057 : 0 : return "unknown";
5058 : : }
5059 : :
5060 : : /*
5061 : : * do_pset
5062 : : *
5063 : : * Performs the assignment "param = value", where value could be NULL;
5064 : : * for some params that has an effect such as inversion, for others
5065 : : * it does nothing.
5066 : : *
5067 : : * Adjusts the state of the formatting options at *popt. (In practice that
5068 : : * is always pset.popt, but maybe someday it could be different.)
5069 : : *
5070 : : * If successful and quiet is false, then invokes printPsetInfo() to report
5071 : : * the change.
5072 : : *
5073 : : * Returns true if successful, else false (eg for invalid param or value).
5074 : : */
5075 : : bool
9600 bruce@momjian.us 5076 :CBC 1405 : do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
5077 : : {
9760 5078 : 1405 : size_t vallen = 0;
5079 : :
4971 andrew@dunslane.net 5080 [ - + ]: 1405 : Assert(param != NULL);
5081 : :
9760 bruce@momjian.us 5082 [ + + ]: 1405 : if (value)
5083 : 1299 : vallen = strlen(value);
5084 : :
5085 : : /* set format */
5086 [ + + ]: 1405 : if (strcmp(param, "format") == 0)
5087 : : {
5088 : : static const struct fmt
5089 : : {
5090 : : const char *name;
5091 : : enum printFormat number;
5092 : : } formats[] =
5093 : : {
5094 : : /* remember to update error message below when adding more */
5095 : : {"aligned", PRINT_ALIGNED},
5096 : : {"asciidoc", PRINT_ASCIIDOC},
5097 : : {"csv", PRINT_CSV},
5098 : : {"html", PRINT_HTML},
5099 : : {"latex", PRINT_LATEX},
5100 : : {"troff-ms", PRINT_TROFF_MS},
5101 : : {"unaligned", PRINT_UNALIGNED},
5102 : : {"wrapped", PRINT_WRAPPED}
5103 : : };
5104 : :
5105 [ + - ]: 449 : if (!value)
5106 : : ;
5107 : : else
5108 : : {
2810 tgl@sss.pgh.pa.us 5109 : 449 : int match_pos = -1;
5110 : :
14 peter@eisentraut.org 5111 [ + + ]:GNC 4013 : for (size_t i = 0; i < lengthof(formats); i++)
5112 : : {
2810 tgl@sss.pgh.pa.us 5113 [ + + ]:CBC 3568 : if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
5114 : : {
5115 [ + + ]: 449 : if (match_pos < 0)
5116 : 445 : match_pos = i;
5117 : : else
5118 : : {
2672 peter@eisentraut.org 5119 : 4 : pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
5120 : : value,
5121 : : formats[match_pos].name, formats[i].name);
2810 tgl@sss.pgh.pa.us 5122 : 4 : return false;
5123 : : }
5124 : : }
5125 : : }
2798 5126 [ + + ]: 445 : if (match_pos >= 0)
5127 : 441 : popt->topt.format = formats[match_pos].number;
5128 [ + - ]: 4 : else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
5129 : : {
5130 : : /*
5131 : : * We must treat latex-longtable specially because latex is a
5132 : : * prefix of it; if both were in the table above, we'd think
5133 : : * "latex" is ambiguous.
5134 : : */
5135 : 4 : popt->topt.format = PRINT_LATEX_LONGTABLE;
5136 : : }
5137 : : else
5138 : : {
2672 peter@eisentraut.org 5139 :UBC 0 : pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
2810 tgl@sss.pgh.pa.us 5140 : 0 : return false;
5141 : : }
5142 : : }
5143 : : }
5144 : :
5145 : : /* set table line style */
6129 tgl@sss.pgh.pa.us 5146 [ + + ]:CBC 956 : else if (strcmp(param, "linestyle") == 0)
5147 : : {
5148 [ + - ]: 20 : if (!value)
5149 : : ;
5150 [ + + ]: 20 : else if (pg_strncasecmp("ascii", value, vallen) == 0)
5151 : 12 : popt->topt.line_style = &pg_asciiformat;
6089 5152 [ + - ]: 8 : else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
5153 : 8 : popt->topt.line_style = &pg_asciiformat_old;
6129 tgl@sss.pgh.pa.us 5154 [ # # ]:UBC 0 : else if (pg_strncasecmp("unicode", value, vallen) == 0)
5155 : 0 : popt->topt.line_style = &pg_utf8format;
5156 : : else
5157 : : {
2672 peter@eisentraut.org 5158 : 0 : pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
6129 tgl@sss.pgh.pa.us 5159 : 0 : return false;
5160 : : }
5161 : : }
5162 : :
5163 : : /* set unicode border line style */
4334 sfrost@snowman.net 5164 [ - + ]:CBC 936 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5165 : : {
4334 sfrost@snowman.net 5166 [ # # ]:UBC 0 : if (!value)
5167 : : ;
3917 tgl@sss.pgh.pa.us 5168 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5169 : : &popt->topt.unicode_border_linestyle))
5170 : 0 : refresh_utf8format(&(popt->topt));
5171 : : else
5172 : : {
2672 peter@eisentraut.org 5173 : 0 : pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4334 sfrost@snowman.net 5174 : 0 : return false;
5175 : : }
5176 : : }
5177 : :
5178 : : /* set unicode column line style */
4334 sfrost@snowman.net 5179 [ - + ]:CBC 936 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5180 : : {
4334 sfrost@snowman.net 5181 [ # # ]:UBC 0 : if (!value)
5182 : : ;
3917 tgl@sss.pgh.pa.us 5183 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5184 : : &popt->topt.unicode_column_linestyle))
5185 : 0 : refresh_utf8format(&(popt->topt));
5186 : : else
5187 : : {
2672 peter@eisentraut.org 5188 : 0 : pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4334 sfrost@snowman.net 5189 : 0 : return false;
5190 : : }
5191 : : }
5192 : :
5193 : : /* set unicode header line style */
4334 sfrost@snowman.net 5194 [ - + ]:CBC 936 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5195 : : {
4334 sfrost@snowman.net 5196 [ # # ]:UBC 0 : if (!value)
5197 : : ;
3917 tgl@sss.pgh.pa.us 5198 [ # # ]: 0 : else if (set_unicode_line_style(value, vallen,
5199 : : &popt->topt.unicode_header_linestyle))
5200 : 0 : refresh_utf8format(&(popt->topt));
5201 : : else
5202 : : {
2672 peter@eisentraut.org 5203 : 0 : pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4334 sfrost@snowman.net 5204 : 0 : return false;
5205 : : }
5206 : : }
5207 : :
5208 : : /* set border style/width */
9760 bruce@momjian.us 5209 [ + + ]:CBC 936 : else if (strcmp(param, "border") == 0)
5210 : : {
5211 [ + - ]: 272 : if (value)
5212 : 272 : popt->topt.border = atoi(value);
5213 : : }
5214 : :
5215 : : /* set expanded/vertical mode */
4224 tgl@sss.pgh.pa.us 5216 [ + - ]: 664 : else if (strcmp(param, "x") == 0 ||
5217 [ + + ]: 664 : strcmp(param, "expanded") == 0 ||
5218 [ - + ]: 440 : strcmp(param, "vertical") == 0)
5219 : : {
5369 peter_e@gmx.net 5220 [ + + - + ]: 224 : if (value && pg_strcasecmp(value, "auto") == 0)
5369 peter_e@gmx.net 5221 :UBC 0 : popt->topt.expanded = 2;
5369 peter_e@gmx.net 5222 [ + + ]:CBC 224 : else if (value)
5223 : : {
5224 : : bool on_off;
5225 : :
3463 tgl@sss.pgh.pa.us 5226 [ + - ]: 178 : if (ParseVariableBool(value, NULL, &on_off))
5227 : 178 : popt->topt.expanded = on_off ? 1 : 0;
5228 : : else
5229 : : {
3463 tgl@sss.pgh.pa.us 5230 :UBC 0 : PsqlVarEnumError(param, value, "on, off, auto");
5231 : 0 : return false;
5232 : : }
5233 : : }
5234 : : else
7084 bruce@momjian.us 5235 :CBC 46 : popt->topt.expanded = !popt->topt.expanded;
5236 : : }
5237 : :
5238 : : /* header line width in expanded mode */
1461 andrew@dunslane.net 5239 [ - + ]: 440 : else if (strcmp(param, "xheader_width") == 0)
5240 : : {
1163 tgl@sss.pgh.pa.us 5241 [ # # ]:UBC 0 : if (!value)
5242 : : ;
1461 andrew@dunslane.net 5243 [ # # ]: 0 : else if (pg_strcasecmp(value, "full") == 0)
5244 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_FULL;
5245 [ # # ]: 0 : else if (pg_strcasecmp(value, "column") == 0)
5246 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_COLUMN;
5247 [ # # ]: 0 : else if (pg_strcasecmp(value, "page") == 0)
5248 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_PAGE;
5249 : : else
5250 : : {
1163 alvherre@alvh.no-ip. 5251 : 0 : int intval = atoi(value);
5252 : :
5253 [ # # ]: 0 : if (intval == 0)
5254 : : {
peter@eisentraut.org 5255 : 0 : pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
1461 andrew@dunslane.net 5256 : 0 : return false;
5257 : : }
5258 : :
1163 alvherre@alvh.no-ip. 5259 : 0 : popt->topt.expanded_header_width_type = PRINT_XHEADER_EXACT_WIDTH;
5260 : 0 : popt->topt.expanded_header_exact_width = intval;
5261 : : }
5262 : : }
5263 : :
5264 : : /* field separator for CSV format */
2798 tgl@sss.pgh.pa.us 5265 [ + + ]:CBC 440 : else if (strcmp(param, "csv_fieldsep") == 0)
5266 : : {
5267 [ + - ]: 40 : if (value)
5268 : : {
5269 : : /* CSV separator has to be a one-byte character */
5270 [ + + ]: 40 : if (strlen(value) != 1)
5271 : : {
2672 peter@eisentraut.org 5272 : 12 : pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
2798 tgl@sss.pgh.pa.us 5273 : 12 : return false;
5274 : : }
5275 [ + + + + : 28 : if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
+ + ]
5276 : : {
2672 peter@eisentraut.org 5277 : 12 : pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
2798 tgl@sss.pgh.pa.us 5278 : 12 : return false;
5279 : : }
5280 : 16 : popt->topt.csvFieldSep[0] = value[0];
5281 : : }
5282 : : }
5283 : :
5284 : : /* locale-aware numeric output */
7677 bruce@momjian.us 5285 [ + + ]: 400 : else if (strcmp(param, "numericlocale") == 0)
5286 : : {
7084 5287 [ + - ]: 8 : if (value)
3463 tgl@sss.pgh.pa.us 5288 : 8 : return ParseVariableBool(value, param, &popt->topt.numericLocale);
5289 : : else
7084 bruce@momjian.us 5290 :UBC 0 : popt->topt.numericLocale = !popt->topt.numericLocale;
5291 : : }
5292 : :
5293 : : /* null display */
9760 bruce@momjian.us 5294 [ + + ]:CBC 392 : else if (strcmp(param, "null") == 0)
5295 : : {
5296 [ + + ]: 79 : if (value)
5297 : : {
5298 : 75 : free(popt->nullPrint);
8217 neilc@samurai.com 5299 : 75 : popt->nullPrint = pg_strdup(value);
5300 : : }
5301 : : }
5302 : :
5303 : : /* 'false' display */
264 alvherre@kurilemu.de 5304 [ + + ]: 313 : else if (strcmp(param, "display_false") == 0)
5305 : : {
5306 [ + + ]: 20 : if (value)
5307 : : {
5308 : 16 : free(popt->falsePrint);
5309 : 16 : popt->falsePrint = pg_strdup(value);
5310 : : }
5311 : : }
5312 : :
5313 : : /* 'true' display */
5314 [ + + ]: 293 : else if (strcmp(param, "display_true") == 0)
5315 : : {
5316 [ + + ]: 20 : if (value)
5317 : : {
5318 : 16 : free(popt->truePrint);
5319 : 16 : popt->truePrint = pg_strdup(value);
5320 : : }
5321 : : }
5322 : :
5323 : : /* field separator for unaligned text */
9760 bruce@momjian.us 5324 [ + + ]: 273 : else if (strcmp(param, "fieldsep") == 0)
5325 : : {
5326 [ + - ]: 4 : if (value)
5327 : : {
5280 peter_e@gmx.net 5328 : 4 : free(popt->topt.fieldSep.separator);
5329 : 4 : popt->topt.fieldSep.separator = pg_strdup(value);
5330 : 4 : popt->topt.fieldSep.separator_zero = false;
5331 : : }
5332 : : }
5333 : :
5334 [ - + ]: 269 : else if (strcmp(param, "fieldsep_zero") == 0)
5335 : : {
5280 peter_e@gmx.net 5336 :UBC 0 : free(popt->topt.fieldSep.separator);
5337 : 0 : popt->topt.fieldSep.separator = NULL;
5338 : 0 : popt->topt.fieldSep.separator_zero = true;
5339 : : }
5340 : :
5341 : : /* record separator for unaligned text */
9685 peter_e@gmx.net 5342 [ - + ]:CBC 269 : else if (strcmp(param, "recordsep") == 0)
5343 : : {
9685 peter_e@gmx.net 5344 [ # # ]:UBC 0 : if (value)
5345 : : {
5280 5346 : 0 : free(popt->topt.recordSep.separator);
5347 : 0 : popt->topt.recordSep.separator = pg_strdup(value);
5348 : 0 : popt->topt.recordSep.separator_zero = false;
5349 : : }
5350 : : }
5351 : :
5280 peter_e@gmx.net 5352 [ - + ]:CBC 269 : else if (strcmp(param, "recordsep_zero") == 0)
5353 : : {
5280 peter_e@gmx.net 5354 :UBC 0 : free(popt->topt.recordSep.separator);
5355 : 0 : popt->topt.recordSep.separator = NULL;
5356 : 0 : popt->topt.recordSep.separator_zero = true;
5357 : : }
5358 : :
5359 : : /* toggle between full and tuples-only format */
9760 bruce@momjian.us 5360 [ + - + + ]:CBC 269 : else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5361 : : {
7084 5362 [ + + ]: 201 : if (value)
3463 tgl@sss.pgh.pa.us 5363 : 169 : return ParseVariableBool(value, param, &popt->topt.tuples_only);
5364 : : else
7084 bruce@momjian.us 5365 : 32 : popt->topt.tuples_only = !popt->topt.tuples_only;
5366 : : }
5367 : :
5368 : : /* set title override */
3946 5369 [ + - + + ]: 68 : else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5370 : : {
9760 5371 : 4 : free(popt->title);
5372 [ - + ]: 4 : if (!value)
9760 bruce@momjian.us 5373 :UBC 0 : popt->title = NULL;
5374 : : else
8217 neilc@samurai.com 5375 :CBC 4 : popt->title = pg_strdup(value);
5376 : : }
5377 : :
5378 : : /* set HTML table tag options */
9760 bruce@momjian.us 5379 [ + - + + ]: 64 : else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5380 : : {
5381 : 32 : free(popt->topt.tableAttr);
5382 [ + + ]: 32 : if (!value)
5383 : 16 : popt->topt.tableAttr = NULL;
5384 : : else
8217 neilc@samurai.com 5385 : 16 : popt->topt.tableAttr = pg_strdup(value);
5386 : : }
5387 : :
5388 : : /* toggle use of pager */
9760 bruce@momjian.us 5389 [ - + ]: 32 : else if (strcmp(param, "pager") == 0)
5390 : : {
8114 tgl@sss.pgh.pa.us 5391 [ # # # # ]:UBC 0 : if (value && pg_strcasecmp(value, "always") == 0)
8391 bruce@momjian.us 5392 : 0 : popt->topt.pager = 2;
7084 5393 [ # # ]: 0 : else if (value)
5394 : : {
5395 : : bool on_off;
5396 : :
3463 tgl@sss.pgh.pa.us 5397 [ # # ]: 0 : if (!ParseVariableBool(value, NULL, &on_off))
5398 : : {
5399 : 0 : PsqlVarEnumError(param, value, "on, off, always");
5400 : 0 : return false;
5401 : : }
5402 : 0 : popt->topt.pager = on_off ? 1 : 0;
5403 : : }
8660 bruce@momjian.us 5404 [ # # ]: 0 : else if (popt->topt.pager == 1)
8391 5405 : 0 : popt->topt.pager = 0;
5406 : : else
5407 : 0 : popt->topt.pager = 1;
5408 : : }
5409 : :
5410 : : /* set minimum lines for pager use */
4137 andrew@dunslane.net 5411 [ - + ]:CBC 32 : else if (strcmp(param, "pager_min_lines") == 0)
5412 : : {
1163 alvherre@alvh.no-ip. 5413 [ # # ]:UBC 0 : if (value &&
5414 [ # # ]: 0 : !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
5415 : 0 : return false;
5416 : : }
5417 : :
5418 : : /* disable "(x rows)" footer */
9205 peter_e@gmx.net 5419 [ - + ]:CBC 32 : else if (strcmp(param, "footer") == 0)
5420 : : {
7084 bruce@momjian.us 5421 [ # # ]:UBC 0 : if (value)
3463 tgl@sss.pgh.pa.us 5422 : 0 : return ParseVariableBool(value, param, &popt->topt.default_footer);
5423 : : else
5198 rhaas@postgresql.org 5424 : 0 : popt->topt.default_footer = !popt->topt.default_footer;
5425 : : }
5426 : :
5427 : : /* set border style/width */
6652 bruce@momjian.us 5428 [ + - ]:CBC 32 : else if (strcmp(param, "columns") == 0)
5429 : : {
5430 [ + - ]: 32 : if (value)
5431 : 32 : popt->topt.columns = atoi(value);
5432 : : }
5433 : : else
5434 : : {
2672 peter@eisentraut.org 5435 :UBC 0 : pg_log_error("\\pset: unknown option: %s", param);
4678 rhaas@postgresql.org 5436 : 0 : return false;
5437 : : }
5438 : :
4640 peter_e@gmx.net 5439 [ + + ]:CBC 1200 : if (!quiet)
5440 : 3 : printPsetInfo(param, &pset.popt);
5441 : :
4678 rhaas@postgresql.org 5442 : 1200 : return true;
5443 : : }
5444 : :
5445 : : /*
5446 : : * printPsetInfo: print the state of the "param" formatting parameter in popt.
5447 : : */
5448 : : static bool
2300 tgl@sss.pgh.pa.us 5449 : 3 : printPsetInfo(const char *param, printQueryOpt *popt)
5450 : : {
4678 rhaas@postgresql.org 5451 [ - + ]: 3 : Assert(param != NULL);
5452 : :
5453 : : /* show border style/width */
5454 [ - + ]: 3 : if (strcmp(param, "border") == 0)
4298 peter_e@gmx.net 5455 :UBC 0 : printf(_("Border style is %d.\n"), popt->topt.border);
5456 : :
5457 : : /* show the target width for the wrapped format */
4678 rhaas@postgresql.org 5458 [ - + ]:CBC 3 : else if (strcmp(param, "columns") == 0)
5459 : : {
4678 rhaas@postgresql.org 5460 [ # # ]:UBC 0 : if (!popt->topt.columns)
4298 peter_e@gmx.net 5461 : 0 : printf(_("Target width is unset.\n"));
5462 : : else
5463 : 0 : printf(_("Target width is %d.\n"), popt->topt.columns);
5464 : : }
5465 : :
5466 : : /* show expanded/vertical mode */
4678 rhaas@postgresql.org 5467 [ + - + + :CBC 3 : else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
- + ]
5468 : : {
5469 [ + - ]: 2 : if (popt->topt.expanded == 1)
4298 peter_e@gmx.net 5470 : 2 : printf(_("Expanded display is on.\n"));
4678 rhaas@postgresql.org 5471 [ # # ]:UBC 0 : else if (popt->topt.expanded == 2)
4298 peter_e@gmx.net 5472 : 0 : printf(_("Expanded display is used automatically.\n"));
5473 : : else
5474 : 0 : printf(_("Expanded display is off.\n"));
5475 : : }
5476 : :
5477 : : /* show xheader width value */
1461 andrew@dunslane.net 5478 [ - + ]:CBC 1 : else if (strcmp(param, "xheader_width") == 0)
5479 : : {
1461 andrew@dunslane.net 5480 [ # # ]:UBC 0 : if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
1163 peter@eisentraut.org 5481 : 0 : printf(_("Expanded header width is \"%s\".\n"), "full");
1461 andrew@dunslane.net 5482 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
1163 peter@eisentraut.org 5483 : 0 : printf(_("Expanded header width is \"%s\".\n"), "column");
1461 andrew@dunslane.net 5484 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
1163 peter@eisentraut.org 5485 : 0 : printf(_("Expanded header width is \"%s\".\n"), "page");
1461 andrew@dunslane.net 5486 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_EXACT_WIDTH)
5487 : 0 : printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
5488 : : }
5489 : :
5490 : : /* show field separator for CSV format */
2798 tgl@sss.pgh.pa.us 5491 [ - + ]:CBC 1 : else if (strcmp(param, "csv_fieldsep") == 0)
5492 : : {
2798 tgl@sss.pgh.pa.us 5493 :UBC 0 : printf(_("Field separator for CSV is \"%s\".\n"),
5494 : : popt->topt.csvFieldSep);
5495 : : }
5496 : :
5497 : : /* show boolean 'false' display */
264 alvherre@kurilemu.de 5498 [ - + ]:CBC 1 : else if (strcmp(param, "display_false") == 0)
5499 : : {
264 alvherre@kurilemu.de 5500 [ # # ]:UBC 0 : printf(_("Boolean false display is \"%s\".\n"),
5501 : : popt->falsePrint ? popt->falsePrint : "f");
5502 : : }
5503 : :
5504 : : /* show boolean 'true' display */
264 alvherre@kurilemu.de 5505 [ - + ]:CBC 1 : else if (strcmp(param, "display_true") == 0)
5506 : : {
264 alvherre@kurilemu.de 5507 [ # # ]:UBC 0 : printf(_("Boolean true display is \"%s\".\n"),
5508 : : popt->truePrint ? popt->truePrint : "t");
5509 : : }
5510 : :
5511 : : /* show field separator for unaligned text */
4678 rhaas@postgresql.org 5512 [ - + ]:CBC 1 : else if (strcmp(param, "fieldsep") == 0)
5513 : : {
4678 rhaas@postgresql.org 5514 [ # # ]:UBC 0 : if (popt->topt.fieldSep.separator_zero)
4298 peter_e@gmx.net 5515 : 0 : printf(_("Field separator is zero byte.\n"));
5516 : : else
5517 : 0 : printf(_("Field separator is \"%s\".\n"),
5518 : : popt->topt.fieldSep.separator);
5519 : : }
5520 : :
4678 rhaas@postgresql.org 5521 [ - + ]:CBC 1 : else if (strcmp(param, "fieldsep_zero") == 0)
5522 : : {
4298 peter_e@gmx.net 5523 :UBC 0 : printf(_("Field separator is zero byte.\n"));
5524 : : }
5525 : :
5526 : : /* show disable "(x rows)" footer */
4678 rhaas@postgresql.org 5527 [ - + ]:CBC 1 : else if (strcmp(param, "footer") == 0)
5528 : : {
4678 rhaas@postgresql.org 5529 [ # # ]:UBC 0 : if (popt->topt.default_footer)
4298 peter_e@gmx.net 5530 : 0 : printf(_("Default footer is on.\n"));
5531 : : else
5532 : 0 : printf(_("Default footer is off.\n"));
5533 : : }
5534 : :
5535 : : /* show format */
4678 rhaas@postgresql.org 5536 [ + - ]:CBC 1 : else if (strcmp(param, "format") == 0)
5537 : : {
4298 peter_e@gmx.net 5538 : 1 : printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
5539 : : }
5540 : :
5541 : : /* show table line style */
4678 rhaas@postgresql.org 5542 [ # # ]:UBC 0 : else if (strcmp(param, "linestyle") == 0)
5543 : : {
4298 peter_e@gmx.net 5544 : 0 : printf(_("Line style is %s.\n"),
5545 : : get_line_style(&popt->topt)->name);
5546 : : }
5547 : :
5548 : : /* show null display */
4678 rhaas@postgresql.org 5549 [ # # ]: 0 : else if (strcmp(param, "null") == 0)
5550 : : {
4298 peter_e@gmx.net 5551 [ # # ]: 0 : printf(_("Null display is \"%s\".\n"),
5552 : : popt->nullPrint ? popt->nullPrint : "");
5553 : : }
5554 : :
5555 : : /* show locale-aware numeric output */
4678 rhaas@postgresql.org 5556 [ # # ]: 0 : else if (strcmp(param, "numericlocale") == 0)
5557 : : {
5558 [ # # ]: 0 : if (popt->topt.numericLocale)
4298 peter_e@gmx.net 5559 : 0 : printf(_("Locale-adjusted numeric output is on.\n"));
5560 : : else
5561 : 0 : printf(_("Locale-adjusted numeric output is off.\n"));
5562 : : }
5563 : :
5564 : : /* show toggle use of pager */
4678 rhaas@postgresql.org 5565 [ # # ]: 0 : else if (strcmp(param, "pager") == 0)
5566 : : {
5567 [ # # ]: 0 : if (popt->topt.pager == 1)
4298 peter_e@gmx.net 5568 : 0 : printf(_("Pager is used for long output.\n"));
4678 rhaas@postgresql.org 5569 [ # # ]: 0 : else if (popt->topt.pager == 2)
4298 peter_e@gmx.net 5570 : 0 : printf(_("Pager is always used.\n"));
5571 : : else
5572 : 0 : printf(_("Pager usage is off.\n"));
5573 : : }
5574 : :
5575 : : /* show minimum lines for pager use */
4137 andrew@dunslane.net 5576 [ # # ]: 0 : else if (strcmp(param, "pager_min_lines") == 0)
5577 : : {
3923 peter_e@gmx.net 5578 : 0 : printf(ngettext("Pager won't be used for less than %d line.\n",
5579 : : "Pager won't be used for less than %d lines.\n",
5580 : : popt->topt.pager_min_lines),
5581 : : popt->topt.pager_min_lines);
5582 : : }
5583 : :
5584 : : /* show record separator for unaligned text */
4678 rhaas@postgresql.org 5585 [ # # ]: 0 : else if (strcmp(param, "recordsep") == 0)
5586 : : {
5587 [ # # ]: 0 : if (popt->topt.recordSep.separator_zero)
4298 peter_e@gmx.net 5588 : 0 : printf(_("Record separator is zero byte.\n"));
4678 rhaas@postgresql.org 5589 [ # # ]: 0 : else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
4298 peter_e@gmx.net 5590 : 0 : printf(_("Record separator is <newline>.\n"));
5591 : : else
5592 : 0 : printf(_("Record separator is \"%s\".\n"),
5593 : : popt->topt.recordSep.separator);
5594 : : }
5595 : :
4678 rhaas@postgresql.org 5596 [ # # ]: 0 : else if (strcmp(param, "recordsep_zero") == 0)
5597 : : {
4298 peter_e@gmx.net 5598 : 0 : printf(_("Record separator is zero byte.\n"));
5599 : : }
5600 : :
5601 : : /* show HTML table tag options */
4678 rhaas@postgresql.org 5602 [ # # # # ]: 0 : else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5603 : : {
5604 [ # # ]: 0 : if (popt->topt.tableAttr)
4298 peter_e@gmx.net 5605 : 0 : printf(_("Table attributes are \"%s\".\n"),
5606 : : popt->topt.tableAttr);
5607 : : else
5608 : 0 : printf(_("Table attributes unset.\n"));
5609 : : }
5610 : :
5611 : : /* show title override */
3946 bruce@momjian.us 5612 [ # # # # ]: 0 : else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5613 : : {
4678 rhaas@postgresql.org 5614 [ # # ]: 0 : if (popt->title)
4298 peter_e@gmx.net 5615 : 0 : printf(_("Title is \"%s\".\n"), popt->title);
5616 : : else
5617 : 0 : printf(_("Title is unset.\n"));
5618 : : }
5619 : :
5620 : : /* show toggle between full and tuples-only format */
4678 rhaas@postgresql.org 5621 [ # # # # ]: 0 : else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5622 : : {
5623 [ # # ]: 0 : if (popt->topt.tuples_only)
4298 peter_e@gmx.net 5624 : 0 : printf(_("Tuples only is on.\n"));
5625 : : else
5626 : 0 : printf(_("Tuples only is off.\n"));
5627 : : }
5628 : :
5629 : : /* Unicode style formatting */
4334 sfrost@snowman.net 5630 [ # # ]: 0 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5631 : : {
3887 peter_e@gmx.net 5632 : 0 : printf(_("Unicode border line style is \"%s\".\n"),
5633 : : _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5634 : : }
5635 : :
4334 sfrost@snowman.net 5636 [ # # ]: 0 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5637 : : {
3887 peter_e@gmx.net 5638 : 0 : printf(_("Unicode column line style is \"%s\".\n"),
5639 : : _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5640 : : }
5641 : :
4334 sfrost@snowman.net 5642 [ # # ]: 0 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5643 : : {
3887 peter_e@gmx.net 5644 : 0 : printf(_("Unicode header line style is \"%s\".\n"),
5645 : : _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
5646 : : }
5647 : :
5648 : : else
5649 : : {
2672 peter@eisentraut.org 5650 : 0 : pg_log_error("\\pset: unknown option: %s", param);
9760 bruce@momjian.us 5651 : 0 : return false;
5652 : : }
5653 : :
9760 bruce@momjian.us 5654 :CBC 3 : return true;
5655 : : }
5656 : :
5657 : : /*
5658 : : * savePsetInfo: make a malloc'd copy of the data in *popt.
5659 : : *
5660 : : * Possibly this should be somewhere else, but it's a bit specific to psql.
5661 : : */
5662 : : printQueryOpt *
2300 tgl@sss.pgh.pa.us 5663 : 94 : savePsetInfo(const printQueryOpt *popt)
5664 : : {
5665 : : printQueryOpt *save;
5666 : :
148 michael@paquier.xyz 5667 : 94 : save = pg_malloc_object(printQueryOpt);
5668 : :
5669 : : /* Flat-copy all the scalar fields, then duplicate sub-structures. */
2300 tgl@sss.pgh.pa.us 5670 : 94 : memcpy(save, popt, sizeof(printQueryOpt));
5671 : :
5672 : : /* topt.line_style points to const data that need not be duplicated */
5673 [ + - ]: 94 : if (popt->topt.fieldSep.separator)
5674 : 94 : save->topt.fieldSep.separator = pg_strdup(popt->topt.fieldSep.separator);
5675 [ + - ]: 94 : if (popt->topt.recordSep.separator)
5676 : 94 : save->topt.recordSep.separator = pg_strdup(popt->topt.recordSep.separator);
5677 [ - + ]: 94 : if (popt->topt.tableAttr)
2300 tgl@sss.pgh.pa.us 5678 :UBC 0 : save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
2300 tgl@sss.pgh.pa.us 5679 [ - + ]:CBC 94 : if (popt->nullPrint)
2300 tgl@sss.pgh.pa.us 5680 :UBC 0 : save->nullPrint = pg_strdup(popt->nullPrint);
74 bruce@momjian.us 5681 [ - + ]:CBC 94 : if (popt->truePrint)
74 bruce@momjian.us 5682 :UBC 0 : save->truePrint = pg_strdup(popt->truePrint);
74 bruce@momjian.us 5683 [ - + ]:CBC 94 : if (popt->falsePrint)
74 bruce@momjian.us 5684 :UBC 0 : save->falsePrint = pg_strdup(popt->falsePrint);
2300 tgl@sss.pgh.pa.us 5685 [ - + ]:CBC 94 : if (popt->title)
2300 tgl@sss.pgh.pa.us 5686 :UBC 0 : save->title = pg_strdup(popt->title);
5687 : :
5688 : : /*
5689 : : * footers and translate_columns are never set in psql's print settings,
5690 : : * so we needn't write code to duplicate them.
5691 : : */
2300 tgl@sss.pgh.pa.us 5692 [ - + ]:CBC 94 : Assert(popt->footers == NULL);
5693 [ - + ]: 94 : Assert(popt->translate_columns == NULL);
5694 : :
5695 : 94 : return save;
5696 : : }
5697 : :
5698 : : /*
5699 : : * restorePsetInfo: restore *popt from the previously-saved copy *save,
5700 : : * then free *save.
5701 : : */
5702 : : void
5703 : 94 : restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
5704 : : {
5705 : : /* Free all the old data we're about to overwrite the pointers to. */
5706 : :
5707 : : /* topt.line_style points to const data that need not be duplicated */
1500 peter@eisentraut.org 5708 : 94 : free(popt->topt.fieldSep.separator);
5709 : 94 : free(popt->topt.recordSep.separator);
5710 : 94 : free(popt->topt.tableAttr);
5711 : 94 : free(popt->nullPrint);
74 bruce@momjian.us 5712 : 94 : free(popt->truePrint);
5713 : 94 : free(popt->falsePrint);
1500 peter@eisentraut.org 5714 : 94 : free(popt->title);
5715 : :
5716 : : /*
5717 : : * footers and translate_columns are never set in psql's print settings,
5718 : : * so we needn't write code to duplicate them.
5719 : : */
2300 tgl@sss.pgh.pa.us 5720 [ - + ]: 94 : Assert(popt->footers == NULL);
5721 [ - + ]: 94 : Assert(popt->translate_columns == NULL);
5722 : :
5723 : : /* Now we may flat-copy all the fields, including pointers. */
5724 : 94 : memcpy(popt, save, sizeof(printQueryOpt));
5725 : :
5726 : : /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5727 : 94 : free(save);
5728 : 94 : }
5729 : :
5730 : : static const char *
4298 peter_e@gmx.net 5731 : 24 : pset_bool_string(bool val)
5732 : : {
5733 [ + + ]: 24 : return val ? "on" : "off";
5734 : : }
5735 : :
5736 : :
5737 : : static char *
5738 : 24 : pset_quoted_string(const char *str)
5739 : : {
4290 tgl@sss.pgh.pa.us 5740 : 24 : char *ret = pg_malloc(strlen(str) * 2 + 3);
4298 peter_e@gmx.net 5741 : 24 : char *r = ret;
5742 : :
5743 : 24 : *r++ = '\'';
5744 : :
5745 [ + + ]: 44 : for (; *str; str++)
5746 : : {
5747 [ + + ]: 20 : if (*str == '\n')
5748 : : {
5749 : 4 : *r++ = '\\';
5750 : 4 : *r++ = 'n';
5751 : : }
5752 [ - + ]: 16 : else if (*str == '\'')
5753 : : {
4298 peter_e@gmx.net 5754 :UBC 0 : *r++ = '\\';
5755 : 0 : *r++ = '\'';
5756 : : }
5757 : : else
4298 peter_e@gmx.net 5758 :CBC 16 : *r++ = *str;
5759 : : }
5760 : :
5761 : 24 : *r++ = '\'';
5762 : 24 : *r = '\0';
5763 : :
5764 : 24 : return ret;
5765 : : }
5766 : :
5767 : :
5768 : : /*
5769 : : * Return a malloc'ed string for the \pset value.
5770 : : *
5771 : : * Note that for some string parameters, print.c distinguishes between unset
5772 : : * and empty string, but for others it doesn't. This function should produce
5773 : : * output that produces the correct setting when fed back into \pset.
5774 : : */
5775 : : static char *
2300 tgl@sss.pgh.pa.us 5776 : 96 : pset_value_string(const char *param, printQueryOpt *popt)
5777 : : {
4298 peter_e@gmx.net 5778 [ - + ]: 96 : Assert(param != NULL);
5779 : :
5780 [ + + ]: 96 : if (strcmp(param, "border") == 0)
5781 : 4 : return psprintf("%d", popt->topt.border);
5782 [ + + ]: 92 : else if (strcmp(param, "columns") == 0)
5783 : 4 : return psprintf("%d", popt->topt.columns);
2798 tgl@sss.pgh.pa.us 5784 [ + + ]: 88 : else if (strcmp(param, "csv_fieldsep") == 0)
5785 : 4 : return pset_quoted_string(popt->topt.csvFieldSep);
264 alvherre@kurilemu.de 5786 [ + + ]: 84 : else if (strcmp(param, "display_false") == 0)
5787 [ - + ]: 4 : return pset_quoted_string(popt->falsePrint ? popt->falsePrint : "f");
5788 [ + + ]: 80 : else if (strcmp(param, "display_true") == 0)
5789 [ - + ]: 4 : return pset_quoted_string(popt->truePrint ? popt->truePrint : "t");
4298 peter_e@gmx.net 5790 [ + + ]: 76 : else if (strcmp(param, "expanded") == 0)
5791 [ + - ]: 8 : return pstrdup(popt->topt.expanded == 2
5792 : : ? "auto"
5793 : 4 : : pset_bool_string(popt->topt.expanded));
5794 [ + + ]: 72 : else if (strcmp(param, "fieldsep") == 0)
5795 [ + - ]: 4 : return pset_quoted_string(popt->topt.fieldSep.separator
5796 : : ? popt->topt.fieldSep.separator
5797 : : : "");
5798 [ + + ]: 68 : else if (strcmp(param, "fieldsep_zero") == 0)
5799 : 4 : return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
5800 [ + + ]: 64 : else if (strcmp(param, "footer") == 0)
5801 : 4 : return pstrdup(pset_bool_string(popt->topt.default_footer));
5802 [ + + ]: 60 : else if (strcmp(param, "format") == 0)
1418 drowley@postgresql.o 5803 : 4 : return pstrdup(_align2string(popt->topt.format));
4298 peter_e@gmx.net 5804 [ + + ]: 56 : else if (strcmp(param, "linestyle") == 0)
1418 drowley@postgresql.o 5805 : 4 : return pstrdup(get_line_style(&popt->topt)->name);
4298 peter_e@gmx.net 5806 [ + + ]: 52 : else if (strcmp(param, "null") == 0)
5807 [ - + ]: 4 : return pset_quoted_string(popt->nullPrint
5808 : : ? popt->nullPrint
5809 : : : "");
5810 [ + + ]: 48 : else if (strcmp(param, "numericlocale") == 0)
5811 : 4 : return pstrdup(pset_bool_string(popt->topt.numericLocale));
5812 [ + + ]: 44 : else if (strcmp(param, "pager") == 0)
5813 : 4 : return psprintf("%d", popt->topt.pager);
4137 andrew@dunslane.net 5814 [ + + ]: 40 : else if (strcmp(param, "pager_min_lines") == 0)
5815 : 4 : return psprintf("%d", popt->topt.pager_min_lines);
4298 peter_e@gmx.net 5816 [ + + ]: 36 : else if (strcmp(param, "recordsep") == 0)
5817 [ + - ]: 4 : return pset_quoted_string(popt->topt.recordSep.separator
5818 : : ? popt->topt.recordSep.separator
5819 : : : "");
5820 [ + + ]: 32 : else if (strcmp(param, "recordsep_zero") == 0)
5821 : 4 : return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
5822 [ + + ]: 28 : else if (strcmp(param, "tableattr") == 0)
5823 [ - + ]: 4 : return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5824 [ + + ]: 24 : else if (strcmp(param, "title") == 0)
5825 [ - + ]: 4 : return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5826 [ + + ]: 20 : else if (strcmp(param, "tuples_only") == 0)
5827 : 4 : return pstrdup(pset_bool_string(popt->topt.tuples_only));
5828 [ + + ]: 16 : else if (strcmp(param, "unicode_border_linestyle") == 0)
5829 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5830 [ + + ]: 12 : else if (strcmp(param, "unicode_column_linestyle") == 0)
5831 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5832 [ + + ]: 8 : else if (strcmp(param, "unicode_header_linestyle") == 0)
5833 : 4 : return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
1461 andrew@dunslane.net 5834 [ + - ]: 4 : else if (strcmp(param, "xheader_width") == 0)
5835 : : {
5836 [ + - ]: 4 : if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
1163 tgl@sss.pgh.pa.us 5837 : 4 : return pstrdup("full");
1461 andrew@dunslane.net 5838 [ # # ]:UBC 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
1163 tgl@sss.pgh.pa.us 5839 : 0 : return pstrdup("column");
1461 andrew@dunslane.net 5840 [ # # ]: 0 : else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
1163 tgl@sss.pgh.pa.us 5841 : 0 : return pstrdup("page");
5842 : : else
5843 : : {
5844 : : /* must be PRINT_XHEADER_EXACT_WIDTH */
5845 : : char wbuff[32];
5846 : :
1461 andrew@dunslane.net 5847 : 0 : snprintf(wbuff, sizeof(wbuff), "%d",
5848 : : popt->topt.expanded_header_exact_width);
5849 : 0 : return pstrdup(wbuff);
5850 : : }
5851 : : }
5852 : : else
4298 peter_e@gmx.net 5853 : 0 : return pstrdup("ERROR");
5854 : : }
5855 : :
5856 : :
5857 : :
5858 : : #ifndef WIN32
5859 : : #define DEFAULT_SHELL "/bin/sh"
5860 : : #else
5861 : : /*
5862 : : * CMD.EXE is in different places in different Win32 releases so we
5863 : : * have to rely on the path to find it.
5864 : : */
5865 : : #define DEFAULT_SHELL "cmd.exe"
5866 : : #endif
5867 : :
5868 : : static bool
9760 bruce@momjian.us 5869 : 0 : do_shell(const char *command)
5870 : : {
5871 : : int result;
5872 : :
1426 tgl@sss.pgh.pa.us 5873 : 0 : fflush(NULL);
9760 bruce@momjian.us 5874 [ # # ]: 0 : if (!command)
5875 : : {
5876 : : char *sys;
5877 : : const char *shellName;
5878 : :
7931 5879 : 0 : shellName = getenv("SHELL");
5880 : : #ifdef WIN32
5881 : : if (shellName == NULL)
5882 : : shellName = getenv("COMSPEC");
5883 : : #endif
9760 5884 [ # # ]: 0 : if (shellName == NULL)
5885 : 0 : shellName = DEFAULT_SHELL;
5886 : :
5887 : : /* See EDITOR handling comment for an explanation */
5888 : : #ifndef WIN32
4659 tgl@sss.pgh.pa.us 5889 : 0 : sys = psprintf("exec %s", shellName);
5890 : : #else
5891 : : sys = psprintf("\"%s\"", shellName);
5892 : : #endif
9760 bruce@momjian.us 5893 : 0 : result = system(sys);
24 peter@eisentraut.org 5894 :UNC 0 : pfree(sys);
5895 : : }
5896 : : else
9760 bruce@momjian.us 5897 :UBC 0 : result = system(command);
5898 : :
1206 tgl@sss.pgh.pa.us 5899 : 0 : SetShellResultVariables(result);
5900 : :
9760 bruce@momjian.us 5901 [ # # # # ]: 0 : if (result == 127 || result == -1)
5902 : : {
2672 peter@eisentraut.org 5903 : 0 : pg_log_error("\\!: failed");
9760 bruce@momjian.us 5904 : 0 : return false;
5905 : : }
5906 : 0 : return true;
5907 : : }
5908 : :
5909 : : /*
5910 : : * do_watch -- handler for \watch
5911 : : *
5912 : : * We break this out of exec_command to avoid having to plaster "volatile"
5913 : : * onto a bunch of exec_command's variables to silence stupider compilers.
5914 : : *
5915 : : * "sleep" is the amount of time to sleep during each loop, measured in
5916 : : * seconds. The internals of this function should use "sleep_ms" for
5917 : : * precise sleep time calculations.
5918 : : */
5919 : : static bool
1061 dgustafsson@postgres 5920 :CBC 7 : do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
5921 : : {
3778 tgl@sss.pgh.pa.us 5922 : 7 : long sleep_ms = (long) (sleep * 1000);
4860 5923 : 7 : printQueryOpt myopt = pset.popt;
5924 : : const char *strftime_fmt;
5925 : : const char *user_title;
5926 : : char *title;
1838 tmunro@postgresql.or 5927 : 7 : const char *pagerprog = NULL;
5928 : 7 : FILE *pagerpipe = NULL;
5929 : : int title_len;
3778 tgl@sss.pgh.pa.us 5930 : 7 : int res = 0;
869 5931 : 7 : bool done = false;
5932 : : #ifndef WIN32
5933 : : sigset_t sigalrm_sigchld_sigint;
5934 : : sigset_t sigalrm_sigchld;
5935 : : sigset_t sigint;
5936 : : struct itimerval interval;
5937 : : #endif
5938 : :
4860 5939 [ + - - + ]: 7 : if (!query_buf || query_buf->len <= 0)
5940 : : {
2672 peter@eisentraut.org 5941 :UBC 0 : pg_log_error("\\watch cannot be used with an empty query");
4860 tgl@sss.pgh.pa.us 5942 : 0 : return false;
5943 : : }
5944 : :
5945 : : #ifndef WIN32
1838 tmunro@postgresql.or 5946 :CBC 7 : sigemptyset(&sigalrm_sigchld_sigint);
5947 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5948 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5949 : 7 : sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5950 : :
5951 : 7 : sigemptyset(&sigalrm_sigchld);
5952 : 7 : sigaddset(&sigalrm_sigchld, SIGCHLD);
5953 : 7 : sigaddset(&sigalrm_sigchld, SIGALRM);
5954 : :
5955 : 7 : sigemptyset(&sigint);
5956 : 7 : sigaddset(&sigint, SIGINT);
5957 : :
5958 : : /*
5959 : : * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5960 : : * configured), to avoid races. sigwait() will receive them.
5961 : : */
5962 : 7 : sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5963 : :
5964 : : /*
5965 : : * Set a timer to interrupt sigwait() so we can run the query at the
5966 : : * requested intervals.
5967 : : */
5968 : 7 : interval.it_value.tv_sec = sleep_ms / 1000;
5969 : 7 : interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5970 : 7 : interval.it_interval = interval.it_value;
5971 [ - + ]: 7 : if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5972 : : {
1838 tmunro@postgresql.or 5973 :UBC 0 : pg_log_error("could not set timer: %m");
5974 : 0 : done = true;
5975 : : }
5976 : : #endif
5977 : :
5978 : : /*
5979 : : * For \watch, we ignore the size of the result and always use the pager
5980 : : * as long as we're talking to a terminal and "\pset pager" is enabled.
5981 : : * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5982 : : * ignore the regular PSQL_PAGER or PAGER environment variables, because
5983 : : * traditional pagers probably won't be very useful for showing a stream
5984 : : * of results.
5985 : : */
5986 : : #ifndef WIN32
1838 tmunro@postgresql.or 5987 :CBC 7 : pagerprog = getenv("PSQL_WATCH_PAGER");
5988 : : /* if variable is empty or all-white-space, don't use pager */
1170 tgl@sss.pgh.pa.us 5989 [ - + - - ]: 7 : if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
1170 tgl@sss.pgh.pa.us 5990 :UBC 0 : pagerprog = NULL;
5991 : : #endif
1170 tgl@sss.pgh.pa.us 5992 [ - + - - :CBC 7 : if (pagerprog && myopt.topt.pager &&
- - ]
1170 tgl@sss.pgh.pa.us 5993 [ # # ]:UBC 0 : isatty(fileno(stdin)) && isatty(fileno(stdout)))
5994 : : {
1426 5995 : 0 : fflush(NULL);
1838 tmunro@postgresql.or 5996 : 0 : disable_sigpipe_trap();
5997 : 0 : pagerpipe = popen(pagerprog, "w");
5998 : :
5999 [ # # ]: 0 : if (!pagerpipe)
6000 : : /* silently proceed without pager */
6001 : 0 : restore_sigpipe_trap();
6002 : : }
6003 : :
6004 : : /*
6005 : : * Choose format for timestamps. We might eventually make this a \pset
6006 : : * option. In the meantime, using a variable for the format suppresses
6007 : : * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
6008 : : */
3692 tgl@sss.pgh.pa.us 6009 :CBC 7 : strftime_fmt = "%c";
6010 : :
6011 : : /*
6012 : : * Set up rendering options, in particular, disable the pager unless
6013 : : * PSQL_WATCH_PAGER was successfully launched.
6014 : : */
1838 tmunro@postgresql.or 6015 [ + - ]: 7 : if (!pagerpipe)
6016 : 7 : myopt.topt.pager = 0;
6017 : :
6018 : : /*
6019 : : * If there's a title in the user configuration, make sure we have room
6020 : : * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
6021 : : * bytes for the rest.
6022 : : */
3778 tgl@sss.pgh.pa.us 6023 : 7 : user_title = myopt.title;
3692 6024 [ - + ]: 7 : title_len = (user_title ? strlen(user_title) : 0) + 256;
3778 6025 : 7 : title = pg_malloc(title_len);
6026 : :
6027 : : /* Loop to run query and then sleep awhile */
869 6028 [ + - ]: 80 : while (!done)
6029 : : {
6030 : : time_t timer;
6031 : : char timebuf[128];
6032 : :
6033 : : /*
6034 : : * Prepare title for output. Note that we intentionally include a
6035 : : * newline at the end of the title; this is somewhat historical but it
6036 : : * makes for reasonably nicely formatted output in simple cases.
6037 : : */
4860 6038 : 80 : timer = time(NULL);
3692 6039 : 80 : strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
6040 : :
3778 6041 [ - + ]: 80 : if (user_title)
3778 tgl@sss.pgh.pa.us 6042 :UBC 0 : snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
6043 : : user_title, timebuf, sleep_ms / 1000.0);
6044 : : else
3778 tgl@sss.pgh.pa.us 6045 :CBC 80 : snprintf(title, title_len, _("%s (every %gs)\n"),
6046 : : timebuf, sleep_ms / 1000.0);
4860 6047 : 80 : myopt.title = title;
6048 : :
6049 : : /* Run the query and print out the result */
1061 dgustafsson@postgres 6050 : 80 : res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
6051 : :
6052 : : /*
6053 : : * PSQLexecWatch handles the case where we can no longer repeat the
6054 : : * query, and returns 0 or -1.
6055 : : */
3778 tgl@sss.pgh.pa.us 6056 [ + + ]: 78 : if (res <= 0)
4860 6057 : 5 : break;
6058 : :
6059 : : /* If we have iteration count, check that it's not exceeded yet */
1206 6060 [ + + + + ]: 76 : if (iter && (--iter <= 0))
6061 : 3 : break;
6062 : :
6063 : : /* Quit if error on pager pipe (probably pager has quit) */
1838 tmunro@postgresql.or 6064 [ - + - - ]: 73 : if (pagerpipe && ferror(pagerpipe))
1838 tmunro@postgresql.or 6065 :UBC 0 : break;
6066 : :
6067 : : /* Tight loop, no wait needed */
649 michael@paquier.xyz 6068 [ + + ]:CBC 73 : if (sleep_ms == 0)
1227 6069 : 4 : continue;
6070 : :
6071 : : #ifdef WIN32
6072 : :
6073 : : /*
6074 : : * Wait a while before running the query again. Break the sleep into
6075 : : * short intervals (at most 1s); that's probably unnecessary since
6076 : : * pg_usleep is interruptible on Windows, but it's cheap insurance.
6077 : : */
6078 : : for (long i = sleep_ms; i > 0;)
6079 : : {
6080 : : long s = Min(i, 1000L);
6081 : :
6082 : : pg_usleep(s * 1000L);
6083 : : if (cancel_pressed)
6084 : : {
6085 : : done = true;
6086 : : break;
6087 : : }
6088 : : i -= s;
6089 : : }
6090 : : #else
6091 : : /* sigwait() will handle SIGINT. */
1838 tmunro@postgresql.or 6092 : 69 : sigprocmask(SIG_BLOCK, &sigint, NULL);
6093 [ - + ]: 69 : if (cancel_pressed)
1838 tmunro@postgresql.or 6094 :UBC 0 : done = true;
6095 : :
6096 : : /* Wait for SIGINT, SIGCHLD or SIGALRM. */
1838 tmunro@postgresql.or 6097 [ + - ]:CBC 69 : while (!done)
6098 : : {
6099 : : int signal_received;
6100 : :
1836 6101 : 69 : errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
6102 [ - + ]: 69 : if (errno != 0)
6103 : : {
6104 : : /* Some other signal arrived? */
1838 tmunro@postgresql.or 6105 [ # # ]:UBC 0 : if (errno == EINTR)
6106 : 0 : continue;
6107 : : else
6108 : : {
6109 : 0 : pg_log_error("could not wait for signals: %m");
6110 : 0 : done = true;
1838 tmunro@postgresql.or 6111 :CBC 69 : break;
6112 : : }
6113 : : }
6114 : : /* On ^C or pager exit, it's time to stop running the query. */
6115 [ + - - + ]: 69 : if (signal_received == SIGINT || signal_received == SIGCHLD)
1838 tmunro@postgresql.or 6116 :UBC 0 : done = true;
6117 : : /* Otherwise, we must have SIGALRM. Time to run the query again. */
1838 tmunro@postgresql.or 6118 :CBC 69 : break;
6119 : : }
6120 : :
6121 : : /* Unblock SIGINT so that slow queries can be interrupted. */
6122 : 69 : sigprocmask(SIG_UNBLOCK, &sigint, NULL);
6123 : : #endif
6124 : : }
6125 : :
6126 [ - + ]: 5 : if (pagerpipe)
6127 : : {
1838 tmunro@postgresql.or 6128 :UBC 0 : pclose(pagerpipe);
6129 : 0 : restore_sigpipe_trap();
6130 : : }
6131 : : else
6132 : : {
6133 : : /*
6134 : : * If the terminal driver echoed "^C", libedit/libreadline might be
6135 : : * confused about the cursor position. Therefore, inject a newline
6136 : : * before the next prompt is displayed. We only do this when not
6137 : : * using a pager, because pagers are expected to restore the screen to
6138 : : * a sane state on exit.
6139 : : */
1476 tmunro@postgresql.or 6140 :CBC 5 : fprintf(stdout, "\n");
6141 : 5 : fflush(stdout);
6142 : : }
6143 : :
6144 : : #ifndef WIN32
6145 : : /* Disable the interval timer. */
1838 6146 : 5 : memset(&interval, 0, sizeof(interval));
6147 : 5 : setitimer(ITIMER_REAL, &interval, NULL);
6148 : : /* Unblock SIGINT, SIGCHLD and SIGALRM. */
6149 : 5 : sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
6150 : : #endif
6151 : :
3778 tgl@sss.pgh.pa.us 6152 : 5 : pg_free(title);
6153 : 5 : return (res >= 0);
6154 : : }
6155 : :
6156 : : /*
6157 : : * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
6158 : : * returns true unless we have ECHO_HIDDEN_NOEXEC.
6159 : : */
6160 : : static bool
4040 6161 : 324 : echo_hidden_command(const char *query)
6162 : : {
4263 andrew@dunslane.net 6163 [ - + ]: 324 : if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
6164 : : {
121 tgl@sss.pgh.pa.us 6165 :UBC 0 : printf(_("/**** INTERNAL QUERY ****/\n"
6166 : : "%s\n"
6167 : : "/************************/\n\n"), query);
4263 andrew@dunslane.net 6168 : 0 : fflush(stdout);
6169 [ # # ]: 0 : if (pset.logfile)
6170 : : {
6171 : 0 : fprintf(pset.logfile,
121 tgl@sss.pgh.pa.us 6172 : 0 : _("/**** INTERNAL QUERY ****/\n"
6173 : : "%s\n"
6174 : : "/************************/\n\n"), query);
4263 andrew@dunslane.net 6175 : 0 : fflush(pset.logfile);
6176 : : }
6177 : :
6178 [ # # ]: 0 : if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
6179 : 0 : return false;
6180 : : }
4263 andrew@dunslane.net 6181 :CBC 324 : return true;
6182 : : }
6183 : :
6184 : : /*
6185 : : * Look up the object identified by obj_type and desc. If successful,
6186 : : * store its OID in *obj_oid and return true, else return false.
6187 : : *
6188 : : * Note that we'll fail if the object doesn't exist OR if there are multiple
6189 : : * matching candidates OR if there's something syntactically wrong with the
6190 : : * object description; unfortunately it can be hard to tell the difference.
6191 : : */
6192 : : static bool
4040 tgl@sss.pgh.pa.us 6193 : 162 : lookup_object_oid(EditableObjectType obj_type, const char *desc,
6194 : : Oid *obj_oid)
6195 : : {
6531 6196 : 162 : bool result = true;
4040 6197 : 162 : PQExpBuffer query = createPQExpBuffer();
6198 : : PGresult *res;
6199 : :
6200 [ + + - ]: 162 : switch (obj_type)
6201 : : {
6202 : 54 : case EditableFunction:
6203 : :
6204 : : /*
6205 : : * We have a function description, e.g. "x" or "x(int)". Issue a
6206 : : * query to retrieve the function's OID using a cast to regproc or
6207 : : * regprocedure (as appropriate).
6208 : : */
121 6209 : 54 : printfPQExpBuffer(query, "/* %s */\n", _("Get function's OID"));
4040 6210 : 54 : appendPQExpBufferStr(query, "SELECT ");
6211 : 54 : appendStringLiteralConn(query, desc, pset.db);
6212 : 54 : appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
6213 [ + + ]: 54 : strchr(desc, '(') ? "regprocedure" : "regproc");
6214 : 54 : break;
6215 : :
6216 : 108 : case EditableView:
6217 : :
6218 : : /*
6219 : : * Convert view name (possibly schema-qualified) to OID. Note:
6220 : : * this code doesn't check if the relation is actually a view.
6221 : : * We'll detect that in get_create_object_cmd().
6222 : : */
121 6223 : 108 : printfPQExpBuffer(query, "/* %s */\n", _("Get view's OID"));
4040 6224 : 108 : appendPQExpBufferStr(query, "SELECT ");
6225 : 108 : appendStringLiteralConn(query, desc, pset.db);
2578 drowley@postgresql.o 6226 : 108 : appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
4040 tgl@sss.pgh.pa.us 6227 : 108 : break;
6228 : : }
6229 : :
6230 [ - + ]: 162 : if (!echo_hidden_command(query->data))
6231 : : {
4262 andrew@dunslane.net 6232 :UBC 0 : destroyPQExpBuffer(query);
4263 6233 : 0 : return false;
6234 : : }
4263 andrew@dunslane.net 6235 :CBC 162 : res = PQexec(pset.db, query->data);
6531 tgl@sss.pgh.pa.us 6236 [ + - + - ]: 162 : if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
4040 6237 : 162 : *obj_oid = atooid(PQgetvalue(res, 0, 0));
6238 : : else
6239 : : {
6531 tgl@sss.pgh.pa.us 6240 :UBC 0 : minimal_error_message(res);
6241 : 0 : result = false;
6242 : : }
6243 : :
6531 tgl@sss.pgh.pa.us 6244 :CBC 162 : PQclear(res);
6245 : 162 : destroyPQExpBuffer(query);
6246 : :
6247 : 162 : return result;
6248 : : }
6249 : :
6250 : : /*
6251 : : * Construct a "CREATE OR REPLACE ..." command that describes the specified
6252 : : * database object. If successful, the result is stored in buf.
6253 : : */
6254 : : static bool
4040 6255 : 162 : get_create_object_cmd(EditableObjectType obj_type, Oid oid,
6256 : : PQExpBuffer buf)
6257 : : {
6531 6258 : 162 : bool result = true;
4040 6259 : 162 : PQExpBuffer query = createPQExpBuffer();
6260 : : PGresult *res;
6261 : :
6262 [ + + - ]: 162 : switch (obj_type)
6263 : : {
6264 : 54 : case EditableFunction:
121 6265 : 54 : printfPQExpBuffer(query, "/* %s */\n", _("Get function's definition"));
6266 : 54 : appendPQExpBuffer(query,
6267 : : "SELECT pg_catalog.pg_get_functiondef(%u)",
6268 : : oid);
4040 6269 : 54 : break;
6270 : :
6271 : 108 : case EditableView:
6272 : :
6273 : : /*
6274 : : * pg_get_viewdef() just prints the query, so we must prepend
6275 : : * CREATE for ourselves. We must fully qualify the view name to
6276 : : * ensure the right view gets replaced. Also, check relation kind
6277 : : * to be sure it's a view.
6278 : : *
6279 : : * Views may have WITH [LOCAL|CASCADED] CHECK OPTION. These are
6280 : : * not part of the view definition returned by pg_get_viewdef()
6281 : : * and so need to be retrieved separately. Materialized views may
6282 : : * have arbitrary storage parameter reloptions.
6283 : : */
121 6284 : 108 : printfPQExpBuffer(query, "/* %s */\n", _("Get view's definition and details"));
23 nathan@postgresql.or 6285 :GNC 108 : appendPQExpBuffer(query,
6286 : : "SELECT nspname, relname, relkind, "
6287 : : "pg_catalog.pg_get_viewdef(c.oid, true), "
6288 : : "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6289 : : "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6290 : : "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
6291 : : "FROM pg_catalog.pg_class c "
6292 : : "LEFT JOIN pg_catalog.pg_namespace n "
6293 : : "ON c.relnamespace = n.oid WHERE c.oid = %u",
6294 : : oid);
4040 tgl@sss.pgh.pa.us 6295 :CBC 108 : break;
6296 : : }
6297 : :
6298 [ - + ]: 162 : if (!echo_hidden_command(query->data))
6299 : : {
4262 andrew@dunslane.net 6300 :UBC 0 : destroyPQExpBuffer(query);
4263 6301 : 0 : return false;
6302 : : }
4263 andrew@dunslane.net 6303 :CBC 162 : res = PQexec(pset.db, query->data);
6531 tgl@sss.pgh.pa.us 6304 [ + - + - ]: 162 : if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6305 : : {
6306 : 162 : resetPQExpBuffer(buf);
4040 6307 [ + + - ]: 162 : switch (obj_type)
6308 : : {
6309 : 54 : case EditableFunction:
6310 : 54 : appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
6311 : 54 : break;
6312 : :
6313 : 108 : case EditableView:
6314 : : {
6315 : 108 : char *nspname = PQgetvalue(res, 0, 0);
6316 : 108 : char *relname = PQgetvalue(res, 0, 1);
6317 : 108 : char *relkind = PQgetvalue(res, 0, 2);
6318 : 108 : char *viewdef = PQgetvalue(res, 0, 3);
3732 dean.a.rasheed@gmail 6319 : 108 : char *reloptions = PQgetvalue(res, 0, 4);
6320 : 108 : char *checkoption = PQgetvalue(res, 0, 5);
6321 : :
6322 : : /*
6323 : : * If the backend ever supports CREATE OR REPLACE
6324 : : * MATERIALIZED VIEW, allow that here; but as of today it
6325 : : * does not, so editing a matview definition in this way
6326 : : * is impossible.
6327 : : */
4040 tgl@sss.pgh.pa.us 6328 [ + - ]: 108 : switch (relkind[0])
6329 : : {
6330 : : #ifdef NOT_USED
6331 : : case RELKIND_MATVIEW:
6332 : : appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
6333 : : break;
6334 : : #endif
3425 6335 : 108 : case RELKIND_VIEW:
4040 6336 : 108 : appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
6337 : 108 : break;
4040 tgl@sss.pgh.pa.us 6338 :UBC 0 : default:
2672 peter@eisentraut.org 6339 : 0 : pg_log_error("\"%s.%s\" is not a view",
6340 : : nspname, relname);
4040 tgl@sss.pgh.pa.us 6341 : 0 : result = false;
6342 : 0 : break;
6343 : : }
4040 tgl@sss.pgh.pa.us 6344 :CBC 108 : appendPQExpBuffer(buf, "%s.", fmtId(nspname));
3732 dean.a.rasheed@gmail 6345 : 108 : appendPQExpBufferStr(buf, fmtId(relname));
6346 : :
6347 : : /* reloptions, if not an empty array "{}" */
6348 [ + - - + ]: 108 : if (reloptions != NULL && strlen(reloptions) > 2)
6349 : : {
3732 dean.a.rasheed@gmail 6350 :UBC 0 : appendPQExpBufferStr(buf, "\n WITH (");
6351 [ # # ]: 0 : if (!appendReloptionsArray(buf, reloptions, "",
6352 : : pset.encoding,
6353 : 0 : standard_strings()))
6354 : : {
2672 peter@eisentraut.org 6355 : 0 : pg_log_error("could not parse reloptions array");
3732 dean.a.rasheed@gmail 6356 : 0 : result = false;
6357 : : }
3266 peter_e@gmx.net 6358 : 0 : appendPQExpBufferChar(buf, ')');
6359 : : }
6360 : :
6361 : : /* View definition from pg_get_viewdef (a SELECT query) */
3732 dean.a.rasheed@gmail 6362 :CBC 108 : appendPQExpBuffer(buf, " AS\n%s", viewdef);
6363 : :
6364 : : /* Get rid of the semicolon that pg_get_viewdef appends */
4040 tgl@sss.pgh.pa.us 6365 [ + - + - ]: 108 : if (buf->len > 0 && buf->data[buf->len - 1] == ';')
6366 : 108 : buf->data[--(buf->len)] = '\0';
6367 : :
6368 : : /* WITH [LOCAL|CASCADED] CHECK OPTION */
3732 dean.a.rasheed@gmail 6369 [ + - - + ]: 108 : if (checkoption && checkoption[0] != '\0')
3732 dean.a.rasheed@gmail 6370 :UBC 0 : appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
6371 : : checkoption);
6372 : : }
4040 tgl@sss.pgh.pa.us 6373 :CBC 108 : break;
6374 : : }
6375 : : /* Make sure result ends with a newline */
6376 [ + - + + ]: 162 : if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
6377 : 108 : appendPQExpBufferChar(buf, '\n');
6378 : : }
6379 : : else
6380 : : {
6531 tgl@sss.pgh.pa.us 6381 :UBC 0 : minimal_error_message(res);
6382 : 0 : result = false;
6383 : : }
6384 : :
6531 tgl@sss.pgh.pa.us 6385 :CBC 162 : PQclear(res);
6386 : 162 : destroyPQExpBuffer(query);
6387 : :
6388 : 162 : return result;
6389 : : }
6390 : :
6391 : : /*
6392 : : * If the given argument of \ef or \ev ends with a line number, delete the line
6393 : : * number from the argument string and return it as an integer. (We need
6394 : : * this kluge because we're too lazy to parse \ef's function or \ev's view
6395 : : * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
6396 : : *
6397 : : * Returns -1 if no line number is present, 0 on error, or a positive value
6398 : : * on success.
6399 : : */
6400 : : static int
4040 tgl@sss.pgh.pa.us 6401 :UBC 0 : strip_lineno_from_objdesc(char *obj)
6402 : : {
6403 : : char *c;
6404 : : int lineno;
6405 : :
6406 [ # # # # ]: 0 : if (!obj || obj[0] == '\0')
5826 6407 : 0 : return -1;
6408 : :
4040 6409 : 0 : c = obj + strlen(obj) - 1;
6410 : :
6411 : : /*
6412 : : * This business of parsing backwards is dangerous as can be in a
6413 : : * multibyte environment: there is no reason to believe that we are
6414 : : * looking at the first byte of a character, nor are we necessarily
6415 : : * working in a "safe" encoding. Fortunately the bitpatterns we are
6416 : : * looking for are unlikely to occur as non-first bytes, but beware of
6417 : : * trying to expand the set of cases that can be recognized. We must
6418 : : * guard the <ctype.h> macros by using isascii() first, too.
6419 : : */
6420 : :
6421 : : /* skip trailing whitespace */
6422 [ # # # # : 0 : while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
# # ]
5826 6423 : 0 : c--;
6424 : :
6425 : : /* must have a digit as last non-space char */
4040 6426 [ # # # # : 0 : if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
# # ]
5826 6427 : 0 : return -1;
6428 : :
6429 : : /* find start of digit string */
4040 6430 [ # # # # : 0 : while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
# # ]
5826 6431 : 0 : c--;
6432 : :
6433 : : /* digits must be separated from object name by space or closing paren */
6434 : : /* notice also that we are not allowing an empty object name ... */
4040 6435 [ # # # # ]: 0 : if (c == obj || !isascii((unsigned char) *c) ||
5813 6436 [ # # # # ]: 0 : !(isspace((unsigned char) *c) || *c == ')'))
5826 6437 : 0 : return -1;
6438 : :
6439 : : /* parse digit string */
6440 : 0 : c++;
6441 : 0 : lineno = atoi(c);
6442 [ # # ]: 0 : if (lineno < 1)
6443 : : {
2672 peter@eisentraut.org 6444 : 0 : pg_log_error("invalid line number: %s", c);
5826 tgl@sss.pgh.pa.us 6445 : 0 : return 0;
6446 : : }
6447 : :
6448 : : /* strip digit string from object name */
6449 : 0 : *c = '\0';
6450 : :
6451 : 0 : return lineno;
6452 : : }
6453 : :
6454 : : /*
6455 : : * Count number of lines in the buffer.
6456 : : * This is used to test if pager is needed or not.
6457 : : */
6458 : : static int
4040 tgl@sss.pgh.pa.us 6459 :CBC 162 : count_lines_in_buf(PQExpBuffer buf)
6460 : : {
6461 : 162 : int lineno = 0;
6462 : 162 : const char *lines = buf->data;
6463 : :
6464 [ + + ]: 2239 : while (*lines != '\0')
6465 : : {
6466 : 2077 : lineno++;
6467 : : /* find start of next line */
6468 : 2077 : lines = strchr(lines, '\n');
6469 [ - + ]: 2077 : if (!lines)
4040 tgl@sss.pgh.pa.us 6470 :UBC 0 : break;
4040 tgl@sss.pgh.pa.us 6471 :CBC 2077 : lines++;
6472 : : }
6473 : :
6474 : 162 : return lineno;
6475 : : }
6476 : :
6477 : : /*
6478 : : * Write text at *lines to output with line numbers.
6479 : : *
6480 : : * For functions, lineno "1" should correspond to the first line of the
6481 : : * function body; lines before that are unnumbered. We expect that
6482 : : * pg_get_functiondef() will emit that on a line beginning with "AS ",
6483 : : * "BEGIN ", or "RETURN ", and that there can be no such line before
6484 : : * the real start of the function body.
6485 : : *
6486 : : * Caution: this scribbles on *lines.
6487 : : */
6488 : : static void
1331 6489 : 28 : print_with_linenumbers(FILE *output, char *lines, bool is_func)
6490 : : {
6491 : 28 : bool in_header = is_func;
4040 6492 : 28 : int lineno = 0;
6493 : :
6494 [ + + ]: 256 : while (*lines != '\0')
6495 : : {
6496 : : char *eol;
6497 : :
1331 6498 [ + + ]: 228 : if (in_header &&
6499 [ + - ]: 124 : (strncmp(lines, "AS ", 3) == 0 ||
6500 [ + + ]: 124 : strncmp(lines, "BEGIN ", 6) == 0 ||
6501 [ + + ]: 100 : strncmp(lines, "RETURN ", 7) == 0))
4040 6502 : 28 : in_header = false;
6503 : :
6504 : : /* increment lineno only for body's lines */
6505 [ + + ]: 228 : if (!in_header)
6506 : 132 : lineno++;
6507 : :
6508 : : /* find and mark end of current line */
6509 : 228 : eol = strchr(lines, '\n');
6510 [ + - ]: 228 : if (eol != NULL)
6511 : 228 : *eol = '\0';
6512 : :
6513 : : /* show current line as appropriate */
6514 [ + + ]: 228 : if (in_header)
6515 : 96 : fprintf(output, " %s\n", lines);
6516 : : else
6517 : 132 : fprintf(output, "%-7d %s\n", lineno, lines);
6518 : :
6519 : : /* advance to next line, if any */
6520 [ - + ]: 228 : if (eol == NULL)
4040 tgl@sss.pgh.pa.us 6521 :UBC 0 : break;
4040 tgl@sss.pgh.pa.us 6522 :CBC 228 : lines = ++eol;
6523 : : }
6524 : 28 : }
6525 : :
6526 : : /*
6527 : : * Report just the primary error; this is to avoid cluttering the output
6528 : : * with, for instance, a redisplay of the internally generated query
6529 : : */
6530 : : static void
6531 tgl@sss.pgh.pa.us 6531 :UBC 0 : minimal_error_message(PGresult *res)
6532 : : {
6533 : : PQExpBuffer msg;
6534 : : const char *fld;
6535 : :
6536 : 0 : msg = createPQExpBuffer();
6537 : :
6538 : 0 : fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
6539 [ # # ]: 0 : if (fld)
6540 : 0 : printfPQExpBuffer(msg, "%s: ", fld);
6541 : : else
6542 : 0 : printfPQExpBuffer(msg, "ERROR: ");
6543 : 0 : fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
6544 [ # # ]: 0 : if (fld)
6545 : 0 : appendPQExpBufferStr(msg, fld);
6546 : : else
6547 : 0 : appendPQExpBufferStr(msg, "(not available)");
3266 peter_e@gmx.net 6548 : 0 : appendPQExpBufferChar(msg, '\n');
6549 : :
2672 peter@eisentraut.org 6550 : 0 : pg_log_error("%s", msg->data);
6551 : :
6531 tgl@sss.pgh.pa.us 6552 : 0 : destroyPQExpBuffer(msg);
6553 : 0 : }
|