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_bind (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_getenv (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
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, const char *cmd)
 
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 void wait_until_connected (PGconn *conn)
 
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, int iter, int min_rows)
 
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, bool is_func)
 
static void minimal_error_message (PGresult *res)
 
static void printSSLInfo (void)
 
static void printGSSInfo (void)
 
static bool printPsetInfo (const char *param, printQueryOpt *popt)
 
static char * pset_value_string (const char *param, printQueryOpt *popt)
 
backslashResult HandleSlashCmds (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static char * prompt_for_password (const char *username, bool *canceled)
 
static bool param_is_newly_set (const char *old_val, const char *new_val)
 
void connection_warnings (bool in_startup)
 
void SyncVariables (void)
 
void UnsyncVariables (void)
 
static bool editFile (const char *fname, int lineno)
 
int process_file (char *filename, bool use_relative_path)
 
static const char * _align2string (enum printFormat in)
 
static bool set_unicode_line_style (const char *value, size_t vallen, unicode_linestyle *linestyle)
 
static const char * _unicode_linestyle2string (int linestyle)
 
bool do_pset (const char *param, const char *value, printQueryOpt *popt, bool quiet)
 
printQueryOptsavePsetInfo (const printQueryOpt *popt)
 
void restorePsetInfo (printQueryOpt *popt, printQueryOpt *save)
 
static const char * pset_bool_string (bool val)
 
static char * pset_quoted_string (const char *str)
 
static bool echo_hidden_command (const char *query)
 

Macro Definition Documentation

◆ DEFAULT_SHELL

#define DEFAULT_SHELL   "/bin/sh"

Definition at line 5179 of file command.c.

Typedef Documentation

◆ EditableObjectType

Enumeration Type Documentation

◆ EditableObjectType

Enumerator
EditableFunction 
EditableView 

Definition at line 53 of file command.c.

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

Function Documentation

◆ _align2string()

static const char* _align2string ( enum printFormat  in)
static

Definition at line 4354 of file command.c.

4355 {
4356  switch (in)
4357  {
4358  case PRINT_NOTHING:
4359  return "nothing";
4360  break;
4361  case PRINT_ALIGNED:
4362  return "aligned";
4363  break;
4364  case PRINT_ASCIIDOC:
4365  return "asciidoc";
4366  break;
4367  case PRINT_CSV:
4368  return "csv";
4369  break;
4370  case PRINT_HTML:
4371  return "html";
4372  break;
4373  case PRINT_LATEX:
4374  return "latex";
4375  break;
4376  case PRINT_LATEX_LONGTABLE:
4377  return "latex-longtable";
4378  break;
4379  case PRINT_TROFF_MS:
4380  return "troff-ms";
4381  break;
4382  case PRINT_UNALIGNED:
4383  return "unaligned";
4384  break;
4385  case PRINT_WRAPPED:
4386  return "wrapped";
4387  break;
4388  }
4389  return "unknown";
4390 }
@ PRINT_LATEX_LONGTABLE
Definition: print.h:36
@ PRINT_CSV
Definition: print.h:33
@ PRINT_UNALIGNED
Definition: print.h:38
@ PRINT_ALIGNED
Definition: print.h:31
@ PRINT_TROFF_MS
Definition: print.h:37
@ PRINT_ASCIIDOC
Definition: print.h:32
@ PRINT_NOTHING
Definition: print.h:30
@ PRINT_LATEX
Definition: print.h:35
@ PRINT_HTML
Definition: print.h:34
@ PRINT_WRAPPED
Definition: print.h:39

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

Referenced by printPsetInfo(), and pset_value_string().

◆ _unicode_linestyle2string()

static const char* _unicode_linestyle2string ( int  linestyle)
static

Definition at line 4410 of file command.c.

4411 {
4412  switch (linestyle)
4413  {
4415  return "single";
4416  break;
4418  return "double";
4419  break;
4420  }
4421  return "unknown";
4422 }
@ UNICODE_LINESTYLE_SINGLE
Definition: print.h:101
@ UNICODE_LINESTYLE_DOUBLE
Definition: print.h:102

References UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by printPsetInfo(), and pset_value_string().

◆ connection_warnings()

void connection_warnings ( bool  in_startup)

Definition at line 3821 of file command.c.

3822 {
3823  if (!pset.quiet && !pset.notty)
3824  {
3825  int client_ver = PG_VERSION_NUM;
3826  char cverbuf[32];
3827  char sverbuf[32];
3828 
3829  if (pset.sversion != client_ver)
3830  {
3831  const char *server_version;
3832 
3833  /* Try to get full text form, might include "devel" etc */
3834  server_version = PQparameterStatus(pset.db, "server_version");
3835  /* Otherwise fall back on pset.sversion */
3836  if (!server_version)
3837  {
3839  sverbuf, sizeof(sverbuf));
3840  server_version = sverbuf;
3841  }
3842 
3843  printf(_("%s (%s, server %s)\n"),
3844  pset.progname, PG_VERSION, server_version);
3845  }
3846  /* For version match, only print psql banner on startup. */
3847  else if (in_startup)
3848  printf("%s (%s)\n", pset.progname, PG_VERSION);
3849 
3850  /*
3851  * Warn if server's major version is newer than ours, or if server
3852  * predates our support cutoff (currently 9.2).
3853  */
3854  if (pset.sversion / 100 > client_ver / 100 ||
3855  pset.sversion < 90200)
3856  printf(_("WARNING: %s major version %s, server major version %s.\n"
3857  " Some psql features might not work.\n"),
3858  pset.progname,
3859  formatPGVersionNumber(client_ver, false,
3860  cverbuf, sizeof(cverbuf)),
3862  sverbuf, sizeof(sverbuf)));
3863 
3864 #ifdef WIN32
3865  if (in_startup)
3866  checkWin32Codepage();
3867 #endif
3868  printSSLInfo();
3869  printGSSInfo();
3870  }
3871 }
static void printSSLInfo(void)
Definition: command.c:3880
static void printGSSInfo(void)
Definition: command.c:3908
#define _(x)
Definition: elog.c:90
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7112
static int server_version
Definition: pg_dumpall.c:110
#define printf(...)
Definition: port.h:244
PsqlSettings pset
Definition: startup.c:32
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177
PGconn * db
Definition: settings.h:82
const char * progname
Definition: settings.h:113

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

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

◆ copy_previous_query()

static bool copy_previous_query ( PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 3226 of file command.c.

3227 {
3228  if (query_buf && query_buf->len == 0)
3229  {
3230  appendPQExpBufferStr(query_buf, previous_buf->data);
3231  return true;
3232  }
3233  return false;
3234 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367

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

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

◆ count_lines_in_buf()

static int count_lines_in_buf ( PQExpBuffer  buf)
static

Definition at line 5786 of file command.c.

5787 {
5788  int lineno = 0;
5789  const char *lines = buf->data;
5790 
5791  while (*lines != '\0')
5792  {
5793  lineno++;
5794  /* find start of next line */
5795  lines = strchr(lines, '\n');
5796  if (!lines)
5797  break;
5798  lines++;
5799  }
5800 
5801  return lineno;
5802 }
static char * buf
Definition: pg_test_fsync.c:73

References buf.

Referenced by exec_command_sf_sv().

◆ discard_query_text()

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

Definition at line 3200 of file command.c.

3202 {
3203  if (query_buf)
3204  {
3205  int new_len = conditional_stack_get_query_len(cstack);
3206 
3207  Assert(new_len >= 0 && new_len <= query_buf->len);
3208  query_buf->len = new_len;
3209  query_buf->data[new_len] = '\0';
3210  }
3211  psql_scan_set_paren_depth(scan_state,
3213 }
#define Assert(condition)
Definition: c.h:858
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:162
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:184
const void size_t len
void psql_scan_set_paren_depth(PsqlScanState state, int depth)

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

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

◆ do_connect()

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

Definition at line 3295 of file command.c.

3297 {
3298  PGconn *o_conn = pset.db,
3299  *n_conn = NULL;
3300  PQconninfoOption *cinfo;
3301  int nconnopts = 0;
3302  bool same_host = false;
3303  char *password = NULL;
3304  char *client_encoding;
3305  bool success = true;
3306  bool keep_password = true;
3307  bool has_connection_string;
3308  bool reuse_previous;
3309 
3310  has_connection_string = dbname ?
3312 
3313  /* Complain if we have additional arguments after a connection string. */
3314  if (has_connection_string && (user || host || port))
3315  {
3316  pg_log_error("Do not give user, host, or port separately when using a connection string");
3317  return false;
3318  }
3319 
3320  switch (reuse_previous_specification)
3321  {
3322  case TRI_YES:
3323  reuse_previous = true;
3324  break;
3325  case TRI_NO:
3326  reuse_previous = false;
3327  break;
3328  default:
3329  reuse_previous = !has_connection_string;
3330  break;
3331  }
3332 
3333  /*
3334  * If we intend to re-use connection parameters, collect them out of the
3335  * old connection, then replace individual values as necessary. (We may
3336  * need to resort to looking at pset.dead_conn, if the connection died
3337  * previously.) Otherwise, obtain a PQconninfoOption array containing
3338  * libpq's defaults, and modify that. Note this function assumes that
3339  * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3340  * containing the same options in the same order.
3341  */
3342  if (reuse_previous)
3343  {
3344  if (o_conn)
3345  cinfo = PQconninfo(o_conn);
3346  else if (pset.dead_conn)
3347  cinfo = PQconninfo(pset.dead_conn);
3348  else
3349  {
3350  /* This is reachable after a non-interactive \connect failure */
3351  pg_log_error("No database connection exists to re-use parameters from");
3352  return false;
3353  }
3354  }
3355  else
3356  cinfo = PQconndefaults();
3357 
3358  if (cinfo)
3359  {
3360  if (has_connection_string)
3361  {
3362  /* Parse the connstring and insert values into cinfo */
3363  PQconninfoOption *replcinfo;
3364  char *errmsg;
3365 
3366  replcinfo = PQconninfoParse(dbname, &errmsg);
3367  if (replcinfo)
3368  {
3369  PQconninfoOption *ci;
3370  PQconninfoOption *replci;
3371  bool have_password = false;
3372 
3373  for (ci = cinfo, replci = replcinfo;
3374  ci->keyword && replci->keyword;
3375  ci++, replci++)
3376  {
3377  Assert(strcmp(ci->keyword, replci->keyword) == 0);
3378  /* Insert value from connstring if one was provided */
3379  if (replci->val)
3380  {
3381  /*
3382  * We know that both val strings were allocated by
3383  * libpq, so the least messy way to avoid memory leaks
3384  * is to swap them.
3385  */
3386  char *swap = replci->val;
3387 
3388  replci->val = ci->val;
3389  ci->val = swap;
3390 
3391  /*
3392  * Check whether connstring provides options affecting
3393  * password re-use. While any change in user, host,
3394  * hostaddr, or port causes us to ignore the old
3395  * connection's password, we don't force that for
3396  * dbname, since passwords aren't database-specific.
3397  */
3398  if (replci->val == NULL ||
3399  strcmp(ci->val, replci->val) != 0)
3400  {
3401  if (strcmp(replci->keyword, "user") == 0 ||
3402  strcmp(replci->keyword, "host") == 0 ||
3403  strcmp(replci->keyword, "hostaddr") == 0 ||
3404  strcmp(replci->keyword, "port") == 0)
3405  keep_password = false;
3406  }
3407  /* Also note whether connstring contains a password. */
3408  if (strcmp(replci->keyword, "password") == 0)
3409  have_password = true;
3410  }
3411  else if (!reuse_previous)
3412  {
3413  /*
3414  * When we have a connstring and are not re-using
3415  * parameters, swap *all* entries, even those not set
3416  * by the connstring. This avoids absorbing
3417  * environment-dependent defaults from the result of
3418  * PQconndefaults(). We don't want to do that because
3419  * they'd override service-file entries if the
3420  * connstring specifies a service parameter, whereas
3421  * the priority should be the other way around. libpq
3422  * can certainly recompute any defaults we don't pass
3423  * here. (In this situation, it's a bit wasteful to
3424  * have called PQconndefaults() at all, but not doing
3425  * so would require yet another major code path here.)
3426  */
3427  replci->val = ci->val;
3428  ci->val = NULL;
3429  }
3430  }
3431  Assert(ci->keyword == NULL && replci->keyword == NULL);
3432 
3433  /* While here, determine how many option slots there are */
3434  nconnopts = ci - cinfo;
3435 
3436  PQconninfoFree(replcinfo);
3437 
3438  /*
3439  * If the connstring contains a password, tell the loop below
3440  * that we may use it, regardless of other settings (i.e.,
3441  * cinfo's password is no longer an "old" password).
3442  */
3443  if (have_password)
3444  keep_password = true;
3445 
3446  /* Don't let code below try to inject dbname into params. */
3447  dbname = NULL;
3448  }
3449  else
3450  {
3451  /* PQconninfoParse failed */
3452  if (errmsg)
3453  {
3454  pg_log_error("%s", errmsg);
3455  PQfreemem(errmsg);
3456  }
3457  else
3458  pg_log_error("out of memory");
3459  success = false;
3460  }
3461  }
3462  else
3463  {
3464  /*
3465  * If dbname isn't a connection string, then we'll inject it and
3466  * the other parameters into the keyword array below. (We can't
3467  * easily insert them into the cinfo array because of memory
3468  * management issues: PQconninfoFree would misbehave on Windows.)
3469  * However, to avoid dependencies on the order in which parameters
3470  * appear in the array, make a preliminary scan to set
3471  * keep_password and same_host correctly.
3472  *
3473  * While any change in user, host, or port causes us to ignore the
3474  * old connection's password, we don't force that for dbname,
3475  * since passwords aren't database-specific.
3476  */
3477  PQconninfoOption *ci;
3478 
3479  for (ci = cinfo; ci->keyword; ci++)
3480  {
3481  if (user && strcmp(ci->keyword, "user") == 0)
3482  {
3483  if (!(ci->val && strcmp(user, ci->val) == 0))
3484  keep_password = false;
3485  }
3486  else if (host && strcmp(ci->keyword, "host") == 0)
3487  {
3488  if (ci->val && strcmp(host, ci->val) == 0)
3489  same_host = true;
3490  else
3491  keep_password = false;
3492  }
3493  else if (port && strcmp(ci->keyword, "port") == 0)
3494  {
3495  if (!(ci->val && strcmp(port, ci->val) == 0))
3496  keep_password = false;
3497  }
3498  }
3499 
3500  /* While here, determine how many option slots there are */
3501  nconnopts = ci - cinfo;
3502  }
3503  }
3504  else
3505  {
3506  /* We failed to create the cinfo structure */
3507  pg_log_error("out of memory");
3508  success = false;
3509  }
3510 
3511  /*
3512  * If the user asked to be prompted for a password, ask for one now. If
3513  * not, use the password from the old connection, provided the username
3514  * etc have not changed. Otherwise, try to connect without a password
3515  * first, and then ask for a password if needed.
3516  *
3517  * XXX: this behavior leads to spurious connection attempts recorded in
3518  * the postmaster's log. But libpq offers no API that would let us obtain
3519  * a password and then continue with the first connection attempt.
3520  */
3521  if (pset.getPassword == TRI_YES && success)
3522  {
3523  bool canceled = false;
3524 
3525  /*
3526  * If a connstring or URI is provided, we don't know which username
3527  * will be used, since we haven't dug that out of the connstring.
3528  * Don't risk issuing a misleading prompt. As in startup.c, it does
3529  * not seem worth working harder, since this getPassword setting is
3530  * normally only used in noninteractive cases.
3531  */
3532  password = prompt_for_password(has_connection_string ? NULL : user,
3533  &canceled);
3534  success = !canceled;
3535  }
3536 
3537  /*
3538  * Consider whether to force client_encoding to "auto" (overriding
3539  * anything in the connection string). We do so if we have a terminal
3540  * connection and there is no PGCLIENTENCODING environment setting.
3541  */
3542  if (pset.notty || getenv("PGCLIENTENCODING"))
3543  client_encoding = NULL;
3544  else
3545  client_encoding = "auto";
3546 
3547  /* Loop till we have a connection or fail, which we might've already */
3548  while (success)
3549  {
3550  const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
3551  const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
3552  int paramnum = 0;
3553  PQconninfoOption *ci;
3554 
3555  /*
3556  * Copy non-default settings into the PQconnectdbParams parameter
3557  * arrays; but inject any values specified old-style, as well as any
3558  * interactively-obtained password, and a couple of fields we want to
3559  * set forcibly.
3560  *
3561  * If you change this code, see also the initial-connection code in
3562  * main().
3563  */
3564  for (ci = cinfo; ci->keyword; ci++)
3565  {
3566  keywords[paramnum] = ci->keyword;
3567 
3568  if (dbname && strcmp(ci->keyword, "dbname") == 0)
3569  values[paramnum++] = dbname;
3570  else if (user && strcmp(ci->keyword, "user") == 0)
3571  values[paramnum++] = user;
3572  else if (host && strcmp(ci->keyword, "host") == 0)
3573  values[paramnum++] = host;
3574  else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
3575  {
3576  /* If we're changing the host value, drop any old hostaddr */
3577  values[paramnum++] = NULL;
3578  }
3579  else if (port && strcmp(ci->keyword, "port") == 0)
3580  values[paramnum++] = port;
3581  /* If !keep_password, we unconditionally drop old password */
3582  else if ((password || !keep_password) &&
3583  strcmp(ci->keyword, "password") == 0)
3584  values[paramnum++] = password;
3585  else if (strcmp(ci->keyword, "fallback_application_name") == 0)
3586  values[paramnum++] = pset.progname;
3587  else if (client_encoding &&
3588  strcmp(ci->keyword, "client_encoding") == 0)
3589  values[paramnum++] = client_encoding;
3590  else if (ci->val)
3591  values[paramnum++] = ci->val;
3592  /* else, don't bother making libpq parse this keyword */
3593  }
3594  /* add array terminator */
3595  keywords[paramnum] = NULL;
3596  values[paramnum] = NULL;
3597 
3598  /* Note we do not want libpq to re-expand the dbname parameter */
3599  n_conn = PQconnectStartParams(keywords, values, false);
3600 
3601  pg_free(keywords);
3602  pg_free(values);
3603 
3604  wait_until_connected(n_conn);
3605  if (PQstatus(n_conn) == CONNECTION_OK)
3606  break;
3607 
3608  /*
3609  * Connection attempt failed; either retry the connection attempt with
3610  * a new password, or give up.
3611  */
3613  {
3614  bool canceled = false;
3615 
3616  /*
3617  * Prompt for password using the username we actually connected
3618  * with --- it might've come out of "dbname" rather than "user".
3619  */
3620  password = prompt_for_password(PQuser(n_conn), &canceled);
3621  PQfinish(n_conn);
3622  n_conn = NULL;
3623  success = !canceled;
3624  continue;
3625  }
3626 
3627  /*
3628  * We'll report the error below ... unless n_conn is NULL, indicating
3629  * that libpq didn't have enough memory to make a PGconn.
3630  */
3631  if (n_conn == NULL)
3632  pg_log_error("out of memory");
3633 
3634  success = false;
3635  } /* end retry loop */
3636 
3637  /* Release locally allocated data, whether we succeeded or not */
3638  pg_free(password);
3639  PQconninfoFree(cinfo);
3640 
3641  if (!success)
3642  {
3643  /*
3644  * Failed to connect to the database. In interactive mode, keep the
3645  * previous connection to the DB; in scripting mode, close our
3646  * previous connection as well.
3647  */
3649  {
3650  if (n_conn)
3651  {
3652  pg_log_info("%s", PQerrorMessage(n_conn));
3653  PQfinish(n_conn);
3654  }
3655 
3656  /* pset.db is left unmodified */
3657  if (o_conn)
3658  pg_log_info("Previous connection kept");
3659  }
3660  else
3661  {
3662  if (n_conn)
3663  {
3664  pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
3665  PQfinish(n_conn);
3666  }
3667 
3668  if (o_conn)
3669  {
3670  /*
3671  * Transition to having no connection.
3672  *
3673  * Unlike CheckConnection(), we close the old connection
3674  * immediately to prevent its parameters from being re-used.
3675  * This is so that a script cannot accidentally reuse
3676  * parameters it did not expect to. Otherwise, the state
3677  * cleanup should be the same as in CheckConnection().
3678  */
3679  PQfinish(o_conn);
3680  pset.db = NULL;
3681  ResetCancelConn();
3682  UnsyncVariables();
3683  }
3684 
3685  /* On the same reasoning, release any dead_conn to prevent reuse */
3686  if (pset.dead_conn)
3687  {
3689  pset.dead_conn = NULL;
3690  }
3691  }
3692 
3693  return false;
3694  }
3695 
3696  /*
3697  * Replace the old connection with the new one, and update
3698  * connection-dependent variables. Keep the resynchronization logic in
3699  * sync with CheckConnection().
3700  */
3701  PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
3702  pset.db = n_conn;
3703  SyncVariables();
3704  connection_warnings(false); /* Must be after SyncVariables */
3705 
3706  /* Tell the user about the new connection */
3707  if (!pset.quiet)
3708  {
3709  if (!o_conn ||
3710  param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
3711  param_is_newly_set(PQport(o_conn), PQport(pset.db)))
3712  {
3713  char *connhost = PQhost(pset.db);
3714  char *hostaddr = PQhostaddr(pset.db);
3715 
3716  if (is_unixsock_path(connhost))
3717  {
3718  /* hostaddr overrides connhost */
3719  if (hostaddr && *hostaddr)
3720  printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
3721  PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
3722  else
3723  printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
3724  PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
3725  }
3726  else
3727  {
3728  if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
3729  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
3730  PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
3731  else
3732  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
3733  PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
3734  }
3735  }
3736  else
3737  printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
3738  PQdb(pset.db), PQuser(pset.db));
3739  }
3740 
3741  /* Drop no-longer-needed connection(s) */
3742  if (o_conn)
3743  PQfinish(o_conn);
3744  if (pset.dead_conn)
3745  {
3747  pset.dead_conn = NULL;
3748  }
3749 
3750  return true;
3751 }
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:267
bool recognized_connection_string(const char *connstr)
Definition: common.c:2265
static Datum values[MAXATTR]
Definition: bootstrap.c:152
void ResetCancelConn(void)
Definition: cancel.c:107
static char * prompt_for_password(const char *username, bool *canceled)
Definition: command.c:3244
static bool param_is_newly_set(const char *old_val, const char *new_val)
Definition: command.c:3272
void UnsyncVariables(void)
Definition: command.c:3990
static void wait_until_connected(PGconn *conn)
Definition: command.c:3759
void SyncVariables(void)
Definition: command.c:3949
void connection_warnings(bool in_startup)
Definition: command.c:3821
int errmsg(const char *fmt,...)
Definition: elog.c:1072
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5728
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:791
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:7026
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6993
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1863
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:7049
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6980
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:6936
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7198
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7147
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7094
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4868
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:7001
char * PQport(const PGconn *conn)
Definition: fe-connect.c:7062
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7326
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
void pg_free(void *ptr)
Definition: fe_memutils.c:105
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static bool success
Definition: initdb.c:186
return false
Definition: isn.c:131
@ CONNECTION_OK
Definition: libpq-fe.h:61
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_info(...)
Definition: logging.h:124
static char * user
Definition: pg_regress.c:120
static int port
Definition: pg_regress.c:116
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:67
static char * password
Definition: streamutil.c:54
char * dbname
Definition: streamutil.c:52
PGconn * dead_conn
Definition: settings.h:129
enum trivalue getPassword
Definition: settings.h:108
bool cur_cmd_interactive
Definition: settings.h:111
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37

References _, Assert, CONNECTION_OK, connection_warnings(), _psqlSettings::cur_cmd_interactive, _psqlSettings::db, dbname, _psqlSettings::dead_conn, errmsg(), _psqlSettings::getPassword, is_unixsock_path(), _PQconninfoOption::keyword, NoticeProcessor(), _psqlSettings::notty, param_is_newly_set(), password, pg_free(), pg_log_error, pg_log_info, pg_malloc(), port, PQconndefaults(), PQconnectionNeedsPassword(), PQconnectStartParams(), 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, values, and wait_until_connected().

Referenced by exec_command_connect().

◆ do_edit()

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

Definition at line 4092 of file command.c.

4094 {
4095  char fnametmp[MAXPGPATH];
4096  FILE *stream = NULL;
4097  const char *fname;
4098  bool error = false;
4099  int fd;
4100  struct stat before,
4101  after;
4102 
4103  if (filename_arg)
4104  fname = filename_arg;
4105  else
4106  {
4107  /* make a temp file to edit */
4108 #ifndef WIN32
4109  const char *tmpdir = getenv("TMPDIR");
4110 
4111  if (!tmpdir)
4112  tmpdir = "/tmp";
4113 #else
4114  char tmpdir[MAXPGPATH];
4115  int ret;
4116 
4117  ret = GetTempPath(MAXPGPATH, tmpdir);
4118  if (ret == 0 || ret > MAXPGPATH)
4119  {
4120  pg_log_error("could not locate temporary directory: %s",
4121  !ret ? strerror(errno) : "");
4122  return false;
4123  }
4124 #endif
4125 
4126  /*
4127  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4128  * current directory to the supplied path unless we use only
4129  * backslashes, so we do that.
4130  */
4131 #ifndef WIN32
4132  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4133  "/", (int) getpid());
4134 #else
4135  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4136  "" /* trailing separator already present */ , (int) getpid());
4137 #endif
4138 
4139  fname = (const char *) fnametmp;
4140 
4141  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4142  if (fd != -1)
4143  stream = fdopen(fd, "w");
4144 
4145  if (fd == -1 || !stream)
4146  {
4147  pg_log_error("could not open temporary file \"%s\": %m", fname);
4148  error = true;
4149  }
4150  else
4151  {
4152  unsigned int ql = query_buf->len;
4153 
4154  /* force newline-termination of what we send to editor */
4155  if (ql > 0 && query_buf->data[ql - 1] != '\n')
4156  {
4157  appendPQExpBufferChar(query_buf, '\n');
4158  ql++;
4159  }
4160 
4161  if (fwrite(query_buf->data, 1, ql, stream) != ql)
4162  {
4163  pg_log_error("%s: %m", fname);
4164 
4165  if (fclose(stream) != 0)
4166  pg_log_error("%s: %m", fname);
4167 
4168  if (remove(fname) != 0)
4169  pg_log_error("%s: %m", fname);
4170 
4171  error = true;
4172  }
4173  else if (fclose(stream) != 0)
4174  {
4175  pg_log_error("%s: %m", fname);
4176  if (remove(fname) != 0)
4177  pg_log_error("%s: %m", fname);
4178  error = true;
4179  }
4180  else
4181  {
4182  struct utimbuf ut;
4183 
4184  /*
4185  * Try to set the file modification time of the temporary file
4186  * a few seconds in the past. Otherwise, the low granularity
4187  * (one second, or even worse on some filesystems) that we can
4188  * portably measure with stat(2) could lead us to not
4189  * recognize a modification, if the user typed very quickly.
4190  *
4191  * This is a rather unlikely race condition, so don't error
4192  * out if the utime(2) call fails --- that would make the cure
4193  * worse than the disease.
4194  */
4195  ut.modtime = ut.actime = time(NULL) - 2;
4196  (void) utime(fname, &ut);
4197  }
4198  }
4199  }
4200 
4201  if (!error && stat(fname, &before) != 0)
4202  {
4203  pg_log_error("%s: %m", fname);
4204  error = true;
4205  }
4206 
4207  /* call editor */
4208  if (!error)
4209  error = !editFile(fname, lineno);
4210 
4211  if (!error && stat(fname, &after) != 0)
4212  {
4213  pg_log_error("%s: %m", fname);
4214  error = true;
4215  }
4216 
4217  /* file was edited if the size or modification time has changed */
4218  if (!error &&
4219  (before.st_size != after.st_size ||
4220  before.st_mtime != after.st_mtime))
4221  {
4222  stream = fopen(fname, PG_BINARY_R);
4223  if (!stream)
4224  {
4225  pg_log_error("%s: %m", fname);
4226  error = true;
4227  }
4228  else
4229  {
4230  /* read file back into query_buf */
4231  char line[1024];
4232 
4233  resetPQExpBuffer(query_buf);
4234  while (fgets(line, sizeof(line), stream) != NULL)
4235  appendPQExpBufferStr(query_buf, line);
4236 
4237  if (ferror(stream))
4238  {
4239  pg_log_error("%s: %m", fname);
4240  error = true;
4241  resetPQExpBuffer(query_buf);
4242  }
4243  else if (edited)
4244  {
4245  *edited = true;
4246  }
4247 
4248  fclose(stream);
4249  }
4250  }
4251  else
4252  {
4253  /*
4254  * If the file was not modified, and the caller requested it, discard
4255  * the query buffer.
4256  */
4257  if (discard_on_quit)
4258  resetPQExpBuffer(query_buf);
4259  }
4260 
4261  /* remove temp file */
4262  if (!filename_arg)
4263  {
4264  if (remove(fname) == -1)
4265  {
4266  pg_log_error("%s: %m", fname);
4267  error = true;
4268  }
4269  }
4270 
4271  return !error;
4272 }
#define PG_BINARY_R
Definition: c.h:1275
static bool editFile(const char *fname, int lineno)
Definition: command.c:4010
#define MAXPGPATH
#define strerror
Definition: port.h:251
#define snprintf
Definition: port.h:238
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static int before(chr x, chr y)
Definition: regc_locale.c:488
static void error(void)
Definition: sql-dyntest.c:147
#define stat
Definition: win32_port.h:284

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

