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

Referenced by do_shell().

Typedef Documentation

◆ EditableObjectType

Enumeration Type Documentation

◆ EditableObjectType

Enumerator
EditableFunction 
EditableView 

Definition at line 52 of file command.c.

Function Documentation

◆ _align2string()

static const char* _align2string ( enum printFormat  in)
static

Definition at line 4064 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().

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

◆ _unicode_linestyle2string()

static const char* _unicode_linestyle2string ( int  linestyle)
static

Definition at line 4120 of file command.c.

References UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by printPsetInfo(), and pset_value_string().

4121 {
4122  switch (linestyle)
4123  {
4125  return "single";
4126  break;
4128  return "double";
4129  break;
4130  }
4131  return "unknown";
4132 }

◆ connection_warnings()

void connection_warnings ( bool  in_startup)

Definition at line 3537 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().

3538 {
3539  if (!pset.quiet && !pset.notty)
3540  {
3541  int client_ver = PG_VERSION_NUM;
3542  char cverbuf[32];
3543  char sverbuf[32];
3544 
3545  if (pset.sversion != client_ver)
3546  {
3547  const char *server_version;
3548 
3549  /* Try to get full text form, might include "devel" etc */
3550  server_version = PQparameterStatus(pset.db, "server_version");
3551  /* Otherwise fall back on pset.sversion */
3552  if (!server_version)
3553  {
3555  sverbuf, sizeof(sverbuf));
3556  server_version = sverbuf;
3557  }
3558 
3559  printf(_("%s (%s, server %s)\n"),
3560  pset.progname, PG_VERSION, server_version);
3561  }
3562  /* For version match, only print psql banner on startup. */
3563  else if (in_startup)
3564  printf("%s (%s)\n", pset.progname, PG_VERSION);
3565 
3566  if (pset.sversion / 100 > client_ver / 100)
3567  printf(_("WARNING: %s major version %s, server major version %s.\n"
3568  " Some psql features might not work.\n"),
3569  pset.progname,
3570  formatPGVersionNumber(client_ver, false,
3571  cverbuf, sizeof(cverbuf)),
3573  sverbuf, sizeof(sverbuf)));
3574 
3575 #ifdef WIN32
3576  if (in_startup)
3577  checkWin32Codepage();
3578 #endif
3579  printSSLInfo();
3580  printGSSInfo();
3581  }
3582 }
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:6700
#define printf(...)
Definition: port.h:222
static void printGSSInfo(void)
Definition: command.c:3619
const char * progname
Definition: settings.h:109
static int server_version
Definition: pg_dumpall.c:82
static void printSSLInfo(void)
Definition: command.c:3591
#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 3026 of file command.c.

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

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

3027 {
3028  if (query_buf && query_buf->len == 0)
3029  {
3030  appendPQExpBufferStr(query_buf, previous_buf->data);
3031  return true;
3032  }
3033  return false;
3034 }
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 5319 of file command.c.

References PQExpBufferData::data.

Referenced by exec_command_sf_sv().

5320 {
5321  int lineno = 0;
5322  const char *lines = buf->data;
5323 
5324  while (*lines != '\0')
5325  {
5326  lineno++;
5327  /* find start of next line */
5328  lines = strchr(lines, '\n');
5329  if (!lines)
5330  break;
5331  lines++;
5332  }
5333 
5334  return lineno;
5335 }

◆ discard_query_text()

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

Definition at line 3000 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().

