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)
 
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 4837 of file command.c.

Referenced by do_shell().

Typedef Documentation

◆ EditableObjectType

Enumeration Type Documentation

◆ EditableObjectType

Enumerator
EditableFunction 
EditableView 

Definition at line 53 of file command.c.

Function Documentation

◆ _align2string()

static const char* _align2string ( enum printFormat  in)
static

Definition at line 4065 of file command.c.

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().

4066 {
4067  switch (in)
4068  {
4069  case PRINT_NOTHING:
4070  return "nothing";
4071  break;
4072  case PRINT_ALIGNED:
4073  return "aligned";
4074  break;
4075  case PRINT_ASCIIDOC:
4076  return "asciidoc";
4077  break;
4078  case PRINT_CSV:
4079  return "csv";
4080  break;
4081  case PRINT_HTML:
4082  return "html";
4083  break;
4084  case PRINT_LATEX:
4085  return "latex";
4086  break;
4087  case PRINT_LATEX_LONGTABLE:
4088  return "latex-longtable";
4089  break;
4090  case PRINT_TROFF_MS:
4091  return "troff-ms";
4092  break;
4093  case PRINT_UNALIGNED:
4094  return "unaligned";
4095  break;
4096  case PRINT_WRAPPED:
4097  return "wrapped";
4098  break;
4099  }
4100  return "unknown";
4101 }

◆ _unicode_linestyle2string()

static const char* _unicode_linestyle2string ( int  linestyle)
static

Definition at line 4121 of file command.c.

References UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by printPsetInfo(), and pset_value_string().

4122 {
4123  switch (linestyle)
4124  {
4126  return "single";
4127  break;
4129  return "double";
4130  break;
4131  }
4132  return "unknown";
4133 }

◆ connection_warnings()

void connection_warnings ( bool  in_startup)

Definition at line 3538 of file command.c.

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().

3539 {
3540  if (!pset.quiet && !pset.notty)
3541  {
3542  int client_ver = PG_VERSION_NUM;
3543  char cverbuf[32];
3544  char sverbuf[32];
3545 
3546  if (pset.sversion != client_ver)
3547  {
3548  const char *server_version;
3549 
3550  /* Try to get full text form, might include "devel" etc */
3551  server_version = PQparameterStatus(pset.db, "server_version");
3552  /* Otherwise fall back on pset.sversion */
3553  if (!server_version)
3554  {
3556  sverbuf, sizeof(sverbuf));
3557  server_version = sverbuf;
3558  }
3559 
3560  printf(_("%s (%s, server %s)\n"),
3561  pset.progname, PG_VERSION, server_version);
3562  }
3563  /* For version match, only print psql banner on startup. */
3564  else if (in_startup)
3565  printf("%s (%s)\n", pset.progname, PG_VERSION);
3566 
3567  if (pset.sversion / 100 > client_ver / 100)
3568  printf(_("WARNING: %s major version %s, server major version %s.\n"
3569  " Some psql features might not work.\n"),
3570  pset.progname,
3571  formatPGVersionNumber(client_ver, false,
3572  cverbuf, sizeof(cverbuf)),
3574  sverbuf, sizeof(sverbuf)));
3575 
3576 #ifdef WIN32
3577  if (in_startup)
3578  checkWin32Codepage();
3579 #endif
3580  printSSLInfo();
3581  printGSSInfo();
3582  }
3583 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6709
#define printf(...)
Definition: port.h:222
static void printGSSInfo(void)
Definition: command.c:3620
const char * progname
Definition: settings.h:109
static int server_version
Definition: pg_dumpall.c:83
static void printSSLInfo(void)
Definition: command.c:3592
#define _(x)
Definition: elog.c:89
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177

◆ copy_previous_query()

