PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 "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/pqcomm.h"
#include "mainloop.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_bind_named (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
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_close (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_parse (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_password (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_prompt (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_pset (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_quit (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_reset (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
 
static backslashResult exec_command_s (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_set (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_setenv (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_sf_sv (PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
 
static backslashResult exec_command_t (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_T (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_timing (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_unset (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_write (PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_watch (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_x (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_z (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_shell_escape (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_slash_command_help (PsqlScanState scan_state, bool active_branch)
 
static char * read_connect_arg (PsqlScanState scan_state)
 
static PQExpBuffer gather_boolean_expression (PsqlScanState scan_state)
 
static bool is_true_boolean_expression (PsqlScanState scan_state, const char *name)
 
static void ignore_boolean_expression (PsqlScanState scan_state)
 
static void ignore_slash_options (PsqlScanState scan_state)
 
static void ignore_slash_filepipe (PsqlScanState scan_state)
 
static void ignore_slash_whole_line (PsqlScanState scan_state)
 
static bool is_branching_command (const char *cmd)
 
static void save_query_text_state (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static void discard_query_text (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static bool copy_previous_query (PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static bool do_connect (enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
 
static void wait_until_connected (PGconn *conn)
 
static bool do_edit (const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
 
static bool do_shell (const char *command)
 
static bool do_watch (PQExpBuffer query_buf, double sleep, int iter, int min_rows)
 
static bool lookup_object_oid (EditableObjectType obj_type, const char *desc, Oid *obj_oid)
 
static bool get_create_object_cmd (EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
 
static int strip_lineno_from_objdesc (char *obj)
 
static int count_lines_in_buf (PQExpBuffer buf)
 
static void print_with_linenumbers (FILE *output, char *lines, bool is_func)
 
static void minimal_error_message (PGresult *res)
 
static void printSSLInfo (void)
 
static void printGSSInfo (void)
 
static bool printPsetInfo (const char *param, printQueryOpt *popt)
 
static char * pset_value_string (const char *param, printQueryOpt *popt)
 
backslashResult HandleSlashCmds (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static char * prompt_for_password (const char *username, bool *canceled)
 
static bool param_is_newly_set (const char *old_val, const char *new_val)
 
void connection_warnings (bool in_startup)
 
void SyncVariables (void)
 
void UnsyncVariables (void)
 
static bool editFile (const char *fname, int lineno)
 
int process_file (char *filename, bool use_relative_path)
 
static const char * _align2string (enum printFormat in)
 
static bool set_unicode_line_style (const char *value, size_t vallen, unicode_linestyle *linestyle)
 
static const char * _unicode_linestyle2string (int linestyle)
 
bool do_pset (const char *param, const char *value, printQueryOpt *popt, bool quiet)
 
printQueryOptsavePsetInfo (const printQueryOpt *popt)
 
void restorePsetInfo (printQueryOpt *popt, printQueryOpt *save)
 
static const char * pset_bool_string (bool val)
 
static char * pset_quoted_string (const char *str)
 
static bool echo_hidden_command (const char *query)
 

Macro Definition Documentation

◆ DEFAULT_SHELL

#define DEFAULT_SHELL   "/bin/sh"

Definition at line 5304 of file command.c.

Typedef Documentation

◆ EditableObjectType

Enumeration Type Documentation

◆ EditableObjectType

Enumerator
EditableFunction 
EditableView 

Definition at line 50 of file command.c.

51 {
EditableObjectType
Definition: command.c:51
@ EditableFunction
Definition: command.c:52
@ EditableView
Definition: command.c:53

Function Documentation

◆ _align2string()

static const char* _align2string ( enum printFormat  in)
static

Definition at line 4479 of file command.c.

4480 {
4481  switch (in)
4482  {
4483  case PRINT_NOTHING:
4484  return "nothing";
4485  break;
4486  case PRINT_ALIGNED:
4487  return "aligned";
4488  break;
4489  case PRINT_ASCIIDOC:
4490  return "asciidoc";
4491  break;
4492  case PRINT_CSV:
4493  return "csv";
4494  break;
4495  case PRINT_HTML:
4496  return "html";
4497  break;
4498  case PRINT_LATEX:
4499  return "latex";
4500  break;
4501  case PRINT_LATEX_LONGTABLE:
4502  return "latex-longtable";
4503  break;
4504  case PRINT_TROFF_MS:
4505  return "troff-ms";
4506  break;
4507  case PRINT_UNALIGNED:
4508  return "unaligned";
4509  break;
4510  case PRINT_WRAPPED:
4511  return "wrapped";
4512  break;
4513  }
4514  return "unknown";
4515 }
@ 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 4535 of file command.c.

4536 {
4537  switch (linestyle)
4538  {
4540  return "single";
4541  break;
4543  return "double";
4544  break;
4545  }
4546  return "unknown";
4547 }
@ 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 3946 of file command.c.

3947 {
3948  if (!pset.quiet && !pset.notty)
3949  {
3950  int client_ver = PG_VERSION_NUM;
3951  char cverbuf[32];
3952  char sverbuf[32];
3953 
3954  if (pset.sversion != client_ver)
3955  {
3956  const char *server_version;
3957 
3958  /* Try to get full text form, might include "devel" etc */
3959  server_version = PQparameterStatus(pset.db, "server_version");
3960  /* Otherwise fall back on pset.sversion */
3961  if (!server_version)
3962  {
3964  sverbuf, sizeof(sverbuf));
3965  server_version = sverbuf;
3966  }
3967 
3968  printf(_("%s (%s, server %s)\n"),
3969  pset.progname, PG_VERSION, server_version);
3970  }
3971  /* For version match, only print psql banner on startup. */
3972  else if (in_startup)
3973  printf("%s (%s)\n", pset.progname, PG_VERSION);
3974 
3975  /*
3976  * Warn if server's major version is newer than ours, or if server
3977  * predates our support cutoff (currently 9.2).
3978  */
3979  if (pset.sversion / 100 > client_ver / 100 ||
3980  pset.sversion < 90200)
3981  printf(_("WARNING: %s major version %s, server major version %s.\n"
3982  " Some psql features might not work.\n"),
3983  pset.progname,
3984  formatPGVersionNumber(client_ver, false,
3985  cverbuf, sizeof(cverbuf)),
3987  sverbuf, sizeof(sverbuf)));
3988 
3989 #ifdef WIN32
3990  if (in_startup)
3991  checkWin32Codepage();
3992 #endif
3993  printSSLInfo();
3994  printGSSInfo();
3995  }
3996 }
static void printSSLInfo(void)
Definition: command.c:4005
static void printGSSInfo(void)
Definition: command.c:4033
#define _(x)
Definition: elog.c:90
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7155
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:91
const char * progname
Definition: settings.h:124

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

3352 {
3353  if (query_buf && query_buf->len == 0)
3354  {
3355  appendPQExpBufferStr(query_buf, previous_buf->data);
3356  return true;
3357  }
3358  return false;
3359 }
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 5916 of file command.c.

5917 {
5918  int lineno = 0;
5919  const char *lines = buf->data;
5920 
5921  while (*lines != '\0')
5922  {
5923  lineno++;
5924  /* find start of next line */
5925  lines = strchr(lines, '\n');
5926  if (!lines)
5927  break;
5928  lines++;
5929  }
5930 
5931  return lineno;
5932 }
static char * buf
Definition: pg_test_fsync.c:72

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

3327 {
3328  if (query_buf)
3329  {
3330  int new_len = conditional_stack_get_query_len(cstack);
3331 
3332  Assert(new_len >= 0 && new_len <= query_buf->len);
3333  query_buf->len = new_len;
3334  query_buf->data[new_len] = '\0';
3335  }
3336  psql_scan_set_paren_depth(scan_state,
3338 }
#define Assert(condition)
Definition: c.h:863
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:162
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:184
const void size_t len
void psql_scan_set_paren_depth(PsqlScanState state, int depth)

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

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

◆ do_connect()

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

Definition at line 3420 of file command.c.

3422 {
3423  PGconn *o_conn = pset.db,
3424  *n_conn = NULL;
3425  PQconninfoOption *cinfo;
3426  int nconnopts = 0;
3427  bool same_host = false;
3428  char *password = NULL;
3429  char *client_encoding;
3430  bool success = true;
3431  bool keep_password = true;
3432  bool has_connection_string;
3433  bool reuse_previous;
3434 
3435  has_connection_string = dbname ?
3437 
3438  /* Complain if we have additional arguments after a connection string. */
3439  if (has_connection_string && (user || host || port))
3440  {
3441  pg_log_error("Do not give user, host, or port separately when using a connection string");
3442  return false;
3443  }
3444 
3445  switch (reuse_previous_specification)
3446  {
3447  case TRI_YES:
3448  reuse_previous = true;
3449  break;
3450  case TRI_NO:
3451  reuse_previous = false;
3452  break;
3453  default:
3454  reuse_previous = !has_connection_string;
3455  break;
3456  }
3457 
3458  /*
3459  * If we intend to re-use connection parameters, collect them out of the
3460  * old connection, then replace individual values as necessary. (We may
3461  * need to resort to looking at pset.dead_conn, if the connection died
3462  * previously.) Otherwise, obtain a PQconninfoOption array containing
3463  * libpq's defaults, and modify that. Note this function assumes that
3464  * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3465  * containing the same options in the same order.
3466  */
3467  if (reuse_previous)
3468  {
3469  if (o_conn)
3470  cinfo = PQconninfo(o_conn);
3471  else if (pset.dead_conn)
3472  cinfo = PQconninfo(pset.dead_conn);
3473  else
3474  {
3475  /* This is reachable after a non-interactive \connect failure */
3476  pg_log_error("No database connection exists to re-use parameters from");
3477  return false;
3478  }
3479  }
3480  else
3481  cinfo = PQconndefaults();
3482 
3483  if (cinfo)
3484  {
3485  if (has_connection_string)
3486  {
3487  /* Parse the connstring and insert values into cinfo */
3488  PQconninfoOption *replcinfo;
3489  char *errmsg;
3490 
3491  replcinfo = PQconninfoParse(dbname, &errmsg);
3492  if (replcinfo)
3493  {
3494  PQconninfoOption *ci;
3495  PQconninfoOption *replci;
3496  bool have_password = false;
3497 
3498  for (ci = cinfo, replci = replcinfo;
3499  ci->keyword && replci->keyword;
3500  ci++, replci++)
3501  {
3502  Assert(strcmp(ci->keyword, replci->keyword) == 0);
3503  /* Insert value from connstring if one was provided */
3504  if (replci->val)
3505  {
3506  /*
3507  * We know that both val strings were allocated by
3508  * libpq, so the least messy way to avoid memory leaks
3509  * is to swap them.
3510  */
3511  char *swap = replci->val;
3512 
3513  replci->val = ci->val;
3514  ci->val = swap;
3515 
3516  /*
3517  * Check whether connstring provides options affecting
3518  * password re-use. While any change in user, host,
3519  * hostaddr, or port causes us to ignore the old
3520  * connection's password, we don't force that for
3521  * dbname, since passwords aren't database-specific.
3522  */
3523  if (replci->val == NULL ||
3524  strcmp(ci->val, replci->val) != 0)
3525  {
3526  if (strcmp(replci->keyword, "user") == 0 ||
3527  strcmp(replci->keyword, "host") == 0 ||
3528  strcmp(replci->keyword, "hostaddr") == 0 ||
3529  strcmp(replci->keyword, "port") == 0)
3530  keep_password = false;
3531  }
3532  /* Also note whether connstring contains a password. */
3533  if (strcmp(replci->keyword, "password") == 0)
3534  have_password = true;
3535  }
3536  else if (!reuse_previous)
3537  {
3538  /*
3539  * When we have a connstring and are not re-using
3540  * parameters, swap *all* entries, even those not set
3541  * by the connstring. This avoids absorbing
3542  * environment-dependent defaults from the result of
3543  * PQconndefaults(). We don't want to do that because
3544  * they'd override service-file entries if the
3545  * connstring specifies a service parameter, whereas
3546  * the priority should be the other way around. libpq
3547  * can certainly recompute any defaults we don't pass
3548  * here. (In this situation, it's a bit wasteful to
3549  * have called PQconndefaults() at all, but not doing
3550  * so would require yet another major code path here.)
3551  */
3552  replci->val = ci->val;
3553  ci->val = NULL;
3554  }
3555  }
3556  Assert(ci->keyword == NULL && replci->keyword == NULL);
3557 
3558  /* While here, determine how many option slots there are */
3559  nconnopts = ci - cinfo;
3560 
3561  PQconninfoFree(replcinfo);
3562 
3563  /*
3564  * If the connstring contains a password, tell the loop below
3565  * that we may use it, regardless of other settings (i.e.,
3566  * cinfo's password is no longer an "old" password).
3567  */
3568  if (have_password)
3569  keep_password = true;
3570 
3571  /* Don't let code below try to inject dbname into params. */
3572  dbname = NULL;
3573  }
3574  else
3575  {
3576  /* PQconninfoParse failed */
3577  if (errmsg)
3578  {
3579  pg_log_error("%s", errmsg);
3580  PQfreemem(errmsg);
3581  }
3582  else
3583  pg_log_error("out of memory");
3584  success = false;
3585  }
3586  }
3587  else
3588  {
3589  /*
3590  * If dbname isn't a connection string, then we'll inject it and
3591  * the other parameters into the keyword array below. (We can't
3592  * easily insert them into the cinfo array because of memory
3593  * management issues: PQconninfoFree would misbehave on Windows.)
3594  * However, to avoid dependencies on the order in which parameters
3595  * appear in the array, make a preliminary scan to set
3596  * keep_password and same_host correctly.
3597  *
3598  * While any change in user, host, or port causes us to ignore the
3599  * old connection's password, we don't force that for dbname,
3600  * since passwords aren't database-specific.
3601  */
3602  PQconninfoOption *ci;
3603 
3604  for (ci = cinfo; ci->keyword; ci++)
3605  {
3606  if (user && strcmp(ci->keyword, "user") == 0)
3607  {
3608  if (!(ci->val && strcmp(user, ci->val) == 0))
3609  keep_password = false;
3610  }
3611  else if (host && strcmp(ci->keyword, "host") == 0)
3612  {
3613  if (ci->val && strcmp(host, ci->val) == 0)
3614  same_host = true;
3615  else
3616  keep_password = false;
3617  }
3618  else if (port && strcmp(ci->keyword, "port") == 0)
3619  {
3620  if (!(ci->val && strcmp(port, ci->val) == 0))
3621  keep_password = false;
3622  }
3623  }
3624 
3625  /* While here, determine how many option slots there are */
3626  nconnopts = ci - cinfo;
3627  }
3628  }
3629  else
3630  {
3631  /* We failed to create the cinfo structure */
3632  pg_log_error("out of memory");
3633  success = false;
3634  }
3635 
3636  /*
3637  * If the user asked to be prompted for a password, ask for one now. If
3638  * not, use the password from the old connection, provided the username
3639  * etc have not changed. Otherwise, try to connect without a password
3640  * first, and then ask for a password if needed.
3641  *
3642  * XXX: this behavior leads to spurious connection attempts recorded in
3643  * the postmaster's log. But libpq offers no API that would let us obtain
3644  * a password and then continue with the first connection attempt.
3645  */
3646  if (pset.getPassword == TRI_YES && success)
3647  {
3648  bool canceled = false;
3649 
3650  /*
3651  * If a connstring or URI is provided, we don't know which username
3652  * will be used, since we haven't dug that out of the connstring.
3653  * Don't risk issuing a misleading prompt. As in startup.c, it does
3654  * not seem worth working harder, since this getPassword setting is
3655  * normally only used in noninteractive cases.
3656  */
3657  password = prompt_for_password(has_connection_string ? NULL : user,
3658  &canceled);
3659  success = !canceled;
3660  }
3661 
3662  /*
3663  * Consider whether to force client_encoding to "auto" (overriding
3664  * anything in the connection string). We do so if we have a terminal
3665  * connection and there is no PGCLIENTENCODING environment setting.
3666  */
3667  if (pset.notty || getenv("PGCLIENTENCODING"))
3668  client_encoding = NULL;
3669  else
3670  client_encoding = "auto";
3671 
3672  /* Loop till we have a connection or fail, which we might've already */
3673  while (success)
3674  {
3675  const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
3676  const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
3677  int paramnum = 0;
3678  PQconninfoOption *ci;
3679 
3680  /*
3681  * Copy non-default settings into the PQconnectdbParams parameter
3682  * arrays; but inject any values specified old-style, as well as any
3683  * interactively-obtained password, and a couple of fields we want to
3684  * set forcibly.
3685  *
3686  * If you change this code, see also the initial-connection code in
3687  * main().
3688  */
3689  for (ci = cinfo; ci->keyword; ci++)
3690  {
3691  keywords[paramnum] = ci->keyword;
3692 
3693  if (dbname && strcmp(ci->keyword, "dbname") == 0)
3694  values[paramnum++] = dbname;
3695  else if (user && strcmp(ci->keyword, "user") == 0)
3696  values[paramnum++] = user;
3697  else if (host && strcmp(ci->keyword, "host") == 0)
3698  values[paramnum++] = host;
3699  else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
3700  {
3701  /* If we're changing the host value, drop any old hostaddr */
3702  values[paramnum++] = NULL;
3703  }
3704  else if (port && strcmp(ci->keyword, "port") == 0)
3705  values[paramnum++] = port;
3706  /* If !keep_password, we unconditionally drop old password */
3707  else if ((password || !keep_password) &&
3708  strcmp(ci->keyword, "password") == 0)
3709  values[paramnum++] = password;
3710  else if (strcmp(ci->keyword, "fallback_application_name") == 0)
3711  values[paramnum++] = pset.progname;
3712  else if (client_encoding &&
3713  strcmp(ci->keyword, "client_encoding") == 0)
3714  values[paramnum++] = client_encoding;
3715  else if (ci->val)
3716  values[paramnum++] = ci->val;
3717  /* else, don't bother making libpq parse this keyword */
3718  }
3719  /* add array terminator */
3720  keywords[paramnum] = NULL;
3721  values[paramnum] = NULL;
3722 
3723  /* Note we do not want libpq to re-expand the dbname parameter */
3724  n_conn = PQconnectStartParams(keywords, values, false);
3725 
3726  pg_free(keywords);
3727  pg_free(values);
3728 
3729  wait_until_connected(n_conn);
3730  if (PQstatus(n_conn) == CONNECTION_OK)
3731  break;
3732 
3733  /*
3734  * Connection attempt failed; either retry the connection attempt with
3735  * a new password, or give up.
3736  */
3738  {
3739  bool canceled = false;
3740 
3741  /*
3742  * Prompt for password using the username we actually connected
3743  * with --- it might've come out of "dbname" rather than "user".
3744  */
3745  password = prompt_for_password(PQuser(n_conn), &canceled);
3746  PQfinish(n_conn);
3747  n_conn = NULL;
3748  success = !canceled;
3749  continue;
3750  }
3751 
3752  /*
3753  * We'll report the error below ... unless n_conn is NULL, indicating
3754  * that libpq didn't have enough memory to make a PGconn.
3755  */
3756  if (n_conn == NULL)
3757  pg_log_error("out of memory");
3758 
3759  success = false;
3760  } /* end retry loop */
3761 
3762  /* Release locally allocated data, whether we succeeded or not */
3763  pg_free(password);
3764  PQconninfoFree(cinfo);
3765 
3766  if (!success)
3767  {
3768  /*
3769  * Failed to connect to the database. In interactive mode, keep the
3770  * previous connection to the DB; in scripting mode, close our
3771  * previous connection as well.
3772  */
3774  {
3775  if (n_conn)
3776  {
3777  pg_log_info("%s", PQerrorMessage(n_conn));
3778  PQfinish(n_conn);
3779  }
3780 
3781  /* pset.db is left unmodified */
3782  if (o_conn)
3783  pg_log_info("Previous connection kept");
3784  }
3785  else
3786  {
3787  if (n_conn)
3788  {
3789  pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
3790  PQfinish(n_conn);
3791  }
3792 
3793  if (o_conn)
3794  {
3795  /*
3796  * Transition to having no connection.
3797  *
3798  * Unlike CheckConnection(), we close the old connection
3799  * immediately to prevent its parameters from being re-used.
3800  * This is so that a script cannot accidentally reuse
3801  * parameters it did not expect to. Otherwise, the state
3802  * cleanup should be the same as in CheckConnection().
3803  */
3804  PQfinish(o_conn);
3805  pset.db = NULL;
3806  ResetCancelConn();
3807  UnsyncVariables();
3808  }
3809 
3810  /* On the same reasoning, release any dead_conn to prevent reuse */
3811  if (pset.dead_conn)
3812  {
3814  pset.dead_conn = NULL;
3815  }
3816  }
3817 
3818  return false;
3819  }
3820 
3821  /*
3822  * Replace the old connection with the new one, and update
3823  * connection-dependent variables. Keep the resynchronization logic in
3824  * sync with CheckConnection().
3825  */
3826  PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
3827  pset.db = n_conn;
3828  SyncVariables();
3829  connection_warnings(false); /* Must be after SyncVariables */
3830 
3831  /* Tell the user about the new connection */
3832  if (!pset.quiet)
3833  {
3834  if (!o_conn ||
3835  param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
3836  param_is_newly_set(PQport(o_conn), PQport(pset.db)))
3837  {
3838  char *connhost = PQhost(pset.db);
3839  char *hostaddr = PQhostaddr(pset.db);
3840 
3841  if (is_unixsock_path(connhost))
3842  {
3843  /* hostaddr overrides connhost */
3844  if (hostaddr && *hostaddr)
3845  printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
3846  PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
3847  else
3848  printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
3849  PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
3850  }
3851  else
3852  {
3853  if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
3854  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
3855  PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
3856  else
3857  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
3858  PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
3859  }
3860  }
3861  else
3862  printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
3863  PQdb(pset.db), PQuser(pset.db));
3864  }
3865 
3866  /* Drop no-longer-needed connection(s) */
3867  if (o_conn)
3868  PQfinish(o_conn);
3869  if (pset.dead_conn)
3870  {
3872  pset.dead_conn = NULL;
3873  }
3874 
3875  return true;
3876 }
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:267
bool recognized_connection_string(const char *connstr)
Definition: common.c:2317
static Datum values[MAXATTR]
Definition: bootstrap.c:151
void ResetCancelConn(void)
Definition: cancel.c:107
static char * prompt_for_password(const char *username, bool *canceled)
Definition: command.c:3369
static bool param_is_newly_set(const char *old_val, const char *new_val)
Definition: command.c:3397
void UnsyncVariables(void)
Definition: command.c:4115
static void wait_until_connected(PGconn *conn)
Definition: command.c:3884
void SyncVariables(void)
Definition: command.c:4074
void connection_warnings(bool in_startup)
Definition: command.c:3946
int errmsg(const char *fmt,...)
Definition: elog.c:1070
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5739
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:792
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:7069
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:7036
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1882
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:7092
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7023
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:6979
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7251
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7200
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7137
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4879
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:7044
char * PQport(const PGconn *conn)
Definition: fe-connect.c:7105
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7379
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
void pg_free(void *ptr)
Definition: fe_memutils.c:105
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static bool success
Definition: initdb.c:186
return false
Definition: isn.c:130
@ CONNECTION_OK
Definition: libpq-fe.h:81
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_info(...)
Definition: logging.h:124
static char * user
Definition: pg_regress.c:119
static int port
Definition: pg_regress.c:115
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:67
static char * password
Definition: streamutil.c:52
char * dbname
Definition: streamutil.c:50
PGconn * dead_conn
Definition: settings.h:140
enum trivalue getPassword
Definition: settings.h:119
bool cur_cmd_interactive
Definition: settings.h:122
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37

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

Referenced by exec_command_connect().

◆ do_edit()

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

Definition at line 4217 of file command.c.

4219 {
4220  char fnametmp[MAXPGPATH];
4221  FILE *stream = NULL;
4222  const char *fname;
4223  bool error = false;
4224  int fd;
4225  struct stat before,
4226  after;
4227 
4228  if (filename_arg)
4229  fname = filename_arg;
4230  else
4231  {
4232  /* make a temp file to edit */
4233 #ifndef WIN32
4234  const char *tmpdir = getenv("TMPDIR");
4235 
4236  if (!tmpdir)
4237  tmpdir = "/tmp";
4238 #else
4239  char tmpdir[MAXPGPATH];
4240  int ret;
4241 
4242  ret = GetTempPath(MAXPGPATH, tmpdir);
4243  if (ret == 0 || ret > MAXPGPATH)
4244  {
4245  pg_log_error("could not locate temporary directory: %s",
4246  !ret ? strerror(errno) : "");
4247  return false;
4248  }
4249 #endif
4250 
4251  /*
4252  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4253  * current directory to the supplied path unless we use only
4254  * backslashes, so we do that.
4255  */
4256 #ifndef WIN32
4257  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4258  "/", (int) getpid());
4259 #else
4260  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4261  "" /* trailing separator already present */ , (int) getpid());
4262 #endif
4263 
4264  fname = (const char *) fnametmp;
4265 
4266  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4267  if (fd != -1)
4268  stream = fdopen(fd, "w");
4269 
4270  if (fd == -1 || !stream)
4271  {
4272  pg_log_error("could not open temporary file \"%s\": %m", fname);
4273  error = true;
4274  }
4275  else
4276  {
4277  unsigned int ql = query_buf->len;
4278 
4279  /* force newline-termination of what we send to editor */
4280  if (ql > 0 && query_buf->data[ql - 1] != '\n')
4281  {
4282  appendPQExpBufferChar(query_buf, '\n');
4283  ql++;
4284  }
4285 
4286  if (fwrite(query_buf->data, 1, ql, stream) != ql)
4287  {
4288  pg_log_error("%s: %m", fname);
4289 
4290  if (fclose(stream) != 0)
4291  pg_log_error("%s: %m", fname);
4292 
4293  if (remove(fname) != 0)
4294  pg_log_error("%s: %m", fname);
4295 
4296  error = true;
4297  }
4298  else if (fclose(stream) != 0)
4299  {
4300  pg_log_error("%s: %m", fname);
4301  if (remove(fname) != 0)
4302  pg_log_error("%s: %m", fname);
4303  error = true;
4304  }
4305  else
4306  {
4307  struct utimbuf ut;
4308 
4309  /*
4310  * Try to set the file modification time of the temporary file
4311  * a few seconds in the past. Otherwise, the low granularity
4312  * (one second, or even worse on some filesystems) that we can
4313  * portably measure with stat(2) could lead us to not
4314  * recognize a modification, if the user typed very quickly.
4315  *
4316  * This is a rather unlikely race condition, so don't error
4317  * out if the utime(2) call fails --- that would make the cure
4318  * worse than the disease.
4319  */
4320  ut.modtime = ut.actime = time(NULL) - 2;
4321  (void) utime(fname, &ut);
4322  }
4323  }
4324  }
4325 
4326  if (!error && stat(fname, &before) != 0)
4327  {
4328  pg_log_error("%s: %m", fname);
4329  error = true;
4330  }
4331 
4332  /* call editor */
4333  if (!error)
4334  error = !editFile(fname, lineno);
4335 
4336  if (!error && stat(fname, &after) != 0)
4337  {
4338  pg_log_error("%s: %m", fname);
4339  error = true;
4340  }
4341 
4342  /* file was edited if the size or modification time has changed */
4343  if (!error &&
4344  (before.st_size != after.st_size ||
4345  before.st_mtime != after.st_mtime))
4346  {
4347  stream = fopen(fname, PG_BINARY_R);
4348  if (!stream)
4349  {
4350  pg_log_error("%s: %m", fname);
4351  error = true;
4352  }
4353  else
4354  {
4355  /* read file back into query_buf */
4356  char line[1024];
4357 
4358  resetPQExpBuffer(query_buf);
4359  while (fgets(line, sizeof(line), stream) != NULL)
4360  appendPQExpBufferStr(query_buf, line);
4361 
4362  if (ferror(stream))
4363  {
4364  pg_log_error("%s: %m", fname);
4365  error = true;
4366  resetPQExpBuffer(query_buf);
4367  }
4368  else if (edited)
4369  {
4370  *edited = true;
4371  }
4372 
4373  fclose(stream);
4374  }
4375  }
4376  else
4377  {
4378  /*
4379  * If the file was not modified, and the caller requested it, discard
4380  * the query buffer.
4381  */
4382  if (discard_on_quit)
4383  resetPQExpBuffer(query_buf);
4384  }
4385 
4386  /* remove temp file */
4387  if (!filename_arg)
4388  {
4389  if (remove(fname) == -1)
4390  {
4391  pg_log_error("%s: %m", fname);
4392  error = true;
4393  }
4394  }
4395 
4396  return !error;
4397 }
#define PG_BINARY_R
Definition: c.h:1280
static bool editFile(const char *fname, int lineno)
Definition: command.c:4135
#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 4565 of file command.c.

4566 {
4567  size_t vallen = 0;
4568 
4569  Assert(param != NULL);
4570 
4571  if (value)
4572  vallen = strlen(value);
4573 
4574  /* set format */
4575  if (strcmp(param, "format") == 0)
4576  {
4577  static const struct fmt
4578  {
4579  const char *name;
4580  enum printFormat number;
4581  } formats[] =
4582  {
4583  /* remember to update error message below when adding more */
4584  {"aligned", PRINT_ALIGNED},
4585  {"asciidoc", PRINT_ASCIIDOC},
4586  {"csv", PRINT_CSV},
4587  {"html", PRINT_HTML},
4588  {"latex", PRINT_LATEX},
4589  {"troff-ms", PRINT_TROFF_MS},
4590  {"unaligned", PRINT_UNALIGNED},
4591  {"wrapped", PRINT_WRAPPED}
4592  };
4593 
4594  if (!value)
4595  ;
4596  else
4597  {
4598  int match_pos = -1;
4599 
4600  for (int i = 0; i < lengthof(formats); i++)
4601  {
4602  if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
4603  {
4604  if (match_pos < 0)
4605  match_pos = i;
4606  else
4607  {
4608  pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
4609  value,
4610  formats[match_pos].name, formats[i].name);
4611  return false;
4612  }
4613  }
4614  }
4615  if (match_pos >= 0)
4616  popt->topt.format = formats[match_pos].number;
4617  else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
4618  {
4619  /*
4620  * We must treat latex-longtable specially because latex is a
4621  * prefix of it; if both were in the table above, we'd think
4622  * "latex" is ambiguous.
4623  */
4625  }
4626  else
4627  {
4628  pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
4629  return false;
4630  }
4631  }
4632  }
4633 
4634  /* set table line style */
4635  else if (strcmp(param, "linestyle") == 0)
4636  {
4637  if (!value)
4638  ;
4639  else if (pg_strncasecmp("ascii", value, vallen) == 0)
4640  popt->topt.line_style = &pg_asciiformat;
4641  else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
4643  else if (pg_strncasecmp("unicode", value, vallen) == 0)
4644  popt->topt.line_style = &pg_utf8format;
4645  else
4646  {
4647  pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
4648  return false;
4649  }
4650  }
4651 
4652  /* set unicode border line style */
4653  else if (strcmp(param, "unicode_border_linestyle") == 0)
4654  {
4655  if (!value)
4656  ;
4657  else if (set_unicode_line_style(value, vallen,
4659  refresh_utf8format(&(popt->topt));
4660  else
4661  {
4662  pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4663  return false;
4664  }
4665  }
4666 
4667  /* set unicode column line style */
4668  else if (strcmp(param, "unicode_column_linestyle") == 0)
4669  {
4670  if (!value)
4671  ;
4672  else if (set_unicode_line_style(value, vallen,
4674  refresh_utf8format(&(popt->topt));
4675  else
4676  {
4677  pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4678  return false;
4679  }
4680  }
4681 
4682  /* set unicode header line style */
4683  else if (strcmp(param, "unicode_header_linestyle") == 0)
4684  {
4685  if (!value)
4686  ;
4687  else if (set_unicode_line_style(value, vallen,
4689  refresh_utf8format(&(popt->topt));
4690  else
4691  {
4692  pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4693  return false;
4694  }
4695  }
4696 
4697  /* set border style/width */
4698  else if (strcmp(param, "border") == 0)
4699  {
4700  if (value)
4701  popt->topt.border = atoi(value);
4702  }
4703 
4704  /* set expanded/vertical mode */
4705  else if (strcmp(param, "x") == 0 ||
4706  strcmp(param, "expanded") == 0 ||
4707  strcmp(param, "vertical") == 0)
4708  {
4709  if (value && pg_strcasecmp(value, "auto") == 0)
4710  popt->topt.expanded = 2;
4711  else if (value)
4712  {
4713  bool on_off;
4714 
4715  if (ParseVariableBool(value, NULL, &on_off))
4716  popt->topt.expanded = on_off ? 1 : 0;
4717  else
4718  {
4719  PsqlVarEnumError(param, value, "on, off, auto");
4720  return false;
4721  }
4722  }
4723  else
4724  popt->topt.expanded = !popt->topt.expanded;
4725  }
4726 
4727  /* header line width in expanded mode */
4728  else if (strcmp(param, "xheader_width") == 0)
4729  {
4730  if (!value)
4731  ;
4732  else if (pg_strcasecmp(value, "full") == 0)
4734  else if (pg_strcasecmp(value, "column") == 0)
4736  else if (pg_strcasecmp(value, "page") == 0)
4738  else
4739  {
4740  int intval = atoi(value);
4741 
4742  if (intval == 0)
4743  {
4744  pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
4745  return false;
4746  }
4747 
4749  popt->topt.expanded_header_exact_width = intval;
4750  }
4751  }
4752 
4753  /* field separator for CSV format */
4754  else if (strcmp(param, "csv_fieldsep") == 0)
4755  {
4756  if (value)
4757  {
4758  /* CSV separator has to be a one-byte character */
4759  if (strlen(value) != 1)
4760  {
4761  pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
4762  return false;
4763  }
4764  if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
4765  {
4766  pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
4767  return false;
4768  }
4769  popt->topt.csvFieldSep[0] = value[0];
4770  }
4771  }
4772 
4773  /* locale-aware numeric output */
4774  else if (strcmp(param, "numericlocale") == 0)
4775  {
4776  if (value)
4777  return ParseVariableBool(value, param, &popt->topt.numericLocale);
4778  else
4779  popt->topt.numericLocale = !popt->topt.numericLocale;
4780  }
4781 
4782  /* null display */
4783  else if (strcmp(param, "null") == 0)
4784  {
4785  if (value)
4786  {
4787  free(popt->nullPrint);
4788  popt->nullPrint = pg_strdup(value);
4789  }
4790  }
4791 
4792  /* field separator for unaligned text */
4793  else if (strcmp(param, "fieldsep") == 0)
4794  {
4795  if (value)
4796  {
4797  free(popt->topt.fieldSep.separator);
4799  popt->topt.fieldSep.separator_zero = false;
4800  }
4801  }
4802 
4803  else if (strcmp(param, "fieldsep_zero") == 0)
4804  {
4805  free(popt->topt.fieldSep.separator);
4806  popt->topt.fieldSep.separator = NULL;
4807  popt->topt.fieldSep.separator_zero = true;
4808  }
4809 
4810  /* record separator for unaligned text */
4811  else if (strcmp(param, "recordsep") == 0)
4812  {
4813  if (value)
4814  {
4815  free(popt->topt.recordSep.separator);
4817  popt->topt.recordSep.separator_zero = false;
4818  }
4819  }
4820 
4821  else if (strcmp(param, "recordsep_zero") == 0)
4822  {
4823  free(popt->topt.recordSep.separator);
4824  popt->topt.recordSep.separator = NULL;
4825  popt->topt.recordSep.separator_zero = true;
4826  }
4827 
4828  /* toggle between full and tuples-only format */
4829  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4830  {
4831  if (value)
4832  return ParseVariableBool(value, param, &popt->topt.tuples_only);
4833  else
4834  popt->topt.tuples_only = !popt->topt.tuples_only;
4835  }
4836 
4837  /* set title override */
4838  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4839  {
4840  free(popt->title);
4841  if (!value)
4842  popt->title = NULL;
4843  else
4844  popt->title = pg_strdup(value);
4845  }
4846 
4847  /* set HTML table tag options */
4848  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4849  {
4850  free(popt->topt.tableAttr);
4851  if (!value)
4852  popt->topt.tableAttr = NULL;
4853  else
4854  popt->topt.tableAttr = pg_strdup(value);
4855  }
4856 
4857  /* toggle use of pager */
4858  else if (strcmp(param, "pager") == 0)
4859  {
4860  if (value && pg_strcasecmp(value, "always") == 0)
4861  popt->topt.pager = 2;
4862  else if (value)
4863  {
4864  bool on_off;
4865 
4866  if (!ParseVariableBool(value, NULL, &on_off))
4867  {
4868  PsqlVarEnumError(param, value, "on, off, always");
4869  return false;
4870  }
4871  popt->topt.pager = on_off ? 1 : 0;
4872  }
4873  else if (popt->topt.pager == 1)
4874  popt->topt.pager = 0;
4875  else
4876  popt->topt.pager = 1;
4877  }
4878 
4879  /* set minimum lines for pager use */
4880  else if (strcmp(param, "pager_min_lines") == 0)
4881  {
4882  if (value &&
4883  !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
4884  return false;
4885  }
4886 
4887  /* disable "(x rows)" footer */
4888  else if (strcmp(param, "footer") == 0)
4889  {
4890  if (value)
4891  return ParseVariableBool(value, param, &popt->topt.default_footer);
4892  else
4893  popt->topt.default_footer = !popt->topt.default_footer;
4894  }
4895 
4896  /* set border style/width */
4897  else if (strcmp(param, "columns") == 0)
4898  {
4899  if (value)
4900  popt->topt.columns = atoi(value);
4901  }
4902  else
4903  {
4904  pg_log_error("\\pset: unknown option: %s", param);
4905  return false;
4906  }
4907 
4908  if (!quiet)
4909  printPsetInfo(param, &pset.popt);
4910 
4911  return true;
4912 }
#define lengthof(array)
Definition: c.h:793
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4522
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:4918
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3691
const printTextFormat pg_asciiformat
Definition: print.c:56
const printTextFormat pg_asciiformat_old
Definition: print.c:77
printTextFormat pg_utf8format
Definition: print.c:99
@ PRINT_XHEADER_EXACT_WIDTH
Definition: print.h:78
@ PRINT_XHEADER_PAGE
Definition: print.h:76
@ PRINT_XHEADER_COLUMN
Definition: print.h:74
@ PRINT_XHEADER_FULL
Definition: print.h:72
printFormat
Definition: print.h:29
#define free(a)
Definition: header.h:65
static struct @160 value
int i
Definition: isn.c:72
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:100
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 5314 of file command.c.

5315 {
5316  int result;
5317 
5318  fflush(NULL);
5319  if (!command)
5320  {
5321  char *sys;
5322  const char *shellName;
5323 
5324  shellName = getenv("SHELL");
5325 #ifdef WIN32
5326  if (shellName == NULL)
5327  shellName = getenv("COMSPEC");
5328 #endif
5329  if (shellName == NULL)
5330  shellName = DEFAULT_SHELL;
5331 
5332  /* See EDITOR handling comment for an explanation */
5333 #ifndef WIN32
5334  sys = psprintf("exec %s", shellName);
5335 #else
5336  sys = psprintf("\"%s\"", shellName);
5337 #endif
5338  result = system(sys);
5339  free(sys);
5340  }
5341  else
5342  result = system(command);
5343 
5344  SetShellResultVariables(result);
5345 
5346  if (result == 127 || result == -1)
5347  {
5348  pg_log_error("\\!: failed");
5349  return false;
5350  }
5351  return true;
5352 }
void SetShellResultVariables(int wait_result)
Definition: common.c:501
#define DEFAULT_SHELL
Definition: command.c:5304
static void const char fflush(stdout)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43

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

5366 {
5367  long sleep_ms = (long) (sleep * 1000);
5368  printQueryOpt myopt = pset.popt;
5369  const char *strftime_fmt;
5370  const char *user_title;
5371  char *title;
5372  const char *pagerprog = NULL;
5373  FILE *pagerpipe = NULL;
5374  int title_len;
5375  int res = 0;
5376  bool done = false;
5377 #ifndef WIN32
5378  sigset_t sigalrm_sigchld_sigint;
5379  sigset_t sigalrm_sigchld;
5380  sigset_t sigint;
5381  struct itimerval interval;
5382 #endif
5383 
5384  if (!query_buf || query_buf->len <= 0)
5385  {
5386  pg_log_error("\\watch cannot be used with an empty query");
5387  return false;
5388  }
5389 
5390 #ifndef WIN32
5391  sigemptyset(&sigalrm_sigchld_sigint);
5392  sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5393  sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5394  sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5395 
5396  sigemptyset(&sigalrm_sigchld);
5397  sigaddset(&sigalrm_sigchld, SIGCHLD);
5398  sigaddset(&sigalrm_sigchld, SIGALRM);
5399 
5400  sigemptyset(&sigint);
5401  sigaddset(&sigint, SIGINT);
5402 
5403  /*
5404  * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5405  * configured), to avoid races. sigwait() will receive them.
5406  */
5407  sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5408 
5409  /*
5410  * Set a timer to interrupt sigwait() so we can run the query at the
5411  * requested intervals.
5412  */
5413  interval.it_value.tv_sec = sleep_ms / 1000;
5414  interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5415  interval.it_interval = interval.it_value;
5416  if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5417  {
5418  pg_log_error("could not set timer: %m");
5419  done = true;
5420  }
5421 #endif
5422 
5423  /*
5424  * For \watch, we ignore the size of the result and always use the pager
5425  * as long as we're talking to a terminal and "\pset pager" is enabled.
5426  * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5427  * ignore the regular PSQL_PAGER or PAGER environment variables, because
5428  * traditional pagers probably won't be very useful for showing a stream
5429  * of results.
5430  */
5431 #ifndef WIN32
5432  pagerprog = getenv("PSQL_WATCH_PAGER");
5433  /* if variable is empty or all-white-space, don't use pager */
5434  if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5435  pagerprog = NULL;
5436 #endif
5437  if (pagerprog && myopt.topt.pager &&
5438  isatty(fileno(stdin)) && isatty(fileno(stdout)))
5439  {
5440  fflush(NULL);
5442  pagerpipe = popen(pagerprog, "w");
5443 
5444  if (!pagerpipe)
5445  /* silently proceed without pager */
5447  }
5448 
5449  /*
5450  * Choose format for timestamps. We might eventually make this a \pset
5451  * option. In the meantime, using a variable for the format suppresses
5452  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5453  */
5454  strftime_fmt = "%c";
5455 
5456  /*
5457  * Set up rendering options, in particular, disable the pager unless
5458  * PSQL_WATCH_PAGER was successfully launched.
5459  */
5460  if (!pagerpipe)
5461  myopt.topt.pager = 0;
5462 
5463  /*
5464  * If there's a title in the user configuration, make sure we have room
5465  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5466  * bytes for the rest.
5467  */
5468  user_title = myopt.title;
5469  title_len = (user_title ? strlen(user_title) : 0) + 256;
5470  title = pg_malloc(title_len);
5471 
5472  /* Loop to run query and then sleep awhile */
5473  while (!done)
5474  {
5475  time_t timer;
5476  char timebuf[128];
5477 
5478  /*
5479  * Prepare title for output. Note that we intentionally include a
5480  * newline at the end of the title; this is somewhat historical but it
5481  * makes for reasonably nicely formatted output in simple cases.
5482  */
5483  timer = time(NULL);
5484  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5485 
5486  if (user_title)
5487  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5488  user_title, timebuf, sleep_ms / 1000.0);
5489  else
5490  snprintf(title, title_len, _("%s (every %gs)\n"),
5491  timebuf, sleep_ms / 1000.0);
5492  myopt.title = title;
5493 
5494  /* Run the query and print out the result */
5495  res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
5496 
5497  /*
5498  * PSQLexecWatch handles the case where we can no longer repeat the
5499  * query, and returns 0 or -1.
5500  */
5501  if (res <= 0)
5502  break;
5503 
5504  /* If we have iteration count, check that it's not exceeded yet */
5505  if (iter && (--iter <= 0))
5506  break;
5507 
5508  /* Quit if error on pager pipe (probably pager has quit) */
5509  if (pagerpipe && ferror(pagerpipe))
5510  break;
5511 
5512  /* Tight loop, no wait needed */
5513  if (sleep_ms == 0)
5514  continue;
5515 
5516 #ifdef WIN32
5517 
5518  /*
5519  * Wait a while before running the query again. Break the sleep into
5520  * short intervals (at most 1s); that's probably unnecessary since
5521  * pg_usleep is interruptible on Windows, but it's cheap insurance.
5522  */
5523  for (long i = sleep_ms; i > 0;)
5524  {
5525  long s = Min(i, 1000L);
5526 
5527  pg_usleep(s * 1000L);
5528  if (cancel_pressed)
5529  {
5530  done = true;
5531  break;
5532  }
5533  i -= s;
5534  }
5535 #else
5536  /* sigwait() will handle SIGINT. */
5537  sigprocmask(SIG_BLOCK, &sigint, NULL);
5538  if (cancel_pressed)
5539  done = true;
5540 
5541  /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5542  while (!done)
5543  {
5544  int signal_received;
5545 
5546  errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5547  if (errno != 0)
5548  {
5549  /* Some other signal arrived? */
5550  if (errno == EINTR)
5551  continue;
5552  else
5553  {
5554  pg_log_error("could not wait for signals: %m");
5555  done = true;
5556  break;
5557  }
5558  }
5559  /* On ^C or pager exit, it's time to stop running the query. */
5560  if (signal_received == SIGINT || signal_received == SIGCHLD)
5561  done = true;
5562  /* Otherwise, we must have SIGALRM. Time to run the query again. */
5563  break;
5564  }
5565 
5566  /* Unblock SIGINT so that slow queries can be interrupted. */
5567  sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5568 #endif
5569  }
5570 
5571  if (pagerpipe)
5572  {
5573  pclose(pagerpipe);
5575  }
5576  else
5577  {
5578  /*
5579  * If the terminal driver echoed "^C", libedit/libreadline might be
5580  * confused about the cursor position. Therefore, inject a newline
5581  * before the next prompt is displayed. We only do this when not
5582  * using a pager, because pagers are expected to restore the screen to
5583  * a sane state on exit.
5584  */
5585  fprintf(stdout, "\n");
5586  fflush(stdout);
5587  }
5588 
5589 #ifndef WIN32
5590  /* Disable the interval timer. */
5591  memset(&interval, 0, sizeof(interval));
5592  setitimer(ITIMER_REAL, &interval, NULL);
5593  /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5594  sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5595 #endif
5596 
5597  pg_free(title);
5598  return (res >= 0);
5599 }
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
Definition: common.c:675
#define Min(x, y)
Definition: c.h:1009
void restore_sigpipe_trap(void)
Definition: print.c:3062
void disable_sigpipe_trap(void)
Definition: print.c:3039
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
#define fprintf
Definition: port.h:242
void pg_usleep(long microsec)
Definition: signal.c:53
static long sleep_ms
Definition: slotsync.c:117
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
Definition: timer.c:86
#define SIGCHLD
Definition: win32_port.h:178
#define EINTR
Definition: win32_port.h:374
#define SIGALRM
Definition: win32_port.h:174
#define ITIMER_REAL
Definition: win32_port.h:190

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

Referenced by exec_command_watch().

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 5606 of file command.c.

5607 {
5609  {
5610  printf(_("/******** QUERY *********/\n"
5611  "%s\n"
5612  "/************************/\n\n"), query);
5613  fflush(stdout);
5614  if (pset.logfile)
5615  {
5617  _("/******** QUERY *********/\n"
5618  "%s\n"
5619  "/************************/\n\n"), query);
5620  fflush(pset.logfile);
5621  }
5622 
5624  return false;
5625  }
5626  return true;
5627 }
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
FILE * logfile
Definition: settings.h:131
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:158

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

4136 {
4137  const char *editorName;
4138  const char *editor_lineno_arg = NULL;
4139  char *sys;
4140  int result;
4141 
4142  Assert(fname != NULL);
4143 
4144  /* Find an editor to use */
4145  editorName = getenv("PSQL_EDITOR");
4146  if (!editorName)
4147  editorName = getenv("EDITOR");
4148  if (!editorName)
4149  editorName = getenv("VISUAL");
4150  if (!editorName)
4151  editorName = DEFAULT_EDITOR;
4152 
4153  /* Get line number argument, if we need it. */
4154  if (lineno > 0)
4155  {
4156  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4157 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4158  if (!editor_lineno_arg)
4159  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4160 #endif
4161  if (!editor_lineno_arg)
4162  {
4163  pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4164  return false;
4165  }
4166  }
4167 
4168  /*
4169  * On Unix the EDITOR value should *not* be quoted, since it might include
4170  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4171  * if necessary. But this policy is not very workable on Windows, due to
4172  * severe brain damage in their command shell plus the fact that standard
4173  * program paths include spaces.
4174  */
4175 #ifndef WIN32
4176  if (lineno > 0)
4177  sys = psprintf("exec %s %s%d '%s'",
4178  editorName, editor_lineno_arg, lineno, fname);
4179  else
4180  sys = psprintf("exec %s '%s'",
4181  editorName, fname);
4182 #else
4183  if (lineno > 0)
4184  sys = psprintf("\"%s\" %s%d \"%s\"",
4185  editorName, editor_lineno_arg, lineno, fname);
4186  else
4187  sys = psprintf("\"%s\" \"%s\"",
4188  editorName, fname);
4189 #endif
4190  fflush(NULL);
4191  result = system(sys);
4192  if (result == -1)
4193  pg_log_error("could not start editor \"%s\"", editorName);
4194  else if (result == 127)
4195  pg_log_error("could not start /bin/sh");
4196  free(sys);
4197 
4198  return result == 0;
4199 }
#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 291 of file command.c.

296 {
297  backslashResult status;
298  bool active_branch = conditional_active(cstack);
299 
300  /*
301  * In interactive mode, warn when we're ignoring a command within a false
302  * \if-branch. But we continue on, so as to parse and discard the right
303  * amount of parameter text. Each individual backslash command subroutine
304  * is responsible for doing nothing after discarding appropriate
305  * arguments, if !active_branch.
306  */
307  if (pset.cur_cmd_interactive && !active_branch &&
308  !is_branching_command(cmd))
309  {
310  pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
311  cmd);
312  }
313 
314  if (strcmp(cmd, "a") == 0)
315  status = exec_command_a(scan_state, active_branch);
316  else if (strcmp(cmd, "bind") == 0)
317  status = exec_command_bind(scan_state, active_branch);
318  else if (strcmp(cmd, "bind_named") == 0)
319  status = exec_command_bind_named(scan_state, active_branch, cmd);
320  else if (strcmp(cmd, "C") == 0)
321  status = exec_command_C(scan_state, active_branch);
322  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
323  status = exec_command_connect(scan_state, active_branch);
324  else if (strcmp(cmd, "cd") == 0)
325  status = exec_command_cd(scan_state, active_branch, cmd);
326  else if (strcmp(cmd, "close") == 0)
327  status = exec_command_close(scan_state, active_branch, cmd);
328  else if (strcmp(cmd, "conninfo") == 0)
329  status = exec_command_conninfo(scan_state, active_branch);
330  else if (pg_strcasecmp(cmd, "copy") == 0)
331  status = exec_command_copy(scan_state, active_branch);
332  else if (strcmp(cmd, "copyright") == 0)
333  status = exec_command_copyright(scan_state, active_branch);
334  else if (strcmp(cmd, "crosstabview") == 0)
335  status = exec_command_crosstabview(scan_state, active_branch);
336  else if (cmd[0] == 'd')
337  status = exec_command_d(scan_state, active_branch, cmd);
338  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
339  status = exec_command_edit(scan_state, active_branch,
340  query_buf, previous_buf);
341  else if (strcmp(cmd, "ef") == 0)
342  status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
343  else if (strcmp(cmd, "ev") == 0)
344  status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
345  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
346  strcmp(cmd, "warn") == 0)
347  status = exec_command_echo(scan_state, active_branch, cmd);
348  else if (strcmp(cmd, "elif") == 0)
349  status = exec_command_elif(scan_state, cstack, query_buf);
350  else if (strcmp(cmd, "else") == 0)
351  status = exec_command_else(scan_state, cstack, query_buf);
352  else if (strcmp(cmd, "endif") == 0)
353  status = exec_command_endif(scan_state, cstack, query_buf);
354  else if (strcmp(cmd, "encoding") == 0)
355  status = exec_command_encoding(scan_state, active_branch);
356  else if (strcmp(cmd, "errverbose") == 0)
357  status = exec_command_errverbose(scan_state, active_branch);
358  else if (strcmp(cmd, "f") == 0)
359  status = exec_command_f(scan_state, active_branch);
360  else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
361  status = exec_command_g(scan_state, active_branch, cmd);
362  else if (strcmp(cmd, "gdesc") == 0)
363  status = exec_command_gdesc(scan_state, active_branch);
364  else if (strcmp(cmd, "getenv") == 0)
365  status = exec_command_getenv(scan_state, active_branch, cmd);
366  else if (strcmp(cmd, "gexec") == 0)
367  status = exec_command_gexec(scan_state, active_branch);
368  else if (strcmp(cmd, "gset") == 0)
369  status = exec_command_gset(scan_state, active_branch);
370  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
371  status = exec_command_help(scan_state, active_branch);
372  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
373  status = exec_command_html(scan_state, active_branch);
374  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
375  strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
376  status = exec_command_include(scan_state, active_branch, cmd);
377  else if (strcmp(cmd, "if") == 0)
378  status = exec_command_if(scan_state, cstack, query_buf);
379  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
380  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
381  status = exec_command_list(scan_state, active_branch, cmd);
382  else if (strncmp(cmd, "lo_", 3) == 0)
383  status = exec_command_lo(scan_state, active_branch, cmd);
384  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
385  status = exec_command_out(scan_state, active_branch);
386  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
387  status = exec_command_print(scan_state, active_branch,
388  query_buf, previous_buf);
389  else if (strcmp(cmd, "parse") == 0)
390  status = exec_command_parse(scan_state, active_branch, cmd);
391  else if (strcmp(cmd, "password") == 0)
392  status = exec_command_password(scan_state, active_branch);
393  else if (strcmp(cmd, "prompt") == 0)
394  status = exec_command_prompt(scan_state, active_branch, cmd);
395  else if (strcmp(cmd, "pset") == 0)
396  status = exec_command_pset(scan_state, active_branch);
397  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
398  status = exec_command_quit(scan_state, active_branch);
399  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
400  status = exec_command_reset(scan_state, active_branch, query_buf);
401  else if (strcmp(cmd, "s") == 0)
402  status = exec_command_s(scan_state, active_branch);
403  else if (strcmp(cmd, "set") == 0)
404  status = exec_command_set(scan_state, active_branch);
405  else if (strcmp(cmd, "setenv") == 0)
406  status = exec_command_setenv(scan_state, active_branch, cmd);
407  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
408  status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
409  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
410  status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
411  else if (strcmp(cmd, "t") == 0)
412  status = exec_command_t(scan_state, active_branch);
413  else if (strcmp(cmd, "T") == 0)
414  status = exec_command_T(scan_state, active_branch);
415  else if (strcmp(cmd, "timing") == 0)
416  status = exec_command_timing(scan_state, active_branch);
417  else if (strcmp(cmd, "unset") == 0)
418  status = exec_command_unset(scan_state, active_branch, cmd);
419  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
420  status = exec_command_write(scan_state, active_branch, cmd,
421  query_buf, previous_buf);
422  else if (strcmp(cmd, "watch") == 0)
423  status = exec_command_watch(scan_state, active_branch,
424  query_buf, previous_buf);
425  else if (strcmp(cmd, "x") == 0)
426  status = exec_command_x(scan_state, active_branch);
427  else if (strcmp(cmd, "z") == 0 || strcmp(cmd, "zS") == 0)
428  status = exec_command_z(scan_state, active_branch, cmd);
429  else if (strcmp(cmd, "!") == 0)
430  status = exec_command_shell_escape(scan_state, active_branch);
431  else if (strcmp(cmd, "?") == 0)
432  status = exec_command_slash_command_help(scan_state, active_branch);
433  else
434  status = PSQL_CMD_UNKNOWN;
435 
436  /*
437  * All the commands that return PSQL_CMD_SEND want to execute previous_buf
438  * if query_buf is empty. For convenience we implement that here, not in
439  * the individual command subroutines.
440  */
441  if (status == PSQL_CMD_SEND)
442  (void) copy_previous_query(query_buf, previous_buf);
443 
444  return status;
445 }
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1999
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:807
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1446
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2168
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1752
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3351
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1504
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2701
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1632
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1732
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:454
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch)
Definition: command.c:473
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2228
static backslashResult exec_command_bind_named(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:509
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3034
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1812
static backslashResult exec_command_close(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:708
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1858
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1476
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2450
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2145
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1363
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:843
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3084
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:644
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1703
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1247
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2755
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2495
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2468
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2304
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2887
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1771
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2039
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2723
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:558
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1408
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1151
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1934
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:741
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:785
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3106
static backslashResult exec_command_parse(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2194
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:819
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2381
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2679
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2785
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2596
static bool is_branching_command(const char *cmd)
Definition: command.c:3289
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:591
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1686
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:3056
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2067
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1649
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2436
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2548
@ 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_bind_named(), exec_command_C(), exec_command_cd(), exec_command_close(), 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_parse(), 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 454 of file command.c.

455 {
456  bool success = true;
457 
458  if (active_branch)
459  {
461  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
462  else
463  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
464  }
465 
467 }
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4565
@ 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 473 of file command.c.

474 {
476 
477  if (active_branch)
478  {
479  char *opt;
480  int nparams = 0;
481  int nalloc = 0;
482 
484 
485  while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
486  {
487  nparams++;
488  if (nparams > nalloc)
489  {
490  nalloc = nalloc ? nalloc * 2 : 1;
491  pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
492  }
493  pset.bind_params[nparams - 1] = opt;
494  }
495 
496  pset.bind_nparams = nparams;
498  }
499  else
500  ignore_slash_options(scan_state);
501 
502  return status;
503 }
void clean_extended_state(void)
Definition: common.c:2279
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:3240
#define pg_realloc_array(pointer, type, count)
Definition: fe_memutils.h:63
@ OT_NORMAL
Definition: psqlscanslash.h:17
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
@ PSQL_SEND_EXTENDED_QUERY_PARAMS
Definition: settings.h:70
char ** bind_params
Definition: settings.h:111
PSQL_SEND_MODE send_mode
Definition: settings.h:108
int bind_nparams
Definition: settings.h:110

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

Referenced by exec_command().

◆ exec_command_bind_named()

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

Definition at line 509 of file command.c.

511 {
513 
514  if (active_branch)
515  {
516  char *opt;
517  int nparams = 0;
518  int nalloc = 0;
519 
521 
522  /* get the mandatory prepared statement name */
523  opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
524  if (!opt)
525  {
526  pg_log_error("\\%s: missing required argument", cmd);
527  status = PSQL_CMD_ERROR;
528  }
529  else
530  {
531  pset.stmtName = opt;
533 
534  /* set of parameters */
535  while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
536  {
537  nparams++;
538  if (nparams > nalloc)
539  {
540  nalloc = nalloc ? nalloc * 2 : 1;
541  pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
542  }
543  pset.bind_params[nparams - 1] = opt;
544  }
545  pset.bind_nparams = nparams;
546  }
547  }
548  else
549  ignore_slash_options(scan_state);
550 
551  return status;
552 }
@ PSQL_SEND_EXTENDED_QUERY_PREPARED
Definition: settings.h:71
char * stmtName
Definition: settings.h:112

References _psqlSettings::bind_nparams, _psqlSettings::bind_params, clean_extended_state(), ignore_slash_options(), OT_NORMAL, pg_log_error, pg_realloc_array, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQL_SEND_EXTENDED_QUERY_PREPARED, _psqlSettings::send_mode, and _psqlSettings::stmtName.

Referenced by exec_command().

◆ exec_command_C()

static backslashResult exec_command_C ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 558 of file command.c.

559 {
560  bool success = true;
561 
562  if (active_branch)
563  {
564  char *opt = psql_scan_slash_option(scan_state,
565  OT_NORMAL, NULL, true);
566 
567  success = do_pset("title", opt, &pset.popt, pset.quiet);
568  free(opt);
569  }
570  else
571  ignore_slash_options(scan_state);
572 
574 }

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

645 {
646  bool success = true;
647 
648  if (active_branch)
649  {
650  char *opt = psql_scan_slash_option(scan_state,
651  OT_NORMAL, NULL, true);
652  char *dir;
653 
654  if (opt)
655  dir = opt;
656  else
657  {
658 #ifndef WIN32
659  /* This should match get_home_path() */
660  dir = getenv("HOME");
661  if (dir == NULL || dir[0] == '\0')
662  {
663  uid_t user_id = geteuid();
664  struct passwd *pw;
665 
666  errno = 0; /* clear errno before call */
667  pw = getpwuid(user_id);
668  if (pw)
669  dir = pw->pw_dir;
670  else
671  {
672  pg_log_error("could not get home directory for user ID %ld: %s",
673  (long) user_id,
674  errno ? strerror(errno) : _("user does not exist"));
675  success = false;
676  }
677  }
678 #else /* WIN32 */
679 
680  /*
681  * On Windows, 'cd' without arguments prints the current
682  * directory, so if someone wants to code this here instead...
683  */
684  dir = "/";
685 #endif /* WIN32 */
686  }
687 
688  if (success &&
689  chdir(dir) < 0)
690  {
691  pg_log_error("\\%s: could not change directory to \"%s\": %m",
692  cmd, dir);
693  success = false;
694  }
695 
696  free(opt);
697  }
698  else
699  ignore_slash_options(scan_state);
700 
702 }
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_close()

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

Definition at line 708 of file command.c.

709 {
711 
712  if (active_branch)
713  {
714  char *opt = psql_scan_slash_option(scan_state,
715  OT_NORMAL, NULL, false);
716 
718 
719  if (!opt)
720  {
721  pg_log_error("\\%s: missing required argument", cmd);
722  status = PSQL_CMD_ERROR;
723  }
724  else
725  {
726  pset.stmtName = opt;
728  status = PSQL_CMD_SEND;
729  }
730  }
731  else
732  ignore_slash_options(scan_state);
733 
734  return status;
735 }
@ PSQL_SEND_EXTENDED_CLOSE
Definition: settings.h:68

References clean_extended_state(), ignore_slash_options(), OT_NORMAL, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQL_SEND_EXTENDED_CLOSE, _psqlSettings::send_mode, and _psqlSettings::stmtName.

Referenced by exec_command().

◆ exec_command_connect()

static backslashResult exec_command_connect ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 591 of file command.c.

592 {
593  bool success = true;
594 
595  if (active_branch)
596  {
597  static const char prefix[] = "-reuse-previous=";
598  char *opt1,
599  *opt2,
600  *opt3,
601  *opt4;
602  enum trivalue reuse_previous = TRI_DEFAULT;
603 
604  opt1 = read_connect_arg(scan_state);
605  if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
606  {
607  bool on_off;
608 
609  success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
610  "-reuse-previous",
611  &on_off);
612  if (success)
613  {
614  reuse_previous = on_off ? TRI_YES : TRI_NO;
615  free(opt1);
616  opt1 = read_connect_arg(scan_state);
617  }
618  }
619 
620  if (success) /* give up if reuse_previous was invalid */
621  {
622  opt2 = read_connect_arg(scan_state);
623  opt3 = read_connect_arg(scan_state);
624  opt4 = read_connect_arg(scan_state);
625 
626  success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
627 
628  free(opt2);
629  free(opt3);
630  free(opt4);
631  }
632  free(opt1);
633  }
634  else
635  ignore_slash_options(scan_state);
636 
638 }
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:3420
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:3137
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 741 of file command.c.

742 {
743  if (active_branch)
744  {
745  char *db = PQdb(pset.db);
746 
747  if (db == NULL)
748  printf(_("You are currently not connected to a database.\n"));
749  else
750  {
751  char *host = PQhost(pset.db);
752  char *hostaddr = PQhostaddr(pset.db);
753 
754  if (is_unixsock_path(host))
755  {
756  /* hostaddr overrides host */
757  if (hostaddr && *hostaddr)
758  printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
759  db, PQuser(pset.db), hostaddr, PQport(pset.db));
760  else
761  printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
762  db, PQuser(pset.db), host, PQport(pset.db));
763  }
764  else
765  {
766  if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
767  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
768  db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
769  else
770  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
771  db, PQuser(pset.db), host, PQport(pset.db));
772  }
773  printSSLInfo();
774  printGSSInfo();
775  }
776  }
777 
778  return PSQL_CMD_SKIP_LINE;
779 }

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

786 {
787  bool success = true;
788 
789  if (active_branch)
790  {
791  char *opt = psql_scan_slash_option(scan_state,
792  OT_WHOLE_LINE, NULL, false);
793 
794  success = do_copy(opt);
795  free(opt);
796  }
797  else
798  ignore_slash_whole_line(scan_state);
799 
801 }
bool do_copy(const char *args)
Definition: copy.c:268
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:3277
@ 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 807 of file command.c.

808 {
809  if (active_branch)
810  print_copyright();
811 
812  return PSQL_CMD_SKIP_LINE;
813 }
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 819 of file command.c.

820 {
822 
823  if (active_branch)
824  {
825  int i;
826 
827  for (i = 0; i < lengthof(pset.ctv_args); i++)
828  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
829  OT_NORMAL, NULL, true);
830  pset.crosstab_flag = true;
831  status = PSQL_CMD_SEND;
832  }
833  else
834  ignore_slash_options(scan_state);
835 
836  return status;
837 }
char * ctv_args[4]
Definition: settings.h:115
bool crosstab_flag
Definition: settings.h:114

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

844 {
846  bool success = true;
847 
848  if (active_branch)
849  {
850  char *pattern;
851  bool show_verbose,
852  show_system;
853 
854  /* We don't do SQLID reduction on the pattern yet */
855  pattern = psql_scan_slash_option(scan_state,
856  OT_NORMAL, NULL, true);
857 
858  show_verbose = strchr(cmd, '+') ? true : false;
859  show_system = strchr(cmd, 'S') ? true : false;
860 
861  switch (cmd[1])
862  {
863  case '\0':
864  case '+':
865  case 'S':
866  if (pattern)
867  success = describeTableDetails(pattern, show_verbose, show_system);
868  else
869  /* standard listing of interesting things */
870  success = listTables("tvmsE", NULL, show_verbose, show_system);
871  break;
872  case 'A':
873  {
874  char *pattern2 = NULL;
875 
876  if (pattern && cmd[2] != '\0' && cmd[2] != '+')
877  pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
878 
879  switch (cmd[2])
880  {
881  case '\0':
882  case '+':
883  success = describeAccessMethods(pattern, show_verbose);
884  break;
885  case 'c':
886  success = listOperatorClasses(pattern, pattern2, show_verbose);
887  break;
888  case 'f':
889  success = listOperatorFamilies(pattern, pattern2, show_verbose);
890  break;
891  case 'o':
892  success = listOpFamilyOperators(pattern, pattern2, show_verbose);
893  break;
894  case 'p':
895  success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
896  break;
897  default:
898  status = PSQL_CMD_UNKNOWN;
899  break;
900  }
901 
902  free(pattern2);
903  }
904  break;
905  case 'a':
906  success = describeAggregates(pattern, show_verbose, show_system);
907  break;
908  case 'b':
909  success = describeTablespaces(pattern, show_verbose);
910  break;
911  case 'c':
912  if (strncmp(cmd, "dconfig", 7) == 0)
914  show_verbose,
915  show_system);
916  else
917  success = listConversions(pattern,
918  show_verbose,
919  show_system);
920  break;
921  case 'C':
922  success = listCasts(pattern, show_verbose);
923  break;
924  case 'd':
925  if (strncmp(cmd, "ddp", 3) == 0)
926  success = listDefaultACLs(pattern);
927  else
928  success = objectDescription(pattern, show_system);
929  break;
930  case 'D':
931  success = listDomains(pattern, show_verbose, show_system);
932  break;
933  case 'f': /* function subsystem */
934  switch (cmd[2])
935  {
936  case '\0':
937  case '+':
938  case 'S':
939  case 'a':
940  case 'n':
941  case 'p':
942  case 't':
943  case 'w':
944  success = exec_command_dfo(scan_state, cmd, pattern,
945  show_verbose, show_system);
946  break;
947  default:
948  status = PSQL_CMD_UNKNOWN;
949  break;
950  }
951  break;
952  case 'g':
953  /* no longer distinct from \du */
954  success = describeRoles(pattern, show_verbose, show_system);
955  break;
956  case 'l':
957  success = listLargeObjects(show_verbose);
958  break;
959  case 'L':
960  success = listLanguages(pattern, show_verbose, show_system);
961  break;
962  case 'n':
963  success = listSchemas(pattern, show_verbose, show_system);
964  break;
965  case 'o':
966  success = exec_command_dfo(scan_state, cmd, pattern,
967  show_verbose, show_system);
968  break;
969  case 'O':
970  success = listCollations(pattern, show_verbose, show_system);
971  break;
972  case 'p':
973  success = permissionsList(pattern, show_system);
974  break;
975  case 'P':
976  {
977  switch (cmd[2])
978  {
979  case '\0':
980  case '+':
981  case 't':
982  case 'i':
983  case 'n':
984  success = listPartitionedTables(&cmd[2], pattern, show_verbose);
985  break;
986  default:
987  status = PSQL_CMD_UNKNOWN;
988  break;
989  }
990  }
991  break;
992  case 'T':
993  success = describeTypes(pattern, show_verbose, show_system);
994  break;
995  case 't':
996  case 'v':
997  case 'm':
998  case 'i':
999  case 's':
1000  case 'E':
1001  success = listTables(&cmd[1], pattern, show_verbose, show_system);
1002  break;
1003  case 'r':
1004  if (cmd[2] == 'd' && cmd[3] == 's')
1005  {
1006  char *pattern2 = NULL;
1007 
1008  if (pattern)
1009  pattern2 = psql_scan_slash_option(scan_state,
1010  OT_NORMAL, NULL, true);
1011  success = listDbRoleSettings(pattern, pattern2);
1012 
1013  free(pattern2);
1014  }
1015  else if (cmd[2] == 'g')
1016  success = describeRoleGrants(pattern, show_system);
1017  else
1018  status = PSQL_CMD_UNKNOWN;
1019  break;
1020  case 'R':
1021  switch (cmd[2])
1022  {
1023  case 'p':
1024  if (show_verbose)
1025  success = describePublications(pattern);
1026  else
1027  success = listPublications(pattern);
1028  break;
1029  case 's':
1030  success = describeSubscriptions(pattern, show_verbose);
1031  break;
1032  default:
1033  status = PSQL_CMD_UNKNOWN;
1034  }
1035  break;
1036  case 'u':
1037  success = describeRoles(pattern, show_verbose, show_system);
1038  break;
1039  case 'F': /* text search subsystem */
1040  switch (cmd[2])
1041  {
1042  case '\0':
1043  case '+':
1044  success = listTSConfigs(pattern, show_verbose);
1045  break;
1046  case 'p':
1047  success = listTSParsers(pattern, show_verbose);
1048  break;
1049  case 'd':
1050  success = listTSDictionaries(pattern, show_verbose);
1051  break;
1052  case 't':
1053  success = listTSTemplates(pattern, show_verbose);
1054  break;
1055  default:
1056  status = PSQL_CMD_UNKNOWN;
1057  break;
1058  }
1059  break;
1060  case 'e': /* SQL/MED subsystem */
1061  switch (cmd[2])
1062  {
1063  case 's':
1064  success = listForeignServers(pattern, show_verbose);
1065  break;
1066  case 'u':
1067  success = listUserMappings(pattern, show_verbose);
1068  break;
1069  case 'w':
1070  success = listForeignDataWrappers(pattern, show_verbose);
1071  break;
1072  case 't':
1073  success = listForeignTables(pattern, show_verbose);
1074  break;
1075  default:
1076  status = PSQL_CMD_UNKNOWN;
1077  break;
1078  }
1079  break;
1080  case 'x': /* Extensions */
1081  if (show_verbose)
1082  success = listExtensionContents(pattern);
1083  else
1084  success = listExtensions(pattern);
1085  break;
1086  case 'X': /* Extended Statistics */
1087  success = listExtendedStats(pattern);
1088  break;
1089  case 'y': /* Event Triggers */
1090  success = listEventTriggers(pattern, show_verbose);
1091  break;
1092  default:
1093  status = PSQL_CMD_UNKNOWN;
1094  }
1095 
1096  free(pattern);
1097  }
1098  else
1099  ignore_slash_options(scan_state);
1100 
1101  if (!success)
1102  status = PSQL_CMD_ERROR;
1103 
1104  return status;
1105 }
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:1109
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:5932
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:5581
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3661
bool listOpFamilyFunctions(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:7038
bool listPublications(const char *pattern)
Definition: describe.c:6274
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5204
bool listExtensionContents(const char *pattern)
Definition: describe.c:6110
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:70
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:5785
bool listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
Definition: describe.c:4154
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:6598
bool describeRoleGrants(const char *pattern, bool showSystem)
Definition: describe.c:3877
bool listExtendedStats(const char *pattern)
Definition: describe.c:4751
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:614
bool listOperatorFamilies(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6851
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:5856
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1444
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4440
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:5451
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3808
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4965
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5083
bool listExtensions(const char *pattern)
Definition: describe.c:6059
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3956
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:5516
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:214
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:4847
bool listOpFamilyOperators(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:6940
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6750
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:5987
bool describeConfigurationParameters(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4603
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:4671
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1174
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4523
bool permissionsList(const char *pattern, bool showSystem)
Definition: describe.c:1010
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:140
bool listLargeObjects(bool verbose)
Definition: describe.c:7127
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4364
bool describePublications(const char *pattern)
Definition: describe.c:6400
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1251
return true
Definition: isn.c:125

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

1112 {
1113  bool success;
1114  char *arg_patterns[FUNC_MAX_ARGS];
1115  int num_arg_patterns = 0;
1116 
1117  /* Collect argument-type patterns too */
1118  if (pattern) /* otherwise it was just \df or \do */
1119  {
1120  char *ap;
1121 
1122  while ((ap = psql_scan_slash_option(scan_state,
1123  OT_NORMAL, NULL, true)) != NULL)
1124  {
1125  arg_patterns[num_arg_patterns++] = ap;
1126  if (num_arg_patterns >= FUNC_MAX_ARGS)
1127  break; /* protect limited-size array */
1128  }
1129  }
1130 
1131  if (cmd[1] == 'f')
1132  success = describeFunctions(&cmd[2], pattern,
1133  arg_patterns, num_arg_patterns,
1134  show_verbose, show_system);
1135  else
1136  success = describeOperators(pattern,
1137  arg_patterns, num_arg_patterns,
1138  show_verbose, show_system);
1139 
1140  while (--num_arg_patterns >= 0)
1141  free(arg_patterns[num_arg_patterns]);
1142 
1143  return success;
1144 }
bool describeFunctions(const char *functypes, const char *func_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:287
bool describeOperators(const char *oper_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:769
#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 1363 of file command.c.

1364 {
1365  if (active_branch)
1366  {
1367  char *value;
1368  char quoted;
1369  bool no_newline = false;
1370  bool first = true;
1371  FILE *fout;
1372 
1373  if (strcmp(cmd, "qecho") == 0)
1374  fout = pset.queryFout;
1375  else if (strcmp(cmd, "warn") == 0)
1376  fout = stderr;
1377  else
1378  fout = stdout;
1379 
1380  while ((value = psql_scan_slash_option(scan_state,
1381  OT_NORMAL, &quoted, false)))
1382  {
1383  if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1384  no_newline = true;
1385  else
1386  {
1387  if (first)
1388  first = false;
1389  else
1390  fputc(' ', fout);
1391  fputs(value, fout);
1392  }
1393  free(value);
1394  }
1395  if (!no_newline)
1396  fputs("\n", fout);
1397  }
1398  else
1399  ignore_slash_options(scan_state);
1400 
1401  return PSQL_CMD_SKIP_LINE;
1402 }
FILE * queryFout
Definition: settings.h:93

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

1153 {
1155 
1156  if (active_branch)
1157  {
1158  if (!query_buf)
1159  {
1160  pg_log_error("no query buffer");
1161  status = PSQL_CMD_ERROR;
1162  }
1163  else
1164  {
1165  char *fname;
1166  char *ln = NULL;
1167  int lineno = -1;
1168 
1169  fname = psql_scan_slash_option(scan_state,
1170  OT_NORMAL, NULL, true);
1171  if (fname)
1172  {
1173  /* try to get separate lineno arg */
1174  ln = psql_scan_slash_option(scan_state,
1175  OT_NORMAL, NULL, true);
1176  if (ln == NULL)
1177  {
1178  /* only one arg; maybe it is lineno not fname */
1179  if (fname[0] &&
1180  strspn(fname, "0123456789") == strlen(fname))
1181  {
1182  /* all digits, so assume it is lineno */
1183  ln = fname;
1184  fname = NULL;
1185  }
1186  }
1187  }
1188  if (ln)
1189  {
1190  lineno = atoi(ln);
1191  if (lineno < 1)
1192  {
1193  pg_log_error("invalid line number: %s", ln);
1194  status = PSQL_CMD_ERROR;
1195  }
1196  }
1197  if (status != PSQL_CMD_ERROR)
1198  {
1199  bool discard_on_quit;
1200 
1201  expand_tilde(&fname);
1202  if (fname)
1203  {
1204  canonicalize_path(fname);
1205  /* Always clear buffer if the file isn't modified */
1206  discard_on_quit = true;
1207  }
1208  else
1209  {
1210  /*
1211  * If query_buf is empty, recall previous query for
1212  * editing. But in that case, the query buffer should be
1213  * emptied if editing doesn't modify the file.
1214  */
1215  discard_on_quit = copy_previous_query(query_buf,
1216  previous_buf);
1217  }
1218 
1219  if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1220  status = PSQL_CMD_NEWEDIT;
1221  else
1222  status = PSQL_CMD_ERROR;
1223  }
1224 
1225  /*
1226  * On error while editing or if specifying an incorrect line
1227  * number, reset the query buffer.
1228  */
1229  if (status == PSQL_CMD_ERROR)
1230  resetPQExpBuffer(query_buf);
1231 
1232  free(fname);
1233  free(ln);
1234  }
1235  }
1236  else
1237  ignore_slash_options(scan_state);
1238 
1239  return status;
1240 }
void expand_tilde(char **filename)
Definition: common.c:2195
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:4217
@ PSQL_CMD_NEWEDIT
Definition: command.h:21
void canonicalize_path(char *path)
Definition: path.c:265

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

1249 {
1251 
1252  if (active_branch)
1253  {
1254  char *obj_desc = psql_scan_slash_option(scan_state,
1255  OT_WHOLE_LINE,
1256  NULL, true);
1257  int lineno = -1;
1258 
1259  if (!query_buf)
1260  {
1261  pg_log_error("no query buffer");
1262  status = PSQL_CMD_ERROR;
1263  }
1264  else
1265  {
1266  Oid obj_oid = InvalidOid;
1268 
1269  lineno = strip_lineno_from_objdesc(obj_desc);
1270  if (lineno == 0)
1271  {
1272  /* error already reported */
1273  status = PSQL_CMD_ERROR;
1274  }
1275  else if (!obj_desc)
1276  {
1277  /* set up an empty command to fill in */
1278  resetPQExpBuffer(query_buf);
1279  if (is_func)
1280  appendPQExpBufferStr(query_buf,
1281  "CREATE FUNCTION ( )\n"
1282  " RETURNS \n"
1283  " LANGUAGE \n"
1284  " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1285  "AS $function$\n"
1286  "\n$function$\n");
1287  else
1288  appendPQExpBufferStr(query_buf,
1289  "CREATE VIEW AS\n"
1290  " SELECT \n"
1291  " -- something...\n");
1292  }
1293  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1294  {
1295  /* error already reported */
1296  status = PSQL_CMD_ERROR;
1297  }
1298  else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1299  {
1300  /* error already reported */
1301  status = PSQL_CMD_ERROR;
1302  }
1303  else if (is_func && lineno > 0)
1304  {
1305  /*
1306  * lineno "1" should correspond to the first line of the
1307  * function body. We expect that pg_get_functiondef() will
1308  * emit that on a line beginning with "AS ", "BEGIN ", or
1309  * "RETURN ", and that there can be no such line before the
1310  * real start of the function body. Increment lineno by the
1311  * number of lines before that line, so that it becomes
1312  * relative to the first line of the function definition.
1313  */
1314  const char *lines = query_buf->data;
1315 
1316  while (*lines != '\0')
1317  {
1318  if (strncmp(lines, "AS ", 3) == 0 ||
1319  strncmp(lines, "BEGIN ", 6) == 0 ||
1320  strncmp(lines, "RETURN ", 7) == 0)
1321  break;
1322  lineno++;
1323  /* find start of next line */
1324  lines = strchr(lines, '\n');
1325  if (!lines)
1326  break;
1327  lines++;
1328  }
1329  }
1330  }
1331 
1332  if (status != PSQL_CMD_ERROR)
1333  {
1334  bool edited = false;
1335 
1336  if (!do_edit(NULL, query_buf, lineno, true, &edited))
1337  status = PSQL_CMD_ERROR;
1338  else if (!edited)
1339  puts(_("No changes"));
1340  else
1341  status = PSQL_CMD_NEWEDIT;
1342  }
1343 
1344  /*
1345  * On error while doing object lookup or while editing, or if
1346  * specifying an incorrect line number, reset the query buffer.
1347  */
1348  if (status == PSQL_CMD_ERROR)
1349  resetPQExpBuffer(query_buf);
1350 
1351  free(obj_desc);
1352  }
1353  else
1354  ignore_slash_whole_line(scan_state);
1355 
1356  return status;
1357 }
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:5698
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:5638
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:5858
#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 1858 of file command.c.

1860 {
1861  bool success = true;
1862 
1863  switch (conditional_stack_peek(cstack))
1864  {
1865  case IFSTATE_TRUE:
1866 
1867  /*
1868  * Just finished active branch of this \if block. Update saved
1869  * state so we will keep whatever data was put in query_buf by the
1870  * active branch.
1871  */
1872  save_query_text_state(scan_state, cstack, query_buf);
1873 
1874  /*
1875  * Discard \elif expression and ignore the rest until \endif.
1876  * Switch state before reading expression to ensure proper lexer
1877  * behavior.
1878  */
1880  ignore_boolean_expression(scan_state);
1881  break;
1882  case IFSTATE_FALSE:
1883 
1884  /*
1885  * Discard any query text added by the just-skipped branch.
1886  */
1887  discard_query_text(scan_state, cstack, query_buf);
1888 
1889  /*
1890  * Have not yet found a true expression in this \if block, so this
1891  * might be the first. We have to change state before examining
1892  * the expression, or the lexer won't do the right thing.
1893  */
1895  if (!is_true_boolean_expression(scan_state, "\\elif expression"))
1897  break;
1898  case IFSTATE_IGNORED:
1899 
1900  /*
1901  * Discard any query text added by the just-skipped branch.
1902  */
1903  discard_query_text(scan_state, cstack, query_buf);
1904 
1905  /*
1906  * Skip expression and move on. Either the \if block already had
1907  * an active section, or whole block is being skipped.
1908  */
1909  ignore_boolean_expression(scan_state);
1910  break;
1911  case IFSTATE_ELSE_TRUE:
1912  case IFSTATE_ELSE_FALSE:
1913  pg_log_error("\\elif: cannot occur after \\else");
1914  success = false;
1915  break;
1916  case IFSTATE_NONE:
1917  /* no \if to elif from */
1918  pg_log_error("\\elif: no matching \\if");
1919  success = false;
1920  break;
1921  }
1922 
1924 }
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3325
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3224
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:3207
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3305
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 1934 of file command.c.

1936 {
1937  bool success = true;
1938 
1939  switch (conditional_stack_peek(cstack))
1940  {
1941  case IFSTATE_TRUE:
1942 
1943  /*
1944  * Just finished active branch of this \if block. Update saved
1945  * state so we will keep whatever data was put in query_buf by the
1946  * active branch.
1947  */
1948  save_query_text_state(scan_state, cstack, query_buf);
1949 
1950  /* Now skip the \else branch */
1952  break;
1953  case IFSTATE_FALSE:
1954 
1955  /*
1956  * Discard any query text added by the just-skipped branch.
1957  */
1958  discard_query_text(scan_state, cstack, query_buf);
1959 
1960  /*
1961  * We've not found any true \if or \elif expression, so execute
1962  * the \else branch.
1963  */
1965  break;
1966  case IFSTATE_IGNORED:
1967 
1968  /*
1969  * Discard any query text added by the just-skipped branch.
1970  */
1971  discard_query_text(scan_state, cstack, query_buf);
1972 
1973  /*
1974  * Either we previously processed the active branch of this \if,
1975  * or the whole \if block is being skipped. Either way, skip the
1976  * \else branch.
1977  */
1979  break;
1980  case IFSTATE_ELSE_TRUE:
1981  case IFSTATE_ELSE_FALSE:
1982  pg_log_error("\\else: cannot occur after \\else");
1983  success = false;
1984  break;
1985  case IFSTATE_NONE:
1986  /* no \if to else from */
1987  pg_log_error("\\else: no matching \\if");
1988  success = false;
1989  break;
1990  }
1991 
1993 }

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

1409 {
1410  if (active_branch)
1411  {
1412  char *encoding = psql_scan_slash_option(scan_state,
1413  OT_NORMAL, NULL, false);
1414 
1415  if (!encoding)
1416  {
1417  /* show encoding */
1419  }
1420  else
1421  {
1422  /* set encoding */
1423  if (PQsetClientEncoding(pset.db, encoding) == -1)
1424  pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1425  else
1426  {
1427  /* save encoding info into psql internal data */
1430  SetVariable(pset.vars, "ENCODING",
1432  }
1433  free(encoding);
1434  }
1435  }
1436  else
1437  ignore_slash_options(scan_state);
1438 
1439  return PSQL_CMD_SKIP_LINE;
1440 }
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7288
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7296
int32 encoding
Definition: pg_database.h:41
#define pg_encoding_to_char
Definition: pg_wchar.h:630
VariableSpace vars
Definition: settings.h:133
int encoding
Definition: settings.h:92
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 1999 of file command.c.

2001 {
2002  bool success = true;
2003 
2004  switch (conditional_stack_peek(cstack))
2005  {
2006  case IFSTATE_TRUE:
2007  case IFSTATE_ELSE_TRUE:
2008  /* Close the \if block, keeping the query text */
2009  success = conditional_stack_pop(cstack);
2010  Assert(success);
2011  break;
2012  case IFSTATE_FALSE:
2013  case IFSTATE_IGNORED:
2014  case IFSTATE_ELSE_FALSE:
2015 
2016  /*
2017  * Discard any query text added by the just-skipped branch.
2018  */
2019  discard_query_text(scan_state, cstack, query_buf);
2020 
2021  /* Close the \if block */
2022  success = conditional_stack_pop(cstack);
2023  Assert(success);
2024  break;
2025  case IFSTATE_NONE:
2026  /* no \if to end */
2027  pg_log_error("\\endif: no matching \\if");
2028  success = false;
2029  break;
2030  }
2031 
2033 }
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 1446 of file command.c.

1447 {
1448  if (active_branch)
1449  {
1450  if (pset.last_error_result)
1451  {
1452  char *msg;
1453 
1457  if (msg)
1458  {
1459  pg_log_error("%s", msg);
1460  PQfreemem(msg);
1461  }
1462  else
1463  puts(_("out of memory"));
1464  }
1465  else
1466  puts(_("There is no previous error."));
1467  }
1468 
1469  return PSQL_CMD_SKIP_LINE;
1470 }
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3435
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:161
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:153
PGresult * last_error_result
Definition: settings.h:98

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

1477 {
1478  bool success = true;
1479 
1480  if (active_branch)
1481  {
1482  char *fname = psql_scan_slash_option(scan_state,
1483  OT_NORMAL, NULL, false);
1484 
1485  success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1486  free(fname);
1487  }
1488  else
1489  ignore_slash_options(scan_state);
1490 
1492 }

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

1505 {
1507  char *fname;
1508 
1509  /*
1510  * Because the option processing for this is fairly complicated, we do it
1511  * and then decide whether the branch is active.
1512  */
1513  fname = psql_scan_slash_option(scan_state,
1514  OT_FILEPIPE, NULL, false);
1515 
1516  if (fname && fname[0] == '(')
1517  {
1518  /* Consume pset options through trailing ')' ... */
1519  status = process_command_g_options(fname + 1, scan_state,
1520  active_branch, cmd);
1521  free(fname);
1522  /* ... and again attempt to scan the filename. */
1523  fname = psql_scan_slash_option(scan_state,
1524  OT_FILEPIPE, NULL, false);
1525  }
1526 
1527  if (status == PSQL_CMD_SKIP_LINE && active_branch)
1528  {
1529  if (!fname)
1530  pset.gfname = NULL;
1531  else
1532  {
1533  expand_tilde(&fname);
1534  pset.gfname = pg_strdup(fname);
1535  }
1536  if (strcmp(cmd, "gx") == 0)
1537  {
1538  /* save settings if not done already, then force expanded=on */
1539  if (pset.gsavepopt == NULL)
1541  pset.popt.topt.expanded = 1;
1542  }
1543  status = PSQL_CMD_SEND;
1544  }
1545 
1546  free(fname);
1547 
1548  return status;
1549 }
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:5118
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1557
@ OT_FILEPIPE
Definition: psqlscanslash.h:20
printQueryOpt * gsavepopt
Definition: settings.h:103
char * gfname
Definition: settings.h:102

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

1633 {
1635 
1636  if (active_branch)
1637  {
1638  pset.gdesc_flag = true;
1639  status = PSQL_CMD_SEND;
1640  }
1641 
1642  return status;
1643 }
bool gdesc_flag
Definition: settings.h:106

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

1651 {
1652  bool success = true;
1653 
1654  if (active_branch)
1655  {
1656  char *myvar = psql_scan_slash_option(scan_state,
1657  OT_NORMAL, NULL, false);
1658  char *envvar = psql_scan_slash_option(scan_state,
1659  OT_NORMAL, NULL, false);
1660 
1661  if (!myvar || !envvar)
1662  {
1663  pg_log_error("\\%s: missing required argument", cmd);
1664  success = false;
1665  }
1666  else
1667  {
1668  char *envval = getenv(envvar);
1669 
1670  if (envval && !SetVariable(pset.vars, myvar, envval))
1671  success = false;
1672  }
1673  free(myvar);
1674  free(envvar);
1675  }
1676  else
1677  ignore_slash_options(scan_state);
1678 
1680 }

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

1687 {
1689 
1690  if (active_branch)
1691  {
1692  pset.gexec_flag = true;
1693  status = PSQL_CMD_SEND;
1694  }
1695 
1696  return status;
1697 }
bool gexec_flag
Definition: settings.h:107

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

1704 {
1706 
1707  if (active_branch)
1708  {
1709  char *prefix = psql_scan_slash_option(scan_state,
1710  OT_NORMAL, NULL, false);
1711 
1712  if (prefix)
1713  pset.gset_prefix = prefix;
1714  else
1715  {
1716  /* we must set a non-NULL prefix to trigger storing */
1717  pset.gset_prefix = pg_strdup("");
1718  }
1719  /* gset_prefix is freed later */
1720  status = PSQL_CMD_SEND;
1721  }
1722  else
1723  ignore_slash_options(scan_state);
1724 
1725  return status;
1726 }
char * gset_prefix
Definition: settings.h:105

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

1733 {
1734  if (active_branch)
1735  {
1736  char *opt = psql_scan_slash_option(scan_state,
1737  OT_WHOLE_LINE, NULL, true);
1738 
1739  helpSQL(opt, pset.popt.topt.pager);
1740  free(opt);
1741  }
1742  else
1743  ignore_slash_whole_line(scan_state);
1744 
1745  return PSQL_CMD_SKIP_LINE;
1746 }
void helpSQL(const char *topic, unsigned short int pager)

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

Referenced by exec_command().

◆ exec_command_html()

static backslashResult exec_command_html ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1752 of file command.c.

1753 {
1754  bool success = true;
1755 
1756  if (active_branch)
1757  {
1758  if (pset.popt.topt.format != PRINT_HTML)
1759  success = do_pset("format", "html", &pset.popt, pset.quiet);
1760  else
1761  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1762  }
1763 
1765 }

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

1814 {
1815  if (conditional_active(cstack))
1816  {
1817  /*
1818  * First, push a new active stack entry; this ensures that the lexer
1819  * will perform variable substitution and backtick evaluation while
1820  * scanning the expression. (That should happen anyway, since we know
1821  * we're in an active outer branch, but let's be sure.)
1822  */
1824 
1825  /* Remember current query state in case we need to restore later */
1826  save_query_text_state(scan_state, cstack, query_buf);
1827 
1828  /*
1829  * Evaluate the expression; if it's false, change to inactive state.
1830  */
1831  if (!is_true_boolean_expression(scan_state, "\\if expression"))
1833  }
1834  else
1835  {
1836  /*
1837  * We're within an inactive outer branch, so this entire \if block
1838  * will be ignored. We don't want to evaluate the expression, so push
1839  * the "ignored" stack state before scanning it.
1840  */
1842 
1843  /* Remember current query state in case we need to restore later */
1844  save_query_text_state(scan_state, cstack, query_buf);
1845 
1846  ignore_boolean_expression(scan_state);
1847  }
1848 
1849  return PSQL_CMD_SKIP_LINE;
1850 }
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 1771 of file command.c.

1772 {
1773  bool success = true;
1774 
1775  if (active_branch)
1776  {
1777  char *fname = psql_scan_slash_option(scan_state,
1778  OT_NORMAL, NULL, true);
1779 
1780  if (!fname)
1781  {
1782  pg_log_error("\\%s: missing required argument", cmd);
1783  success = false;
1784  }
1785  else
1786  {
1787  bool include_relative;
1788 
1789  include_relative = (strcmp(cmd, "ir") == 0
1790  || strcmp(cmd, "include_relative") == 0);
1791  expand_tilde(&fname);
1792  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1793  free(fname);
1794  }
1795  }
1796  else
1797  ignore_slash_options(scan_state);
1798 
1800 }
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4412
#define EXIT_SUCCESS
Definition: settings.h:174

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

2040 {
2041  bool success = true;
2042 
2043  if (active_branch)
2044  {
2045  char *pattern;
2046  bool show_verbose;
2047 
2048  pattern = psql_scan_slash_option(scan_state,
2049  OT_NORMAL, NULL, true);
2050 
2051  show_verbose = strchr(cmd, '+') ? true : false;
2052 
2053  success = listAllDbs(pattern, show_verbose);
2054 
2055  free(pattern);
2056  }
2057  else
2058  ignore_slash_options(scan_state);
2059 
2061 }
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:910

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

2068 {
2070  bool success = true;
2071 
2072  if (active_branch)
2073  {
2074  char *opt1,
2075  *opt2;
2076 
2077  opt1 = psql_scan_slash_option(scan_state,
2078  OT_NORMAL, NULL, true);
2079  opt2 = psql_scan_slash_option(scan_state,
2080  OT_NORMAL, NULL, true);
2081 
2082  if (strcmp(cmd + 3, "export") == 0)
2083  {
2084  if (!opt2)
2085  {
2086  pg_log_error("\\%s: missing required argument", cmd);
2087  success = false;
2088  }
2089  else
2090  {
2091  expand_tilde(&opt2);
2092  success = do_lo_export(opt1, opt2);
2093  }
2094  }
2095 
2096  else if (strcmp(cmd + 3, "import") == 0)
2097  {
2098  if (!opt1)
2099  {
2100  pg_log_error("\\%s: missing required argument", cmd);
2101  success = false;
2102  }
2103  else
2104  {
2105  expand_tilde(&opt1);
2106  success = do_lo_import(opt1, opt2);
2107  }
2108  }
2109 
2110  else if (strcmp(cmd + 3, "list") == 0)
2111  success = listLargeObjects(false);
2112  else if (strcmp(cmd + 3, "list+") == 0)
2113  success = listLargeObjects(true);
2114 
2115  else if (strcmp(cmd + 3, "unlink") == 0)
2116  {
2117  if (!opt1)
2118  {
2119  pg_log_error("\\%s: missing required argument", cmd);
2120  success = false;
2121  }
2122  else
2123  success = do_lo_unlink(opt1);
2124  }
2125 
2126  else
2127  status = PSQL_CMD_UNKNOWN;
2128 
2129  free(opt1);
2130  free(opt2);
2131  }
2132  else
2133  ignore_slash_options(scan_state);
2134 
2135  if (!success)
2136  status = PSQL_CMD_ERROR;
2137 
2138  return status;
2139 }
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 2145 of file command.c.

2146 {
2147  bool success = true;
2148 
2149  if (active_branch)
2150  {
2151  char *fname = psql_scan_slash_option(scan_state,
2152  OT_FILEPIPE, NULL, true);
2153 
2154  expand_tilde(&fname);
2155  success = setQFout(fname);
2156  free(fname);
2157  }
2158  else
2159  ignore_slash_filepipe(scan_state);
2160 
2162 }
bool setQFout(const char *fname)
Definition: common.c:132
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:3257

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

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

Definition at line 2194 of file command.c.

2196 {
2198 
2199  if (active_branch)
2200  {
2201  char *opt = psql_scan_slash_option(scan_state,
2202  OT_NORMAL, NULL, false);
2203 
2205 
2206  if (!opt)
2207  {
2208  pg_log_error("\\%s: missing required argument", cmd);
2209  status = PSQL_CMD_ERROR;
2210  }
2211  else
2212  {
2213  pset.stmtName = opt;
2215  status = PSQL_CMD_SEND;
2216  }
2217  }
2218  else
2219  ignore_slash_options(scan_state);
2220 
2221  return status;
2222 }
@ PSQL_SEND_EXTENDED_PARSE
Definition: settings.h:69

References clean_extended_state(), ignore_slash_options(), OT_NORMAL, pg_log_error, pset, PSQL_CMD_ERROR, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQL_SEND_EXTENDED_PARSE, _psqlSettings::send_mode, and _psqlSettings::stmtName.

Referenced by exec_command().

◆ exec_command_password()

static backslashResult exec_command_password ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2228 of file command.c.

2229 {
2230  bool success = true;
2231 
2232  if (active_branch)
2233  {
2234  char *user = psql_scan_slash_option(scan_state,
2235  OT_SQLID, NULL, true);
2236  char *pw1 = NULL;
2237  char *pw2 = NULL;
2239  PromptInterruptContext prompt_ctx;
2240 
2241  if (user == NULL)
2242  {
2243  /* By default, the command applies to CURRENT_USER */
2244  PGresult *res;
2245 
2246  res = PSQLexec("SELECT CURRENT_USER");
2247  if (!res)
2248  return PSQL_CMD_ERROR;
2249 
2250  user = pg_strdup(PQgetvalue(res, 0, 0));
2251  PQclear(res);
2252  }
2253 
2254  /* Set up to let SIGINT cancel simple_prompt_extended() */
2255  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2256  prompt_ctx.enabled = &sigint_interrupt_enabled;
2257  prompt_ctx.canceled = false;
2258 
2259  initPQExpBuffer(&buf);
2260  printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2261 
2262  pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2263  if (!prompt_ctx.canceled)
2264  pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2265 
2266  if (prompt_ctx.canceled)
2267  {
2268  /* fail silently */
2269  success = false;
2270  }
2271  else if (strcmp(pw1, pw2) != 0)
2272  {
2273  pg_log_error("Passwords didn't match.");
2274  success = false;
2275  }
2276  else
2277  {
2279 
2281  {
2283  success = false;
2284  }
2285 
2286  PQclear(res);
2287  }
2288 
2289  free(user);
2290  free(pw1);
2291  free(pw2);
2292  termPQExpBuffer(&buf);
2293  }
2294  else
2295  ignore_slash_options(scan_state);
2296 
2298 }
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:292
PGresult * PSQLexec(const char *query)
Definition: common.c:620
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:294
PGresult * PQchangePassword(PGconn *conn, const char *user, const char *passwd)
Definition: fe-auth.c:1442
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:120
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
@ OT_SQLID
Definition: psqlscanslash.h:18
char * simple_prompt_extended(const char *prompt, bool echo, PromptInterruptContext *prompt_ctx)
Definition: sprompt.c:53
volatile sig_atomic_t * enabled
Definition: string.h:21

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

Referenced by exec_command().

◆ exec_command_print()

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

Definition at line 2168 of file command.c.

2170 {
2171  if (active_branch)
2172  {
2173  /*
2174  * We want to print the same thing \g would execute, but not to change
2175  * the query buffer state; so we can't use copy_previous_query().
2176  * Also, beware of possibility that buffer pointers are NULL.
2177  */
2178  if (query_buf && query_buf->len > 0)
2179  puts(query_buf->data);
2180  else if (previous_buf && previous_buf->len > 0)
2181  puts(previous_buf->data);
2182  else if (!pset.quiet)
2183  puts(_("Query buffer is empty."));
2184  fflush(stdout);
2185  }
2186 
2187  return PSQL_CMD_SKIP_LINE;
2188 }

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

2306 {
2307  bool success = true;
2308 
2309  if (active_branch)
2310  {
2311  char *opt,
2312  *prompt_text = NULL;
2313  char *arg1,
2314  *arg2;
2315 
2316  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2317  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2318 
2319  if (!arg1)
2320  {
2321  pg_log_error("\\%s: missing required argument", cmd);
2322  success = false;
2323  }
2324  else
2325  {
2326  char *result;
2327  PromptInterruptContext prompt_ctx;
2328 
2329  /* Set up to let SIGINT cancel simple_prompt_extended() */
2330  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2331  prompt_ctx.enabled = &sigint_interrupt_enabled;
2332  prompt_ctx.canceled = false;
2333 
2334  if (arg2)
2335  {
2336  prompt_text = arg1;
2337  opt = arg2;
2338  }
2339  else
2340  opt = arg1;
2341 
2342  if (!pset.inputfile)
2343  {
2344  result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2345  }
2346  else
2347  {
2348  if (prompt_text)
2349  {
2350  fputs(prompt_text, stdout);
2351  fflush(stdout);
2352  }
2353  result = gets_fromFile(stdin);
2354  if (!result)
2355  {
2356  pg_log_error("\\%s: could not read value for variable",
2357  cmd);
2358  success = false;
2359  }
2360  }
2361 
2362  if (prompt_ctx.canceled ||
2363  (result && !SetVariable(pset.vars, opt, result)))
2364  success = false;
2365 
2366  free(result);
2367  free(prompt_text);
2368  free(opt);
2369  }
2370  }
2371  else
2372  ignore_slash_options(scan_state);
2373 
2375 }
char * gets_fromFile(FILE *source)
Definition: input.c:186
char * inputfile
Definition: settings.h:125

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

2382 {
2383  bool success = true;
2384 
2385  if (active_branch)
2386  {
2387  char *opt0 = psql_scan_slash_option(scan_state,
2388  OT_NORMAL, NULL, false);
2389  char *opt1 = psql_scan_slash_option(scan_state,
2390  OT_NORMAL, NULL, false);
2391 
2392  if (!opt0)
2393  {
2394  /* list all variables */
2395 
2396  int i;
2397  static const char *const my_list[] = {
2398  "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2399  "fieldsep_zero", "footer", "format", "linestyle", "null",
2400  "numericlocale", "pager", "pager_min_lines",
2401  "recordsep", "recordsep_zero",
2402  "tableattr", "title", "tuples_only",
2403  "unicode_border_linestyle",
2404  "unicode_column_linestyle",
2405  "unicode_header_linestyle",
2406  "xheader_width",
2407  NULL
2408  };
2409 
2410  for (i = 0; my_list[i] != NULL; i++)
2411  {
2412  char *val = pset_value_string(my_list[i], &pset.popt);
2413 
2414  printf("%-24s %s\n", my_list[i], val);
2415  free(val);
2416  }
2417 
2418  success = true;
2419  }
2420  else
2421  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2422 
2423  free(opt0);
2424  free(opt1);
2425  }
2426  else
2427  ignore_slash_options(scan_state);
2428 
2430 }
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:5225
long val
Definition: informix.c:689

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

2437 {
2439 
2440  if (active_branch)
2441  status = PSQL_CMD_TERMINATE;
2442 
2443  return status;
2444 }
@ 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 2450 of file command.c.

2452 {
2453  if (active_branch)
2454  {
2455  resetPQExpBuffer(query_buf);
2456  psql_scan_reset(scan_state);
2457  if (!pset.quiet)
2458  puts(_("Query buffer reset (cleared)."));
2459  }
2460 
2461  return PSQL_CMD_SKIP_LINE;
2462 }
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 2468 of file command.c.

2469 {
2470  bool success = true;
2471 
2472  if (active_branch)
2473  {
2474  char *fname = psql_scan_slash_option(scan_state,
2475  OT_NORMAL, NULL, true);
2476 
2477  expand_tilde(&fname);
2478  success = printHistory(fname, pset.popt.topt.pager);
2479  if (success && !pset.quiet && fname)
2480  printf(_("Wrote history to file \"%s\".\n"), fname);
2481  if (!fname)
2482  putchar('\n');
2483  free(fname);
2484  }
2485  else
2486  ignore_slash_options(scan_state);
2487 
2489 }
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:494

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

Referenced by exec_command().

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2495 of file command.c.

2496 {
2497  bool success = true;
2498 
2499  if (active_branch)
2500  {
2501  char *opt0 = psql_scan_slash_option(scan_state,
2502  OT_NORMAL, NULL, false);
2503 
2504  if (!opt0)
2505  {
2506  /* list all variables */
2508  success = true;
2509  }
2510  else
2511  {
2512  /*
2513  * Set variable to the concatenation of the arguments.
2514  */
2515  char *newval;
2516  char *opt;
2517 
2518  opt = psql_scan_slash_option(scan_state,
2519  OT_NORMAL, NULL, false);
2520  newval = pg_strdup(opt ? opt : "");
2521  free(opt);
2522 
2523  while ((opt = psql_scan_slash_option(scan_state,
2524  OT_NORMAL, NULL, false)))
2525  {
2526  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2527  strcat(newval, opt);
2528  free(opt);
2529  }
2530 
2531  if (!SetVariable(pset.vars, opt0, newval))
2532  success = false;
2533 
2534  free(newval);
2535  }
2536  free(opt0);
2537  }
2538  else
2539  ignore_slash_options(scan_state);
2540 
2542 }
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 2548 of file command.c.

2550 {
2551  bool success = true;
2552 
2553  if (active_branch)
2554  {
2555  char *envvar = psql_scan_slash_option(scan_state,
2556  OT_NORMAL, NULL, false);
2557  char *envval = psql_scan_slash_option(scan_state,
2558  OT_NORMAL, NULL, false);
2559 
2560  if (!envvar)
2561  {
2562  pg_log_error("\\%s: missing required argument", cmd);
2563  success = false;
2564  }
2565  else if (strchr(envvar, '=') != NULL)
2566  {
2567  pg_log_error("\\%s: environment variable name must not contain \"=\"",
2568  cmd);
2569  success = false;
2570  }
2571  else if (!envval)
2572  {
2573  /* No argument - unset the environment variable */
2574  unsetenv(envvar);
2575  success = true;
2576  }
2577  else
2578  {
2579  /* Set variable to the value of the next argument */
2580  setenv(envvar, envval, 1);
2581  success = true;
2582  }
2583  free(envvar);
2584  free(envval);
2585  }
2586  else
2587  ignore_slash_options(scan_state);
2588 
2590 }
#define unsetenv(x)
Definition: win32_port.h:556
#define setenv(x, y, z)
Definition: win32_port.h:555

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

2598 {
2600 
2601  if (active_branch)
2602  {
2603  bool show_linenumbers = (strchr(cmd, '+') != NULL);
2604  PQExpBuffer buf;
2605  char *obj_desc;
2606  Oid obj_oid = InvalidOid;
2608 
2609  buf = createPQExpBuffer();
2610  obj_desc = psql_scan_slash_option(scan_state,
2611  OT_WHOLE_LINE, NULL, true);
2612  if (!obj_desc)
2613  {
2614  if (is_func)
2615  pg_log_error("function name is required");
2616  else
2617  pg_log_error("view name is required");
2618  status = PSQL_CMD_ERROR;
2619  }
2620  else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2621  {
2622  /* error already reported */
2623  status = PSQL_CMD_ERROR;
2624  }
2625  else if (!get_create_object_cmd(eot, obj_oid, buf))
2626  {
2627  /* error already reported */
2628  status = PSQL_CMD_ERROR;
2629  }
2630  else
2631  {
2632  FILE *output;
2633  bool is_pager;
2634 
2635  /* Select output stream: stdout, pager, or file */
2636  if (pset.queryFout == stdout)
2637  {
2638  /* count lines in function to see if pager is needed */
2639  int lineno = count_lines_in_buf(buf);
2640 
2641  output = PageOutput(lineno, &(pset.popt.topt));
2642  is_pager = true;
2643  }
2644  else
2645  {
2646  /* use previously set output file, without pager */
2647  output = pset.queryFout;
2648  is_pager = false;
2649  }
2650 
2651  if (show_linenumbers)
2652  {
2653  /* add line numbers */
2654  print_with_linenumbers(output, buf->data, is_func);
2655  }
2656  else
2657  {
2658  /* just send the definition to output */
2659  fputs(buf->data, output);
2660  }
2661 
2662  if (is_pager)
2663  ClosePager(output);
2664  }
2665 
2666  free(obj_desc);
2668  }
2669  else
2670  ignore_slash_whole_line(scan_state);
2671 
2672  return status;
2673 }
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:5916
static void print_with_linenumbers(FILE *output, char *lines, bool is_func)
Definition: command.c:5946
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 3084 of file command.c.

3085 {
3086  bool success = true;
3087 
3088  if (active_branch)
3089  {
3090  char *opt = psql_scan_slash_option(scan_state,
3091  OT_WHOLE_LINE, NULL, false);
3092 
3093  success = do_shell(opt);
3094  free(opt);
3095  }
3096  else
3097  ignore_slash_whole_line(scan_state);
3098 
3100 }
static bool do_shell(const char *command)
Definition: command.c:5314

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

3107 {
3108  if (active_branch)
3109  {
3110  char *opt0 = psql_scan_slash_option(scan_state,
3111  OT_NORMAL, NULL, false);
3112 
3113  if (!opt0 || strcmp(opt0, "commands") == 0)
3115  else if (strcmp(opt0, "options") == 0)
3117  else if (strcmp(opt0, "variables") == 0)
3119  else
3121 
3122  free(opt0);
3123  }
3124  else
3125  ignore_slash_options(scan_state);
3126 
3127  return PSQL_CMD_SKIP_LINE;
3128 }
void slashUsage(unsigned short int pager)
Definition: help.c:148
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 2679 of file command.c.

2680 {
2681  bool success = true;
2682 
2683  if (active_branch)
2684  {
2685  char *opt = psql_scan_slash_option(scan_state,
2686  OT_NORMAL, NULL, true);
2687 
2688  success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
2689  free(opt);
2690  }
2691  else
2692  ignore_slash_options(scan_state);
2693 
2695 }

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

2702 {
2703  bool success = true;
2704 
2705  if (active_branch)
2706  {
2707  char *value = psql_scan_slash_option(scan_state,
2708  OT_NORMAL, NULL, false);
2709 
2710  success = do_pset("tableattr", value, &pset.popt, pset.quiet);
2711  free(value);
2712  }
2713  else
2714  ignore_slash_options(scan_state);
2715 
2717 }

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

2724 {
2725  bool success = true;
2726 
2727  if (active_branch)
2728  {
2729  char *opt = psql_scan_slash_option(scan_state,
2730  OT_NORMAL, NULL, false);
2731 
2732  if (opt)
2733  success = ParseVariableBool(opt, "\\timing", &pset.timing);
2734  else
2735  pset.timing = !pset.timing;
2736  if (!pset.quiet)
2737  {
2738  if (pset.timing)
2739  puts(_("Timing is on."));
2740  else
2741  puts(_("Timing is off."));
2742  }
2743  free(opt);
2744  }
2745  else
2746  ignore_slash_options(scan_state);
2747 
2749 }

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

2757 {
2758  bool success = true;
2759 
2760  if (active_branch)
2761  {
2762  char *opt = psql_scan_slash_option(scan_state,
2763  OT_NORMAL, NULL, false);
2764 
2765  if (!opt)
2766  {
2767  pg_log_error("\\%s: missing required argument", cmd);
2768  success = false;
2769  }
2770  else if (!SetVariable(pset.vars, opt, NULL))
2771  success = false;
2772 
2773  free(opt);
2774  }
2775  else
2776  ignore_slash_options(scan_state);
2777 
2779 }

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

2889 {
2890  bool success = true;
2891 
2892  if (active_branch)
2893  {
2894  bool have_sleep = false;
2895  bool have_iter = false;
2896  bool have_min_rows = false;
2897  double sleep = 2;
2898  int iter = 0;
2899  int min_rows = 0;
2900 
2901  /*
2902  * Parse arguments. We allow either an unlabeled interval or
2903  * "name=value", where name is from the set ('i', 'interval', 'c',
2904  * 'count', 'm', 'min_rows').
2905  */
2906  while (success)
2907  {
2908  char *opt = psql_scan_slash_option(scan_state,
2909  OT_NORMAL, NULL, true);
2910  char *valptr;
2911  char *opt_end;
2912 
2913  if (!opt)
2914  break; /* no more arguments */
2915 
2916  valptr = strchr(opt, '=');
2917  if (valptr)
2918  {
2919  /* Labeled argument */
2920  valptr++;
2921  if (strncmp("i=", opt, strlen("i=")) == 0 ||
2922  strncmp("interval=", opt, strlen("interval=")) == 0)
2923  {
2924  if (have_sleep)
2925  {
2926  pg_log_error("\\watch: interval value is specified more than once");
2927  success = false;
2928  }
2929  else
2930  {
2931  have_sleep = true;
2932  errno = 0;
2933  sleep = strtod(valptr, &opt_end);
2934  if (sleep < 0 || *opt_end || errno == ERANGE)
2935  {
2936  pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
2937  success = false;
2938  }
2939  }
2940  }
2941  else if (strncmp("c=", opt, strlen("c=")) == 0 ||
2942  strncmp("count=", opt, strlen("count=")) == 0)
2943  {
2944  if (have_iter)
2945  {
2946  pg_log_error("\\watch: iteration count is specified more than once");
2947  success = false;
2948  }
2949  else
2950  {
2951  have_iter = true;
2952  errno = 0;
2953  iter = strtoint(valptr, &opt_end, 10);
2954  if (iter <= 0 || *opt_end || errno == ERANGE)
2955  {
2956  pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
2957  success = false;
2958  }
2959  }
2960  }
2961  else if (strncmp("m=", opt, strlen("m=")) == 0 ||
2962  strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
2963  {
2964  if (have_min_rows)
2965  {
2966  pg_log_error("\\watch: minimum row count specified more than once");
2967  success = false;
2968  }
2969  else
2970  {
2971  have_min_rows = true;
2972  errno = 0;
2973  min_rows = strtoint(valptr, &opt_end, 10);
2974  if (min_rows <= 0 || *opt_end || errno == ERANGE)
2975  {
2976  pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
2977  success = false;
2978  }
2979  }
2980  }
2981  else
2982  {
2983  pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
2984  success = false;
2985  }
2986  }
2987  else
2988  {
2989  /* Unlabeled argument: take it as interval */
2990  if (have_sleep)
2991  {
2992  pg_log_error("\\watch: interval value is specified more than once");
2993  success = false;
2994  }
2995  else
2996  {
2997  have_sleep = true;
2998  errno = 0;
2999  sleep = strtod(opt, &opt_end);
3000  if (sleep < 0 || *opt_end || errno == ERANGE)
3001  {
3002  pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3003  success = false;
3004  }
3005  }
3006  }
3007 
3008  free(opt);
3009  }
3010 
3011  /* If we parsed arguments successfully, do the command */
3012  if (success)
3013  {
3014  /* If query_buf is empty, recall and execute previous query */
3015  (void) copy_previous_query(query_buf, previous_buf);
3016 
3017  success = do_watch(query_buf, sleep, iter, min_rows);
3018  }
3019 
3020  /* Reset the query buffer as though for \r */
3021  resetPQExpBuffer(query_buf);
3022  psql_scan_reset(scan_state);
3023  }
3024  else
3025  ignore_slash_options(scan_state);
3026 
3028 }
static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
Definition: command.c:5365
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
Definition: string.c:50

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

Referenced by exec_command().

◆ exec_command_write()

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

Definition at line 2785 of file command.c.

2788 {
2790 
2791  if (active_branch)
2792  {
2793  char *fname = psql_scan_slash_option(scan_state,
2794  OT_FILEPIPE, NULL, true);
2795  FILE *fd = NULL;
2796  bool is_pipe = false;
2797 
2798  if (!query_buf)
2799  {
2800  pg_log_error("no query buffer");
2801  status = PSQL_CMD_ERROR;
2802  }
2803  else
2804  {
2805  if (!fname)
2806  {
2807  pg_log_error("\\%s: missing required argument", cmd);
2808  status = PSQL_CMD_ERROR;
2809  }
2810  else
2811  {
2812  expand_tilde(&fname);
2813  if (fname[0] == '|')
2814  {
2815  is_pipe = true;
2816  fflush(NULL);
2818  fd = popen(&fname[1], "w");
2819  }
2820  else
2821  {
2822  canonicalize_path(fname);
2823  fd = fopen(fname, "w");
2824  }
2825  if (!fd)
2826  {
2827  pg_log_error("%s: %m", fname);
2828  status = PSQL_CMD_ERROR;
2829  }
2830  }
2831  }
2832 
2833  if (fd)
2834  {
2835  int result;
2836 
2837  /*
2838  * We want to print the same thing \g would execute, but not to
2839  * change the query buffer state; so we can't use
2840  * copy_previous_query(). Also, beware of possibility that buffer
2841  * pointers are NULL.
2842  */
2843  if (query_buf && query_buf->len > 0)
2844  fprintf(fd, "%s\n", query_buf->data);
2845  else if (previous_buf && previous_buf->len > 0)
2846  fprintf(fd, "%s\n", previous_buf->data);
2847 
2848  if (is_pipe)
2849  {
2850  result = pclose(fd);
2851 
2852  if (result != 0)
2853  {
2854  pg_log_error("%s: %s", fname, wait_result_to_str(result));
2855  status = PSQL_CMD_ERROR;
2856  }
2857  SetShellResultVariables(result);
2858  }
2859  else
2860  {
2861  result = fclose(fd);
2862 
2863  if (result == EOF)
2864  {
2865  pg_log_error("%s: %m", fname);
2866  status = PSQL_CMD_ERROR;
2867  }
2868  }
2869  }
2870 
2871  if (is_pipe)
2873 
2874  free(fname);
2875  }
2876  else
2877  ignore_slash_filepipe(scan_state);
2878 
2879  return status;
2880 }
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33

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

Referenced by exec_command().

◆ exec_command_x()

static backslashResult exec_command_x ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 3034 of file command.c.

3035 {
3036  bool success = true;
3037 
3038  if (active_branch)
3039  {
3040  char *opt = psql_scan_slash_option(scan_state,
3041  OT_NORMAL, NULL, true);
3042 
3043  success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3044  free(opt);
3045  }
3046  else
3047  ignore_slash_options(scan_state);
3048 
3050 }

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

Referenced by exec_command().

◆ exec_command_z()

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

Definition at line 3056 of file command.c.

3057 {
3058  bool success = true;
3059 
3060  if (active_branch)
3061  {
3062  char *pattern;
3063  bool show_system;
3064 
3065  pattern = psql_scan_slash_option(scan_state,
3066  OT_NORMAL, NULL, true);
3067 
3068  show_system = strchr(cmd, 'S') ? true : false;
3069 
3070  success = permissionsList(pattern, show_system);
3071 
3072  free(pattern);
3073  }
3074  else
3075  ignore_slash_options(scan_state);
3076 
3078 }

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

Referenced by exec_command().

◆ gather_boolean_expression()

static PQExpBuffer gather_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3177 of file command.c.

3178 {
3179  PQExpBuffer exp_buf = createPQExpBuffer();
3180  int num_options = 0;
3181  char *value;
3182 
3183  /* collect all arguments for the conditional command into exp_buf */
3184  while ((value = psql_scan_slash_option(scan_state,
3185  OT_NORMAL, NULL, false)) != NULL)
3186  {
3187  /* add spaces between tokens */
3188  if (num_options > 0)
3189  appendPQExpBufferChar(exp_buf, ' ');
3190  appendPQExpBufferStr(exp_buf, value);
3191  num_options++;
3192  free(value);
3193  }
3194 
3195  return exp_buf;
3196 }

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

Referenced by ignore_boolean_expression(), and is_true_boolean_expression().

◆ get_create_object_cmd()

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

Definition at line 5698 of file command.c.

5700 {
5701  bool result = true;
5702  PQExpBuffer query = createPQExpBuffer();
5703  PGresult *res;
5704 
5705  switch (obj_type)
5706  {
5707  case EditableFunction:
5708  printfPQExpBuffer(query,
5709  "SELECT pg_catalog.pg_get_functiondef(%u)",
5710  oid);
5711  break;
5712 
5713  case EditableView:
5714 
5715  /*
5716  * pg_get_viewdef() just prints the query, so we must prepend
5717  * CREATE for ourselves. We must fully qualify the view name to
5718  * ensure the right view gets replaced. Also, check relation kind
5719  * to be sure it's a view.
5720  *
5721  * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
5722  * CHECK OPTION. These are not part of the view definition
5723  * returned by pg_get_viewdef() and so need to be retrieved
5724  * separately. Materialized views (introduced in 9.3) may have
5725  * arbitrary storage parameter reloptions.
5726  */
5727  if (pset.sversion >= 90400)
5728  {
5729  printfPQExpBuffer(query,
5730  "SELECT nspname, relname, relkind, "
5731  "pg_catalog.pg_get_viewdef(c.oid, true), "
5732  "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5733  "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5734  "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
5735  "FROM pg_catalog.pg_class c "
5736  "LEFT JOIN pg_catalog.pg_namespace n "
5737  "ON c.relnamespace = n.oid WHERE c.oid = %u",
5738  oid);
5739  }
5740  else
5741  {
5742  printfPQExpBuffer(query,
5743  "SELECT nspname, relname, relkind, "
5744  "pg_catalog.pg_get_viewdef(c.oid, true), "
5745  "c.reloptions AS reloptions, "
5746  "NULL AS checkoption "
5747  "FROM pg_catalog.pg_class c "
5748  "LEFT JOIN pg_catalog.pg_namespace n "
5749  "ON c.relnamespace = n.oid WHERE c.oid = %u",
5750  oid);
5751  }
5752  break;
5753  }
5754 
5755  if (!echo_hidden_command(query->data))
5756  {
5757  destroyPQExpBuffer(query);
5758  return false;
5759  }
5760  res = PQexec(pset.db, query->data);
5761  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
5762  {
5764  switch (obj_type)
5765  {
5766  case EditableFunction:
5768  break;
5769 
5770  case EditableView:
5771  {
5772  char *nspname = PQgetvalue(res, 0, 0);
5773  char *relname = PQgetvalue(res, 0, 1);
5774  char *relkind = PQgetvalue(res, 0, 2);
5775  char *viewdef = PQgetvalue(res, 0, 3);
5776  char *reloptions = PQgetvalue(res, 0, 4);
5777  char *checkoption = PQgetvalue(res, 0, 5);
5778 
5779  /*
5780  * If the backend ever supports CREATE OR REPLACE
5781  * MATERIALIZED VIEW, allow that here; but as of today it
5782  * does not, so editing a matview definition in this way
5783  * is impossible.
5784  */
5785  switch (relkind[0])
5786  {
5787 #ifdef NOT_USED
5788  case RELKIND_MATVIEW:
5789  appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
5790  break;
5791 #endif
5792  case RELKIND_VIEW:
5793  appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
5794  break;
5795  default:
5796  pg_log_error("\"%s.%s\" is not a view",
5797  nspname, relname);
5798  result = false;
5799  break;
5800  }
5801  appendPQExpBuffer(buf, "%s.", fmtId(nspname));
5803 
5804  /* reloptions, if not an empty array "{}" */
5805  if (reloptions != NULL && strlen(reloptions) > 2)
5806  {
5807  appendPQExpBufferStr(buf, "\n WITH (");
5808  if (!appendReloptionsArray(buf, reloptions, "",
5809  pset.encoding,
5810  standard_strings()))
5811  {
5812  pg_log_error("could not parse reloptions array");
5813  result = false;
5814  }
5815  appendPQExpBufferChar(buf, ')');
5816  }
5817 
5818  /* View definition from pg_get_viewdef (a SELECT query) */
5819  appendPQExpBuffer(buf, " AS\n%s", viewdef);
5820 
5821  /* Get rid of the semicolon that pg_get_viewdef appends */
5822  if (buf->len > 0 && buf->data[buf->len - 1] == ';')
5823  buf->data[--(buf->len)] = '\0';
5824 
5825  /* WITH [LOCAL|CASCADED] CHECK OPTION */
5826  if (checkoption && checkoption[0] != '\0')
5827  appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
5828  checkoption);
5829  }
5830  break;
5831  }
5832  /* Make sure result ends with a newline */
5833  if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
5834  appendPQExpBufferChar(buf, '\n');
5835  }
5836  else
5837  {
5839  result = false;
5840  }
5841 
5842  PQclear(res);
5843  destroyPQExpBuffer(query);
5844 
5845  return result;
5846 }
bool standard_strings(void)
Definition: common.c:2154
static bool echo_hidden_command(const char *query)
Definition: command.c:5606
static void minimal_error_message(PGresult *res)
Definition: command.c:5988
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:123
NameData relname
Definition: pg_class.h:38
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
Definition: string_utils.c:804

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

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ HandleSlashCmds()

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

Definition at line 218 of file command.c.

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

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

Referenced by main(), and MainLoop().

◆ ignore_boolean_expression()

static void ignore_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3224 of file command.c.

3225 {
3227 
3229 }
static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3177

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

Referenced by exec_command_elif(), and exec_command_if().

◆ ignore_slash_filepipe()

static void ignore_slash_filepipe ( PsqlScanState  scan_state)
static

Definition at line 3257 of file command.c.

3258 {
3259  char *arg = psql_scan_slash_option(scan_state,
3260  OT_FILEPIPE, NULL, false);
3261 
3262  free(arg);
3263 }

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

Referenced by exec_command_out(), and exec_command_write().

◆ ignore_slash_options()

◆ ignore_slash_whole_line()

static void ignore_slash_whole_line ( PsqlScanState  scan_state)
static

Definition at line 3277 of file command.c.

3278 {
3279  char *arg = psql_scan_slash_option(scan_state,
3280  OT_WHOLE_LINE, NULL, false);
3281 
3282  free(arg);
3283 }

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

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

◆ is_branching_command()

static bool is_branching_command ( const char *  cmd)
static

Definition at line 3289 of file command.c.

3290 {
3291  return (strcmp(cmd, "if") == 0 ||
3292  strcmp(cmd, "elif") == 0 ||
3293  strcmp(cmd, "else") == 0 ||
3294  strcmp(cmd, "endif") == 0);
3295 }

Referenced by exec_command().

◆ is_true_boolean_expression()

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

Definition at line 3207 of file command.c.

3208 {
3210  bool value = false;
3211  bool success = ParseVariableBool(buf->data, name, &value);
3212 
3214  return success && value;
3215 }

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

Referenced by exec_command_elif(), and exec_command_if().

◆ lookup_object_oid()

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

Definition at line 5638 of file command.c.

5640 {
5641  bool result = true;
5642  PQExpBuffer query = createPQExpBuffer();
5643  PGresult *res;
5644 
5645  switch (obj_type)
5646  {
5647  case EditableFunction:
5648 
5649  /*
5650  * We have a function description, e.g. "x" or "x(int)". Issue a
5651  * query to retrieve the function's OID using a cast to regproc or
5652  * regprocedure (as appropriate).
5653  */
5654  appendPQExpBufferStr(query, "SELECT ");
5655  appendStringLiteralConn(query, desc, pset.db);
5656  appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
5657  strchr(desc, '(') ? "regprocedure" : "regproc");
5658  break;
5659 
5660  case EditableView:
5661 
5662  /*
5663  * Convert view name (possibly schema-qualified) to OID. Note:
5664  * this code doesn't check if the relation is actually a view.
5665  * We'll detect that in get_create_object_cmd().
5666  */
5667  appendPQExpBufferStr(query, "SELECT ");
5668  appendStringLiteralConn(query, desc, pset.db);
5669  appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
5670  break;
5671  }
5672 
5673  if (!echo_hidden_command(query->data))
5674  {
5675  destroyPQExpBuffer(query);
5676  return false;
5677  }
5678  res = PQexec(pset.db, query->data);
5679  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
5680  *obj_oid = atooid(PQgetvalue(res, 0, 0));
5681  else
5682  {
5684  result = false;
5685  }
5686 
5687  PQclear(res);
5688  destroyPQExpBuffer(query);
5689 
5690  return result;
5691 }
#define atooid(x)
Definition: postgres_ext.h:42
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293

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

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ minimal_error_message()

static void minimal_error_message ( PGresult res)
static

Definition at line 5988 of file command.c.

5989 {
5990  PQExpBuffer msg;
5991  const char *fld;
5992 
5993  msg = createPQExpBuffer();
5994 
5996  if (fld)
5997  printfPQExpBuffer(msg, "%s: ", fld);
5998  else
5999  printfPQExpBuffer(msg, "ERROR: ");
6001  if (fld)
6002  appendPQExpBufferStr(msg, fld);
6003  else
6004  appendPQExpBufferStr(msg, "(not available)");
6005  appendPQExpBufferChar(msg, '\n');
6006 
6007  pg_log_error("%s", msg->data);
6008 
6009  destroyPQExpBuffer(msg);
6010 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54

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

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ param_is_newly_set()

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

Definition at line 3397 of file command.c.

3398 {
3399  if (new_val == NULL)
3400  return false;
3401 
3402  if (old_val == NULL || strcmp(old_val, new_val) != 0)
3403  return true;
3404 
3405  return false;
3406 }

Referenced by do_connect().

◆ print_with_linenumbers()

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

Definition at line 5946 of file command.c.

5947 {
5948  bool in_header = is_func;
5949  int lineno = 0;
5950 
5951  while (*lines != '\0')
5952  {
5953  char *eol;
5954 
5955  if (in_header &&
5956  (strncmp(lines, "AS ", 3) == 0 ||
5957  strncmp(lines, "BEGIN ", 6) == 0 ||
5958  strncmp(lines, "RETURN ", 7) == 0))
5959  in_header = false;
5960 
5961  /* increment lineno only for body's lines */
5962  if (!in_header)
5963  lineno++;
5964 
5965  /* find and mark end of current line */
5966  eol = strchr(lines, '\n');
5967  if (eol != NULL)
5968  *eol = '\0';
5969 
5970  /* show current line as appropriate */
5971  if (in_header)
5972  fprintf(output, " %s\n", lines);
5973  else
5974  fprintf(output, "%-7d %s\n", lineno, lines);
5975 
5976  /* advance to next line, if any */
5977  if (eol == NULL)
5978  break;
5979  lines = ++eol;
5980  }
5981 }

References fprintf, and output.

Referenced by exec_command_sf_sv().

◆ printGSSInfo()

static void printGSSInfo ( void  )
static

Definition at line 4033 of file command.c.

4034 {
4035  if (!PQgssEncInUse(pset.db))
4036  return; /* no GSSAPI encryption in use */
4037 
4038  printf(_("GSSAPI-encrypted connection\n"));
4039 }
int PQgssEncInUse(PGconn *conn)

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

Referenced by connection_warnings(), and exec_command_conninfo().

◆ printPsetInfo()

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

Definition at line 4918 of file command.c.

4919 {
4920  Assert(param != NULL);
4921 
4922  /* show border style/width */
4923  if (strcmp(param, "border") == 0)
4924  printf(_("Border style is %d.\n"), popt->topt.border);
4925 
4926  /* show the target width for the wrapped format */
4927  else if (strcmp(param, "columns") == 0)
4928  {
4929  if (!popt->topt.columns)
4930  printf(_("Target width is unset.\n"));
4931  else
4932  printf(_("Target width is %d.\n"), popt->topt.columns);
4933  }
4934 
4935  /* show expanded/vertical mode */
4936  else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
4937  {
4938  if (popt->topt.expanded == 1)
4939  printf(_("Expanded display is on.\n"));
4940  else if (popt->topt.expanded == 2)
4941  printf(_("Expanded display is used automatically.\n"));
4942  else
4943  printf(_("Expanded display is off.\n"));
4944  }
4945 
4946  /* show xheader width value */
4947  else if (strcmp(param, "xheader_width") == 0)
4948  {
4950  printf(_("Expanded header width is \"%s\".\n"), "full");
4952  printf(_("Expanded header width is \"%s\".\n"), "column");
4954  printf(_("Expanded header width is \"%s\".\n"), "page");
4956  printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
4957  }
4958 
4959  /* show field separator for CSV format */
4960  else if (strcmp(param, "csv_fieldsep") == 0)
4961  {
4962  printf(_("Field separator for CSV is \"%s\".\n"),
4963  popt->topt.csvFieldSep);
4964  }
4965 
4966  /* show field separator for unaligned text */
4967  else if (strcmp(param, "fieldsep") == 0)
4968  {
4969  if (popt->topt.fieldSep.separator_zero)
4970  printf(_("Field separator is zero byte.\n"));
4971  else
4972  printf(_("Field separator is \"%s\".\n"),
4973  popt->topt.fieldSep.separator);
4974  }
4975 
4976  else if (strcmp(param, "fieldsep_zero") == 0)
4977  {
4978  printf(_("Field separator is zero byte.\n"));
4979  }
4980 
4981  /* show disable "(x rows)" footer */
4982  else if (strcmp(param, "footer") == 0)
4983  {
4984  if (popt->topt.default_footer)
4985  printf(_("Default footer is on.\n"));
4986  else
4987  printf(_("Default footer is off.\n"));
4988  }
4989 
4990  /* show format */
4991  else if (strcmp(param, "format") == 0)
4992  {
4993  printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
4994  }
4995 
4996  /* show table line style */
4997  else if (strcmp(param, "linestyle") == 0)
4998  {
4999  printf(_("Line style is %s.\n"),
5000  get_line_style(&popt->topt)->name);
5001  }
5002 
5003  /* show null display */
5004  else if (strcmp(param, "null") == 0)
5005  {
5006  printf(_("Null display is \"%s\".\n"),
5007  popt->nullPrint ? popt->nullPrint : "");
5008  }
5009 
5010  /* show locale-aware numeric output */
5011  else if (strcmp(param, "numericlocale") == 0)
5012  {
5013  if (popt->topt.numericLocale)
5014  printf(_("Locale-adjusted numeric output is on.\n"));
5015  else
5016  printf(_("Locale-adjusted numeric output is off.\n"));
5017  }
5018 
5019  /* show toggle use of pager */
5020  else if (strcmp(param, "pager") == 0)
5021  {
5022  if (popt->topt.pager == 1)
5023  printf(_("Pager is used for long output.\n"));
5024  else if (popt->topt.pager == 2)
5025  printf(_("Pager is always used.\n"));
5026  else
5027  printf(_("Pager usage is off.\n"));
5028  }
5029 
5030  /* show minimum lines for pager use */
5031  else if (strcmp(param, "pager_min_lines") == 0)
5032  {
5033  printf(ngettext("Pager won't be used for less than %d line.\n",
5034  "Pager won't be used for less than %d lines.\n",
5035  popt->topt.pager_min_lines),
5036  popt->topt.pager_min_lines);
5037  }
5038 
5039  /* show record separator for unaligned text */
5040  else if (strcmp(param, "recordsep") == 0)
5041  {
5042  if (popt->topt.recordSep.separator_zero)
5043  printf(_("Record separator is zero byte.\n"));
5044  else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
5045  printf(_("Record separator is <newline>.\n"));
5046  else
5047  printf(_("Record separator is \"%s\".\n"),
5048  popt->topt.recordSep.separator);
5049  }
5050 
5051  else if (strcmp(param, "recordsep_zero") == 0)
5052  {
5053  printf(_("Record separator is zero byte.\n"));
5054  }
5055 
5056  /* show HTML table tag options */
5057  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5058  {
5059  if (popt->topt.tableAttr)
5060  printf(_("Table attributes are \"%s\".\n"),
5061  popt->topt.tableAttr);
5062  else
5063  printf(_("Table attributes unset.\n"));
5064  }
5065 
5066  /* show title override */
5067  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5068  {
5069  if (popt->title)
5070  printf(_("Title is \"%s\".\n"), popt->title);
5071  else
5072  printf(_("Title is unset.\n"));
5073  }
5074 
5075  /* show toggle between full and tuples-only format */
5076  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5077  {
5078  if (popt->topt.tuples_only)
5079  printf(_("Tuples only is on.\n"));
5080  else
5081  printf(_("Tuples only is off.\n"));
5082  }
5083 
5084  /* Unicode style formatting */
5085  else if (strcmp(param, "unicode_border_linestyle") == 0)
5086  {
5087  printf(_("Unicode border line style is \"%s\".\n"),
5089  }
5090 
5091  else if (strcmp(param, "unicode_column_linestyle") == 0)
5092  {
5093  printf(_("Unicode column line style is \"%s\".\n"),
5095  }
5096 
5097  else if (strcmp(param, "unicode_header_linestyle") == 0)
5098  {
5099  printf(_("Unicode header line style is \"%s\".\n"),
5101  }
5102 
5103  else
5104  {
5105  pg_log_error("\\pset: unknown option: %s", param);
5106  return false;
5107  }
5108 
5109  return true;
5110 }
#define ngettext(s, p, n)
Definition: c.h:1186
static const char * _align2string(enum printFormat in)
Definition: command.c:4479
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:4535
const printTextFormat * get_line_style(const printTableOpt *opt)
Definition: print.c:3677
const char * name
Definition: print.h:84

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

Referenced by do_pset().

◆ printSSLInfo()

static void printSSLInfo ( void  )
static

Definition at line 4005 of file command.c.

4006 {
4007  const char *protocol;
4008  const char *cipher;
4009  const char *compression;
4010  const char *alpn;
4011 
4012  if (!PQsslInUse(pset.db))
4013  return; /* no SSL */
4014 
4015  protocol = PQsslAttribute(pset.db, "protocol");
4016  cipher = PQsslAttribute(pset.db, "cipher");
4017  compression = PQsslAttribute(pset.db, "compression");
4018  alpn = PQsslAttribute(pset.db, "alpn");
4019 
4020  printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
4021  protocol ? protocol : _("unknown"),
4022  cipher ? cipher : _("unknown"),
4023  (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4024  (alpn && alpn[0] != '\0') ? alpn : _("none"));
4025 }
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:103

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

Referenced by connection_warnings(), and exec_command_conninfo().

◆ process_command_g_options()

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

Definition at line 1557 of file command.c.

1559 {
1560  bool success = true;
1561  bool found_r_paren = false;
1562 
1563  do
1564  {
1565  char *option;
1566  size_t optlen;
1567 
1568  /* If not first time through, collect a new option */
1569  if (first_option)
1570  option = first_option;
1571  else
1572  {
1573  option = psql_scan_slash_option(scan_state,
1574  OT_NORMAL, NULL, false);
1575  if (!option)
1576  {
1577  if (active_branch)
1578  {
1579  pg_log_error("\\%s: missing right parenthesis", cmd);
1580  success = false;
1581  }
1582  break;
1583  }
1584  }
1585 
1586  /* Check for terminating right paren, and remove it from string */
1587  optlen = strlen(option);
1588  if (optlen > 0 && option[optlen - 1] == ')')
1589  {
1590  option[--optlen] = '\0';
1591  found_r_paren = true;
1592  }
1593 
1594  /* If there was anything besides parentheses, parse/execute it */
1595  if (optlen > 0)
1596  {
1597  /* We can have either "name" or "name=value" */
1598  char *valptr = strchr(option, '=');
1599 
1600  if (valptr)
1601  *valptr++ = '\0';
1602  if (active_branch)
1603  {
1604  /* save settings if not done already, then apply option */
1605  if (pset.gsavepopt == NULL)
1607  success &= do_pset(option, valptr, &pset.popt, true);
1608  }
1609  }
1610 
1611  /* Clean up after this option. We should not free first_option. */
1612  if (first_option)
1613  first_option = NULL;
1614  else
1615  free(option);
1616  } while (!found_r_paren);
1617 
1618  /* If we failed after already changing some options, undo side-effects */
1619  if (!success && active_branch && pset.gsavepopt)
1620  {
1622  pset.gsavepopt = NULL;
1623  }
1624 
1626 }
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:5154

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

Referenced by exec_command_g().

◆ process_file()

int process_file ( char *  filename,
bool  use_relative_path 
)

Definition at line 4412 of file command.c.

4413 {
4414  FILE *fd;
4415  int result;
4416  char *oldfilename;
4417  char relpath[MAXPGPATH];
4418 
4419  if (!filename)
4420  {
4421  fd = stdin;
4422  filename = NULL;
4423  }
4424  else if (strcmp(filename, "-") != 0)
4425  {
4427 
4428  /*
4429  * If we were asked to resolve the pathname relative to the location
4430  * of the currently executing script, and there is one, and this is a
4431  * relative pathname, then prepend all but the last pathname component
4432  * of the current script to this pathname.
4433  */
4434  if (use_relative_path && pset.inputfile &&
4436  {
4437  strlcpy(relpath, pset.inputfile, sizeof(relpath));
4441 
4442  filename = relpath;
4443  }
4444 
4445  fd = fopen(filename, PG_BINARY_R);
4446 
4447  if (!fd)
4448  {
4449  pg_log_error("%s: %m", filename);
4450  return EXIT_FAILURE;
4451  }
4452  }
4453  else
4454  {
4455  fd = stdin;
4456  filename = "<stdin>"; /* for future error messages */
4457  }
4458 
4459  oldfilename = pset.inputfile;
4461 
4463 
4464  result = MainLoop(fd);
4465 
4466  if (fd != stdin)
4467  fclose(fd);
4468 
4469  pset.inputfile = oldfilename;
4470 
4472 
4473  return result;
4474 }
void pg_logging_config(int new_flags)
Definition: logging.c:166
#define PG_LOG_FLAG_TERSE
Definition: logging.h:86
int MainLoop(FILE *source)
Definition: mainloop.c:33
static char * filename
Definition: pg_dumpall.c:119
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:220
#define is_absolute_path(filename)
Definition: port.h:103
void get_parent_directory(char *path)
Definition: path.c:991
bool has_drive_prefix(const char *path)
Definition: path.c:89
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define relpath(rlocator, forknum)
Definition: relpath.h:102
#define EXIT_FAILURE
Definition: settings.h:178

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

Referenced by exec_command_include().

◆ prompt_for_password()

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

Definition at line 3369 of file command.c.

3370 {
3371  char *result;
3372  PromptInterruptContext prompt_ctx;
3373 
3374  /* Set up to let SIGINT cancel simple_prompt_extended() */
3375  prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3376  prompt_ctx.enabled = &sigint_interrupt_enabled;
3377  prompt_ctx.canceled = false;
3378 
3379  if (username == NULL || username[0] == '\0')
3380  result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3381  else
3382  {
3383  char *prompt_text;
3384 
3385  prompt_text = psprintf(_("Password for user %s: "), username);
3386  result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3387  free(prompt_text);
3388  }
3389 
3390  if (canceled)
3391  *canceled = prompt_ctx.canceled;
3392 
3393  return result;
3394 }
static char * username
Definition: initdb.c:153

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

Referenced by do_connect().

◆ pset_bool_string()

static const char* pset_bool_string ( bool  val)
static

Definition at line 5180 of file command.c.

5181 {
5182  return val ? "on" : "off";
5183 }

References val.

Referenced by pset_value_string().

◆ pset_quoted_string()

static char* pset_quoted_string ( const char *  str)
static

Definition at line 5187 of file command.c.

5188 {
5189  char *ret = pg_malloc(strlen(str) * 2 + 3);
5190  char *r = ret;
5191 
5192  *r++ = '\'';
5193 
5194  for (; *str; str++)
5195  {
5196  if (*str == '\n')
5197  {
5198  *r++ = '\\';
5199  *r++ = 'n';
5200  }
5201  else if (*str == '\'')
5202  {
5203  *r++ = '\\';
5204  *r++ = '\'';
5205  }
5206  else
5207  *r++ = *str;
5208  }
5209 
5210  *r++ = '\'';
5211  *r = '\0';
5212 
5213  return ret;
5214 }
const char * str

References pg_malloc(), and str.

Referenced by pset_value_string().

◆ pset_value_string()

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

Definition at line 5225 of file command.c.

5226 {
5227  Assert(param != NULL);
5228 
5229  if (strcmp(param, "border") == 0)
5230  return psprintf("%d", popt->topt.border);
5231  else if (strcmp(param, "columns") == 0)
5232  return psprintf("%d", popt->topt.columns);
5233  else if (strcmp(param, "csv_fieldsep") == 0)
5234  return pset_quoted_string(popt->topt.csvFieldSep);
5235  else if (strcmp(param, "expanded") == 0)
5236  return pstrdup(popt->topt.expanded == 2
5237  ? "auto"
5238  : pset_bool_string(popt->topt.expanded));
5239  else if (strcmp(param, "fieldsep") == 0)
5241  ? popt->topt.fieldSep.separator
5242  : "");
5243  else if (strcmp(param, "fieldsep_zero") == 0)
5245  else if (strcmp(param, "footer") == 0)
5247  else if (strcmp(param, "format") == 0)
5248  return pstrdup(_align2string(popt->topt.format));
5249  else if (strcmp(param, "linestyle") == 0)
5250  return pstrdup(get_line_style(&popt->topt)->name);
5251  else if (strcmp(param, "null") == 0)
5252  return pset_quoted_string(popt->nullPrint
5253  ? popt->nullPrint
5254  : "");
5255  else if (strcmp(param, "numericlocale") == 0)
5256  return pstrdup(pset_bool_string(popt->topt.numericLocale));
5257  else if (strcmp(param, "pager") == 0)
5258  return psprintf("%d", popt->topt.pager);
5259  else if (strcmp(param, "pager_min_lines") == 0)
5260  return psprintf("%d", popt->topt.pager_min_lines);
5261  else if (strcmp(param, "recordsep") == 0)
5263  ? popt->topt.recordSep.separator
5264  : "");
5265  else if (strcmp(param, "recordsep_zero") == 0)
5267  else if (strcmp(param, "tableattr") == 0)
5268  return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5269  else if (strcmp(param, "title") == 0)
5270  return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5271  else if (strcmp(param, "tuples_only") == 0)
5272  return pstrdup(pset_bool_string(popt->topt.tuples_only));
5273  else if (strcmp(param, "unicode_border_linestyle") == 0)
5275  else if (strcmp(param, "unicode_column_linestyle") == 0)
5277  else if (strcmp(param, "unicode_header_linestyle") == 0)
5279  else if (strcmp(param, "xheader_width") == 0)
5280  {
5282  return pstrdup("full");
5284  return pstrdup("column");
5286  return pstrdup("page");
5287  else
5288  {
5289  /* must be PRINT_XHEADER_EXACT_WIDTH */
5290  char wbuff[32];
5291 
5292  snprintf(wbuff, sizeof(wbuff), "%d",
5294  return pstrdup(wbuff);
5295  }
5296  }
5297  else
5298  return pstrdup("ERROR");
5299 }
static char * pset_quoted_string(const char *str)
Definition: command.c:5187
static const char * pset_bool_string(bool val)
Definition: command.c:5180
char * pstrdup(const char *in)
Definition: mcxt.c:1696

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

Referenced by exec_command_pset().

◆ read_connect_arg()

static char * read_connect_arg ( PsqlScanState  scan_state)
static

Definition at line 3137 of file command.c.

3138 {
3139  char *result;
3140  char quote;
3141 
3142  /*
3143  * Ideally we should treat the arguments as SQL identifiers. But for
3144  * backwards compatibility with 7.2 and older pg_dump files, we have to
3145  * take unquoted arguments verbatim (don't downcase them). For now,
3146  * double-quoted arguments may be stripped of double quotes (as if SQL
3147  * identifiers). By 7.4 or so, pg_dump files can be expected to
3148  * double-quote all mixed-case \connect arguments, and then we can get rid
3149  * of OT_SQLIDHACK.
3150  */
3151  result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
3152 
3153  if (!result)
3154  return NULL;
3155 
3156  if (quote)
3157  return result;
3158 
3159  if (*result == '\0' || strcmp(result, "-") == 0)
3160  {
3161  free(result);
3162  return NULL;
3163  }
3164 
3165  return result;
3166 }
@ OT_SQLIDHACK
Definition: psqlscanslash.h:19

References free, OT_SQLIDHACK, and psql_scan_slash_option().

Referenced by exec_command_connect().

◆ restorePsetInfo()

void restorePsetInfo ( printQueryOpt popt,
printQueryOpt save 
)

Definition at line 5154 of file command.c.

5155 {
5156  /* Free all the old data we're about to overwrite the pointers to. */
5157 
5158  /* topt.line_style points to const data that need not be duplicated */
5159  free(popt->topt.fieldSep.separator);
5160  free(popt->topt.recordSep.separator);
5161  free(popt->topt.tableAttr);
5162  free(popt->nullPrint);
5163  free(popt->title);
5164 
5165  /*
5166  * footers and translate_columns are never set in psql's print settings,
5167  * so we needn't write code to duplicate them.
5168  */
5169  Assert(popt->footers == NULL);
5170  Assert(popt->translate_columns == NULL);
5171 
5172  /* Now we may flat-copy all the fields, including pointers. */
5173  memcpy(popt, save, sizeof(printQueryOpt));
5174 
5175  /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5176  free(save);
5177 }
const bool * translate_columns
Definition: print.h:190
char ** footers
Definition: print.h:188

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

Referenced by process_command_g_options(), and SendQuery().

◆ save_query_text_state()

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

Definition at line 3305 of file command.c.

3307 {
3308  if (query_buf)
3309  conditional_stack_set_query_len(cstack, query_buf->len);
3311  psql_scan_get_paren_depth(scan_state));
3312 }
void conditional_stack_set_paren_depth(ConditionalStack cstack, int depth)
Definition: conditional.c:173
void conditional_stack_set_query_len(ConditionalStack cstack, int len)
Definition: conditional.c:151
int psql_scan_get_paren_depth(PsqlScanState state)

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

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

◆ savePsetInfo()

printQueryOpt* savePsetInfo ( const printQueryOpt popt)

Definition at line 5118 of file command.c.

5119 {
5120  printQueryOpt *save;
5121 
5122  save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
5123 
5124  /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5125  memcpy(save, popt, sizeof(printQueryOpt));
5126 
5127  /* topt.line_style points to const data that need not be duplicated */
5128  if (popt->topt.fieldSep.separator)
5130  if (popt->topt.recordSep.separator)
5132  if (popt->topt.tableAttr)
5133  save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5134  if (popt->nullPrint)
5135  save->nullPrint = pg_strdup(popt->nullPrint);
5136  if (popt->title)
5137  save->title = pg_strdup(popt->title);
5138 
5139  /*
5140  * footers and translate_columns are never set in psql's print settings,
5141  * so we needn't write code to duplicate them.
5142  */
5143  Assert(popt->footers == NULL);
5144  Assert(popt->translate_columns == NULL);
5145 
5146  return save;
5147 }

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

Referenced by exec_command_g(), and process_command_g_options().

◆ set_unicode_line_style()

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

Definition at line 4522 of file command.c.

4524 {
4525  if (pg_strncasecmp("single", value, vallen) == 0)
4526  *linestyle = UNICODE_LINESTYLE_SINGLE;
4527  else if (pg_strncasecmp("double", value, vallen) == 0)
4528  *linestyle = UNICODE_LINESTYLE_DOUBLE;
4529  else
4530  return false;
4531  return true;
4532 }

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

Referenced by do_pset().

◆ strip_lineno_from_objdesc()

static int strip_lineno_from_objdesc ( char *  obj)
static

Definition at line 5858 of file command.c.

5859 {
5860  char *c;
5861  int lineno;
5862 
5863  if (!obj || obj[0] == '\0')
5864  return -1;
5865 
5866  c = obj + strlen(obj) - 1;
5867 
5868  /*
5869  * This business of parsing backwards is dangerous as can be in a
5870  * multibyte environment: there is no reason to believe that we are
5871  * looking at the first byte of a character, nor are we necessarily
5872  * working in a "safe" encoding. Fortunately the bitpatterns we are
5873  * looking for are unlikely to occur as non-first bytes, but beware of
5874  * trying to expand the set of cases that can be recognized. We must
5875  * guard the <ctype.h> macros by using isascii() first, too.
5876  */
5877 
5878  /* skip trailing whitespace */
5879  while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
5880  c--;
5881 
5882  /* must have a digit as last non-space char */
5883  if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
5884  return -1;
5885 
5886  /* find start of digit string */
5887  while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
5888  c--;
5889 
5890  /* digits must be separated from object name by space or closing paren */
5891  /* notice also that we are not allowing an empty object name ... */
5892  if (c == obj || !isascii((unsigned char) *c) ||
5893  !(isspace((unsigned char) *c) || *c == ')'))
5894  return -1;
5895 
5896  /* parse digit string */
5897  c++;
5898  lineno = atoi(c);
5899  if (lineno < 1)
5900  {
5901  pg_log_error("invalid line number: %s", c);
5902  return 0;
5903  }
5904 
5905  /* strip digit string from object name */
5906  *c = '\0';
5907 
5908  return lineno;
5909 }
char * c

References pg_log_error.

Referenced by exec_command_ef_ev().

◆ SyncVariables()

void SyncVariables ( void  )

Definition at line 4074 of file command.c.

4075 {
4076  char vbuf[32];
4077  const char *server_version;
4078 
4079  /* get stuff from connection */
4083 
4084  SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4085  SetVariable(pset.vars, "USER", PQuser(pset.db));
4086  SetVariable(pset.vars, "HOST", PQhost(pset.db));
4087  SetVariable(pset.vars, "PORT", PQport(pset.db));
4089 
4090  /* this bit should match connection_warnings(): */
4091  /* Try to get full text form of version, might include "devel" etc */
4092  server_version = PQparameterStatus(pset.db, "server_version");
4093  /* Otherwise fall back on pset.sversion */
4094  if (!server_version)
4095  {
4096  formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4097  server_version = vbuf;
4098  }
4099  SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4100 
4101  snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4102  SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4103 
4104  /* send stuff to it, too */
4107 }
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7190
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7350
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7338
PGVerbosity verbosity
Definition: settings.h:165
PGContextVisibility show_context
Definition: settings.h:167

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

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

◆ UnsyncVariables()

void UnsyncVariables ( void  )

Definition at line 4115 of file command.c.

4116 {
4117  SetVariable(pset.vars, "DBNAME", NULL);
4118  SetVariable(pset.vars, "USER", NULL);
4119  SetVariable(pset.vars, "HOST", NULL);
4120  SetVariable(pset.vars, "PORT", NULL);
4121  SetVariable(pset.vars, "ENCODING", NULL);
4122  SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4123  SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
4124 }

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

Referenced by CheckConnection(), and do_connect().

◆ wait_until_connected()

static void wait_until_connected ( PGconn conn)
static

Definition at line 3884 of file command.c.

3885 {
3886  bool forRead = false;
3887 
3888  while (true)
3889  {
3890  int rc;
3891  int sock;
3893 
3894  /*
3895  * On every iteration of the connection sequence, let's check if the
3896  * user has requested a cancellation.
3897  */
3898  if (cancel_pressed)
3899  break;
3900 
3901  /*
3902  * Do not assume that the socket remains the same across
3903  * PQconnectPoll() calls.
3904  */
3905  sock = PQsocket(conn);
3906  if (sock == -1)
3907  break;
3908 
3909  /*
3910  * If the user sends SIGINT between the cancel_pressed check, and
3911  * polling of the socket, it will not be recognized. Instead, we will
3912  * just wait until the next step in the connection sequence or
3913  * forever, which might require users to send SIGTERM or SIGQUIT.
3914  *
3915  * Some solutions would include the "self-pipe trick," using
3916  * pselect(2) and ppoll(2), or using a timeout.
3917  *
3918  * The self-pipe trick requires a bit of code to setup. pselect(2) and
3919  * ppoll(2) are not on all the platforms we support. The simplest
3920  * solution happens to just be adding a timeout, so let's wait for 1
3921  * second and check cancel_pressed again.
3922  */
3923  end_time = PQgetCurrentTimeUSec() + 1000000;
3924  rc = PQsocketPoll(sock, forRead, !forRead, end_time);
3925  if (rc == -1)
3926  return;
3927 
3928  switch (PQconnectPoll(conn))
3929  {
3930  case PGRES_POLLING_OK:
3931  case PGRES_POLLING_FAILED:
3932  return;
3933  case PGRES_POLLING_READING:
3934  forRead = true;
3935  continue;
3936  case PGRES_POLLING_WRITING:
3937  forRead = false;
3938  continue;
3939  case PGRES_POLLING_ACTIVE:
3940  pg_unreachable();
3941  }
3942  }
3943 }
#define pg_unreachable()
Definition: c.h:311
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2597
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7226
int PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time)
Definition: fe-misc.c:1106
pg_usec_time_t PQgetCurrentTimeUSec(void)
Definition: fe-misc.c:1200
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:114
@ PGRES_POLLING_OK
Definition: libpq-fe.h:113
@ PGRES_POLLING_READING
Definition: libpq-fe.h:111
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:112
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:110
pg_int64 pg_usec_time_t
Definition: libpq-fe.h:226
static int64 end_time
Definition: pgbench.c:175
PGconn * conn
Definition: streamutil.c:53

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

Referenced by do_connect().