PostgreSQL Source Code  git master
command.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <time.h>
#include <pwd.h>
#include <utime.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "catalog/pg_class_d.h"
#include "command.h"
#include "common.h"
#include "common/logging.h"
#include "common/string.h"
#include "copy.h"
#include "crosstabview.h"
#include "describe.h"
#include "fe_utils/cancel.h"
#include "fe_utils/print.h"
#include "fe_utils/string_utils.h"
#include "help.h"
#include "input.h"
#include "large_obj.h"
#include "libpq-fe.h"
#include "libpq/pqcomm.h"
#include "mainloop.h"
#include "portability/instr_time.h"
#include "pqexpbuffer.h"
#include "psqlscanslash.h"
#include "settings.h"
#include "variables.h"
Include dependency graph for command.c:

Go to the source code of this file.

Macros

#define DEFAULT_SHELL   "/bin/sh"
 

Typedefs

typedef enum EditableObjectType EditableObjectType
 

Enumerations

enum  EditableObjectType { EditableFunction , EditableView }
 

Functions

static backslashResult exec_command (const char *cmd, PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_a (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_C (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_connect (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_cd (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_conninfo (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_copy (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_copyright (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_crosstabview (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_d (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static bool exec_command_dfo (PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
 
static backslashResult exec_command_edit (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_ef_ev (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
 
static backslashResult exec_command_echo (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_elif (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_else (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_endif (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_encoding (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_errverbose (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_f (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_g (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult process_command_g_options (char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_gdesc (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_gexec (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_gset (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_help (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_html (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_include (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_if (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_list (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_lo (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_out (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_print (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_password (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_prompt (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_pset (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_quit (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_reset (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
 
static backslashResult exec_command_s (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_set (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_setenv (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_sf_sv (PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
 
static backslashResult exec_command_t (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_T (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_timing (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_unset (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_write (PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_watch (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_x (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_z (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_shell_escape (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_slash_command_help (PsqlScanState scan_state, bool active_branch)
 
static char * read_connect_arg (PsqlScanState scan_state)
 
static PQExpBuffer gather_boolean_expression (PsqlScanState scan_state)
 
static bool is_true_boolean_expression (PsqlScanState scan_state, const char *name)
 
static void ignore_boolean_expression (PsqlScanState scan_state)
 
static void ignore_slash_options (PsqlScanState scan_state)
 
static void ignore_slash_filepipe (PsqlScanState scan_state)
 
static void ignore_slash_whole_line (PsqlScanState scan_state)
 
static bool is_branching_command (const char *cmd)
 
static void save_query_text_state (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static void discard_query_text (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static bool copy_previous_query (PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static bool do_connect (enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
 
static bool do_edit (const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
 
static bool do_shell (const char *command)
 
static bool do_watch (PQExpBuffer query_buf, double sleep)
 
static bool lookup_object_oid (EditableObjectType obj_type, const char *desc, Oid *obj_oid)
 
static bool get_create_object_cmd (EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
 
static int strip_lineno_from_objdesc (char *obj)
 
static int count_lines_in_buf (PQExpBuffer buf)
 
static void print_with_linenumbers (FILE *output, char *lines, const char *header_keyword)
 
static void minimal_error_message (PGresult *res)
 
static void printSSLInfo (void)
 
static void printGSSInfo (void)
 
static bool printPsetInfo (const char *param, printQueryOpt *popt)
 
static char * pset_value_string (const char *param, printQueryOpt *popt)
 
backslashResult HandleSlashCmds (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static char * prompt_for_password (const char *username, bool *canceled)
 
static bool param_is_newly_set (const char *old_val, const char *new_val)
 
void connection_warnings (bool in_startup)
 
void SyncVariables (void)
 
void UnsyncVariables (void)
 
static bool editFile (const char *fname, int lineno)
 
int process_file (char *filename, bool use_relative_path)
 
static const char * _align2string (enum printFormat in)
 
static bool set_unicode_line_style (const char *value, size_t vallen, unicode_linestyle *linestyle)
 
static const char * _unicode_linestyle2string (int linestyle)
 
bool do_pset (const char *param, const char *value, printQueryOpt *popt, bool quiet)
 
printQueryOptsavePsetInfo (const printQueryOpt *popt)
 
void restorePsetInfo (printQueryOpt *popt, printQueryOpt *save)
 
static const char * pset_bool_string (bool val)
 
static char * pset_quoted_string (const char *str)
 
static bool echo_hidden_command (const char *query)
 

Macro Definition Documentation

◆ DEFAULT_SHELL

#define DEFAULT_SHELL   "/bin/sh"

Definition at line 4884 of file command.c.

Typedef Documentation

◆ EditableObjectType

Enumeration Type Documentation

◆ EditableObjectType

Enumerator
EditableFunction 
EditableView 

Definition at line 53 of file command.c.

54 {
EditableObjectType
Definition: command.c:54
@ EditableFunction
Definition: command.c:55
@ EditableView
Definition: command.c:56

Function Documentation

◆ _align2string()

static const char* _align2string ( enum printFormat  in)
static

Definition at line 4112 of file command.c.

4113 {
4114  switch (in)
4115  {
4116  case PRINT_NOTHING:
4117  return "nothing";
4118  break;
4119  case PRINT_ALIGNED:
4120  return "aligned";
4121  break;
4122  case PRINT_ASCIIDOC:
4123  return "asciidoc";
4124  break;
4125  case PRINT_CSV:
4126  return "csv";
4127  break;
4128  case PRINT_HTML:
4129  return "html";
4130  break;
4131  case PRINT_LATEX:
4132  return "latex";
4133  break;
4134  case PRINT_LATEX_LONGTABLE:
4135  return "latex-longtable";
4136  break;
4137  case PRINT_TROFF_MS:
4138  return "troff-ms";
4139  break;
4140  case PRINT_UNALIGNED:
4141  return "unaligned";
4142  break;
4143  case PRINT_WRAPPED:
4144  return "wrapped";
4145  break;
4146  }
4147  return "unknown";
4148 }
@ PRINT_LATEX_LONGTABLE
Definition: print.h:36
@ PRINT_CSV
Definition: print.h:33
@ PRINT_UNALIGNED
Definition: print.h:38
@ PRINT_ALIGNED
Definition: print.h:31
@ PRINT_TROFF_MS
Definition: print.h:37
@ PRINT_ASCIIDOC
Definition: print.h:32
@ PRINT_NOTHING
Definition: print.h:30
@ PRINT_LATEX
Definition: print.h:35
@ PRINT_HTML
Definition: print.h:34
@ PRINT_WRAPPED
Definition: print.h:39

References PRINT_ALIGNED, PRINT_ASCIIDOC, PRINT_CSV, PRINT_HTML, PRINT_LATEX, PRINT_LATEX_LONGTABLE, PRINT_NOTHING, PRINT_TROFF_MS, PRINT_UNALIGNED, and PRINT_WRAPPED.

Referenced by printPsetInfo(), and pset_value_string().

◆ _unicode_linestyle2string()

static const char* _unicode_linestyle2string ( int  linestyle)
static

Definition at line 4168 of file command.c.

4169 {
4170  switch (linestyle)
4171  {
4173  return "single";
4174  break;
4176  return "double";
4177  break;
4178  }
4179  return "unknown";
4180 }
@ UNICODE_LINESTYLE_SINGLE
Definition: print.h:89
@ UNICODE_LINESTYLE_DOUBLE
Definition: print.h:90

References UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by printPsetInfo(), and pset_value_string().

◆ connection_warnings()

void connection_warnings ( bool  in_startup)

Definition at line 3585 of file command.c.

3586 {
3587  if (!pset.quiet && !pset.notty)
3588  {
3589  int client_ver = PG_VERSION_NUM;
3590  char cverbuf[32];
3591  char sverbuf[32];
3592 
3593  if (pset.sversion != client_ver)
3594  {
3595  const char *server_version;
3596 
3597  /* Try to get full text form, might include "devel" etc */
3598  server_version = PQparameterStatus(pset.db, "server_version");
3599  /* Otherwise fall back on pset.sversion */
3600  if (!server_version)
3601  {
3603  sverbuf, sizeof(sverbuf));
3604  server_version = sverbuf;
3605  }
3606 
3607  printf(_("%s (%s, server %s)\n"),
3608  pset.progname, PG_VERSION, server_version);
3609  }
3610  /* For version match, only print psql banner on startup. */
3611  else if (in_startup)
3612  printf("%s (%s)\n", pset.progname, PG_VERSION);
3613 
3614  if (pset.sversion / 100 > client_ver / 100)
3615  printf(_("WARNING: %s major version %s, server major version %s.\n"
3616  " Some psql features might not work.\n"),
3617  pset.progname,
3618  formatPGVersionNumber(client_ver, false,
3619  cverbuf, sizeof(cverbuf)),
3621  sverbuf, sizeof(sverbuf)));
3622 
3623 #ifdef WIN32
3624  if (in_startup)
3625  checkWin32Codepage();
3626 #endif
3627  printSSLInfo();
3628  printGSSInfo();
3629  }
3630 }
static void printSSLInfo(void)
Definition: command.c:3639
static void printGSSInfo(void)
Definition: command.c:3667
#define _(x)
Definition: elog.c:89
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6735
static int server_version
Definition: pg_dumpall.c:83
#define printf(...)
Definition: port.h:228
PsqlSettings pset
Definition: startup.c:32
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177
PGconn * db
Definition: settings.h:82
const char * progname
Definition: settings.h:109

References _, _psqlSettings::db, formatPGVersionNumber(), _psqlSettings::notty, PQparameterStatus(), printf, printGSSInfo(), printSSLInfo(), _psqlSettings::progname, pset, _psqlSettings::quiet, server_version, and _psqlSettings::sversion.

Referenced by CheckConnection(), do_connect(), and main().

◆ copy_previous_query()

static bool copy_previous_query ( PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 3055 of file command.c.

3056 {
3057  if (query_buf && query_buf->len == 0)
3058  {
3059  appendPQExpBufferStr(query_buf, previous_buf->data);
3060  return true;
3061  }
3062  return false;
3063 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369

References appendPQExpBufferStr(), PQExpBufferData::data, and PQExpBufferData::len.

Referenced by exec_command(), exec_command_edit(), and exec_command_watch().

◆ count_lines_in_buf()

static int count_lines_in_buf ( PQExpBuffer  buf)
static

Definition at line 5482 of file command.c.

5483 {
5484  int lineno = 0;
5485  const char *lines = buf->data;
5486 
5487  while (*lines != '\0')
5488  {
5489  lineno++;
5490  /* find start of next line */
5491  lines = strchr(lines, '\n');
5492  if (!lines)
5493  break;
5494  lines++;
5495  }
5496 
5497  return lineno;
5498 }
static char * buf
Definition: pg_test_fsync.c:70

References buf.

Referenced by exec_command_sf_sv().

◆ discard_query_text()

static void discard_query_text ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf 
)
static

Definition at line 3029 of file command.c.

3031 {
3032  if (query_buf)
3033  {
3034  int new_len = conditional_stack_get_query_len(cstack);
3035 
3036  Assert(new_len >= 0 && new_len <= query_buf->len);
3037  query_buf->len = new_len;
3038  query_buf->data[new_len] = '\0';
3039  }
3040  psql_scan_set_paren_depth(scan_state,
3042 }
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:150
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:172
Assert(fmt[strlen(fmt) - 1] !='\n')
const void size_t len
void psql_scan_set_paren_depth(PsqlScanState state, int depth)

References Assert(), conditional_stack_get_paren_depth(), conditional_stack_get_query_len(), PQExpBufferData::data, PQExpBufferData::len, len, and psql_scan_set_paren_depth().

Referenced by exec_command_elif(), exec_command_else(), and exec_command_endif().

◆ do_connect()

static bool do_connect ( enum trivalue  reuse_previous_specification,
char *  dbname,
char *  user,
char *  host,
char *  port 
)
static

Definition at line 3124 of file command.c.

3126 {
3127  PGconn *o_conn = pset.db,
3128  *n_conn = NULL;
3129  PQconninfoOption *cinfo;
3130  int nconnopts = 0;
3131  bool same_host = false;
3132  char *password = NULL;
3133  char *client_encoding;
3134  bool success = true;
3135  bool keep_password = true;
3136  bool has_connection_string;
3137  bool reuse_previous;
3138 
3139  has_connection_string = dbname ?
3141 
3142  /* Complain if we have additional arguments after a connection string. */
3143  if (has_connection_string && (user || host || port))
3144  {
3145  pg_log_error("Do not give user, host, or port separately when using a connection string");
3146  return false;
3147  }
3148 
3149  switch (reuse_previous_specification)
3150  {
3151  case TRI_YES:
3152  reuse_previous = true;
3153  break;
3154  case TRI_NO:
3155  reuse_previous = false;
3156  break;
3157  default:
3158  reuse_previous = !has_connection_string;
3159  break;
3160  }
3161 
3162  /*
3163  * If we intend to re-use connection parameters, collect them out of the
3164  * old connection, then replace individual values as necessary. (We may
3165  * need to resort to looking at pset.dead_conn, if the connection died
3166  * previously.) Otherwise, obtain a PQconninfoOption array containing
3167  * libpq's defaults, and modify that. Note this function assumes that
3168  * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3169  * containing the same options in the same order.
3170  */
3171  if (reuse_previous)
3172  {
3173  if (o_conn)
3174  cinfo = PQconninfo(o_conn);
3175  else if (pset.dead_conn)
3176  cinfo = PQconninfo(pset.dead_conn);
3177  else
3178  {
3179  /* This is reachable after a non-interactive \connect failure */
3180  pg_log_error("No database connection exists to re-use parameters from");
3181  return false;
3182  }
3183  }
3184  else
3185  cinfo = PQconndefaults();
3186 
3187  if (cinfo)
3188  {
3189  if (has_connection_string)
3190  {
3191  /* Parse the connstring and insert values into cinfo */
3192  PQconninfoOption *replcinfo;
3193  char *errmsg;
3194 
3195  replcinfo = PQconninfoParse(dbname, &errmsg);
3196  if (replcinfo)
3197  {
3198  PQconninfoOption *ci;
3199  PQconninfoOption *replci;
3200  bool have_password = false;
3201 
3202  for (ci = cinfo, replci = replcinfo;
3203  ci->keyword && replci->keyword;
3204  ci++, replci++)
3205  {
3206  Assert(strcmp(ci->keyword, replci->keyword) == 0);
3207  /* Insert value from connstring if one was provided */
3208  if (replci->val)
3209  {
3210  /*
3211  * We know that both val strings were allocated by
3212  * libpq, so the least messy way to avoid memory leaks
3213  * is to swap them.
3214  */
3215  char *swap = replci->val;
3216 
3217  replci->val = ci->val;
3218  ci->val = swap;
3219 
3220  /*
3221  * Check whether connstring provides options affecting
3222  * password re-use. While any change in user, host,
3223  * hostaddr, or port causes us to ignore the old
3224  * connection's password, we don't force that for
3225  * dbname, since passwords aren't database-specific.
3226  */
3227  if (replci->val == NULL ||
3228  strcmp(ci->val, replci->val) != 0)
3229  {
3230  if (strcmp(replci->keyword, "user") == 0 ||
3231  strcmp(replci->keyword, "host") == 0 ||
3232  strcmp(replci->keyword, "hostaddr") == 0 ||
3233  strcmp(replci->keyword, "port") == 0)
3234  keep_password = false;
3235  }
3236  /* Also note whether connstring contains a password. */
3237  if (strcmp(replci->keyword, "password") == 0)
3238  have_password = true;
3239  }
3240  else if (!reuse_previous)
3241  {
3242  /*
3243  * When we have a connstring and are not re-using
3244  * parameters, swap *all* entries, even those not set
3245  * by the connstring. This avoids absorbing
3246  * environment-dependent defaults from the result of
3247  * PQconndefaults(). We don't want to do that because
3248  * they'd override service-file entries if the
3249  * connstring specifies a service parameter, whereas
3250  * the priority should be the other way around. libpq
3251  * can certainly recompute any defaults we don't pass
3252  * here. (In this situation, it's a bit wasteful to
3253  * have called PQconndefaults() at all, but not doing
3254  * so would require yet another major code path here.)
3255  */
3256  replci->val = ci->val;
3257  ci->val = NULL;
3258  }
3259  }
3260  Assert(ci->keyword == NULL && replci->keyword == NULL);
3261 
3262  /* While here, determine how many option slots there are */
3263  nconnopts = ci - cinfo;
3264 
3265  PQconninfoFree(replcinfo);
3266 
3267  /*
3268  * If the connstring contains a password, tell the loop below
3269  * that we may use it, regardless of other settings (i.e.,
3270  * cinfo's password is no longer an "old" password).
3271  */
3272  if (have_password)
3273  keep_password = true;
3274 
3275  /* Don't let code below try to inject dbname into params. */
3276  dbname = NULL;
3277  }
3278  else
3279  {
3280  /* PQconninfoParse failed */
3281  if (errmsg)
3282  {
3283  pg_log_error("%s", errmsg);
3284  PQfreemem(errmsg);
3285  }
3286  else
3287  pg_log_error("out of memory");
3288  success = false;
3289  }
3290  }
3291  else
3292  {
3293  /*
3294  * If dbname isn't a connection string, then we'll inject it and
3295  * the other parameters into the keyword array below. (We can't
3296  * easily insert them into the cinfo array because of memory
3297  * management issues: PQconninfoFree would misbehave on Windows.)
3298  * However, to avoid dependencies on the order in which parameters
3299  * appear in the array, make a preliminary scan to set
3300  * keep_password and same_host correctly.
3301  *
3302  * While any change in user, host, or port causes us to ignore the
3303  * old connection's password, we don't force that for dbname,
3304  * since passwords aren't database-specific.
3305  */
3306  PQconninfoOption *ci;
3307 
3308  for (ci = cinfo; ci->keyword; ci++)
3309  {
3310  if (user && strcmp(ci->keyword, "user") == 0)
3311  {
3312  if (!(ci->val && strcmp(user, ci->val) == 0))
3313  keep_password = false;
3314  }
3315  else if (host && strcmp(ci->keyword, "host") == 0)
3316  {
3317  if (ci->val && strcmp(host, ci->val) == 0)
3318  same_host = true;
3319  else
3320  keep_password = false;
3321  }
3322  else if (port && strcmp(ci->keyword, "port") == 0)
3323  {
3324  if (!(ci->val && strcmp(port, ci->val) == 0))
3325  keep_password = false;
3326  }
3327  }
3328 
3329  /* While here, determine how many option slots there are */
3330  nconnopts = ci - cinfo;
3331  }
3332  }
3333  else
3334  {
3335  /* We failed to create the cinfo structure */
3336  pg_log_error("out of memory");
3337  success = false;
3338  }
3339 
3340  /*
3341  * If the user asked to be prompted for a password, ask for one now. If
3342  * not, use the password from the old connection, provided the username
3343  * etc have not changed. Otherwise, try to connect without a password
3344  * first, and then ask for a password if needed.
3345  *
3346  * XXX: this behavior leads to spurious connection attempts recorded in
3347  * the postmaster's log. But libpq offers no API that would let us obtain
3348  * a password and then continue with the first connection attempt.
3349  */
3350  if (pset.getPassword == TRI_YES && success)
3351  {
3352  bool canceled = false;
3353 
3354  /*
3355  * If a connstring or URI is provided, we don't know which username
3356  * will be used, since we haven't dug that out of the connstring.
3357  * Don't risk issuing a misleading prompt. As in startup.c, it does
3358  * not seem worth working harder, since this getPassword setting is
3359  * normally only used in noninteractive cases.
3360  */
3361  password = prompt_for_password(has_connection_string ? NULL : user,
3362  &canceled);
3363  success = !canceled;
3364  }
3365 
3366  /*
3367  * Consider whether to force client_encoding to "auto" (overriding
3368  * anything in the connection string). We do so if we have a terminal
3369  * connection and there is no PGCLIENTENCODING environment setting.
3370  */
3371  if (pset.notty || getenv("PGCLIENTENCODING"))
3372  client_encoding = NULL;
3373  else
3374  client_encoding = "auto";
3375 
3376  /* Loop till we have a connection or fail, which we might've already */
3377  while (success)
3378  {
3379  const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
3380  const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
3381  int paramnum = 0;
3382  PQconninfoOption *ci;
3383 
3384  /*
3385  * Copy non-default settings into the PQconnectdbParams parameter
3386  * arrays; but inject any values specified old-style, as well as any
3387  * interactively-obtained password, and a couple of fields we want to
3388  * set forcibly.
3389  *
3390  * If you change this code, see also the initial-connection code in
3391  * main().
3392  */
3393  for (ci = cinfo; ci->keyword; ci++)
3394  {
3395  keywords[paramnum] = ci->keyword;
3396 
3397  if (dbname && strcmp(ci->keyword, "dbname") == 0)
3398  values[paramnum++] = dbname;
3399  else if (user && strcmp(ci->keyword, "user") == 0)
3400  values[paramnum++] = user;
3401  else if (host && strcmp(ci->keyword, "host") == 0)
3402  values[paramnum++] = host;
3403  else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
3404  {
3405  /* If we're changing the host value, drop any old hostaddr */
3406  values[paramnum++] = NULL;
3407  }
3408  else if (port && strcmp(ci->keyword, "port") == 0)
3409  values[paramnum++] = port;
3410  /* If !keep_password, we unconditionally drop old password */
3411  else if ((password || !keep_password) &&
3412  strcmp(ci->keyword, "password") == 0)
3413  values[paramnum++] = password;
3414  else if (strcmp(ci->keyword, "fallback_application_name") == 0)
3415  values[paramnum++] = pset.progname;
3416  else if (client_encoding &&
3417  strcmp(ci->keyword, "client_encoding") == 0)
3418  values[paramnum++] = client_encoding;
3419  else if (ci->val)
3420  values[paramnum++] = ci->val;
3421  /* else, don't bother making libpq parse this keyword */
3422  }
3423  /* add array terminator */
3424  keywords[paramnum] = NULL;
3425  values[paramnum] = NULL;
3426 
3427  /* Note we do not want libpq to re-expand the dbname parameter */
3428  n_conn = PQconnectdbParams(keywords, values, false);
3429 
3430  pg_free(keywords);
3431  pg_free(values);
3432 
3433  if (PQstatus(n_conn) == CONNECTION_OK)
3434  break;
3435 
3436  /*
3437  * Connection attempt failed; either retry the connection attempt with
3438  * a new password, or give up.
3439  */
3441  {
3442  bool canceled = false;
3443 
3444  /*
3445  * Prompt for password using the username we actually connected
3446  * with --- it might've come out of "dbname" rather than "user".
3447  */
3448  password = prompt_for_password(PQuser(n_conn), &canceled);
3449  PQfinish(n_conn);
3450  n_conn = NULL;
3451  success = !canceled;
3452  continue;
3453  }
3454 
3455  /*
3456  * We'll report the error below ... unless n_conn is NULL, indicating
3457  * that libpq didn't have enough memory to make a PGconn.
3458  */
3459  if (n_conn == NULL)
3460  pg_log_error("out of memory");
3461 
3462  success = false;
3463  } /* end retry loop */
3464 
3465  /* Release locally allocated data, whether we succeeded or not */
3466  if (password)
3467  pg_free(password);
3468  if (cinfo)
3469  PQconninfoFree(cinfo);
3470 
3471  if (!success)
3472  {
3473  /*
3474  * Failed to connect to the database. In interactive mode, keep the
3475  * previous connection to the DB; in scripting mode, close our
3476  * previous connection as well.
3477  */
3479  {
3480  if (n_conn)
3481  {
3482  pg_log_info("%s", PQerrorMessage(n_conn));
3483  PQfinish(n_conn);
3484  }
3485 
3486  /* pset.db is left unmodified */
3487  if (o_conn)
3488  pg_log_info("Previous connection kept");
3489  }
3490  else
3491  {
3492  if (n_conn)
3493  {
3494  pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
3495  PQfinish(n_conn);
3496  }
3497 
3498  if (o_conn)
3499  {
3500  /*
3501  * Transition to having no connection.
3502  *
3503  * Unlike CheckConnection(), we close the old connection
3504  * immediately to prevent its parameters from being re-used.
3505  * This is so that a script cannot accidentally reuse
3506  * parameters it did not expect to. Otherwise, the state
3507  * cleanup should be the same as in CheckConnection().
3508  */
3509  PQfinish(o_conn);
3510  pset.db = NULL;
3511  ResetCancelConn();
3512  UnsyncVariables();
3513  }
3514 
3515  /* On the same reasoning, release any dead_conn to prevent reuse */
3516  if (pset.dead_conn)
3517  {
3519  pset.dead_conn = NULL;
3520  }
3521  }
3522 
3523  return false;
3524  }
3525 
3526  /*
3527  * Replace the old connection with the new one, and update
3528  * connection-dependent variables. Keep the resynchronization logic in
3529  * sync with CheckConnection().
3530  */
3531  PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
3532  pset.db = n_conn;
3533  SyncVariables();
3534  connection_warnings(false); /* Must be after SyncVariables */
3535 
3536  /* Tell the user about the new connection */
3537  if (!pset.quiet)
3538  {
3539  if (!o_conn ||
3540  param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
3541  param_is_newly_set(PQport(o_conn), PQport(pset.db)))
3542  {
3543  char *host = PQhost(pset.db);
3544  char *hostaddr = PQhostaddr(pset.db);
3545 
3546  if (is_unixsock_path(host))
3547  {
3548  /* hostaddr overrides host */
3549  if (hostaddr && *hostaddr)
3550  printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
3551  PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
3552  else
3553  printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
3554  PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
3555  }
3556  else
3557  {
3558  if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
3559  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
3560  PQdb(pset.db), PQuser(pset.db), host, hostaddr, PQport(pset.db));
3561  else
3562  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
3563  PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
3564  }
3565  }
3566  else
3567  printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
3568  PQdb(pset.db), PQuser(pset.db));
3569  }
3570 
3571  /* Drop no-longer-needed connection(s) */
3572  if (o_conn)
3573  PQfinish(o_conn);
3574  if (pset.dead_conn)
3575  {
3577  pset.dead_conn = NULL;
3578  }
3579 
3580  return true;
3581 }
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:220
bool recognized_connection_string(const char *connstr)
Definition: common.c:2312
static Datum values[MAXATTR]
Definition: bootstrap.c:156
void ResetCancelConn(void)
Definition: cancel.c:100
static char * prompt_for_password(const char *username, bool *canceled)
Definition: command.c:3073
static bool param_is_newly_set(const char *old_val, const char *new_val)
Definition: command.c:3101
void UnsyncVariables(void)
Definition: command.c:3749
void SyncVariables(void)
Definition: command.c:3708
void connection_warnings(bool in_startup)
Definition: command.c:3585
int errmsg(const char *fmt,...)
Definition: elog.c:909
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5363
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6649
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:657
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6616
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1472
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:6672
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6598
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:6554
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6821
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6770
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6717
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4257
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6624
char * PQport(const PGconn *conn)
Definition: fe-connect.c:6685
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6938
void PQfreemem(void *ptr)
Definition: fe-exec.c:3796
void pg_free(void *ptr)
Definition: fe_memutils.c:105
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static bool success
Definition: initdb.c:166
return false
Definition: isn.c:131
@ CONNECTION_OK
Definition: libpq-fe.h:58
#define pg_log_error(...)
Definition: logging.h:80
#define pg_log_info(...)
Definition: logging.h:88
static char * user
Definition: pg_regress.c:95
static int port
Definition: pg_regress.c:92
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:93
static char * password
Definition: streamutil.c:53
char * dbname
Definition: streamutil.c:51
PGconn * dead_conn
Definition: settings.h:125
enum trivalue getPassword
Definition: settings.h:104
bool cur_cmd_interactive
Definition: settings.h:107
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37

References _, Assert(), CONNECTION_OK, connection_warnings(), _psqlSettings::cur_cmd_interactive, _psqlSettings::db, dbname, _psqlSettings::dead_conn, errmsg(), _psqlSettings::getPassword, is_unixsock_path(), _PQconninfoOption::keyword, NoticeProcessor(), _psqlSettings::notty, param_is_newly_set(), password, pg_free(), pg_log_error, pg_log_info, pg_malloc(), port, PQconndefaults(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQconninfo(), PQconninfoFree(), PQconninfoParse(), PQdb(), PQerrorMessage(), PQfinish(), PQfreemem(), PQhost(), PQhostaddr(), PQport(), PQsetNoticeProcessor(), PQstatus(), PQuser(), printf, _psqlSettings::progname, prompt_for_password(), pset, _psqlSettings::quiet, recognized_connection_string(), ResetCancelConn(), success, SyncVariables(), TRI_NO, TRI_YES, UnsyncVariables(), user, _PQconninfoOption::val, and values.

Referenced by exec_command_connect().

◆ do_edit()

static bool do_edit ( const char *  filename_arg,
PQExpBuffer  query_buf,
int  lineno,
bool  discard_on_quit,
bool edited 
)
static

Definition at line 3850 of file command.c.

3852 {
3853  char fnametmp[MAXPGPATH];
3854  FILE *stream = NULL;
3855  const char *fname;
3856  bool error = false;
3857  int fd;
3858  struct stat before,
3859  after;
3860 
3861  if (filename_arg)
3862  fname = filename_arg;
3863  else
3864  {
3865  /* make a temp file to edit */
3866 #ifndef WIN32
3867  const char *tmpdir = getenv("TMPDIR");
3868 
3869  if (!tmpdir)
3870  tmpdir = "/tmp";
3871 #else
3872  char tmpdir[MAXPGPATH];
3873  int ret;
3874 
3875  ret = GetTempPath(MAXPGPATH, tmpdir);
3876  if (ret == 0 || ret > MAXPGPATH)
3877  {
3878  pg_log_error("could not locate temporary directory: %s",
3879  !ret ? strerror(errno) : "");
3880  return false;
3881  }
3882 #endif
3883 
3884  /*
3885  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
3886  * current directory to the supplied path unless we use only
3887  * backslashes, so we do that.
3888  */
3889 #ifndef WIN32
3890  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
3891  "/", (int) getpid());
3892 #else
3893  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
3894  "" /* trailing separator already present */ , (int) getpid());
3895 #endif
3896 
3897  fname = (const char *) fnametmp;
3898 
3899  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
3900  if (fd != -1)
3901  stream = fdopen(fd, "w");
3902 
3903  if (fd == -1 || !stream)
3904  {
3905  pg_log_error("could not open temporary file \"%s\": %m", fname);
3906  error = true;
3907  }
3908  else
3909  {
3910  unsigned int ql = query_buf->len;
3911 
3912  /* force newline-termination of what we send to editor */
3913  if (ql > 0 && query_buf->data[ql - 1] != '\n')
3914  {
3915  appendPQExpBufferChar(query_buf, '\n');
3916  ql++;
3917  }
3918 
3919  if (fwrite(query_buf->data, 1, ql, stream) != ql)
3920  {
3921  pg_log_error("%s: %m", fname);
3922 
3923  if (fclose(stream) != 0)
3924  pg_log_error("%s: %m", fname);
3925 
3926  if (remove(fname) != 0)
3927  pg_log_error("%s: %m", fname);
3928 
3929  error = true;
3930  }
3931  else if (fclose(stream) != 0)
3932  {
3933  pg_log_error("%s: %m", fname);
3934  if (remove(fname) != 0)
3935  pg_log_error("%s: %m", fname);
3936  error = true;
3937  }
3938  else
3939  {
3940  struct utimbuf ut;
3941 
3942  /*
3943  * Try to set the file modification time of the temporary file
3944  * a few seconds in the past. Otherwise, the low granularity
3945  * (one second, or even worse on some filesystems) that we can
3946  * portably measure with stat(2) could lead us to not
3947  * recognize a modification, if the user typed very quickly.
3948  *
3949  * This is a rather unlikely race condition, so don't error
3950  * out if the utime(2) call fails --- that would make the cure
3951  * worse than the disease.
3952  */
3953  ut.modtime = ut.actime = time(NULL) - 2;
3954  (void) utime(fname, &ut);
3955  }
3956  }
3957  }
3958 
3959  if (!error && stat(fname, &before) != 0)
3960  {
3961  pg_log_error("%s: %m", fname);
3962  error = true;
3963  }
3964 
3965  /* call editor */
3966  if (!error)
3967  error = !editFile(fname, lineno);
3968 
3969  if (!error && stat(fname, &after) != 0)
3970  {
3971  pg_log_error("%s: %m", fname);
3972  error = true;
3973  }
3974 
3975  /* file was edited if the size or modification time has changed */
3976  if (!error &&
3977  (before.st_size != after.st_size ||
3978  before.st_mtime != after.st_mtime))
3979  {
3980  stream = fopen(fname, PG_BINARY_R);
3981  if (!stream)
3982  {
3983  pg_log_error("%s: %m", fname);
3984  error = true;
3985  }
3986  else
3987  {
3988  /* read file back into query_buf */
3989  char line[1024];
3990 
3991  resetPQExpBuffer(query_buf);
3992  while (fgets(line, sizeof(line), stream) != NULL)
3993  appendPQExpBufferStr(query_buf, line);
3994 
3995  if (ferror(stream))
3996  {
3997  pg_log_error("%s: %m", fname);
3998  error = true;
3999  resetPQExpBuffer(query_buf);
4000  }
4001  else if (edited)
4002  {
4003  *edited = true;
4004  }
4005 
4006  fclose(stream);
4007  }
4008  }
4009  else
4010  {
4011  /*
4012  * If the file was not modified, and the caller requested it, discard
4013  * the query buffer.
4014  */
4015  if (discard_on_quit)
4016  resetPQExpBuffer(query_buf);
4017  }
4018 
4019  /* remove temp file */
4020  if (!filename_arg)
4021  {
4022  if (remove(fname) == -1)
4023  {
4024  pg_log_error("%s: %m", fname);
4025  error = true;
4026  }
4027  }
4028 
4029  return !error;
4030 }
#define PG_BINARY_R
Definition: c.h:1270
static bool editFile(const char *fname, int lineno)
Definition: command.c:3769
#define MAXPGPATH
#define strerror
Definition: port.h:235
#define snprintf
Definition: port.h:222
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static int before(chr x, chr y)
Definition: regc_locale.c:492
static void error(void)
Definition: sql-dyntest.c:147
#define stat
Definition: win32_port.h:283

References appendPQExpBufferChar(), appendPQExpBufferStr(), before(), PQExpBufferData::data, editFile(), error(), fd(), PQExpBufferData::len, MAXPGPATH, PG_BINARY_R, pg_log_error, resetPQExpBuffer(), snprintf, stat::st_mtime, stat::st_size, stat, and strerror.

Referenced by exec_command_edit(), and exec_command_ef_ev().

◆ do_pset()

bool do_pset ( const char *  param,
const char *  value,
printQueryOpt popt,
bool  quiet 
)

Definition at line 4198 of file command.c.

4199 {
4200  size_t vallen = 0;
4201 
4202  Assert(param != NULL);
4203 
4204  if (value)
4205  vallen = strlen(value);
4206 
4207  /* set format */
4208  if (strcmp(param, "format") == 0)
4209  {
4210  static const struct fmt
4211  {
4212  const char *name;
4213  enum printFormat number;
4214  } formats[] =
4215  {
4216  /* remember to update error message below when adding more */
4217  {"aligned", PRINT_ALIGNED},
4218  {"asciidoc", PRINT_ASCIIDOC},
4219  {"csv", PRINT_CSV},
4220  {"html", PRINT_HTML},
4221  {"latex", PRINT_LATEX},
4222  {"troff-ms", PRINT_TROFF_MS},
4223  {"unaligned", PRINT_UNALIGNED},
4224  {"wrapped", PRINT_WRAPPED}
4225  };
4226 
4227  if (!value)
4228  ;
4229  else
4230  {
4231  int match_pos = -1;
4232 
4233  for (int i = 0; i < lengthof(formats); i++)
4234  {
4235  if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
4236  {
4237  if (match_pos < 0)
4238  match_pos = i;
4239  else
4240  {
4241  pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
4242  value,
4243  formats[match_pos].name, formats[i].name);
4244  return false;
4245  }
4246  }
4247  }
4248  if (match_pos >= 0)
4249  popt->topt.format = formats[match_pos].number;
4250  else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
4251  {
4252  /*
4253  * We must treat latex-longtable specially because latex is a
4254  * prefix of it; if both were in the table above, we'd think
4255  * "latex" is ambiguous.
4256  */
4258  }
4259  else
4260  {
4261  pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
4262  return false;
4263  }
4264  }
4265  }
4266 
4267  /* set table line style */
4268  else if (strcmp(param, "linestyle") == 0)
4269  {
4270  if (!value)
4271  ;
4272  else if (pg_strncasecmp("ascii", value, vallen) == 0)
4273  popt->topt.line_style = &pg_asciiformat;
4274  else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
4276  else if (pg_strncasecmp("unicode", value, vallen) == 0)
4277  popt->topt.line_style = &pg_utf8format;
4278  else
4279  {
4280  pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
4281  return false;
4282  }
4283  }
4284 
4285  /* set unicode border line style */
4286  else if (strcmp(param, "unicode_border_linestyle") == 0)
4287  {
4288  if (!value)
4289  ;
4290  else if (set_unicode_line_style(value, vallen,
4292  refresh_utf8format(&(popt->topt));
4293  else
4294  {
4295  pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4296  return false;
4297  }
4298  }
4299 
4300  /* set unicode column line style */
4301  else if (strcmp(param, "unicode_column_linestyle") == 0)
4302  {
4303  if (!value)
4304  ;
4305  else if (set_unicode_line_style(value, vallen,
4307  refresh_utf8format(&(popt->topt));
4308  else
4309  {
4310  pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4311  return false;
4312  }
4313  }
4314 
4315  /* set unicode header line style */
4316  else if (strcmp(param, "unicode_header_linestyle") == 0)
4317  {
4318  if (!value)
4319  ;
4320  else if (set_unicode_line_style(value, vallen,
4322  refresh_utf8format(&(popt->topt));
4323  else
4324  {
4325  pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4326  return false;
4327  }
4328  }
4329 
4330  /* set border style/width */
4331  else if (strcmp(param, "border") == 0)
4332  {
4333  if (value)
4334  popt->topt.border = atoi(value);
4335  }
4336 
4337  /* set expanded/vertical mode */
4338  else if (strcmp(param, "x") == 0 ||
4339  strcmp(param, "expanded") == 0 ||
4340  strcmp(param, "vertical") == 0)
4341  {
4342  if (value && pg_strcasecmp(value, "auto") == 0)
4343  popt->topt.expanded = 2;
4344  else if (value)
4345  {
4346  bool on_off;
4347 
4348  if (ParseVariableBool(value, NULL, &on_off))
4349  popt->topt.expanded = on_off ? 1 : 0;
4350  else
4351  {
4352  PsqlVarEnumError(param, value, "on, off, auto");
4353  return false;
4354  }
4355  }
4356  else
4357  popt->topt.expanded = !popt->topt.expanded;
4358  }
4359 
4360  /* field separator for CSV format */
4361  else if (strcmp(param, "csv_fieldsep") == 0)
4362  {
4363  if (value)
4364  {
4365  /* CSV separator has to be a one-byte character */
4366  if (strlen(value) != 1)
4367  {
4368  pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
4369  return false;
4370  }
4371  if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
4372  {
4373  pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
4374  return false;
4375  }
4376  popt->topt.csvFieldSep[0] = value[0];
4377  }
4378  }
4379 
4380  /* locale-aware numeric output */
4381  else if (strcmp(param, "numericlocale") == 0)
4382  {
4383  if (value)
4384  return ParseVariableBool(value, param, &popt->topt.numericLocale);
4385  else
4386  popt->topt.numericLocale = !popt->topt.numericLocale;
4387  }
4388 
4389  /* null display */
4390  else if (strcmp(param, "null") == 0)
4391  {
4392  if (value)
4393  {
4394  free(popt->nullPrint);
4395  popt->nullPrint = pg_strdup(value);
4396  }
4397  }
4398 
4399  /* field separator for unaligned text */
4400  else if (strcmp(param, "fieldsep") == 0)
4401  {
4402  if (value)
4403  {
4404  free(popt->topt.fieldSep.separator);
4406  popt->topt.fieldSep.separator_zero = false;
4407  }
4408  }
4409 
4410  else if (strcmp(param, "fieldsep_zero") == 0)
4411  {
4412  free(popt->topt.fieldSep.separator);
4413  popt->topt.fieldSep.separator = NULL;
4414  popt->topt.fieldSep.separator_zero = true;
4415  }
4416 
4417  /* record separator for unaligned text */
4418  else if (strcmp(param, "recordsep") == 0)
4419  {
4420  if (value)
4421  {
4422  free(popt->topt.recordSep.separator);
4424  popt->topt.recordSep.separator_zero = false;
4425  }
4426  }
4427 
4428  else if (strcmp(param, "recordsep_zero") == 0)
4429  {
4430  free(popt->topt.recordSep.separator);
4431  popt->topt.recordSep.separator = NULL;
4432  popt->topt.recordSep.separator_zero = true;
4433  }
4434 
4435  /* toggle between full and tuples-only format */
4436  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4437  {
4438  if (value)
4439  return ParseVariableBool(value, param, &popt->topt.tuples_only);
4440  else
4441  popt->topt.tuples_only = !popt->topt.tuples_only;
4442  }
4443 
4444  /* set title override */
4445  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4446  {
4447  free(popt->title);
4448  if (!value)
4449  popt->title = NULL;
4450  else
4451  popt->title = pg_strdup(value);
4452  }
4453 
4454  /* set HTML table tag options */
4455  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4456  {
4457  free(popt->topt.tableAttr);
4458  if (!value)
4459  popt->topt.tableAttr = NULL;
4460  else
4461  popt->topt.tableAttr = pg_strdup(value);
4462  }
4463 
4464  /* toggle use of pager */
4465  else if (strcmp(param, "pager") == 0)
4466  {
4467  if (value && pg_strcasecmp(value, "always") == 0)
4468  popt->topt.pager = 2;
4469  else if (value)
4470  {
4471  bool on_off;
4472 
4473  if (!ParseVariableBool(value, NULL, &on_off))
4474  {
4475  PsqlVarEnumError(param, value, "on, off, always");
4476  return false;
4477  }
4478  popt->topt.pager = on_off ? 1 : 0;
4479  }
4480  else if (popt->topt.pager == 1)
4481  popt->topt.pager = 0;
4482  else
4483  popt->topt.pager = 1;
4484  }
4485 
4486  /* set minimum lines for pager use */
4487  else if (strcmp(param, "pager_min_lines") == 0)
4488  {
4489  if (value)
4490  popt->topt.pager_min_lines = atoi(value);
4491  }
4492 
4493  /* disable "(x rows)" footer */
4494  else if (strcmp(param, "footer") == 0)
4495  {
4496  if (value)
4497  return ParseVariableBool(value, param, &popt->topt.default_footer);
4498  else
4499  popt->topt.default_footer = !popt->topt.default_footer;
4500  }
4501 
4502  /* set border style/width */
4503  else if (strcmp(param, "columns") == 0)
4504  {
4505  if (value)
4506  popt->topt.columns = atoi(value);
4507  }
4508  else
4509  {
4510  pg_log_error("\\pset: unknown option: %s", param);
4511  return false;
4512  }
4513 
4514  if (!quiet)
4515  printPsetInfo(param, &pset.popt);
4516 
4517  return true;
4518 }
#define lengthof(array)
Definition: c.h:734
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4155
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:4524
const char * name
Definition: encode.c:561
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3632
const printTextFormat pg_asciiformat
Definition: print.c:56
const printTextFormat pg_asciiformat_old
Definition: print.c:77
printTextFormat pg_utf8format
Definition: print.c:99
printFormat
Definition: print.h:29
#define free(a)
Definition: header.h:65
static struct @142 value
int i
Definition: isn.c:73
static void const char * fmt
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
printQueryOpt popt
Definition: settings.h:91
printTableOpt topt
Definition: print.h:169
char * nullPrint
Definition: print.h:170
char * title
Definition: print.h:171
unsigned short int expanded
Definition: print.h:102
unicode_linestyle unicode_border_linestyle
Definition: print.h:125
bool tuples_only
Definition: print.h:110
int columns
Definition: print.h:124
enum printFormat format
Definition: print.h:101
struct separator fieldSep
Definition: print.h:116
struct separator recordSep
Definition: print.h:117
char csvFieldSep[2]
Definition: print.h:118
const printTextFormat * line_style
Definition: print.h:115
bool default_footer
Definition: print.h:113
int pager_min_lines
Definition: print.h:108
unsigned short int pager
Definition: print.h:106
char * tableAttr
Definition: print.h:121
bool numericLocale
Definition: print.h:119
unsigned short int border
Definition: print.h:104
unicode_linestyle unicode_header_linestyle
Definition: print.h:127
unicode_linestyle unicode_column_linestyle
Definition: print.h:126
bool separator_zero
Definition: print.h:96
char * separator
Definition: print.h:95
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:417
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107

References Assert(), printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::fieldSep, fmt, printTableOpt::format, free, i, lengthof, printTableOpt::line_style, name, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, ParseVariableBool(), pg_asciiformat, pg_asciiformat_old, pg_log_error, pg_strcasecmp(), pg_strdup(), pg_strncasecmp(), pg_utf8format, _psqlSettings::popt, PRINT_ALIGNED, PRINT_ASCIIDOC, PRINT_CSV, PRINT_HTML, PRINT_LATEX, PRINT_LATEX_LONGTABLE, PRINT_TROFF_MS, PRINT_UNALIGNED, PRINT_WRAPPED, printPsetInfo(), pset, PsqlVarEnumError(), printTableOpt::recordSep, refresh_utf8format(), separator::separator, separator::separator_zero, set_unicode_line_style(), printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, printTableOpt::unicode_header_linestyle, and value.

Referenced by exec_command_a(), exec_command_C(), exec_command_f(), exec_command_html(), exec_command_pset(), exec_command_t(), exec_command_T(), exec_command_x(), parse_psql_options(), and process_command_g_options().

◆ do_shell()

static bool do_shell ( const char *  command)
static

Definition at line 4894 of file command.c.

4895 {
4896  int result;
4897 
4898  if (!command)
4899  {
4900  char *sys;
4901  const char *shellName;
4902 
4903  shellName = getenv("SHELL");
4904 #ifdef WIN32
4905  if (shellName == NULL)
4906  shellName = getenv("COMSPEC");
4907 #endif
4908  if (shellName == NULL)
4909  shellName = DEFAULT_SHELL;
4910 
4911  /* See EDITOR handling comment for an explanation */
4912 #ifndef WIN32
4913  sys = psprintf("exec %s", shellName);
4914 #else
4915  sys = psprintf("\"%s\"", shellName);
4916 #endif
4917  result = system(sys);
4918  free(sys);
4919  }
4920  else
4921  result = system(command);
4922 
4923  if (result == 127 || result == -1)
4924  {
4925  pg_log_error("\\!: failed");
4926  return false;
4927  }
4928  return true;
4929 }
#define DEFAULT_SHELL
Definition: command.c:4884
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

References DEFAULT_SHELL, free, pg_log_error, and psprintf().

Referenced by exec_command_shell_escape().

◆ do_watch()

static bool do_watch ( PQExpBuffer  query_buf,
double  sleep 
)
static

Definition at line 4938 of file command.c.

4939 {
4940  long sleep_ms = (long) (sleep * 1000);
4941  printQueryOpt myopt = pset.popt;
4942  const char *strftime_fmt;
4943  const char *user_title;
4944  char *title;
4945  const char *pagerprog = NULL;
4946  FILE *pagerpipe = NULL;
4947  int title_len;
4948  int res = 0;
4949 #ifdef HAVE_POSIX_DECL_SIGWAIT
4950  sigset_t sigalrm_sigchld_sigint;
4951  sigset_t sigalrm_sigchld;
4952  sigset_t sigint;
4953  struct itimerval interval;
4954  bool done = false;
4955 #endif
4956 
4957  if (!query_buf || query_buf->len <= 0)
4958  {
4959  pg_log_error("\\watch cannot be used with an empty query");
4960  return false;
4961  }
4962 
4963 #ifdef HAVE_POSIX_DECL_SIGWAIT
4964  sigemptyset(&sigalrm_sigchld_sigint);
4965  sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
4966  sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
4967  sigaddset(&sigalrm_sigchld_sigint, SIGINT);
4968 
4969  sigemptyset(&sigalrm_sigchld);
4970  sigaddset(&sigalrm_sigchld, SIGCHLD);
4971  sigaddset(&sigalrm_sigchld, SIGALRM);
4972 
4973  sigemptyset(&sigint);
4974  sigaddset(&sigint, SIGINT);
4975 
4976  /*
4977  * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
4978  * configured), to avoid races. sigwait() will receive them.
4979  */
4980  sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
4981 
4982  /*
4983  * Set a timer to interrupt sigwait() so we can run the query at the
4984  * requested intervals.
4985  */
4986  interval.it_value.tv_sec = sleep_ms / 1000;
4987  interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
4988  interval.it_interval = interval.it_value;
4989  if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
4990  {
4991  pg_log_error("could not set timer: %m");
4992  done = true;
4993  }
4994 #endif
4995 
4996  /*
4997  * For \watch, we ignore the size of the result and always use the pager
4998  * if PSQL_WATCH_PAGER is set. We also ignore the regular PSQL_PAGER or
4999  * PAGER environment variables, because traditional pagers probably won't
5000  * be very useful for showing a stream of results.
5001  */
5002 #ifdef HAVE_POSIX_DECL_SIGWAIT
5003  pagerprog = getenv("PSQL_WATCH_PAGER");
5004 #endif
5005  if (pagerprog && myopt.topt.pager)
5006  {
5008  pagerpipe = popen(pagerprog, "w");
5009 
5010  if (!pagerpipe)
5011  /* silently proceed without pager */
5013  }
5014 
5015  /*
5016  * Choose format for timestamps. We might eventually make this a \pset
5017  * option. In the meantime, using a variable for the format suppresses
5018  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5019  */
5020  strftime_fmt = "%c";
5021 
5022  /*
5023  * Set up rendering options, in particular, disable the pager unless
5024  * PSQL_WATCH_PAGER was successfully launched.
5025  */
5026  if (!pagerpipe)
5027  myopt.topt.pager = 0;
5028 
5029 
5030  /*
5031  * If there's a title in the user configuration, make sure we have room
5032  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5033  * bytes for the rest.
5034  */
5035  user_title = myopt.title;
5036  title_len = (user_title ? strlen(user_title) : 0) + 256;
5037  title = pg_malloc(title_len);
5038 
5039  for (;;)
5040  {
5041  time_t timer;
5042  char timebuf[128];
5043 
5044  /*
5045  * Prepare title for output. Note that we intentionally include a
5046  * newline at the end of the title; this is somewhat historical but it
5047  * makes for reasonably nicely formatted output in simple cases.
5048  */
5049  timer = time(NULL);
5050  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5051 
5052  if (user_title)
5053  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5054  user_title, timebuf, sleep);
5055  else
5056  snprintf(title, title_len, _("%s (every %gs)\n"),
5057  timebuf, sleep);
5058  myopt.title = title;
5059 
5060  /* Run the query and print out the results */
5061  res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe);
5062 
5063  /*
5064  * PSQLexecWatch handles the case where we can no longer repeat the
5065  * query, and returns 0 or -1.
5066  */
5067  if (res <= 0)
5068  break;
5069 
5070  if (pagerpipe && ferror(pagerpipe))
5071  break;
5072 
5073 #ifndef HAVE_POSIX_DECL_SIGWAIT
5074 
5075  /*
5076  * Set up cancellation of 'watch' via SIGINT. We redo this each time
5077  * through the loop since it's conceivable something inside
5078  * PSQLexecWatch could change sigint_interrupt_jmp.
5079  */
5080  if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
5081  break;
5082 
5083  /*
5084  * Enable 'watch' cancellations and wait a while before running the
5085  * query again. Break the sleep into short intervals (at most 1s).
5086  */
5087  sigint_interrupt_enabled = true;
5088  for (long i = sleep_ms; i > 0;)
5089  {
5090  long s = Min(i, 1000L);
5091 
5092  pg_usleep(s * 1000L);
5093  if (cancel_pressed)
5094  break;
5095  i -= s;
5096  }
5097  sigint_interrupt_enabled = false;
5098 #else
5099  /* sigwait() will handle SIGINT. */
5100  sigprocmask(SIG_BLOCK, &sigint, NULL);
5101  if (cancel_pressed)
5102  done = true;
5103 
5104  /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5105  while (!done)
5106  {
5107  int signal_received;
5108 
5109  errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5110  if (errno != 0)
5111  {
5112  /* Some other signal arrived? */
5113  if (errno == EINTR)
5114  continue;
5115  else
5116  {
5117  pg_log_error("could not wait for signals: %m");
5118  done = true;
5119  break;
5120  }
5121  }
5122  /* On ^C or pager exit, it's time to stop running the query. */
5123  if (signal_received == SIGINT || signal_received == SIGCHLD)
5124  done = true;
5125  /* Otherwise, we must have SIGALRM. Time to run the query again. */
5126  break;
5127  }
5128 
5129  /* Unblock SIGINT so that slow queries can be interrupted. */
5130  sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5131  if (done)
5132  break;
5133 #endif
5134  }
5135 
5136  if (pagerpipe)
5137  {
5138  pclose(pagerpipe);
5140  }
5141 
5142 #ifdef HAVE_POSIX_DECL_SIGWAIT
5143  /* Disable the interval timer. */
5144  memset(&interval, 0, sizeof(interval));
5145  setitimer(ITIMER_REAL, &interval, NULL);
5146  /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5147  sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5148 #endif
5149 
5150  pg_free(title);
5151  return (res >= 0);
5152 }
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:247
volatile bool sigint_interrupt_enabled
Definition: common.c:245
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout)
Definition: common.c:595
#define Min(x, y)
Definition: c.h:986
void restore_sigpipe_trap(void)
Definition: print.c:3018
void disable_sigpipe_trap(void)
Definition: print.c:2995
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
void pg_usleep(long microsec)
Definition: signal.c:53
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
Definition: timer.c:86
#define SIGCHLD
Definition: win32_port.h:177
#define EINTR
Definition: win32_port.h:351
#define SIGALRM
Definition: win32_port.h:173
#define ITIMER_REAL
Definition: win32_port.h:195

References _, cancel_pressed, PQExpBufferData::data, disable_sigpipe_trap(), EINTR, i, ITIMER_REAL, PQExpBufferData::len, Min, printTableOpt::pager, pg_free(), pg_log_error, pg_malloc(), pg_usleep(), _psqlSettings::popt, pset, PSQLexecWatch(), res, restore_sigpipe_trap(), setitimer(), SIGALRM, SIGCHLD, sigint_interrupt_enabled, sigint_interrupt_jmp, snprintf, printQueryOpt::title, and printQueryOpt::topt.

Referenced by exec_command_watch().

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 5159 of file command.c.

5160 {
5162  {
5163  printf(_("********* QUERY **********\n"
5164  "%s\n"
5165  "**************************\n\n"), query);
5166  fflush(stdout);
5167  if (pset.logfile)
5168  {
5170  _("********* QUERY **********\n"
5171  "%s\n"
5172  "**************************\n\n"), query);
5173  fflush(pset.logfile);
5174  }
5175 
5177  return false;
5178  }
5179  return true;
5180 }
static void const char fflush(stdout)
#define fprintf
Definition: port.h:226
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
FILE * logfile
Definition: settings.h:116
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:143

References _, _psqlSettings::echo_hidden, fflush(), fprintf, _psqlSettings::logfile, printf, pset, PSQL_ECHO_HIDDEN_NOEXEC, PSQL_ECHO_HIDDEN_OFF, and generate_unaccent_rules::stdout.

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ editFile()

static bool editFile ( const char *  fname,
int  lineno 
)
static

Definition at line 3769 of file command.c.

3770 {
3771  const char *editorName;
3772  const char *editor_lineno_arg = NULL;
3773  char *sys;
3774  int result;
3775 
3776  Assert(fname != NULL);
3777 
3778  /* Find an editor to use */
3779  editorName = getenv("PSQL_EDITOR");
3780  if (!editorName)
3781  editorName = getenv("EDITOR");
3782  if (!editorName)
3783  editorName = getenv("VISUAL");
3784  if (!editorName)
3785  editorName = DEFAULT_EDITOR;
3786 
3787  /* Get line number argument, if we need it. */
3788  if (lineno > 0)
3789  {
3790  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
3791 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
3792  if (!editor_lineno_arg)
3793  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
3794 #endif
3795  if (!editor_lineno_arg)
3796  {
3797  pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
3798  return false;
3799  }
3800  }
3801 
3802  /*
3803  * On Unix the EDITOR value should *not* be quoted, since it might include
3804  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
3805  * if necessary. But this policy is not very workable on Windows, due to
3806  * severe brain damage in their command shell plus the fact that standard
3807  * program paths include spaces.
3808  */
3809 #ifndef WIN32
3810  if (lineno > 0)
3811  sys = psprintf("exec %s %s%d '%s'",
3812  editorName, editor_lineno_arg, lineno, fname);
3813  else
3814  sys = psprintf("exec %s '%s'",
3815  editorName, fname);
3816 #else
3817  if (lineno > 0)
3818  sys = psprintf("\"%s\" %s%d \"%s\"",
3819  editorName, editor_lineno_arg, lineno, fname);
3820  else
3821  sys = psprintf("\"%s\" \"%s\"",
3822  editorName, fname);
3823 #endif
3824  result = system(sys);
3825  if (result == -1)
3826  pg_log_error("could not start editor \"%s\"", editorName);
3827  else if (result == 127)
3828  pg_log_error("could not start /bin/sh");
3829  free(sys);
3830 
3831  return result == 0;
3832 }
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23
#define DEFAULT_EDITOR
Definition: settings.h:22

References Assert(), DEFAULT_EDITOR, DEFAULT_EDITOR_LINENUMBER_ARG, free, pg_log_error, and psprintf().

Referenced by do_edit().

◆ exec_command()

static backslashResult exec_command ( const char *  cmd,
PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 284 of file command.c.

289 {
291  bool active_branch = conditional_active(cstack);
292 
293  /*
294  * In interactive mode, warn when we're ignoring a command within a false
295  * \if-branch. But we continue on, so as to parse and discard the right
296  * amount of parameter text. Each individual backslash command subroutine
297  * is responsible for doing nothing after discarding appropriate
298  * arguments, if !active_branch.
299  */
300  if (pset.cur_cmd_interactive && !active_branch &&
301  !is_branching_command(cmd))
302  {
303  pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
304  cmd);
305  }
306 
307  if (strcmp(cmd, "a") == 0)
308  status = exec_command_a(scan_state, active_branch);
309  else if (strcmp(cmd, "C") == 0)
310  status = exec_command_C(scan_state, active_branch);
311  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
312  status = exec_command_connect(scan_state, active_branch);
313  else if (strcmp(cmd, "cd") == 0)
314  status = exec_command_cd(scan_state, active_branch, cmd);
315  else if (strcmp(cmd, "conninfo") == 0)
316  status = exec_command_conninfo(scan_state, active_branch);
317  else if (pg_strcasecmp(cmd, "copy") == 0)
318  status = exec_command_copy(scan_state, active_branch);
319  else if (strcmp(cmd, "copyright") == 0)
320  status = exec_command_copyright(scan_state, active_branch);
321  else if (strcmp(cmd, "crosstabview") == 0)
322  status = exec_command_crosstabview(scan_state, active_branch);
323  else if (cmd[0] == 'd')
324  status = exec_command_d(scan_state, active_branch, cmd);
325  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
326  status = exec_command_edit(scan_state, active_branch,
327  query_buf, previous_buf);
328  else if (strcmp(cmd, "ef") == 0)
329  status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
330  else if (strcmp(cmd, "ev") == 0)
331  status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
332  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
333  strcmp(cmd, "warn") == 0)
334  status = exec_command_echo(scan_state, active_branch, cmd);
335  else if (strcmp(cmd, "elif") == 0)
336  status = exec_command_elif(scan_state, cstack, query_buf);
337  else if (strcmp(cmd, "else") == 0)
338  status = exec_command_else(scan_state, cstack, query_buf);
339  else if (strcmp(cmd, "endif") == 0)
340  status = exec_command_endif(scan_state, cstack, query_buf);
341  else if (strcmp(cmd, "encoding") == 0)
342  status = exec_command_encoding(scan_state, active_branch);
343  else if (strcmp(cmd, "errverbose") == 0)
344  status = exec_command_errverbose(scan_state, active_branch);
345  else if (strcmp(cmd, "f") == 0)
346  status = exec_command_f(scan_state, active_branch);
347  else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
348  status = exec_command_g(scan_state, active_branch, cmd);
349  else if (strcmp(cmd, "gdesc") == 0)
350  status = exec_command_gdesc(scan_state, active_branch);
351  else if (strcmp(cmd, "gexec") == 0)
352  status = exec_command_gexec(scan_state, active_branch);
353  else if (strcmp(cmd, "gset") == 0)
354  status = exec_command_gset(scan_state, active_branch);
355  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
356  status = exec_command_help(scan_state, active_branch);
357  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
358  status = exec_command_html(scan_state, active_branch);
359  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
360  strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
361  status = exec_command_include(scan_state, active_branch, cmd);
362  else if (strcmp(cmd, "if") == 0)
363  status = exec_command_if(scan_state, cstack, query_buf);
364  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
365  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
366  status = exec_command_list(scan_state, active_branch, cmd);
367  else if (strncmp(cmd, "lo_", 3) == 0)
368  status = exec_command_lo(scan_state, active_branch, cmd);
369  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
370  status = exec_command_out(scan_state, active_branch);
371  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
372  status = exec_command_print(scan_state, active_branch,
373  query_buf, previous_buf);
374  else if (strcmp(cmd, "password") == 0)
375  status = exec_command_password(scan_state, active_branch);
376  else if (strcmp(cmd, "prompt") == 0)
377  status = exec_command_prompt(scan_state, active_branch, cmd);
378  else if (strcmp(cmd, "pset") == 0)
379  status = exec_command_pset(scan_state, active_branch);
380  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
381  status = exec_command_quit(scan_state, active_branch);
382  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
383  status = exec_command_reset(scan_state, active_branch, query_buf);
384  else if (strcmp(cmd, "s") == 0)
385  status = exec_command_s(scan_state, active_branch);
386  else if (strcmp(cmd, "set") == 0)
387  status = exec_command_set(scan_state, active_branch);
388  else if (strcmp(cmd, "setenv") == 0)
389  status = exec_command_setenv(scan_state, active_branch, cmd);
390  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
391  status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
392  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
393  status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
394  else if (strcmp(cmd, "t") == 0)
395  status = exec_command_t(scan_state, active_branch);
396  else if (strcmp(cmd, "T") == 0)
397  status = exec_command_T(scan_state, active_branch);
398  else if (strcmp(cmd, "timing") == 0)
399  status = exec_command_timing(scan_state, active_branch);
400  else if (strcmp(cmd, "unset") == 0)
401  status = exec_command_unset(scan_state, active_branch, cmd);
402  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
403  status = exec_command_write(scan_state, active_branch, cmd,
404  query_buf, previous_buf);
405  else if (strcmp(cmd, "watch") == 0)
406  status = exec_command_watch(scan_state, active_branch,
407  query_buf, previous_buf);
408  else if (strcmp(cmd, "x") == 0)
409  status = exec_command_x(scan_state, active_branch);
410  else if (strcmp(cmd, "z") == 0)
411  status = exec_command_z(scan_state, active_branch);
412  else if (strcmp(cmd, "!") == 0)
413  status = exec_command_shell_escape(scan_state, active_branch);
414  else if (strcmp(cmd, "?") == 0)
415  status = exec_command_slash_command_help(scan_state, active_branch);
416  else
418 
419  /*
420  * All the commands that return PSQL_CMD_SEND want to execute previous_buf
421  * if query_buf is empty. For convenience we implement that here, not in
422  * the individual command subroutines.
423  */
424  if (status == PSQL_CMD_SEND)
425  (void) copy_previous_query(query_buf, previous_buf);
426 
427  return status;
428 }
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1826
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:666
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1299
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1994
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1579
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3055
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1357
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2532
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1485
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1548
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:437
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2766
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2020
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2744
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1639
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1685
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1329
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2259
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1971
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1216
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:702
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2789
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:542
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1519
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1094
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2586
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2304
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2277
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2112
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2705
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1598
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1866
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2554
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:456
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1261
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1004
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1761
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:600
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:644
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2811
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:678
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2191
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2510
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2616
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2405
static bool is_branching_command(const char *cmd)
Definition: command.c:2993
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:489
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1502
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1895
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2245
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2357
@ PSQL_CMD_UNKNOWN
Definition: command.h:17
@ PSQL_CMD_SEND
Definition: command.h:18
enum _backslashResult backslashResult
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
#define pg_log_warning(...)
Definition: pgfnames.c:24

References conditional_active(), copy_previous_query(), _psqlSettings::cur_cmd_interactive, exec_command_a(), exec_command_C(), exec_command_cd(), exec_command_connect(), exec_command_conninfo(), exec_command_copy(), exec_command_copyright(), exec_command_crosstabview(), exec_command_d(), exec_command_echo(), exec_command_edit(), exec_command_ef_ev(), exec_command_elif(), exec_command_else(), exec_command_encoding(), exec_command_endif(), exec_command_errverbose(), exec_command_f(), exec_command_g(), exec_command_gdesc(), exec_command_gexec(), exec_command_gset(), exec_command_help(), exec_command_html(), exec_command_if(), exec_command_include(), exec_command_list(), exec_command_lo(), exec_command_out(), exec_command_password(), exec_command_print(), exec_command_prompt(), exec_command_pset(), exec_command_quit(), exec_command_reset(), exec_command_s(), exec_command_set(), exec_command_setenv(), exec_command_sf_sv(), exec_command_shell_escape(), exec_command_slash_command_help(), exec_command_t(), exec_command_T(), exec_command_timing(), exec_command_unset(), exec_command_watch(), exec_command_write(), exec_command_x(), exec_command_z(), is_branching_command(), pg_log_warning, pg_strcasecmp(), pset, PSQL_CMD_SEND, PSQL_CMD_UNKNOWN, and status().

Referenced by HandleSlashCmds().

◆ exec_command_a()

static backslashResult exec_command_a ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 437 of file command.c.

438 {
439  bool success = true;
440 
441  if (active_branch)
442  {
444  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
445  else
446  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
447  }
448 
450 }
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4198
@ PSQL_CMD_ERROR
Definition: command.h:22
@ PSQL_CMD_SKIP_LINE
Definition: command.h:19

References do_pset(), printTableOpt::format, _psqlSettings::popt, PRINT_ALIGNED, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, _psqlSettings::quiet, success, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_C()

static backslashResult exec_command_C ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 456 of file command.c.

457 {
458  bool success = true;
459 
460  if (active_branch)
461  {
462  char *opt = psql_scan_slash_option(scan_state,
463  OT_NORMAL, NULL, true);
464 
465  success = do_pset("title", opt, &pset.popt, pset.quiet);
466  free(opt);
467  }
468  else
469  ignore_slash_options(scan_state);
470 
472 }
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2946
@ OT_NORMAL
Definition: psqlscanslash.h:17
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)

References do_pset(), free, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, and success.

Referenced by exec_command().

◆ exec_command_cd()

static backslashResult exec_command_cd ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 542 of file command.c.

543 {
544  bool success = true;
545 
546  if (active_branch)
547  {
548  char *opt = psql_scan_slash_option(scan_state,
549  OT_NORMAL, NULL, true);
550  char *dir;
551 
552  if (opt)
553  dir = opt;
554  else
555  {
556 #ifndef WIN32
557  struct passwd *pw;
558  uid_t user_id = geteuid();
559 
560  errno = 0; /* clear errno before call */
561  pw = getpwuid(user_id);
562  if (!pw)
563  {
564  pg_log_error("could not get home directory for user ID %ld: %s",
565  (long) user_id,
566  errno ? strerror(errno) : _("user does not exist"));
568  }
569  dir = pw->pw_dir;
570 #else /* WIN32 */
571 
572  /*
573  * On Windows, 'cd' without arguments prints the current
574  * directory, so if someone wants to code this here instead...
575  */
576  dir = "/";
577 #endif /* WIN32 */
578  }
579 
580  if (chdir(dir) == -1)
581  {
582  pg_log_error("\\%s: could not change directory to \"%s\": %m",
583  cmd, dir);
584  success = false;
585  }
586 
587  if (opt)
588  free(opt);
589  }
590  else
591  ignore_slash_options(scan_state);
592 
594 }
exit(1)
#define EXIT_FAILURE
Definition: settings.h:162
int uid_t
Definition: win32_port.h:244

References _, exit(), EXIT_FAILURE, free, ignore_slash_options(), OT_NORMAL, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), strerror, and success.

Referenced by exec_command().

◆ exec_command_connect()

static backslashResult exec_command_connect ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 489 of file command.c.

490 {
491  bool success = true;
492 
493  if (active_branch)
494  {
495  static const char prefix[] = "-reuse-previous=";
496  char *opt1,
497  *opt2,
498  *opt3,
499  *opt4;
500  enum trivalue reuse_previous = TRI_DEFAULT;
501 
502  opt1 = read_connect_arg(scan_state);
503  if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
504  {
505  bool on_off;
506 
507  success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
508  "-reuse-previous",
509  &on_off);
510  if (success)
511  {
512  reuse_previous = on_off ? TRI_YES : TRI_NO;
513  free(opt1);
514  opt1 = read_connect_arg(scan_state);
515  }
516  }
517 
518  if (success) /* give up if reuse_previous was invalid */
519  {
520  opt2 = read_connect_arg(scan_state);
521  opt3 = read_connect_arg(scan_state);
522  opt4 = read_connect_arg(scan_state);
523 
524  success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
525 
526  free(opt2);
527  free(opt3);
528  free(opt4);
529  }
530  free(opt1);
531  }
532  else
533  ignore_slash_options(scan_state);
534 
536 }
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:3124
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:2843
trivalue
Definition: vacuumlo.c:35
@ TRI_DEFAULT
Definition: vacuumlo.c:36

References do_connect(), free, ignore_slash_options(), ParseVariableBool(), PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, read_connect_arg(), success, TRI_DEFAULT, TRI_NO, and TRI_YES.

Referenced by exec_command().

◆ exec_command_conninfo()

static backslashResult exec_command_conninfo ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 600 of file command.c.

601 {
602  if (active_branch)
603  {
604  char *db = PQdb(pset.db);
605 
606  if (db == NULL)
607  printf(_("You are currently not connected to a database.\n"));
608  else
609  {
610  char *host = PQhost(pset.db);
611  char *hostaddr = PQhostaddr(pset.db);
612 
613  if (is_unixsock_path(host))
614  {
615  /* hostaddr overrides host */
616  if (hostaddr && *hostaddr)
617  printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
618  db, PQuser(pset.db), hostaddr, PQport(pset.db));
619  else
620  printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
621  db, PQuser(pset.db), host, PQport(pset.db));
622  }
623  else
624  {
625  if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
626  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
627  db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
628  else
629  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
630  db, PQuser(pset.db), host, PQport(pset.db));
631  }
632  printSSLInfo();
633  printGSSInfo();
634  }
635  }
636 
637  return PSQL_CMD_SKIP_LINE;
638 }

References _, _psqlSettings::db, is_unixsock_path(), PQdb(), PQhost(), PQhostaddr(), PQport(), PQuser(), printf, printGSSInfo(), printSSLInfo(), pset, and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 644 of file command.c.

645 {
646  bool success = true;
647 
648  if (active_branch)
649  {
650  char *opt = psql_scan_slash_option(scan_state,
651  OT_WHOLE_LINE, NULL, false);
652 
653  success = do_copy(opt);
654  free(opt);
655  }
656  else
657  ignore_slash_whole_line(scan_state);
658 
660 }
bool do_copy(const char *args)
Definition: copy.c:268
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:2980
@ OT_WHOLE_LINE
Definition: psqlscanslash.h:21

References do_copy(), free, ignore_slash_whole_line(), OT_WHOLE_LINE, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and success.

Referenced by exec_command().

◆ exec_command_copyright()

static backslashResult exec_command_copyright ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 666 of file command.c.

667 {
668  if (active_branch)
669  print_copyright();
670 
671  return PSQL_CMD_SKIP_LINE;
672 }
void print_copyright(void)
Definition: help.c:691

References print_copyright(), and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_crosstabview()

static backslashResult exec_command_crosstabview ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 678 of file command.c.

679 {
681 
682  if (active_branch)
683  {
684  int i;
685 
686  for (i = 0; i < lengthof(pset.ctv_args); i++)
687  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
688  OT_NORMAL, NULL, true);
689  pset.crosstab_flag = true;
691  }
692  else
693  ignore_slash_options(scan_state);
694 
695  return status;
696 }
char * ctv_args[4]
Definition: settings.h:100
bool crosstab_flag
Definition: settings.h:99

References _psqlSettings::crosstab_flag, _psqlSettings::ctv_args, i, ignore_slash_options(), lengthof, OT_NORMAL, pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and status().

Referenced by exec_command().

◆ exec_command_d()

static backslashResult exec_command_d ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 702 of file command.c.

703 {
705  bool success = true;
706 
707  if (active_branch)
708  {
709  char *pattern;
710  bool show_verbose,
711  show_system;
712 
713  /* We don't do SQLID reduction on the pattern yet */
714  pattern = psql_scan_slash_option(scan_state,
715  OT_NORMAL, NULL, true);
716 
717  show_verbose = strchr(cmd, '+') ? true : false;
718  show_system = strchr(cmd, 'S') ? true : false;
719 
720  switch (cmd[1])
721  {
722  case '\0':
723  case '+':
724  case 'S':
725  if (pattern)
726  success = describeTableDetails(pattern, show_verbose, show_system);
727  else
728  /* standard listing of interesting things */
729  success = listTables("tvmsE", NULL, show_verbose, show_system);
730  break;
731  case 'A':
732  {
733  char *pattern2 = NULL;
734 
735  if (pattern && cmd[2] != '\0' && cmd[2] != '+')
736  pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
737 
738  switch (cmd[2])
739  {
740  case '\0':
741  case '+':
742  success = describeAccessMethods(pattern, show_verbose);
743  break;
744  case 'c':
745  success = listOperatorClasses(pattern, pattern2, show_verbose);
746  break;
747  case 'f':
748  success = listOperatorFamilies(pattern, pattern2, show_verbose);
749  break;
750  case 'o':
751  success = listOpFamilyOperators(pattern, pattern2, show_verbose);
752  break;
753  case 'p':
754  success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
755  break;
756  default:
758  break;
759  }
760 
761  if (pattern2)
762  free(pattern2);
763  }
764  break;
765  case 'a':
766  success = describeAggregates(pattern, show_verbose, show_system);
767  break;
768  case 'b':
769  success = describeTablespaces(pattern, show_verbose);
770  break;
771  case 'c':
772  success = listConversions(pattern, show_verbose, show_system);
773  break;
774  case 'C':
775  success = listCasts(pattern, show_verbose);
776  break;
777  case 'd':
778  if (strncmp(cmd, "ddp", 3) == 0)
779  success = listDefaultACLs(pattern);
780  else
781  success = objectDescription(pattern, show_system);
782  break;
783  case 'D':
784  success = listDomains(pattern, show_verbose, show_system);
785  break;
786  case 'f': /* function subsystem */
787  switch (cmd[2])
788  {
789  case '\0':
790  case '+':
791  case 'S':
792  case 'a':
793  case 'n':
794  case 'p':
795  case 't':
796  case 'w':
797  success = exec_command_dfo(scan_state, cmd, pattern,
798  show_verbose, show_system);
799  break;
800  default:
802  break;
803  }
804  break;
805  case 'g':
806  /* no longer distinct from \du */
807  success = describeRoles(pattern, show_verbose, show_system);
808  break;
809  case 'l':
810  success = do_lo_list();
811  break;
812  case 'L':
813  success = listLanguages(pattern, show_verbose, show_system);
814  break;
815  case 'n':
816  success = listSchemas(pattern, show_verbose, show_system);
817  break;
818  case 'o':
819  success = exec_command_dfo(scan_state, cmd, pattern,
820  show_verbose, show_system);
821  break;
822  case 'O':
823  success = listCollations(pattern, show_verbose, show_system);
824  break;
825  case 'p':
826  success = permissionsList(pattern);
827  break;
828  case 'P':
829  {
830  switch (cmd[2])
831  {
832  case '\0':
833  case '+':
834  case 't':
835  case 'i':
836  case 'n':
837  success = listPartitionedTables(&cmd[2], pattern, show_verbose);
838  break;
839  default:
841  break;
842  }
843  }
844  break;
845  case 'T':
846  success = describeTypes(pattern, show_verbose, show_system);
847  break;
848  case 't':
849  case 'v':
850  case 'm':
851  case 'i':
852  case 's':
853  case 'E':
854  success = listTables(&cmd[1], pattern, show_verbose, show_system);
855  break;
856  case 'r':
857  if (cmd[2] == 'd' && cmd[3] == 's')
858  {
859  char *pattern2 = NULL;
860 
861  if (pattern)
862  pattern2 = psql_scan_slash_option(scan_state,
863  OT_NORMAL, NULL, true);
864  success = listDbRoleSettings(pattern, pattern2);
865 
866  if (pattern2)
867  free(pattern2);
868  }
869  else
871  break;
872  case 'R':
873  switch (cmd[2])
874  {
875  case 'p':
876  if (show_verbose)
877  success = describePublications(pattern);
878  else
879  success = listPublications(pattern);
880  break;
881  case 's':
882  success = describeSubscriptions(pattern, show_verbose);
883  break;
884  default:
886  }
887  break;
888  case 'u':
889  success = describeRoles(pattern, show_verbose, show_system);
890  break;
891  case 'F': /* text search subsystem */
892  switch (cmd[2])
893  {
894  case '\0':
895  case '+':
896  success = listTSConfigs(pattern, show_verbose);
897  break;
898  case 'p':
899  success = listTSParsers(pattern, show_verbose);
900  break;
901  case 'd':
902  success = listTSDictionaries(pattern, show_verbose);
903  break;
904  case 't':
905  success = listTSTemplates(pattern, show_verbose);
906  break;
907  default:
909  break;
910  }
911  break;
912  case 'e': /* SQL/MED subsystem */
913  switch (cmd[2])
914  {
915  case 's':
916  success = listForeignServers(pattern, show_verbose);
917  break;
918  case 'u':
919  success = listUserMappings(pattern, show_verbose);
920  break;
921  case 'w':
922  success = listForeignDataWrappers(pattern, show_verbose);
923  break;
924  case 't':
925  success = listForeignTables(pattern, show_verbose);
926  break;
927  default:
929  break;
930  }
931  break;
932  case 'x': /* Extensions */
933  if (show_verbose)
934  success = listExtensionContents(pattern);
935  else
936  success = listExtensions(pattern);
937  break;
938  case 'X': /* Extended Statistics */
939  success = listExtendedStats(pattern);
940  break;
941  case 'y': /* Event Triggers */
942  success = listEventTriggers(pattern, show_verbose);
943  break;
944  default:
946  }
947 
948  if (pattern)
949  free(pattern);
950  }
951  else
952  ignore_slash_options(scan_state);
953 
954  if (!success)
956 
957  return status;
958 }
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:962
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:5923
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:5552
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3761
bool listOpFamilyFunctions(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6878
bool listPublications(const char *pattern)
Definition: describe.c:6232
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5163
bool listExtensionContents(const char *pattern)
Definition: describe.c:6119
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:64
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:5758
bool listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
Definition: describe.c:4233
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:6505
bool listExtendedStats(const char *pattern)
Definition: describe.c:4732
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:716
bool listOperatorFamilies(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6709
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:5841
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1532
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4504
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:5410
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3933
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4942
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5041
bool listExtensions(const char *pattern)
Definition: describe.c:6062
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4017
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:5481
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:220
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:4824
bool listOpFamilyOperators(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6791
bool permissionsList(const char *pattern)
Definition: describe.c:1095
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6615
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:5984
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:4666
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1255
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4590
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:150
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4429
bool describePublications(const char *pattern)
Definition: describe.c:6342
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1340
return true
Definition: isn.c:126
bool do_lo_list(void)
Definition: large_obj.c:274

References describeAccessMethods(), describeAggregates(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_lo_list(), exec_command_dfo(), free, ignore_slash_options(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSDictionaries(), listTSParsers(), listTSTemplates(), listUserMappings(), objectDescription(), OT_NORMAL, permissionsList(), PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, PSQL_CMD_UNKNOWN, psql_scan_slash_option(), status(), success, and true.

Referenced by exec_command().

◆ exec_command_dfo()

static bool exec_command_dfo ( PsqlScanState  scan_state,
const char *  cmd,
const char *  pattern,
bool  show_verbose,
bool  show_system 
)
static

Definition at line 962 of file command.c.

965 {
966  bool success;
967  char *arg_patterns[FUNC_MAX_ARGS];
968  int num_arg_patterns = 0;
969 
970  /* Collect argument-type patterns too */
971  if (pattern) /* otherwise it was just \df or \do */
972  {
973  char *ap;
974 
975  while ((ap = psql_scan_slash_option(scan_state,
976  OT_NORMAL, NULL, true)) != NULL)
977  {
978  arg_patterns[num_arg_patterns++] = ap;
979  if (num_arg_patterns >= FUNC_MAX_ARGS)
980  break; /* protect limited-size array */
981  }
982  }
983 
984  if (cmd[1] == 'f')
985  success = describeFunctions(&cmd[2], pattern,
986  arg_patterns, num_arg_patterns,
987  show_verbose, show_system);
988  else
989  success = describeOperators(pattern,
990  arg_patterns, num_arg_patterns,
991  show_verbose, show_system);
992 
993  while (--num_arg_patterns >= 0)
994  free(arg_patterns[num_arg_patterns]);
995 
996  return success;
997 }
bool describeFunctions(const char *functypes, const char *func_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:316
bool describeOperators(const char *oper_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:890
#define FUNC_MAX_ARGS

References describeFunctions(), describeOperators(), free, FUNC_MAX_ARGS, OT_NORMAL, psql_scan_slash_option(), and success.

Referenced by exec_command_d().

◆ exec_command_echo()

static backslashResult exec_command_echo ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 1216 of file command.c.

1217 {
1218  if (active_branch)
1219  {
1220  char *value;
1221  char quoted;
1222  bool no_newline = false;
1223  bool first = true;
1224  FILE *fout;
1225 
1226  if (strcmp(cmd, "qecho") == 0)
1227  fout = pset.queryFout;
1228  else if (strcmp(cmd, "warn") == 0)
1229  fout = stderr;
1230  else
1231  fout = stdout;
1232 
1233  while ((value = psql_scan_slash_option(scan_state,
1234  OT_NORMAL, &quoted, false)))
1235  {
1236  if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1237  no_newline = true;
1238  else
1239  {
1240  if (first)
1241  first = false;
1242  else
1243  fputc(' ', fout);
1244  fputs(value, fout);
1245  }
1246  free(value);
1247  }
1248  if (!no_newline)
1249  fputs("\n", fout);
1250  }
1251  else
1252  ignore_slash_options(scan_state);
1253 
1254  return PSQL_CMD_SKIP_LINE;
1255 }
FILE * queryFout
Definition: settings.h:84

References free, ignore_slash_options(), OT_NORMAL, pset, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::queryFout, generate_unaccent_rules::stdout, and value.

Referenced by exec_command().

◆ exec_command_edit()

static backslashResult exec_command_edit ( PsqlScanState  scan_state,
bool  active_branch,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 1004 of file command.c.

1006 {
1008 
1009  if (active_branch)
1010  {
1011  if (!query_buf)
1012  {
1013  pg_log_error("no query buffer");
1015  }
1016  else
1017  {
1018  char *fname;
1019  char *ln = NULL;
1020  int lineno = -1;
1021 
1022  fname = psql_scan_slash_option(scan_state,
1023  OT_NORMAL, NULL, true);
1024  if (fname)
1025  {
1026  /* try to get separate lineno arg */
1027  ln = psql_scan_slash_option(scan_state,
1028  OT_NORMAL, NULL, true);
1029  if (ln == NULL)
1030  {
1031  /* only one arg; maybe it is lineno not fname */
1032  if (fname[0] &&
1033  strspn(fname, "0123456789") == strlen(fname))
1034  {
1035  /* all digits, so assume it is lineno */
1036  ln = fname;
1037  fname = NULL;
1038  }
1039  }
1040  }
1041  if (ln)
1042  {
1043  lineno = atoi(ln);
1044  if (lineno < 1)
1045  {
1046  pg_log_error("invalid line number: %s", ln);
1048  }
1049  }
1050  if (status != PSQL_CMD_ERROR)
1051  {
1052  bool discard_on_quit;
1053 
1054  expand_tilde(&fname);
1055  if (fname)
1056  {
1057  canonicalize_path(fname);
1058  /* Always clear buffer if the file isn't modified */
1059  discard_on_quit = true;
1060  }
1061  else
1062  {
1063  /*
1064  * If query_buf is empty, recall previous query for
1065  * editing. But in that case, the query buffer should be
1066  * emptied if editing doesn't modify the file.
1067  */
1068  discard_on_quit = copy_previous_query(query_buf,
1069  previous_buf);
1070  }
1071 
1072  if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1074  else
1076  }
1077  if (fname)
1078  free(fname);
1079  if (ln)
1080  free(ln);
1081  }
1082  }
1083  else
1084  ignore_slash_options(scan_state);
1085 
1086  return status;
1087 }
void expand_tilde(char **filename)
Definition: common.c:2227
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:3850
@ PSQL_CMD_NEWEDIT
Definition: command.h:21
void canonicalize_path(char *path)
Definition: path.c:254

References canonicalize_path(), copy_previous_query(), do_edit(), expand_tilde(), free, ignore_slash_options(), OT_NORMAL, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_NEWEDIT, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and status().

Referenced by exec_command().

◆ exec_command_ef_ev()

static backslashResult exec_command_ef_ev ( PsqlScanState  scan_state,
bool  active_branch,
PQExpBuffer  query_buf,
bool  is_func 
)
static

Definition at line 1094 of file command.c.

1096 {
1098 
1099  if (active_branch)
1100  {
1101  char *obj_desc = psql_scan_slash_option(scan_state,
1102  OT_WHOLE_LINE,
1103  NULL, true);
1104  int lineno = -1;
1105 
1106  if (pset.sversion < (is_func ? 80400 : 70400))
1107  {
1108  char sverbuf[32];
1109 
1111  sverbuf, sizeof(sverbuf));
1112  if (is_func)
1113  pg_log_error("The server (version %s) does not support editing function source.",
1114  sverbuf);
1115  else
1116  pg_log_error("The server (version %s) does not support editing view definitions.",
1117  sverbuf);
1119  }
1120  else if (!query_buf)
1121  {
1122  pg_log_error("no query buffer");
1124  }
1125  else
1126  {
1127  Oid obj_oid = InvalidOid;
1129 
1130  lineno = strip_lineno_from_objdesc(obj_desc);
1131  if (lineno == 0)
1132  {
1133  /* error already reported */
1135  }
1136  else if (!obj_desc)
1137  {
1138  /* set up an empty command to fill in */
1139  resetPQExpBuffer(query_buf);
1140  if (is_func)
1141  appendPQExpBufferStr(query_buf,
1142  "CREATE FUNCTION ( )\n"
1143  " RETURNS \n"
1144  " LANGUAGE \n"
1145  " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1146  "AS $function$\n"
1147  "\n$function$\n");
1148  else
1149  appendPQExpBufferStr(query_buf,
1150  "CREATE VIEW AS\n"
1151  " SELECT \n"
1152  " -- something...\n");
1153  }
1154  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1155  {
1156  /* error already reported */
1158  }
1159  else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1160  {
1161  /* error already reported */
1163  }
1164  else if (is_func && lineno > 0)
1165  {
1166  /*
1167  * lineno "1" should correspond to the first line of the
1168  * function body. We expect that pg_get_functiondef() will
1169  * emit that on a line beginning with "AS ", and that there
1170  * can be no such line before the real start of the function
1171  * body. Increment lineno by the number of lines before that
1172  * line, so that it becomes relative to the first line of the
1173  * function definition.
1174  */
1175  const char *lines = query_buf->data;
1176 
1177  while (*lines != '\0')
1178  {
1179  if (strncmp(lines, "AS ", 3) == 0)
1180  break;
1181  lineno++;
1182  /* find start of next line */
1183  lines = strchr(lines, '\n');
1184  if (!lines)
1185  break;
1186  lines++;
1187  }
1188  }
1189  }
1190 
1191  if (status != PSQL_CMD_ERROR)
1192  {
1193  bool edited = false;
1194 
1195  if (!do_edit(NULL, query_buf, lineno, true, &edited))
1197  else if (!edited)
1198  puts(_("No changes"));
1199  else
1201  }
1202 
1203  if (obj_desc)
1204  free(obj_desc);
1205  }
1206  else
1207  ignore_slash_whole_line(scan_state);
1208 
1209  return status;
1210 }
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:5251
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:5191
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:5424
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31

References _, appendPQExpBufferStr(), PQExpBufferData::data, do_edit(), EditableFunction, EditableView, formatPGVersionNumber(), free, get_create_object_cmd(), ignore_slash_whole_line(), InvalidOid, lookup_object_oid(), OT_WHOLE_LINE, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_NEWEDIT, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), resetPQExpBuffer(), status(), strip_lineno_from_objdesc(), and _psqlSettings::sversion.

Referenced by exec_command().

◆ exec_command_elif()

static backslashResult exec_command_elif ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf 
)
static

Definition at line 1685 of file command.c.

1687 {
1688  bool success = true;
1689 
1690  switch (conditional_stack_peek(cstack))
1691  {
1692  case IFSTATE_TRUE:
1693 
1694  /*
1695  * Just finished active branch of this \if block. Update saved
1696  * state so we will keep whatever data was put in query_buf by the
1697  * active branch.
1698  */
1699  save_query_text_state(scan_state, cstack, query_buf);
1700 
1701  /*
1702  * Discard \elif expression and ignore the rest until \endif.
1703  * Switch state before reading expression to ensure proper lexer
1704  * behavior.
1705  */
1707  ignore_boolean_expression(scan_state);
1708  break;
1709  case IFSTATE_FALSE:
1710 
1711  /*
1712  * Discard any query text added by the just-skipped branch.
1713  */
1714  discard_query_text(scan_state, cstack, query_buf);
1715 
1716  /*
1717  * Have not yet found a true expression in this \if block, so this
1718  * might be the first. We have to change state before examining
1719  * the expression, or the lexer won't do the right thing.
1720  */
1722  if (!is_true_boolean_expression(scan_state, "\\elif expression"))
1724  break;
1725  case IFSTATE_IGNORED:
1726 
1727  /*
1728  * Discard any query text added by the just-skipped branch.
1729  */
1730  discard_query_text(scan_state, cstack, query_buf);
1731 
1732  /*
1733  * Skip expression and move on. Either the \if block already had
1734  * an active section, or whole block is being skipped.
1735  */
1736  ignore_boolean_expression(scan_state);
1737  break;
1738  case IFSTATE_ELSE_TRUE:
1739  case IFSTATE_ELSE_FALSE:
1740  pg_log_error("\\elif: cannot occur after \\else");
1741  success = false;
1742  break;
1743  case IFSTATE_NONE:
1744  /* no \if to elif from */
1745  pg_log_error("\\elif: no matching \\if");
1746  success = false;
1747  break;
1748  }
1749 
1751 }
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3029
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:2930
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:2913
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3009
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:94
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:106
@ IFSTATE_FALSE
Definition: conditional.h:34
@ IFSTATE_ELSE_TRUE
Definition: conditional.h:40
@ IFSTATE_IGNORED
Definition: conditional.h:37
@ IFSTATE_TRUE
Definition: conditional.h:32
@ IFSTATE_NONE
Definition: conditional.h:31
@ IFSTATE_ELSE_FALSE
Definition: conditional.h:42

References conditional_stack_peek(), conditional_stack_poke(), discard_query_text(), IFSTATE_ELSE_FALSE, IFSTATE_ELSE_TRUE, IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_NONE, IFSTATE_TRUE, ignore_boolean_expression(), is_true_boolean_expression(), pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, save_query_text_state(), and success.

Referenced by exec_command().

◆ exec_command_else()

static backslashResult exec_command_else ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf 
)
static

Definition at line 1761 of file command.c.

1763 {
1764  bool success = true;
1765 
1766  switch (conditional_stack_peek(cstack))
1767  {
1768  case IFSTATE_TRUE:
1769 
1770  /*
1771  * Just finished active branch of this \if block. Update saved
1772  * state so we will keep whatever data was put in query_buf by the
1773  * active branch.
1774  */
1775  save_query_text_state(scan_state, cstack, query_buf);
1776 
1777  /* Now skip the \else branch */
1779  break;
1780  case IFSTATE_FALSE:
1781 
1782  /*
1783  * Discard any query text added by the just-skipped branch.
1784  */
1785  discard_query_text(scan_state, cstack, query_buf);
1786 
1787  /*
1788  * We've not found any true \if or \elif expression, so execute
1789  * the \else branch.
1790  */
1792  break;
1793  case IFSTATE_IGNORED:
1794 
1795  /*
1796  * Discard any query text added by the just-skipped branch.
1797  */
1798  discard_query_text(scan_state, cstack, query_buf);
1799 
1800  /*
1801  * Either we previously processed the active branch of this \if,
1802  * or the whole \if block is being skipped. Either way, skip the
1803  * \else branch.
1804  */
1806  break;
1807  case IFSTATE_ELSE_TRUE:
1808  case IFSTATE_ELSE_FALSE:
1809  pg_log_error("\\else: cannot occur after \\else");
1810  success = false;
1811  break;
1812  case IFSTATE_NONE:
1813  /* no \if to else from */
1814  pg_log_error("\\else: no matching \\if");
1815  success = false;
1816  break;
1817  }
1818 
1820 }

References conditional_stack_peek(), conditional_stack_poke(), discard_query_text(), IFSTATE_ELSE_FALSE, IFSTATE_ELSE_TRUE, IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_NONE, IFSTATE_TRUE, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, save_query_text_state(), and success.

Referenced by exec_command().

◆ exec_command_encoding()

static backslashResult exec_command_encoding ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1261 of file command.c.

1262 {
1263  if (active_branch)
1264  {
1265  char *encoding = psql_scan_slash_option(scan_state,
1266  OT_NORMAL, NULL, false);
1267 
1268  if (!encoding)
1269  {
1270  /* show encoding */
1272  }
1273  else
1274  {
1275  /* set encoding */
1276  if (PQsetClientEncoding(pset.db, encoding) == -1)
1277  pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1278  else
1279  {
1280  /* save encoding info into psql internal data */
1283  SetVariable(pset.vars, "ENCODING",
1285  }
1286  free(encoding);
1287  }
1288  }
1289  else
1290  ignore_slash_options(scan_state);
1291 
1292  return PSQL_CMD_SKIP_LINE;
1293 }
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6847
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6855
int32 encoding
Definition: pg_database.h:41
VariableSpace vars
Definition: settings.h:118
int encoding
Definition: settings.h:83
int encoding
Definition: print.h:122
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211

References _psqlSettings::db, _psqlSettings::encoding, encoding, printTableOpt::encoding, free, ignore_slash_options(), OT_NORMAL, pg_encoding_to_char(), pg_log_error, _psqlSettings::popt, PQclientEncoding(), PQsetClientEncoding(), pset, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), SetVariable(), printQueryOpt::topt, and _psqlSettings::vars.

Referenced by exec_command().

◆ exec_command_endif()

static backslashResult exec_command_endif ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf 
)
static

Definition at line 1826 of file command.c.

1828 {
1829  bool success = true;
1830 
1831  switch (conditional_stack_peek(cstack))
1832  {
1833  case IFSTATE_TRUE:
1834  case IFSTATE_ELSE_TRUE:
1835  /* Close the \if block, keeping the query text */
1836  success = conditional_stack_pop(cstack);
1837  Assert(success);
1838  break;
1839  case IFSTATE_FALSE:
1840  case IFSTATE_IGNORED:
1841  case IFSTATE_ELSE_FALSE:
1842 
1843  /*
1844  * Discard any query text added by the just-skipped branch.
1845  */
1846  discard_query_text(scan_state, cstack, query_buf);
1847 
1848  /* Close the \if block */
1849  success = conditional_stack_pop(cstack);
1850  Assert(success);
1851  break;
1852  case IFSTATE_NONE:
1853  /* no \if to end */
1854  pg_log_error("\\endif: no matching \\if");
1855  success = false;
1856  break;
1857  }
1858 
1860 }
bool conditional_stack_pop(ConditionalStack cstack)
Definition: conditional.c:57

References Assert(), conditional_stack_peek(), conditional_stack_pop(), discard_query_text(), IFSTATE_ELSE_FALSE, IFSTATE_ELSE_TRUE, IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_NONE, IFSTATE_TRUE, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, and success.

Referenced by exec_command().

◆ exec_command_errverbose()

static backslashResult exec_command_errverbose ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1299 of file command.c.

1300 {
1301  if (active_branch)
1302  {
1303  if (pset.last_error_result)
1304  {
1305  char *msg;
1306 
1310  if (msg)
1311  {
1312  pg_log_error("%s", msg);
1313  PQfreemem(msg);
1314  }
1315  else
1316  puts(_("out of memory"));
1317  }
1318  else
1319  puts(_("There is no previous error."));
1320  }
1321 
1322  return PSQL_CMD_SKIP_LINE;
1323 }
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3202
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:135
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:127
PGresult * last_error_result
Definition: settings.h:89

References _, _psqlSettings::last_error_result, pg_log_error, PQERRORS_VERBOSE, PQfreemem(), PQresultVerboseErrorMessage(), PQSHOW_CONTEXT_ALWAYS, pset, and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_f()

static backslashResult exec_command_f ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1329 of file command.c.

1330 {
1331  bool success = true;
1332 
1333  if (active_branch)
1334  {
1335  char *fname = psql_scan_slash_option(scan_state,
1336  OT_NORMAL, NULL, false);
1337 
1338  success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1339  free(fname);
1340  }
1341  else
1342  ignore_slash_options(scan_state);
1343 
1345 }

References do_pset(), free, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, and success.

Referenced by exec_command().

◆ exec_command_g()

static backslashResult exec_command_g ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 1357 of file command.c.

1358 {
1360  char *fname;
1361 
1362  /*
1363  * Because the option processing for this is fairly complicated, we do it
1364  * and then decide whether the branch is active.
1365  */
1366  fname = psql_scan_slash_option(scan_state,
1367  OT_FILEPIPE, NULL, false);
1368 
1369  if (fname && fname[0] == '(')
1370  {
1371  /* Consume pset options through trailing ')' ... */
1372  status = process_command_g_options(fname + 1, scan_state,
1373  active_branch, cmd);
1374  free(fname);
1375  /* ... and again attempt to scan the filename. */
1376  fname = psql_scan_slash_option(scan_state,
1377  OT_FILEPIPE, NULL, false);
1378  }
1379 
1380  if (status == PSQL_CMD_SKIP_LINE && active_branch)
1381  {
1382  if (!fname)
1383  pset.gfname = NULL;
1384  else
1385  {
1386  expand_tilde(&fname);
1387  pset.gfname = pg_strdup(fname);
1388  }
1389  if (strcmp(cmd, "gx") == 0)
1390  {
1391  /* save settings if not done already, then force expanded=on */
1392  if (pset.gsavepopt == NULL)
1394  pset.popt.topt.expanded = 1;
1395  }
1397  }
1398 
1399  free(fname);
1400 
1401  return status;
1402 }
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:4711
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1410
@ OT_FILEPIPE
Definition: psqlscanslash.h:20
printQueryOpt * gsavepopt
Definition: settings.h:94
char * gfname
Definition: settings.h:93

References expand_tilde(), printTableOpt::expanded, free, _psqlSettings::gfname, _psqlSettings::gsavepopt, OT_FILEPIPE, pg_strdup(), _psqlSettings::popt, process_command_g_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), savePsetInfo(), status(), and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_gdesc()

static backslashResult exec_command_gdesc ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1485 of file command.c.

1486 {
1488 
1489  if (active_branch)
1490  {
1491  pset.gdesc_flag = true;
1493  }
1494 
1495  return status;
1496 }
bool gdesc_flag
Definition: settings.h:97

References _psqlSettings::gdesc_flag, pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, and status().

Referenced by exec_command().

◆ exec_command_gexec()

static backslashResult exec_command_gexec ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1502 of file command.c.

1503 {
1505 
1506  if (active_branch)
1507  {
1508  pset.gexec_flag = true;
1510  }
1511 
1512  return status;
1513 }
bool gexec_flag
Definition: settings.h:98

References _psqlSettings::gexec_flag, pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, and status().

Referenced by exec_command().

◆ exec_command_gset()

static backslashResult exec_command_gset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1519 of file command.c.

1520 {
1522 
1523  if (active_branch)
1524  {
1525  char *prefix = psql_scan_slash_option(scan_state,
1526  OT_NORMAL, NULL, false);
1527 
1528  if (prefix)
1529  pset.gset_prefix = prefix;
1530  else
1531  {
1532  /* we must set a non-NULL prefix to trigger storing */
1533  pset.gset_prefix = pg_strdup("");
1534  }
1535  /* gset_prefix is freed later */
1537  }
1538  else
1539  ignore_slash_options(scan_state);
1540 
1541  return status;
1542 }
char * gset_prefix
Definition: settings.h:96

References _psqlSettings::gset_prefix, ignore_slash_options(), OT_NORMAL, pg_strdup(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and status().

Referenced by exec_command().

◆ exec_command_help()

static backslashResult exec_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1548 of file command.c.

1549 {
1550  if (active_branch)
1551  {
1552  char *opt = psql_scan_slash_option(scan_state,
1553  OT_WHOLE_LINE, NULL, false);
1554  size_t len;
1555 
1556  /* strip any trailing spaces and semicolons */
1557  if (opt)
1558  {
1559  len = strlen(opt);
1560  while (len > 0 &&
1561  (isspace((unsigned char) opt[len - 1])
1562  || opt[len - 1] == ';'))
1563  opt[--len] = '\0';
1564  }
1565 
1566  helpSQL(opt, pset.popt.topt.pager);
1567  free(opt);
1568  }
1569  else
1570  ignore_slash_whole_line(scan_state);
1571 
1572  return PSQL_CMD_SKIP_LINE;
1573 }
void helpSQL(const char *topic, unsigned short int pager)
Definition: help.c:529

References free, helpSQL(), ignore_slash_whole_line(), len, OT_WHOLE_LINE, printTableOpt::pager, _psqlSettings::popt, pset, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1579 of file command.c.

1580 {
1581  bool success = true;
1582 
1583  if (active_branch)
1584  {
1585  if (pset.popt.topt.format != PRINT_HTML)
1586  success = do_pset("format", "html", &pset.popt, pset.quiet);
1587  else
1588  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1589  }
1590 
1592 }

References do_pset(), printTableOpt::format, _psqlSettings::popt, PRINT_HTML, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, _psqlSettings::quiet, success, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_if()

static backslashResult exec_command_if ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf 
)
static

Definition at line 1639 of file command.c.

1641 {
1642  if (conditional_active(cstack))
1643  {
1644  /*
1645  * First, push a new active stack entry; this ensures that the lexer
1646  * will perform variable substitution and backtick evaluation while
1647  * scanning the expression. (That should happen anyway, since we know
1648  * we're in an active outer branch, but let's be sure.)
1649  */
1651 
1652  /* Remember current query state in case we need to restore later */
1653  save_query_text_state(scan_state, cstack, query_buf);
1654 
1655  /*
1656  * Evaluate the expression; if it's false, change to inactive state.
1657  */
1658  if (!is_true_boolean_expression(scan_state, "\\if expression"))
1660  }
1661  else
1662  {
1663  /*
1664  * We're within an inactive outer branch, so this entire \if block
1665  * will be ignored. We don't want to evaluate the expression, so push
1666  * the "ignored" stack state before scanning it.
1667  */
1669 
1670  /* Remember current query state in case we need to restore later */
1671  save_query_text_state(scan_state, cstack, query_buf);
1672 
1673  ignore_boolean_expression(scan_state);
1674  }
1675 
1676  return PSQL_CMD_SKIP_LINE;
1677 }
void conditional_stack_push(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:41

References conditional_active(), conditional_stack_poke(), conditional_stack_push(), IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_TRUE, ignore_boolean_expression(), is_true_boolean_expression(), PSQL_CMD_SKIP_LINE, and save_query_text_state().

Referenced by exec_command().

◆ exec_command_include()

static backslashResult exec_command_include ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 1598 of file command.c.

1599 {
1600  bool success = true;
1601 
1602  if (active_branch)
1603  {
1604  char *fname = psql_scan_slash_option(scan_state,
1605  OT_NORMAL, NULL, true);
1606 
1607  if (!fname)
1608  {
1609  pg_log_error("\\%s: missing required argument", cmd);
1610  success = false;
1611  }
1612  else
1613  {
1614  bool include_relative;
1615 
1616  include_relative = (strcmp(cmd, "ir") == 0
1617  || strcmp(cmd, "include_relative") == 0);
1618  expand_tilde(&fname);
1619  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1620  free(fname);
1621  }
1622  }
1623  else
1624  ignore_slash_options(scan_state);
1625 
1627 }
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4045
#define EXIT_SUCCESS
Definition: settings.h:158

References EXIT_SUCCESS, expand_tilde(), free, ignore_slash_options(), OT_NORMAL, pg_log_error, process_file(), PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and success.

Referenced by exec_command().

◆ exec_command_list()

static backslashResult exec_command_list ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 1866 of file command.c.

1867 {
1868  bool success = true;
1869 
1870  if (active_branch)
1871  {
1872  char *pattern;
1873  bool show_verbose;
1874 
1875  pattern = psql_scan_slash_option(scan_state,
1876  OT_NORMAL, NULL, true);
1877 
1878  show_verbose = strchr(cmd, '+') ? true : false;
1879 
1880  success = listAllDbs(pattern, show_verbose);
1881 
1882  if (pattern)
1883  free(pattern);
1884  }
1885  else
1886  ignore_slash_options(scan_state);
1887 
1889 }
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:1025

References free, ignore_slash_options(), listAllDbs(), OT_NORMAL, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), success, and true.

Referenced by exec_command().

◆ exec_command_lo()

static backslashResult exec_command_lo ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 1895 of file command.c.

1896 {
1898  bool success = true;
1899 
1900  if (active_branch)
1901  {
1902  char *opt1,
1903  *opt2;
1904 
1905  opt1 = psql_scan_slash_option(scan_state,
1906  OT_NORMAL, NULL, true);
1907  opt2 = psql_scan_slash_option(scan_state,
1908  OT_NORMAL, NULL, true);
1909 
1910  if (strcmp(cmd + 3, "export") == 0)
1911  {
1912  if (!opt2)
1913  {
1914  pg_log_error("\\%s: missing required argument", cmd);
1915  success = false;
1916  }
1917  else
1918  {
1919  expand_tilde(&opt2);
1920  success = do_lo_export(opt1, opt2);
1921  }
1922  }
1923 
1924  else if (strcmp(cmd + 3, "import") == 0)
1925  {
1926  if (!opt1)
1927  {
1928  pg_log_error("\\%s: missing required argument", cmd);
1929  success = false;
1930  }
1931  else
1932  {
1933  expand_tilde(&opt1);
1934  success = do_lo_import(opt1, opt2);
1935  }
1936  }
1937 
1938  else if (strcmp(cmd + 3, "list") == 0)
1939  success = do_lo_list();
1940 
1941  else if (strcmp(cmd + 3, "unlink") == 0)
1942  {
1943  if (!opt1)
1944  {
1945  pg_log_error("\\%s: missing required argument", cmd);
1946  success = false;
1947  }
1948  else
1949  success = do_lo_unlink(opt1);
1950  }
1951 
1952  else
1954 
1955  free(opt1);
1956  free(opt2);
1957  }
1958  else
1959  ignore_slash_options(scan_state);
1960 
1961  if (!success)
1963 
1964  return status;
1965 }
bool do_lo_export(const char *loid_arg, const char *filename_arg)
Definition: large_obj.c:142
bool do_lo_import(const char *filename_arg, const char *comment_arg)
Definition: large_obj.c:176
bool do_lo_unlink(const char *loid_arg)
Definition: large_obj.c:239

References do_lo_export(), do_lo_import(), do_lo_list(), do_lo_unlink(), expand_tilde(), free, ignore_slash_options(), OT_NORMAL, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, PSQL_CMD_UNKNOWN, psql_scan_slash_option(), status(), and success.

Referenced by exec_command().

◆ exec_command_out()

static backslashResult exec_command_out ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1971 of file command.c.

1972 {
1973  bool success = true;
1974 
1975  if (active_branch)
1976  {
1977  char *fname = psql_scan_slash_option(scan_state,
1978  OT_FILEPIPE, NULL, true);
1979 
1980  expand_tilde(&fname);
1981  success = setQFout(fname);
1982  free(fname);
1983  }
1984  else
1985  ignore_slash_filepipe(scan_state);
1986 
1988 }
bool setQFout(const char *fname)
Definition: common.c:85
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:2963

References expand_tilde(), free, ignore_slash_filepipe(), OT_FILEPIPE, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), setQFout(), and success.

Referenced by exec_command().

◆ exec_command_password()

static backslashResult exec_command_password ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2020 of file command.c.

2021 {
2022  bool success = true;
2023 
2024  if (active_branch)
2025  {
2026  char *user = psql_scan_slash_option(scan_state,
2027  OT_SQLID, NULL, true);
2028  char *pw1 = NULL;
2029  char *pw2 = NULL;
2031  PromptInterruptContext prompt_ctx;
2032 
2033  if (user == NULL)
2034  {
2035  /* By default, the command applies to CURRENT_USER */
2036  PGresult *res;
2037 
2038  res = PSQLexec("SELECT CURRENT_USER");
2039  if (!res)
2040  return PSQL_CMD_ERROR;
2041 
2042  user = pg_strdup(PQgetvalue(res, 0, 0));
2043  PQclear(res);
2044  }
2045 
2046  /* Set up to let SIGINT cancel simple_prompt_extended() */
2047  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2048  prompt_ctx.enabled = &sigint_interrupt_enabled;
2049  prompt_ctx.canceled = false;
2050 
2051  initPQExpBuffer(&buf);
2052  printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2053 
2054  pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2055  if (!prompt_ctx.canceled)
2056  pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2057 
2058  if (prompt_ctx.canceled)
2059  {
2060  /* fail silently */
2061  success = false;
2062  }
2063  else if (strcmp(pw1, pw2) != 0)
2064  {
2065  pg_log_error("Passwords didn't match.");
2066  success = false;
2067  }
2068  else
2069  {
2070  char *encrypted_password;
2071 
2072  encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
2073 
2074  if (!encrypted_password)
2075  {
2077  success = false;
2078  }
2079  else
2080  {
2081  PGresult *res;
2082 
2083  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
2084  fmtId(user));
2085  appendStringLiteralConn(&buf, encrypted_password, pset.db);
2086  res = PSQLexec(buf.data);
2087  if (!res)
2088  success = false;
2089  else
2090  PQclear(res);
2091  PQfreemem(encrypted_password);
2092  }
2093  }
2094 
2095  free(user);
2096  if (pw1)
2097  free(pw1);
2098  if (pw2)
2099  free(pw2);
2100  termPQExpBuffer(&buf);
2101  }
2102  else
2103  ignore_slash_options(scan_state);
2104 
2106 }
PGresult * PSQLexec(const char *query)
Definition: common.c:540
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1217
void PQclear(PGresult *res)
Definition: fe-exec.c:694
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3642
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
@ OT_SQLID
Definition: psqlscanslash.h:18
char * simple_prompt_extended(const char *prompt, bool echo, PromptInterruptContext *prompt_ctx)
Definition: sprompt.c:53
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
volatile bool * enabled
Definition: string.h:19

References _, appendStringLiteralConn(), buf, PromptInterruptContext::canceled, _psqlSettings::db, PromptInterruptContext::enabled, fmtId(), free, ignore_slash_options(), initPQExpBuffer(), PromptInterruptContext::jmpbuf, OT_SQLID, pg_log_error, pg_log_info, pg_strdup(), PQclear(), PQencryptPasswordConn(), PQerrorMessage(), PQfreemem(), PQgetvalue(), printfPQExpBuffer(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQLexec(), res, sigint_interrupt_enabled, sigint_interrupt_jmp, simple_prompt_extended(), success, termPQExpBuffer(), and user.

Referenced by exec_command().

◆ exec_command_print()

static backslashResult exec_command_print ( PsqlScanState  scan_state,
bool  active_branch,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 1994 of file command.c.

1996 {
1997  if (active_branch)
1998  {
1999  /*
2000  * We want to print the same thing \g would execute, but not to change
2001  * the query buffer state; so we can't use copy_previous_query().
2002  * Also, beware of possibility that buffer pointers are NULL.
2003  */
2004  if (query_buf && query_buf->len > 0)
2005  puts(query_buf->data);
2006  else if (previous_buf && previous_buf->len > 0)
2007  puts(previous_buf->data);
2008  else if (!pset.quiet)
2009  puts(_("Query buffer is empty."));
2010  fflush(stdout);
2011  }
2012 
2013  return PSQL_CMD_SKIP_LINE;
2014 }

References _, PQExpBufferData::data, fflush(), PQExpBufferData::len, pset, PSQL_CMD_SKIP_LINE, _psqlSettings::quiet, and generate_unaccent_rules::stdout.

Referenced by exec_command().

◆ exec_command_prompt()

static backslashResult exec_command_prompt ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 2112 of file command.c.

2114 {
2115  bool success = true;
2116 
2117  if (active_branch)
2118  {
2119  char *opt,
2120  *prompt_text = NULL;
2121  char *arg1,
2122  *arg2;
2123 
2124  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2125  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2126 
2127  if (!arg1)
2128  {
2129  pg_log_error("\\%s: missing required argument", cmd);
2130  success = false;
2131  }
2132  else
2133  {
2134  char *result;
2135  PromptInterruptContext prompt_ctx;
2136 
2137  /* Set up to let SIGINT cancel simple_prompt_extended() */
2138  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2139  prompt_ctx.enabled = &sigint_interrupt_enabled;
2140  prompt_ctx.canceled = false;
2141 
2142  if (arg2)
2143  {
2144  prompt_text = arg1;
2145  opt = arg2;
2146  }
2147  else
2148  opt = arg1;
2149 
2150  if (!pset.inputfile)
2151  {
2152  result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2153  }
2154  else
2155  {
2156  if (prompt_text)
2157  {
2158  fputs(prompt_text, stdout);
2159  fflush(stdout);
2160  }
2161  result = gets_fromFile(stdin);
2162  if (!result)
2163  {
2164  pg_log_error("\\%s: could not read value for variable",
2165  cmd);
2166  success = false;
2167  }
2168  }
2169 
2170  if (prompt_ctx.canceled ||
2171  (result && !SetVariable(pset.vars, opt, result)))
2172  success = false;
2173 
2174  if (result)
2175  free(result);
2176  if (prompt_text)
2177  free(prompt_text);
2178  free(opt);
2179  }
2180  }
2181  else
2182  ignore_slash_options(scan_state);
2183 
2185 }
char * gets_fromFile(FILE *source)
Definition: input.c:188
char * inputfile
Definition: settings.h:110

References PromptInterruptContext::canceled, PromptInterruptContext::enabled, fflush(), free, gets_fromFile(), ignore_slash_options(), _psqlSettings::inputfile, PromptInterruptContext::jmpbuf, OT_NORMAL, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), SetVariable(), sigint_interrupt_enabled, sigint_interrupt_jmp, simple_prompt_extended(), generate_unaccent_rules::stdout, success, and _psqlSettings::vars.

Referenced by exec_command().

◆ exec_command_pset()

static backslashResult exec_command_pset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2191 of file command.c.

2192 {
2193  bool success = true;
2194 
2195  if (active_branch)
2196  {
2197  char *opt0 = psql_scan_slash_option(scan_state,
2198  OT_NORMAL, NULL, false);
2199  char *opt1 = psql_scan_slash_option(scan_state,
2200  OT_NORMAL, NULL, false);
2201 
2202  if (!opt0)
2203  {
2204  /* list all variables */
2205 
2206  int i;
2207  static const char *const my_list[] = {
2208  "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2209  "fieldsep_zero", "footer", "format", "linestyle", "null",
2210  "numericlocale", "pager", "pager_min_lines",
2211  "recordsep", "recordsep_zero",
2212  "tableattr", "title", "tuples_only",
2213  "unicode_border_linestyle",
2214  "unicode_column_linestyle",
2215  "unicode_header_linestyle",
2216  NULL
2217  };
2218 
2219  for (i = 0; my_list[i] != NULL; i++)
2220  {
2221  char *val = pset_value_string(my_list[i], &pset.popt);
2222 
2223  printf("%-24s %s\n", my_list[i], val);
2224  free(val);
2225  }
2226 
2227  success = true;
2228  }
2229  else
2230  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2231 
2232  free(opt0);
2233  free(opt1);
2234  }
2235  else
2236  ignore_slash_options(scan_state);
2237 
2239 }
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:4823
long val
Definition: informix.c:664

References do_pset(), free, i, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, printf, pset, pset_value_string(), PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, success, and val.

Referenced by exec_command().

◆ exec_command_quit()

static backslashResult exec_command_quit ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2245 of file command.c.

2246 {
2248 
2249  if (active_branch)
2251 
2252  return status;
2253 }
@ PSQL_CMD_TERMINATE
Definition: command.h:20

References PSQL_CMD_SKIP_LINE, PSQL_CMD_TERMINATE, and status().

Referenced by exec_command().

◆ exec_command_reset()

static backslashResult exec_command_reset ( PsqlScanState  scan_state,
bool  active_branch,
PQExpBuffer  query_buf 
)
static

Definition at line 2259 of file command.c.

2261 {
2262  if (active_branch)
2263  {
2264  resetPQExpBuffer(query_buf);
2265  psql_scan_reset(scan_state);
2266  if (!pset.quiet)
2267  puts(_("Query buffer reset (cleared)."));
2268  }
2269 
2270  return PSQL_CMD_SKIP_LINE;
2271 }
void psql_scan_reset(PsqlScanState state)

References _, pset, PSQL_CMD_SKIP_LINE, psql_scan_reset(), _psqlSettings::quiet, and resetPQExpBuffer().

Referenced by exec_command().

◆ exec_command_s()

static backslashResult exec_command_s ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2277 of file command.c.

2278 {
2279  bool success = true;
2280 
2281  if (active_branch)
2282  {
2283  char *fname = psql_scan_slash_option(scan_state,
2284  OT_NORMAL, NULL, true);
2285 
2286  expand_tilde(&fname);
2287  success = printHistory(fname, pset.popt.topt.pager);
2288  if (success && !pset.quiet && fname)
2289  printf(_("Wrote history to file \"%s\".\n"), fname);
2290  if (!fname)
2291  putchar('\n');
2292  free(fname);
2293  }
2294  else
2295  ignore_slash_options(scan_state);
2296 
2298 }
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:489

References _, expand_tilde(), free, ignore_slash_options(), OT_NORMAL, printTableOpt::pager, _psqlSettings::popt, printf, printHistory(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, success, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2304 of file command.c.

2305 {
2306  bool success = true;
2307 
2308  if (active_branch)
2309  {
2310  char *opt0 = psql_scan_slash_option(scan_state,
2311  OT_NORMAL, NULL, false);
2312 
2313  if (!opt0)
2314  {
2315  /* list all variables */
2317  success = true;
2318  }
2319  else
2320  {
2321  /*
2322  * Set variable to the concatenation of the arguments.
2323  */
2324  char *newval;
2325  char *opt;
2326 
2327  opt = psql_scan_slash_option(scan_state,
2328  OT_NORMAL, NULL, false);
2329  newval = pg_strdup(opt ? opt : "");
2330  free(opt);
2331 
2332  while ((opt = psql_scan_slash_option(scan_state,
2333  OT_NORMAL, NULL, false)))
2334  {
2335  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2336  strcat(newval, opt);
2337  free(opt);
2338  }
2339 
2340  if (!SetVariable(pset.vars, opt0, newval))
2341  success = false;
2342 
2343  free(newval);
2344  }
2345  free(opt0);
2346  }
2347  else
2348  ignore_slash_options(scan_state);
2349 
2351 }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define newval
void PrintVariables(VariableSpace space)
Definition: variables.c:186

References free, ignore_slash_options(), newval, OT_NORMAL, pg_realloc(), pg_strdup(), PrintVariables(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), SetVariable(), success, and _psqlSettings::vars.

Referenced by exec_command().

◆ exec_command_setenv()

static backslashResult exec_command_setenv ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 2357 of file command.c.

2359 {
2360  bool success = true;
2361 
2362  if (active_branch)
2363  {
2364  char *envvar = psql_scan_slash_option(scan_state,
2365  OT_NORMAL, NULL, false);
2366  char *envval = psql_scan_slash_option(scan_state,
2367  OT_NORMAL, NULL, false);
2368 
2369  if (!envvar)
2370  {
2371  pg_log_error("\\%s: missing required argument", cmd);
2372  success = false;
2373  }
2374  else if (strchr(envvar, '=') != NULL)
2375  {
2376  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2377  cmd);
2378  success = false;
2379  }
2380  else if (!envval)
2381  {
2382  /* No argument - unset the environment variable */
2383  unsetenv(envvar);
2384  success = true;
2385  }
2386  else
2387  {
2388  /* Set variable to the value of the next argument */
2389  setenv(envvar, envval, 1);
2390  success = true;
2391  }
2392  free(envvar);
2393  free(envval);
2394  }
2395  else
2396  ignore_slash_options(scan_state);
2397 
2399 }
#define unsetenv(x)
Definition: win32_port.h:508
#define setenv(x, y, z)
Definition: win32_port.h:507

References free, ignore_slash_options(), OT_NORMAL, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), setenv, success, and unsetenv.

Referenced by exec_command().

◆ exec_command_sf_sv()

static backslashResult exec_command_sf_sv ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd,
bool  is_func 
)
static

Definition at line 2405 of file command.c.

2407 {
2409 
2410  if (active_branch)
2411  {
2412  bool show_linenumbers = (strchr(cmd, '+') != NULL);
2413  PQExpBuffer buf;
2414  char *obj_desc;
2415  Oid obj_oid = InvalidOid;
2417 
2418  buf = createPQExpBuffer();
2419  obj_desc = psql_scan_slash_option(scan_state,
2420  OT_WHOLE_LINE, NULL, true);
2421  if (pset.sversion < (is_func ? 80400 : 70400))
2422  {
2423  char sverbuf[32];
2424 
2426  sverbuf, sizeof(sverbuf));
2427  if (is_func)
2428  pg_log_error("The server (version %s) does not support showing function source.",
2429  sverbuf);
2430  else
2431  pg_log_error("The server (version %s) does not support showing view definitions.",
2432  sverbuf);
2434  }
2435  else if (!obj_desc)
2436  {
2437  if (is_func)
2438  pg_log_error("function name is required");
2439  else
2440  pg_log_error("view name is required");
2442  }
2443  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2444  {
2445  /* error already reported */
2447  }
2448  else if (!get_create_object_cmd(eot, obj_oid, buf))
2449  {
2450  /* error already reported */
2452  }
2453  else
2454  {
2455  FILE *output;
2456  bool is_pager;
2457 
2458  /* Select output stream: stdout, pager, or file */
2459  if (pset.queryFout == stdout)
2460  {
2461  /* count lines in function to see if pager is needed */
2462  int lineno = count_lines_in_buf(buf);
2463 
2464  output = PageOutput(lineno, &(pset.popt.topt));
2465  is_pager = true;
2466  }
2467  else
2468  {
2469  /* use previously set output file, without pager */
2470  output = pset.queryFout;
2471  is_pager = false;
2472  }
2473 
2474  if (show_linenumbers)
2475  {
2476  /*
2477  * For functions, lineno "1" should correspond to the first
2478  * line of the function body. We expect that
2479  * pg_get_functiondef() will emit that on a line beginning
2480  * with "AS ", and that there can be no such line before the
2481  * real start of the function body.
2482  */
2484  is_func ? "AS " : NULL);
2485  }
2486  else
2487  {
2488  /* just send the definition to output */
2489  fputs(buf->data, output);
2490  }
2491 
2492  if (is_pager)
2493  ClosePager(output);
2494  }
2495 
2496  if (obj_desc)
2497  free(obj_desc);
2499  }
2500  else
2501  ignore_slash_whole_line(scan_state);
2502 
2503  return status;
2504 }
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:5482
static void print_with_linenumbers(FILE *output, char *lines, const char *header_keyword)
Definition: command.c:5509
void ClosePager(FILE *pagerpipe)
Definition: print.c:3096
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:3045
static void output(uint64 loop_count)
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116

References buf, ClosePager(), count_lines_in_buf(), createPQExpBuffer(), destroyPQExpBuffer(), EditableFunction, EditableView, formatPGVersionNumber(), free, get_create_object_cmd(), ignore_slash_whole_line(), InvalidOid, lookup_object_oid(), OT_WHOLE_LINE, output(), PageOutput(), pg_log_error, _psqlSettings::popt, print_with_linenumbers(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::queryFout, status(), generate_unaccent_rules::stdout, _psqlSettings::sversion, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_shell_escape()

static backslashResult exec_command_shell_escape ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2789 of file command.c.

2790 {
2791  bool success = true;
2792 
2793  if (active_branch)
2794  {
2795  char *opt = psql_scan_slash_option(scan_state,
2796  OT_WHOLE_LINE, NULL, false);
2797 
2798  success = do_shell(opt);
2799  free(opt);
2800  }
2801  else
2802  ignore_slash_whole_line(scan_state);
2803 
2805 }
static bool do_shell(const char *command)
Definition: command.c:4894

References do_shell(), free, ignore_slash_whole_line(), OT_WHOLE_LINE, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), and success.

Referenced by exec_command().

◆ exec_command_slash_command_help()

static backslashResult exec_command_slash_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2811 of file command.c.

2812 {
2813  if (active_branch)
2814  {
2815  char *opt0 = psql_scan_slash_option(scan_state,
2816  OT_NORMAL, NULL, false);
2817 
2818  if (!opt0 || strcmp(opt0, "commands") == 0)
2820  else if (strcmp(opt0, "options") == 0)
2822  else if (strcmp(opt0, "variables") == 0)
2824  else
2826 
2827  if (opt0)
2828  free(opt0);
2829  }
2830  else
2831  ignore_slash_options(scan_state);
2832 
2833  return PSQL_CMD_SKIP_LINE;
2834 }
void helpVariables(unsigned short int pager)
Definition: help.c:340
void slashUsage(unsigned short int pager)
Definition: help.c:157
static void usage(const char *progname)
Definition: vacuumlo.c:417

References free, helpVariables(), ignore_slash_options(), OT_NORMAL, printTableOpt::pager, _psqlSettings::popt, pset, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), slashUsage(), printQueryOpt::topt, and usage().

Referenced by exec_command().

◆ exec_command_t()

static backslashResult exec_command_t ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2510 of file command.c.

2511 {
2512  bool success = true;
2513 
2514  if (active_branch)
2515  {
2516  char *opt = psql_scan_slash_option(scan_state,
2517  OT_NORMAL, NULL, true);
2518 
2519  success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
2520  free(opt);
2521  }
2522  else
2523  ignore_slash_options(scan_state);
2524 
2526 }

References do_pset(), free, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, and success.

Referenced by exec_command().

◆ exec_command_T()

static backslashResult exec_command_T ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2532 of file command.c.

2533 {
2534  bool success = true;
2535 
2536  if (active_branch)
2537  {
2538  char *value = psql_scan_slash_option(scan_state,
2539  OT_NORMAL, NULL, false);
2540 
2541  success = do_pset("tableattr", value, &pset.popt, pset.quiet);
2542  free(value);
2543  }
2544  else
2545  ignore_slash_options(scan_state);
2546 
2548 }

References do_pset(), free, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, success, and value.

Referenced by exec_command().

◆ exec_command_timing()

static backslashResult exec_command_timing ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2554 of file command.c.

2555 {
2556  bool success = true;
2557 
2558  if (active_branch)
2559  {
2560  char *opt = psql_scan_slash_option(scan_state,
2561  OT_NORMAL, NULL, false);
2562 
2563  if (opt)
2564  success = ParseVariableBool(opt, "\\timing", &pset.timing);
2565  else
2566  pset.timing = !pset.timing;
2567  if (!pset.quiet)
2568  {
2569  if (pset.timing)
2570  puts(_("Timing is on."));
2571  else
2572  puts(_("Timing is off."));
2573  }
2574  free(opt);
2575  }
2576  else
2577  ignore_slash_options(scan_state);
2578 
2580 }

References _, free, ignore_slash_options(), OT_NORMAL, ParseVariableBool(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, success, and _psqlSettings::timing.

Referenced by exec_command().

◆ exec_command_unset()

static backslashResult exec_command_unset ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd 
)
static

Definition at line 2586 of file command.c.

2588 {
2589  bool success = true;
2590 
2591  if (active_branch)
2592  {
2593  char *opt = psql_scan_slash_option(scan_state,
2594  OT_NORMAL, NULL, false);
2595 
2596  if (!opt)
2597  {
2598  pg_log_error("\\%s: missing required argument", cmd);
2599  success = false;
2600  }
2601  else if (!SetVariable(pset.vars, opt, NULL))
2602  success = false;
2603 
2604  free(opt);
2605  }
2606  else
2607  ignore_slash_options(scan_state);
2608 
2610 }

References free, ignore_slash_options(), OT_NORMAL, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), SetVariable(), success, and _psqlSettings::vars.

Referenced by exec_command().

◆ exec_command_watch()

static backslashResult exec_command_watch ( PsqlScanState  scan_state,
bool  active_branch,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 2705 of file command.c.

2707 {
2708  bool success = true;
2709 
2710  if (active_branch)
2711  {
2712  char *opt = psql_scan_slash_option(scan_state,
2713  OT_NORMAL, NULL, true);
2714  double sleep = 2;
2715 
2716  /* Convert optional sleep-length argument */
2717  if (opt)
2718  {
2719  sleep = strtod(opt, NULL);
2720  if (sleep <= 0)
2721  sleep = 1;
2722  free(opt);
2723  }
2724 
2725  /* If query_buf is empty, recall and execute previous query */
2726  (void) copy_previous_query(query_buf, previous_buf);
2727 
2728  success = do_watch(query_buf, sleep);
2729 
2730  /* Reset the query buffer as though for \r */
2731  resetPQExpBuffer(query_buf);
2732  psql_scan_reset(scan_state);
2733  }
2734  else
2735  ignore_slash_options(scan_state);
2736 
2738 }
static bool do_watch(PQExpBuffer query_buf, double sleep)
Definition: command.c:4938

References copy_previous_query(), do_watch(), free, ignore_slash_options(), OT_NORMAL, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_reset(), psql_scan_slash_option(), resetPQExpBuffer(), and success.

Referenced by exec_command().

◆ exec_command_write()

static backslashResult exec_command_write ( PsqlScanState  scan_state,
bool  active_branch,
const char *  cmd,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 2616 of file command.c.

2619 {
2621 
2622  if (active_branch)
2623  {
2624  char *fname = psql_scan_slash_option(scan_state,
2625  OT_FILEPIPE, NULL, true);
2626  FILE *fd = NULL;
2627  bool is_pipe = false;
2628 
2629  if (!query_buf)
2630  {
2631  pg_log_error("no query buffer");
2633  }
2634  else
2635  {
2636  if (!fname)
2637  {
2638  pg_log_error("\\%s: missing required argument", cmd);
2640  }
2641  else
2642  {
2643  expand_tilde(&fname);
2644  if (fname[0] == '|')
2645  {
2646  is_pipe = true;
2648  fd = popen(&fname[1], "w");
2649  }
2650  else
2651  {
2652  canonicalize_path(fname);
2653  fd = fopen(fname, "w");
2654  }
2655  if (!fd)
2656  {
2657  pg_log_error("%s: %m", fname);
2659  }
2660  }
2661  }
2662 
2663  if (fd)
2664  {
2665  int result;
2666 
2667  /*
2668  * We want to print the same thing \g would execute, but not to
2669  * change the query buffer state; so we can't use
2670  * copy_previous_query(). Also, beware of possibility that buffer
2671  * pointers are NULL.
2672  */
2673  if (query_buf && query_buf->len > 0)
2674  fprintf(fd, "%s\n", query_buf->data);
2675  else if (previous_buf && previous_buf->len > 0)
2676  fprintf(fd, "%s\n", previous_buf->data);
2677 
2678  if (is_pipe)
2679  result = pclose(fd);
2680  else
2681  result = fclose(fd);
2682 
2683  if (result == EOF)
2684  {
2685  pg_log_error("%s: %m", fname);
2687  }
2688  }
2689 
2690  if (is_pipe)
2692 
2693  free(fname);
2694  }
2695  else
2696  ignore_slash_filepipe(scan_state);
2697 
2698  return status;
2699 }

References canonicalize_path(), PQExpBufferData::data, disable_sigpipe_trap(), expand_tilde(), fd(), fprintf, free, ignore_slash_filepipe(), PQExpBufferData::len, OT_FILEPIPE, pg_log_error, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), restore_sigpipe_trap(), and status().

Referenced by exec_command().

◆ exec_command_x()

static backslashResult exec_command_x ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2744 of file command.c.

2745 {
2746  bool success = true;
2747 
2748  if (active_branch)
2749  {
2750  char *opt = psql_scan_slash_option(scan_state,
2751  OT_NORMAL, NULL, true);
2752 
2753  success = do_pset("expanded", opt, &pset.popt, pset.quiet);
2754  free(opt);
2755  }
2756  else
2757  ignore_slash_options(scan_state);
2758 
2760 }

References do_pset(), free, ignore_slash_options(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), _psqlSettings::quiet, and success.

Referenced by exec_command().

◆ exec_command_z()

static backslashResult exec_command_z ( PsqlScanState  sc