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

4303 {
4304  switch (in)
4305  {
4306  case PRINT_NOTHING:
4307  return "nothing";
4308  break;
4309  case PRINT_ALIGNED:
4310  return "aligned";
4311  break;
4312  case PRINT_ASCIIDOC:
4313  return "asciidoc";
4314  break;
4315  case PRINT_CSV:
4316  return "csv";
4317  break;
4318  case PRINT_HTML:
4319  return "html";
4320  break;
4321  case PRINT_LATEX:
4322  return "latex";
4323  break;
4324  case PRINT_LATEX_LONGTABLE:
4325  return "latex-longtable";
4326  break;
4327  case PRINT_TROFF_MS:
4328  return "troff-ms";
4329  break;
4330  case PRINT_UNALIGNED:
4331  return "unaligned";
4332  break;
4333  case PRINT_WRAPPED:
4334  return "wrapped";
4335  break;
4336  }
4337  return "unknown";
4338 }
@ 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 4358 of file command.c.

4359 {
4360  switch (linestyle)
4361  {
4363  return "single";
4364  break;
4366  return "double";
4367  break;
4368  }
4369  return "unknown";
4370 }
@ 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 3772 of file command.c.

3773 {
3774  if (!pset.quiet && !pset.notty)
3775  {
3776  int client_ver = PG_VERSION_NUM;
3777  char cverbuf[32];
3778  char sverbuf[32];
3779 
3780  if (pset.sversion != client_ver)
3781  {
3782  const char *server_version;
3783 
3784  /* Try to get full text form, might include "devel" etc */
3785  server_version = PQparameterStatus(pset.db, "server_version");
3786  /* Otherwise fall back on pset.sversion */
3787  if (!server_version)
3788  {
3790  sverbuf, sizeof(sverbuf));
3791  server_version = sverbuf;
3792  }
3793 
3794  printf(_("%s (%s, server %s)\n"),
3795  pset.progname, PG_VERSION, server_version);
3796  }
3797  /* For version match, only print psql banner on startup. */
3798  else if (in_startup)
3799  printf("%s (%s)\n", pset.progname, PG_VERSION);
3800 
3801  /*
3802  * Warn if server's major version is newer than ours, or if server
3803  * predates our support cutoff (currently 9.2).
3804  */
3805  if (pset.sversion / 100 > client_ver / 100 ||
3806  pset.sversion < 90200)
3807  printf(_("WARNING: %s major version %s, server major version %s.\n"
3808  " Some psql features might not work.\n"),
3809  pset.progname,
3810  formatPGVersionNumber(client_ver, false,
3811  cverbuf, sizeof(cverbuf)),
3813  sverbuf, sizeof(sverbuf)));
3814 
3815 #ifdef WIN32
3816  if (in_startup)
3817  checkWin32Codepage();
3818 #endif
3819  printSSLInfo();
3820  printGSSInfo();
3821  }
3822 }
static void printSSLInfo(void)
Definition: command.c:3831
static void printGSSInfo(void)
Definition: command.c:3856
#define _(x)
Definition: elog.c:91
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7213
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 3244 of file command.c.

3245 {
3246  if (query_buf && query_buf->len == 0)
3247  {
3248  appendPQExpBufferStr(query_buf, previous_buf->data);
3249  return true;
3250  }
3251  return false;
3252 }
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 5741 of file command.c.

5742 {
5743  int lineno = 0;
5744  const char *lines = buf->data;
5745 
5746  while (*lines != '\0')
5747  {
5748  lineno++;
5749  /* find start of next line */
5750  lines = strchr(lines, '\n');
5751  if (!lines)
5752  break;
5753  lines++;
5754  }
5755 
5756  return lineno;
5757 }
static char * buf
Definition: pg_test_fsync.c:67

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

3220 {
3221  if (query_buf)
3222  {
3223  int new_len = conditional_stack_get_query_len(cstack);
3224 
3225  Assert(new_len >= 0 && new_len <= query_buf->len);
3226  query_buf->len = new_len;
3227  query_buf->data[new_len] = '\0';
3228  }
3229  psql_scan_set_paren_depth(scan_state,
3231 }
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:162
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:184
Assert(fmt[strlen(fmt) - 1] !='\n')
const void size_t len
void psql_scan_set_paren_depth(PsqlScanState state, int depth)

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

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

◆ do_connect()

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

Definition at line 3313 of file command.c.

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

Referenced by exec_command_connect().

◆ do_edit()

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

Definition at line 4040 of file command.c.

4042 {
4043  char fnametmp[MAXPGPATH];
4044  FILE *stream = NULL;
4045  const char *fname;
4046  bool error = false;
4047  int fd;
4048  struct stat before,
4049  after;
4050 
4051  if (filename_arg)
4052  fname = filename_arg;
4053  else
4054  {
4055  /* make a temp file to edit */
4056 #ifndef WIN32
4057  const char *tmpdir = getenv("TMPDIR");
4058 
4059  if (!tmpdir)
4060  tmpdir = "/tmp";
4061 #else
4062  char tmpdir[MAXPGPATH];
4063  int ret;
4064 
4065  ret = GetTempPath(MAXPGPATH, tmpdir);
4066  if (ret == 0 || ret > MAXPGPATH)
4067  {
4068  pg_log_error("could not locate temporary directory: %s",
4069  !ret ? strerror(errno) : "");
4070  return false;
4071  }
4072 #endif
4073 
4074  /*
4075  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4076  * current directory to the supplied path unless we use only
4077  * backslashes, so we do that.
4078  */
4079 #ifndef WIN32
4080  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4081  "/", (int) getpid());
4082 #else
4083  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4084  "" /* trailing separator already present */ , (int) getpid());
4085 #endif
4086 
4087  fname = (const char *) fnametmp;
4088 
4089  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4090  if (fd != -1)
4091  stream = fdopen(fd, "w");
4092 
4093  if (fd == -1 || !stream)
4094  {
4095  pg_log_error("could not open temporary file \"%s\": %m", fname);
4096  error = true;
4097  }
4098  else
4099  {
4100  unsigned int ql = query_buf->len;
4101 
4102  /* force newline-termination of what we send to editor */
4103  if (ql > 0 && query_buf->data[ql - 1] != '\n')
4104  {
4105  appendPQExpBufferChar(query_buf, '\n');
4106  ql++;
4107  }
4108 
4109  if (fwrite(query_buf->data, 1, ql, stream) != ql)
4110  {
4111  pg_log_error("%s: %m", fname);
4112 
4113  if (fclose(stream) != 0)
4114  pg_log_error("%s: %m", fname);
4115 
4116  if (remove(fname) != 0)
4117  pg_log_error("%s: %m", fname);
4118 
4119  error = true;
4120  }
4121  else if (fclose(stream) != 0)
4122  {
4123  pg_log_error("%s: %m", fname);
4124  if (remove(fname) != 0)
4125  pg_log_error("%s: %m", fname);
4126  error = true;
4127  }
4128  else
4129  {
4130  struct utimbuf ut;
4131 
4132  /*
4133  * Try to set the file modification time of the temporary file
4134  * a few seconds in the past. Otherwise, the low granularity
4135  * (one second, or even worse on some filesystems) that we can
4136  * portably measure with stat(2) could lead us to not
4137  * recognize a modification, if the user typed very quickly.
4138  *
4139  * This is a rather unlikely race condition, so don't error
4140  * out if the utime(2) call fails --- that would make the cure
4141  * worse than the disease.
4142  */
4143  ut.modtime = ut.actime = time(NULL) - 2;
4144  (void) utime(fname, &ut);
4145  }
4146  }
4147  }
4148 
4149  if (!error && stat(fname, &before) != 0)
4150  {
4151  pg_log_error("%s: %m", fname);
4152  error = true;
4153  }
4154 
4155  /* call editor */
4156  if (!error)
4157  error = !editFile(fname, lineno);
4158 
4159  if (!error && stat(fname, &after) != 0)
4160  {
4161  pg_log_error("%s: %m", fname);
4162  error = true;
4163  }
4164 
4165  /* file was edited if the size or modification time has changed */
4166  if (!error &&
4167  (before.st_size != after.st_size ||
4168  before.st_mtime != after.st_mtime))
4169  {
4170  stream = fopen(fname, PG_BINARY_R);
4171  if (!stream)
4172  {
4173  pg_log_error("%s: %m", fname);
4174  error = true;
4175  }
4176  else
4177  {
4178  /* read file back into query_buf */
4179  char line[1024];
4180 
4181  resetPQExpBuffer(query_buf);
4182  while (fgets(line, sizeof(line), stream) != NULL)
4183  appendPQExpBufferStr(query_buf, line);
4184 
4185  if (ferror(stream))
4186  {
4187  pg_log_error("%s: %m", fname);
4188  error = true;
4189  resetPQExpBuffer(query_buf);
4190  }
4191  else if (edited)
4192  {
4193  *edited = true;
4194  }
4195 
4196  fclose(stream);
4197  }
4198  }
4199  else
4200  {
4201  /*
4202  * If the file was not modified, and the caller requested it, discard
4203  * the query buffer.
4204  */
4205  if (discard_on_quit)
4206  resetPQExpBuffer(query_buf);
4207  }
4208 
4209  /* remove temp file */
4210  if (!filename_arg)
4211  {
4212  if (remove(fname) == -1)
4213  {
4214  pg_log_error("%s: %m", fname);
4215  error = true;
4216  }
4217  }
4218 
4219  return !error;
4220 }
#define PG_BINARY_R
Definition: c.h:1285
static bool editFile(const char *fname, int lineno)
Definition: command.c:3958
#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 4388 of file command.c.