Referenced by exec_command_edit(), and exec_command_ef_ev().

◆ do_pset()

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

Definition at line 4440 of file command.c.

4441 {
4442  size_t vallen = 0;
4443 
4444  Assert(param != NULL);
4445 
4446  if (value)
4447  vallen = strlen(value);
4448 
4449  /* set format */
4450  if (strcmp(param, "format") == 0)
4451  {
4452  static const struct fmt
4453  {
4454  const char *name;
4455  enum printFormat number;
4456  } formats[] =
4457  {
4458  /* remember to update error message below when adding more */
4459  {"aligned", PRINT_ALIGNED},
4460  {"asciidoc", PRINT_ASCIIDOC},
4461  {"csv", PRINT_CSV},
4462  {"html", PRINT_HTML},
4463  {"latex", PRINT_LATEX},
4464  {"troff-ms", PRINT_TROFF_MS},
4465  {"unaligned", PRINT_UNALIGNED},
4466  {"wrapped", PRINT_WRAPPED}
4467  };
4468 
4469  if (!value)
4470  ;
4471  else
4472  {
4473  int match_pos = -1;
4474 
4475  for (int i = 0; i < lengthof(formats); i++)
4476  {
4477  if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
4478  {
4479  if (match_pos < 0)
4480  match_pos = i;
4481  else
4482  {
4483  pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
4484  value,
4485  formats[match_pos].name, formats[i].name);
4486  return false;
4487  }
4488  }
4489  }
4490  if (match_pos >= 0)
4491  popt->topt.format = formats[match_pos].number;
4492  else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
4493  {
4494  /*
4495  * We must treat latex-longtable specially because latex is a
4496  * prefix of it; if both were in the table above, we'd think
4497  * "latex" is ambiguous.
4498  */
4500  }
4501  else
4502  {
4503  pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
4504  return false;
4505  }
4506  }
4507  }
4508 
4509  /* set table line style */
4510  else if (strcmp(param, "linestyle") == 0)
4511  {
4512  if (!value)
4513  ;
4514  else if (pg_strncasecmp("ascii", value, vallen) == 0)
4515  popt->topt.line_style = &pg_asciiformat;
4516  else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
4518  else if (pg_strncasecmp("unicode", value, vallen) == 0)
4519  popt->topt.line_style = &pg_utf8format;
4520  else
4521  {
4522  pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
4523  return false;
4524  }
4525  }
4526 
4527  /* set unicode border line style */
4528  else if (strcmp(param, "unicode_border_linestyle") == 0)
4529  {
4530  if (!value)
4531  ;
4532  else if (set_unicode_line_style(value, vallen,
4534  refresh_utf8format(&(popt->topt));
4535  else
4536  {
4537  pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4538  return false;
4539  }
4540  }
4541 
4542  /* set unicode column line style */
4543  else if (strcmp(param, "unicode_column_linestyle") == 0)
4544  {
4545  if (!value)
4546  ;
4547  else if (set_unicode_line_style(value, vallen,
4549  refresh_utf8format(&(popt->topt));
4550  else
4551  {
4552  pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4553  return false;
4554  }
4555  }
4556 
4557  /* set unicode header line style */
4558  else if (strcmp(param, "unicode_header_linestyle") == 0)
4559  {
4560  if (!value)
4561  ;
4562  else if (set_unicode_line_style(value, vallen,
4564  refresh_utf8format(&(popt->topt));
4565  else
4566  {
4567  pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4568  return false;
4569  }
4570  }
4571 
4572  /* set border style/width */
4573  else if (strcmp(param, "border") == 0)
4574  {
4575  if (value)
4576  popt->topt.border = atoi(value);
4577  }
4578 
4579  /* set expanded/vertical mode */
4580  else if (strcmp(param, "x") == 0 ||
4581  strcmp(param, "expanded") == 0 ||
4582  strcmp(param, "vertical") == 0)
4583  {
4584  if (value && pg_strcasecmp(value, "auto") == 0)
4585  popt->topt.expanded = 2;
4586  else if (value)
4587  {
4588  bool on_off;
4589 
4590  if (ParseVariableBool(value, NULL, &on_off))
4591  popt->topt.expanded = on_off ? 1 : 0;
4592  else
4593  {
4594  PsqlVarEnumError(param, value, "on, off, auto");
4595  return false;
4596  }
4597  }
4598  else
4599  popt->topt.expanded = !popt->topt.expanded;
4600  }
4601 
4602  /* header line width in expanded mode */
4603  else if (strcmp(param, "xheader_width") == 0)
4604  {
4605  if (!value)
4606  ;
4607  else if (pg_strcasecmp(value, "full") == 0)
4609  else if (pg_strcasecmp(value, "column") == 0)
4611  else if (pg_strcasecmp(value, "page") == 0)
4613  else
4614  {
4615  int intval = atoi(value);
4616 
4617  if (intval == 0)
4618  {
4619  pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
4620  return false;
4621  }
4622 
4624  popt->topt.expanded_header_exact_width = intval;
4625  }
4626  }
4627 
4628  /* field separator for CSV format */
4629  else if (strcmp(param, "csv_fieldsep") == 0)
4630  {
4631  if (value)
4632  {
4633  /* CSV separator has to be a one-byte character */
4634  if (strlen(value) != 1)
4635  {
4636  pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
4637  return false;
4638  }
4639  if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
4640  {
4641  pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
4642  return false;
4643  }
4644  popt->topt.csvFieldSep[0] = value[0];
4645  }
4646  }
4647 
4648  /* locale-aware numeric output */
4649  else if (strcmp(param, "numericlocale") == 0)
4650  {
4651  if (value)
4652  return ParseVariableBool(value, param, &popt->topt.numericLocale);
4653  else
4654  popt->topt.numericLocale = !popt->topt.numericLocale;
4655  }
4656 
4657  /* null display */
4658  else if (strcmp(param, "null") == 0)
4659  {
4660  if (value)
4661  {
4662  free(popt->nullPrint);
4663  popt->nullPrint = pg_strdup(value);
4664  }
4665  }
4666 
4667  /* field separator for unaligned text */
4668  else if (strcmp(param, "fieldsep") == 0)
4669  {
4670  if (value)
4671  {
4672  free(popt->topt.fieldSep.separator);
4674  popt->topt.fieldSep.separator_zero = false;
4675  }
4676  }
4677 
4678  else if (strcmp(param, "fieldsep_zero") == 0)
4679  {
4680  free(popt->topt.fieldSep.separator);
4681  popt->topt.fieldSep.separator = NULL;
4682  popt->topt.fieldSep.separator_zero = true;
4683  }
4684 
4685  /* record separator for unaligned text */
4686  else if (strcmp(param, "recordsep") == 0)
4687  {
4688  if (value)
4689  {
4690  free(popt->topt.recordSep.separator);
4692  popt->topt.recordSep.separator_zero = false;
4693  }
4694  }
4695 
4696  else if (strcmp(param, "recordsep_zero") == 0)
4697  {
4698  free(popt->topt.recordSep.separator);
4699  popt->topt.recordSep.separator = NULL;
4700  popt->topt.recordSep.separator_zero = true;
4701  }
4702 
4703  /* toggle between full and tuples-only format */
4704  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4705  {
4706  if (value)
4707  return ParseVariableBool(value, param, &popt->topt.tuples_only);
4708  else
4709  popt->topt.tuples_only = !popt->topt.tuples_only;
4710  }
4711 
4712  /* set title override */
4713  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4714  {
4715  free(popt->title);
4716  if (!value)
4717  popt->title = NULL;
4718  else
4719  popt->title = pg_strdup(value);
4720  }
4721 
4722  /* set HTML table tag options */
4723  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4724  {
4725  free(popt->topt.tableAttr);
4726  if (!value)
4727  popt->topt.tableAttr = NULL;
4728  else
4729  popt->topt.tableAttr = pg_strdup(value);
4730  }
4731 
4732  /* toggle use of pager */
4733  else if (strcmp(param, "pager") == 0)
4734  {
4735  if (value && pg_strcasecmp(value, "always") == 0)
4736  popt->topt.pager = 2;
4737  else if (value)
4738  {
4739  bool on_off;
4740 
4741  if (!ParseVariableBool(value, NULL, &on_off))
4742  {
4743  PsqlVarEnumError(param, value, "on, off, always");
4744  return false;
4745  }
4746  popt->topt.pager = on_off ? 1 : 0;
4747  }
4748  else if (popt->topt.pager == 1)
4749  popt->topt.pager = 0;
4750  else
4751  popt->topt.pager = 1;
4752  }
4753 
4754  /* set minimum lines for pager use */
4755  else if (strcmp(param, "pager_min_lines") == 0)
4756  {
4757  if (value &&
4758  !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
4759  return false;
4760  }
4761 
4762  /* disable "(x rows)" footer */
4763  else if (strcmp(param, "footer") == 0)
4764  {
4765  if (value)
4766  return ParseVariableBool(value, param, &popt->topt.default_footer);
4767  else
4768  popt->topt.default_footer = !popt->topt.default_footer;
4769  }
4770 
4771  /* set border style/width */
4772  else if (strcmp(param, "columns") == 0)
4773  {
4774  if (value)
4775  popt->topt.columns = atoi(value);
4776  }
4777  else
4778  {
4779  pg_log_error("\\pset: unknown option: %s", param);
4780  return false;
4781  }
4782 
4783  if (!quiet)
4784  printPsetInfo(param, &pset.popt);
4785 
4786  return true;
4787 }
#define lengthof(array)
Definition: c.h:788
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4397
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:4793
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3691
const printTextFormat pg_asciiformat
Definition: print.c:56
const printTextFormat pg_asciiformat_old
Definition: print.c:77
printTextFormat pg_utf8format
Definition: print.c:99
@ PRINT_XHEADER_EXACT_WIDTH
Definition: print.h:78
@ PRINT_XHEADER_PAGE
Definition: print.h:76
@ PRINT_XHEADER_COLUMN
Definition: print.h:74
@ PRINT_XHEADER_FULL
Definition: print.h:72
printFormat
Definition: print.h:29
#define free(a)
Definition: header.h:65
static struct @155 value
int i
Definition: isn.c:73
static void const char * fmt
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
printQueryOpt popt
Definition: settings.h:91
printTableOpt topt
Definition: print.h:185
char * nullPrint
Definition: print.h:186
char * title
Definition: print.h:187
unsigned short int expanded
Definition: print.h:114
unicode_linestyle unicode_border_linestyle
Definition: print.h:141
bool tuples_only
Definition: print.h:126
int columns
Definition: print.h:140
enum printFormat format
Definition: print.h:113
struct separator fieldSep
Definition: print.h:132
int expanded_header_exact_width
Definition: print.h:118
struct separator recordSep
Definition: print.h:133
printXheaderWidthType expanded_header_width_type
Definition: print.h:116
char csvFieldSep[2]
Definition: print.h:134
const printTextFormat * line_style
Definition: print.h:131
bool default_footer
Definition: print.h:129
int pager_min_lines
Definition: print.h:124
unsigned short int pager
Definition: print.h:122
char * tableAttr
Definition: print.h:137
bool numericLocale
Definition: print.h:135
unsigned short int border
Definition: print.h:120
unicode_linestyle unicode_header_linestyle
Definition: print.h:143
unicode_linestyle unicode_column_linestyle
Definition: print.h:142
bool separator_zero
Definition: print.h:108
char * separator
Definition: print.h:107
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:416
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
bool ParseVariableNum(const char *value, const char *name, int *result)
Definition: variables.c:156
const char * name

References Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::expanded_header_exact_width, printTableOpt::expanded_header_width_type, printTableOpt::fieldSep, fmt, printTableOpt::format, free, i, lengthof, printTableOpt::line_style, name, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, ParseVariableBool(), ParseVariableNum(), 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, PRINT_XHEADER_COLUMN, PRINT_XHEADER_EXACT_WIDTH, PRINT_XHEADER_FULL, PRINT_XHEADER_PAGE, printPsetInfo(), pset, PsqlVarEnumError(), printTableOpt::recordSep, refresh_utf8format(), separator::separator, separator::separator_zero, set_unicode_line_style(), printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, printTableOpt::unicode_header_linestyle, and value.

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

◆ do_shell()

static bool do_shell ( const char *  command)
static

Definition at line 5189 of file command.c.

5190 {
5191  int result;
5192 
5193  fflush(NULL);
5194  if (!command)
5195  {
5196  char *sys;
5197  const char *shellName;
5198 
5199  shellName = getenv("SHELL");
5200 #ifdef WIN32
5201  if (shellName == NULL)
5202  shellName = getenv("COMSPEC");
5203 #endif
5204  if (shellName == NULL)
5205  shellName = DEFAULT_SHELL;
5206 
5207  /* See EDITOR handling comment for an explanation */
5208 #ifndef WIN32
5209  sys = psprintf("exec %s", shellName);
5210 #else
5211  sys = psprintf("\"%s\"", shellName);
5212 #endif
5213  result = system(sys);
5214  free(sys);
5215  }
5216  else
5217  result = system(command);
5218 
5219  SetShellResultVariables(result);
5220 
5221  if (result == 127 || result == -1)
5222  {
5223  pg_log_error("\\!: failed");
5224  return false;
5225  }
5226  return true;
5227 }
void SetShellResultVariables(int wait_result)
Definition: common.c:501
#define DEFAULT_SHELL
Definition: command.c:5179
static void const char fflush(stdout)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

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

Referenced by exec_command_shell_escape().

◆ do_watch()

static bool do_watch ( PQExpBuffer  query_buf,
double  sleep,
int  iter,
int  min_rows 
)
static

Definition at line 5236 of file command.c.

5237 {
5238  long sleep_ms = (long) (sleep * 1000);
5239  printQueryOpt myopt = pset.popt;
5240  const char *strftime_fmt;
5241  const char *user_title;
5242  char *title;
5243  const char *pagerprog = NULL;
5244  FILE *pagerpipe = NULL;
5245  int title_len;
5246  int res = 0;
5247  bool done = false;
5248 #ifndef WIN32
5249  sigset_t sigalrm_sigchld_sigint;
5250  sigset_t sigalrm_sigchld;
5251  sigset_t sigint;
5252  struct itimerval interval;
5253 #endif
5254 
5255  if (!query_buf || query_buf->len <= 0)
5256  {
5257  pg_log_error("\\watch cannot be used with an empty query");
5258  return false;
5259  }
5260 
5261 #ifndef WIN32
5262  sigemptyset(&sigalrm_sigchld_sigint);
5263  sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5264  sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5265  sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5266 
5267  sigemptyset(&sigalrm_sigchld);
5268  sigaddset(&sigalrm_sigchld, SIGCHLD);
5269  sigaddset(&sigalrm_sigchld, SIGALRM);
5270 
5271  sigemptyset(&sigint);
5272  sigaddset(&sigint, SIGINT);
5273 
5274  /*
5275  * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5276  * configured), to avoid races. sigwait() will receive them.
5277  */
5278  sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5279 
5280  /*
5281  * Set a timer to interrupt sigwait() so we can run the query at the
5282  * requested intervals.
5283  */
5284  interval.it_value.tv_sec = sleep_ms / 1000;
5285  interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5286  interval.it_interval = interval.it_value;
5287  if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5288  {
5289  pg_log_error("could not set timer: %m");
5290  done = true;
5291  }
5292 #endif
5293 
5294  /*
5295  * For \watch, we ignore the size of the result and always use the pager
5296  * as long as we're talking to a terminal and "\pset pager" is enabled.
5297  * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5298  * ignore the regular PSQL_PAGER or PAGER environment variables, because
5299  * traditional pagers probably won't be very useful for showing a stream
5300  * of results.
5301  */
5302 #ifndef WIN32
5303  pagerprog = getenv("PSQL_WATCH_PAGER");
5304  /* if variable is empty or all-white-space, don't use pager */
5305  if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5306  pagerprog = NULL;
5307 #endif
5308  if (pagerprog && myopt.topt.pager &&
5309  isatty(fileno(stdin)) && isatty(fileno(stdout)))
5310  {
5311  fflush(NULL);
5313  pagerpipe = popen(pagerprog, "w");
5314 
5315  if (!pagerpipe)
5316  /* silently proceed without pager */
5318  }
5319 
5320  /*
5321  * Choose format for timestamps. We might eventually make this a \pset
5322  * option. In the meantime, using a variable for the format suppresses
5323  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5324  */
5325  strftime_fmt = "%c";
5326 
5327  /*
5328  * Set up rendering options, in particular, disable the pager unless
5329  * PSQL_WATCH_PAGER was successfully launched.
5330  */
5331  if (!pagerpipe)
5332  myopt.topt.pager = 0;
5333 
5334  /*
5335  * If there's a title in the user configuration, make sure we have room
5336  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5337  * bytes for the rest.
5338  */
5339  user_title = myopt.title;
5340  title_len = (user_title ? strlen(user_title) : 0) + 256;
5341  title = pg_malloc(title_len);
5342 
5343  /* Loop to run query and then sleep awhile */
5344  while (!done)
5345  {
5346  time_t timer;
5347  char timebuf[128];
5348 
5349  /*
5350  * Prepare title for output. Note that we intentionally include a
5351  * newline at the end of the title; this is somewhat historical but it
5352  * makes for reasonably nicely formatted output in simple cases.
5353  */
5354  timer = time(NULL);
5355  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5356 
5357  if (user_title)
5358  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5359  user_title, timebuf, sleep);
5360  else
5361  snprintf(title, title_len, _("%s (every %gs)\n"),
5362  timebuf, sleep);
5363  myopt.title = title;
5364 
5365  /* Run the query and print out the result */
5366  res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
5367 
5368  /*
5369  * PSQLexecWatch handles the case where we can no longer repeat the
5370  * query, and returns 0 or -1.
5371  */
5372  if (res <= 0)
5373  break;
5374 
5375  /* If we have iteration count, check that it's not exceeded yet */
5376  if (iter && (--iter <= 0))
5377  break;
5378 
5379  /* Quit if error on pager pipe (probably pager has quit) */
5380  if (pagerpipe && ferror(pagerpipe))
5381  break;
5382 
5383  if (sleep == 0)
5384  continue;
5385 
5386 #ifdef WIN32
5387 
5388  /*
5389  * Wait a while before running the query again. Break the sleep into
5390  * short intervals (at most 1s); that's probably unnecessary since
5391  * pg_usleep is interruptible on Windows, but it's cheap insurance.
5392  */
5393  for (long i = sleep_ms; i > 0;)
5394  {
5395  long s = Min(i, 1000L);
5396 
5397  pg_usleep(s * 1000L);
5398  if (cancel_pressed)
5399  {
5400  done = true;
5401  break;
5402  }
5403  i -= s;
5404  }
5405 #else
5406  /* sigwait() will handle SIGINT. */
5407  sigprocmask(SIG_BLOCK, &sigint, NULL);
5408  if (cancel_pressed)
5409  done = true;
5410 
5411  /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5412  while (!done)
5413  {
5414  int signal_received;
5415 
5416  errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5417  if (errno != 0)
5418  {
5419  /* Some other signal arrived? */
5420  if (errno == EINTR)
5421  continue;
5422  else
5423  {
5424  pg_log_error("could not wait for signals: %m");
5425  done = true;
5426  break;
5427  }
5428  }
5429  /* On ^C or pager exit, it's time to stop running the query. */
5430  if (signal_received == SIGINT || signal_received == SIGCHLD)
5431  done = true;
5432  /* Otherwise, we must have SIGALRM. Time to run the query again. */
5433  break;
5434  }
5435 
5436  /* Unblock SIGINT so that slow queries can be interrupted. */
5437  sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5438 #endif
5439  }
5440 
5441  if (pagerpipe)
5442  {
5443  pclose(pagerpipe);
5445  }
5446  else
5447  {
5448  /*
5449  * If the terminal driver echoed "^C", libedit/libreadline might be
5450  * confused about the cursor position. Therefore, inject a newline
5451  * before the next prompt is displayed. We only do this when not
5452  * using a pager, because pagers are expected to restore the screen to
5453  * a sane state on exit.
5454  */
5455  fprintf(stdout, "\n");
5456  fflush(stdout);
5457  }
5458 
5459 #ifndef WIN32
5460  /* Disable the interval timer. */
5461  memset(&interval, 0, sizeof(interval));
5462  setitimer(ITIMER_REAL, &interval, NULL);
5463  /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5464  sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5465 #endif
5466 
5467  pg_free(title);
5468  return (res >= 0);
5469 }
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
Definition: common.c:675
#define Min(x, y)
Definition: c.h:1004
void restore_sigpipe_trap(void)
Definition: print.c:3062
void disable_sigpipe_trap(void)
Definition: print.c:3039
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
#define fprintf
Definition: port.h:242
void pg_usleep(long microsec)
Definition: signal.c:53
static long sleep_ms
Definition: slotsync.c:119
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
Definition: timer.c:86
#define SIGCHLD
Definition: win32_port.h:178
#define EINTR
Definition: win32_port.h:374
#define SIGALRM
Definition: win32_port.h:174
#define ITIMER_REAL
Definition: win32_port.h:190

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

Referenced by exec_command_watch().

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 5476 of file command.c.

5477 {
5479  {
5480  printf(_("/******** QUERY *********/\n"
5481  "%s\n"
5482  "/************************/\n\n"), query);
5483  fflush(stdout);
5484  if (pset.logfile)
5485  {
5487  _("/******** QUERY *********/\n"
5488  "%s\n"
5489  "/************************/\n\n"), query);
5490  fflush(pset.logfile);
5491  }
5492 
5494  return false;
5495  }
5496  return true;
5497 }
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
FILE * logfile
Definition: settings.h:120
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:147

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

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ editFile()

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

Definition at line 4010 of file command.c.

4011 {
4012  const char *editorName;
4013  const char *editor_lineno_arg = NULL;
4014  char *sys;
4015  int result;
4016 
4017  Assert(fname != NULL);
4018 
4019  /* Find an editor to use */
4020  editorName = getenv("PSQL_EDITOR");
4021  if (!editorName)
4022  editorName = getenv("EDITOR");
4023  if (!editorName)
4024  editorName = getenv("VISUAL");
4025  if (!editorName)
4026  editorName = DEFAULT_EDITOR;
4027 
4028  /* Get line number argument, if we need it. */
4029  if (lineno > 0)
4030  {
4031  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4032 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4033  if (!editor_lineno_arg)
4034  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4035 #endif
4036  if (!editor_lineno_arg)
4037  {
4038  pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4039  return false;
4040  }
4041  }
4042 
4043  /*
4044  * On Unix the EDITOR value should *not* be quoted, since it might include
4045  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4046  * if necessary. But this policy is not very workable on Windows, due to
4047  * severe brain damage in their command shell plus the fact that standard
4048  * program paths include spaces.
4049  */
4050 #ifndef WIN32
4051  if (lineno > 0)
4052  sys = psprintf("exec %s %s%d '%s'",
4053  editorName, editor_lineno_arg, lineno, fname);
4054  else
4055  sys = psprintf("exec %s '%s'",
4056  editorName, fname);
4057 #else
4058  if (lineno > 0)
4059  sys = psprintf("\"%s\" %s%d \"%s\"",
4060  editorName, editor_lineno_arg, lineno, fname);
4061  else
4062  sys = psprintf("\"%s\" \"%s\"",
4063  editorName, fname);
4064 #endif
4065  fflush(NULL);
4066  result = system(sys);
4067  if (result == -1)
4068  pg_log_error("could not start editor \"%s\"", editorName);
4069  else if (result == 127)
4070  pg_log_error("could not start /bin/sh");
4071  free(sys);
4072 
4073  return result == 0;
4074 }
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23
#define DEFAULT_EDITOR
Definition: settings.h:22

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

Referenced by do_edit().

◆ exec_command()

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

Definition at line 288 of file command.c.

293 {
294  backslashResult status;
295  bool active_branch = conditional_active(cstack);
296 
297  /*
298  * In interactive mode, warn when we're ignoring a command within a false
299  * \if-branch. But we continue on, so as to parse and discard the right
300  * amount of parameter text. Each individual backslash command subroutine
301  * is responsible for doing nothing after discarding appropriate
302  * arguments, if !active_branch.
303  */
304  if (pset.cur_cmd_interactive && !active_branch &&
305  !is_branching_command(cmd))
306  {
307  pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
308  cmd);
309  }
310 
311  if (strcmp(cmd, "a") == 0)
312  status = exec_command_a(scan_state, active_branch);
313  else if (strcmp(cmd, "bind") == 0)
314  status = exec_command_bind(scan_state, active_branch);
315  else if (strcmp(cmd, "C") == 0)
316  status = exec_command_C(scan_state, active_branch);
317  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
318  status = exec_command_connect(scan_state, active_branch);
319  else if (strcmp(cmd, "cd") == 0)
320  status = exec_command_cd(scan_state, active_branch, cmd);
321  else if (strcmp(cmd, "conninfo") == 0)
322  status = exec_command_conninfo(scan_state, active_branch);
323  else if (pg_strcasecmp(cmd, "copy") == 0)
324  status = exec_command_copy(scan_state, active_branch);
325  else if (strcmp(cmd, "copyright") == 0)
326  status = exec_command_copyright(scan_state, active_branch);
327  else if (strcmp(cmd, "crosstabview") == 0)
328  status = exec_command_crosstabview(scan_state, active_branch);
329  else if (cmd[0] == 'd')
330  status = exec_command_d(scan_state, active_branch, cmd);
331  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
332  status = exec_command_edit(scan_state, active_branch,
333  query_buf, previous_buf);
334  else if (strcmp(cmd, "ef") == 0)
335  status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
336  else if (strcmp(cmd, "ev") == 0)
337  status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
338  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
339  strcmp(cmd, "warn") == 0)
340  status = exec_command_echo(scan_state, active_branch, cmd);
341  else if (strcmp(cmd, "elif") == 0)
342  status = exec_command_elif(scan_state, cstack, query_buf);
343  else if (strcmp(cmd, "else") == 0)
344  status = exec_command_else(scan_state, cstack, query_buf);
345  else if (strcmp(cmd, "endif") == 0)
346  status = exec_command_endif(scan_state, cstack, query_buf);
347  else if (strcmp(cmd, "encoding") == 0)
348  status = exec_command_encoding(scan_state, active_branch);
349  else if (strcmp(cmd, "errverbose") == 0)
350  status = exec_command_errverbose(scan_state, active_branch);
351  else if (strcmp(cmd, "f") == 0)
352  status = exec_command_f(scan_state, active_branch);
353  else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
354  status = exec_command_g(scan_state, active_branch, cmd);
355  else if (strcmp(cmd, "gdesc") == 0)
356  status = exec_command_gdesc(scan_state, active_branch);
357  else if (strcmp(cmd, "getenv") == 0)
358  status = exec_command_getenv(scan_state, active_branch, cmd);
359  else if (strcmp(cmd, "gexec") == 0)
360  status = exec_command_gexec(scan_state, active_branch);
361  else if (strcmp(cmd, "gset") == 0)
362  status = exec_command_gset(scan_state, active_branch);
363  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
364  status = exec_command_help(scan_state, active_branch);
365  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
366  status = exec_command_html(scan_state, active_branch);
367  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
368  strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
369  status = exec_command_include(scan_state, active_branch, cmd);
370  else if (strcmp(cmd, "if") == 0)
371  status = exec_command_if(scan_state, cstack, query_buf);
372  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
373  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
374  status = exec_command_list(scan_state, active_branch, cmd);
375  else if (strncmp(cmd, "lo_", 3) == 0)
376  status = exec_command_lo(scan_state, active_branch, cmd);
377  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
378  status = exec_command_out(scan_state, active_branch);
379  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
380  status = exec_command_print(scan_state, active_branch,
381  query_buf, previous_buf);
382  else if (strcmp(cmd, "password") == 0)
383  status = exec_command_password(scan_state, active_branch);
384  else if (strcmp(cmd, "prompt") == 0)
385  status = exec_command_prompt(scan_state, active_branch, cmd);
386  else if (strcmp(cmd, "pset") == 0)
387  status = exec_command_pset(scan_state, active_branch);
388  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
389  status = exec_command_quit(scan_state, active_branch);
390  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
391  status = exec_command_reset(scan_state, active_branch, query_buf);
392  else if (strcmp(cmd, "s") == 0)
393  status = exec_command_s(scan_state, active_branch);
394  else if (strcmp(cmd, "set") == 0)
395  status = exec_command_set(scan_state, active_branch);
396  else if (strcmp(cmd, "setenv") == 0)
397  status = exec_command_setenv(scan_state, active_branch, cmd);
398  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
399  status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
400  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
401  status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
402  else if (strcmp(cmd, "t") == 0)
403  status = exec_command_t(scan_state, active_branch);
404  else if (strcmp(cmd, "T") == 0)
405  status = exec_command_T(scan_state, active_branch);
406  else if (strcmp(cmd, "timing") == 0)
407  status = exec_command_timing(scan_state, active_branch);
408  else if (strcmp(cmd, "unset") == 0)
409  status = exec_command_unset(scan_state, active_branch, cmd);
410  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
411  status = exec_command_write(scan_state, active_branch, cmd,
412  query_buf, previous_buf);
413  else if (strcmp(cmd, "watch") == 0)
414  status = exec_command_watch(scan_state, active_branch,
415  query_buf, previous_buf);
416  else if (strcmp(cmd, "x") == 0)
417  status = exec_command_x(scan_state, active_branch);
418  else if (strcmp(cmd, "z") == 0 || strcmp(cmd, "zS") == 0)
419  status = exec_command_z(scan_state, active_branch, cmd);
420  else if (strcmp(cmd, "!") == 0)
421  status = exec_command_shell_escape(scan_state, active_branch);
422  else if (strcmp(cmd, "?") == 0)
423  status = exec_command_slash_command_help(scan_state, active_branch);
424  else
425  status = PSQL_CMD_UNKNOWN;
426 
427  /*
428  * All the commands that return PSQL_CMD_SEND want to execute previous_buf
429  * if query_buf is empty. For convenience we implement that here, not in
430  * the individual command subroutines.
431  */
432  if (status == PSQL_CMD_SEND)
433  (void) copy_previous_query(query_buf, previous_buf);
434 
435  return status;
436 }
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1908
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:716
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1355
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2077
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1661
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3226
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1413
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2576
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1541
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1641
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:445
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch)
Definition: command.c:464
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2103
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2909
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1721
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1767
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1385
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2325
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2054
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1272
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:752
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2959
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:586
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1612
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1156
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2630
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2370
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2343
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2179
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2762
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1680
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1948
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2598
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:500
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1317
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1060
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1843
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:650
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:694
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2981
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:728
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2256
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2554
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2660
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2471
static bool is_branching_command(const char *cmd)
Definition: command.c:3164
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:533
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1595
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2931
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1976
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1558
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2311
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2423
@ PSQL_CMD_UNKNOWN
Definition: command.h:17
@ PSQL_CMD_SEND
Definition: command.h:18
enum _backslashResult backslashResult
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:140
#define pg_log_warning(...)
Definition: pgfnames.c:24

References conditional_active(), copy_previous_query(), _psqlSettings::cur_cmd_interactive, exec_command_a(), exec_command_bind(), 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_getenv(), 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, and PSQL_CMD_UNKNOWN.

Referenced by HandleSlashCmds().

◆ exec_command_a()

static backslashResult exec_command_a ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 445 of file command.c.

446 {
447  bool success = true;
448 
449  if (active_branch)
450  {
452  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
453  else
454  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
455  }
456 
458 }
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4440
@ PSQL_CMD_ERROR
Definition: command.h:22
@ PSQL_CMD_SKIP_LINE
Definition: command.h:19

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

Referenced by exec_command().

◆ exec_command_bind()

static backslashResult exec_command_bind ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 464 of file command.c.

465 {
467 
468  if (active_branch)
469  {
470  char *opt;
471  int nparams = 0;
472  int nalloc = 0;
473 
474  pset.bind_params = NULL;
475 
476  while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
477  {
478  nparams++;
479  if (nparams > nalloc)
480  {
481  nalloc = nalloc ? nalloc * 2 : 1;
482  pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
483  }
484  pset.bind_params[nparams - 1] = opt;
485  }
486 
487  pset.bind_nparams = nparams;
488  pset.bind_flag = true;
489  }
490  else
491  ignore_slash_options(scan_state);
492 
493  return status;
494 }
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:3115
#define pg_realloc_array(pointer, type, count)
Definition: fe_memutils.h:51
@ OT_NORMAL
Definition: psqlscanslash.h:17
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool bind_flag
Definition: settings.h:99
char ** bind_params
Definition: settings.h:102
int bind_nparams
Definition: settings.h:101

References _psqlSettings::bind_flag, _psqlSettings::bind_nparams, _psqlSettings::bind_params, ignore_slash_options(), OT_NORMAL, pg_realloc_array, pset, PSQL_CMD_SKIP_LINE, and psql_scan_slash_option().

Referenced by exec_command().

◆ exec_command_C()

static backslashResult exec_command_C ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 500 of file command.c.

501 {
502  bool success = true;
503 
504  if (active_branch)
505  {
506  char *opt = psql_scan_slash_option(scan_state,
507  OT_NORMAL, NULL, true);
508 
509  success = do_pset("title", opt, &pset.popt, pset.quiet);
510  free(opt);
511  }
512  else
513  ignore_slash_options(scan_state);
514 
516 }

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

Referenced by exec_command().

◆ exec_command_cd()

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

Definition at line 586 of file command.c.

587 {
588  bool success = true;
589 
590  if (active_branch)
591  {
592  char *opt = psql_scan_slash_option(scan_state,
593  OT_NORMAL, NULL, true);
594  char *dir;
595 
596  if (opt)
597  dir = opt;
598  else
599  {
600 #ifndef WIN32
601  /* This should match get_home_path() */
602  dir = getenv("HOME");
603  if (dir == NULL || dir[0] == '\0')
604  {
605  uid_t user_id = geteuid();
606  struct passwd *pw;
607 
608  errno = 0; /* clear errno before call */
609  pw = getpwuid(user_id);
610  if (pw)
611  dir = pw->pw_dir;
612  else
613  {
614  pg_log_error("could not get home directory for user ID %ld: %s",
615  (long) user_id,
616  errno ? strerror(errno) : _("user does not exist"));
617  success = false;
618  }
619  }
620 #else /* WIN32 */
621 
622  /*
623  * On Windows, 'cd' without arguments prints the current
624  * directory, so if someone wants to code this here instead...
625  */
626  dir = "/";
627 #endif /* WIN32 */
628  }
629 
630  if (success &&
631  chdir(dir) < 0)
632  {
633  pg_log_error("\\%s: could not change directory to \"%s\": %m",
634  cmd, dir);
635  success = false;
636  }
637 
638  free(opt);
639  }
640  else
641  ignore_slash_options(scan_state);
642 
644 }
int uid_t
Definition: win32_port.h:244

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

Referenced by exec_command().

◆ exec_command_connect()

static backslashResult exec_command_connect ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 533 of file command.c.

534 {
535  bool success = true;
536 
537  if (active_branch)
538  {
539  static const char prefix[] = "-reuse-previous=";
540  char *opt1,
541  *opt2,
542  *opt3,
543  *opt4;
544  enum trivalue reuse_previous = TRI_DEFAULT;
545 
546  opt1 = read_connect_arg(scan_state);
547  if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
548  {
549  bool on_off;
550 
551  success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
552  "-reuse-previous",
553  &on_off);
554  if (success)
555  {
556  reuse_previous = on_off ? TRI_YES : TRI_NO;
557  free(opt1);
558  opt1 = read_connect_arg(scan_state);
559  }
560  }
561 
562  if (success) /* give up if reuse_previous was invalid */
563  {
564  opt2 = read_connect_arg(scan_state);
565  opt3 = read_connect_arg(scan_state);
566  opt4 = read_connect_arg(scan_state);
567 
568  success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
569 
570  free(opt2);
571  free(opt3);
572  free(opt4);
573  }
574  free(opt1);
575  }
576  else
577  ignore_slash_options(scan_state);
578 
580 }
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:3295
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:3012
trivalue
Definition: vacuumlo.c:35
@ TRI_DEFAULT
Definition: vacuumlo.c:36

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