static bool copy_previous_query ( PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 3027 of file command.c.

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

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

3028 {
3029  if (query_buf && query_buf->len == 0)
3030  {
3031  appendPQExpBufferStr(query_buf, previous_buf->data);
3032  return true;
3033  }
3034  return false;
3035 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369

◆ count_lines_in_buf()

static int count_lines_in_buf ( PQExpBuffer  buf)
static

Definition at line 5435 of file command.c.

References PQExpBufferData::data.

Referenced by exec_command_sf_sv().

5436 {
5437  int lineno = 0;
5438  const char *lines = buf->data;
5439 
5440  while (*lines != '\0')
5441  {
5442  lineno++;
5443  /* find start of next line */
5444  lines = strchr(lines, '\n');
5445  if (!lines)
5446  break;
5447  lines++;
5448  }
5449 
5450  return lineno;
5451 }

◆ discard_query_text()

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

Definition at line 3001 of file command.c.

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

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

3003 {
3004  if (query_buf)
3005  {
3006  int new_len = conditional_stack_get_query_len(cstack);
3007 
3008  Assert(new_len >= 0 && new_len <= query_buf->len);
3009  query_buf->len = new_len;
3010  query_buf->data[new_len] = '\0';
3011  }
3012  psql_scan_set_paren_depth(scan_state,
3014 }
void psql_scan_set_paren_depth(PsqlScanState state, int depth)
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:150
#define Assert(condition)
Definition: c.h:804
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:172

◆ do_connect()

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

Definition at line 3084 of file command.c.

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().

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

◆ 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 3803 of file command.c.

References appendPQExpBufferChar(), appendPQExpBufferStr(), 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().

3805 {
3806  char fnametmp[MAXPGPATH];
3807  FILE *stream = NULL;
3808  const char *fname;
3809  bool error = false;
3810  int fd;
3811  struct stat before,
3812  after;
3813 
3814  if (filename_arg)
3815  fname = filename_arg;
3816  else
3817  {
3818  /* make a temp file to edit */
3819 #ifndef WIN32
3820  const char *tmpdir = getenv("TMPDIR");
3821 
3822  if (!tmpdir)
3823  tmpdir = "/tmp";
3824 #else
3825  char tmpdir[MAXPGPATH];
3826  int ret;
3827 
3828  ret = GetTempPath(MAXPGPATH, tmpdir);
3829  if (ret == 0 || ret > MAXPGPATH)
3830  {
3831  pg_log_error("could not locate temporary directory: %s",
3832  !ret ? strerror(errno) : "");
3833  return false;
3834  }
3835 #endif
3836 
3837  /*
3838  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
3839  * current directory to the supplied path unless we use only
3840  * backslashes, so we do that.
3841  */
3842 #ifndef WIN32
3843  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
3844  "/", (int) getpid());
3845 #else
3846  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
3847  "" /* trailing separator already present */ , (int) getpid());
3848 #endif
3849 
3850  fname = (const char *) fnametmp;
3851 
3852  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
3853  if (fd != -1)
3854  stream = fdopen(fd, "w");
3855 
3856  if (fd == -1 || !stream)
3857  {
3858  pg_log_error("could not open temporary file \"%s\": %m", fname);
3859  error = true;
3860  }
3861  else
3862  {
3863  unsigned int ql = query_buf->len;
3864 
3865  /* force newline-termination of what we send to editor */
3866  if (ql > 0 && query_buf->data[ql - 1] != '\n')
3867  {
3868  appendPQExpBufferChar(query_buf, '\n');
3869  ql++;
3870  }
3871 
3872  if (fwrite(query_buf->data, 1, ql, stream) != ql)
3873  {
3874  pg_log_error("%s: %m", fname);
3875 
3876  if (fclose(stream) != 0)
3877  pg_log_error("%s: %m", fname);
3878 
3879  if (remove(fname) != 0)
3880  pg_log_error("%s: %m", fname);
3881 
3882  error = true;
3883  }
3884  else if (fclose(stream) != 0)
3885  {
3886  pg_log_error("%s: %m", fname);
3887  if (remove(fname) != 0)
3888  pg_log_error("%s: %m", fname);
3889  error = true;
3890  }
3891  else
3892  {
3893  struct utimbuf ut;
3894 
3895  /*
3896  * Try to set the file modification time of the temporary file
3897  * a few seconds in the past. Otherwise, the low granularity
3898  * (one second, or even worse on some filesystems) that we can
3899  * portably measure with stat(2) could lead us to not
3900  * recognize a modification, if the user typed very quickly.
3901  *
3902  * This is a rather unlikely race condition, so don't error
3903  * out if the utime(2) call fails --- that would make the cure
3904  * worse than the disease.
3905  */
3906  ut.modtime = ut.actime = time(NULL) - 2;
3907  (void) utime(fname, &ut);
3908  }
3909  }
3910  }
3911 
3912  if (!error && stat(fname, &before) != 0)
3913  {
3914  pg_log_error("%s: %m", fname);
3915  error = true;
3916  }
3917 
3918  /* call editor */
3919  if (!error)
3920  error = !editFile(fname, lineno);
3921 
3922  if (!error && stat(fname, &after) != 0)
3923  {
3924  pg_log_error("%s: %m", fname);
3925  error = true;
3926  }
3927 
3928  /* file was edited if the size or modification time has changed */
3929  if (!error &&
3930  (before.st_size != after.st_size ||
3931  before.st_mtime != after.st_mtime))
3932  {
3933  stream = fopen(fname, PG_BINARY_R);
3934  if (!stream)
3935  {
3936  pg_log_error("%s: %m", fname);
3937  error = true;
3938  }
3939  else
3940  {
3941  /* read file back into query_buf */
3942  char line[1024];
3943 
3944  resetPQExpBuffer(query_buf);
3945  while (fgets(line, sizeof(line), stream) != NULL)
3946  appendPQExpBufferStr(query_buf, line);
3947 
3948  if (ferror(stream))
3949  {
3950  pg_log_error("%s: %m", fname);
3951  error = true;
3952  resetPQExpBuffer(query_buf);
3953  }
3954  else if (edited)
3955  {
3956  *edited = true;
3957  }
3958 
3959  fclose(stream);
3960  }
3961  }
3962  else
3963  {
3964  /*
3965  * If the file was not modified, and the caller requested it, discard
3966  * the query buffer.
3967  */
3968  if (discard_on_quit)
3969  resetPQExpBuffer(query_buf);
3970  }
3971 
3972  /* remove temp file */
3973  if (!filename_arg)
3974  {
3975  if (remove(fname) == -1)
3976  {
3977  pg_log_error("%s: %m", fname);
3978  error = true;
3979  }
3980  }
3981 
3982  return !error;
3983 }
static void error(void)
Definition: sql-dyntest.c:147
#define pg_log_error(...)
Definition: logging.h:80
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_BINARY_R
Definition: c.h:1273
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
#define MAXPGPATH
static bool editFile(const char *fname, int lineno)
Definition: command.c:3722
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
#define strerror
Definition: port.h:229
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define snprintf
Definition: port.h:216
#define stat
Definition: win32_port.h:275

◆ do_pset()

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

Definition at line 4151 of file command.c.

References Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::fieldSep, 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, and printTableOpt::unicode_header_linestyle.

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().

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

◆ do_shell()

static bool do_shell ( const char *  command)
static

Definition at line 4847 of file command.c.

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

Referenced by exec_command_shell_escape().

4848 {
4849  int result;
4850 
4851  if (!command)
4852  {
4853  char *sys;
4854  const char *shellName;
4855 
4856  shellName = getenv("SHELL");
4857 #ifdef WIN32
4858  if (shellName == NULL)
4859  shellName = getenv("COMSPEC");
4860 #endif
4861  if (shellName == NULL)
4862  shellName = DEFAULT_SHELL;
4863 
4864  /* See EDITOR handling comment for an explanation */
4865 #ifndef WIN32
4866  sys = psprintf("exec %s", shellName);
4867 #else
4868  sys = psprintf("\"%s\"", shellName);
4869 #endif
4870  result = system(sys);
4871  free(sys);
4872  }
4873  else
4874  result = system(command);
4875 
4876  if (result == 127 || result == -1)
4877  {
4878  pg_log_error("\\!: failed");
4879  return false;
4880  }
4881  return true;
4882 }
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define free(a)
Definition: header.h:65
#define DEFAULT_SHELL
Definition: command.c:4837

◆ do_watch()

static bool do_watch ( PQExpBuffer  query_buf,
double  sleep 
)
static

Definition at line 4891 of file command.c.

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

Referenced by exec_command_watch().

4892 {
4893  long sleep_ms = (long) (sleep * 1000);
4894  printQueryOpt myopt = pset.popt;
4895  const char *strftime_fmt;
4896  const char *user_title;
4897  char *title;
4898  const char *pagerprog = NULL;
4899  FILE *pagerpipe = NULL;
4900  int title_len;
4901  int res = 0;
4902 #ifdef HAVE_POSIX_DECL_SIGWAIT
4903  sigset_t sigalrm_sigchld_sigint;
4904  sigset_t sigalrm_sigchld;
4905  sigset_t sigint;
4906  struct itimerval interval;
4907  bool done = false;
4908 #endif
4909 
4910  if (!query_buf || query_buf->len <= 0)
4911  {
4912  pg_log_error("\\watch cannot be used with an empty query");
4913  return false;
4914  }
4915 
4916 #ifdef HAVE_POSIX_DECL_SIGWAIT
4917  sigemptyset(&sigalrm_sigchld_sigint);
4918  sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
4919  sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
4920  sigaddset(&sigalrm_sigchld_sigint, SIGINT);
4921 
4922  sigemptyset(&sigalrm_sigchld);
4923  sigaddset(&sigalrm_sigchld, SIGCHLD);
4924  sigaddset(&sigalrm_sigchld, SIGALRM);
4925 
4926  sigemptyset(&sigint);
4927  sigaddset(&sigint, SIGINT);
4928 
4929  /*
4930  * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
4931  * configured), to avoid races. sigwait() will receive them.
4932  */
4933  sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
4934 
4935  /*
4936  * Set a timer to interrupt sigwait() so we can run the query at the
4937  * requested intervals.
4938  */
4939  interval.it_value.tv_sec = sleep_ms / 1000;
4940  interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
4941  interval.it_interval = interval.it_value;
4942  if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
4943  {
4944  pg_log_error("could not set timer: %m");
4945  done = true;
4946  }
4947 #endif
4948 
4949  /*
4950  * For \watch, we ignore the size of the result and always use the pager
4951  * if PSQL_WATCH_PAGER is set. We also ignore the regular PSQL_PAGER or
4952  * PAGER environment variables, because traditional pagers probably won't
4953  * be very useful for showing a stream of results.
4954  */
4955 #ifdef HAVE_POSIX_DECL_SIGWAIT
4956  pagerprog = getenv("PSQL_WATCH_PAGER");
4957 #endif
4958  if (pagerprog && myopt.topt.pager)
4959  {
4961  pagerpipe = popen(pagerprog, "w");
4962 
4963  if (!pagerpipe)
4964  /* silently proceed without pager */
4966  }
4967 
4968  /*
4969  * Choose format for timestamps. We might eventually make this a \pset
4970  * option. In the meantime, using a variable for the format suppresses
4971  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
4972  */
4973  strftime_fmt = "%c";
4974 
4975  /*
4976  * Set up rendering options, in particular, disable the pager unless
4977  * PSQL_WATCH_PAGER was successfully launched.
4978  */
4979  if (!pagerpipe)
4980  myopt.topt.pager = 0;
4981 
4982 
4983  /*
4984  * If there's a title in the user configuration, make sure we have room
4985  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
4986  * bytes for the rest.
4987  */
4988  user_title = myopt.title;
4989  title_len = (user_title ? strlen(user_title) : 0) + 256;
4990  title = pg_malloc(title_len);
4991 
4992  for (;;)
4993  {
4994  time_t timer;
4995  char timebuf[128];
4996 
4997  /*
4998  * Prepare title for output. Note that we intentionally include a
4999  * newline at the end of the title; this is somewhat historical but it
5000  * makes for reasonably nicely formatted output in simple cases.
5001  */
5002  timer = time(NULL);
5003  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5004 
5005  if (user_title)
5006  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5007  user_title, timebuf, sleep);
5008  else
5009  snprintf(title, title_len, _("%s (every %gs)\n"),
5010  timebuf, sleep);
5011  myopt.title = title;
5012 
5013  /* Run the query and print out the results */
5014  res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe);
5015 
5016  /*
5017  * PSQLexecWatch handles the case where we can no longer repeat the
5018  * query, and returns 0 or -1.
5019  */
5020  if (res <= 0)
5021  break;
5022 
5023  if (pagerpipe && ferror(pagerpipe))
5024  break;
5025 
5026 #ifndef HAVE_POSIX_DECL_SIGWAIT
5027 
5028  /*
5029  * Set up cancellation of 'watch' via SIGINT. We redo this each time
5030  * through the loop since it's conceivable something inside
5031  * PSQLexecWatch could change sigint_interrupt_jmp.
5032  */
5033  if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
5034  break;
5035 
5036  /*
5037  * Enable 'watch' cancellations and wait a while before running the
5038  * query again. Break the sleep into short intervals (at most 1s).
5039  */
5040  sigint_interrupt_enabled = true;
5041  for (long i = sleep_ms; i > 0;)
5042  {
5043  long s = Min(i, 1000L);
5044 
5045  pg_usleep(s * 1000L);
5046  if (cancel_pressed)
5047  break;
5048  i -= s;
5049  }
5050  sigint_interrupt_enabled = false;
5051 #else
5052  /* sigwait() will handle SIGINT. */
5053  sigprocmask(SIG_BLOCK, &sigint, NULL);
5054  if (cancel_pressed)
5055  done = true;
5056 
5057  /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5058  while (!done)
5059  {
5060  int signal_received;
5061 
5062  errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5063  if (errno != 0)
5064  {
5065  /* Some other signal arrived? */
5066  if (errno == EINTR)
5067  continue;
5068  else
5069  {
5070  pg_log_error("could not wait for signals: %m");
5071  done = true;
5072  break;
5073  }
5074  }
5075  /* On ^C or pager exit, it's time to stop running the query. */
5076  if (signal_received == SIGINT || signal_received == SIGCHLD)
5077  done = true;
5078  /* Otherwise, we must have SIGALRM. Time to run the query again. */
5079  break;
5080  }
5081 
5082  /* Unblock SIGINT so that slow queries can be interrupted. */
5083  sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5084  if (done)
5085  break;
5086 #endif
5087  }
5088 
5089  if (pagerpipe)
5090  {
5091  pclose(pagerpipe);
5093  }
5094 
5095 #ifdef HAVE_POSIX_DECL_SIGWAIT
5096  /* Disable the interval timer. */
5097  memset(&interval, 0, sizeof(interval));
5098  setitimer(ITIMER_REAL, &interval, NULL);
5099  /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5100  sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5101 #endif
5102 
5103  pg_free(title);
5104  return (res >= 0);
5105 }
volatile bool sigint_interrupt_enabled
Definition: common.c:245
PsqlSettings pset
Definition: startup.c:32
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void disable_sigpipe_trap(void)
Definition: print.c:2925
#define SIGCHLD
Definition: win32_port.h:169
#define pg_log_error(...)
Definition: logging.h:80
#define Min(x, y)
Definition: c.h:986
printTableOpt topt
Definition: print.h:169
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:247
void pg_usleep(long microsec)
Definition: signal.c:53
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
Definition: timer.c:86
void restore_sigpipe_trap(void)
Definition: print.c:2948
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
unsigned short int pager
Definition: print.h:106
char * title
Definition: print.h:171
printQueryOpt popt
Definition: settings.h:91
#define SIGALRM
Definition: win32_port.h:165
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int i
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout)
Definition: common.c:595
#define EINTR
Definition: win32_port.h:343
#define snprintf
Definition: port.h:216
#define _(x)
Definition: elog.c:89
#define ITIMER_REAL
Definition: win32_port.h:187

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 5112 of file command.c.