4389 {
4390  size_t vallen = 0;
4391 
4392  Assert(param != NULL);
4393 
4394  if (value)
4395  vallen = strlen(value);
4396 
4397  /* set format */
4398  if (strcmp(param, "format") == 0)
4399  {
4400  static const struct fmt
4401  {
4402  const char *name;
4403  enum printFormat number;
4404  } formats[] =
4405  {
4406  /* remember to update error message below when adding more */
4407  {"aligned", PRINT_ALIGNED},
4408  {"asciidoc", PRINT_ASCIIDOC},
4409  {"csv", PRINT_CSV},
4410  {"html", PRINT_HTML},
4411  {"latex", PRINT_LATEX},
4412  {"troff-ms", PRINT_TROFF_MS},
4413  {"unaligned", PRINT_UNALIGNED},
4414  {"wrapped", PRINT_WRAPPED}
4415  };
4416 
4417  if (!value)
4418  ;
4419  else
4420  {
4421  int match_pos = -1;
4422 
4423  for (int i = 0; i < lengthof(formats); i++)
4424  {
4425  if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
4426  {
4427  if (match_pos < 0)
4428  match_pos = i;
4429  else
4430  {
4431  pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
4432  value,
4433  formats[match_pos].name, formats[i].name);
4434  return false;
4435  }
4436  }
4437  }
4438  if (match_pos >= 0)
4439  popt->topt.format = formats[match_pos].number;
4440  else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
4441  {
4442  /*
4443  * We must treat latex-longtable specially because latex is a
4444  * prefix of it; if both were in the table above, we'd think
4445  * "latex" is ambiguous.
4446  */
4448  }
4449  else
4450  {
4451  pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
4452  return false;
4453  }
4454  }
4455  }
4456 
4457  /* set table line style */
4458  else if (strcmp(param, "linestyle") == 0)
4459  {
4460  if (!value)
4461  ;
4462  else if (pg_strncasecmp("ascii", value, vallen) == 0)
4463  popt->topt.line_style = &pg_asciiformat;
4464  else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
4466  else if (pg_strncasecmp("unicode", value, vallen) == 0)
4467  popt->topt.line_style = &pg_utf8format;
4468  else
4469  {
4470  pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
4471  return false;
4472  }
4473  }
4474 
4475  /* set unicode border line style */
4476  else if (strcmp(param, "unicode_border_linestyle") == 0)
4477  {
4478  if (!value)
4479  ;
4480  else if (set_unicode_line_style(value, vallen,
4482  refresh_utf8format(&(popt->topt));
4483  else
4484  {
4485  pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4486  return false;
4487  }
4488  }
4489 
4490  /* set unicode column line style */
4491  else if (strcmp(param, "unicode_column_linestyle") == 0)
4492  {
4493  if (!value)
4494  ;
4495  else if (set_unicode_line_style(value, vallen,
4497  refresh_utf8format(&(popt->topt));
4498  else
4499  {
4500  pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4501  return false;
4502  }
4503  }
4504 
4505  /* set unicode header line style */
4506  else if (strcmp(param, "unicode_header_linestyle") == 0)
4507  {
4508  if (!value)
4509  ;
4510  else if (set_unicode_line_style(value, vallen,
4512  refresh_utf8format(&(popt->topt));
4513  else
4514  {
4515  pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4516  return false;
4517  }
4518  }
4519 
4520  /* set border style/width */
4521  else if (strcmp(param, "border") == 0)
4522  {
4523  if (value)
4524  popt->topt.border = atoi(value);
4525  }
4526 
4527  /* set expanded/vertical mode */
4528  else if (strcmp(param, "x") == 0 ||
4529  strcmp(param, "expanded") == 0 ||
4530  strcmp(param, "vertical") == 0)
4531  {
4532  if (value && pg_strcasecmp(value, "auto") == 0)
4533  popt->topt.expanded = 2;
4534  else if (value)
4535  {
4536  bool on_off;
4537 
4538  if (ParseVariableBool(value, NULL, &on_off))
4539  popt->topt.expanded = on_off ? 1 : 0;
4540  else
4541  {
4542  PsqlVarEnumError(param, value, "on, off, auto");
4543  return false;
4544  }
4545  }
4546  else
4547  popt->topt.expanded = !popt->topt.expanded;
4548  }
4549 
4550  /* header line width in expanded mode */
4551  else if (strcmp(param, "xheader_width") == 0)
4552  {
4553  if (!value)
4554  ;
4555  else if (pg_strcasecmp(value, "full") == 0)
4557  else if (pg_strcasecmp(value, "column") == 0)
4559  else if (pg_strcasecmp(value, "page") == 0)
4561  else
4562  {
4563  int intval = atoi(value);
4564 
4565  if (intval == 0)
4566  {
4567  pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
4568  return false;
4569  }
4570 
4572  popt->topt.expanded_header_exact_width = intval;
4573  }
4574  }
4575 
4576  /* field separator for CSV format */
4577  else if (strcmp(param, "csv_fieldsep") == 0)
4578  {
4579  if (value)
4580  {
4581  /* CSV separator has to be a one-byte character */
4582  if (strlen(value) != 1)
4583  {
4584  pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
4585  return false;
4586  }
4587  if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
4588  {
4589  pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
4590  return false;
4591  }
4592  popt->topt.csvFieldSep[0] = value[0];
4593  }
4594  }
4595 
4596  /* locale-aware numeric output */
4597  else if (strcmp(param, "numericlocale") == 0)
4598  {
4599  if (value)
4600  return ParseVariableBool(value, param, &popt->topt.numericLocale);
4601  else
4602  popt->topt.numericLocale = !popt->topt.numericLocale;
4603  }
4604 
4605  /* null display */
4606  else if (strcmp(param, "null") == 0)
4607  {
4608  if (value)
4609  {
4610  free(popt->nullPrint);
4611  popt->nullPrint = pg_strdup(value);
4612  }
4613  }
4614 
4615  /* field separator for unaligned text */
4616  else if (strcmp(param, "fieldsep") == 0)
4617  {
4618  if (value)
4619  {
4620  free(popt->topt.fieldSep.separator);
4622  popt->topt.fieldSep.separator_zero = false;
4623  }
4624  }
4625 
4626  else if (strcmp(param, "fieldsep_zero") == 0)
4627  {
4628  free(popt->topt.fieldSep.separator);
4629  popt->topt.fieldSep.separator = NULL;
4630  popt->topt.fieldSep.separator_zero = true;
4631  }
4632 
4633  /* record separator for unaligned text */
4634  else if (strcmp(param, "recordsep") == 0)
4635  {
4636  if (value)
4637  {
4638  free(popt->topt.recordSep.separator);
4640  popt->topt.recordSep.separator_zero = false;
4641  }
4642  }
4643 
4644  else if (strcmp(param, "recordsep_zero") == 0)
4645  {
4646  free(popt->topt.recordSep.separator);
4647  popt->topt.recordSep.separator = NULL;
4648  popt->topt.recordSep.separator_zero = true;
4649  }
4650 
4651  /* toggle between full and tuples-only format */
4652  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4653  {
4654  if (value)
4655  return ParseVariableBool(value, param, &popt->topt.tuples_only);
4656  else
4657  popt->topt.tuples_only = !popt->topt.tuples_only;
4658  }
4659 
4660  /* set title override */
4661  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4662  {
4663  free(popt->title);
4664  if (!value)
4665  popt->title = NULL;
4666  else
4667  popt->title = pg_strdup(value);
4668  }
4669 
4670  /* set HTML table tag options */
4671  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4672  {
4673  free(popt->topt.tableAttr);
4674  if (!value)
4675  popt->topt.tableAttr = NULL;
4676  else
4677  popt->topt.tableAttr = pg_strdup(value);
4678  }
4679 
4680  /* toggle use of pager */
4681  else if (strcmp(param, "pager") == 0)
4682  {
4683  if (value && pg_strcasecmp(value, "always") == 0)
4684  popt->topt.pager = 2;
4685  else if (value)
4686  {
4687  bool on_off;
4688 
4689  if (!ParseVariableBool(value, NULL, &on_off))
4690  {
4691  PsqlVarEnumError(param, value, "on, off, always");
4692  return false;
4693  }
4694  popt->topt.pager = on_off ? 1 : 0;
4695  }
4696  else if (popt->topt.pager == 1)
4697  popt->topt.pager = 0;
4698  else
4699  popt->topt.pager = 1;
4700  }
4701 
4702  /* set minimum lines for pager use */
4703  else if (strcmp(param, "pager_min_lines") == 0)
4704  {
4705  if (value &&
4706  !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
4707  return false;
4708  }
4709 
4710  /* disable "(x rows)" footer */
4711  else if (strcmp(param, "footer") == 0)
4712  {
4713  if (value)
4714  return ParseVariableBool(value, param, &popt->topt.default_footer);
4715  else
4716  popt->topt.default_footer = !popt->topt.default_footer;
4717  }
4718 
4719  /* set border style/width */
4720  else if (strcmp(param, "columns") == 0)
4721  {
4722  if (value)
4723  popt->topt.columns = atoi(value);
4724  }
4725  else
4726  {
4727  pg_log_error("\\pset: unknown option: %s", param);
4728  return false;
4729  }
4730 
4731  if (!quiet)
4732  printPsetInfo(param, &pset.popt);
4733 
4734  return true;
4735 }
#define lengthof(array)
Definition: c.h:777
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4345
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:4741
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3677
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 @148 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 5137 of file command.c.

5138 {
5139  int result;
5140 
5141  fflush(NULL);
5142  if (!command)
5143  {
5144  char *sys;
5145  const char *shellName;
5146 
5147  shellName = getenv("SHELL");
5148 #ifdef WIN32
5149  if (shellName == NULL)
5150  shellName = getenv("COMSPEC");
5151 #endif
5152  if (shellName == NULL)
5153  shellName = DEFAULT_SHELL;
5154 
5155  /* See EDITOR handling comment for an explanation */
5156 #ifndef WIN32
5157  sys = psprintf("exec %s", shellName);
5158 #else
5159  sys = psprintf("\"%s\"", shellName);
5160 #endif
5161  result = system(sys);
5162  free(sys);
5163  }
5164  else
5165  result = system(command);
5166 
5167  SetShellResultVariables(result);
5168 
5169  if (result == 127 || result == -1)
5170  {
5171  pg_log_error("\\!: failed");
5172  return false;
5173  }
5174  return true;
5175 }
void SetShellResultVariables(int wait_result)
Definition: common.c:462
#define DEFAULT_SHELL
Definition: command.c:5127
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 5184 of file command.c.

5185 {
5186  long sleep_ms = (long) (sleep * 1000);
5187  printQueryOpt myopt = pset.popt;
5188  const char *strftime_fmt;
5189  const char *user_title;
5190  char *title;
5191  const char *pagerprog = NULL;
5192  FILE *pagerpipe = NULL;
5193  int title_len;
5194  int res = 0;
5195 #ifndef WIN32
5196  sigset_t sigalrm_sigchld_sigint;
5197  sigset_t sigalrm_sigchld;
5198  sigset_t sigint;
5199  struct itimerval interval;
5200  bool done = false;
5201 #endif
5202 
5203  if (!query_buf || query_buf->len <= 0)
5204  {
5205  pg_log_error("\\watch cannot be used with an empty query");
5206  return false;
5207  }
5208 
5209 #ifndef WIN32
5210  sigemptyset(&sigalrm_sigchld_sigint);
5211  sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5212  sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5213  sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5214 
5215  sigemptyset(&sigalrm_sigchld);
5216  sigaddset(&sigalrm_sigchld, SIGCHLD);
5217  sigaddset(&sigalrm_sigchld, SIGALRM);
5218 
5219  sigemptyset(&sigint);
5220  sigaddset(&sigint, SIGINT);
5221 
5222  /*
5223  * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5224  * configured), to avoid races. sigwait() will receive them.
5225  */
5226  sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5227 
5228  /*
5229  * Set a timer to interrupt sigwait() so we can run the query at the
5230  * requested intervals.
5231  */
5232  interval.it_value.tv_sec = sleep_ms / 1000;
5233  interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5234  interval.it_interval = interval.it_value;
5235  if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5236  {
5237  pg_log_error("could not set timer: %m");
5238  done = true;
5239  }
5240 #endif
5241 
5242  /*
5243  * For \watch, we ignore the size of the result and always use the pager
5244  * as long as we're talking to a terminal and "\pset pager" is enabled.
5245  * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5246  * ignore the regular PSQL_PAGER or PAGER environment variables, because
5247  * traditional pagers probably won't be very useful for showing a stream
5248  * of results.
5249  */
5250 #ifndef WIN32
5251  pagerprog = getenv("PSQL_WATCH_PAGER");
5252  /* if variable is empty or all-white-space, don't use pager */
5253  if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5254  pagerprog = NULL;
5255 #endif
5256  if (pagerprog && myopt.topt.pager &&
5257  isatty(fileno(stdin)) && isatty(fileno(stdout)))
5258  {
5259  fflush(NULL);
5261  pagerpipe = popen(pagerprog, "w");
5262 
5263  if (!pagerpipe)
5264  /* silently proceed without pager */
5266  }
5267 
5268  /*
5269  * Choose format for timestamps. We might eventually make this a \pset
5270  * option. In the meantime, using a variable for the format suppresses
5271  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5272  */
5273  strftime_fmt = "%c";
5274 
5275  /*
5276  * Set up rendering options, in particular, disable the pager unless
5277  * PSQL_WATCH_PAGER was successfully launched.
5278  */
5279  if (!pagerpipe)
5280  myopt.topt.pager = 0;
5281 
5282 
5283  /*
5284  * If there's a title in the user configuration, make sure we have room
5285  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5286  * bytes for the rest.
5287  */
5288  user_title = myopt.title;
5289  title_len = (user_title ? strlen(user_title) : 0) + 256;
5290  title = pg_malloc(title_len);
5291 
5292  for (;;)
5293  {
5294  time_t timer;
5295  char timebuf[128];
5296 
5297  /*
5298  * Prepare title for output. Note that we intentionally include a
5299  * newline at the end of the title; this is somewhat historical but it
5300  * makes for reasonably nicely formatted output in simple cases.
5301  */
5302  timer = time(NULL);
5303  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5304 
5305  if (user_title)
5306  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5307  user_title, timebuf, sleep);
5308  else
5309  snprintf(title, title_len, _("%s (every %gs)\n"),
5310  timebuf, sleep);
5311  myopt.title = title;
5312 
5313  /* Run the query and print out the result */
5314  res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
5315 
5316  /*
5317  * PSQLexecWatch handles the case where we can no longer repeat the
5318  * query, and returns 0 or -1.
5319  */
5320  if (res <= 0)
5321  break;
5322 
5323  /* If we have iteration count, check that it's not exceeded yet */
5324  if (iter && (--iter <= 0))
5325  break;
5326 
5327  if (pagerpipe && ferror(pagerpipe))
5328  break;
5329 
5330  if (sleep == 0)
5331  continue;
5332 
5333 #ifdef WIN32
5334 
5335  /*
5336  * Set up cancellation of 'watch' via SIGINT. We redo this each time
5337  * through the loop since it's conceivable something inside
5338  * PSQLexecWatch could change sigint_interrupt_jmp.
5339  */
5340  if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
5341  break;
5342 
5343  /*
5344  * Enable 'watch' cancellations and wait a while before running the
5345  * query again. Break the sleep into short intervals (at most 1s).
5346  */
5347  sigint_interrupt_enabled = true;
5348  for (long i = sleep_ms; i > 0;)
5349  {
5350  long s = Min(i, 1000L);
5351 
5352  pg_usleep(s * 1000L);
5353  if (cancel_pressed)
5354  break;
5355  i -= s;
5356  }
5357  sigint_interrupt_enabled = false;
5358 #else
5359  /* sigwait() will handle SIGINT. */
5360  sigprocmask(SIG_BLOCK, &sigint, NULL);
5361  if (cancel_pressed)
5362  done = true;
5363 
5364  /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5365  while (!done)
5366  {
5367  int signal_received;
5368 
5369  errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5370  if (errno != 0)
5371  {
5372  /* Some other signal arrived? */
5373  if (errno == EINTR)
5374  continue;
5375  else
5376  {
5377  pg_log_error("could not wait for signals: %m");
5378  done = true;
5379  break;
5380  }
5381  }
5382  /* On ^C or pager exit, it's time to stop running the query. */
5383  if (signal_received == SIGINT || signal_received == SIGCHLD)
5384  done = true;
5385  /* Otherwise, we must have SIGALRM. Time to run the query again. */
5386  break;
5387  }
5388 
5389  /* Unblock SIGINT so that slow queries can be interrupted. */
5390  sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5391  if (done)
5392  break;
5393 #endif
5394  }
5395 
5396  if (pagerpipe)
5397  {
5398  pclose(pagerpipe);
5400  }
5401  else
5402  {
5403  /*
5404  * If the terminal driver echoed "^C", libedit/libreadline might be
5405  * confused about the cursor position. Therefore, inject a newline
5406  * before the next prompt is displayed. We only do this when not
5407  * using a pager, because pagers are expected to restore the screen to
5408  * a sane state on exit.
5409  */
5410  fprintf(stdout, "\n");
5411  fflush(stdout);
5412  }
5413 
5414 #ifndef WIN32
5415  /* Disable the interval timer. */
5416  memset(&interval, 0, sizeof(interval));
5417  setitimer(ITIMER_REAL, &interval, NULL);
5418  /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5419  sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5420 #endif
5421 
5422  pg_free(title);
5423  return (res >= 0);
5424 }
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:254
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:256
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
Definition: common.c:636
#define Min(x, y)
Definition: c.h:993
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
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, sigint_interrupt_enabled, sigint_interrupt_jmp, 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 5431 of file command.c.

5432 {
5434  {
5435  printf(_("/******** QUERY *********/\n"
5436  "%s\n"
5437  "/************************/\n\n"), query);
5438  fflush(stdout);
5439  if (pset.logfile)
5440  {
5442  _("/******** QUERY *********/\n"
5443  "%s\n"
5444  "/************************/\n\n"), query);
5445  fflush(pset.logfile);
5446  }
5447 
5449  return false;
5450  }
5451  return true;
5452 }
@ 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 3958 of file command.c.

3959 {
3960  const char *editorName;
3961  const char *editor_lineno_arg = NULL;
3962  char *sys;
3963  int result;
3964 
3965  Assert(fname != NULL);
3966 
3967  /* Find an editor to use */
3968  editorName = getenv("PSQL_EDITOR");
3969  if (!editorName)
3970  editorName = getenv("EDITOR");
3971  if (!editorName)
3972  editorName = getenv("VISUAL");
3973  if (!editorName)
3974  editorName = DEFAULT_EDITOR;
3975 
3976  /* Get line number argument, if we need it. */
3977  if (lineno > 0)
3978  {
3979  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
3980 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
3981  if (!editor_lineno_arg)
3982  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
3983 #endif
3984  if (!editor_lineno_arg)
3985  {
3986  pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
3987  return false;
3988  }
3989  }
3990 
3991  /*
3992  * On Unix the EDITOR value should *not* be quoted, since it might include
3993  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
3994  * if necessary. But this policy is not very workable on Windows, due to
3995  * severe brain damage in their command shell plus the fact that standard
3996  * program paths include spaces.
3997  */
3998 #ifndef WIN32
3999  if (lineno > 0)
4000  sys = psprintf("exec %s %s%d '%s'",
4001  editorName, editor_lineno_arg, lineno, fname);
4002  else
4003  sys = psprintf("exec %s '%s'",
4004  editorName, fname);
4005 #else
4006  if (lineno > 0)
4007  sys = psprintf("\"%s\" %s%d \"%s\"",
4008  editorName, editor_lineno_arg, lineno, fname);
4009  else
4010  sys = psprintf("\"%s\" \"%s\"",
4011  editorName, fname);
4012 #endif
4013  fflush(NULL);
4014  result = system(sys);
4015  if (result == -1)
4016  pg_log_error("could not start editor \"%s\"", editorName);
4017  else if (result == 127)
4018  pg_log_error("could not start /bin/sh");
4019  free(sys);
4020 
4021  return result == 0;
4022 }
#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 287 of file command.c.

292 {
293  backslashResult status;
294  bool active_branch = conditional_active(cstack);
295 
296  /*
297  * In interactive mode, warn when we're ignoring a command within a false
298  * \if-branch. But we continue on, so as to parse and discard the right
299  * amount of parameter text. Each individual backslash command subroutine
300  * is responsible for doing nothing after discarding appropriate
301  * arguments, if !active_branch.
302  */
303  if (pset.cur_cmd_interactive && !active_branch &&
304  !is_branching_command(cmd))
305  {
306  pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
307  cmd);
308  }
309 
310  if (strcmp(cmd, "a") == 0)
311  status = exec_command_a(scan_state, active_branch);
312  else if (strcmp(cmd, "bind") == 0)
313  status = exec_command_bind(scan_state, active_branch);
314  else if (strcmp(cmd, "C") == 0)
315  status = exec_command_C(scan_state, active_branch);
316  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
317  status = exec_command_connect(scan_state, active_branch);
318  else if (strcmp(cmd, "cd") == 0)
319  status = exec_command_cd(scan_state, active_branch, cmd);
320  else if (strcmp(cmd, "conninfo") == 0)
321  status = exec_command_conninfo(scan_state, active_branch);
322  else if (pg_strcasecmp(cmd, "copy") == 0)
323  status = exec_command_copy(scan_state, active_branch);
324  else if (strcmp(cmd, "copyright") == 0)
325  status = exec_command_copyright(scan_state, active_branch);
326  else if (strcmp(cmd, "crosstabview") == 0)
327  status = exec_command_crosstabview(scan_state, active_branch);
328  else if (cmd[0] == 'd')
329  status = exec_command_d(scan_state, active_branch, cmd);
330  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
331  status = exec_command_edit(scan_state, active_branch,
332  query_buf, previous_buf);
333  else if (strcmp(cmd, "ef") == 0)
334  status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
335  else if (strcmp(cmd, "ev") == 0)
336  status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
337  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
338  strcmp(cmd, "warn") == 0)
339  status = exec_command_echo(scan_state, active_branch, cmd);
340  else if (strcmp(cmd, "elif") == 0)
341  status = exec_command_elif(scan_state, cstack, query_buf);
342  else if (strcmp(cmd, "else") == 0)
343  status = exec_command_else(scan_state, cstack, query_buf);
344  else if (strcmp(cmd, "endif") == 0)
345  status = exec_command_endif(scan_state, cstack, query_buf);
346  else if (strcmp(cmd, "encoding") == 0)
347  status = exec_command_encoding(scan_state, active_branch);
348  else if (strcmp(cmd, "errverbose") == 0)
349  status = exec_command_errverbose(scan_state, active_branch);
350  else if (strcmp(cmd, "f") == 0)
351  status = exec_command_f(scan_state, active_branch);
352  else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
353  status = exec_command_g(scan_state, active_branch, cmd);
354  else if (strcmp(cmd, "gdesc") == 0)
355  status = exec_command_gdesc(scan_state, active_branch);
356  else if (strcmp(cmd, "getenv") == 0)
357  status = exec_command_getenv(scan_state, active_branch, cmd);
358  else if (strcmp(cmd, "gexec") == 0)
359  status = exec_command_gexec(scan_state, active_branch);
360  else if (strcmp(cmd, "gset") == 0)
361  status = exec_command_gset(scan_state, active_branch);
362  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
363  status = exec_command_help(scan_state, active_branch);
364  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
365  status = exec_command_html(scan_state, active_branch);
366  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
367  strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
368  status = exec_command_include(scan_state, active_branch, cmd);
369  else if (strcmp(cmd, "if") == 0)
370  status = exec_command_if(scan_state, cstack, query_buf);
371  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
372  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
373  status = exec_command_list(scan_state, active_branch, cmd);
374  else if (strncmp(cmd, "lo_", 3) == 0)
375  status = exec_command_lo(scan_state, active_branch, cmd);
376  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
377  status = exec_command_out(scan_state, active_branch);
378  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
379  status = exec_command_print(scan_state, active_branch,
380  query_buf, previous_buf);
381  else if (strcmp(cmd, "password") == 0)
382  status = exec_command_password(scan_state, active_branch);
383  else if (strcmp(cmd, "prompt") == 0)
384  status = exec_command_prompt(scan_state, active_branch, cmd);
385  else if (strcmp(cmd, "pset") == 0)
386  status = exec_command_pset(scan_state, active_branch);
387  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
388  status = exec_command_quit(scan_state, active_branch);
389  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
390  status = exec_command_reset(scan_state, active_branch, query_buf);
391  else if (strcmp(cmd, "s") == 0)
392  status = exec_command_s(scan_state, active_branch);
393  else if (strcmp(cmd, "set") == 0)
394  status = exec_command_set(scan_state, active_branch);
395  else if (strcmp(cmd, "setenv") == 0)
396  status = exec_command_setenv(scan_state, active_branch, cmd);
397  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
398  status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
399  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
400  status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
401  else if (strcmp(cmd, "t") == 0)
402  status = exec_command_t(scan_state, active_branch);
403  else if (strcmp(cmd, "T") == 0)
404  status = exec_command_T(scan_state, active_branch);
405  else if (strcmp(cmd, "timing") == 0)
406  status = exec_command_timing(scan_state, active_branch);
407  else if (strcmp(cmd, "unset") == 0)
408  status = exec_command_unset(scan_state, active_branch, cmd);
409  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
410  status = exec_command_write(scan_state, active_branch, cmd,
411  query_buf, previous_buf);
412  else if (strcmp(cmd, "watch") == 0)
413  status = exec_command_watch(scan_state, active_branch,
414  query_buf, previous_buf);
415  else if (strcmp(cmd, "x") == 0)
416  status = exec_command_x(scan_state, active_branch);
417  else if (strcmp(cmd, "z") == 0 || strcmp(cmd, "zS") == 0)
418  status = exec_command_z(scan_state, active_branch, cmd);
419  else if (strcmp(cmd, "!") == 0)
420  status = exec_command_shell_escape(scan_state, active_branch);
421  else if (strcmp(cmd, "?") == 0)
422  status = exec_command_slash_command_help(scan_state, active_branch);
423  else
424  status = PSQL_CMD_UNKNOWN;
425 
426  /*
427  * All the commands that return PSQL_CMD_SEND want to execute previous_buf
428  * if query_buf is empty. For convenience we implement that here, not in
429  * the individual command subroutines.
430  */
431  if (status == PSQL_CMD_SEND)
432  (void) copy_previous_query(query_buf, previous_buf);
433 
434  return status;
435 }
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1916
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:713
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1352
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2085
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1669
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3244
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1410
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2598
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1538
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1638
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:444
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch)
Definition: command.c:463
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2111
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2931
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1729
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1775
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1382
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2347
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2062
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1269
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:749
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2981
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:583
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1609
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1153
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2652
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2392
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2365
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2201
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2784
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1688
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1956
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2620
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:497
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1314
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1057
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1851
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:647
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:691
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3003
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:725
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2278
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2576
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2682
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2493
static bool is_branching_command(const char *cmd)
Definition: command.c:3182
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:530
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1592
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2953
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1984
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1555
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2333
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2445
@ 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 444 of file command.c.

445 {
446  bool success = true;
447 
448  if (active_branch)
449  {
451  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
452  else
453  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
454  }
455 
457 }
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4388
@ 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 463 of file command.c.

464 {
466 
467  if (active_branch)
468  {
469  char *opt;
470  int nparams = 0;
471  int nalloc = 0;
472 
473  pset.bind_params = NULL;
474 
475  while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
476  {
477  nparams++;
478  if (nparams > nalloc)
479  {
480  nalloc = nalloc ? nalloc * 2 : 1;
481  pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
482  }
483  pset.bind_params[nparams - 1] = opt;
484  }
485 
486  pset.bind_nparams = nparams;
487  pset.bind_flag = true;
488  }
489 
490  return status;
491 }
#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, 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 497 of file command.c.

498 {
499  bool success = true;
500 
501  if (active_branch)
502  {
503  char *opt = psql_scan_slash_option(scan_state,
504  OT_NORMAL, NULL, true);
505 
506  success = do_pset("title", opt, &pset.popt, pset.quiet);
507  free(opt);
508  }
509  else
510  ignore_slash_options(scan_state);
511 
513 }
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:3137

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

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

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

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

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

692 {
693  bool success = true;
694 
695  if (active_branch)
696  {
697  char *opt = psql_scan_slash_option(scan_state,
698  OT_WHOLE_LINE, NULL, false);
699 
700  success = do_copy(opt);
701  free(opt);
702  }
703  else
704  ignore_slash_whole_line(scan_state);
705 
707 }
bool do_copy(const char *args)
Definition: copy.c:268
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:3170
@ 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 713 of file command.c.

714 {
715  if (active_branch)
716  print_copyright();
717 
718  return PSQL_CMD_SKIP_LINE;
719 }
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 725 of file command.c.

726 {
728 
729  if (active_branch)
730  {
731  int i;
732 
733  for (i = 0; i < lengthof(pset.ctv_args); i++)
734  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
735  OT_NORMAL, NULL, true);
736  pset.crosstab_flag = true;
737  status = PSQL_CMD_SEND;
738  }
739  else
740  ignore_slash_options(scan_state);
741 
742  return status;
743 }
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 749 of file command.c.

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

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