3002 {
3003  if (query_buf)
3004  {
3005  int new_len = conditional_stack_get_query_len(cstack);
3006 
3007  Assert(new_len >= 0 && new_len <= query_buf->len);
3008  query_buf->len = new_len;
3009  query_buf->data[new_len] = '\0';
3010  }
3011  psql_scan_set_paren_depth(scan_state,
3013 }
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 3083 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().

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

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

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

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

Referenced by exec_command_shell_escape().

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

◆ do_watch()

static bool do_watch ( PQExpBuffer  query_buf,
double  sleep 
)
static

Definition at line 4890 of file command.c.

References _, cancel_pressed, PQExpBufferData::data, i, PQExpBufferData::len, Min, printTableOpt::pager, pg_free(), pg_log_error, pg_malloc(), pg_usleep(), _psqlSettings::popt, pset, PSQLexecWatch(), sigint_interrupt_enabled, sigint_interrupt_jmp, snprintf, printQueryOpt::title, and printQueryOpt::topt.

Referenced by exec_command_watch().

4891 {
4892  long sleep_ms = (long) (sleep * 1000);
4893  printQueryOpt myopt = pset.popt;
4894  const char *strftime_fmt;
4895  const char *user_title;
4896  char *title;
4897  int title_len;
4898  int res = 0;
4899 
4900  if (!query_buf || query_buf->len <= 0)
4901  {
4902  pg_log_error("\\watch cannot be used with an empty query");
4903  return false;
4904  }
4905 
4906  /*
4907  * Choose format for timestamps. We might eventually make this a \pset
4908  * option. In the meantime, using a variable for the format suppresses
4909  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
4910  */
4911  strftime_fmt = "%c";
4912 
4913  /*
4914  * Set up rendering options, in particular, disable the pager, because
4915  * nobody wants to be prompted while watching the output of 'watch'.
4916  */
4917  myopt.topt.pager = 0;
4918 
4919  /*
4920  * If there's a title in the user configuration, make sure we have room
4921  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
4922  * bytes for the rest.
4923  */
4924  user_title = myopt.title;
4925  title_len = (user_title ? strlen(user_title) : 0) + 256;
4926  title = pg_malloc(title_len);
4927 
4928  for (;;)
4929  {
4930  time_t timer;
4931  char timebuf[128];
4932  long i;
4933 
4934  /*
4935  * Prepare title for output. Note that we intentionally include a
4936  * newline at the end of the title; this is somewhat historical but it
4937  * makes for reasonably nicely formatted output in simple cases.
4938  */
4939  timer = time(NULL);
4940  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
4941 
4942  if (user_title)
4943  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
4944  user_title, timebuf, sleep);
4945  else
4946  snprintf(title, title_len, _("%s (every %gs)\n"),
4947  timebuf, sleep);
4948  myopt.title = title;
4949 
4950  /* Run the query and print out the results */
4951  res = PSQLexecWatch(query_buf->data, &myopt);
4952 
4953  /*
4954  * PSQLexecWatch handles the case where we can no longer repeat the
4955  * query, and returns 0 or -1.
4956  */
4957  if (res <= 0)
4958  break;
4959 
4960  /*
4961  * Set up cancellation of 'watch' via SIGINT. We redo this each time
4962  * through the loop since it's conceivable something inside
4963  * PSQLexecWatch could change sigint_interrupt_jmp.
4964  */
4965  if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
4966  break;
4967 
4968  /*
4969  * Enable 'watch' cancellations and wait a while before running the
4970  * query again. Break the sleep into short intervals (at most 1s)
4971  * since pg_usleep isn't interruptible on some platforms.
4972  */
4973  sigint_interrupt_enabled = true;
4974  i = sleep_ms;
4975  while (i > 0)
4976  {
4977  long s = Min(i, 1000L);
4978 
4979  pg_usleep(s * 1000L);
4980  if (cancel_pressed)
4981  break;
4982  i -= s;
4983  }
4984  sigint_interrupt_enabled = false;
4985  }
4986 
4987  pg_free(title);
4988  return (res >= 0);
4989 }
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
int PSQLexecWatch(const char *query, const printQueryOpt *opt)
Definition: common.c:595
#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
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
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int i
#define snprintf
Definition: port.h:216
#define _(x)
Definition: elog.c:89

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 4996 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().

4997 {
4999  {
5000  printf(_("********* QUERY **********\n"
5001  "%s\n"
5002  "**************************\n\n"), query);
5003  fflush(stdout);
5004  if (pset.logfile)
5005  {
5007  _("********* QUERY **********\n"
5008  "%s\n"
5009  "**************************\n\n"), query);
5010  fflush(pset.logfile);
5011  }
5012 
5014  return false;
5015  }
5016  return true;
5017 }
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 3721 of file command.c.

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

Referenced by do_edit().

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