References _, _psqlSettings::echo_hidden, 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().

5113 {
5115  {
5116  printf(_("********* QUERY **********\n"
5117  "%s\n"
5118  "**************************\n\n"), query);
5119  fflush(stdout);
5120  if (pset.logfile)
5121  {
5123  _("********* QUERY **********\n"
5124  "%s\n"
5125  "**************************\n\n"), query);
5126  fflush(pset.logfile);
5127  }
5128 
5130  return false;
5131  }
5132  return true;
5133 }
PsqlSettings pset
Definition: startup.c:32
#define printf(...)
Definition: port.h:222
#define fprintf
Definition: port.h:220
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:143
FILE * logfile
Definition: settings.h:116
#define _(x)
Definition: elog.c:89

◆ editFile()

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

Definition at line 3722 of file command.c.

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

Referenced by do_edit().

3723 {
3724  const char *editorName;
3725  const char *editor_lineno_arg = NULL;
3726  char *sys;
3727  int result;
3728 
3729  Assert(fname != NULL);
3730 
3731  /* Find an editor to use */
3732  editorName = getenv("PSQL_EDITOR");
3733  if (!editorName)
3734  editorName = getenv("EDITOR");
3735  if (!editorName)
3736  editorName = getenv("VISUAL");
3737  if (!editorName)
3738  editorName = DEFAULT_EDITOR;
3739 
3740  /* Get line number argument, if we need it. */
3741  if (lineno > 0)
3742  {
3743  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
3744 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
3745  if (!editor_lineno_arg)
3746  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
3747 #endif
3748  if (!editor_lineno_arg)
3749  {
3750  pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
3751  return false;
3752  }
3753  }
3754 
3755  /*
3756  * On Unix the EDITOR value should *not* be quoted, since it might include
3757  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
3758  * if necessary. But this policy is not very workable on Windows, due to
3759  * severe brain damage in their command shell plus the fact that standard
3760  * program paths include spaces.
3761  */
3762 #ifndef WIN32
3763  if (lineno > 0)
3764  sys = psprintf("exec %s %s%d '%s'",
3765  editorName, editor_lineno_arg, lineno, fname);
3766  else
3767  sys = psprintf("exec %s '%s'",
3768  editorName, fname);
3769 #else
3770  if (lineno > 0)
3771  sys = psprintf("\"%s\" %s%d \"%s\"",
3772  editorName, editor_lineno_arg, lineno, fname);
3773  else
3774  sys = psprintf("\"%s\" \"%s\"",
3775  editorName, fname);
3776 #endif
3777  result = system(sys);
3778  if (result == -1)
3779  pg_log_error("could not start editor \"%s\"", editorName);
3780  else if (result == 127)
3781  pg_log_error("could not start /bin/sh");
3782  free(sys);
3783 
3784  return result == 0;
3785 }
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define DEFAULT_EDITOR
Definition: settings.h:22
#define free(a)
Definition: header.h:65
#define Assert(condition)
Definition: c.h:804
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23