1270 {
1271  if (active_branch)
1272  {
1273  char *value;
1274  char quoted;
1275  bool no_newline = false;
1276  bool first = true;
1277  FILE *fout;
1278 
1279  if (strcmp(cmd, "qecho") == 0)
1280  fout = pset.queryFout;
1281  else if (strcmp(cmd, "warn") == 0)
1282  fout = stderr;
1283  else
1284  fout = stdout;
1285 
1286  while ((value = psql_scan_slash_option(scan_state,
1287  OT_NORMAL, &quoted, false)))
1288  {
1289  if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1290  no_newline = true;
1291  else
1292  {
1293  if (first)
1294  first = false;
1295  else
1296  fputc(' ', fout);
1297  fputs(value, fout);
1298  }
1299  free(value);
1300  }
1301  if (!no_newline)
1302  fputs("\n", fout);
1303  }
1304  else
1305  ignore_slash_options(scan_state);
1306 
1307  return PSQL_CMD_SKIP_LINE;
1308 }
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 1057 of file command.c.

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

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

1777 {
1778  bool success = true;
1779 
1780  switch (conditional_stack_peek(cstack))
1781  {
1782  case IFSTATE_TRUE:
1783 
1784  /*
1785  * Just finished active branch of this \if block. Update saved
1786  * state so we will keep whatever data was put in query_buf by the
1787  * active branch.
1788  */
1789  save_query_text_state(scan_state, cstack, query_buf);
1790 
1791  /*
1792  * Discard \elif expression and ignore the rest until \endif.
1793  * Switch state before reading expression to ensure proper lexer
1794  * behavior.
1795  */
1797  ignore_boolean_expression(scan_state);
1798  break;
1799  case IFSTATE_FALSE:
1800 
1801  /*
1802  * Discard any query text added by the just-skipped branch.
1803  */
1804  discard_query_text(scan_state, cstack, query_buf);
1805 
1806  /*
1807  * Have not yet found a true expression in this \if block, so this
1808  * might be the first. We have to change state before examining
1809  * the expression, or the lexer won't do the right thing.
1810  */
1812  if (!is_true_boolean_expression(scan_state, "\\elif expression"))
1814  break;
1815  case IFSTATE_IGNORED:
1816 
1817  /*
1818  * Discard any query text added by the just-skipped branch.
1819  */
1820  discard_query_text(scan_state, cstack, query_buf);
1821 
1822  /*
1823  * Skip expression and move on. Either the \if block already had
1824  * an active section, or whole block is being skipped.
1825  */
1826  ignore_boolean_expression(scan_state);
1827  break;
1828  case IFSTATE_ELSE_TRUE:
1829  case IFSTATE_ELSE_FALSE:
1830  pg_log_error("\\elif: cannot occur after \\else");
1831  success = false;
1832  break;
1833  case IFSTATE_NONE:
1834  /* no \if to elif from */
1835  pg_log_error("\\elif: no matching \\if");
1836  success = false;
1837  break;
1838  }
1839 
1841 }
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3218
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3121
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:3104
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3198
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 1851 of file command.c.

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

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

