Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 750c5ee

Browse files
committed
Fix psql \s to work with recent libedit, and add pager support.
psql's \s (print command history) doesn't work at all with recent libedit versions when printing to the terminal, because libedit tries to do an fchmod() on the target file which will fail if the target is /dev/tty. (We'd already noted this in the context of the target being /dev/null.) Even before that, it didn't work pleasantly, because libedit likes to encode the command history file (to ensure successful reloading), which renders it nigh unreadable, not to mention significantly different-looking depending on exactly which libedit version you have. So let's forget using write_history() for this purpose, and instead print the data ourselves, using logic similar to that used to iterate over the history for newline encoding/decoding purposes. While we're at it, insert the ability to use the pager when \s is printing to the terminal. This has been an acknowledged shortcoming of \s for many years, so while you could argue it's not exactly a back-patchable bug fix it still seems like a good improvement. Anyone who's seriously annoyed at this can use "\s /dev/tty" or local equivalent to get the old behavior. Experimentation with this showed that the history iteration logic was actually rather broken when used with libedit. It turns out that with libedit you have to use previous_history() not next_history() to advance to more recent history entries. The easiest and most robust fix for this seems to be to make a run-time test to verify which function to call. We had not noticed this because libedit doesn't really need the newline encoding logic: its own encoding ensures that command entries containing newlines are reloaded correctly (unlike libreadline). So the effective behavior with recent libedits was that only the oldest history entry got newline-encoded or newline-decoded. However, because of yet other bugs in history_set_pos(), some old versions of libedit allowed the existing loop logic to reach entries besides the oldest, which means there may be libedit ~/.psql_history files out there containing encoded newlines in more than just the oldest entry. To ensure we can reload such files, it seems appropriate to back-patch this fix, even though that will result in some incompatibility with older psql versions (ie, multiline history entries written by a psql with this fix will look corrupted to a psql without it, if its libedit is reasonably up to date). Stepan Rutz and Tom Lane
1 parent 0640c1b commit 750c5ee

File tree

4 files changed

+144
-52
lines changed

4 files changed

+144
-52
lines changed

doc/src/sgml/ref/psql-ref.sgml

+9-7
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ EOF
277277
<term><option>--no-readline</></term>
278278
<listitem>
279279
<para>
280-
Do not use <application>readline</application> for line editing and do not use the history.
280+
Do not use <application>Readline</application> for line editing and do
281+
not use the command history.
281282
This can be useful to turn off tab expansion when cutting and pasting.
282283
</para>
283284
</listitem>
@@ -2357,12 +2358,13 @@ lo_import 152801
23572358
<term><literal>\s [ <replaceable class="parameter">filename</replaceable> ]</literal></term>
23582359
<listitem>
23592360
<para>
2360-
Print or save the command line history to <replaceable
2361-
class="parameter">filename</replaceable>. If <replaceable
2362-
class="parameter">filename</replaceable> is omitted, the history
2363-
is written to the standard output. This option is only available
2364-
if <application>psql</application> is configured to use the
2365-
<acronym>GNU</acronym> <application>Readline</application> library.
2361+
Print <application>psql</application>'s command line history
2362+
to <replaceable class="parameter">filename</replaceable>.
2363+
If <replaceable class="parameter">filename</replaceable> is omitted,
2364+
the history is written to the standard output (using the pager if
2365+
appropriate). This command is not available
2366+
if <application>psql</application> was built
2367+
without <application>Readline</application> support.
23662368
</para>
23672369
</listitem>
23682370
</varlistentry>

src/bin/psql/command.c

+1-13
Original file line numberDiff line numberDiff line change
@@ -1088,20 +1088,8 @@ exec_command(const char *cmd,
10881088
char *fname = psql_scan_slash_option(scan_state,
10891089
OT_NORMAL, NULL, true);
10901090

1091-
#if defined(WIN32) && !defined(__CYGWIN__)
1092-
1093-
/*
1094-
* XXX This does not work for all terminal environments or for output
1095-
* containing non-ASCII characters; see comments in simple_prompt().
1096-
*/
1097-
#define DEVTTY "con"
1098-
#else
1099-
#define DEVTTY "/dev/tty"
1100-
#endif
1101-
11021091
expand_tilde(&fname);
1103-
/* This scrolls off the screen when using /dev/tty */
1104-
success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
1092+
success = printHistory(fname, pset.popt.topt.pager);
11051093
if (success && !pset.quiet && fname)
11061094
printf(_("Wrote history to file \"%s\".\n"), fname);
11071095
if (!fname)

src/bin/psql/input.c

+132-31
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <unistd.h>
1212
#endif
1313
#include <fcntl.h>
14+
#include <limits.h>
1415

1516
#include "input.h"
1617
#include "settings.h"
@@ -222,23 +223,73 @@ gets_fromFile(FILE *source)
222223

223224

224225
#ifdef USE_READLINE
226+
227+
/*
228+
* Macros to iterate over each element of the history list in order
229+
*
230+
* You would think this would be simple enough, but in its inimitable fashion
231+
* libedit has managed to break it: in libreadline we must use next_history()
232+
* to go from oldest to newest, but in libedit we must use previous_history().
233+
* To detect what to do, we make a trial call of previous_history(): if it
234+
* fails, then either next_history() is what to use, or there's zero or one
235+
* history entry so that it doesn't matter which direction we go.
236+
*
237+
* In case that wasn't disgusting enough: the code below is not as obvious as
238+
* it might appear. In some libedit releases history_set_pos(0) fails until
239+
* at least one add_history() call has been done. This is not an issue for
240+
* printHistory() or encode_history(), which cannot be invoked before that has
241+
* happened. In decode_history(), that's not so, and what actually happens is
242+
* that we are sitting on the newest entry to start with, previous_history()
243+
* fails, and we iterate over all the entries using next_history(). So the
244+
* decode_history() loop iterates over the entries in the wrong order when
245+
* using such a libedit release, and if there were another attempt to use
246+
* BEGIN_ITERATE_HISTORY() before some add_history() call had happened, it
247+
* wouldn't work. Fortunately we don't care about either of those things.
248+
*
249+
* Usage pattern is:
250+
*
251+
* BEGIN_ITERATE_HISTORY(varname);
252+
* {
253+
* loop body referencing varname->line;
254+
* }
255+
* END_ITERATE_HISTORY();
256+
*/
257+
#define BEGIN_ITERATE_HISTORY(VARNAME) \
258+
do { \
259+
HIST_ENTRY *VARNAME; \
260+
bool use_prev_; \
261+
\
262+
history_set_pos(0); \
263+
use_prev_ = (previous_history() != NULL); \
264+
history_set_pos(0); \
265+
for (VARNAME = current_history(); VARNAME != NULL; \
266+
VARNAME = use_prev_ ? previous_history() : next_history()) \
267+
{ \
268+
(void) 0
269+
270+
#define END_ITERATE_HISTORY() \
271+
} \
272+
} while(0)
273+
274+
225275
/*
226276
* Convert newlines to NL_IN_HISTORY for safe saving in readline history file
227277
*/
228278
static void
229279
encode_history(void)
230280
{
231-
HIST_ENTRY *cur_hist;
232-
char *cur_ptr;
233-
234-
history_set_pos(0);
235-
for (cur_hist = current_history(); cur_hist; cur_hist = next_history())
281+
BEGIN_ITERATE_HISTORY(cur_hist);
236282
{
283+
char *cur_ptr;
284+
237285
/* some platforms declare HIST_ENTRY.line as const char * */
238286
for (cur_ptr = (char *) cur_hist->line; *cur_ptr; cur_ptr++)
287+
{
239288
if (*cur_ptr == '\n')
240289
*cur_ptr = NL_IN_HISTORY;
290+
}
241291
}
292+
END_ITERATE_HISTORY();
242293
}
243294

244295
/*
@@ -247,17 +298,18 @@ encode_history(void)
247298
static void
248299
decode_history(void)
249300
{
250-
HIST_ENTRY *cur_hist;
251-
char *cur_ptr;
252-
253-
history_set_pos(0);
254-
for (cur_hist = current_history(); cur_hist; cur_hist = next_history())
301+
BEGIN_ITERATE_HISTORY(cur_hist);
255302
{
303+
char *cur_ptr;
304+
256305
/* some platforms declare HIST_ENTRY.line as const char * */
257306
for (cur_ptr = (char *) cur_hist->line; *cur_ptr; cur_ptr++)
307+
{
258308
if (*cur_ptr == NL_IN_HISTORY)
259309
*cur_ptr = '\n';
310+
}
260311
}
312+
END_ITERATE_HISTORY();
261313
}
262314
#endif /* USE_READLINE */
263315