◆ 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.

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().

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
417  status = PSQL_CMD_UNKNOWN;
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_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1866
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1216
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1598
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2558
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1761
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2090
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:437
PsqlSettings pset
Definition: startup.c:32
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1548
static bool is_branching_command(const char *cmd)
Definition: command.c:2965
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_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1329
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2783
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_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2482
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2163
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1299
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2020
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3027
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2738
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1357
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2677
bool cur_cmd_interactive
Definition: settings.h:107
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2761
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2329
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:600
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_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1685
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:678
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:489
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1519
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1826
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2276
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1639
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1502
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2526
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1261
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1579
enum _backslashResult backslashResult
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2249
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2588
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2217
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2716
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:542
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:666
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1895
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2504
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1971
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:644
#define pg_log_warning(...)
Definition: pgfnames.c:24
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2231
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1485
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:456
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2377
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:702

◆ exec_command_a()

static backslashResult exec_command_a ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 437 of file command.c.

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().

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 
449  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
450 }
PsqlSettings pset
Definition: startup.c:32
enum printFormat format
Definition: print.h:101
printTableOpt topt
Definition: print.h:169
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
printQueryOpt popt
Definition: settings.h:91
static bool success
Definition: initdb.c:165

◆ exec_command_C()

static backslashResult exec_command_C ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 456 of file command.c.

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().

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 
471  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
472 }
PsqlSettings pset
Definition: startup.c:32
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165