1315 {
1316  if (active_branch)
1317  {
1318  char *encoding = psql_scan_slash_option(scan_state,
1319  OT_NORMAL, NULL, false);
1320 
1321  if (!encoding)
1322  {
1323  /* show encoding */
1325  }
1326  else
1327  {
1328  /* set encoding */
1329  if (PQsetClientEncoding(pset.db, encoding) == -1)
1330  pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1331  else
1332  {
1333  /* save encoding info into psql internal data */
1336  SetVariable(pset.vars, "ENCODING",
1338  }
1339  free(encoding);
1340  }
1341  }
1342  else
1343  ignore_slash_options(scan_state);
1344 
1345  return PSQL_CMD_SKIP_LINE;
1346 }
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7336
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7344
int32 encoding
Definition: pg_database.h:41
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 1916 of file command.c.

1918 {
1919  bool success = true;
1920 
1921  switch (conditional_stack_peek(cstack))
1922  {
1923  case IFSTATE_TRUE:
1924  case IFSTATE_ELSE_TRUE:
1925  /* Close the \if block, keeping the query text */
1926  success = conditional_stack_pop(cstack);
1927  Assert(success);
1928  break;
1929  case IFSTATE_FALSE:
1930  case IFSTATE_IGNORED:
1931  case IFSTATE_ELSE_FALSE:
1932 
1933  /*
1934  * Discard any query text added by the just-skipped branch.
1935  */
1936  discard_query_text(scan_state, cstack, query_buf);
1937 
1938  /* Close the \if block */
1939  success = conditional_stack_pop(cstack);
1940  Assert(success);
1941  break;
1942  case IFSTATE_NONE:
1943  /* no \if to end */
1944  pg_log_error("\\endif: no matching \\if");
1945  success = false;
1946  break;
1947  }
1948 
1950 }
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 1352 of file command.c.

1353 {
1354  if (active_branch)
1355  {
1356  if (pset.last_error_result)
1357  {
1358  char *msg;
1359 
1363  if (msg)
1364  {
1365  pg_log_error("%s", msg);
1366  PQfreemem(msg);
1367  }
1368  else
1369  puts(_("out of memory"));
1370  }
1371  else
1372  puts(_("There is no previous error."));
1373  }
1374 
1375  return PSQL_CMD_SKIP_LINE;
1376 }
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3349
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
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 1382 of file command.c.

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

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

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

1539 {
1541 
1542  if (active_branch)
1543  {
1544  pset.gdesc_flag = true;
1545  status = PSQL_CMD_SEND;
1546  }
1547 
1548  return status;
1549 }
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 1555 of file command.c.

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

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

1593 {
1595 
1596  if (active_branch)
1597  {
1598  pset.gexec_flag = true;
1599  status = PSQL_CMD_SEND;
1600  }
1601 
1602  return status;
1603 }
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 1609 of file command.c.

1610 {
1612 
1613  if (active_branch)
1614  {
1615  char *prefix = psql_scan_slash_option(scan_state,
1616  OT_NORMAL, NULL, false);
1617 
1618  if (prefix)
1619  pset.gset_prefix = prefix;
1620  else
1621  {
1622  /* we must set a non-NULL prefix to trigger storing */
1623  pset.gset_prefix = pg_strdup("");
1624  }
1625  /* gset_prefix is freed later */
1626  status = PSQL_CMD_SEND;
1627  }
1628  else
1629  ignore_slash_options(scan_state);
1630 
1631  return status;
1632 }
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 1638 of file command.c.

1639 {
1640  if (active_branch)
1641  {
1642  char *opt = psql_scan_slash_option(scan_state,
1643  OT_WHOLE_LINE, NULL, false);
1644  size_t len;
1645 
1646  /* strip any trailing spaces and semicolons */
1647  if (opt)
1648  {
1649  len = strlen(opt);
1650  while (len > 0 &&
1651  (isspace((unsigned char) opt[len - 1])
1652  || opt[len - 1] == ';'))
1653  opt[--len] = '\0';
1654  }
1655 
1656  helpSQL(opt, pset.popt.topt.pager);
1657  free(opt);
1658  }
1659  else
1660  ignore_slash_whole_line(scan_state);
1661 
1662  return PSQL_CMD_SKIP_LINE;
1663 }
void helpSQL(const char *topic, unsigned short int pager)

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

Referenced by exec_command().

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1669 of file command.c.

1670 {
1671  bool success = true;
1672 
1673  if (active_branch)
1674  {
1675  if (pset.popt.topt.format != PRINT_HTML)
1676  success = do_pset("format", "html", &pset.popt, pset.quiet);
1677  else
1678  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1679  }
1680 
1682 }

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

1731 {
1732  if (conditional_active(cstack))
1733  {
1734  /*
1735  * First, push a new active stack entry; this ensures that the lexer
1736  * will perform variable substitution and backtick evaluation while
1737  * scanning the expression. (That should happen anyway, since we know
1738  * we're in an active outer branch, but let's be sure.)
1739  */
1741 
1742  /* Remember current query state in case we need to restore later */
1743  save_query_text_state(scan_state, cstack, query_buf);
1744 
1745  /*
1746  * Evaluate the expression; if it's false, change to inactive state.
1747  */
1748  if (!is_true_boolean_expression(scan_state, "\\if expression"))
1750  }
1751  else
1752  {
1753  /*
1754  * We're within an inactive outer branch, so this entire \if block
1755  * will be ignored. We don't want to evaluate the expression, so push
1756  * the "ignored" stack state before scanning it.
1757  */
1759 
1760  /* Remember current query state in case we need to restore later */
1761  save_query_text_state(scan_state, cstack, query_buf);
1762 
1763  ignore_boolean_expression(scan_state);
1764  }
1765 
1766  return PSQL_CMD_SKIP_LINE;
1767 }
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 1688 of file command.c.

1689 {
1690  bool success = true;
1691 
1692  if (active_branch)
1693  {
1694  char *fname = psql_scan_slash_option(scan_state,
1695  OT_NORMAL, NULL, true);
1696 
1697  if (!fname)
1698  {
1699  pg_log_error("\\%s: missing required argument", cmd);
1700  success = false;
1701  }
1702  else
1703  {
1704  bool include_relative;
1705 
1706  include_relative = (strcmp(cmd, "ir") == 0
1707  || strcmp(cmd, "include_relative") == 0);
1708  expand_tilde(&fname);
1709  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1710  free(fname);
1711  }
1712  }
1713  else
1714  ignore_slash_options(scan_state);
1715 
1717 }
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4235
#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 1956 of file command.c.

1957 {
1958  bool success = true;
1959 
1960  if (active_branch)
1961  {
1962  char *pattern;
1963  bool show_verbose;
1964 
1965  pattern = psql_scan_slash_option(scan_state,
1966  OT_NORMAL, NULL, true);
1967 
1968  show_verbose = strchr(cmd, '+') ? true : false;
1969 
1970  success = listAllDbs(pattern, show_verbose);
1971 
1972  free(pattern);
1973  }
1974  else
1975  ignore_slash_options(scan_state);
1976 
1978 }
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:917

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

1985 {
1987  bool success = true;
1988 
1989  if (active_branch)
1990  {
1991  char *opt1,
1992  *opt2;
1993 
1994  opt1 = psql_scan_slash_option(scan_state,
1995  OT_NORMAL, NULL, true);
1996  opt2 = psql_scan_slash_option(scan_state,
1997  OT_NORMAL, NULL, true);
1998 
1999  if (strcmp(cmd + 3, "export") == 0)
2000  {
2001  if (!opt2)
2002  {
2003  pg_log_error("\\%s: missing required argument", cmd);
2004  success = false;
2005  }
2006  else
2007  {
2008  expand_tilde(&opt2);
2009  success = do_lo_export(opt1, opt2);
2010  }
2011  }
2012 
2013  else if (strcmp(cmd + 3, "import") == 0)
2014  {
2015  if (!opt1)
2016  {
2017  pg_log_error("\\%s: missing required argument", cmd);
2018  success = false;
2019  }
2020  else
2021  {
2022  expand_tilde(&opt1);
2023  success = do_lo_import(opt1, opt2);
2024  }
2025  }
2026 
2027  else if (strcmp(cmd + 3, "list") == 0)
2028  success = listLargeObjects(false);
2029  else if (strcmp(cmd + 3, "list+") == 0)
2030  success = listLargeObjects(true);
2031 
2032  else if (strcmp(cmd + 3, "unlink") == 0)
2033  {
2034  if (!opt1)
2035  {
2036  pg_log_error("\\%s: missing required argument", cmd);
2037  success = false;
2038  }
2039  else
2040  success = do_lo_unlink(opt1);
2041  }
2042 
2043  else
2044  status = PSQL_CMD_UNKNOWN;
2045 
2046  free(opt1);
2047  free(opt2);
2048  }
2049  else
2050  ignore_slash_options(scan_state);
2051 
2052  if (!success)
2053  status = PSQL_CMD_ERROR;
2054 
2055  return status;
2056 }
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 2062 of file command.c.

2063 {
2064  bool success = true;
2065 
2066  if (active_branch)
2067  {
2068  char *fname = psql_scan_slash_option(scan_state,
2069  OT_FILEPIPE, NULL, true);
2070 
2071  expand_tilde(&fname);
2072  success = setQFout(fname);
2073  free(fname);
2074  }
2075  else
2076  ignore_slash_filepipe(scan_state);
2077 
2079 }
bool setQFout(const char *fname)
Definition: common.c:94
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:3154

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

2112 {
2113  bool success = true;
2114 
2115  if (active_branch)
2116  {
2117  char *user = psql_scan_slash_option(scan_state,
2118  OT_SQLID, NULL, true);
2119  char *pw1 = NULL;
2120  char *pw2 = NULL;
2122  PromptInterruptContext prompt_ctx;
2123 
2124  if (user == NULL)
2125  {
2126  /* By default, the command applies to CURRENT_USER */
2127  PGresult *res;
2128 
2129  res = PSQLexec("SELECT CURRENT_USER");
2130  if (!res)
2131  return PSQL_CMD_ERROR;
2132 
2133  user = pg_strdup(PQgetvalue(res, 0, 0));
2134  PQclear(res);
2135  }
2136 
2137  /* Set up to let SIGINT cancel simple_prompt_extended() */
2138  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2139  prompt_ctx.enabled = &sigint_interrupt_enabled;
2140  prompt_ctx.canceled = false;
2141 
2142  initPQExpBuffer(&buf);
2143  printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2144 
2145  pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2146  if (!prompt_ctx.canceled)
2147  pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2148 
2149  if (prompt_ctx.canceled)
2150  {
2151  /* fail silently */
2152  success = false;
2153  }
2154  else if (strcmp(pw1, pw2) != 0)
2155  {
2156  pg_log_error("Passwords didn't match.");
2157  success = false;
2158  }
2159  else
2160  {
2161  char *encrypted_password;
2162 
2163  encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
2164 
2165  if (!encrypted_password)
2166  {
2168  success = false;
2169  }
2170  else
2171  {
2172  PGresult *res;
2173 
2174  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
2175  fmtId(user));
2176  appendStringLiteralConn(&buf, encrypted_password, pset.db);
2177  res = PSQLexec(buf.data);
2178  if (!res)
2179  success = false;
2180  else
2181  PQclear(res);
2182  PQfreemem(encrypted_password);
2183  }
2184  }
2185 
2186  free(user);
2187  free(pw1);
2188  free(pw2);
2189  termPQExpBuffer(&buf);
2190  }
2191  else
2192  ignore_slash_options(scan_state);
2193 
2195 }
PGresult * PSQLexec(const char *query)
Definition: common.c:581
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1277
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3790
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
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
volatile sig_atomic_t * enabled
Definition: string.h:21

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