Referenced by exec_command().

◆ exec_command_conninfo()

static backslashResult exec_command_conninfo ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 650 of file command.c.

651 {
652  if (active_branch)
653  {
654  char *db = PQdb(pset.db);
655 
656  if (db == NULL)
657  printf(_("You are currently not connected to a database.\n"));
658  else
659  {
660  char *host = PQhost(pset.db);
661  char *hostaddr = PQhostaddr(pset.db);
662 
663  if (is_unixsock_path(host))
664  {
665  /* hostaddr overrides host */
666  if (hostaddr && *hostaddr)
667  printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
668  db, PQuser(pset.db), hostaddr, PQport(pset.db));
669  else
670  printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
671  db, PQuser(pset.db), host, PQport(pset.db));
672  }
673  else
674  {
675  if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
676  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
677  db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
678  else
679  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
680  db, PQuser(pset.db), host, PQport(pset.db));
681  }
682  printSSLInfo();
683  printGSSInfo();
684  }
685  }
686 
687  return PSQL_CMD_SKIP_LINE;
688 }

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

Referenced by exec_command().

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 694 of file command.c.

695 {
696  bool success = true;
697 
698  if (active_branch)
699  {
700  char *opt = psql_scan_slash_option(scan_state,
701  OT_WHOLE_LINE, NULL, false);
702 
703  success = do_copy(opt);
704  free(opt);
705  }
706  else
707  ignore_slash_whole_line(scan_state);
708 
710 }
bool do_copy(const char *args)
Definition: copy.c:268
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:3152
@ OT_WHOLE_LINE
Definition: psqlscanslash.h:21

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