◆ 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.

References _, 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().

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"));
567  exit(EXIT_FAILURE);
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 
593  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
594 }
#define pg_log_error(...)
Definition: logging.h:80
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
#define strerror
Definition: port.h:229
int uid_t
Definition: win32_port.h:236
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
#define EXIT_FAILURE
Definition: settings.h:162
static bool success
Definition: initdb.c:165
#define _(x)
Definition: elog.c:89

◆ exec_command_connect()

static backslashResult exec_command_connect ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 489 of file command.c.

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().

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 
535  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
536 }
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:2815
trivalue
Definition: vacuumlo.c:34
#define free(a)
Definition: header.h:65
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:3084

◆ exec_command_conninfo()

static backslashResult exec_command_conninfo ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 600 of file command.c.

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

Referenced by exec_command().

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 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:93
char * PQport(const PGconn *conn)
Definition: fe-connect.c:6659
#define printf(...)
Definition: port.h:222
static void printGSSInfo(void)
Definition: command.c:3620
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6598
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:6646
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6623
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6590
static void printSSLInfo(void)
Definition: command.c:3592
#define _(x)
Definition: elog.c:89

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 644 of file command.c.

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().

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 
659  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
660 }
bool do_copy(const char *args)
Definition: copy.c:268
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
static bool success
Definition: initdb.c:165
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:2952

◆ exec_command_copyright()

static backslashResult exec_command_copyright ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 666 of file command.c.

References print_copyright(), and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

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

◆ exec_command_crosstabview()

static backslashResult exec_command_crosstabview ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 678 of file command.c.

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().

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;
690  status = PSQL_CMD_SEND;
691  }
692  else
693  ignore_slash_options(scan_state);
694 
695  return status;
696 }
PsqlSettings pset
Definition: startup.c:32
#define lengthof(array)
Definition: c.h:734
char * ctv_args[4]
Definition: settings.h:100
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
enum _backslashResult backslashResult
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
int i
bool crosstab_flag
Definition: settings.h:99
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ 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.

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().

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:
757  status = PSQL_CMD_UNKNOWN;
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:
801  status = PSQL_CMD_UNKNOWN;
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:
840  status = PSQL_CMD_UNKNOWN;
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
870  status = PSQL_CMD_UNKNOWN;
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:
885  status = PSQL_CMD_UNKNOWN;
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:
908  status = PSQL_CMD_UNKNOWN;
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:
928  status = PSQL_CMD_UNKNOWN;
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:
945  status = PSQL_CMD_UNKNOWN;
946  }
947 
948  if (pattern)
949  free(pattern);
950  }
951  else
952  ignore_slash_options(scan_state);
953 
954  if (!success)
955  status = PSQL_CMD_ERROR;
956 
957  return status;
958 }
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6496
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:5465
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1341
bool listExtensionContents(const char *pattern)
Definition: describe.c:6032
bool listOpFamilyOperators(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6672
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:4644
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4920
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4407
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4482
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5019
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:220
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:6386
#define true
Definition: c.h:395
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:64
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3995
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1533
bool listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
Definition: describe.c:4211
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4568
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:5897
bool describePublications(const char *pattern)
Definition: describe.c:6220
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:5323
bool listPublications(const char *pattern)
Definition: describe.c:6145
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:5754
#define free(a)
Definition: header.h:65
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:717
enum _backslashResult backslashResult
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:150
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:5671
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:5836
bool listOperatorFamilies(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6590
bool do_lo_list(void)
Definition: large_obj.c:274
bool listExtensions(const char *pattern)
Definition: describe.c:5975
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
bool listExtendedStats(const char *pattern)
Definition: describe.c:4710
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:4802
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1256
bool permissionsList(const char *pattern)
Definition: describe.c:1096
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
static bool success
Definition: initdb.c:165
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3911
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:5394
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3739
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5076
bool listOpFamilyFunctions(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6759
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:962

◆ 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.

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

Referenced by exec_command_d().

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
#define FUNC_MAX_ARGS
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
bool describeOperators(const char *oper_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:891
static bool success
Definition: initdb.c:165

◆ 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.

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().

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 }
PsqlSettings pset
Definition: startup.c:32
FILE * queryFout
Definition: settings.h:84
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
static struct @143 value
#define free(a)
Definition: header.h:65
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918

◆ 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.

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().

1006 {
1008 
1009  if (active_branch)
1010  {
1011  if (!query_buf)
1012  {
1013  pg_log_error("no query buffer");
1014  status = PSQL_CMD_ERROR;
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);
1047  status = PSQL_CMD_ERROR;
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))
1073  status = PSQL_CMD_NEWEDIT;
1074  else
1075  status = PSQL_CMD_ERROR;
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 }
#define pg_log_error(...)
Definition: logging.h:80
void canonicalize_path(char *path)
Definition: path.c:254
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3027
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
enum _backslashResult backslashResult
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:3803
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ 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.

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().

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);
1118  status = PSQL_CMD_ERROR;
1119  }
1120  else if (!query_buf)
1121  {
1122  pg_log_error("no query buffer");
1123  status = PSQL_CMD_ERROR;
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 */
1134  status = PSQL_CMD_ERROR;
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 */
1157  status = PSQL_CMD_ERROR;
1158  }
1159  else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1160  {
1161  /* error already reported */
1162  status = PSQL_CMD_ERROR;
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))
1196  status = PSQL_CMD_ERROR;
1197  else if (!edited)
1198  puts(_("No changes"));
1199  else
1200  status = PSQL_CMD_NEWEDIT;
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 }
EditableObjectType
Definition: command.c:53
PsqlSettings pset
Definition: startup.c:32
#define pg_log_error(...)
Definition: logging.h:80
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:5144
unsigned int Oid
Definition: postgres_ext.h:31
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define InvalidOid
Definition: postgres_ext.h:36
#define free(a)
Definition: header.h:65
enum _backslashResult backslashResult
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:5377
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:3803
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:5204
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define _(x)
Definition: elog.c:89
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:2952