288 {
290  bool active_branch = conditional_active(cstack);
291 
292  /*
293  * In interactive mode, warn when we're ignoring a command within a false
294  * \if-branch. But we continue on, so as to parse and discard the right
295  * amount of parameter text. Each individual backslash command subroutine
296  * is responsible for doing nothing after discarding appropriate
297  * arguments, if !active_branch.
298  */
299  if (pset.cur_cmd_interactive && !active_branch &&
300  !is_branching_command(cmd))
301  {
302  pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
303  cmd);
304  }
305 
306  if (strcmp(cmd, "a") == 0)
307  status = exec_command_a(scan_state, active_branch);
308  else if (strcmp(cmd, "C") == 0)
309  status = exec_command_C(scan_state, active_branch);
310  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
311  status = exec_command_connect(scan_state, active_branch);
312  else if (strcmp(cmd, "cd") == 0)
313  status = exec_command_cd(scan_state, active_branch, cmd);
314  else if (strcmp(cmd, "conninfo") == 0)
315  status = exec_command_conninfo(scan_state, active_branch);
316  else if (pg_strcasecmp(cmd, "copy") == 0)
317  status = exec_command_copy(scan_state, active_branch);
318  else if (strcmp(cmd, "copyright") == 0)
319  status = exec_command_copyright(scan_state, active_branch);
320  else if (strcmp(cmd, "crosstabview") == 0)
321  status = exec_command_crosstabview(scan_state, active_branch);
322  else if (cmd[0] == 'd')
323  status = exec_command_d(scan_state, active_branch, cmd);
324  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
325  status = exec_command_edit(scan_state, active_branch,
326  query_buf, previous_buf);
327  else if (strcmp(cmd, "ef") == 0)
328  status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
329  else if (strcmp(cmd, "ev") == 0)
330  status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
331  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
332  strcmp(cmd, "warn") == 0)
333  status = exec_command_echo(scan_state, active_branch, cmd);
334  else if (strcmp(cmd, "elif") == 0)
335  status = exec_command_elif(scan_state, cstack, query_buf);
336  else if (strcmp(cmd, "else") == 0)
337  status = exec_command_else(scan_state, cstack, query_buf);
338  else if (strcmp(cmd, "endif") == 0)
339  status = exec_command_endif(scan_state, cstack, query_buf);
340  else if (strcmp(cmd, "encoding") == 0)
341  status = exec_command_encoding(scan_state, active_branch);
342  else if (strcmp(cmd, "errverbose") == 0)
343  status = exec_command_errverbose(scan_state, active_branch);
344  else if (strcmp(cmd, "f") == 0)
345  status = exec_command_f(scan_state, active_branch);
346  else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
347  status = exec_command_g(scan_state, active_branch, cmd);
348  else if (strcmp(cmd, "gdesc") == 0)
349  status = exec_command_gdesc(scan_state, active_branch);
350  else if (strcmp(cmd, "gexec") == 0)
351  status = exec_command_gexec(scan_state, active_branch);
352  else if (strcmp(cmd, "gset") == 0)
353  status = exec_command_gset(scan_state, active_branch);
354  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
355  status = exec_command_help(scan_state, active_branch);
356  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
357  status = exec_command_html(scan_state, active_branch);
358  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
359  strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
360  status = exec_command_include(scan_state, active_branch, cmd);
361  else if (strcmp(cmd, "if") == 0)
362  status = exec_command_if(scan_state, cstack, query_buf);
363  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
364  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
365  status = exec_command_list(scan_state, active_branch, cmd);
366  else if (strncmp(cmd, "lo_", 3) == 0)
367  status = exec_command_lo(scan_state, active_branch, cmd);
368  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
369  status = exec_command_out(scan_state, active_branch);
370  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
371  status = exec_command_print(scan_state, active_branch,
372  query_buf, previous_buf);
373  else if (strcmp(cmd, "password") == 0)
374  status = exec_command_password(scan_state, active_branch);
375  else if (strcmp(cmd, "prompt") == 0)
376  status = exec_command_prompt(scan_state, active_branch, cmd);
377  else if (strcmp(cmd, "pset") == 0)
378  status = exec_command_pset(scan_state, active_branch);
379  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
380  status = exec_command_quit(scan_state, active_branch);
381  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
382  status = exec_command_reset(scan_state, active_branch, query_buf);
383  else if (strcmp(cmd, "s") == 0)
384  status = exec_command_s(scan_state, active_branch);
385  else if (strcmp(cmd, "set") == 0)
386  status = exec_command_set(scan_state, active_branch);
387  else if (strcmp(cmd, "setenv") == 0)
388  status = exec_command_setenv(scan_state, active_branch, cmd);
389  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
390  status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
391  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
392  status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
393  else if (strcmp(cmd, "t") == 0)
394  status = exec_command_t(scan_state, active_branch);
395  else if (strcmp(cmd, "T") == 0)
396  status = exec_command_T(scan_state, active_branch);
397  else if (strcmp(cmd, "timing") == 0)
398  status = exec_command_timing(scan_state, active_branch);
399  else if (strcmp(cmd, "unset") == 0)
400  status = exec_command_unset(scan_state, active_branch, cmd);
401  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
402  status = exec_command_write(scan_state, active_branch, cmd,
403  query_buf, previous_buf);
404  else if (strcmp(cmd, "watch") == 0)
405  status = exec_command_watch(scan_state, active_branch,
406  query_buf, previous_buf);
407  else if (strcmp(cmd, "x") == 0)
408  status = exec_command_x(scan_state, active_branch);
409  else if (strcmp(cmd, "z") == 0)
410  status = exec_command_z(scan_state, active_branch);
411  else if (strcmp(cmd, "!") == 0)
412  status = exec_command_shell_escape(scan_state, active_branch);
413  else if (strcmp(cmd, "?") == 0)
414  status = exec_command_slash_command_help(scan_state, active_branch);
415  else
416  status = PSQL_CMD_UNKNOWN;
417 
418  /*
419  * All the commands that return PSQL_CMD_SEND want to execute previous_buf
420  * if query_buf is empty. For convenience we implement that here, not in
421  * the individual command subroutines.
422  */
423  if (status == PSQL_CMD_SEND)
424  (void) copy_previous_query(query_buf, previous_buf);
425 
426  return status;
427 }
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1865
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1215
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1597
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2557
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1760
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:2089
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:436
PsqlSettings pset
Definition: startup.c:32
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1547
static bool is_branching_command(const char *cmd)
Definition: command.c:2964
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1003
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1328
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2782
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1993
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2481
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2162
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1298
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:2019
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3026
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2737
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1356
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2676
bool cur_cmd_interactive
Definition: settings.h:107
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2760
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2328
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:599
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1093
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1684
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:677
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:488
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1518
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1825
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2275
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1638
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1501
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2525
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1260
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1578
enum _backslashResult backslashResult
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2248
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2587
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2216
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2715
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:541
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:665
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1894
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2503
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1970
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:643
#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:2230
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1484
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:455
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2376
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:701