Referenced by exec_command().

◆ exec_command_copyright()

static backslashResult exec_command_copyright ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 716 of file command.c.

717 {
718  if (active_branch)
719  print_copyright();
720 
721  return PSQL_CMD_SKIP_LINE;
722 }
void print_copyright(void)

References print_copyright(), and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_crosstabview()

static backslashResult exec_command_crosstabview ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 728 of file command.c.

729 {
731 
732  if (active_branch)
733  {
734  int i;
735 
736  for (i = 0; i < lengthof(pset.ctv_args); i++)
737  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
738  OT_NORMAL, NULL, true);
739  pset.crosstab_flag = true;
740  status = PSQL_CMD_SEND;
741  }
742  else
743  ignore_slash_options(scan_state);
744 
745  return status;
746 }
char * ctv_args[4]
Definition: settings.h:104
bool crosstab_flag
Definition: settings.h:103

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

Referenced by exec_command().

◆ exec_command_d()

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

Definition at line 752 of file command.c.

753 {
755  bool success = true;
756 
757  if (active_branch)
758  {
759  char *pattern;
760  bool show_verbose,
761  show_system;
762 
763  /* We don't do SQLID reduction on the pattern yet */
764  pattern = psql_scan_slash_option(scan_state,
765  OT_NORMAL, NULL, true);
766 
767  show_verbose = strchr(cmd, '+') ? true : false;
768  show_system = strchr(cmd, 'S') ? true : false;
769 
770  switch (cmd[1])
771  {
772  case '\0':
773  case '+':
774  case 'S':
775  if (pattern)
776  success = describeTableDetails(pattern, show_verbose, show_system);
777  else
778  /* standard listing of interesting things */
779  success = listTables("tvmsE", NULL, show_verbose, show_system);
780  break;
781  case 'A':
782  {
783  char *pattern2 = NULL;
784 
785  if (pattern && cmd[2] != '\0' && cmd[2] != '+')
786  pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
787 
788  switch (cmd[2])
789  {
790  case '\0':
791  case '+':
792  success = describeAccessMethods(pattern, show_verbose);
793  break;
794  case 'c':
795  success = listOperatorClasses(pattern, pattern2, show_verbose);
796  break;
797  case 'f':
798  success = listOperatorFamilies(pattern, pattern2, show_verbose);
799  break;
800  case 'o':
801  success = listOpFamilyOperators(pattern, pattern2, show_verbose);
802  break;
803  case 'p':
804  success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
805  break;
806  default:
807  status = PSQL_CMD_UNKNOWN;
808  break;
809  }
810 
811  free(pattern2);
812  }
813  break;
814  case 'a':
815  success = describeAggregates(pattern, show_verbose, show_system);
816  break;
817  case 'b':
818  success = describeTablespaces(pattern, show_verbose);
819  break;
820  case 'c':
821  if (strncmp(cmd, "dconfig", 7) == 0)
823  show_verbose,
824  show_system);
825  else
826  success = listConversions(pattern,
827  show_verbose,
828  show_system);
829  break;
830  case 'C':
831  success = listCasts(pattern, show_verbose);
832  break;
833  case 'd':
834  if (strncmp(cmd, "ddp", 3) == 0)
835  success = listDefaultACLs(pattern);
836  else
837  success = objectDescription(pattern, show_system);
838  break;
839  case 'D':
840  success = listDomains(pattern, show_verbose, show_system);
841  break;
842  case 'f': /* function subsystem */
843  switch (cmd[2])
844  {
845  case '\0':
846  case '+':
847  case 'S':
848  case 'a':
849  case 'n':
850  case 'p':
851  case 't':
852  case 'w':
853  success = exec_command_dfo(scan_state, cmd, pattern,
854  show_verbose, show_system);
855  break;
856  default:
857  status = PSQL_CMD_UNKNOWN;
858  break;
859  }
860  break;
861  case 'g':
862  /* no longer distinct from \du */
863  success = describeRoles(pattern, show_verbose, show_system);
864  break;
865  case 'l':
866  success = listLargeObjects(show_verbose);
867  break;
868  case 'L':
869  success = listLanguages(pattern, show_verbose, show_system);
870  break;
871  case 'n':
872  success = listSchemas(pattern, show_verbose, show_system);
873  break;
874  case 'o':
875  success = exec_command_dfo(scan_state, cmd, pattern,
876  show_verbose, show_system);
877  break;
878  case 'O':
879  success = listCollations(pattern, show_verbose, show_system);
880  break;
881  case 'p':
882  success = permissionsList(pattern, show_system);
883  break;
884  case 'P':
885  {
886  switch (cmd[2])
887  {
888  case '\0':
889  case '+':
890  case 't':
891  case 'i':
892  case 'n':
893  success = listPartitionedTables(&cmd[2], pattern, show_verbose);
894  break;
895  default:
896  status = PSQL_CMD_UNKNOWN;
897  break;
898  }
899  }
900  break;
901  case 'T':
902  success = describeTypes(pattern, show_verbose, show_system);
903  break;
904  case 't':
905  case 'v':
906  case 'm':
907  case 'i':
908  case 's':
909  case 'E':
910  success = listTables(&cmd[1], pattern, show_verbose, show_system);
911  break;
912  case 'r':
913  if (cmd[2] == 'd' && cmd[3] == 's')
914  {
915  char *pattern2 = NULL;
916 
917  if (pattern)
918  pattern2 = psql_scan_slash_option(scan_state,
919  OT_NORMAL, NULL, true);
920  success = listDbRoleSettings(pattern, pattern2);
921 
922  free(pattern2);
923  }
924  else if (cmd[2] == 'g')
925  success = describeRoleGrants(pattern, show_system);
926  else
927  status = PSQL_CMD_UNKNOWN;
928  break;
929  case 'R':
930  switch (cmd[2])
931  {
932  case 'p':
933  if (show_verbose)
934  success = describePublications(pattern);
935  else
936  success = listPublications(pattern);
937  break;
938  case 's':
939  success = describeSubscriptions(pattern, show_verbose);
940  break;
941  default:
942  status = PSQL_CMD_UNKNOWN;
943  }
944  break;
945  case 'u':
946  success = describeRoles(pattern, show_verbose, show_system);
947  break;
948  case 'F': /* text search subsystem */
949  switch (cmd[2])
950  {
951  case '\0':
952  case '+':
953  success = listTSConfigs(pattern, show_verbose);
954  break;
955  case 'p':
956  success = listTSParsers(pattern, show_verbose);
957  break;
958  case 'd':
959  success = listTSDictionaries(pattern, show_verbose);
960  break;
961  case 't':
962  success = listTSTemplates(pattern, show_verbose);
963  break;
964  default:
965  status = PSQL_CMD_UNKNOWN;
966  break;
967  }
968  break;
969  case 'e': /* SQL/MED subsystem */
970  switch (cmd[2])
971  {
972  case 's':
973  success = listForeignServers(pattern, show_verbose);
974  break;
975  case 'u':
976  success = listUserMappings(pattern, show_verbose);
977  break;
978  case 'w':
979  success = listForeignDataWrappers(pattern, show_verbose);
980  break;
981  case 't':
982  success = listForeignTables(pattern, show_verbose);
983  break;
984  default:
985  status = PSQL_CMD_UNKNOWN;
986  break;
987  }
988  break;
989  case 'x': /* Extensions */
990  if (show_verbose)
991  success = listExtensionContents(pattern);
992  else
993  success = listExtensions(pattern);
994  break;
995  case 'X': /* Extended Statistics */
996  success = listExtendedStats(pattern);
997  break;
998  case 'y': /* Event Triggers */
999  success = listEventTriggers(pattern, show_verbose);
1000  break;
1001  default:
1002  status = PSQL_CMD_UNKNOWN;
1003  }
1004 
1005  free(pattern);
1006  }
1007  else
1008  ignore_slash_options(scan_state);
1009 
1010  if (!success)
1011  status = PSQL_CMD_ERROR;
1012 
1013  return status;
1014 }
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:1018
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:5927
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:5576
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3666
bool listOpFamilyFunctions(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:7017
bool listPublications(const char *pattern)
Definition: describe.c:6269
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5199
bool listExtensionContents(const char *pattern)
Definition: describe.c:6105
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:71
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:5780
bool listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
Definition: describe.c:4159
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:6577
bool describeRoleGrants(const char *pattern, bool showSystem)
Definition: describe.c:3882
bool listExtendedStats(const char *pattern)
Definition: describe.c:4746
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:615
bool listOperatorFamilies(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6830
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:5851
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1445
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4435
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:5446
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3813
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4960
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5078
bool listExtensions(const char *pattern)
Definition: describe.c:6054
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3961
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:5511
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:215
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:4842
bool listOpFamilyOperators(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6919
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6729
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:5982
bool describeConfigurationParameters(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4598
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:4666
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1175
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4518
bool permissionsList(const char *pattern, bool showSystem)
Definition: describe.c:1011
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:141
bool listLargeObjects(bool verbose)
Definition: describe.c:7106
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4359
bool describePublications(const char *pattern)
Definition: describe.c:6391
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1252
return true
Definition: isn.c:126

References describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describePublications(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), exec_command_dfo(), free, ignore_slash_options(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), 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(), success, and true.

Referenced by exec_command().

◆ exec_command_dfo()

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

Definition at line 1018 of file command.c.

1021 {
1022  bool success;
1023  char *arg_patterns[FUNC_MAX_ARGS];
1024  int num_arg_patterns = 0;
1025 
1026  /* Collect argument-type patterns too */
1027  if (pattern) /* otherwise it was just \df or \do */
1028  {
1029  char *ap;
1030 
1031  while ((ap = psql_scan_slash_option(scan_state,
1032  OT_NORMAL, NULL, true)) != NULL)
1033  {
1034  arg_patterns[num_arg_patterns++] = ap;
1035  if (num_arg_patterns >= FUNC_MAX_ARGS)
1036  break; /* protect limited-size array */
1037  }
1038  }
1039 
1040  if (cmd[1] == 'f')
1041  success = describeFunctions(&cmd[2], pattern,
1042  arg_patterns, num_arg_patterns,
1043  show_verbose, show_system);
1044  else
1045  success = describeOperators(pattern,
1046  arg_patterns, num_arg_patterns,
1047  show_verbose, show_system);
1048 
1049  while (--num_arg_patterns >= 0)
1050  free(arg_patterns[num_arg_patterns]);
1051 
1052  return success;
1053 }
bool describeFunctions(const char *functypes, const char *func_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:288
bool describeOperators(const char *oper_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:770
#define FUNC_MAX_ARGS

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

Referenced by exec_command_d().

◆ exec_command_echo()

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

Definition at line 1272 of file command.c.

1273 {
1274  if (active_branch)
1275  {
1276  char *value;
1277  char quoted;
1278  bool no_newline = false;
1279  bool first = true;
1280  FILE *fout;
1281 
1282  if (strcmp(cmd, "qecho") == 0)
1283  fout = pset.queryFout;
1284  else if (strcmp(cmd, "warn") == 0)
1285  fout = stderr;
1286  else
1287  fout = stdout;
1288 
1289  while ((value = psql_scan_slash_option(scan_state,
1290  OT_NORMAL, &quoted, false)))
1291  {
1292  if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1293  no_newline = true;
1294  else
1295  {
1296  if (first)
1297  first = false;
1298  else
1299  fputc(' ', fout);
1300  fputs(value, fout);
1301  }
1302  free(value);
1303  }
1304  if (!no_newline)
1305  fputs("\n", fout);
1306  }
1307  else
1308  ignore_slash_options(scan_state);
1309 
1310  return PSQL_CMD_SKIP_LINE;
1311 }
FILE * queryFout
Definition: settings.h:84

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

Referenced by exec_command().

◆ exec_command_edit()

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

Definition at line 1060 of file command.c.

1062 {
1064 
1065  if (active_branch)
1066  {
1067  if (!query_buf)
1068  {
1069  pg_log_error("no query buffer");
1070  status = PSQL_CMD_ERROR;
1071  }
1072  else
1073  {
1074  char *fname;
1075  char *ln = NULL;
1076  int lineno = -1;
1077 
1078  fname = psql_scan_slash_option(scan_state,
1079  OT_NORMAL, NULL, true);
1080  if (fname)
1081  {
1082  /* try to get separate lineno arg */
1083  ln = psql_scan_slash_option(scan_state,
1084  OT_NORMAL, NULL, true);
1085  if (ln == NULL)
1086  {
1087  /* only one arg; maybe it is lineno not fname */
1088  if (fname[0] &&
1089  strspn(fname, "0123456789") == strlen(fname))
1090  {
1091  /* all digits, so assume it is lineno */
1092  ln = fname;
1093  fname = NULL;
1094  }
1095  }
1096  }
1097  if (ln)
1098  {
1099  lineno = atoi(ln);
1100  if (lineno < 1)
1101  {
1102  pg_log_error("invalid line number: %s", ln);
1103  status = PSQL_CMD_ERROR;
1104  }
1105  }
1106  if (status != PSQL_CMD_ERROR)
1107  {
1108  bool discard_on_quit;
1109 
1110  expand_tilde(&fname);
1111  if (fname)
1112  {
1113  canonicalize_path(fname);
1114  /* Always clear buffer if the file isn't modified */
1115  discard_on_quit = true;
1116  }
1117  else
1118  {
1119  /*
1120  * If query_buf is empty, recall previous query for
1121  * editing. But in that case, the query buffer should be
1122  * emptied if editing doesn't modify the file.
1123  */
1124  discard_on_quit = copy_previous_query(query_buf,
1125  previous_buf);
1126  }
1127 
1128  if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1129  status = PSQL_CMD_NEWEDIT;
1130  else
1131  status = PSQL_CMD_ERROR;
1132  }
1133 
1134  /*
1135  * On error while editing or if specifying an incorrect line
1136  * number, reset the query buffer.
1137  */
1138  if (status == PSQL_CMD_ERROR)
1139  resetPQExpBuffer(query_buf);
1140 
1141  free(fname);
1142  free(ln);
1143  }
1144  }
1145  else
1146  ignore_slash_options(scan_state);
1147 
1148  return status;
1149 }
void expand_tilde(char **filename)
Definition: common.c:2180
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:4092
@ PSQL_CMD_NEWEDIT
Definition: command.h:21
void canonicalize_path(char *path)
Definition: path.c:264

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

Referenced by exec_command().

◆ exec_command_ef_ev()

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

Definition at line 1156 of file command.c.

1158 {
1160 
1161  if (active_branch)
1162  {
1163  char *obj_desc = psql_scan_slash_option(scan_state,
1164  OT_WHOLE_LINE,
1165  NULL, true);
1166  int lineno = -1;
1167 
1168  if (!query_buf)
1169  {
1170  pg_log_error("no query buffer");
1171  status = PSQL_CMD_ERROR;
1172  }
1173  else
1174  {
1175  Oid obj_oid = InvalidOid;
1177 
1178  lineno = strip_lineno_from_objdesc(obj_desc);
1179  if (lineno == 0)
1180  {
1181  /* error already reported */
1182  status = PSQL_CMD_ERROR;
1183  }
1184  else if (!obj_desc)
1185  {
1186  /* set up an empty command to fill in */
1187  resetPQExpBuffer(query_buf);
1188  if (is_func)
1189  appendPQExpBufferStr(query_buf,
1190  "CREATE FUNCTION ( )\n"
1191  " RETURNS \n"
1192  " LANGUAGE \n"
1193  " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1194  "AS $function$\n"
1195  "\n$function$\n");
1196  else
1197  appendPQExpBufferStr(query_buf,
1198  "CREATE VIEW AS\n"
1199  " SELECT \n"
1200  " -- something...\n");
1201  }
1202  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1203  {
1204  /* error already reported */
1205  status = PSQL_CMD_ERROR;
1206  }
1207  else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1208  {
1209  /* error already reported */
1210  status = PSQL_CMD_ERROR;
1211  }
1212  else if (is_func && lineno > 0)
1213  {
1214  /*
1215  * lineno "1" should correspond to the first line of the
1216  * function body. We expect that pg_get_functiondef() will
1217  * emit that on a line beginning with "AS ", "BEGIN ", or
1218  * "RETURN ", and that there can be no such line before the
1219  * real start of the function body. Increment lineno by the
1220  * number of lines before that line, so that it becomes
1221  * relative to the first line of the function definition.
1222  */
1223  const char *lines = query_buf->data;
1224 
1225  while (*lines != '\0')
1226  {
1227  if (strncmp(lines, "AS ", 3) == 0 ||
1228  strncmp(lines, "BEGIN ", 6) == 0 ||
1229  strncmp(lines, "RETURN ", 7) == 0)
1230  break;
1231  lineno++;
1232  /* find start of next line */
1233  lines = strchr(lines, '\n');
1234  if (!lines)
1235  break;
1236  lines++;
1237  }
1238  }
1239  }
1240 
1241  if (status != PSQL_CMD_ERROR)
1242  {
1243  bool edited = false;
1244 
1245  if (!do_edit(NULL, query_buf, lineno, true, &edited))
1246  status = PSQL_CMD_ERROR;
1247  else if (!edited)
1248  puts(_("No changes"));
1249  else
1250  status = PSQL_CMD_NEWEDIT;
1251  }
1252 
1253  /*
1254  * On error while doing object lookup or while editing, or if
1255  * specifying an incorrect line number, reset the query buffer.
1256  */
1257  if (status == PSQL_CMD_ERROR)
1258  resetPQExpBuffer(query_buf);
1259 
1260  free(obj_desc);
1261  }
1262  else
1263  ignore_slash_whole_line(scan_state);
1264 
1265  return status;
1266 }
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:5568
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:5508
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:5728
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31

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

Referenced by exec_command().

◆ exec_command_elif()

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

Definition at line 1767 of file command.c.

1769 {
1770  bool success = true;
1771 
1772  switch (conditional_stack_peek(cstack))
1773  {
1774  case IFSTATE_TRUE:
1775 
1776  /*
1777  * Just finished active branch of this \if block. Update saved
1778  * state so we will keep whatever data was put in query_buf by the
1779  * active branch.
1780  */
1781  save_query_text_state(scan_state, cstack, query_buf);
1782 
1783  /*
1784  * Discard \elif expression and ignore the rest until \endif.
1785  * Switch state before reading expression to ensure proper lexer
1786  * behavior.
1787  */
1789  ignore_boolean_expression(scan_state);
1790  break;
1791  case IFSTATE_FALSE:
1792 
1793  /*
1794  * Discard any query text added by the just-skipped branch.
1795  */
1796  discard_query_text(scan_state, cstack, query_buf);
1797 
1798  /*
1799  * Have not yet found a true expression in this \if block, so this
1800  * might be the first. We have to change state before examining
1801  * the expression, or the lexer won't do the right thing.
1802  */
1804  if (!is_true_boolean_expression(scan_state, "\\elif expression"))
1806  break;
1807  case IFSTATE_IGNORED:
1808 
1809  /*
1810  * Discard any query text added by the just-skipped branch.
1811  */
1812  discard_query_text(scan_state, cstack, query_buf);
1813 
1814  /*
1815  * Skip expression and move on. Either the \if block already had
1816  * an active section, or whole block is being skipped.
1817  */
1818  ignore_boolean_expression(scan_state);
1819  break;
1820  case IFSTATE_ELSE_TRUE:
1821  case IFSTATE_ELSE_FALSE:
1822  pg_log_error("\\elif: cannot occur after \\else");
1823  success = false;
1824  break;
1825  case IFSTATE_NONE:
1826  /* no \if to elif from */
1827  pg_log_error("\\elif: no matching \\if");
1828  success = false;
1829  break;
1830  }
1831 
1833 }
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3200
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3099
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:3082
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3180
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:106
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:118
@ IFSTATE_FALSE
Definition: conditional.h:34
@ IFSTATE_ELSE_TRUE
Definition: conditional.h:40
@ IFSTATE_IGNORED
Definition: conditional.h:37
@ IFSTATE_TRUE
Definition: conditional.h:32
@ IFSTATE_NONE
Definition: conditional.h:31
@ IFSTATE_ELSE_FALSE
Definition: conditional.h:42

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

Referenced by exec_command().

◆ exec_command_else()

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

Definition at line 1843 of file command.c.

1845 {
1846  bool success = true;
1847 
1848  switch (conditional_stack_peek(cstack))
1849  {
1850  case IFSTATE_TRUE:
1851 
1852  /*
1853  * Just finished active branch of this \if block. Update saved
1854  * state so we will keep whatever data was put in query_buf by the
1855  * active branch.
1856  */
1857  save_query_text_state(scan_state, cstack, query_buf);
1858 
1859  /* Now skip the \else branch */
1861  break;
1862  case IFSTATE_FALSE:
1863 
1864  /*
1865  * Discard any query text added by the just-skipped branch.
1866  */
1867  discard_query_text(scan_state, cstack, query_buf);
1868 
1869  /*
1870  * We've not found any true \if or \elif expression, so execute
1871  * the \else branch.
1872  */
1874  break;
1875  case IFSTATE_IGNORED:
1876 
1877  /*
1878  * Discard any query text added by the just-skipped branch.
1879  */
1880  discard_query_text(scan_state, cstack, query_buf);
1881 
1882  /*
1883  * Either we previously processed the active branch of this \if,
1884  * or the whole \if block is being skipped. Either way, skip the
1885  * \else branch.
1886  */
1888  break;
1889  case IFSTATE_ELSE_TRUE:
1890  case IFSTATE_ELSE_FALSE:
1891  pg_log_error("\\else: cannot occur after \\else");
1892  success = false;
1893  break;
1894  case IFSTATE_NONE:
1895  /* no \if to else from */
1896  pg_log_error("\\else: no matching \\if");
1897  success = false;
1898  break;
1899  }
1900 
1902 }

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

Referenced by exec_command().

◆ exec_command_encoding()

static backslashResult exec_command_encoding ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1317 of file command.c.

1318 {
1319  if (active_branch)
1320  {
1321  char *encoding = psql_scan_slash_option(scan_state,
1322  OT_NORMAL, NULL, false);
1323 
1324  if (!encoding)
1325  {
1326  /* show encoding */
1328  }
1329  else
1330  {
1331  /* set encoding */
1332  if (PQsetClientEncoding(pset.db, encoding) == -1)
1333  pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1334  else
1335  {
1336  /* save encoding info into psql internal data */
1339  SetVariable(pset.vars, "ENCODING",
1341  }
1342  free(encoding);
1343  }
1344  }
1345  else
1346  ignore_slash_options(scan_state);
1347 
1348  return PSQL_CMD_SKIP_LINE;
1349 }
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7235
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7243
int32 encoding
Definition: pg_database.h:41
#define pg_encoding_to_char
Definition: pg_wchar.h:630
VariableSpace vars
Definition: settings.h:122
int encoding
Definition: settings.h:83
int encoding
Definition: print.h:138
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211

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

Referenced by exec_command().

◆ exec_command_endif()

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

Definition at line 1908 of file command.c.

1910 {
1911  bool success = true;
1912 
1913  switch (conditional_stack_peek(cstack))
1914  {
1915  case IFSTATE_TRUE:
1916  case IFSTATE_ELSE_TRUE:
1917  /* Close the \if block, keeping the query text */
1918  success = conditional_stack_pop(cstack);
1919  Assert(success);
1920  break;
1921  case IFSTATE_FALSE:
1922  case IFSTATE_IGNORED:
1923  case IFSTATE_ELSE_FALSE:
1924 
1925  /*
1926  * Discard any query text added by the just-skipped branch.
1927  */
1928  discard_query_text(scan_state, cstack, query_buf);
1929 
1930  /* Close the \if block */
1931  success = conditional_stack_pop(cstack);
1932  Assert(success);
1933  break;
1934  case IFSTATE_NONE:
1935  /* no \if to end */
1936  pg_log_error("\\endif: no matching \\if");
1937  success = false;
1938  break;
1939  }
1940 
1942 }
bool conditional_stack_pop(ConditionalStack cstack)
Definition: conditional.c:69

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

Referenced by exec_command().

◆ exec_command_errverbose()

static backslashResult exec_command_errverbose ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1355 of file command.c.

1356 {
1357  if (active_branch)
1358  {
1359  if (pset.last_error_result)
1360  {
1361  char *msg;
1362 
1366  if (msg)
1367  {
1368  pg_log_error("%s", msg);
1369  PQfreemem(msg);
1370  }
1371  else
1372  puts(_("out of memory"));
1373  }
1374  else
1375  puts(_("There is no previous error."));
1376  }
1377 
1378  return PSQL_CMD_SKIP_LINE;
1379 }
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3435
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:141
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:133
PGresult * last_error_result
Definition: settings.h:89

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

Referenced by exec_command().

◆ exec_command_f()

static backslashResult exec_command_f ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1385 of file command.c.

1386 {
1387  bool success = true;
1388 
1389  if (active_branch)
1390  {
1391  char *fname = psql_scan_slash_option(scan_state,
1392  OT_NORMAL, NULL, false);
1393 
1394  success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1395  free(fname);
1396  }
1397  else
1398  ignore_slash_options(scan_state);
1399 
1401 }

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

Referenced by exec_command().

◆ exec_command_g()

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

Definition at line 1413 of file command.c.

1414 {
1416  char *fname;
1417 
1418  /*
1419  * Because the option processing for this is fairly complicated, we do it
1420  * and then decide whether the branch is active.
1421  */
1422  fname = psql_scan_slash_option(scan_state,
1423  OT_FILEPIPE, NULL, false);
1424 
1425  if (fname && fname[0] == '(')
1426  {
1427  /* Consume pset options through trailing ')' ... */
1428  status = process_command_g_options(fname + 1, scan_state,
1429  active_branch, cmd);
1430  free(fname);
1431  /* ... and again attempt to scan the filename. */
1432  fname = psql_scan_slash_option(scan_state,
1433  OT_FILEPIPE, NULL, false);
1434  }
1435 
1436  if (status == PSQL_CMD_SKIP_LINE && active_branch)
1437  {
1438  if (!fname)
1439  pset.gfname = NULL;
1440  else
1441  {
1442  expand_tilde(&fname);
1443  pset.gfname = pg_strdup(fname);
1444  }
1445  if (strcmp(cmd, "gx") == 0)
1446  {
1447  /* save settings if not done already, then force expanded=on */
1448  if (pset.gsavepopt == NULL)
1450  pset.popt.topt.expanded = 1;
1451  }
1452  status = PSQL_CMD_SEND;
1453  }
1454 
1455  free(fname);
1456 
1457  return status;
1458 }
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:4993
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1466
@ OT_FILEPIPE
Definition: psqlscanslash.h:20
printQueryOpt * gsavepopt
Definition: settings.h:94
char * gfname
Definition: settings.h:93

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

Referenced by exec_command().

◆ exec_command_gdesc()

static backslashResult exec_command_gdesc ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1541 of file command.c.

1542 {
1544 
1545  if (active_branch)
1546  {
1547  pset.gdesc_flag = true;
1548  status = PSQL_CMD_SEND;
1549  }
1550 
1551  return status;
1552 }
bool gdesc_flag
Definition: settings.h:97

References _psqlSettings::gdesc_flag, pset, PSQL_CMD_SEND, and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_getenv()

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

Definition at line 1558 of file command.c.

1560 {
1561  bool success = true;
1562 
1563  if (active_branch)
1564  {
1565  char *myvar = psql_scan_slash_option(scan_state,
1566  OT_NORMAL, NULL, false);
1567  char *envvar = psql_scan_slash_option(scan_state,
1568  OT_NORMAL, NULL, false);
1569 
1570  if (!myvar || !envvar)
1571  {
1572  pg_log_error("\\%s: missing required argument", cmd);
1573  success = false;
1574  }
1575  else
1576  {
1577  char *envval = getenv(envvar);
1578 
1579  if (envval && !SetVariable(pset.vars, myvar, envval))
1580  success = false;
1581  }
1582  free(myvar);
1583  free(envvar);
1584  }
1585  else
1586  ignore_slash_options(scan_state);
1587 
1589 }

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

Referenced by exec_command().

◆ exec_command_gexec()

static backslashResult exec_command_gexec ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1595 of file command.c.

1596 {
1598 
1599  if (active_branch)
1600  {
1601  pset.gexec_flag = true;
1602  status = PSQL_CMD_SEND;
1603  }
1604 
1605  return status;
1606 }
bool gexec_flag
Definition: settings.h:98

References _psqlSettings::gexec_flag, pset, PSQL_CMD_SEND, and PSQL_CMD_SKIP_LINE.

Referenced by exec_command().

◆ exec_command_gset()

static backslashResult exec_command_gset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1612 of file command.c.

1613 {
1615 
1616  if (active_branch)
1617  {
1618  char *prefix = psql_scan_slash_option(scan_state,
1619  OT_NORMAL, NULL, false);
1620 
1621  if (prefix)
1622  pset.gset_prefix = prefix;
1623  else
1624  {
1625  /* we must set a non-NULL prefix to trigger storing */
1626  pset.gset_prefix = pg_strdup("");
1627  }
1628  /* gset_prefix is freed later */
1629  status = PSQL_CMD_SEND;
1630  }
1631  else
1632  ignore_slash_options(scan_state);
1633 
1634  return status;
1635 }
char * gset_prefix
Definition: settings.h:96

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

Referenced by exec_command().

◆ exec_command_help()

static backslashResult exec_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1641 of file command.c.

1642 {
1643  if (active_branch)
1644  {
1645  char *opt = psql_scan_slash_option(scan_state,
1646  OT_WHOLE_LINE, NULL, true);
1647 
1648  helpSQL(opt, pset.popt.topt.pager);
1649  free(opt);
1650  }
1651  else
1652  ignore_slash_whole_line(scan_state);
1653 
1654  return PSQL_CMD_SKIP_LINE;
1655 }
void helpSQL(const char *topic, unsigned short int pager)

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

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1661 of file command.c.

1662 {
1663  bool success = true;
1664 
1665  if (active_branch)
1666  {
1667  if (pset.popt.topt.format != PRINT_HTML)
1668  success = do_pset("format", "html", &pset.popt, pset.quiet);
1669  else
1670  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1671  }
1672 
1674 }

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

Referenced by exec_command().

◆ exec_command_if()

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

Definition at line 1721 of file command.c.

1723 {
1724  if (conditional_active(cstack))
1725  {
1726  /*
1727  * First, push a new active stack entry; this ensures that the lexer
1728  * will perform variable substitution and backtick evaluation while
1729  * scanning the expression. (That should happen anyway, since we know
1730  * we're in an active outer branch, but let's be sure.)
1731  */
1733 
1734  /* Remember current query state in case we need to restore later */
1735  save_query_text_state(scan_state, cstack, query_buf);
1736 
1737  /*
1738  * Evaluate the expression; if it's false, change to inactive state.
1739  */
1740  if (!is_true_boolean_expression(scan_state, "\\if expression"))
1742  }
1743  else
1744  {
1745  /*
1746  * We're within an inactive outer branch, so this entire \if block
1747  * will be ignored. We don't want to evaluate the expression, so push
1748  * the "ignored" stack state before scanning it.
1749  */
1751 
1752  /* Remember current query state in case we need to restore later */
1753  save_query_text_state(scan_state, cstack, query_buf);
1754 
1755  ignore_boolean_expression(scan_state);
1756  }
1757 
1758  return PSQL_CMD_SKIP_LINE;
1759 }
void conditional_stack_push(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:53

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

Referenced by exec_command().

◆ exec_command_include()

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

Definition at line 1680 of file command.c.

1681 {
1682  bool success = true;
1683 
1684  if (active_branch)
1685  {
1686  char *fname = psql_scan_slash_option(scan_state,
1687  OT_NORMAL, NULL, true);
1688 
1689  if (!fname)
1690  {
1691  pg_log_error("\\%s: missing required argument", cmd);
1692  success = false;
1693  }
1694  else
1695  {
1696  bool include_relative;
1697 
1698  include_relative = (strcmp(cmd, "ir") == 0
1699  || strcmp(cmd, "include_relative") == 0);
1700  expand_tilde(&fname);
1701  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1702  free(fname);
1703  }
1704  }
1705  else
1706  ignore_slash_options(scan_state);
1707 
1709 }
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4287
#define EXIT_SUCCESS
Definition: settings.h:163

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

Referenced by exec_command().

◆ exec_command_list()

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

Definition at line 1948 of file command.c.

1949 {
1950  bool success = true;
1951 
1952  if (active_branch)
1953  {
1954  char *pattern;
1955  bool show_verbose;
1956 
1957  pattern = psql_scan_slash_option(scan_state,
1958  OT_NORMAL, NULL, true);
1959 
1960  show_verbose = strchr(cmd, '+') ? true : false;
1961 
1962  success = listAllDbs(pattern, show_verbose);
1963 
1964  free(pattern);
1965  }
1966  else
1967  ignore_slash_options(scan_state);
1968 
1970 }
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:911

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

Referenced by exec_command().

◆ exec_command_lo()

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

Definition at line 1976 of file command.c.

1977 {
1979  bool success = true;
1980 
1981  if (active_branch)
1982  {
1983  char *opt1,
1984  *opt2;
1985 
1986  opt1 = psql_scan_slash_option(scan_state,
1987  OT_NORMAL, NULL, true);
1988  opt2 = psql_scan_slash_option(scan_state,
1989  OT_NORMAL, NULL, true);
1990 
1991  if (strcmp(cmd + 3, "export") == 0)
1992  {
1993  if (!opt2)
1994  {
1995  pg_log_error("\\%s: missing required argument", cmd);
1996  success = false;
1997  }
1998  else
1999  {
2000  expand_tilde(&opt2);
2001  success = do_lo_export(opt1, opt2);
2002  }
2003  }
2004 
2005  else if (strcmp(cmd + 3, "import") == 0)
2006  {
2007  if (!opt1)
2008  {
2009  pg_log_error("\\%s: missing required argument", cmd);
2010  success = false;
2011  }
2012  else
2013  {
2014  expand_tilde(&opt1);
2015  success = do_lo_import(opt1, opt2);
2016  }
2017  }
2018 
2019  else if (strcmp(cmd + 3, "list") == 0)
2020  success = listLargeObjects(false);
2021  else if (strcmp(cmd + 3, "list+") == 0)
2022  success = listLargeObjects(true);
2023 
2024  else if (strcmp(cmd + 3, "unlink") == 0)
2025  {
2026  if (!opt1)
2027  {
2028  pg_log_error("\\%s: missing required argument", cmd);
2029  success = false;
2030  }
2031  else
2032  success = do_lo_unlink(opt1);
2033  }
2034 
2035  else
2036  status = PSQL_CMD_UNKNOWN;
2037 
2038  free(opt1);
2039  free(opt2);
2040  }
2041  else
2042  ignore_slash_options(scan_state);
2043 
2044  if (!success)
2045  status = PSQL_CMD_ERROR;
2046 
2047  return status;
2048 }
bool do_lo_export(const char *loid_arg, const char *filename_arg)
Definition: large_obj.c:142
bool do_lo_import(const char *filename_arg, const char *comment_arg)
Definition: large_obj.c:176
bool do_lo_unlink(const char *loid_arg)
Definition: large_obj.c:239

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

Referenced by exec_command().

◆ exec_command_out()

static backslashResult exec_command_out ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2054 of file command.c.

2055 {
2056  bool success = true;
2057 
2058  if (active_branch)
2059  {
2060  char *fname = psql_scan_slash_option(scan_state,
2061  OT_FILEPIPE, NULL, true);
2062 
2063  expand_tilde(&fname);
2064  success = setQFout(fname);
2065  free(fname);
2066  }
2067  else
2068  ignore_slash_filepipe(scan_state);
2069 
2071 }
bool setQFout(const char *fname)
Definition: common.c:132
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:3132

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

Referenced by exec_command().

◆ exec_command_password()

static backslashResult exec_command_password ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2103 of file command.c.

2104 {
2105  bool success = true;
2106 
2107  if (active_branch)
2108  {
2109  char *user = psql_scan_slash_option(scan_state,
2110  OT_SQLID, NULL, true);
2111  char *pw1 = NULL;
2112  char *pw2 = NULL;
2114  PromptInterruptContext prompt_ctx;
2115 
2116  if (user == NULL)
2117  {
2118  /* By default, the command applies to CURRENT_USER */
2119  PGresult *res;
2120 
2121  res = PSQLexec("SELECT CURRENT_USER");
2122  if (!res)
2123  return PSQL_CMD_ERROR;
2124 
2125  user = pg_strdup(PQgetvalue(res, 0, 0));
2126  PQclear(res);
2127  }
2128 
2129  /* Set up to let SIGINT cancel simple_prompt_extended() */
2130  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2131  prompt_ctx.enabled = &sigint_interrupt_enabled;
2132  prompt_ctx.canceled = false;
2133 
2134  initPQExpBuffer(&buf);
2135  printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2136 
2137  pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2138  if (!prompt_ctx.canceled)
2139  pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2140 
2141  if (prompt_ctx.canceled)
2142  {
2143  /* fail silently */
2144  success = false;
2145  }
2146  else if (strcmp(pw1, pw2) != 0)
2147  {
2148  pg_log_error("Passwords didn't match.");
2149  success = false;
2150  }
2151  else
2152  {
2154 
2156  {
2158  success = false;
2159  }
2160 
2161  PQclear(res);
2162  }
2163 
2164  free(user);
2165  free(pw1);
2166  free(pw2);
2167  termPQExpBuffer(&buf);
2168  }
2169  else
2170  ignore_slash_options(scan_state);
2171 
2173 }
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:292
PGresult * PSQLexec(const char *query)
Definition: common.c:620
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:294
PGresult * PQchangePassword(PGconn *conn, const char *user, const char *passwd)
Definition: fe-auth.c:1400
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
@ OT_SQLID
Definition: psqlscanslash.h:18
char * simple_prompt_extended(const char *prompt, bool echo, PromptInterruptContext *prompt_ctx)
Definition: sprompt.c:53
volatile sig_atomic_t * enabled
Definition: string.h:21

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

Referenced by exec_command().

◆ exec_command_print()

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

Definition at line 2077 of file command.c.

2079 {
2080  if (active_branch)
2081  {
2082  /*
2083  * We want to print the same thing \g would execute, but not to change
2084  * the query buffer state; so we can't use copy_previous_query().
2085  * Also, beware of possibility that buffer pointers are NULL.
2086  */
2087  if (query_buf && query_buf->len > 0)
2088  puts(query_buf->data);
2089  else if (previous_buf && previous_buf->len > 0)
2090  puts(previous_buf->data);
2091  else if (!pset.quiet)
2092  puts(_("Query buffer is empty."));
2093  fflush(stdout);
2094  }
2095 
2096  return PSQL_CMD_SKIP_LINE;
2097 }

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

Referenced by exec_command().

◆ exec_command_prompt()

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

Definition at line 2179 of file command.c.

2181 {
2182  bool success = true;
2183 
2184  if (active_branch)
2185  {
2186  char *opt,
2187  *prompt_text = NULL;
2188  char *arg1,
2189  *arg2;
2190 
2191  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2192  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2193 
2194  if (!arg1)
2195  {
2196  pg_log_error("\\%s: missing required argument", cmd);
2197  success = false;
2198  }
2199  else
2200  {
2201  char *result;
2202  PromptInterruptContext prompt_ctx;
2203 
2204  /* Set up to let SIGINT cancel simple_prompt_extended() */
2205  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2206  prompt_ctx.enabled = &sigint_interrupt_enabled;
2207  prompt_ctx.canceled = false;
2208 
2209  if (arg2)
2210  {
2211  prompt_text = arg1;
2212  opt = arg2;
2213  }
2214  else
2215  opt = arg1;
2216 
2217  if (!pset.inputfile)
2218  {
2219  result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2220  }
2221  else
2222  {
2223  if (prompt_text)
2224  {
2225  fputs(prompt_text, stdout);
2226  fflush(stdout);
2227  }
2228  result = gets_fromFile(stdin);
2229  if (!result)
2230  {
2231  pg_log_error("\\%s: could not read value for variable",
2232  cmd);
2233  success = false;
2234  }
2235  }
2236 
2237  if (prompt_ctx.canceled ||
2238  (result && !SetVariable(pset.vars, opt, result)))
2239  success = false;
2240 
2241  free(result);
2242  free(prompt_text);
2243  free(opt);
2244  }
2245  }
2246  else
2247  ignore_slash_options(scan_state);
2248 
2250 }
char * gets_fromFile(FILE *source)
Definition: input.c:186
char * inputfile
Definition: settings.h:114

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

Referenced by exec_command().

◆ exec_command_pset()

static backslashResult exec_command_pset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2256 of file command.c.

2257 {
2258  bool success = true;
2259 
2260  if (active_branch)
2261  {
2262  char *opt0 = psql_scan_slash_option(scan_state,
2263  OT_NORMAL, NULL, false);
2264  char *opt1 = psql_scan_slash_option(scan_state,
2265  OT_NORMAL, NULL, false);
2266 
2267  if (!opt0)
2268  {
2269  /* list all variables */
2270 
2271  int i;
2272  static const char *const my_list[] = {
2273  "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2274  "fieldsep_zero", "footer", "format", "linestyle", "null",
2275  "numericlocale", "pager", "pager_min_lines",
2276  "recordsep", "recordsep_zero",
2277  "tableattr", "title", "tuples_only",
2278  "unicode_border_linestyle",
2279  "unicode_column_linestyle",
2280  "unicode_header_linestyle",
2281  "xheader_width",
2282  NULL
2283  };
2284 
2285  for (i = 0; my_list[i] != NULL; i++)
2286  {
2287  char *val = pset_value_string(my_list[i], &pset.popt);
2288 
2289  printf("%-24s %s\n", my_list[i], val);
2290  free(val);
2291  }
2292 
2293  success = true;
2294  }
2295  else
2296  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2297 
2298  free(opt0);
2299  free(opt1);
2300  }
2301  else
2302  ignore_slash_options(scan_state);
2303 
2305 }
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:5100
long val
Definition: informix.c:670

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

Referenced by exec_command().

◆ exec_command_quit()

static backslashResult exec_command_quit ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2311 of file command.c.

2312 {
2314 
2315  if (active_branch)
2316  status = PSQL_CMD_TERMINATE;
2317 
2318  return status;
2319 }
@ PSQL_CMD_TERMINATE
Definition: command.h:20

References PSQL_CMD_SKIP_LINE, and PSQL_CMD_TERMINATE.

Referenced by exec_command().

◆ exec_command_reset()

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

Definition at line 2325 of file command.c.

2327 {
2328  if (active_branch)
2329  {
2330  resetPQExpBuffer(query_buf);
2331  psql_scan_reset(scan_state);
2332  if (!pset.quiet)
2333  puts(_("Query buffer reset (cleared)."));
2334  }
2335 
2336  return PSQL_CMD_SKIP_LINE;
2337 }
void psql_scan_reset(PsqlScanState state)

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

Referenced by exec_command().

◆ exec_command_s()

static backslashResult exec_command_s ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2343 of file command.c.

2344 {
2345  bool success = true;
2346 
2347  if (active_branch)
2348  {
2349  char *fname = psql_scan_slash_option(scan_state,
2350  OT_NORMAL, NULL, true);
2351 
2352  expand_tilde(&fname);
2353  success = printHistory(fname, pset.popt.topt.pager);
2354  if (success && !pset.quiet && fname)
2355  printf(_("Wrote history to file \"%s\".\n"), fname);
2356  if (!fname)
2357  putchar('\n');
2358  free(fname);
2359  }
2360  else
2361  ignore_slash_options(scan_state);
2362 
2364 }
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:494

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

Referenced by exec_command().

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2370 of file command.c.

2371 {
2372  bool success = true;
2373 
2374  if (active_branch)
2375  {
2376  char *opt0 = psql_scan_slash_option(scan_state,
2377  OT_NORMAL, NULL, false);
2378 
2379  if (!opt0)
2380  {
2381  /* list all variables */
2383  success = true;
2384  }
2385  else
2386  {
2387  /*
2388  * Set variable to the concatenation of the arguments.
2389  */
2390  char *newval;
2391  char *opt;
2392 
2393  opt = psql_scan_slash_option(scan_state,
2394  OT_NORMAL, NULL, false);
2395  newval = pg_strdup(opt ? opt : "");
2396  free(opt);
2397 
2398  while ((opt = psql_scan_slash_option(scan_state,
2399  OT_NORMAL, NULL, false)))
2400  {
2401  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2402  strcat(newval, opt);
2403  free(opt);
2404  }
2405 
2406  if (!SetVariable(pset.vars, opt0, newval))
2407  success = false;
2408 
2409  free(newval);
2410  }
2411  free(opt0);
2412  }
2413  else
2414  ignore_slash_options(scan_state);
2415 
2417 }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define newval
void PrintVariables(VariableSpace space)
Definition: variables.c:186

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

Referenced by exec_command().

◆ exec_command_setenv()

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

Definition at line 2423 of file command.c.

2425 {
2426  bool success = true;
2427 
2428  if (active_branch)
2429  {
2430  char *envvar = psql_scan_slash_option(scan_state,
2431  OT_NORMAL, NULL, false);
2432  char *envval = psql_scan_slash_option(scan_state,
2433  OT_NORMAL, NULL, false);
2434 
2435  if (!envvar)
2436  {
2437  pg_log_error("\\%s: missing required argument", cmd);
2438  success = false;
2439  }
2440  else if (strchr(envvar, '=') != NULL)
2441  {
2442  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2443  cmd);
2444  success = false;
2445  }
2446  else if (!envval)
2447  {
2448  /* No argument - unset the environment variable */
2449  unsetenv(envvar);
2450  success = true;
2451  }
2452  else
2453  {
2454  /* Set variable to the value of the next argument */
2455  setenv(envvar, envval, 1);
2456  success = true;
2457  }
2458  free(envvar);
2459  free(envval);
2460  }
2461  else
2462  ignore_slash_options(scan_state);
2463 
2465 }
#define unsetenv(x)
Definition: win32_port.h:538
#define setenv(x, y, z)
Definition: win32_port.h:537

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

Referenced by exec_command().

◆ exec_command_sf_sv()

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

Definition at line 2471 of file command.c.

2473 {
2475 
2476  if (active_branch)
2477  {
2478  bool show_linenumbers = (strchr(cmd, '+') != NULL);
2479  PQExpBuffer buf;
2480  char *obj_desc;
2481  Oid obj_oid = InvalidOid;
2483 
2484  buf = createPQExpBuffer();
2485  obj_desc = psql_scan_slash_option(scan_state,
2486  OT_WHOLE_LINE, NULL, true);
2487  if (!obj_desc)
2488  {
2489  if (is_func)
2490  pg_log_error("function name is required");
2491  else
2492  pg_log_error("view name is required");
2493  status = PSQL_CMD_ERROR;
2494  }
2495  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2496  {
2497  /* error already reported */
2498  status = PSQL_CMD_ERROR;
2499  }
2500  else if (!get_create_object_cmd(eot, obj_oid, buf))
2501  {
2502  /* error already reported */
2503  status = PSQL_CMD_ERROR;
2504  }
2505  else
2506  {
2507  FILE *output;
2508  bool is_pager;
2509 
2510  /* Select output stream: stdout, pager, or file */
2511  if (pset.queryFout == stdout)
2512  {
2513  /* count lines in function to see if pager is needed */
2514  int lineno = count_lines_in_buf(buf);
2515 
2516  output = PageOutput(lineno, &(pset.popt.topt));
2517  is_pager = true;
2518  }
2519  else
2520  {
2521  /* use previously set output file, without pager */
2522  output = pset.queryFout;
2523  is_pager = false;
2524  }
2525 
2526  if (show_linenumbers)
2527  {
2528  /* add line numbers */
2529  print_with_linenumbers(output, buf->data, is_func);
2530  }
2531  else
2532  {
2533  /* just send the definition to output */
2534  fputs(buf->data, output);
2535  }
2536 
2537  if (is_pager)
2538  ClosePager(output);
2539  }
2540 
2541  free(obj_desc);
2543  }
2544  else
2545  ignore_slash_whole_line(scan_state);
2546 
2547  return status;
2548 }
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:5786
static void print_with_linenumbers(FILE *output, char *lines, bool is_func)
Definition: command.c:5816
void ClosePager(FILE *pagerpipe)
Definition: print.c:3141
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:3089
FILE * output
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114

References buf, ClosePager(), count_lines_in_buf(), createPQExpBuffer(), destroyPQExpBuffer(), EditableFunction, EditableView, 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, generate_unaccent_rules::stdout, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_shell_escape()

static backslashResult exec_command_shell_escape ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2959 of file command.c.

2960 {
2961  bool success = true;
2962 
2963  if (active_branch)
2964  {
2965  char *opt = psql_scan_slash_option(scan_state,
2966  OT_WHOLE_LINE, NULL, false);
2967 
2968  success = do_shell(opt);
2969  free(opt);
2970  }
2971  else
2972  ignore_slash_whole_line(scan_state);
2973 
2975 }
static bool do_shell(const char *command)
Definition: command.c:5189

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

Referenced by exec_command().

◆ exec_command_slash_command_help()

static backslashResult exec_command_slash_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2981 of file command.c.

2982 {
2983  if (active_branch)
2984  {
2985  char *opt0 = psql_scan_slash_option(scan_state,
2986  OT_NORMAL, NULL, false);
2987 
2988  if (!opt0 || strcmp(opt0, "commands") == 0)
2990  else if (strcmp(opt0, "options") == 0)
2992  else if (strcmp(opt0, "variables") == 0)
2994  else
2996 
2997  free(opt0);
2998  }
2999  else
3000  ignore_slash_options(scan_state);
3001 
3002  return PSQL_CMD_SKIP_LINE;
3003 }
void slashUsage(unsigned short int pager)
Definition: help.c:151
void helpVariables(unsigned short int pager)
static void usage(const char *progname)
Definition: vacuumlo.c:414

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

Referenced by exec_command().

◆ exec_command_t()

static backslashResult exec_command_t ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2554 of file command.c.

2555 {
2556  bool success = true;
2557 
2558  if (active_branch)
2559  {
2560  char *opt = psql_scan_slash_option(scan_state,
2561  OT_NORMAL, NULL, true);
2562 
2563  success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
2564  free(opt);
2565  }
2566  else
2567  ignore_slash_options(scan_state);
2568 
2570 }

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

Referenced by exec_command().

◆ exec_command_T()

static backslashResult exec_command_T ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2576 of file command.c.

2577 {
2578  bool success = true;
2579 
2580  if (active_branch)
2581  {
2582  char *value = psql_scan_slash_option(scan_state,
2583  OT_NORMAL, NULL, false);
2584 
2585  success = do_pset("tableattr", value, &pset.popt, pset.quiet);
2586  free(value);
2587  }
2588  else
2589  ignore_slash_options(scan_state);
2590 
2592 }

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

Referenced by exec_command().

◆ exec_command_timing()

static backslashResult exec_command_timing ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2598 of file command.c.

2599 {
2600  bool success = true;
2601 
2602  if (active_branch)
2603  {
2604  char *opt = psql_scan_slash_option(scan_state,
2605  OT_NORMAL, NULL, false);
2606 
2607  if (opt)
2608  success = ParseVariableBool(opt, "\\timing", &pset.timing);
2609  else
2610  pset.timing = !pset.timing;
2611  if (!pset.quiet)
2612  {
2613  if (pset.timing)
2614  puts(_("Timing is on."));
2615  else
2616  puts(_("Timing is off."));
2617  }
2618  free(opt);
2619  }
2620  else
2621  ignore_slash_options(scan_state);
2622 
2624 }

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

Referenced by exec_command().

◆ exec_command_unset()

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

Definition at line 2630 of file command.c.

2632 {
2633  bool success = true;
2634 
2635  if (active_branch)
2636  {
2637  char *opt = psql_scan_slash_option(scan_state,
2638  OT_NORMAL, NULL, false);
2639 
2640  if (!opt)
2641  {
2642  pg_log_error("\\%s: missing required argument", cmd);
2643  success = false;
2644  }
2645  else if (!SetVariable(pset.vars, opt, NULL))
2646  success = false;
2647 
2648  free(opt);
2649  }
2650  else
2651  ignore_slash_options(scan_state);
2652 
2654 }

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

Referenced by exec_command().

◆ exec_command_watch()

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

Definition at line 2762 of file command.c.

2764 {
2765  bool success = true;
2766 
2767  if (active_branch)
2768  {
2769  bool have_sleep = false;
2770  bool have_iter = false;
2771  bool have_min_rows = false;
2772  double sleep = 2;
2773  int iter = 0;
2774  int min_rows = 0;
2775 
2776  /*
2777  * Parse arguments. We allow either an unlabeled interval or
2778  * "name=value", where name is from the set ('i', 'interval', 'c',
2779  * 'count', 'm', 'min_rows').
2780  */
2781  while (success)
2782  {
2783  char *opt = psql_scan_slash_option(scan_state,
2784  OT_NORMAL, NULL, true);
2785  char *valptr;
2786  char *opt_end;
2787 
2788  if (!opt)
2789  break; /* no more arguments */
2790 
2791  valptr = strchr(opt, '=');
2792  if (valptr)
2793  {
2794  /* Labeled argument */
2795  valptr++;
2796  if (strncmp("i=", opt, strlen("i=")) == 0 ||
2797  strncmp("interval=", opt, strlen("interval=")) == 0)
2798  {
2799  if (have_sleep)
2800  {
2801  pg_log_error("\\watch: interval value is specified more than once");
2802  success = false;
2803  }
2804  else
2805  {
2806  have_sleep = true;
2807  errno = 0;
2808  sleep = strtod(valptr, &opt_end);
2809  if (sleep < 0 || *opt_end || errno == ERANGE)
2810  {
2811  pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
2812  success = false;
2813  }
2814  }
2815  }
2816  else if (strncmp("c=", opt, strlen("c=")) == 0 ||
2817  strncmp("count=", opt, strlen("count=")) == 0)
2818  {
2819  if (have_iter)
2820  {
2821  pg_log_error("\\watch: iteration count is specified more than once");
2822  success = false;
2823  }
2824  else
2825  {
2826  have_iter = true;
2827  errno = 0;
2828  iter = strtoint(valptr, &opt_end, 10);
2829  if (iter <= 0 || *opt_end || errno == ERANGE)
2830  {
2831  pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
2832  success = false;
2833  }
2834  }
2835  }
2836  else if (strncmp("m=", opt, strlen("m=")) == 0 ||
2837  strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
2838  {
2839  if (have_min_rows)
2840  {
2841  pg_log_error("\\watch: minimum row count specified more than once");
2842  success = false;
2843  }
2844  else
2845  {
2846  have_min_rows = true;
2847  errno = 0;
2848  min_rows = strtoint(valptr, &opt_end, 10);
2849  if (min_rows <= 0 || *opt_end || errno == ERANGE)
2850  {
2851  pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
2852  success = false;
2853  }
2854  }
2855  }
2856  else
2857  {
2858  pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
2859  success = false;
2860  }
2861  }
2862  else
2863  {
2864  /* Unlabeled argument: take it as interval */
2865  if (have_sleep)
2866  {
2867  pg_log_error("\\watch: interval value is specified more than once");
2868  success = false;
2869  }
2870  else
2871  {
2872  have_sleep = true;
2873  errno = 0;
2874  sleep = strtod(opt, &opt_end);
2875  if (sleep < 0 || *opt_end || errno == ERANGE)
2876  {
2877  pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
2878  success = false;
2879  }
2880  }
2881  }
2882 
2883  free(opt);
2884  }
2885 
2886  /* If we parsed arguments successfully, do the command */
2887  if (success)
2888  {
2889  /* If query_buf is empty, recall and execute previous query */
2890  (void) copy_previous_query(query_buf, previous_buf);
2891 
2892  success = do_watch(query_buf, sleep, iter, min_rows);
2893  }
2894 
2895  /* Reset the query buffer as though for \r */
2896  resetPQExpBuffer(query_buf);
2897  psql_scan_reset(scan_state);
2898  }
2899  else
2900  ignore_slash_options(scan_state);
2901 
2903 }
static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
Definition: command.c:5236
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
Definition: string.c:51

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

Referenced by exec_command().

◆ exec_command_write()

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

Definition at line 2660 of file command.c.

2663 {
2665 
2666  if (active_branch)
2667  {
2668  char *fname = psql_scan_slash_option(scan_state,
2669  OT_FILEPIPE, NULL, true);
2670  FILE *fd = NULL;
2671  bool is_pipe = false;
2672 
2673  if (!query_buf)
2674  {
2675  pg_log_error("no query buffer");
2676  status = PSQL_CMD_ERROR;
2677  }
2678  else
2679  {
2680  if (!fname)
2681  {
2682  pg_log_error("\\%s: missing required argument", cmd);
2683  status = PSQL_CMD_ERROR;
2684  }
2685  else
2686  {
2687  expand_tilde(&fname);
2688  if (fname[0] == '|')
2689  {
2690  is_pipe = true;
2691  fflush(NULL);
2693  fd = popen(&fname[1], "w");
2694  }
2695  else
2696  {
2697  canonicalize_path(fname);
2698  fd = fopen(fname, "w");
2699  }
2700  if (!fd)
2701  {
2702  pg_log_error("%s: %m", fname);
2703  status = PSQL_CMD_ERROR;
2704  }
2705  }
2706  }
2707 
2708  if (fd)
2709  {
2710  int result;
2711 
2712  /*
2713  * We want to print the same thing \g would execute, but not to
2714  * change the query buffer state; so we can't use
2715  * copy_previous_query(). Also, beware of possibility that buffer
2716  * pointers are NULL.
2717  */
2718  if (query_buf && query_buf->len > 0)
2719  fprintf(fd, "%s\n", query_buf->data);
2720  else if (previous_buf && previous_buf->len > 0)
2721  fprintf(fd, "%s\n", previous_buf->data);
2722 
2723  if (is_pipe)
2724  {
2725  result = pclose(fd);
2726 
2727  if (result != 0)
2728  {
2729  pg_log_error("%s: %s", fname, wait_result_to_str(result));
2730  status = PSQL_CMD_ERROR;
2731  }
2732  SetShellResultVariables(result);
2733  }
2734  else
2735  {
2736  result = fclose(fd);
2737 
2738  if (result == EOF)
2739  {
2740  pg_log_error("%s: %m", fname);
2741  status = PSQL_CMD_ERROR;
2742  }
2743  }
2744  }
2745 
2746  if (is_pipe)
2748 
2749  free(fname);
2750  }
2751  else
2752  ignore_slash_filepipe(scan_state);
2753 
2754  return status;
2755 }
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33

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

Referenced by exec_command().

◆ exec_command_x()

static backslashResult exec_command_x ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2909 of file command.c.

2910 {
2911  bool success = true;
2912 
2913  if (active_branch)
2914  {
2915  char *opt = psql_scan_slash_option(scan_state,
2916  OT_NORMAL, NULL, true);
2917 
2918  success = do_pset("expanded", opt, &pset.popt, pset.quiet);
2919  free(opt);
2920  }
2921  else
2922  ignore_slash_options(scan_state);
2923 
2925 }

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

Referenced by exec_command().

◆ exec_command_z()

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

Definition at line 2931 of file command.c.

2932 {
2933  bool success = true;
2934 
2935  if (active_branch)
2936  {
2937  char *pattern;
2938  bool show_system;
2939 
2940  pattern = psql_scan_slash_option(scan_state,
2941  OT_NORMAL, NULL, true);
2942 
2943  show_system = strchr(cmd, 'S') ? true : false;
2944 
2945  success = permissionsList(pattern, show_system);
2946 
2947  free(pattern);
2948  }
2949  else
2950  ignore_slash_options(scan_state);
2951 
2953 }

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

Referenced by exec_command().

◆ gather_boolean_expression()

static PQExpBuffer gather_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3052 of file command.c.

3053 {
3054  PQExpBuffer exp_buf = createPQExpBuffer();
3055  int num_options = 0;
3056  char *value;
3057 
3058  /* collect all arguments for the conditional command into exp_buf */
3059  while ((value = psql_scan_slash_option(scan_state,
3060  OT_NORMAL, NULL, false)) != NULL)
3061  {
3062  /* add spaces between tokens */
3063  if (num_options > 0)
3064  appendPQExpBufferChar(exp_buf, ' ');
3065  appendPQExpBufferStr(exp_buf, value);
3066  num_options++;
3067  free(value);
3068  }
3069 
3070  return exp_buf;
3071 }

References appendPQExpBufferChar(), appendPQExpBufferStr(), createPQExpBuffer(), free, OT_NORMAL, psql_scan_slash_option(), and value.

Referenced by ignore_boolean_expression(), and is_true_boolean_expression().

◆ get_create_object_cmd()

static bool get_create_object_cmd ( EditableObjectType  obj_type,
Oid  oid,
PQExpBuffer  buf 
)
static

Definition at line 5568 of file command.c.

5570 {
5571  bool result = true;
5572  PQExpBuffer query = createPQExpBuffer();
5573  PGresult *res;
5574 
5575  switch (obj_type)
5576  {
5577  case EditableFunction:
5578  printfPQExpBuffer(query,
5579  "SELECT pg_catalog.pg_get_functiondef(%u)",
5580  oid);
5581  break;
5582 
5583  case EditableView:
5584 
5585  /*
5586  * pg_get_viewdef() just prints the query, so we must prepend
5587  * CREATE for ourselves. We must fully qualify the view name to
5588  * ensure the right view gets replaced. Also, check relation kind
5589  * to be sure it's a view.
5590  *
5591  * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
5592  * CHECK OPTION. These are not part of the view definition
5593  * returned by pg_get_viewdef() and so need to be retrieved
5594  * separately. Materialized views (introduced in 9.3) may have
5595  * arbitrary storage parameter reloptions.
5596  */
5597  if (pset.sversion >= 90400)
5598  {
5599  printfPQExpBuffer(query,
5600  "SELECT nspname, relname, relkind, "
5601  "pg_catalog.pg_get_viewdef(c.oid, true), "
5602  "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5603  "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5604  "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
5605  "FROM pg_catalog.pg_class c "
5606  "LEFT JOIN pg_catalog.pg_namespace n "
5607  "ON c.relnamespace = n.oid WHERE c.oid = %u",
5608  oid);
5609  }
5610  else
5611  {
5612  printfPQExpBuffer(query,
5613  "SELECT nspname, relname, relkind, "
5614  "pg_catalog.pg_get_viewdef(c.oid, true), "
5615  "c.reloptions AS reloptions, "
5616  "NULL AS checkoption "
5617  "FROM pg_catalog.pg_class c "
5618  "LEFT JOIN pg_catalog.pg_namespace n "
5619  "ON c.relnamespace = n.oid WHERE c.oid = %u",
5620  oid);
5621  }
5622  break;
5623  }
5624 
5625  if (!echo_hidden_command(query->data))
5626  {
5627  destroyPQExpBuffer(query);
5628  return false;
5629  }
5630  res = PQexec(pset.db, query->data);
5631  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
5632  {
5634  switch (obj_type)
5635  {
5636  case EditableFunction:
5638  break;
5639 
5640  case EditableView:
5641  {
5642  char *nspname = PQgetvalue(res, 0, 0);
5643  char *relname = PQgetvalue(res, 0, 1);
5644  char *relkind = PQgetvalue(res, 0, 2);
5645  char *viewdef = PQgetvalue(res, 0, 3);
5646  char *reloptions = PQgetvalue(res, 0, 4);
5647  char *checkoption = PQgetvalue(res, 0, 5);
5648 
5649  /*
5650  * If the backend ever supports CREATE OR REPLACE
5651  * MATERIALIZED VIEW, allow that here; but as of today it
5652  * does not, so editing a matview definition in this way
5653  * is impossible.
5654  */
5655  switch (relkind[0])
5656  {
5657 #ifdef NOT_USED
5658  case RELKIND_MATVIEW:
5659  appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
5660  break;
5661 #endif
5662  case RELKIND_VIEW:
5663  appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
5664  break;
5665  default:
5666  pg_log_error("\"%s.%s\" is not a view",
5667  nspname, relname);
5668  result = false;
5669  break;
5670  }
5671  appendPQExpBuffer(buf, "%s.", fmtId(nspname));
5673 
5674  /* reloptions, if not an empty array "{}" */
5675  if (reloptions != NULL && strlen(reloptions) > 2)
5676  {
5677  appendPQExpBufferStr(buf, "\n WITH (");
5678  if (!appendReloptionsArray(buf, reloptions, "",
5679  pset.encoding,
5680  standard_strings()))
5681  {
5682  pg_log_error("could not parse reloptions array");
5683  result = false;
5684  }
5685  appendPQExpBufferChar(buf, ')');
5686  }
5687 
5688  /* View definition from pg_get_viewdef (a SELECT query) */
5689  appendPQExpBuffer(buf, " AS\n%s", viewdef);
5690 
5691  /* Get rid of the semicolon that pg_get_viewdef appends */
5692  if (buf->len > 0 && buf->data[buf->len - 1] == ';')
5693  buf->data[--(buf->len)] = '\0';
5694 
5695  /* WITH [LOCAL|CASCADED] CHECK OPTION */
5696  if (checkoption && checkoption[0] != '\0')
5697  appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
5698  checkoption);
5699  }
5700  break;
5701  }
5702  /* Make sure result ends with a newline */
5703  if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
5704  appendPQExpBufferChar(buf, '\n');
5705  }
5706  else
5707  {
5709  result = false;
5710  }
5711 
5712  PQclear(res);
5713  destroyPQExpBuffer(query);
5714 
5715  return result;
5716 }
bool standard_strings(void)
Definition: common.c:2139
static bool echo_hidden_command(const char *query)
Definition: command.c:5476
static void minimal_error_message(PGresult *res)
Definition: command.c:5858
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
NameData relname
Definition: pg_class.h:38
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
Definition: string_utils.c:804

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendReloptionsArray(), buf, createPQExpBuffer(), PQExpBufferData::data, _psqlSettings::db, destroyPQExpBuffer(), echo_hidden_command(), EditableFunction, EditableView, _psqlSettings::encoding, fmtId(), minimal_error_message(), pg_log_error, PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQntuples(), PQresultStatus(), printfPQExpBuffer(), pset, relname, res, resetPQExpBuffer(), standard_strings(), and _psqlSettings::sversion.

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ HandleSlashCmds()

backslashResult HandleSlashCmds ( PsqlScanState  scan_state,
ConditionalStack  cstack,
PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)

Definition at line 215 of file command.c.

219 {
220  backslashResult status;
221  char *cmd;
222  char *arg;
223 
224  Assert(scan_state != NULL);
225  Assert(cstack != NULL);
226 
227  /* Parse off the command name */
228  cmd = psql_scan_slash_command(scan_state);
229 
230  /* And try to execute it */
231  status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
232 
233  if (status == PSQL_CMD_UNKNOWN)
234  {
235  pg_log_error("invalid command \\%s", cmd);
237  pg_log_error_hint("Try \\? for help.");
238  status = PSQL_CMD_ERROR;
239  }
240 
241  if (status != PSQL_CMD_ERROR)
242  {
243  /*
244  * Eat any remaining arguments after a valid command. We want to
245  * suppress evaluation of backticks in this situation, so transiently
246  * push an inactive conditional-stack entry.
247  */
248  bool active_branch = conditional_active(cstack);
249 
251  while ((arg = psql_scan_slash_option(scan_state,
252  OT_NORMAL, NULL, false)))
253  {
254  if (active_branch)
255  pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
256  free(arg);
257  }
258  conditional_stack_pop(cstack);
259  }
260  else
261  {
262  /* silently throw away rest of line after an erroneous command */
263  while ((arg = psql_scan_slash_option(scan_state,
264  OT_WHOLE_LINE, NULL, false)))
265  free(arg);
266  }
267 
268  /* if there is a trailing \\, swallow it */
269  psql_scan_slash_command_end(scan_state);
270 
271  free(cmd);
272 
273  /* some commands write to queryFout, so make sure output is sent */
275 
276  return status;
277 }
static backslashResult exec_command(const char *cmd, PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:288
#define pg_log_error_hint(...)
Definition: logging.h:112
void * arg
char * psql_scan_slash_command(PsqlScanState state)
void psql_scan_slash_command_end(PsqlScanState state)

References arg, Assert, conditional_active(), conditional_stack_pop(), conditional_stack_push(), _psqlSettings::cur_cmd_interactive, exec_command(), fflush(), free, IFSTATE_IGNORED, OT_NORMAL, OT_WHOLE_LINE, pg_log_error, pg_log_error_hint, pg_log_warning, pset, PSQL_CMD_ERROR, PSQL_CMD_UNKNOWN, psql_scan_slash_command(), psql_scan_slash_command_end(), psql_scan_slash_option(), and _psqlSettings::queryFout.

Referenced by main(), and MainLoop().

◆ ignore_boolean_expression()

static void ignore_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3099 of file command.c.

3100 {
3102 
3104 }
static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3052

References buf, destroyPQExpBuffer(), and gather_boolean_expression().

Referenced by exec_command_elif(), and exec_command_if().

◆ ignore_slash_filepipe()

static void ignore_slash_filepipe ( PsqlScanState  scan_state)
static

Definition at line 3132 of file command.c.

3133 {
3134  char *arg = psql_scan_slash_option(scan_state,
3135  OT_FILEPIPE, NULL, false);
3136 
3137  free(arg);
3138 }

References arg, free, OT_FILEPIPE, and psql_scan_slash_option().

Referenced by exec_command_out(), and exec_command_write().

◆ ignore_slash_options()

◆ ignore_slash_whole_line()

static void ignore_slash_whole_line ( PsqlScanState  scan_state)
static

Definition at line 3152 of file command.c.

3153 {
3154  char *arg = psql_scan_slash_option(scan_state,
3155  OT_WHOLE_LINE, NULL, false);
3156 
3157  free(arg);
3158 }

References arg, free, OT_WHOLE_LINE, and psql_scan_slash_option().

Referenced by exec_command_copy(), exec_command_ef_ev(), exec_command_help(), exec_command_sf_sv(), and exec_command_shell_escape().

◆ is_branching_command()

static bool is_branching_command ( const char *  cmd)
static

Definition at line 3164 of file command.c.

3165 {
3166  return (strcmp(cmd, "if") == 0 ||
3167  strcmp(cmd, "elif") == 0 ||
3168  strcmp(cmd, "else") == 0 ||
3169  strcmp(cmd, "endif") == 0);
3170 }

Referenced by exec_command().

◆ is_true_boolean_expression()

static bool is_true_boolean_expression ( PsqlScanState  scan_state,
const char *  name 
)
static

Definition at line 3082 of file command.c.

3083 {
3085  bool value = false;
3086  bool success = ParseVariableBool(buf->data, name, &value);
3087 
3089  return success && value;
3090 }

References buf, destroyPQExpBuffer(), gather_boolean_expression(), name, ParseVariableBool(), success, and value.

Referenced by exec_command_elif(), and exec_command_if().

◆ lookup_object_oid()

static bool lookup_object_oid ( EditableObjectType  obj_type,
const char *  desc,
Oid obj_oid 
)
static

Definition at line 5508 of file command.c.

5510 {
5511  bool result = true;
5512  PQExpBuffer query = createPQExpBuffer();
5513  PGresult *res;
5514 
5515  switch (obj_type)
5516  {
5517  case EditableFunction:
5518 
5519  /*
5520  * We have a function description, e.g. "x" or "x(int)". Issue a
5521  * query to retrieve the function's OID using a cast to regproc or
5522  * regprocedure (as appropriate).
5523  */
5524  appendPQExpBufferStr(query, "SELECT ");
5525  appendStringLiteralConn(query, desc, pset.db);
5526  appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
5527  strchr(desc, '(') ? "regprocedure" : "regproc");
5528  break;
5529 
5530  case EditableView:
5531 
5532  /*
5533  * Convert view name (possibly schema-qualified) to OID. Note:
5534  * this code doesn't check if the relation is actually a view.
5535  * We'll detect that in get_create_object_cmd().
5536  */
5537  appendPQExpBufferStr(query, "SELECT ");
5538  appendStringLiteralConn(query, desc, pset.db);
5539  appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
5540  break;
5541  }
5542 
5543  if (!echo_hidden_command(query->data))
5544  {
5545  destroyPQExpBuffer(query);
5546  return false;
5547  }
5548  res = PQexec(pset.db, query->data);
5549  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
5550  *obj_oid = atooid(PQgetvalue(res, 0, 0));
5551  else
5552  {
5554  result = false;
5555  }
5556 
5557  PQclear(res);
5558  destroyPQExpBuffer(query);
5559 
5560  return result;
5561 }
#define atooid(x)
Definition: postgres_ext.h:42
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), atooid, createPQExpBuffer(), PQExpBufferData::data, _psqlSettings::db, destroyPQExpBuffer(), echo_hidden_command(), EditableFunction, EditableView, minimal_error_message(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQntuples(), PQresultStatus(), pset, and res.

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ minimal_error_message()

static void minimal_error_message ( PGresult res)
static

Definition at line 5858 of file command.c.

5859 {
5860  PQExpBuffer msg;
5861  const char *fld;
5862 
5863  msg = createPQExpBuffer();
5864 
5866  if (fld)
5867  printfPQExpBuffer(msg, "%s: ", fld);
5868  else
5869  printfPQExpBuffer(msg, "ERROR: ");
5871  if (fld)
5872  appendPQExpBufferStr(msg, fld);
5873  else
5874  appendPQExpBufferStr(msg, "(not available)");
5875  appendPQExpBufferChar(msg, '\n');
5876 
5877  pg_log_error("%s", msg->data);
5878 
5879  destroyPQExpBuffer(msg);
5880 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54

References appendPQExpBufferChar(), appendPQExpBufferStr(), createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SEVERITY, pg_log_error, PQresultErrorField(), printfPQExpBuffer(), and res.

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ param_is_newly_set()

static bool param_is_newly_set ( const char *  old_val,
const char *  new_val 
)
static

Definition at line 3272 of file command.c.

3273 {
3274  if (new_val == NULL)
3275  return false;
3276 
3277  if (old_val == NULL || strcmp(old_val, new_val) != 0)
3278  return true;
3279 
3280  return false;
3281 }

Referenced by do_connect().

◆ print_with_linenumbers()

static void print_with_linenumbers ( FILE *  output,
char *  lines,
bool  is_func 
)
static

Definition at line 5816 of file command.c.

5817 {
5818  bool in_header = is_func;
5819  int lineno = 0;
5820 
5821  while (*lines != '\0')
5822  {
5823  char *eol;
5824 
5825  if (in_header &&
5826  (strncmp(lines, "AS ", 3) == 0 ||
5827  strncmp(lines, "BEGIN ", 6) == 0 ||
5828  strncmp(lines, "RETURN ", 7) == 0))
5829  in_header = false;
5830 
5831  /* increment lineno only for body's lines */
5832  if (!in_header)
5833  lineno++;
5834 
5835  /* find and mark end of current line */
5836  eol = strchr(lines, '\n');
5837  if (eol != NULL)
5838  *eol = '\0';
5839 
5840  /* show current line as appropriate */
5841  if (in_header)
5842  fprintf(output, " %s\n", lines);
5843  else
5844  fprintf(output, "%-7d %s\n", lineno, lines);
5845 
5846  /* advance to next line, if any */
5847  if (eol == NULL)
5848  break;
5849  lines = ++eol;
5850  }
5851 }

References fprintf, and output.

Referenced by exec_command_sf_sv().

◆ printGSSInfo()

static void printGSSInfo ( void  )
static

Definition at line 3908 of file command.c.

3909 {
3910  if (!PQgssEncInUse(pset.db))
3911  return; /* no GSSAPI encryption in use */
3912 
3913  printf(_("GSSAPI-encrypted connection\n"));
3914 }
int PQgssEncInUse(PGconn *conn)

References _, _psqlSettings::db, PQgssEncInUse(), printf, and pset.

Referenced by connection_warnings(), and exec_command_conninfo().

◆ printPsetInfo()

static bool printPsetInfo ( const char *  param,
printQueryOpt popt 
)
static

Definition at line 4793 of file command.c.

4794 {
4795  Assert(param != NULL);
4796 
4797  /* show border style/width */
4798  if (strcmp(param, "border") == 0)
4799  printf(_("Border style is %d.\n"), popt->topt.border);
4800 
4801  /* show the target width for the wrapped format */
4802  else if (strcmp(param, "columns") == 0)
4803  {
4804  if (!popt->topt.columns)
4805  printf(_("Target width is unset.\n"));
4806  else
4807  printf(_("Target width is %d.\n"), popt->topt.columns);
4808  }
4809 
4810  /* show expanded/vertical mode */
4811  else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
4812  {
4813  if (popt->topt.expanded == 1)
4814  printf(_("Expanded display is on.\n"));
4815  else if (popt->topt.expanded == 2)
4816  printf(_("Expanded display is used automatically.\n"));
4817  else
4818  printf(_("Expanded display is off.\n"));
4819  }
4820 
4821  /* show xheader width value */
4822  else if (strcmp(param, "xheader_width") == 0)
4823  {
4825  printf(_("Expanded header width is \"%s\".\n"), "full");
4827  printf(_("Expanded header width is \"%s\".\n"), "column");
4829  printf(_("Expanded header width is \"%s\".\n"), "page");
4831  printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
4832  }
4833 
4834  /* show field separator for CSV format */
4835  else if (strcmp(param, "csv_fieldsep") == 0)
4836  {
4837  printf(_("Field separator for CSV is \"%s\".\n"),
4838  popt->topt.csvFieldSep);
4839  }
4840 
4841  /* show field separator for unaligned text */
4842  else if (strcmp(param, "fieldsep") == 0)
4843  {
4844  if (popt->topt.fieldSep.separator_zero)
4845  printf(_("Field separator is zero byte.\n"));
4846  else
4847  printf(_("Field separator is \"%s\".\n"),
4848  popt->topt.fieldSep.separator);
4849  }
4850 
4851  else if (strcmp(param, "fieldsep_zero") == 0)
4852  {
4853  printf(_("Field separator is zero byte.\n"));
4854  }
4855 
4856  /* show disable "(x rows)" footer */
4857  else if (strcmp(param, "footer") == 0)
4858  {
4859  if (popt->topt.default_footer)
4860  printf(_("Default footer is on.\n"));
4861  else
4862  printf(_("Default footer is off.\n"));
4863  }
4864 
4865  /* show format */
4866  else if (strcmp(param, "format") == 0)
4867  {
4868  printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
4869  }
4870 
4871  /* show table line style */
4872  else if (strcmp(param, "linestyle") == 0)
4873  {
4874  printf(_("Line style is %s.\n"),
4875  get_line_style(&popt->topt)->name);
4876  }
4877 
4878  /* show null display */
4879  else if (strcmp(param, "null") == 0)
4880  {
4881  printf(_("Null display is \"%s\".\n"),
4882  popt->nullPrint ? popt->nullPrint : "");
4883  }
4884 
4885  /* show locale-aware numeric output */
4886  else if (strcmp(param, "numericlocale") == 0)
4887  {
4888  if (popt->topt.numericLocale)
4889  printf(_("Locale-adjusted numeric output is on.\n"));
4890  else
4891  printf(_("Locale-adjusted numeric output is off.\n"));
4892  }
4893 
4894  /* show toggle use of pager */
4895  else if (strcmp(param, "pager") == 0)
4896  {
4897  if (popt->topt.pager == 1)
4898  printf(_("Pager is used for long output.\n"));
4899  else if (popt->topt.pager == 2)
4900  printf(_("Pager is always used.\n"));
4901  else
4902  printf(_("Pager usage is off.\n"));
4903  }
4904 
4905  /* show minimum lines for pager use */
4906  else if (strcmp(param, "pager_min_lines") == 0)
4907  {
4908  printf(ngettext("Pager won't be used for less than %d line.\n",
4909  "Pager won't be used for less than %d lines.\n",
4910  popt->topt.pager_min_lines),
4911  popt->topt.pager_min_lines);
4912  }
4913 
4914  /* show record separator for unaligned text */
4915  else if (strcmp(param, "recordsep") == 0)
4916  {
4917  if (popt->topt.recordSep.separator_zero)
4918  printf(_("Record separator is zero byte.\n"));
4919  else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
4920  printf(_("Record separator is <newline>.\n"));
4921  else
4922  printf(_("Record separator is \"%s\".\n"),
4923  popt->topt.recordSep.separator);
4924  }
4925 
4926  else if (strcmp(param, "recordsep_zero") == 0)
4927  {
4928  printf(_("Record separator is zero byte.\n"));
4929  }
4930 
4931  /* show HTML table tag options */
4932  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4933  {
4934  if (popt->topt.tableAttr)
4935  printf(_("Table attributes are \"%s\".\n"),
4936  popt->topt.tableAttr);
4937  else
4938  printf(_("Table attributes unset.\n"));
4939  }
4940 
4941  /* show title override */
4942  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4943  {
4944  if (popt->title)
4945  printf(_("Title is \"%s\".\n"), popt->title);
4946  else
4947  printf(_("Title is unset.\n"));
4948  }
4949 
4950  /* show toggle between full and tuples-only format */
4951  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4952  {
4953  if (popt->topt.tuples_only)
4954  printf(_("Tuples only is on.\n"));
4955  else
4956  printf(_("Tuples only is off.\n"));
4957  }
4958 
4959  /* Unicode style formatting */
4960  else if (strcmp(param, "unicode_border_linestyle") == 0)
4961  {
4962  printf(_("Unicode border line style is \"%s\".\n"),
4964  }
4965 
4966  else if (strcmp(param, "unicode_column_linestyle") == 0)
4967  {
4968  printf(_("Unicode column line style is \"%s\".\n"),
4970  }
4971 
4972  else if (strcmp(param, "unicode_header_linestyle") == 0)
4973  {
4974  printf(_("Unicode header line style is \"%s\".\n"),
4976  }
4977 
4978  else
4979  {
4980  pg_log_error("\\pset: unknown option: %s", param);
4981  return false;
4982  }
4983 
4984  return true;
4985 }
#define ngettext(s, p, n)
Definition: c.h:1181
static const char * _align2string(enum printFormat in)
Definition: command.c:4354
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:4410
const printTextFormat * get_line_style(const printTableOpt *opt)
Definition: print.c:3677
const char * name
Definition: print.h:84

References _, _align2string(), _unicode_linestyle2string(), Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::expanded_header_exact_width, printTableOpt::expanded_header_width_type, printTableOpt::fieldSep, printTableOpt::format, get_line_style(), printTextFormat::name, ngettext, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, pg_log_error, PRINT_XHEADER_COLUMN, PRINT_XHEADER_EXACT_WIDTH, PRINT_XHEADER_FULL, PRINT_XHEADER_PAGE, printf, printTableOpt::recordSep, separator::separator, separator::separator_zero, printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, and printTableOpt::unicode_header_linestyle.

Referenced by do_pset().

◆ printSSLInfo()

static void printSSLInfo ( void  )
static

Definition at line 3880 of file command.c.

3881 {
3882  const char *protocol;
3883  const char *cipher;
3884  const char *compression;
3885  const char *alpn;
3886 
3887  if (!PQsslInUse(pset.db))
3888  return; /* no SSL */
3889 
3890  protocol = PQsslAttribute(pset.db, "protocol");
3891  cipher = PQsslAttribute(pset.db, "cipher");
3892  compression = PQsslAttribute(pset.db, "compression");
3893  alpn = PQsslAttribute(pset.db, "alpn");
3894 
3895  printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
3896  protocol ? protocol : _("unknown"),
3897  cipher ? cipher : _("unknown"),
3898  (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
3899  alpn ? alpn : _("none"));
3900 }
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:103

References _, _psqlSettings::db, PQsslAttribute(), PQsslInUse(), printf, and pset.

Referenced by connection_warnings(), and exec_command_conninfo().

◆ process_command_g_options()

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

Definition at line 1466 of file command.c.

1468 {
1469  bool success = true;
1470  bool found_r_paren = false;
1471 
1472  do
1473  {
1474  char *option;
1475  size_t optlen;
1476 
1477  /* If not first time through, collect a new option */
1478  if (first_option)
1479  option = first_option;
1480  else
1481  {
1482  option = psql_scan_slash_option(scan_state,
1483  OT_NORMAL, NULL, false);
1484  if (!option)
1485  {
1486  if (active_branch)
1487  {
1488  pg_log_error("\\%s: missing right parenthesis", cmd);
1489  success = false;
1490  }
1491  break;
1492  }
1493  }
1494 
1495  /* Check for terminating right paren, and remove it from string */
1496  optlen = strlen(option);
1497  if (optlen > 0 && option[optlen - 1] == ')')
1498  {
1499  option[--optlen] = '\0';
1500  found_r_paren = true;
1501  }
1502 
1503  /* If there was anything besides parentheses, parse/execute it */
1504  if (optlen > 0)
1505  {
1506  /* We can have either "name" or "name=value" */
1507  char *valptr = strchr(option, '=');
1508 
1509  if (valptr)
1510  *valptr++ = '\0';
1511  if (active_branch)
1512  {
1513  /* save settings if not done already, then apply option */
1514  if (pset.gsavepopt == NULL)
1516  success &= do_pset(option, valptr, &pset.popt, true);
1517  }
1518  }
1519 
1520  /* Clean up after this option. We should not free first_option. */
1521  if (first_option)
1522  first_option = NULL;
1523  else
1524  free(option);
1525  } while (!found_r_paren);
1526 
1527  /* If we failed after already changing some options, undo side-effects */
1528  if (!success && active_branch && pset.gsavepopt)
1529  {
1531  pset.gsavepopt = NULL;
1532  }
1533 
1535 }
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:5029

References do_pset(), free, _psqlSettings::gsavepopt, OT_NORMAL, pg_log_error, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), restorePsetInfo(), savePsetInfo(), and success.

Referenced by exec_command_g().

◆ process_file()

int process_file ( char *  filename,
bool  use_relative_path 
)

Definition at line 4287 of file command.c.

4288 {
4289  FILE *fd;
4290  int result;
4291  char *oldfilename;
4292  char relpath[MAXPGPATH];
4293 
4294  if (!filename)
4295  {
4296  fd = stdin;
4297  filename = NULL;
4298  }
4299  else if (strcmp(filename, "-") != 0)
4300  {
4302 
4303  /*
4304  * If we were asked to resolve the pathname relative to the location
4305  * of the currently executing script, and there is one, and this is a
4306  * relative pathname, then prepend all but the last pathname component
4307  * of the current script to this pathname.
4308  */
4309  if (use_relative_path && pset.inputfile &&
4311  {
4312  strlcpy(relpath, pset.inputfile, sizeof(relpath));
4316 
4317  filename = relpath;
4318  }
4319 
4320  fd = fopen(filename, PG_BINARY_R);
4321 
4322  if (!fd)
4323  {
4324  pg_log_error("%s: %m", filename);
4325  return EXIT_FAILURE;
4326  }
4327  }
4328  else
4329  {
4330  fd = stdin;
4331  filename = "<stdin>"; /* for future error messages */
4332  }
4333 
4334  oldfilename = pset.inputfile;
4336 
4338 
4339  result = MainLoop(fd);
4340 
4341  if (fd != stdin)
4342  fclose(fd);
4343 
4344  pset.inputfile = oldfilename;
4345 
4347 
4348  return result;
4349 }
void pg_logging_config(int new_flags)
Definition: logging.c:163
#define PG_LOG_FLAG_TERSE
Definition: logging.h:86
int MainLoop(FILE *source)
Definition: mainloop.c:33
static char * filename
Definition: pg_dumpall.c:119
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:219
#define is_absolute_path(filename)
Definition: port.h:103
void get_parent_directory(char *path)
Definition: path.c:976
bool has_drive_prefix(const char *path)
Definition: path.c:88
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define relpath(rlocator, forknum)
Definition: relpath.h:94
#define EXIT_FAILURE
Definition: settings.h:167

References canonicalize_path(), EXIT_FAILURE, fd(), filename, get_parent_directory(), has_drive_prefix(), _psqlSettings::inputfile, is_absolute_path, join_path_components(), MainLoop(), MAXPGPATH, PG_BINARY_R, pg_log_error, PG_LOG_FLAG_TERSE, pg_logging_config(), pset, relpath, and strlcpy().

Referenced by exec_command_include().

◆ prompt_for_password()

static char* prompt_for_password ( const char *  username,
bool canceled 
)
static

Definition at line 3244 of file command.c.

3245 {
3246  char *result;
3247  PromptInterruptContext prompt_ctx;
3248 
3249  /* Set up to let SIGINT cancel simple_prompt_extended() */
3250  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3251  prompt_ctx.enabled = &sigint_interrupt_enabled;
3252  prompt_ctx.canceled = false;
3253 
3254  if (username == NULL || username[0] == '\0')
3255  result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3256  else
3257  {
3258  char *prompt_text;
3259 
3260  prompt_text = psprintf(_("Password for user %s: "), username);
3261  result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3262  free(prompt_text);
3263  }
3264 
3265  if (canceled)
3266  *canceled = prompt_ctx.canceled;
3267 
3268  return result;
3269 }
const char * username
Definition: pgbench.c:296

References _, PromptInterruptContext::canceled, PromptInterruptContext::enabled, free, PromptInterruptContext::jmpbuf, psprintf(), sigint_interrupt_enabled, sigint_interrupt_jmp, simple_prompt_extended(), and username.

Referenced by do_connect().

◆ pset_bool_string()

static const char* pset_bool_string ( bool  val)
static

Definition at line 5055 of file command.c.

5056 {
5057  return val ? "on" : "off";
5058 }

References val.

Referenced by pset_value_string().

◆ pset_quoted_string()

static char* pset_quoted_string ( const char *  str)
static

Definition at line 5062 of file command.c.

5063 {
5064  char *ret = pg_malloc(strlen(str) * 2 + 3);
5065  char *r = ret;
5066 
5067  *r++ = '\'';
5068 
5069  for (; *str; str++)
5070  {
5071  if (*str == '\n')
5072  {
5073  *r++ = '\\';
5074  *r++ = 'n';
5075  }
5076  else if (*str == '\'')
5077  {
5078  *r++ = '\\';
5079  *r++ = '\'';
5080  }
5081  else
5082  *r++ = *str;
5083  }
5084 
5085  *r++ = '\'';
5086  *r = '\0';
5087 
5088  return ret;
5089 }
const char * str

References pg_malloc(), and str.

Referenced by pset_value_string().

◆ pset_value_string()

static char * pset_value_string ( const char *  param,
printQueryOpt popt 
)
static

Definition at line 5100 of file command.c.

5101 {
5102  Assert(param != NULL);
5103 
5104  if (strcmp(param, "border") == 0)
5105  return psprintf("%d", popt->topt.border);
5106  else if (strcmp(param, "columns") == 0)
5107  return psprintf("%d", popt->topt.columns);
5108  else if (strcmp(param, "csv_fieldsep") == 0)
5109  return pset_quoted_string(popt->topt.csvFieldSep);
5110  else if (strcmp(param, "expanded") == 0)
5111  return pstrdup(popt->topt.expanded == 2
5112  ? "auto"
5113  : pset_bool_string(popt->topt.expanded));
5114  else if (strcmp(param, "fieldsep") == 0)
5116  ? popt->topt.fieldSep.separator
5117  : "");
5118  else if (strcmp(param, "fieldsep_zero") == 0)
5120  else if (strcmp(param, "footer") == 0)
5122  else if (strcmp(param, "format") == 0)
5123  return pstrdup(_align2string(popt->topt.format));
5124  else if (strcmp(param, "linestyle") == 0)
5125  return pstrdup(get_line_style(&popt->topt)->name);
5126  else if (strcmp(param, "null") == 0)
5127  return pset_quoted_string(popt->nullPrint
5128  ? popt->nullPrint
5129  : "");
5130  else if (strcmp(param, "numericlocale") == 0)
5131  return pstrdup(pset_bool_string(popt->topt.numericLocale));
5132  else if (strcmp(param, "pager") == 0)
5133  return psprintf("%d", popt->topt.pager);
5134  else if (strcmp(param, "pager_min_lines") == 0)
5135  return psprintf("%d", popt->topt.pager_min_lines);
5136  else if (strcmp(param, "recordsep") == 0)
5138  ? popt->topt.recordSep.separator
5139  : "");
5140  else if (strcmp(param, "recordsep_zero") == 0)
5142  else if (strcmp(param, "tableattr") == 0)
5143  return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5144  else if (strcmp(param, "title") == 0)
5145  return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5146  else if (strcmp(param, "tuples_only") == 0)
5147  return pstrdup(pset_bool_string(popt->topt.tuples_only));
5148  else if (strcmp(param, "unicode_border_linestyle") == 0)
5150  else if (strcmp(param, "unicode_column_linestyle") == 0)
5152  else if (strcmp(param, "unicode_header_linestyle") == 0)
5154  else if (strcmp(param, "xheader_width") == 0)
5155  {
5157  return pstrdup("full");
5159  return pstrdup("column");
5161  return pstrdup("page");
5162  else
5163  {
5164  /* must be PRINT_XHEADER_EXACT_WIDTH */
5165  char wbuff[32];
5166 
5167  snprintf(wbuff, sizeof(wbuff), "%d",
5169  return pstrdup(wbuff);
5170  }
5171  }
5172  else
5173  return pstrdup("ERROR");
5174 }
static char * pset_quoted_string(const char *str)
Definition: command.c:5062
static const char * pset_bool_string(bool val)
Definition: command.c:5055
char * pstrdup(const char *in)
Definition: mcxt.c:1695

References _align2string(), _unicode_linestyle2string(), Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::expanded_header_exact_width, printTableOpt::expanded_header_width_type, printTableOpt::fieldSep, printTableOpt::format, get_line_style(), printTextFormat::name, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, PRINT_XHEADER_COLUMN, PRINT_XHEADER_FULL, PRINT_XHEADER_PAGE, pset_bool_string(), pset_quoted_string(), psprintf(), pstrdup(), printTableOpt::recordSep, separator::separator, separator::separator_zero, snprintf, 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_pset().

◆ read_connect_arg()

static char * read_connect_arg ( PsqlScanState  scan_state)
static

Definition at line 3012 of file command.c.

3013 {
3014  char *result;
3015  char quote;
3016 
3017  /*
3018  * Ideally we should treat the arguments as SQL identifiers. But for
3019  * backwards compatibility with 7.2 and older pg_dump files, we have to
3020  * take unquoted arguments verbatim (don't downcase them). For now,
3021  * double-quoted arguments may be stripped of double quotes (as if SQL
3022  * identifiers). By 7.4 or so, pg_dump files can be expected to
3023  * double-quote all mixed-case \connect arguments, and then we can get rid
3024  * of OT_SQLIDHACK.
3025  */
3026  result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
3027 
3028  if (!result)
3029  return NULL;
3030 
3031  if (quote)
3032  return result;
3033 
3034  if (*result == '\0' || strcmp(result, "-") == 0)
3035  {
3036  free(result);
3037  return NULL;
3038  }
3039 
3040  return result;
3041 }
@ OT_SQLIDHACK
Definition: psqlscanslash.h:19

References free, OT_SQLIDHACK, and psql_scan_slash_option().

Referenced by exec_command_connect().

◆ restorePsetInfo()

void restorePsetInfo ( printQueryOpt popt,
printQueryOpt save 
)

Definition at line 5029 of file command.c.

5030 {
5031  /* Free all the old data we're about to overwrite the pointers to. */
5032 
5033  /* topt.line_style points to const data that need not be duplicated */
5034  free(popt->topt.fieldSep.separator);
5035  free(popt->topt.recordSep.separator);
5036  free(popt->topt.tableAttr);
5037  free(popt->nullPrint);
5038  free(popt->title);
5039 
5040  /*
5041  * footers and translate_columns are never set in psql's print settings,
5042  * so we needn't write code to duplicate them.
5043  */
5044  Assert(popt->footers == NULL);
5045  Assert(popt->translate_columns == NULL);
5046 
5047  /* Now we may flat-copy all the fields, including pointers. */
5048  memcpy(popt, save, sizeof(printQueryOpt));
5049 
5050  /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5051  free(save);
5052 }
const bool * translate_columns
Definition: print.h:190
char ** footers
Definition: print.h:188

References Assert, printTableOpt::fieldSep, printQueryOpt::footers, free, printQueryOpt::nullPrint, printTableOpt::recordSep, separator::separator, printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, and printQueryOpt::translate_columns.

Referenced by process_command_g_options(), and SendQuery().

◆ save_query_text_state()

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

Definition at line 3180 of file command.c.

3182 {
3183  if (query_buf)
3184  conditional_stack_set_query_len(cstack, query_buf->len);
3186  psql_scan_get_paren_depth(scan_state));
3187 }
void conditional_stack_set_paren_depth(ConditionalStack cstack, int depth)
Definition: conditional.c:173
void conditional_stack_set_query_len(ConditionalStack cstack, int len)
Definition: conditional.c:151
int psql_scan_get_paren_depth(PsqlScanState state)

References conditional_stack_set_paren_depth(), conditional_stack_set_query_len(), PQExpBufferData::len, and psql_scan_get_paren_depth().

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

◆ savePsetInfo()

printQueryOpt* savePsetInfo ( const printQueryOpt popt)

Definition at line 4993 of file command.c.

4994 {
4995  printQueryOpt *save;
4996 
4997  save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
4998 
4999  /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5000  memcpy(save, popt, sizeof(printQueryOpt));
5001 
5002  /* topt.line_style points to const data that need not be duplicated */
5003  if (popt->topt.fieldSep.separator)
5005  if (popt->topt.recordSep.separator)
5007  if (popt->topt.tableAttr)
5008  save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5009  if (popt->nullPrint)
5010  save->nullPrint = pg_strdup(popt->nullPrint);
5011  if (popt->title)
5012  save->title = pg_strdup(popt->title);
5013 
5014  /*
5015  * footers and translate_columns are never set in psql's print settings,
5016  * so we needn't write code to duplicate them.
5017  */
5018  Assert(popt->footers == NULL);
5019  Assert(popt->translate_columns == NULL);
5020 
5021  return save;
5022 }

References Assert, printTableOpt::fieldSep, printQueryOpt::footers, printQueryOpt::nullPrint, pg_malloc(), pg_strdup(), printTableOpt::recordSep, separator::separator, printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, and printQueryOpt::translate_columns.

Referenced by exec_command_g(), and process_command_g_options().

◆ set_unicode_line_style()

static bool set_unicode_line_style ( const char *  value,
size_t  vallen,
unicode_linestyle linestyle 
)
static

Definition at line 4397 of file command.c.

4399 {
4400  if (pg_strncasecmp("single", value, vallen) == 0)
4401  *linestyle = UNICODE_LINESTYLE_SINGLE;
4402  else if (pg_strncasecmp("double", value, vallen) == 0)
4403  *linestyle = UNICODE_LINESTYLE_DOUBLE;
4404  else
4405  return false;
4406  return true;
4407 }

References pg_strncasecmp(), UNICODE_LINESTYLE_DOUBLE, UNICODE_LINESTYLE_SINGLE, and value.

Referenced by do_pset().

◆ strip_lineno_from_objdesc()

static int strip_lineno_from_objdesc ( char *  obj)
static

Definition at line 5728 of file command.c.

5729 {
5730  char *c;
5731  int lineno;
5732 
5733  if (!obj || obj[0] == '\0')
5734  return -1;
5735 
5736  c = obj + strlen(obj) - 1;
5737 
5738  /*
5739  * This business of parsing backwards is dangerous as can be in a
5740  * multibyte environment: there is no reason to believe that we are
5741  * looking at the first byte of a character, nor are we necessarily
5742  * working in a "safe" encoding. Fortunately the bitpatterns we are
5743  * looking for are unlikely to occur as non-first bytes, but beware of
5744  * trying to expand the set of cases that can be recognized. We must
5745  * guard the <ctype.h> macros by using isascii() first, too.
5746  */
5747 
5748  /* skip trailing whitespace */
5749  while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
5750  c--;
5751 
5752  /* must have a digit as last non-space char */
5753  if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
5754  return -1;
5755 
5756  /* find start of digit string */
5757  while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
5758  c--;
5759 
5760  /* digits must be separated from object name by space or closing paren */
5761  /* notice also that we are not allowing an empty object name ... */
5762  if (c == obj || !isascii((unsigned char) *c) ||
5763  !(isspace((unsigned char) *c) || *c == ')'))
5764  return -1;
5765 
5766  /* parse digit string */
5767  c++;
5768  lineno = atoi(c);
5769  if (lineno < 1)
5770  {
5771  pg_log_error("invalid line number: %s", c);
5772  return 0;
5773  }
5774 
5775  /* strip digit string from object name */
5776  *c = '\0';
5777 
5778  return lineno;
5779 }
char * c

References pg_log_error.

Referenced by exec_command_ef_ev().

◆ SyncVariables()

void SyncVariables ( void  )

Definition at line 3949 of file command.c.

3950 {
3951  char vbuf[32];
3952  const char *server_version;
3953 
3954  /* get stuff from connection */
3958 
3959  SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
3960  SetVariable(pset.vars, "USER", PQuser(pset.db));
3961  SetVariable(pset.vars, "HOST", PQhost(pset.db));
3962  SetVariable(pset.vars, "PORT", PQport(pset.db));
3964 
3965  /* this bit should match connection_warnings(): */
3966  /* Try to get full text form of version, might include "devel" etc */
3967  server_version = PQparameterStatus(pset.db, "server_version");
3968  /* Otherwise fall back on pset.sversion */
3969  if (!server_version)
3970  {
3971  formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
3972  server_version = vbuf;
3973  }
3974  SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
3975 
3976  snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
3977  SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
3978 
3979  /* send stuff to it, too */
3982 }
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7137
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7297
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7285
PGVerbosity verbosity
Definition: settings.h:154
PGContextVisibility show_context
Definition: settings.h:156

References _psqlSettings::db, _psqlSettings::encoding, printTableOpt::encoding, formatPGVersionNumber(), pg_encoding_to_char, _psqlSettings::popt, PQclientEncoding(), PQdb(), PQhost(), PQparameterStatus(), PQport(), PQserverVersion(), PQsetErrorContextVisibility(), PQsetErrorVerbosity(), PQuser(), pset, server_version, SetVariable(), _psqlSettings::show_context, snprintf, _psqlSettings::sversion, printQueryOpt::topt, _psqlSettings::vars, and _psqlSettings::verbosity.

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

◆ UnsyncVariables()

void UnsyncVariables ( void  )

Definition at line 3990 of file command.c.

3991 {
3992  SetVariable(pset.vars, "DBNAME", NULL);
3993  SetVariable(pset.vars, "USER", NULL);
3994  SetVariable(pset.vars, "HOST", NULL);
3995  SetVariable(pset.vars, "PORT", NULL);
3996  SetVariable(pset.vars, "ENCODING", NULL);
3997  SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
3998  SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
3999 }

References pset, SetVariable(), and _psqlSettings::vars.

Referenced by CheckConnection(), and do_connect().

◆ wait_until_connected()

static void wait_until_connected ( PGconn conn)
static

Definition at line 3759 of file command.c.

3760 {
3761  bool forRead = false;
3762 
3763  while (true)
3764  {
3765  int rc;
3766  int sock;
3767  time_t end_time;
3768 
3769  /*
3770  * On every iteration of the connection sequence, let's check if the
3771  * user has requested a cancellation.
3772  */
3773  if (cancel_pressed)
3774  break;
3775 
3776  /*
3777  * Do not assume that the socket remains the same across
3778  * PQconnectPoll() calls.
3779  */
3780  sock = PQsocket(conn);
3781  if (sock == -1)
3782  break;
3783 
3784  /*
3785  * If the user sends SIGINT between the cancel_pressed check, and
3786  * polling of the socket, it will not be recognized. Instead, we will
3787  * just wait until the next step in the connection sequence or
3788  * forever, which might require users to send SIGTERM or SIGQUIT.
3789  *
3790  * Some solutions would include the "self-pipe trick," using
3791  * pselect(2) and ppoll(2), or using a timeout.
3792  *
3793  * The self-pipe trick requires a bit of code to setup. pselect(2) and
3794  * ppoll(2) are not on all the platforms we support. The simplest
3795  * solution happens to just be adding a timeout, so let's wait for 1
3796  * second and check cancel_pressed again.
3797  */
3798  end_time = time(NULL) + 1;
3799  rc = PQsocketPoll(sock, forRead, !forRead, end_time);
3800  if (rc == -1)
3801  return;
3802 
3803  switch (PQconnectPoll(conn))
3804  {
3805  case PGRES_POLLING_OK:
3806  case PGRES_POLLING_FAILED:
3807  return;
3808  case PGRES_POLLING_READING:
3809  forRead = true;
3810  continue;
3811  case PGRES_POLLING_WRITING:
3812  forRead = false;
3813  continue;
3814  case PGRES_POLLING_ACTIVE:
3815  pg_unreachable();
3816  }
3817  }
3818 }
#define pg_unreachable()
Definition: c.h:296
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2591
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7173
int PQsocketPoll(int sock, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1086
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:94
@ PGRES_POLLING_OK
Definition: libpq-fe.h:93
@ PGRES_POLLING_READING
Definition: libpq-fe.h:91
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:92
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:90
int64 end_time
Definition: pgbench.c:175
PGconn * conn
Definition: streamutil.c:55

References cancel_pressed, conn, end_time, pg_unreachable, PGRES_POLLING_ACTIVE, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PQconnectPoll(), PQsocket(), and PQsocketPoll().

Referenced by do_connect().