@@ -319,22 +371,15 @@ initializeInput(int flags)
319371

320372

321373
/*
322-
* This function saves the readline history when user
323-
* runs \s command or when psql exits.
374+
* This function saves the readline history when psql exits.
324375
*
325376
* fname: pathname of history file. (Should really be "const char *",
326377
* but some ancient versions of readline omit the const-decoration.)
327378
*
328379
* max_lines: if >= 0, limit history file to that many entries.
329-
*
330-
* appendFlag: if true, try to append just our new lines to the file.
331-
* If false, write the whole available history.
332-
*
333-
* encodeFlag: whether to encode \n as \x01. For \s calls we don't wish
334-
* to do that, but must do so when saving the final history file.
335380
*/
336-
bool
337-
saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag)
381+
static bool
382+
saveHistory(char *fname, int max_lines)
338383
{
339384
#ifdef USE_READLINE
340385

@@ -344,11 +389,15 @@ saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag)
344389
* where write_history will fail because it tries to chmod the target
345390
* file.
346391
*/
347-
if (useHistory && fname &&
348-
strcmp(fname, DEVNULL) != 0)
392+
if (strcmp(fname, DEVNULL) != 0)
349393
{
350-
if (encodeFlag)
351-
encode_history();
394+
/*
395+
* Encode \n, since otherwise readline will reload multiline history
396+
* entries as separate lines. (libedit doesn't really need this, but
397+
* we do it anyway since it's too hard to tell which implementation we
398+
* are using.)
399+
*/
400+
encode_history();
352401

353402
/*
354403
* On newer versions of libreadline, truncate the history file as
@@ -362,7 +411,6 @@ saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag)
362411
* see if the write failed. Similarly for append_history.
363412
*/
364413
#if defined(HAVE_HISTORY_TRUNCATE_FILE) && defined(HAVE_APPEND_HISTORY)
365-
if (appendFlag)
366414
{
367415
int nlines;
368416
int fd;
@@ -387,8 +435,7 @@ saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag)
387435
if (errno == 0)
388436
return true;
389437
}
390-
else
391-
#endif
438+
#else /* don't have append support */
392439
{
393440
/* truncate what we have ... */
394441
if (max_lines >= 0)
@@ -399,19 +446,73 @@ saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag)
399446
if (errno == 0)
400447
return true;
401448
}
449+
#endif
402450