◆ exec_command_a()

static backslashResult exec_command_a ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 436 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().

437 {
438  bool success = true;
439 
440  if (active_branch)
441  {
443  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
444  else
445  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
446  }
447 
448  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
449 }
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:4150
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 455 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().

456 {
457  bool success = true;
458 
459  if (active_branch)
460  {
461  char *opt = psql_scan_slash_option(scan_state,
462  OT_NORMAL, NULL, true);
463 
464  success = do_pset("title", opt, &pset.popt, pset.quiet);
465  free(opt);
466  }
467  else
468  ignore_slash_options(scan_state);
469 
470  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
471 }
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:4150
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2917
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 541 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().

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

489 {
490  bool success = true;
491 
492  if (active_branch)
493  {
494  static const char prefix[] = "-reuse-previous=";
495  char *opt1,
496  *opt2,
497  *opt3,
498  *opt4;
499  enum trivalue reuse_previous = TRI_DEFAULT;
500 
501  opt1 = read_connect_arg(scan_state);
502  if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
503  {
504  bool on_off;
505 
506  success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
507  "-reuse-previous",
508  &on_off);
509  if (success)
510  {
511  reuse_previous = on_off ? TRI_YES : TRI_NO;
512  free(opt1);
513  opt1 = read_connect_arg(scan_state);
514  }
515  }
516 
517  if (success) /* give up if reuse_previous was invalid */
518  {
519  opt2 = read_connect_arg(scan_state);
520  opt3 = read_connect_arg(scan_state);
521  opt4 = read_connect_arg(scan_state);
522 
523  success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
524 
525  free(opt2);
526  free(opt3);
527  free(opt4);
528  }
529  free(opt1);
530  }
531  else
532  ignore_slash_options(scan_state);
533 
534  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
535 }
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:2814
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:2917
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:3083

◆ exec_command_conninfo()

static backslashResult exec_command_conninfo ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 599 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().

600 {
601  if (active_branch)
602  {
603  char *db = PQdb(pset.db);
604 
605  if (db == NULL)
606  printf(_("You are currently not connected to a database.\n"));
607  else
608  {
609  char *host = PQhost(pset.db);
610  char *hostaddr = PQhostaddr(pset.db);
611 
612  if (is_unixsock_path(host))
613  {
614  /* hostaddr overrides host */
615  if (hostaddr && *hostaddr)
616  printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
617  db, PQuser(pset.db), hostaddr, PQport(pset.db));
618  else
619  printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
620  db, PQuser(pset.db), host, PQport(pset.db));
621  }
622  else
623  {
624  if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
625  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
626  db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
627  else
628  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
629  db, PQuser(pset.db), host, PQport(pset.db));
630  }
631  printSSLInfo();
632  printGSSInfo();
633  }
634  }
635 
636  return PSQL_CMD_SKIP_LINE;
637 }
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:6650
#define printf(...)
Definition: port.h:222
static void printGSSInfo(void)
Definition: command.c:3619
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6589
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:6637
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6614
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6581
static void printSSLInfo(void)
Definition: command.c:3591
#define _(x)
Definition: elog.c:89

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 643 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().

644 {
645  bool success = true;
646 
647  if (active_branch)
648  {
649  char *opt = psql_scan_slash_option(scan_state,
650  OT_WHOLE_LINE, NULL, false);
651 
652  success = do_copy(opt);
653  free(opt);
654  }
655  else
656  ignore_slash_whole_line(scan_state);
657 
658  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
659 }
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:2951

◆ exec_command_copyright()

static backslashResult exec_command_copyright ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 665 of file command.c.

References print_copyright(), and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

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

◆ exec_command_crosstabview()

static backslashResult exec_command_crosstabview ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 677 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().

678 {
680 
681  if (active_branch)
682  {
683  int i;
684 
685  for (i = 0; i < lengthof(pset.ctv_args); i++)
686  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
687  OT_NORMAL, NULL, true);
688  pset.crosstab_flag = true;
689  status = PSQL_CMD_SEND;
690  }
691  else
692  ignore_slash_options(scan_state);
693 
694  return status;
695 }
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:2917
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 701 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().

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

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

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

Referenced by exec_command_d().

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

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

◆ exec_command_edit()

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

Definition at line 1003 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().

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

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

◆ exec_command_elif()

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

Definition at line 1684 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().

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