◆ 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.

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().

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 
1750  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1751 }
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:2902
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2981
#define pg_log_error(...)
Definition: logging.h:80
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:2885
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3001
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:94
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:106
static bool success
Definition: initdb.c:165

◆ 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.

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().

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 
1819  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1820 }
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2981
#define pg_log_error(...)
Definition: logging.h:80
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3001
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:94
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:106
static bool success
Definition: initdb.c:165

◆ exec_command_encoding()

static backslashResult exec_command_encoding ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1261 of file command.c.

References _psqlSettings::db, encoding, _psqlSettings::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().

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 }
PGconn * db
Definition: settings.h:82
int encoding
Definition: print.h:122
PsqlSettings pset
Definition: startup.c:32
#define pg_log_error(...)
Definition: logging.h:80
printTableOpt topt
Definition: print.h:169
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6821
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6829
#define free(a)
Definition: header.h:65
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
printQueryOpt popt
Definition: settings.h:91
int32 encoding
Definition: pg_database.h:41
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
int encoding
Definition: settings.h:83
VariableSpace vars
Definition: settings.h:118

◆ 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.

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().

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 
1859  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1860 }
bool conditional_stack_pop(ConditionalStack cstack)
Definition: conditional.c:57
#define pg_log_error(...)
Definition: logging.h:80
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3001
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:94
#define Assert(condition)
Definition: c.h:804
static bool success
Definition: initdb.c:165

◆ exec_command_errverbose()

static backslashResult exec_command_errverbose ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1299 of file command.c.

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().

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 }
PsqlSettings pset
Definition: startup.c:32
#define pg_log_error(...)
Definition: logging.h:80
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3202
PGresult * last_error_result
Definition: settings.h:89
#define _(x)
Definition: elog.c:89
void PQfreemem(void *ptr)
Definition: fe-exec.c:3796

◆ exec_command_f()

static backslashResult exec_command_f ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1329 of file command.c.

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().

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 
1344  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1345 }
PsqlSettings pset
Definition: startup.c:32
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165

◆ 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.

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().

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  }
1396  status = PSQL_CMD_SEND;
1397  }
1398 
1399  free(fname);
1400 
1401  return status;
1402 }
PsqlSettings pset
Definition: startup.c:32
printTableOpt topt
Definition: print.h:169
printQueryOpt * gsavepopt
Definition: settings.h:94
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:4664
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1410
unsigned short int expanded
Definition: print.h:102
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char * gfname
Definition: settings.h:93
#define free(a)
Definition: header.h:65
enum _backslashResult backslashResult
printQueryOpt popt
Definition: settings.h:91
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ exec_command_gdesc()

static backslashResult exec_command_gdesc ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1485 of file command.c.

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

Referenced by exec_command().

1486 {
1488 
1489  if (active_branch)
1490  {
1491  pset.gdesc_flag = true;
1492  status = PSQL_CMD_SEND;
1493  }
1494 
1495  return status;
1496 }
PsqlSettings pset
Definition: startup.c:32
bool gdesc_flag
Definition: settings.h:97
enum _backslashResult backslashResult
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ exec_command_gexec()

static backslashResult exec_command_gexec ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1502 of file command.c.

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

Referenced by exec_command().

1503 {
1505 
1506  if (active_branch)
1507  {
1508  pset.gexec_flag = true;
1509  status = PSQL_CMD_SEND;
1510  }
1511 
1512  return status;
1513 }
PsqlSettings pset
Definition: startup.c:32
bool gexec_flag
Definition: settings.h:98
enum _backslashResult backslashResult
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ exec_command_gset()

static backslashResult exec_command_gset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1519 of file command.c.

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().

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 */
1536  status = PSQL_CMD_SEND;
1537  }
1538  else
1539  ignore_slash_options(scan_state);
1540 
1541  return status;
1542 }
char * gset_prefix
Definition: settings.h:96
PsqlSettings pset
Definition: startup.c:32
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
enum _backslashResult backslashResult
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ exec_command_help()

static backslashResult exec_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1548 of file command.c.

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

Referenced by exec_command().

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 }
PsqlSettings pset
Definition: startup.c:32
printTableOpt topt
Definition: print.h:169
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
unsigned short int pager
Definition: print.h:106
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
void helpSQL(const char *topic, unsigned short int pager)
Definition: help.c:529
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:2952

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1579 of file command.c.

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().

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 
1591  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1592 }
PsqlSettings pset
Definition: startup.c:32
enum printFormat format
Definition: print.h:101
printTableOpt topt
Definition: print.h:169
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
printQueryOpt popt
Definition: settings.h:91
static bool success
Definition: initdb.c:165

◆ 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.

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().

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 }
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:2902
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2981
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:2885
void conditional_stack_push(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:41
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:106

◆ 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.

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().

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 
1626  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1627 }
#define EXIT_SUCCESS
Definition: settings.h:158
#define pg_log_error(...)
Definition: logging.h:80
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
int process_file(char *filename, bool use_relative_path)
Definition: command.c:3998
#define free(a)
Definition: header.h:65
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165

◆ 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.

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().

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 
1888  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1889 }
#define true
Definition: c.h:395
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:1026