Referenced by exec_command().

◆ exec_command_print()

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

Definition at line 2085 of file command.c.

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

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

2203 {
2204  bool success = true;
2205 
2206  if (active_branch)
2207  {
2208  char *opt,
2209  *prompt_text = NULL;
2210  char *arg1,
2211  *arg2;
2212 
2213  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2214  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2215 
2216  if (!arg1)
2217  {
2218  pg_log_error("\\%s: missing required argument", cmd);
2219  success = false;
2220  }
2221  else
2222  {
2223  char *result;
2224  PromptInterruptContext prompt_ctx;
2225 
2226  /* Set up to let SIGINT cancel simple_prompt_extended() */
2227  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2228  prompt_ctx.enabled = &sigint_interrupt_enabled;
2229  prompt_ctx.canceled = false;
2230 
2231  if (arg2)
2232  {
2233  prompt_text = arg1;
2234  opt = arg2;
2235  }
2236  else
2237  opt = arg1;
2238 
2239  if (!pset.inputfile)
2240  {
2241  result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2242  }
2243  else
2244  {
2245  if (prompt_text)
2246  {
2247  fputs(prompt_text, stdout);
2248  fflush(stdout);
2249  }
2250  result = gets_fromFile(stdin);
2251  if (!result)
2252  {
2253  pg_log_error("\\%s: could not read value for variable",
2254  cmd);
2255  success = false;
2256  }
2257  }
2258 
2259  if (prompt_ctx.canceled ||
2260  (result && !SetVariable(pset.vars, opt, result)))
2261  success = false;
2262 
2263  free(result);
2264  free(prompt_text);
2265  free(opt);
2266  }
2267  }
2268  else
2269  ignore_slash_options(scan_state);
2270 
2272 }
char * gets_fromFile(FILE *source)
Definition: input.c:187
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 2278 of file command.c.