1762 {
1763  bool success = true;
1764 
1765  switch (conditional_stack_peek(cstack))
1766  {
1767  case IFSTATE_TRUE:
1768 
1769  /*
1770  * Just finished active branch of this \if block. Update saved
1771  * state so we will keep whatever data was put in query_buf by the
1772  * active branch.
1773  */
1774  save_query_text_state(scan_state, cstack, query_buf);
1775 
1776  /* Now skip the \else branch */
1778  break;
1779  case IFSTATE_FALSE:
1780 
1781  /*
1782  * Discard any query text added by the just-skipped branch.
1783  */
1784  discard_query_text(scan_state, cstack, query_buf);
1785 
1786  /*
1787  * We've not found any true \if or \elif expression, so execute
1788  * the \else branch.
1789  */
1791  break;
1792  case IFSTATE_IGNORED:
1793 
1794  /*
1795  * Discard any query text added by the just-skipped branch.
1796  */
1797  discard_query_text(scan_state, cstack, query_buf);
1798 
1799  /*
1800  * Either we previously processed the active branch of this \if,
1801  * or the whole \if block is being skipped. Either way, skip the
1802  * \else branch.
1803  */
1805  break;
1806  case IFSTATE_ELSE_TRUE:
1807  case IFSTATE_ELSE_FALSE:
1808  pg_log_error("\\else: cannot occur after \\else");
1809  success = false;
1810  break;
1811  case IFSTATE_NONE:
1812  /* no \if to else from */
1813  pg_log_error("\\else: no matching \\if");
1814  success = false;
1815  break;
1816  }
1817 
1818  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1819 }
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2980
#define pg_log_error(...)
Definition: logging.h:80
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3000
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 1260 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().