◆ 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.

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().

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
1953  status = PSQL_CMD_UNKNOWN;
1954 
1955  free(opt1);
1956  free(opt2);
1957  }
1958  else
1959  ignore_slash_options(scan_state);
1960 
1961  if (!success)
1962  status = PSQL_CMD_ERROR;
1963 
1964  return status;
1965 }
bool do_lo_export(const char *loid_arg, const char *filename_arg)
Definition: large_obj.c:142
#define pg_log_error(...)
Definition: logging.h:80
bool do_lo_unlink(const char *loid_arg)
Definition: large_obj.c:239
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool do_lo_import(const char *filename_arg, const char *comment_arg)
Definition: large_obj.c:176
#define free(a)
Definition: header.h:65
enum _backslashResult backslashResult
bool do_lo_list(void)
Definition: large_obj.c:274
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
static bool success
Definition: initdb.c:165

◆ exec_command_out()

static backslashResult exec_command_out ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1971 of file command.c.

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().

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 
1987  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1988 }
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:2935
bool setQFout(const char *fname)
Definition: common.c:85
#define free(a)
Definition: header.h:65
static bool success
Definition: initdb.c:165

◆ exec_command_password()

static backslashResult exec_command_password ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2020 of file command.c.

References appendStringLiteralConn(), buf, PQExpBufferData::data, _psqlSettings::db, fmtId(), free, ignore_slash_options(), initPQExpBuffer(), OT_SQLID, pg_log_error, pg_log_info, PQclear(), PQencryptPasswordConn(), PQerrorMessage(), PQfreemem(), PQuser(), printfPQExpBuffer(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQLexec(), simple_prompt(), success, termPQExpBuffer(), and user.

Referenced by exec_command().

2021 {
2022  bool success = true;
2023 
2024  if (active_branch)
2025  {
2026  char *opt0 = psql_scan_slash_option(scan_state,
2027  OT_SQLID, NULL, true);
2028  char *pw1;
2029  char *pw2;
2030 
2031  pw1 = simple_prompt("Enter new password: ", false);
2032  pw2 = simple_prompt("Enter it again: ", false);
2033 
2034  if (strcmp(pw1, pw2) != 0)
2035  {
2036  pg_log_error("Passwords didn't match.");
2037  success = false;
2038  }
2039  else
2040  {
2041  char *user;
2042  char *encrypted_password;
2043 
2044  if (opt0)
2045  user = opt0;
2046  else
2047  user = PQuser(pset.db);
2048 
2049  encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
2050 
2051  if (!encrypted_password)
2052  {
2054  success = false;
2055  }
2056  else
2057  {
2059  PGresult *res;
2060 
2061  initPQExpBuffer(&buf);
2062  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
2063  fmtId(user));
2064  appendStringLiteralConn(&buf, encrypted_password, pset.db);
2065  res = PSQLexec(buf.data);
2066  termPQExpBuffer(&buf);
2067  if (!res)
2068  success = false;
2069  else
2070  PQclear(res);
2071  PQfreemem(encrypted_password);
2072  }
2073  }
2074 
2075  if (opt0)
2076  free(opt0);
2077  free(pw1);
2078  free(pw2);
2079  }
2080  else
2081  ignore_slash_options(scan_state);
2082 
2083  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2084 }
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6744
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PsqlSettings pset
Definition: startup.c:32
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define pg_log_error(...)
Definition: logging.h:80
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6598
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
static char * buf
Definition: pg_test_fsync.c:68
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define free(a)
Definition: header.h:65
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1217
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
static char * user
Definition: pg_regress.c:95
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
void PQfreemem(void *ptr)
Definition: fe-exec.c:3796
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define pg_log_info(...)
Definition: logging.h:88
PGresult * PSQLexec(const char *query)
Definition: common.c:540

◆ 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.

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

Referenced by exec_command().

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 }
PsqlSettings pset
Definition: startup.c:32
#define _(x)
Definition: elog.c:89

◆ exec_command_prompt()

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

Definition at line 2090 of file command.c.

References free, gets_fromFile(), ignore_slash_options(), _psqlSettings::inputfile, OT_NORMAL, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), SetVariable(), simple_prompt(), generate_unaccent_rules::stdout, success, and _psqlSettings::vars.

Referenced by exec_command().

2092 {
2093  bool success = true;
2094 
2095  if (active_branch)
2096  {
2097  char *opt,
2098  *prompt_text = NULL;
2099  char *arg1,
2100  *arg2;
2101 
2102  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2103  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2104 
2105  if (!arg1)
2106  {
2107  pg_log_error("\\%s: missing required argument", cmd);
2108  success = false;
2109  }
2110  else
2111  {
2112  char *result;
2113 
2114  if (arg2)
2115  {
2116  prompt_text = arg1;
2117  opt = arg2;
2118  }
2119  else
2120  opt = arg1;
2121 
2122  if (!pset.inputfile)
2123  {
2124  result = simple_prompt(prompt_text, true);
2125  }
2126  else
2127  {
2128  if (prompt_text)
2129  {
2130  fputs(prompt_text, stdout);
2131  fflush(stdout);
2132  }
2133  result = gets_fromFile(stdin);
2134  if (!result)
2135  {
2136  pg_log_error("\\%s: could not read value for variable",
2137  cmd);
2138  success = false;
2139  }
2140  }
2141 
2142  if (result &&
2143  !SetVariable(pset.vars, opt, result))
2144  success = false;
2145 
2146  if (result)
2147  free(result);
2148  if (prompt_text)
2149  free(prompt_text);
2150  free(opt);
2151  }
2152  }
2153  else
2154  ignore_slash_options(scan_state);
2155 
2156  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2157 }
PsqlSettings pset
Definition: startup.c:32
#define pg_log_error(...)
Definition: logging.h:80
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
char * inputfile
Definition: settings.h:110
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
char * gets_fromFile(FILE *source)
Definition: input.c:188
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
VariableSpace vars
Definition: settings.h:118

◆ exec_command_pset()

static backslashResult exec_command_pset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2163 of file command.c.

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().