403451
psql_error("could not save history to file \"%s\": %s\n",
404452
fname, strerror(errno));
405453
}
406-
#else
407-
/* only get here in \s case, so complain */
408-
psql_error("history is not supported by this installation\n");
409454
#endif
410455

411456
return false;
412457
}
413458

414459

460+
/*
461+
* Print history to the specified file, or to the console if fname is NULL
462+
* (psql \s command)
463+
*
464+
* We used to use saveHistory() for this purpose, but that doesn't permit
465+
* use of a pager; moreover libedit's implementation behaves incompatibly
466+
* (preferring to encode its output) and may fail outright when the target
467+
* file is specified as /dev/tty.
468+
*/
469+
bool
470+
printHistory(const char *fname, unsigned short int pager)
471+
{
472+
#ifdef USE_READLINE
473+
FILE *output;
474+
bool is_pager;
475+
476+
if (!useHistory)
477+
return false;
478+
479+
if (fname == NULL)
480+
{
481+
/* use pager, if enabled, when printing to console */
482+
output = PageOutput(INT_MAX, pager);
483+
is_pager = true;
484+
}
485+
else
486+
{
487+
output = fopen(fname, "w");
488+
if (output == NULL)
489+
{
490+
psql_error("could not save history to file \"%s\": %s\n",
491+
fname, strerror(errno));
492+
return false;
493+
}
494+
is_pager = false;
495+
}
496+
497+
BEGIN_ITERATE_HISTORY(cur_hist);
498+
{
499+
fprintf(output, "%s\n", cur_hist->line);
500+
}
501+
END_ITERATE_HISTORY();
502+
503+
if (is_pager)
504+
ClosePager(output);
505+
else
506+
fclose(output);
507+
508+
return true;
509+
#else
510+
psql_error("history is not supported by this installation\n");
511+
return false;
512+
#endif
513+
}
514+
515+
415516
static void
416517
finishInput(void)
417518
{
@@ -421,7 +522,7 @@ finishInput(void)
421522
int hist_size;
422523

423524
hist_size = GetVariableNum(pset.vars, "HISTSIZE", 500, -1, true);
424-
saveHistory(psql_history, hist_size, true, true);
525+
(void) saveHistory(psql_history, hist_size);
425526
free(psql_history);
426527
psql_history = NULL;
427528
}

src/bin/psql/input.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ char *gets_interactive(const char *prompt);
4242
char *gets_fromFile(FILE *source);
4343

4444
void initializeInput(int flags);
45-
bool saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag);
45+
46+
bool printHistory(const char *fname, unsigned short int pager);
4647

4748
void pg_append_history(const char *s, PQExpBuffer history_buf);
4849
void pg_send_history(PQExpBuffer history_buf);

0 commit comments

Comments
 (0)