1261 {
1262  if (active_branch)
1263  {
1264  char *encoding = psql_scan_slash_option(scan_state,
1265  OT_NORMAL, NULL, false);
1266 
1267  if (!encoding)
1268  {
1269  /* show encoding */
1271  }
1272  else
1273  {
1274  /* set encoding */
1275  if (PQsetClientEncoding(pset.db, encoding) == -1)
1276  pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1277  else
1278  {
1279  /* save encoding info into psql internal data */
1282  SetVariable(pset.vars, "ENCODING",
1284  }
1285  free(encoding);
1286  }
1287  }
1288  else
1289  ignore_slash_options(scan_state);
1290 
1291  return PSQL_CMD_SKIP_LINE;
1292 }
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:6804
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:6812
#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:2917
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 1825 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().

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

1299 {
1300  if (active_branch)
1301  {
1302  if (pset.last_error_result)
1303  {
1304  char *msg;
1305 
1309  if (msg)
1310  {
1311  pg_log_error("%s", msg);
1312  PQfreemem(msg);
1313  }
1314  else
1315  puts(_("out of memory"));
1316  }
1317  else
1318  puts(_("There is no previous error."));
1319  }
1320 
1321  return PSQL_CMD_SKIP_LINE;
1322 }
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:3121
PGresult * last_error_result
Definition: settings.h:89
#define _(x)
Definition: elog.c:89
void PQfreemem(void *ptr)
Definition: fe-exec.c:3715

◆ exec_command_f()

static backslashResult exec_command_f ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1328 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().

1329 {
1330  bool success = true;
1331 
1332  if (active_branch)
1333  {
1334  char *fname = psql_scan_slash_option(scan_state,
1335  OT_NORMAL, NULL, false);
1336 
1337  success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1338  free(fname);
1339  }
1340  else
1341  ignore_slash_options(scan_state);
1342 
1343  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1344 }
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:4150
#define free(a)
Definition: header.h:65
printQueryOpt popt
Definition: settings.h:91
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2917
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 1356 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().

1357 {
1359  char *fname;
1360 
1361  /*
1362  * Because the option processing for this is fairly complicated, we do it
1363  * and then decide whether the branch is active.
1364  */
1365  fname = psql_scan_slash_option(scan_state,
1366  OT_FILEPIPE, NULL, false);
1367 
1368  if (fname && fname[0] == '(')
1369  {
1370  /* Consume pset options through trailing ')' ... */
1371  status = process_command_g_options(fname + 1, scan_state,
1372  active_branch, cmd);
1373  free(fname);
1374  /* ... and again attempt to scan the filename. */
1375  fname = psql_scan_slash_option(scan_state,
1376  OT_FILEPIPE, NULL, false);
1377  }
1378 
1379  if (status == PSQL_CMD_SKIP_LINE && active_branch)
1380  {
1381  if (!fname)
1382  pset.gfname = NULL;
1383  else
1384  {
1385  expand_tilde(&fname);
1386  pset.gfname = pg_strdup(fname);
1387  }
1388  if (strcmp(cmd, "gx") == 0)
1389  {
1390  /* save settings if not done already, then force expanded=on */
1391  if (pset.gsavepopt == NULL)
1393  pset.popt.topt.expanded = 1;
1394  }
1395  status = PSQL_CMD_SEND;
1396  }
1397 
1398  free(fname);
1399 
1400  return status;
1401 }
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:4663
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1409
unsigned short int expanded
Definition: print.h:102
void expand_tilde(char **filename)
Definition: common.c:2220
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 1484 of file command.c.

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

Referenced by exec_command().

1485 {
1487 
1488  if (active_branch)
1489  {
1490  pset.gdesc_flag = true;
1491  status = PSQL_CMD_SEND;
1492  }
1493 
1494  return status;
1495 }
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 1501 of file command.c.

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

Referenced by exec_command().

1502 {
1504 
1505  if (active_branch)
1506  {
1507  pset.gexec_flag = true;
1508  status = PSQL_CMD_SEND;
1509  }
1510 
1511  return status;
1512 }
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 1518 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().

1519 {
1521 
1522  if (active_branch)
1523  {
1524  char *prefix = psql_scan_slash_option(scan_state,
1525  OT_NORMAL, NULL, false);
1526 
1527  if (prefix)
1528  pset.gset_prefix = prefix;
1529  else
1530  {
1531  /* we must set a non-NULL prefix to trigger storing */
1532  pset.gset_prefix = pg_strdup("");
1533  }
1534  /* gset_prefix is freed later */
1535  status = PSQL_CMD_SEND;
1536  }
1537  else
1538  ignore_slash_options(scan_state);
1539 
1540  return status;
1541 }
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:2917
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 1547 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().

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

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1578 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().

1579 {
1580  bool success = true;
1581 
1582  if (active_branch)
1583  {
1584  if (pset.popt.topt.format != PRINT_HTML)
1585  success = do_pset("format", "html", &pset.popt, pset.quiet);
1586  else
1587  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1588  }
1589 
1590  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1591 }
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:4150
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 1638 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().

1640 {
1641  if (conditional_active(cstack))
1642  {
1643  /*
1644  * First, push a new active stack entry; this ensures that the lexer
1645  * will perform variable substitution and backtick evaluation while
1646  * scanning the expression. (That should happen anyway, since we know
1647  * we're in an active outer branch, but let's be sure.)
1648  */
1650 
1651  /* Remember current query state in case we need to restore later */
1652  save_query_text_state(scan_state, cstack, query_buf);
1653 
1654  /*
1655  * Evaluate the expression; if it's false, change to inactive state.
1656  */
1657  if (!is_true_boolean_expression(scan_state, "\\if expression"))
1659  }
1660  else
1661  {
1662  /*
1663  * We're within an inactive outer branch, so this entire \if block
1664  * will be ignored. We don't want to evaluate the expression, so push
1665  * the "ignored" stack state before scanning it.
1666  */
1668 
1669  /* Remember current query state in case we need to restore later */
1670  save_query_text_state(scan_state, cstack, query_buf);
1671 
1672  ignore_boolean_expression(scan_state);
1673  }
1674 
1675  return PSQL_CMD_SKIP_LINE;
1676 }
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:2901
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:2980
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:2884
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 1597 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().

1598 {
1599  bool success = true;
1600 
1601  if (active_branch)
1602  {
1603  char *fname = psql_scan_slash_option(scan_state,
1604  OT_NORMAL, NULL, true);
1605 
1606  if (!fname)
1607  {
1608  pg_log_error("\\%s: missing required argument", cmd);
1609  success = false;
1610  }
1611  else
1612  {
1613  bool include_relative;
1614 
1615  include_relative = (strcmp(cmd, "ir") == 0
1616  || strcmp(cmd, "include_relative") == 0);
1617  expand_tilde(&fname);
1618  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1619  free(fname);
1620  }
1621  }
1622  else
1623  ignore_slash_options(scan_state);
1624 
1625  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1626 }
#define EXIT_SUCCESS
Definition: settings.h:158
#define pg_log_error(...)
Definition: logging.h:80
void expand_tilde(char **filename)
Definition: common.c:2220
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:3997
#define free(a)
Definition: header.h:65
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2917
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 1865 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().

1866 {
1867  bool success = true;
1868 
1869  if (active_branch)
1870  {
1871  char *pattern;
1872  bool show_verbose;
1873 
1874  pattern = psql_scan_slash_option(scan_state,
1875  OT_NORMAL, NULL, true);
1876 
1877  show_verbose = strchr(cmd, '+') ? true : false;
1878 
1879  success = listAllDbs(pattern, show_verbose);
1880 
1881  if (pattern)
1882  free(pattern);
1883  }
1884  else
1885  ignore_slash_options(scan_state);
1886 
1887  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1888 }
#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:2917
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 1894 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().

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

1971 {
1972  bool success = true;
1973 
1974  if (active_branch)
1975  {
1976  char *fname = psql_scan_slash_option(scan_state,
1977  OT_FILEPIPE, NULL, true);
1978 
1979  expand_tilde(&fname);
1980  success = setQFout(fname);
1981  free(fname);
1982  }
1983  else
1984  ignore_slash_filepipe(scan_state);
1985 
1986  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1987 }
void expand_tilde(char **filename)
Definition: common.c:2220
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:2934
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 2019 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().

2020 {
2021  bool success = true;
2022 
2023  if (active_branch)
2024  {
2025  char *opt0 = psql_scan_slash_option(scan_state,
2026  OT_SQLID, NULL, true);
2027  char *pw1;
2028  char *pw2;
2029 
2030  pw1 = simple_prompt("Enter new password: ", false);
2031  pw2 = simple_prompt("Enter it again: ", false);
2032 
2033  if (strcmp(pw1, pw2) != 0)
2034  {
2035  pg_log_error("Passwords didn't match.");
2036  success = false;
2037  }
2038  else
2039  {
2040  char *user;
2041  char *encrypted_password;
2042 
2043  if (opt0)
2044  user = opt0;
2045  else
2046  user = PQuser(pset.db);
2047 
2048  encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
2049 
2050  if (!encrypted_password)
2051  {
2053  success = false;
2054  }
2055  else
2056  {
2058  PGresult *res;
2059 
2060  initPQExpBuffer(&buf);
2061  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
2062  fmtId(user));
2063  appendStringLiteralConn(&buf, encrypted_password, pset.db);
2064  res = PSQLexec(buf.data);
2065  termPQExpBuffer(&buf);
2066  if (!res)
2067  success = false;
2068  else
2069  PQclear(res);
2070  PQfreemem(encrypted_password);
2071  }
2072  }
2073 
2074  if (opt0)
2075  free(opt0);
2076  free(pw1);
2077  free(pw2);
2078  }
2079  else
2080  ignore_slash_options(scan_state);
2081 
2082  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2083 }
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
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:6589
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:680
#define free(a)
Definition: header.h:65
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1192
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:2917
static bool success
Definition: initdb.c:165
void PQfreemem(void *ptr)
Definition: fe-exec.c:3715
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 1993 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().

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