2279 {
2280  bool success = true;
2281 
2282  if (active_branch)
2283  {
2284  char *opt0 = psql_scan_slash_option(scan_state,
2285  OT_NORMAL, NULL, false);
2286  char *opt1 = psql_scan_slash_option(scan_state,
2287  OT_NORMAL, NULL, false);
2288 
2289  if (!opt0)
2290  {
2291  /* list all variables */
2292 
2293  int i;
2294  static const char *const my_list[] = {
2295  "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2296  "fieldsep_zero", "footer", "format", "linestyle", "null",
2297  "numericlocale", "pager", "pager_min_lines",
2298  "recordsep", "recordsep_zero",
2299  "tableattr", "title", "tuples_only",
2300  "unicode_border_linestyle",
2301  "unicode_column_linestyle",
2302  "unicode_header_linestyle",
2303  "xheader_width",
2304  NULL
2305  };
2306 
2307  for (i = 0; my_list[i] != NULL; i++)
2308  {
2309  char *val = pset_value_string(my_list[i], &pset.popt);
2310 
2311  printf("%-24s %s\n", my_list[i], val);
2312  free(val);
2313  }
2314 
2315  success = true;
2316  }
2317  else
2318  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2319 
2320  free(opt0);
2321  free(opt1);
2322  }
2323  else
2324  ignore_slash_options(scan_state);
2325 
2327 }
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:5048
long val
Definition: informix.c:664

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