2164 {
2165  bool success = true;
2166 
2167  if (active_branch)
2168  {
2169  char *opt0 = psql_scan_slash_option(scan_state,
2170  OT_NORMAL, NULL, false);
2171  char *opt1 = psql_scan_slash_option(scan_state,
2172  OT_NORMAL, NULL, false);
2173 
2174  if (!opt0)
2175  {
2176  /* list all variables */
2177 
2178  int i;
2179  static const char *const my_list[] = {
2180  "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2181  "fieldsep_zero", "footer", "format", "linestyle", "null",
2182  "numericlocale", "pager", "pager_min_lines",
2183  "recordsep", "recordsep_zero",
2184  "tableattr", "title", "tuples_only",
2185  "unicode_border_linestyle",
2186  "unicode_column_linestyle",
2187  "unicode_header_linestyle",
2188  NULL
2189  };
2190 
2191  for (i = 0; my_list[i] != NULL; i++)
2192  {
2193  char *val = pset_value_string(my_list[i], &pset.popt);
2194 
2195  printf("%-24s %s\n", my_list[i], val);
2196  free(val);
2197  }
2198 
2199  success = true;
2200  }
2201  else
2202  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2203 
2204  free(opt0);
2205  free(opt1);
2206  }
2207  else
2208  ignore_slash_options(scan_state);
2209 
2210  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2211 }
PsqlSettings pset
Definition: startup.c:32
#define printf(...)
Definition: port.h:222
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
int i
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:4776
static bool success
Definition: initdb.c:165
long val
Definition: informix.c:664

◆ exec_command_quit()

static backslashResult exec_command_quit ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2217 of file command.c.

References PSQL_CMD_SKIP_LINE, PSQL_CMD_TERMINATE, and status().

Referenced by exec_command().

2218 {
2220 
2221  if (active_branch)
2222  status = PSQL_CMD_TERMINATE;
2223 
2224  return status;
2225 }
enum _backslashResult backslashResult
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ exec_command_reset()

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

Definition at line 2231 of file command.c.

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

Referenced by exec_command().

2233 {
2234  if (active_branch)
2235  {
2236  resetPQExpBuffer(query_buf);
2237  psql_scan_reset(scan_state);
2238  if (!pset.quiet)
2239  puts(_("Query buffer reset (cleared)."));
2240  }
2241 
2242  return PSQL_CMD_SKIP_LINE;
2243 }
PsqlSettings pset
Definition: startup.c:32
void psql_scan_reset(PsqlScanState state)
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define _(x)
Definition: elog.c:89

◆ exec_command_s()

static backslashResult exec_command_s ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2249 of file command.c.

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().

2250 {
2251  bool success = true;
2252 
2253  if (active_branch)
2254  {
2255  char *fname = psql_scan_slash_option(scan_state,
2256  OT_NORMAL, NULL, true);
2257 
2258  expand_tilde(&fname);
2259  success = printHistory(fname, pset.popt.topt.pager);
2260  if (success && !pset.quiet && fname)
2261  printf(_("Wrote history to file \"%s\".\n"), fname);
2262  if (!fname)
2263  putchar('\n');
2264  free(fname);
2265  }
2266  else
2267  ignore_slash_options(scan_state);
2268 
2269  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2270 }
PsqlSettings pset
Definition: startup.c:32
printTableOpt topt
Definition: print.h:169
#define printf(...)
Definition: port.h:222
void expand_tilde(char **filename)
Definition: common.c:2223
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
unsigned short int pager
Definition: print.h:106
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
#define _(x)
Definition: elog.c:89
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:489

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2276 of file command.c.

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().

2277 {
2278  bool success = true;
2279 
2280  if (active_branch)
2281  {
2282  char *opt0 = psql_scan_slash_option(scan_state,
2283  OT_NORMAL, NULL, false);
2284 
2285  if (!opt0)
2286  {
2287  /* list all variables */
2289  success = true;
2290  }
2291  else
2292  {
2293  /*
2294  * Set variable to the concatenation of the arguments.
2295  */
2296  char *newval;
2297  char *opt;
2298 
2299  opt = psql_scan_slash_option(scan_state,
2300  OT_NORMAL, NULL, false);
2301  newval = pg_strdup(opt ? opt : "");
2302  free(opt);
2303 
2304  while ((opt = psql_scan_slash_option(scan_state,
2305  OT_NORMAL, NULL, false)))
2306  {
2307  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2308  strcat(newval, opt);
2309  free(opt);
2310  }
2311 
2312  if (!SetVariable(pset.vars, opt0, newval))
2313  success = false;
2314 
2315  free(newval);
2316  }
2317  free(opt0);
2318  }
2319  else
2320  ignore_slash_options(scan_state);
2321 
2322  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2323 }
PsqlSettings pset
Definition: startup.c:32
void PrintVariables(VariableSpace space)
Definition: variables.c:186
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define free(a)
Definition: header.h:65
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
#define newval
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2918
static bool success
Definition: initdb.c:165
VariableSpace vars
Definition: settings.h:118

◆ exec_command_setenv()

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

Definition at line 2329 of file command.c.

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().

2331 {
2332  bool success = true;
2333 
2334  if (active_branch)
2335  {
2336  char *envvar = psql_scan_slash_option(scan_state,
2337  OT_NORMAL, NULL, false);
2338  char *envval = psql_scan_slash_option(scan_state,
2339  OT_NORMAL, NULL, false);
2340 
2341  if (!envvar)
2342  {
2343  pg_log_error("\\%s: missing required argument", cmd);
2344  success = false;
2345  }
2346  else if (strchr(envvar, '=') != NULL)
2347  {
2348  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2349  cmd);
2350  success = false;
2351  }
2352  else if (!envval)
2353  {
2354  /* No argument - unset the environment variable */
2355  unsetenv(envvar);
2356  success = true;
2357  }
2358  else
2359  {
2360  /* Set variable to the value of the next argument */
2361  setenv(envvar, envval, 1);
2362  success = true;
2363  }
2364  free(envvar);
2365  free(envval);
2366  }
2367  else
2368  ignore_slash_options(scan_state);
2369 
2370  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2371 }
#define pg_log_error(...)
Definition: logging.h:80
#define setenv(x, y, z)
Definition: win32_port.h:497
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define free(a)
Definition: header.h:65