2091 {
2092  bool success = true;
2093 
2094  if (active_branch)
2095  {
2096  char *opt,
2097  *prompt_text = NULL;
2098  char *arg1,
2099  *arg2;
2100 
2101  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2102  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2103 
2104  if (!arg1)
2105  {
2106  pg_log_error("\\%s: missing required argument", cmd);
2107  success = false;
2108  }
2109  else
2110  {
2111  char *result;
2112 
2113  if (arg2)
2114  {
2115  prompt_text = arg1;
2116  opt = arg2;
2117  }
2118  else
2119  opt = arg1;
2120 
2121  if (!pset.inputfile)
2122  {
2123  result = simple_prompt(prompt_text, true);
2124  }
2125  else
2126  {
2127  if (prompt_text)
2128  {
2129  fputs(prompt_text, stdout);
2130  fflush(stdout);
2131  }
2132  result = gets_fromFile(stdin);
2133  if (!result)
2134  {
2135  pg_log_error("\\%s: could not read value for variable",
2136  cmd);
2137  success = false;
2138  }
2139  }
2140 
2141  if (result &&
2142  !SetVariable(pset.vars, opt, result))
2143  success = false;
2144 
2145  if (result)
2146  free(result);
2147  if (prompt_text)
2148  free(prompt_text);
2149  free(opt);
2150  }
2151  }
2152  else
2153  ignore_slash_options(scan_state);
2154 
2155  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2156 }
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:2917
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 2162 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().

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

References PSQL_CMD_SKIP_LINE, PSQL_CMD_TERMINATE, and status().

Referenced by exec_command().

2217 {
2219 
2220  if (active_branch)
2221  status = PSQL_CMD_TERMINATE;
2222 
2223  return status;
2224 }
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 2230 of file command.c.

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

Referenced by exec_command().

2232 {
2233  if (active_branch)
2234  {
2235  resetPQExpBuffer(query_buf);
2236  psql_scan_reset(scan_state);
2237  if (!pset.quiet)
2238  puts(_("Query buffer reset (cleared)."));
2239  }
2240 
2241  return PSQL_CMD_SKIP_LINE;
2242 }
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 2248 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().

2249 {
2250  bool success = true;
2251 
2252  if (active_branch)
2253  {
2254  char *fname = psql_scan_slash_option(scan_state,
2255  OT_NORMAL, NULL, true);
2256 
2257  expand_tilde(&fname);
2258  success = printHistory(fname, pset.popt.topt.pager);
2259  if (success && !pset.quiet && fname)
2260  printf(_("Wrote history to file \"%s\".\n"), fname);
2261  if (!fname)
2262  putchar('\n');
2263  free(fname);
2264  }
2265  else
2266  ignore_slash_options(scan_state);
2267 
2268  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2269 }
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:2220
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:2917
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 2275 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().