Referenced by exec_command().

◆ exec_command_quit()

static backslashResult exec_command_quit ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2333 of file command.c.

2334 {
2336 
2337  if (active_branch)
2338  status = PSQL_CMD_TERMINATE;
2339 
2340  return status;
2341 }
@ 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 2347 of file command.c.

2349 {
2350  if (active_branch)
2351  {
2352  resetPQExpBuffer(query_buf);
2353  psql_scan_reset(scan_state);
2354  if (!pset.quiet)
2355  puts(_("Query buffer reset (cleared)."));
2356  }
2357 
2358  return PSQL_CMD_SKIP_LINE;
2359 }
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 2365 of file command.c.

2366 {
2367  bool success = true;
2368 
2369  if (active_branch)
2370  {
2371  char *fname = psql_scan_slash_option(scan_state,
2372  OT_NORMAL, NULL, true);
2373 
2374  expand_tilde(&fname);
2375  success = printHistory(fname, pset.popt.topt.pager);
2376  if (success && !pset.quiet && fname)
2377  printf(_("Wrote history to file \"%s\".\n"), fname);
2378  if (!fname)
2379  putchar('\n');
2380  free(fname);
2381  }
2382  else
2383  ignore_slash_options(scan_state);
2384 
2386 }
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:495

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

2393 {
2394  bool success = true;
2395 
2396  if (active_branch)
2397  {
2398  char *opt0 = psql_scan_slash_option(scan_state,
2399  OT_NORMAL, NULL, false);
2400 
2401  if (!opt0)
2402  {
2403  /* list all variables */
2405  success = true;
2406  }
2407  else
2408  {
2409  /*
2410  * Set variable to the concatenation of the arguments.
2411  */
2412  char *newval;
2413  char *opt;
2414 
2415  opt = psql_scan_slash_option(scan_state,
2416  OT_NORMAL, NULL, false);
2417  newval = pg_strdup(opt ? opt : "");
2418  free(opt);
2419 
2420  while ((opt = psql_scan_slash_option(scan_state,
2421  OT_NORMAL, NULL, false)))
2422  {
2423  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2424  strcat(newval, opt);
2425  free(opt);
2426  }
2427 
2428  if (!SetVariable(pset.vars, opt0, newval))
2429  success = false;
2430 
2431  free(newval);
2432  }
2433  free(opt0);
2434  }
2435  else
2436  ignore_slash_options(scan_state);
2437 
2439 }
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 2445 of file command.c.

2447 {
2448  bool success = true;
2449 
2450  if (active_branch)
2451  {
2452  char *envvar = psql_scan_slash_option(scan_state,
2453  OT_NORMAL, NULL, false);
2454  char *envval = psql_scan_slash_option(scan_state,
2455  OT_NORMAL, NULL, false);
2456 
2457  if (!envvar)
2458  {
2459  pg_log_error("\\%s: missing required argument", cmd);
2460  success = false;
2461  }
2462  else if (strchr(envvar, '=') != NULL)
2463  {
2464  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2465  cmd);
2466  success = false;
2467  }
2468  else if (!envval)
2469  {
2470  /* No argument - unset the environment variable */
2471  unsetenv(envvar);
2472  success = true;
2473  }
2474  else
2475  {
2476  /* Set variable to the value of the next argument */
2477  setenv(envvar, envval, 1);
2478  success = true;
2479  }
2480  free(envvar);
2481  free(envval);
2482  }
2483  else
2484  ignore_slash_options(scan_state);
2485 
2487 }
#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 2493 of file command.c.

2495 {
2497 
2498  if (active_branch)
2499  {
2500  bool show_linenumbers = (strchr(cmd, '+') != NULL);
2501  PQExpBuffer buf;
2502  char *obj_desc;
2503  Oid obj_oid = InvalidOid;
2505 
2506  buf = createPQExpBuffer();
2507  obj_desc = psql_scan_slash_option(scan_state,
2508  OT_WHOLE_LINE, NULL, true);
2509  if (!obj_desc)
2510  {
2511  if (is_func)
2512  pg_log_error("function name is required");
2513  else
2514  pg_log_error("view name is required");
2515  status = PSQL_CMD_ERROR;
2516  }
2517  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2518  {
2519  /* error already reported */
2520  status = PSQL_CMD_ERROR;
2521  }
2522  else if (!get_create_object_cmd(eot, obj_oid, buf))
2523  {
2524  /* error already reported */
2525  status = PSQL_CMD_ERROR;
2526  }
2527  else
2528  {
2529  FILE *output;
2530  bool is_pager;
2531 
2532  /* Select output stream: stdout, pager, or file */
2533  if (pset.queryFout == stdout)
2534  {
2535  /* count lines in function to see if pager is needed */
2536  int lineno = count_lines_in_buf(buf);
2537 
2538  output = PageOutput(lineno, &(pset.popt.topt));
2539  is_pager = true;
2540  }
2541  else
2542  {
2543  /* use previously set output file, without pager */
2544  output = pset.queryFout;
2545  is_pager = false;
2546  }
2547 
2548  if (show_linenumbers)
2549  {
2550  /* add line numbers */
2551  print_with_linenumbers(output, buf->data, is_func);
2552  }
2553  else
2554  {
2555  /* just send the definition to output */
2556  fputs(buf->data, output);
2557  }
2558 
2559  if (is_pager)
2560  ClosePager(output);
2561  }
2562 
2563  free(obj_desc);
2565  }
2566  else
2567  ignore_slash_whole_line(scan_state);
2568 
2569  return status;
2570 }
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:5741
static void print_with_linenumbers(FILE *output, char *lines, bool is_func)
Definition: command.c:5771
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 2981 of file command.c.

2982 {
2983  bool success = true;
2984 
2985  if (active_branch)
2986  {
2987  char *opt = psql_scan_slash_option(scan_state,
2988  OT_WHOLE_LINE, NULL, false);
2989 
2990  success = do_shell(opt);
2991  free(opt);
2992  }
2993  else
2994  ignore_slash_whole_line(scan_state);
2995 
2997 }
static bool do_shell(const char *command)
Definition: command.c:5137

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

3004 {
3005  if (active_branch)
3006  {
3007  char *opt0 = psql_scan_slash_option(scan_state,
3008  OT_NORMAL, NULL, false);
3009 
3010  if (!opt0 || strcmp(opt0, "commands") == 0)
3012  else if (strcmp(opt0, "options") == 0)
3014  else if (strcmp(opt0, "variables") == 0)
3016  else
3018 
3019  free(opt0);
3020  }
3021  else
3022  ignore_slash_options(scan_state);
3023 
3024  return PSQL_CMD_SKIP_LINE;
3025 }
void slashUsage(unsigned short int pager)
Definition: help.c:176
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 2576 of file command.c.

2577 {
2578  bool success = true;
2579 
2580  if (active_branch)
2581  {
2582  char *opt = psql_scan_slash_option(scan_state,
2583  OT_NORMAL, NULL, true);
2584 
2585  success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
2586  free(opt);
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, and success.

Referenced by exec_command().

◆ exec_command_T()

static backslashResult exec_command_T ( 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 *value = psql_scan_slash_option(scan_state,
2605  OT_NORMAL, NULL, false);
2606 
2607  success = do_pset("tableattr", value, &pset.popt, pset.quiet);
2608  free(value);
2609  }
2610  else
2611  ignore_slash_options(scan_state);
2612 
2614 }

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

2621 {
2622  bool success = true;
2623 
2624  if (active_branch)
2625  {
2626  char *opt = psql_scan_slash_option(scan_state,
2627  OT_NORMAL, NULL, false);
2628 
2629  if (opt)
2630  success = ParseVariableBool(opt, "\\timing", &pset.timing);
2631  else
2632  pset.timing = !pset.timing;
2633  if (!pset.quiet)
2634  {
2635  if (pset.timing)
2636  puts(_("Timing is on."));
2637  else
2638  puts(_("Timing is off."));
2639  }
2640  free(opt);
2641  }
2642  else
2643  ignore_slash_options(scan_state);
2644 
2646 }

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

2654 {
2655  bool success = true;
2656 
2657  if (active_branch)
2658  {
2659  char *opt = psql_scan_slash_option(scan_state,
2660  OT_NORMAL, NULL, false);
2661 
2662  if (!opt)
2663  {
2664  pg_log_error("\\%s: missing required argument", cmd);
2665  success = false;
2666  }
2667  else if (!SetVariable(pset.vars, opt, NULL))
2668  success = false;
2669 
2670  free(opt);
2671  }
2672  else
2673  ignore_slash_options(scan_state);
2674 
2676 }

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

2786 {
2787  bool success = true;
2788 
2789  if (active_branch)
2790  {
2791  bool have_sleep = false;
2792  bool have_iter = false;
2793  bool have_min_rows = false;
2794  double sleep = 2;
2795  int iter = 0;
2796  int min_rows = 0;
2797 
2798  /*
2799  * Parse arguments. We allow either an unlabeled interval or
2800  * "name=value", where name is from the set ('i', 'interval', 'c',
2801  * 'count', 'm', 'min_rows').
2802  */
2803  while (success)
2804  {
2805  char *opt = psql_scan_slash_option(scan_state,
2806  OT_NORMAL, NULL, true);
2807  char *valptr;
2808  char *opt_end;
2809 
2810  if (!opt)
2811  break; /* no more arguments */
2812 
2813  valptr = strchr(opt, '=');
2814  if (valptr)
2815  {
2816  /* Labeled argument */
2817  valptr++;
2818  if (strncmp("i=", opt, strlen("i=")) == 0 ||
2819  strncmp("interval=", opt, strlen("interval=")) == 0)
2820  {
2821  if (have_sleep)
2822  {
2823  pg_log_error("\\