2276 {
2277  bool success = true;
2278 
2279  if (active_branch)
2280  {
2281  char *opt0 = psql_scan_slash_option(scan_state,
2282  OT_NORMAL, NULL, false);
2283 
2284  if (!opt0)
2285  {
2286  /* list all variables */
2288  success = true;
2289  }
2290  else
2291  {
2292  /*
2293  * Set variable to the concatenation of the arguments.
2294  */
2295  char *newval;
2296  char *opt;
2297 
2298  opt = psql_scan_slash_option(scan_state,
2299  OT_NORMAL, NULL, false);
2300  newval = pg_strdup(opt ? opt : "");
2301  free(opt);
2302 
2303  while ((opt = psql_scan_slash_option(scan_state,
2304  OT_NORMAL, NULL, false)))
2305  {
2306  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2307  strcat(newval, opt);
2308  free(opt);
2309  }
2310 
2311  if (!SetVariable(pset.vars, opt0, newval))
2312  success = false;
2313 
2314  free(newval);
2315  }
2316  free(opt0);
2317  }
2318  else
2319  ignore_slash_options(scan_state);
2320 
2321  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2322 }
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:2917
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 2328 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().

2330 {
2331  bool success = true;
2332 
2333  if (active_branch)
2334  {
2335  char *envvar = psql_scan_slash_option(scan_state,
2336  OT_NORMAL, NULL, false);
2337  char *envval = psql_scan_slash_option(scan_state,
2338  OT_NORMAL, NULL, false);
2339 
2340  if (!envvar)
2341  {
2342  pg_log_error("\\%s: missing required argument", cmd);
2343  success = false;
2344  }
2345  else if (strchr(envvar, '=') != NULL)
2346  {
2347  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2348  cmd);
2349  success = false;
2350  }
2351  else if (!envval)
2352  {
2353  /* No argument - unset the environment variable */
2354  unsetenv(envvar);
2355  success = true;
2356  }
2357  else
2358  {
2359  /* Set variable to the value of the next argument */
2360  setenv(envvar, envval, 1);
2361  success = true;
2362  }
2363  free(envvar);
2364  free(envval);
2365  }
2366  else
2367  ignore_slash_options(scan_state);
2368 
2369  return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2370 }
#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
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:2917
static bool success
Definition: initdb.c:165
#define unsetenv(x)
Definition: win32_port.h:498

◆ exec_command_sf_sv()

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

Definition at line 2376 of file command.c.

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

Referenced by exec_command().

2378 {
2380 
2381  if (active_branch)
2382  {
2383  bool show_linenumbers = (strchr(cmd, '+') != NULL);
2384  PQExpBuffer buf;
2385  char *obj_desc;
2386  Oid obj_oid = InvalidOid;
2388 
2389  buf = createPQExpBuffer();
2390  obj_desc = psql_scan_slash_option(scan_state,
2391  OT_WHOLE_LINE, NULL, true);
2392  if (pset.sversion < (is_func ? 80400 : 70400))
2393  {
2394  char sverbuf[32];
2395 
2397  sverbuf, sizeof(sverbuf));
2398  if (is_func)
2399  pg_log_error("The server (version %s) does not support showing function source.",
2400  sverbuf);
2401  else
2402  pg_log_error("The server (version %s) does not support showing view definitions.",
2403  sverbuf);
2404  status = PSQL_CMD_ERROR;
2405  }
2406  else if (!obj_desc)
2407  {
2408  if (is_func)
2409  pg_log_error("function name is required");
2410  else
2411  pg_log_error("view name is required");
2412  status = PSQL_CMD_ERROR;
2413  }
2414  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2415  {
2416  /* error already reported */
2417  status = PSQL_CMD_ERROR;
2418  }
2419  else if (!get_create_object_cmd(eot, obj_oid, buf))
2420  {
2421  /* error already reported */
2422  status = PSQL_CMD_ERROR;
2423  }
2424  else
2425  {
2426  FILE *output;
2427  bool is_pager;
2428 
2429  /* Select output stream: stdout, pager, or file */
2430  if (pset.queryFout == stdout)
2431  {
2432  /* count lines in function to see if pager is needed */
2433  int lineno = count_lines_in_buf(buf);
2434 
2435  output = PageOutput(lineno, &(pset.popt.topt));
2436  is_pager = true;
2437  }
2438  else
2439  {
2440  /* use previously set output file, without pager */
2441  output = pset.queryFout;
2442  is_pager = false;
2443  }
2444 
2445  if (show_linenumbers)
2446  {
2447  /*
2448  * For functions, lineno "1" should correspond to the first
2449  * line of the function body. We expect that
2450  * pg_get_functiondef() will emit that on a line beginning
2451  * with "AS ", and that there can be no such line before the
2452  * real start of the function body.
2453  */
2454  print_with_linenumbers(output, buf->data,
2455  is_func ? "AS " : NULL);
2456  }
2457  else
2458  {
2459  /* just send the definition to output */
2460  fputs(buf->data, output);
2461  }
2462 
2463