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_endpipeline (PsqlScanState scan_state, bool active_branch)
 
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_flush (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_flushrequest (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_getresults (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_sendpipeline (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_startpipeline (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_syncpipeline (PsqlScanState scan_state, bool active_branch)
 
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 5710 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 4885 of file command.c.

4886{
4887 switch (in)
4888 {
4889 case PRINT_NOTHING:
4890 return "nothing";
4891 break;
4892 case PRINT_ALIGNED:
4893 return "aligned";
4894 break;
4895 case PRINT_ASCIIDOC:
4896 return "asciidoc";
4897 break;
4898 case PRINT_CSV:
4899 return "csv";
4900 break;
4901 case PRINT_HTML:
4902 return "html";
4903 break;
4904 case PRINT_LATEX:
4905 return "latex";
4906 break;
4908 return "latex-longtable";
4909 break;
4910 case PRINT_TROFF_MS:
4911 return "troff-ms";
4912 break;
4913 case PRINT_UNALIGNED:
4914 return "unaligned";
4915 break;
4916 case PRINT_WRAPPED:
4917 return "wrapped";
4918 break;
4919 }
4920 return "unknown";
4921}
@ 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 4941 of file command.c.

4942{
4943 switch (linestyle)
4944 {
4946 return "single";
4947 break;
4949 return "double";
4950 break;
4951 }
4952 return "unknown";
4953}
@ 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 4348 of file command.c.

4349{
4350 if (!pset.quiet && !pset.notty)
4351 {
4352 int client_ver = PG_VERSION_NUM;
4353 char cverbuf[32];
4354 char sverbuf[32];
4355
4356 if (pset.sversion != client_ver)
4357 {
4358 const char *server_version;
4359
4360 /* Try to get full text form, might include "devel" etc */
4361 server_version = PQparameterStatus(pset.db, "server_version");
4362 /* Otherwise fall back on pset.sversion */
4363 if (!server_version)
4364 {
4366 sverbuf, sizeof(sverbuf));
4367 server_version = sverbuf;
4368 }
4369
4370 printf(_("%s (%s, server %s)\n"),
4371 pset.progname, PG_VERSION, server_version);
4372 }
4373 /* For version match, only print psql banner on startup. */
4374 else if (in_startup)
4375 printf("%s (%s)\n", pset.progname, PG_VERSION);
4376
4377 /*
4378 * Warn if server's major version is newer than ours, or if server
4379 * predates our support cutoff (currently 9.2).
4380 */
4381 if (pset.sversion / 100 > client_ver / 100 ||
4382 pset.sversion < 90200)
4383 printf(_("WARNING: %s major version %s, server major version %s.\n"
4384 " Some psql features might not work.\n"),
4385 pset.progname,
4386 formatPGVersionNumber(client_ver, false,
4387 cverbuf, sizeof(cverbuf)),
4389 sverbuf, sizeof(sverbuf)));
4390
4391#ifdef WIN32
4392 if (in_startup)
4393 checkWin32Codepage();
4394#endif
4395 printSSLInfo();
4396 printGSSInfo();
4397 }
4398}
static void printSSLInfo(void)
Definition: command.c:4407
static void printGSSInfo(void)
Definition: command.c:4435
#define _(x)
Definition: elog.c:90
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7508
static int server_version
Definition: pg_dumpall.c:117
#define printf(...)
Definition: port.h:245
PsqlSettings pset
Definition: startup.c:32
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:313
PGconn * db
Definition: settings.h:103
const char * progname
Definition: settings.h:142

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

3754{
3755 if (query_buf && query_buf->len == 0)
3756 {
3757 appendPQExpBufferStr(query_buf, previous_buf->data);
3758 return true;
3759 }
3760 return false;
3761}
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 6322 of file command.c.

6323{
6324 int lineno = 0;
6325 const char *lines = buf->data;
6326
6327 while (*lines != '\0')
6328 {
6329 lineno++;
6330 /* find start of next line */
6331 lines = strchr(lines, '\n');
6332 if (!lines)
6333 break;
6334 lines++;
6335 }
6336
6337 return lineno;
6338}
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 3727 of file command.c.

3729{
3730 if (query_buf)
3731 {
3732 int new_len = conditional_stack_get_query_len(cstack);
3733
3734 Assert(new_len >= 0 && new_len <= query_buf->len);
3735 query_buf->len = new_len;
3736 query_buf->data[new_len] = '\0';
3737 }
3738 psql_scan_set_paren_depth(scan_state,
3740}
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:162
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:184
Assert(PointerIsAligned(start, uint64))
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 3822 of file command.c.

3824{
3825 PGconn *o_conn = pset.db,
3826 *n_conn = NULL;
3827 PQconninfoOption *cinfo;
3828 int nconnopts = 0;
3829 bool same_host = false;
3830 char *password = NULL;
3831 char *client_encoding;
3832 bool success = true;
3833 bool keep_password = true;
3834 bool has_connection_string;
3835 bool reuse_previous;
3836
3837 has_connection_string = dbname ?
3839
3840 /* Complain if we have additional arguments after a connection string. */
3841 if (has_connection_string && (user || host || port))
3842 {
3843 pg_log_error("Do not give user, host, or port separately when using a connection string");
3844 return false;
3845 }
3846
3847 switch (reuse_previous_specification)
3848 {
3849 case TRI_YES:
3850 reuse_previous = true;
3851 break;
3852 case TRI_NO:
3853 reuse_previous = false;
3854 break;
3855 default:
3856 reuse_previous = !has_connection_string;
3857 break;
3858 }
3859
3860 /*
3861 * If we intend to re-use connection parameters, collect them out of the
3862 * old connection, then replace individual values as necessary. (We may
3863 * need to resort to looking at pset.dead_conn, if the connection died
3864 * previously.) Otherwise, obtain a PQconninfoOption array containing
3865 * libpq's defaults, and modify that. Note this function assumes that
3866 * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3867 * containing the same options in the same order.
3868 */
3869 if (reuse_previous)
3870 {
3871 if (o_conn)
3872 cinfo = PQconninfo(o_conn);
3873 else if (pset.dead_conn)
3874 cinfo = PQconninfo(pset.dead_conn);
3875 else
3876 {
3877 /* This is reachable after a non-interactive \connect failure */
3878 pg_log_error("No database connection exists to re-use parameters from");
3879 return false;
3880 }
3881 }
3882 else
3883 cinfo = PQconndefaults();
3884
3885 if (cinfo)
3886 {
3887 if (has_connection_string)
3888 {
3889 /* Parse the connstring and insert values into cinfo */
3890 PQconninfoOption *replcinfo;
3891 char *errmsg;
3892
3893 replcinfo = PQconninfoParse(dbname, &errmsg);
3894 if (replcinfo)
3895 {
3896 PQconninfoOption *ci;
3897 PQconninfoOption *replci;
3898 bool have_password = false;
3899
3900 for (ci = cinfo, replci = replcinfo;
3901 ci->keyword && replci->keyword;
3902 ci++, replci++)
3903 {
3904 Assert(strcmp(ci->keyword, replci->keyword) == 0);
3905 /* Insert value from connstring if one was provided */
3906 if (replci->val)
3907 {
3908 /*
3909 * We know that both val strings were allocated by
3910 * libpq, so the least messy way to avoid memory leaks
3911 * is to swap them.
3912 */
3913 char *swap = replci->val;
3914
3915 replci->val = ci->val;
3916 ci->val = swap;
3917
3918 /*
3919 * Check whether connstring provides options affecting
3920 * password re-use. While any change in user, host,
3921 * hostaddr, or port causes us to ignore the old
3922 * connection's password, we don't force that for
3923 * dbname, since passwords aren't database-specific.
3924 */
3925 if (replci->val == NULL ||
3926 strcmp(ci->val, replci->val) != 0)
3927 {
3928 if (strcmp(replci->keyword, "user") == 0 ||
3929 strcmp(replci->keyword, "host") == 0 ||
3930 strcmp(replci->keyword, "hostaddr") == 0 ||
3931 strcmp(replci->keyword, "port") == 0)
3932 keep_password = false;
3933 }
3934 /* Also note whether connstring contains a password. */
3935 if (strcmp(replci->keyword, "password") == 0)
3936 have_password = true;
3937 }
3938 else if (!reuse_previous)
3939 {
3940 /*
3941 * When we have a connstring and are not re-using
3942 * parameters, swap *all* entries, even those not set
3943 * by the connstring. This avoids absorbing
3944 * environment-dependent defaults from the result of
3945 * PQconndefaults(). We don't want to do that because
3946 * they'd override service-file entries if the
3947 * connstring specifies a service parameter, whereas
3948 * the priority should be the other way around. libpq
3949 * can certainly recompute any defaults we don't pass
3950 * here. (In this situation, it's a bit wasteful to
3951 * have called PQconndefaults() at all, but not doing
3952 * so would require yet another major code path here.)
3953 */
3954 replci->val = ci->val;
3955 ci->val = NULL;
3956 }
3957 }
3958 Assert(ci->keyword == NULL && replci->keyword == NULL);
3959
3960 /* While here, determine how many option slots there are */
3961 nconnopts = ci - cinfo;
3962
3963 PQconninfoFree(replcinfo);
3964
3965 /*
3966 * If the connstring contains a password, tell the loop below
3967 * that we may use it, regardless of other settings (i.e.,
3968 * cinfo's password is no longer an "old" password).
3969 */
3970 if (have_password)
3971 keep_password = true;
3972
3973 /* Don't let code below try to inject dbname into params. */
3974 dbname = NULL;
3975 }
3976 else
3977 {
3978 /* PQconninfoParse failed */
3979 if (errmsg)
3980 {
3981 pg_log_error("%s", errmsg);
3983 }
3984 else
3985 pg_log_error("out of memory");
3986 success = false;
3987 }
3988 }
3989 else
3990 {
3991 /*
3992 * If dbname isn't a connection string, then we'll inject it and
3993 * the other parameters into the keyword array below. (We can't
3994 * easily insert them into the cinfo array because of memory
3995 * management issues: PQconninfoFree would misbehave on Windows.)
3996 * However, to avoid dependencies on the order in which parameters
3997 * appear in the array, make a preliminary scan to set
3998 * keep_password and same_host correctly.
3999 *
4000 * While any change in user, host, or port causes us to ignore the
4001 * old connection's password, we don't force that for dbname,
4002 * since passwords aren't database-specific.
4003 */
4004 PQconninfoOption *ci;
4005
4006 for (ci = cinfo; ci->keyword; ci++)
4007 {
4008 if (user && strcmp(ci->keyword, "user") == 0)
4009 {
4010 if (!(ci->val && strcmp(user, ci->val) == 0))
4011 keep_password = false;
4012 }
4013 else if (host && strcmp(ci->keyword, "host") == 0)
4014 {
4015 if (ci->val && strcmp(host, ci->val) == 0)
4016 same_host = true;
4017 else
4018 keep_password = false;
4019 }
4020 else if (port && strcmp(ci->keyword, "port") == 0)
4021 {
4022 if (!(ci->val && strcmp(port, ci->val) == 0))
4023 keep_password = false;
4024 }
4025 }
4026
4027 /* While here, determine how many option slots there are */
4028 nconnopts = ci - cinfo;
4029 }
4030 }
4031 else
4032 {
4033 /* We failed to create the cinfo structure */
4034 pg_log_error("out of memory");
4035 success = false;
4036 }
4037
4038 /*
4039 * If the user asked to be prompted for a password, ask for one now. If
4040 * not, use the password from the old connection, provided the username
4041 * etc have not changed. Otherwise, try to connect without a password
4042 * first, and then ask for a password if needed.
4043 *
4044 * XXX: this behavior leads to spurious connection attempts recorded in
4045 * the postmaster's log. But libpq offers no API that would let us obtain
4046 * a password and then continue with the first connection attempt.
4047 */
4048 if (pset.getPassword == TRI_YES && success)
4049 {
4050 bool canceled = false;
4051
4052 /*
4053 * If a connstring or URI is provided, we don't know which username
4054 * will be used, since we haven't dug that out of the connstring.
4055 * Don't risk issuing a misleading prompt. As in startup.c, it does
4056 * not seem worth working harder, since this getPassword setting is
4057 * normally only used in noninteractive cases.
4058 */
4059 password = prompt_for_password(has_connection_string ? NULL : user,
4060 &canceled);
4061 success = !canceled;
4062 }
4063
4064 /*
4065 * Consider whether to force client_encoding to "auto" (overriding
4066 * anything in the connection string). We do so if we have a terminal
4067 * connection and there is no PGCLIENTENCODING environment setting.
4068 */
4069 if (pset.notty || getenv("PGCLIENTENCODING"))
4070 client_encoding = NULL;
4071 else
4072 client_encoding = "auto";
4073
4074 /* Loop till we have a connection or fail, which we might've already */
4075 while (success)
4076 {
4077 const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
4078 const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
4079 int paramnum = 0;
4080 PQconninfoOption *ci;
4081
4082 /*
4083 * Copy non-default settings into the PQconnectdbParams parameter
4084 * arrays; but inject any values specified old-style, as well as any
4085 * interactively-obtained password, and a couple of fields we want to
4086 * set forcibly.
4087 *
4088 * If you change this code, see also the initial-connection code in
4089 * main().
4090 */
4091 for (ci = cinfo; ci->keyword; ci++)
4092 {
4093 keywords[paramnum] = ci->keyword;
4094
4095 if (dbname && strcmp(ci->keyword, "dbname") == 0)
4096 values[paramnum++] = dbname;
4097 else if (user && strcmp(ci->keyword, "user") == 0)
4098 values[paramnum++] = user;
4099 else if (host && strcmp(ci->keyword, "host") == 0)
4100 values[paramnum++] = host;
4101 else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
4102 {
4103 /* If we're changing the host value, drop any old hostaddr */
4104 values[paramnum++] = NULL;
4105 }
4106 else if (port && strcmp(ci->keyword, "port") == 0)
4107 values[paramnum++] = port;
4108 /* If !keep_password, we unconditionally drop old password */
4109 else if ((password || !keep_password) &&
4110 strcmp(ci->keyword, "password") == 0)
4111 values[paramnum++] = password;
4112 else if (strcmp(ci->keyword, "fallback_application_name") == 0)
4113 values[paramnum++] = pset.progname;
4114 else if (client_encoding &&
4115 strcmp(ci->keyword, "client_encoding") == 0)
4116 values[paramnum++] = client_encoding;
4117 else if (ci->val)
4118 values[paramnum++] = ci->val;
4119 /* else, don't bother making libpq parse this keyword */
4120 }
4121 /* add array terminator */
4122 keywords[paramnum] = NULL;
4123 values[paramnum] = NULL;
4124
4125 /* Note we do not want libpq to re-expand the dbname parameter */
4126 n_conn = PQconnectStartParams(keywords, values, false);
4127
4129 pg_free(values);
4130
4131 wait_until_connected(n_conn);
4132 if (PQstatus(n_conn) == CONNECTION_OK)
4133 break;
4134
4135 /*
4136 * Connection attempt failed; either retry the connection attempt with
4137 * a new password, or give up.
4138 */
4140 {
4141 bool canceled = false;
4142
4143 /*
4144 * Prompt for password using the username we actually connected
4145 * with --- it might've come out of "dbname" rather than "user".
4146 */
4147 password = prompt_for_password(PQuser(n_conn), &canceled);
4148 PQfinish(n_conn);
4149 n_conn = NULL;
4150 success = !canceled;
4151 continue;
4152 }
4153
4154 /*
4155 * We'll report the error below ... unless n_conn is NULL, indicating
4156 * that libpq didn't have enough memory to make a PGconn.
4157 */
4158 if (n_conn == NULL)
4159 pg_log_error("out of memory");
4160
4161 success = false;
4162 } /* end retry loop */
4163
4164 /* Release locally allocated data, whether we succeeded or not */
4166 PQconninfoFree(cinfo);
4167
4168 if (!success)
4169 {
4170 /*
4171 * Failed to connect to the database. In interactive mode, keep the
4172 * previous connection to the DB; in scripting mode, close our
4173 * previous connection as well.
4174 */
4176 {
4177 if (n_conn)
4178 {
4179 pg_log_info("%s", PQerrorMessage(n_conn));
4180 PQfinish(n_conn);
4181 }
4182
4183 /* pset.db is left unmodified */
4184 if (o_conn)
4185 pg_log_info("Previous connection kept");
4186 }
4187 else
4188 {
4189 if (n_conn)
4190 {
4191 pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
4192 PQfinish(n_conn);
4193 }
4194
4195 if (o_conn)
4196 {
4197 /*
4198 * Transition to having no connection.
4199 *
4200 * Unlike CheckConnection(), we close the old connection
4201 * immediately to prevent its parameters from being re-used.
4202 * This is so that a script cannot accidentally reuse
4203 * parameters it did not expect to. Otherwise, the state
4204 * cleanup should be the same as in CheckConnection().
4205 */
4206 PQfinish(o_conn);
4207 pset.db = NULL;
4210 }
4211
4212 /* On the same reasoning, release any dead_conn to prevent reuse */
4213 if (pset.dead_conn)
4214 {
4216 pset.dead_conn = NULL;
4217 }
4218 }
4219
4220 return false;
4221 }
4222
4223 /*
4224 * Replace the old connection with the new one, and update
4225 * connection-dependent variables. Keep the resynchronization logic in
4226 * sync with CheckConnection().
4227 */
4229 pset.db = n_conn;
4230 SyncVariables();
4231 connection_warnings(false); /* Must be after SyncVariables */
4232
4233 /* Tell the user about the new connection */
4234 if (!pset.quiet)
4235 {
4236 if (!o_conn ||
4237 param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
4239 {
4240 char *connhost = PQhost(pset.db);
4241 char *hostaddr = PQhostaddr(pset.db);
4242
4243 if (is_unixsock_path(connhost))
4244 {
4245 /* hostaddr overrides connhost */
4246 if (hostaddr && *hostaddr)
4247 printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
4248 PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
4249 else
4250 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
4251 PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4252 }
4253 else
4254 {
4255 if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
4256 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
4257 PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
4258 else
4259 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
4260 PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4261 }
4262 }
4263 else
4264 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
4265 PQdb(pset.db), PQuser(pset.db));
4266 }
4267
4268 /* Drop no-longer-needed connection(s) */
4269 if (o_conn)
4270 PQfinish(o_conn);
4271 if (pset.dead_conn)
4272 {
4274 pset.dead_conn = NULL;
4275 }
4276
4277 return true;
4278}
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:279
bool recognized_connection_string(const char *connstr)
Definition: common.c:2625
static Datum values[MAXATTR]
Definition: bootstrap.c:151
void ResetCancelConn(void)
Definition: cancel.c:107
static bool param_is_newly_set(const char *old_val, const char *new_val)
Definition: command.c:3799
void UnsyncVariables(void)
Definition: command.c:4520
static void wait_until_connected(PGconn *conn)
Definition: command.c:4286
void SyncVariables(void)
Definition: command.c:4476
void connection_warnings(bool in_startup)
Definition: command.c:4348
static char * prompt_for_password(const char *username, bool *canceled)
Definition: command.c:3771
int errmsg(const char *fmt,...)
Definition: elog.c:1070
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:7381
char * PQport(const PGconn *conn)
Definition: fe-connect.c:7458
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:7422
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:7324
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7368
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:6084
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7606
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7490
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:839
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5224
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:7445
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:2127
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:7397
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7734
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7553
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void pg_free(void *ptr)
Definition: fe_memutils.c:105
static bool success
Definition: initdb.c:187
return false
Definition: isn.c:132
static const JsonPathKeyword keywords[]
@ CONNECTION_OK
Definition: libpq-fe.h:84
#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:51
char * dbname
Definition: streamutil.c:49
PGconn * dead_conn
Definition: settings.h:158
enum trivalue getPassword
Definition: settings.h:137
bool cur_cmd_interactive
Definition: settings.h:140
@ 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, keywords, 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 4623 of file command.c.

4625{
4626 char fnametmp[MAXPGPATH];
4627 FILE *stream = NULL;
4628 const char *fname;
4629 bool error = false;
4630 int fd;
4631 struct stat before,
4632 after;
4633
4634 if (filename_arg)
4635 fname = filename_arg;
4636 else
4637 {
4638 /* make a temp file to edit */
4639#ifndef WIN32
4640 const char *tmpdir = getenv("TMPDIR");
4641
4642 if (!tmpdir)
4643 tmpdir = "/tmp";
4644#else
4645 char tmpdir[MAXPGPATH];
4646 int ret;
4647
4648 ret = GetTempPath(MAXPGPATH, tmpdir);
4649 if (ret == 0 || ret > MAXPGPATH)
4650 {
4651 pg_log_error("could not locate temporary directory: %s",
4652 !ret ? strerror(errno) : "");
4653 return false;
4654 }
4655#endif
4656
4657 /*
4658 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4659 * current directory to the supplied path unless we use only
4660 * backslashes, so we do that.
4661 */
4662#ifndef WIN32
4663 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4664 "/", (int) getpid());
4665#else
4666 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4667 "" /* trailing separator already present */ , (int) getpid());
4668#endif
4669
4670 fname = (const char *) fnametmp;
4671
4672 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4673 if (fd != -1)
4674 stream = fdopen(fd, "w");
4675
4676 if (fd == -1 || !stream)
4677 {
4678 pg_log_error("could not open temporary file \"%s\": %m", fname);
4679 error = true;
4680 }
4681 else
4682 {
4683 unsigned int ql = query_buf->len;
4684
4685 /* force newline-termination of what we send to editor */
4686 if (ql > 0 && query_buf->data[ql - 1] != '\n')
4687 {
4688 appendPQExpBufferChar(query_buf, '\n');
4689 ql++;
4690 }
4691
4692 if (fwrite(query_buf->data, 1, ql, stream) != ql)
4693 {
4694 pg_log_error("%s: %m", fname);
4695
4696 if (fclose(stream) != 0)
4697 pg_log_error("%s: %m", fname);
4698
4699 if (remove(fname) != 0)
4700 pg_log_error("%s: %m", fname);
4701
4702 error = true;
4703 }
4704 else if (fclose(stream) != 0)
4705 {
4706 pg_log_error("%s: %m", fname);
4707 if (remove(fname) != 0)
4708 pg_log_error("%s: %m", fname);
4709 error = true;
4710 }
4711 else
4712 {
4713 struct utimbuf ut;
4714
4715 /*
4716 * Try to set the file modification time of the temporary file
4717 * a few seconds in the past. Otherwise, the low granularity
4718 * (one second, or even worse on some filesystems) that we can
4719 * portably measure with stat(2) could lead us to not
4720 * recognize a modification, if the user typed very quickly.
4721 *
4722 * This is a rather unlikely race condition, so don't error
4723 * out if the utime(2) call fails --- that would make the cure
4724 * worse than the disease.
4725 */
4726 ut.modtime = ut.actime = time(NULL) - 2;
4727 (void) utime(fname, &ut);
4728 }
4729 }
4730 }
4731
4732 if (!error && stat(fname, &before) != 0)
4733 {
4734 pg_log_error("%s: %m", fname);
4735 error = true;
4736 }
4737
4738 /* call editor */
4739 if (!error)
4740 error = !editFile(fname, lineno);
4741
4742 if (!error && stat(fname, &after) != 0)
4743 {
4744 pg_log_error("%s: %m", fname);
4745 error = true;
4746 }
4747
4748 /* file was edited if the size or modification time has changed */
4749 if (!error &&
4750 (before.st_size != after.st_size ||
4751 before.st_mtime != after.st_mtime))
4752 {
4753 stream = fopen(fname, PG_BINARY_R);
4754 if (!stream)
4755 {
4756 pg_log_error("%s: %m", fname);
4757 error = true;
4758 }
4759 else
4760 {
4761 /* read file back into query_buf */
4762 char line[1024];
4763
4764 resetPQExpBuffer(query_buf);
4765 while (fgets(line, sizeof(line), stream) != NULL)
4766 appendPQExpBufferStr(query_buf, line);
4767
4768 if (ferror(stream))
4769 {
4770 pg_log_error("%s: %m", fname);
4771 error = true;
4772 resetPQExpBuffer(query_buf);
4773 }
4774 else if (edited)
4775 {
4776 *edited = true;
4777 }
4778
4779 fclose(stream);
4780 }
4781 }
4782 else
4783 {
4784 /*
4785 * If the file was not modified, and the caller requested it, discard
4786 * the query buffer.
4787 */
4788 if (discard_on_quit)
4789 resetPQExpBuffer(query_buf);
4790 }
4791
4792 /* remove temp file */
4793 if (!filename_arg)
4794 {
4795 if (remove(fname) == -1)
4796 {
4797 pg_log_error("%s: %m", fname);
4798 error = true;
4799 }
4800 }
4801
4802 return !error;
4803}
#define PG_BINARY_R
Definition: c.h:1246
static bool editFile(const char *fname, int lineno)
Definition: command.c:4541
#define MAXPGPATH
#define strerror
Definition: port.h:252
#define snprintf
Definition: port.h:239
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:274

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

4972{
4973 size_t vallen = 0;
4974
4975 Assert(param != NULL);
4976
4977 if (value)
4978 vallen = strlen(value);
4979
4980 /* set format */
4981 if (strcmp(param, "format") == 0)
4982 {
4983 static const struct fmt
4984 {
4985 const char *name;
4986 enum printFormat number;
4987 } formats[] =
4988 {
4989 /* remember to update error message below when adding more */
4990 {"aligned", PRINT_ALIGNED},
4991 {"asciidoc", PRINT_ASCIIDOC},
4992 {"csv", PRINT_CSV},
4993 {"html", PRINT_HTML},
4994 {"latex", PRINT_LATEX},
4995 {"troff-ms", PRINT_TROFF_MS},
4996 {"unaligned", PRINT_UNALIGNED},
4997 {"wrapped", PRINT_WRAPPED}
4998 };
4999
5000 if (!value)
5001 ;
5002 else
5003 {
5004 int match_pos = -1;
5005
5006 for (int i = 0; i < lengthof(formats); i++)
5007 {
5008 if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
5009 {
5010 if (match_pos < 0)
5011 match_pos = i;
5012 else
5013 {
5014 pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
5015 value,
5016 formats[match_pos].name, formats[i].name);
5017 return false;
5018 }
5019 }
5020 }
5021 if (match_pos >= 0)
5022 popt->topt.format = formats[match_pos].number;
5023 else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
5024 {
5025 /*
5026 * We must treat latex-longtable specially because latex is a
5027 * prefix of it; if both were in the table above, we'd think
5028 * "latex" is ambiguous.
5029 */
5031 }
5032 else
5033 {
5034 pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
5035 return false;
5036 }
5037 }
5038 }
5039
5040 /* set table line style */
5041 else if (strcmp(param, "linestyle") == 0)
5042 {
5043 if (!value)
5044 ;
5045 else if (pg_strncasecmp("ascii", value, vallen) == 0)
5047 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
5049 else if (pg_strncasecmp("unicode", value, vallen) == 0)
5050 popt->topt.line_style = &pg_utf8format;
5051 else
5052 {
5053 pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
5054 return false;
5055 }
5056 }
5057
5058 /* set unicode border line style */
5059 else if (strcmp(param, "unicode_border_linestyle") == 0)
5060 {
5061 if (!value)
5062 ;
5063 else if (set_unicode_line_style(value, vallen,
5065 refresh_utf8format(&(popt->topt));
5066 else
5067 {
5068 pg_log_error("\\pset: allowed Unicode border line styles are single, double");
5069 return false;
5070 }
5071 }
5072
5073 /* set unicode column line style */
5074 else if (strcmp(param, "unicode_column_linestyle") == 0)
5075 {
5076 if (!value)
5077 ;
5078 else if (set_unicode_line_style(value, vallen,
5080 refresh_utf8format(&(popt->topt));
5081 else
5082 {
5083 pg_log_error("\\pset: allowed Unicode column line styles are single, double");
5084 return false;
5085 }
5086 }
5087
5088 /* set unicode header line style */
5089 else if (strcmp(param, "unicode_header_linestyle") == 0)
5090 {
5091 if (!value)
5092 ;
5093 else if (set_unicode_line_style(value, vallen,
5095 refresh_utf8format(&(popt->topt));
5096 else
5097 {
5098 pg_log_error("\\pset: allowed Unicode header line styles are single, double");
5099 return false;
5100 }
5101 }
5102
5103 /* set border style/width */
5104 else if (strcmp(param, "border") == 0)
5105 {
5106 if (value)
5107 popt->topt.border = atoi(value);
5108 }
5109
5110 /* set expanded/vertical mode */
5111 else if (strcmp(param, "x") == 0 ||
5112 strcmp(param, "expanded") == 0 ||
5113 strcmp(param, "vertical") == 0)
5114 {
5115 if (value && pg_strcasecmp(value, "auto") == 0)
5116 popt->topt.expanded = 2;
5117 else if (value)
5118 {
5119 bool on_off;
5120
5121 if (ParseVariableBool(value, NULL, &on_off))
5122 popt->topt.expanded = on_off ? 1 : 0;
5123 else
5124 {
5125 PsqlVarEnumError(param, value, "on, off, auto");
5126 return false;
5127 }
5128 }
5129 else
5130 popt->topt.expanded = !popt->topt.expanded;
5131 }
5132
5133 /* header line width in expanded mode */
5134 else if (strcmp(param, "xheader_width") == 0)
5135 {
5136 if (!value)
5137 ;
5138 else if (pg_strcasecmp(value, "full") == 0)
5140 else if (pg_strcasecmp(value, "column") == 0)
5142 else if (pg_strcasecmp(value, "page") == 0)
5144 else
5145 {
5146 int intval = atoi(value);
5147
5148 if (intval == 0)
5149 {
5150 pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
5151 return false;
5152 }
5153
5155 popt->topt.expanded_header_exact_width = intval;
5156 }
5157 }
5158
5159 /* field separator for CSV format */
5160 else if (strcmp(param, "csv_fieldsep") == 0)
5161 {
5162 if (value)
5163 {
5164 /* CSV separator has to be a one-byte character */
5165 if (strlen(value) != 1)
5166 {
5167 pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
5168 return false;
5169 }
5170 if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
5171 {
5172 pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
5173 return false;
5174 }
5175 popt->topt.csvFieldSep[0] = value[0];
5176 }
5177 }
5178
5179 /* locale-aware numeric output */
5180 else if (strcmp(param, "numericlocale") == 0)
5181 {
5182 if (value)
5183 return ParseVariableBool(value, param, &popt->topt.numericLocale);
5184 else
5185 popt->topt.numericLocale = !popt->topt.numericLocale;
5186 }
5187
5188 /* null display */
5189 else if (strcmp(param, "null") == 0)
5190 {
5191 if (value)
5192 {
5193 free(popt->nullPrint);
5194 popt->nullPrint = pg_strdup(value);
5195 }
5196 }
5197
5198 /* field separator for unaligned text */
5199 else if (strcmp(param, "fieldsep") == 0)
5200 {
5201 if (value)
5202 {
5203 free(popt->topt.fieldSep.separator);
5205 popt->topt.fieldSep.separator_zero = false;
5206 }
5207 }
5208
5209 else if (strcmp(param, "fieldsep_zero") == 0)
5210 {
5211 free(popt->topt.fieldSep.separator);
5212 popt->topt.fieldSep.separator = NULL;
5213 popt->topt.fieldSep.separator_zero = true;
5214 }
5215
5216 /* record separator for unaligned text */
5217 else if (strcmp(param, "recordsep") == 0)
5218 {
5219 if (value)
5220 {
5223 popt->topt.recordSep.separator_zero = false;
5224 }
5225 }
5226
5227 else if (strcmp(param, "recordsep_zero") == 0)
5228 {
5230 popt->topt.recordSep.separator = NULL;
5231 popt->topt.recordSep.separator_zero = true;
5232 }
5233
5234 /* toggle between full and tuples-only format */
5235 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5236 {
5237 if (value)
5238 return ParseVariableBool(value, param, &popt->topt.tuples_only);
5239 else
5240 popt->topt.tuples_only = !popt->topt.tuples_only;
5241 }
5242
5243 /* set title override */
5244 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5245 {
5246 free(popt->title);
5247 if (!value)
5248 popt->title = NULL;
5249 else
5250 popt->title = pg_strdup(value);
5251 }
5252
5253 /* set HTML table tag options */
5254 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5255 {
5256 free(popt->topt.tableAttr);
5257 if (!value)
5258 popt->topt.tableAttr = NULL;
5259 else
5260 popt->topt.tableAttr = pg_strdup(value);
5261 }
5262
5263 /* toggle use of pager */
5264 else if (strcmp(param, "pager") == 0)
5265 {
5266 if (value && pg_strcasecmp(value, "always") == 0)
5267 popt->topt.pager = 2;
5268 else if (value)
5269 {
5270 bool on_off;
5271
5272 if (!ParseVariableBool(value, NULL, &on_off))
5273 {
5274 PsqlVarEnumError(param, value, "on, off, always");
5275 return false;
5276 }
5277 popt->topt.pager = on_off ? 1 : 0;
5278 }
5279 else if (popt->topt.pager == 1)
5280 popt->topt.pager = 0;
5281 else
5282 popt->topt.pager = 1;
5283 }
5284
5285 /* set minimum lines for pager use */
5286 else if (strcmp(param, "pager_min_lines") == 0)
5287 {
5288 if (value &&
5289 !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
5290 return false;
5291 }
5292
5293 /* disable "(x rows)" footer */
5294 else if (strcmp(param, "footer") == 0)
5295 {
5296 if (value)
5297 return ParseVariableBool(value, param, &popt->topt.default_footer);
5298 else
5299 popt->topt.default_footer = !popt->topt.default_footer;
5300 }
5301
5302 /* set border style/width */
5303 else if (strcmp(param, "columns") == 0)
5304 {
5305 if (value)
5306 popt->topt.columns = atoi(value);
5307 }
5308 else
5309 {
5310 pg_log_error("\\pset: unknown option: %s", param);
5311 return false;
5312 }
5313
5314 if (!quiet)
5315 printPsetInfo(param, &pset.popt);
5316
5317 return true;
5318}
#define lengthof(array)
Definition: c.h:759
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4928
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:5324
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 @165 value
int i
Definition: isn.c:74
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:112
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:486
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:109
bool ParseVariableNum(const char *value, const char *name, int *result)
Definition: variables.c:158
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, 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 5720 of file command.c.

5721{
5722 int result;
5723
5724 fflush(NULL);
5725 if (!command)
5726 {
5727 char *sys;
5728 const char *shellName;
5729
5730 shellName = getenv("SHELL");
5731#ifdef WIN32
5732 if (shellName == NULL)
5733 shellName = getenv("COMSPEC");
5734#endif
5735 if (shellName == NULL)
5736 shellName = DEFAULT_SHELL;
5737
5738 /* See EDITOR handling comment for an explanation */
5739#ifndef WIN32
5740 sys = psprintf("exec %s", shellName);
5741#else
5742 sys = psprintf("\"%s\"", shellName);
5743#endif
5744 result = system(sys);
5745 free(sys);
5746 }
5747 else
5748 result = system(command);
5749
5751
5752 if (result == 127 || result == -1)
5753 {
5754 pg_log_error("\\!: failed");
5755 return false;
5756 }
5757 return true;
5758}
void SetShellResultVariables(int wait_result)
Definition: common.c:516
#define DEFAULT_SHELL
Definition: command.c:5710
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43

References DEFAULT_SHELL, 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 5771 of file command.c.

5772{
5773 long sleep_ms = (long) (sleep * 1000);
5774 printQueryOpt myopt = pset.popt;
5775 const char *strftime_fmt;
5776 const char *user_title;
5777 char *title;
5778 const char *pagerprog = NULL;
5779 FILE *pagerpipe = NULL;
5780 int title_len;
5781 int res = 0;
5782 bool done = false;
5783#ifndef WIN32
5784 sigset_t sigalrm_sigchld_sigint;
5785 sigset_t sigalrm_sigchld;
5786 sigset_t sigint;
5787 struct itimerval interval;
5788#endif
5789
5790 if (!query_buf || query_buf->len <= 0)
5791 {
5792 pg_log_error("\\watch cannot be used with an empty query");
5793 return false;
5794 }
5795
5796#ifndef WIN32
5797 sigemptyset(&sigalrm_sigchld_sigint);
5798 sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5799 sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5800 sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5801
5802 sigemptyset(&sigalrm_sigchld);
5803 sigaddset(&sigalrm_sigchld, SIGCHLD);
5804 sigaddset(&sigalrm_sigchld, SIGALRM);
5805
5806 sigemptyset(&sigint);
5807 sigaddset(&sigint, SIGINT);
5808
5809 /*
5810 * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5811 * configured), to avoid races. sigwait() will receive them.
5812 */
5813 sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5814
5815 /*
5816 * Set a timer to interrupt sigwait() so we can run the query at the
5817 * requested intervals.
5818 */
5819 interval.it_value.tv_sec = sleep_ms / 1000;
5820 interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5821 interval.it_interval = interval.it_value;
5822 if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5823 {
5824 pg_log_error("could not set timer: %m");
5825 done = true;
5826 }
5827#endif
5828
5829 /*
5830 * For \watch, we ignore the size of the result and always use the pager
5831 * as long as we're talking to a terminal and "\pset pager" is enabled.
5832 * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5833 * ignore the regular PSQL_PAGER or PAGER environment variables, because
5834 * traditional pagers probably won't be very useful for showing a stream
5835 * of results.
5836 */
5837#ifndef WIN32
5838 pagerprog = getenv("PSQL_WATCH_PAGER");
5839 /* if variable is empty or all-white-space, don't use pager */
5840 if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5841 pagerprog = NULL;
5842#endif
5843 if (pagerprog && myopt.topt.pager &&
5844 isatty(fileno(stdin)) && isatty(fileno(stdout)))
5845 {
5846 fflush(NULL);
5848 pagerpipe = popen(pagerprog, "w");
5849
5850 if (!pagerpipe)
5851 /* silently proceed without pager */
5853 }
5854
5855 /*
5856 * Choose format for timestamps. We might eventually make this a \pset
5857 * option. In the meantime, using a variable for the format suppresses
5858 * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5859 */
5860 strftime_fmt = "%c";
5861
5862 /*
5863 * Set up rendering options, in particular, disable the pager unless
5864 * PSQL_WATCH_PAGER was successfully launched.
5865 */
5866 if (!pagerpipe)
5867 myopt.topt.pager = 0;
5868
5869 /*
5870 * If there's a title in the user configuration, make sure we have room
5871 * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5872 * bytes for the rest.
5873 */
5874 user_title = myopt.title;
5875 title_len = (user_title ? strlen(user_title) : 0) + 256;
5876 title = pg_malloc(title_len);
5877
5878 /* Loop to run query and then sleep awhile */
5879 while (!done)
5880 {
5881 time_t timer;
5882 char timebuf[128];
5883
5884 /*
5885 * Prepare title for output. Note that we intentionally include a
5886 * newline at the end of the title; this is somewhat historical but it
5887 * makes for reasonably nicely formatted output in simple cases.
5888 */
5889 timer = time(NULL);
5890 strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5891
5892 if (user_title)
5893 snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5894 user_title, timebuf, sleep_ms / 1000.0);
5895 else
5896 snprintf(title, title_len, _("%s (every %gs)\n"),
5897 timebuf, sleep_ms / 1000.0);
5898 myopt.title = title;
5899
5900 /* Run the query and print out the result */
5901 res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
5902
5903 /*
5904 * PSQLexecWatch handles the case where we can no longer repeat the
5905 * query, and returns 0 or -1.
5906 */
5907 if (res <= 0)
5908 break;
5909
5910 /* If we have iteration count, check that it's not exceeded yet */
5911 if (iter && (--iter <= 0))
5912 break;
5913
5914 /* Quit if error on pager pipe (probably pager has quit) */
5915 if (pagerpipe && ferror(pagerpipe))
5916 break;
5917
5918 /* Tight loop, no wait needed */
5919 if (sleep_ms == 0)
5920 continue;
5921
5922#ifdef WIN32
5923
5924 /*
5925 * Wait a while before running the query again. Break the sleep into
5926 * short intervals (at most 1s); that's probably unnecessary since
5927 * pg_usleep is interruptible on Windows, but it's cheap insurance.
5928 */
5929 for (long i = sleep_ms; i > 0;)
5930 {
5931 long s = Min(i, 1000L);
5932
5933 pg_usleep(s * 1000L);
5934 if (cancel_pressed)
5935 {
5936 done = true;
5937 break;
5938 }
5939 i -= s;
5940 }
5941#else
5942 /* sigwait() will handle SIGINT. */
5943 sigprocmask(SIG_BLOCK, &sigint, NULL);
5944 if (cancel_pressed)
5945 done = true;
5946
5947 /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5948 while (!done)
5949 {
5950 int signal_received;
5951
5952 errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5953 if (errno != 0)
5954 {
5955 /* Some other signal arrived? */
5956 if (errno == EINTR)
5957 continue;
5958 else
5959 {
5960 pg_log_error("could not wait for signals: %m");
5961 done = true;
5962 break;
5963 }
5964 }
5965 /* On ^C or pager exit, it's time to stop running the query. */
5966 if (signal_received == SIGINT || signal_received == SIGCHLD)
5967 done = true;
5968 /* Otherwise, we must have SIGALRM. Time to run the query again. */
5969 break;
5970 }
5971
5972 /* Unblock SIGINT so that slow queries can be interrupted. */
5973 sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5974#endif
5975 }
5976
5977 if (pagerpipe)
5978 {
5979 pclose(pagerpipe);
5981 }
5982 else
5983 {
5984 /*
5985 * If the terminal driver echoed "^C", libedit/libreadline might be
5986 * confused about the cursor position. Therefore, inject a newline
5987 * before the next prompt is displayed. We only do this when not
5988 * using a pager, because pagers are expected to restore the screen to
5989 * a sane state on exit.
5990 */
5991 fprintf(stdout, "\n");
5992 fflush(stdout);
5993 }
5994
5995#ifndef WIN32
5996 /* Disable the interval timer. */
5997 memset(&interval, 0, sizeof(interval));
5999 /* Unblock SIGINT, SIGCHLD and SIGALRM. */
6000 sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
6001#endif
6002
6003 pg_free(title);
6004 return (res >= 0);
6005}
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
Definition: common.c:710
#define Min(x, y)
Definition: c.h:975
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
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
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:168
#define EINTR
Definition: win32_port.h:364
#define SIGALRM
Definition: win32_port.h:164
#define ITIMER_REAL
Definition: win32_port.h:180

References _, cancel_pressed, PQExpBufferData::data, disable_sigpipe_trap(), EINTR, fprintf, i, ITIMER_REAL, PQExpBufferData::len, Min, printTableOpt::pager, pg_free(), pg_log_error, pg_malloc(), pg_usleep(), _psqlSettings::popt, pset, PSQLexecWatch(), restore_sigpipe_trap(), setitimer(), SIGALRM, SIGCHLD, 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 6012 of file command.c.

6013{
6015 {
6016 printf(_("/******** QUERY *********/\n"
6017 "%s\n"
6018 "/************************/\n\n"), query);
6019 fflush(stdout);
6020 if (pset.logfile)
6021 {
6023 _("/******** QUERY *********/\n"
6024 "%s\n"
6025 "/************************/\n\n"), query);
6026 fflush(pset.logfile);
6027 }
6028
6030 return false;
6031 }
6032 return true;
6033}
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:53
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:51
FILE * logfile
Definition: settings.h:149
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:177

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

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ editFile()

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

Definition at line 4541 of file command.c.

4542{
4543 const char *editorName;
4544 const char *editor_lineno_arg = NULL;
4545 char *sys;
4546 int result;
4547
4548 Assert(fname != NULL);
4549
4550 /* Find an editor to use */
4551 editorName = getenv("PSQL_EDITOR");
4552 if (!editorName)
4553 editorName = getenv("EDITOR");
4554 if (!editorName)
4555 editorName = getenv("VISUAL");
4556 if (!editorName)
4557 editorName = DEFAULT_EDITOR;
4558
4559 /* Get line number argument, if we need it. */
4560 if (lineno > 0)
4561 {
4562 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4563#ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4564 if (!editor_lineno_arg)
4565 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4566#endif
4567 if (!editor_lineno_arg)
4568 {
4569 pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4570 return false;
4571 }
4572 }
4573
4574 /*
4575 * On Unix the EDITOR value should *not* be quoted, since it might include
4576 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4577 * if necessary. But this policy is not very workable on Windows, due to
4578 * severe brain damage in their command shell plus the fact that standard
4579 * program paths include spaces.
4580 */
4581#ifndef WIN32
4582 if (lineno > 0)
4583 sys = psprintf("exec %s %s%d '%s'",
4584 editorName, editor_lineno_arg, lineno, fname);
4585 else
4586 sys = psprintf("exec %s '%s'",
4587 editorName, fname);
4588#else
4589 if (lineno > 0)
4590 sys = psprintf("\"%s\" %s%d \"%s\"",
4591 editorName, editor_lineno_arg, lineno, fname);
4592 else
4593 sys = psprintf("\"%s\" \"%s\"",
4594 editorName, fname);
4595#endif
4596 fflush(NULL);
4597 result = system(sys);
4598 if (result == -1)
4599 pg_log_error("could not start editor \"%s\"", editorName);
4600 else if (result == 127)
4601 pg_log_error("could not start /bin/sh");
4602 free(sys);
4603
4604 return result == 0;
4605}
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23
#define DEFAULT_EDITOR
Definition: settings.h:22

References Assert(), DEFAULT_EDITOR, DEFAULT_EDITOR_LINENUMBER_ARG, 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 298 of file command.c.

303{
304 backslashResult status;
305 bool active_branch = conditional_active(cstack);
306
307 /*
308 * In interactive mode, warn when we're ignoring a command within a false
309 * \if-branch. But we continue on, so as to parse and discard the right
310 * amount of parameter text. Each individual backslash command subroutine
311 * is responsible for doing nothing after discarding appropriate
312 * arguments, if !active_branch.
313 */
314 if (pset.cur_cmd_interactive && !active_branch &&
316 {
317 pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
318 cmd);
319 }
320
321 if (strcmp(cmd, "a") == 0)
322 status = exec_command_a(scan_state, active_branch);
323 else if (strcmp(cmd, "bind") == 0)
324 status = exec_command_bind(scan_state, active_branch);
325 else if (strcmp(cmd, "bind_named") == 0)
326 status = exec_command_bind_named(scan_state, active_branch, cmd);
327 else if (strcmp(cmd, "C") == 0)
328 status = exec_command_C(scan_state, active_branch);
329 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
330 status = exec_command_connect(scan_state, active_branch);
331 else if (strcmp(cmd, "cd") == 0)
332 status = exec_command_cd(scan_state, active_branch, cmd);
333 else if (strcmp(cmd, "close") == 0)
334 status = exec_command_close(scan_state, active_branch, cmd);
335 else if (strcmp(cmd, "conninfo") == 0)
336 status = exec_command_conninfo(scan_state, active_branch);
337 else if (pg_strcasecmp(cmd, "copy") == 0)
338 status = exec_command_copy(scan_state, active_branch);
339 else if (strcmp(cmd, "copyright") == 0)
340 status = exec_command_copyright(scan_state, active_branch);
341 else if (strcmp(cmd, "crosstabview") == 0)
342 status = exec_command_crosstabview(scan_state, active_branch);
343 else if (cmd[0] == 'd')
344 status = exec_command_d(scan_state, active_branch, cmd);
345 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
346 status = exec_command_edit(scan_state, active_branch,
347 query_buf, previous_buf);
348 else if (strcmp(cmd, "ef") == 0)
349 status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
350 else if (strcmp(cmd, "ev") == 0)
351 status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
352 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
353 strcmp(cmd, "warn") == 0)
354 status = exec_command_echo(scan_state, active_branch, cmd);
355 else if (strcmp(cmd, "elif") == 0)
356 status = exec_command_elif(scan_state, cstack, query_buf);
357 else if (strcmp(cmd, "else") == 0)
358 status = exec_command_else(scan_state, cstack, query_buf);
359 else if (strcmp(cmd, "endif") == 0)
360 status = exec_command_endif(scan_state, cstack, query_buf);
361 else if (strcmp(cmd, "endpipeline") == 0)
362 status = exec_command_endpipeline(scan_state, active_branch);
363 else if (strcmp(cmd, "encoding") == 0)
364 status = exec_command_encoding(scan_state, active_branch);
365 else if (strcmp(cmd, "errverbose") == 0)
366 status = exec_command_errverbose(scan_state, active_branch);
367 else if (strcmp(cmd, "f") == 0)
368 status = exec_command_f(scan_state, active_branch);
369 else if (strcmp(cmd, "flush") == 0)
370 status = exec_command_flush(scan_state, active_branch);
371 else if (strcmp(cmd, "flushrequest") == 0)
372 status = exec_command_flushrequest(scan_state, active_branch);
373 else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
374 status = exec_command_g(scan_state, active_branch, cmd);
375 else if (strcmp(cmd, "gdesc") == 0)
376 status = exec_command_gdesc(scan_state, active_branch);
377 else if (strcmp(cmd, "getenv") == 0)
378 status = exec_command_getenv(scan_state, active_branch, cmd);
379 else if (strcmp(cmd, "getresults") == 0)
380 status = exec_command_getresults(scan_state, active_branch);
381 else if (strcmp(cmd, "gexec") == 0)
382 status = exec_command_gexec(scan_state, active_branch);
383 else if (strcmp(cmd, "gset") == 0)
384 status = exec_command_gset(scan_state, active_branch);
385 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
386 status = exec_command_help(scan_state, active_branch);
387 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
388 status = exec_command_html(scan_state, active_branch);
389 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
390 strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
391 status = exec_command_include(scan_state, active_branch, cmd);
392 else if (strcmp(cmd, "if") == 0)
393 status = exec_command_if(scan_state, cstack, query_buf);
394 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
395 strcmp(cmd, "lx") == 0 || strcmp(cmd, "listx") == 0 ||
396 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0 ||
397 strcmp(cmd, "lx+") == 0 || strcmp(cmd, "listx+") == 0 ||
398 strcmp(cmd, "l+x") == 0 || strcmp(cmd, "list+x") == 0)
399 status = exec_command_list(scan_state, active_branch, cmd);
400 else if (strncmp(cmd, "lo_", 3) == 0)
401 status = exec_command_lo(scan_state, active_branch, cmd);
402 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
403 status = exec_command_out(scan_state, active_branch);
404 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
405 status = exec_command_print(scan_state, active_branch,
406 query_buf, previous_buf);
407 else if (strcmp(cmd, "parse") == 0)
408 status = exec_command_parse(scan_state, active_branch, cmd);
409 else if (strcmp(cmd, "password") == 0)
410 status = exec_command_password(scan_state, active_branch);
411 else if (strcmp(cmd, "prompt") == 0)
412 status = exec_command_prompt(scan_state, active_branch, cmd);
413 else if (strcmp(cmd, "pset") == 0)
414 status = exec_command_pset(scan_state, active_branch);
415 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
416 status = exec_command_quit(scan_state, active_branch);
417 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
418 status = exec_command_reset(scan_state, active_branch, query_buf);
419 else if (strcmp(cmd, "s") == 0)
420 status = exec_command_s(scan_state, active_branch);
421 else if (strcmp(cmd, "sendpipeline") == 0)
422 status = exec_command_sendpipeline(scan_state, active_branch);
423 else if (strcmp(cmd, "set") == 0)
424 status = exec_command_set(scan_state, active_branch);
425 else if (strcmp(cmd, "setenv") == 0)
426 status = exec_command_setenv(scan_state, active_branch, cmd);
427 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
428 status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
429 else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
430 status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
431 else if (strcmp(cmd, "startpipeline") == 0)
432 status = exec_command_startpipeline(scan_state, active_branch);
433 else if (strcmp(cmd, "syncpipeline") == 0)
434 status = exec_command_syncpipeline(scan_state, active_branch);
435 else if (strcmp(cmd, "t") == 0)
436 status = exec_command_t(scan_state, active_branch);
437 else if (strcmp(cmd, "T") == 0)
438 status = exec_command_T(scan_state, active_branch);
439 else if (strcmp(cmd, "timing") == 0)
440 status = exec_command_timing(scan_state, active_branch);
441 else if (strcmp(cmd, "unset") == 0)
442 status = exec_command_unset(scan_state, active_branch, cmd);
443 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
444 status = exec_command_write(scan_state, active_branch, cmd,
445 query_buf, previous_buf);
446 else if (strcmp(cmd, "watch") == 0)
447 status = exec_command_watch(scan_state, active_branch,
448 query_buf, previous_buf);
449 else if (strcmp(cmd, "x") == 0)
450 status = exec_command_x(scan_state, active_branch);
451 else if (strcmp(cmd, "z") == 0 ||
452 strcmp(cmd, "zS") == 0 || strcmp(cmd, "zx") == 0 ||
453 strcmp(cmd, "zSx") == 0 || strcmp(cmd, "zxS") == 0)
454 status = exec_command_z(scan_state, active_branch, cmd);
455 else if (strcmp(cmd, "!") == 0)
456 status = exec_command_shell_escape(scan_state, active_branch);
457 else if (strcmp(cmd, "?") == 0)
458 status = exec_command_slash_command_help(scan_state, active_branch);
459 else
460 status = PSQL_CMD_UNKNOWN;
461
462 /*
463 * All the commands that return PSQL_CMD_SEND want to execute previous_buf
464 * if query_buf is empty. For convenience we implement that here, not in
465 * the individual command subroutines.
466 */
467 if (status == PSQL_CMD_SEND)
468 (void) copy_previous_query(query_buf, previous_buf);
469
470 return status;
471}
static backslashResult exec_command_startpipeline(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3006
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2267
static backslashResult exec_command_getresults(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1905
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:961
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1619
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2458
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2020
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3753
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1715
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3085
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1851
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2000
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:480
static backslashResult exec_command_flushrequest(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1690
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch)
Definition: command.c:499
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2518
static backslashResult exec_command_bind_named(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:535
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3427
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2080
static backslashResult exec_command_close(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:734
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2126
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1649
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2740
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2435
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1535
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:997
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3486
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:670
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1964
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1419
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:3139
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2822
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2758
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2594
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3271
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2039
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2307
static backslashResult exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2785
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3107
static backslashResult exec_command_endpipeline(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3044
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:584
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1580
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1323
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2202
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:767
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:939
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3508
static backslashResult exec_command_parse(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2484
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:973
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2671
static backslashResult exec_command_flush(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1671
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3063
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3169
static backslashResult exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3025
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2923
static bool is_branching_command(const char *cmd)
Definition: command.c:3691
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:617
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1941
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:3449
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2344
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1868
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2726
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2875
@ 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_endpipeline(), exec_command_errverbose(), exec_command_f(), exec_command_flush(), exec_command_flushrequest(), exec_command_g(), exec_command_gdesc(), exec_command_getenv(), exec_command_getresults(), 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_sendpipeline(), exec_command_set(), exec_command_setenv(), exec_command_sf_sv(), exec_command_shell_escape(), exec_command_slash_command_help(), exec_command_startpipeline(), exec_command_syncpipeline(), 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 480 of file command.c.

481{
482 bool success = true;
483
484 if (active_branch)
485 {
487 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
488 else
489 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
490 }
491
493}
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4971
@ 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 499 of file command.c.

500{
502
503 if (active_branch)
504 {
505 char *opt;
506 int nparams = 0;
507 int nalloc = 0;
508
510
511 while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
512 {
513 nparams++;
514 if (nparams > nalloc)
515 {
516 nalloc = nalloc ? nalloc * 2 : 1;
518 }
519 pset.bind_params[nparams - 1] = opt;
520 }
521
522 pset.bind_nparams = nparams;
524 }
525 else
526 ignore_slash_options(scan_state);
527
528 return status;
529}
void clean_extended_state(void)
Definition: common.c:2581
static void ignore_slash_options(PsqlScanState scan_state)
Definition: command.c:3642
#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:76
char ** bind_params
Definition: settings.h:123
PSQL_SEND_MODE send_mode
Definition: settings.h:120
int bind_nparams
Definition: settings.h:122

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

537{
539
540 if (active_branch)
541 {
542 char *opt;
543 int nparams = 0;
544 int nalloc = 0;
545
547
548 /* get the mandatory prepared statement name */
549 opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
550 if (!opt)
551 {
552 pg_log_error("\\%s: missing required argument", cmd);
553 status = PSQL_CMD_ERROR;
554 }
555 else
556 {
557 pset.stmtName = opt;
559
560 /* set of parameters */
561 while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
562 {
563 nparams++;
564 if (nparams > nalloc)
565 {
566 nalloc = nalloc ? nalloc * 2 : 1;
568 }
569 pset.bind_params[nparams - 1] = opt;
570 }
571 pset.bind_nparams = nparams;
572 }
573 }
574 else
575 ignore_slash_options(scan_state);
576
577 return status;
578}
@ PSQL_SEND_EXTENDED_QUERY_PREPARED
Definition: settings.h:77
char * stmtName
Definition: settings.h:124

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

585{
586 bool success = true;
587
588 if (active_branch)
589 {
590 char *opt = psql_scan_slash_option(scan_state,
591 OT_NORMAL, NULL, true);
592
593 success = do_pset("title", opt, &pset.popt, pset.quiet);
594 free(opt);
595 }
596 else
597 ignore_slash_options(scan_state);
598
600}

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

671{
672 bool success = true;
673
674 if (active_branch)
675 {
676 char *opt = psql_scan_slash_option(scan_state,
677 OT_NORMAL, NULL, true);
678 char *dir;
679
680 if (opt)
681 dir = opt;
682 else
683 {
684#ifndef WIN32
685 /* This should match get_home_path() */
686 dir = getenv("HOME");
687 if (dir == NULL || dir[0] == '\0')
688 {
689 uid_t user_id = geteuid();
690 struct passwd *pw;
691
692 errno = 0; /* clear errno before call */
693 pw = getpwuid(user_id);
694 if (pw)
695 dir = pw->pw_dir;
696 else
697 {
698 pg_log_error("could not get home directory for user ID %ld: %s",
699 (long) user_id,
700 errno ? strerror(errno) : _("user does not exist"));
701 success = false;
702 }
703 }
704#else /* WIN32 */
705
706 /*
707 * On Windows, 'cd' without arguments prints the current
708 * directory, so if someone wants to code this here instead...
709 */
710 dir = "/";
711#endif /* WIN32 */
712 }
713
714 if (success &&
715 chdir(dir) < 0)
716 {
717 pg_log_error("\\%s: could not change directory to \"%s\": %m",
718 cmd, dir);
719 success = false;
720 }
721
722 free(opt);
723 }
724 else
725 ignore_slash_options(scan_state);
726
728}
int uid_t
Definition: win32_port.h:234

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

735{
737
738 if (active_branch)
739 {
740 char *opt = psql_scan_slash_option(scan_state,
741 OT_NORMAL, NULL, false);
742
744
745 if (!opt)
746 {
747 pg_log_error("\\%s: missing required argument", cmd);
748 status = PSQL_CMD_ERROR;
749 }
750 else
751 {
752 pset.stmtName = opt;
754 status = PSQL_CMD_SEND;
755 }
756 }
757 else
758 ignore_slash_options(scan_state);
759
760 return status;
761}
@ PSQL_SEND_EXTENDED_CLOSE
Definition: settings.h:74

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

618{
619 bool success = true;
620
621 if (active_branch)
622 {
623 static const char prefix[] = "-reuse-previous=";
624 char *opt1,
625 *opt2,
626 *opt3,
627 *opt4;
628 enum trivalue reuse_previous = TRI_DEFAULT;
629
630 opt1 = read_connect_arg(scan_state);
631 if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
632 {
633 bool on_off;
634
635 success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
636 "-reuse-previous",
637 &on_off);
638 if (success)
639 {
640 reuse_previous = on_off ? TRI_YES : TRI_NO;
641 free(opt1);
642 opt1 = read_connect_arg(scan_state);
643 }
644 }
645
646 if (success) /* give up if reuse_previous was invalid */
647 {
648 opt2 = read_connect_arg(scan_state);
649 opt3 = read_connect_arg(scan_state);
650 opt4 = read_connect_arg(scan_state);
651
652 success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
653
654 free(opt2);
655 free(opt3);
656 free(opt4);
657 }
658 free(opt1);
659 }
660 else
661 ignore_slash_options(scan_state);
662
664}
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:3822
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:3539
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 767 of file command.c.

768{
770 int rows,
771 cols;
772 char *db;
773 char *host;
774 bool print_hostaddr;
775 char *hostaddr;
776 char *protocol_version,
777 *backend_pid;
778 int ssl_in_use,
779 password_used,
780 gssapi_used;
781 char *paramval;
782
783 if (!active_branch)
784 return PSQL_CMD_SKIP_LINE;
785
786 db = PQdb(pset.db);
787 if (db == NULL)
788 {
789 printf(_("You are currently not connected to a database.\n"));
790 return PSQL_CMD_SKIP_LINE;
791 }
792
793 /* Get values for the parameters */
794 host = PQhost(pset.db);
795 hostaddr = PQhostaddr(pset.db);
796 protocol_version = psprintf("%d", PQprotocolVersion(pset.db));
797 ssl_in_use = PQsslInUse(pset.db);
798 password_used = PQconnectionUsedPassword(pset.db);
799 gssapi_used = PQconnectionUsedGSSAPI(pset.db);
800 backend_pid = psprintf("%d", PQbackendPID(pset.db));
801
802 /* Only print hostaddr if it differs from host, and not if unixsock */
803 print_hostaddr = (!is_unixsock_path(host) &&
804 hostaddr && *hostaddr && strcmp(host, hostaddr) != 0);
805
806 /* Determine the exact number of rows to print */
807 rows = 12;
808 cols = 2;
809 if (ssl_in_use)
810 rows += 6;
811 if (print_hostaddr)
812 rows++;
813
814 /* Set it all up */
815 printTableInit(&cont, &pset.popt.topt, _("Connection Information"), cols, rows);
816 printTableAddHeader(&cont, _("Parameter"), true, 'l');
817 printTableAddHeader(&cont, _("Value"), true, 'l');
818
819 /* Database */
820 printTableAddCell(&cont, _("Database"), false, false);
821 printTableAddCell(&cont, db, false, false);
822
823 /* Client User */
824 printTableAddCell(&cont, _("Client User"), false, false);
825 printTableAddCell(&cont, PQuser(pset.db), false, false);
826
827 /* Host/hostaddr/socket */
828 if (is_unixsock_path(host))
829 {
830 /* hostaddr if specified overrides socket, so suppress the latter */
831 if (hostaddr && *hostaddr)
832 {
833 printTableAddCell(&cont, _("Host Address"), false, false);
834 printTableAddCell(&cont, hostaddr, false, false);
835 }
836 else
837 {
838 printTableAddCell(&cont, _("Socket Directory"), false, false);
839 printTableAddCell(&cont, host, false, false);
840 }
841 }
842 else
843 {
844 printTableAddCell(&cont, _("Host"), false, false);
845 printTableAddCell(&cont, host, false, false);
846 if (print_hostaddr)
847 {
848 printTableAddCell(&cont, _("Host Address"), false, false);
849 printTableAddCell(&cont, hostaddr, false, false);
850 }
851 }
852
853 /* Server Port */
854 printTableAddCell(&cont, _("Server Port"), false, false);
855 printTableAddCell(&cont, PQport(pset.db), false, false);
856
857 /* Options */
858 printTableAddCell(&cont, _("Options"), false, false);
859 printTableAddCell(&cont, PQoptions(pset.db), false, false);
860
861 /* Protocol Version */
862 printTableAddCell(&cont, _("Protocol Version"), false, false);
863 printTableAddCell(&cont, protocol_version, false, false);
864
865 /* Password Used */
866 printTableAddCell(&cont, _("Password Used"), false, false);
867 printTableAddCell(&cont, password_used ? _("true") : _("false"), false, false);
868
869 /* GSSAPI Authenticated */
870 printTableAddCell(&cont, _("GSSAPI Authenticated"), false, false);
871 printTableAddCell(&cont, gssapi_used ? _("true") : _("false"), false, false);
872
873 /* Backend PID */
874 printTableAddCell(&cont, _("Backend PID"), false, false);
875 printTableAddCell(&cont, backend_pid, false, false);
876
877 /* TLS Connection */
878 printTableAddCell(&cont, _("TLS Connection"), false, false);
879 printTableAddCell(&cont, ssl_in_use ? _("true") : _("false"), false, false);
880
881 /* TLS Information */
882 if (ssl_in_use)
883 {
884 char *library,
885 *protocol,
886 *key_bits,
887 *cipher,
888 *compression,
889 *alpn;
890
891 library = (char *) PQsslAttribute(pset.db, "library");
892 protocol = (char *) PQsslAttribute(pset.db, "protocol");
893 key_bits = (char *) PQsslAttribute(pset.db, "key_bits");
894 cipher = (char *) PQsslAttribute(pset.db, "cipher");
895 compression = (char *) PQsslAttribute(pset.db, "compression");
896 alpn = (char *) PQsslAttribute(pset.db, "alpn");
897
898 printTableAddCell(&cont, _("TLS Library"), false, false);
899 printTableAddCell(&cont, library ? library : _("unknown"), false, false);
900
901 printTableAddCell(&cont, _("TLS Protocol"), false, false);
902 printTableAddCell(&cont, protocol ? protocol : _("unknown"), false, false);
903
904 printTableAddCell(&cont, _("TLS Key Bits"), false, false);
905 printTableAddCell(&cont, key_bits ? key_bits : _("unknown"), false, false);
906
907 printTableAddCell(&cont, _("TLS Cipher"), false, false);
908 printTableAddCell(&cont, cipher ? cipher : _("unknown"), false, false);
909
910 printTableAddCell(&cont, _("TLS Compression"), false, false);
911 printTableAddCell(&cont, (compression && strcmp(compression, "off") != 0) ?
912 _("true") : _("false"), false, false);
913
914 printTableAddCell(&cont, _("ALPN"), false, false);
915 printTableAddCell(&cont, (alpn && alpn[0] != '\0') ? alpn : _("none"), false, false);
916 }
917
918 paramval = (char *) PQparameterStatus(pset.db, "is_superuser");
919 printTableAddCell(&cont, "Superuser", false, false);
920 printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
921
922 paramval = (char *) PQparameterStatus(pset.db, "in_hot_standby");
923 printTableAddCell(&cont, "Hot Standby", false, false);
924 printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
925
926 printTable(&cont, pset.queryFout, false, pset.logfile);
927 printTableCleanup(&cont);
928
929 pfree(protocol_version);
930 pfree(backend_pid);
931
932 return PSQL_CMD_SKIP_LINE;
933}
int PQprotocolVersion(const PGconn *conn)
Definition: fe-connect.c:7523
char * PQoptions(const PGconn *conn)
Definition: fe-connect.c:7482
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7621
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7632
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:7589
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:103
void printTableInit(printTableContent *const content, const printTableOpt *opt, const char *title, const int ncolumns, const int nrows)
Definition: print.c:3172
void printTableCleanup(printTableContent *const content)
Definition: print.c:3353
void printTableAddCell(printTableContent *const content, char *cell, const bool translate, const bool mustfree)
Definition: print.c:3260
void printTable(const printTableContent *cont, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3443
void printTableAddHeader(printTableContent *const content, char *header, const bool translate, const char align)
Definition: print.c:3220
void pfree(void *pointer)
Definition: mcxt.c:1524
FILE * queryFout
Definition: settings.h:105

References _, _psqlSettings::db, is_unixsock_path(), _psqlSettings::logfile, pfree(), _psqlSettings::popt, PQbackendPID(), PQconnectionUsedGSSAPI(), PQconnectionUsedPassword(), PQdb(), PQhost(), PQhostaddr(), PQoptions(), PQparameterStatus(), PQport(), PQprotocolVersion(), PQsslAttribute(), PQsslInUse(), PQuser(), printf, printTable(), printTableAddCell(), printTableAddHeader(), printTableCleanup(), printTableInit(), pset, psprintf(), PSQL_CMD_SKIP_LINE, _psqlSettings::queryFout, and printQueryOpt::topt.

Referenced by exec_command().

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 939 of file command.c.

940{
941 bool success = true;
942
943 if (active_branch)
944 {
945 char *opt = psql_scan_slash_option(scan_state,
946 OT_WHOLE_LINE, NULL, false);
947
948 success = do_copy(opt);
949 free(opt);
950 }
951 else
952 ignore_slash_whole_line(scan_state);
953
955}
bool do_copy(const char *args)
Definition: copy.c:268
static void ignore_slash_whole_line(PsqlScanState scan_state)
Definition: command.c:3679
@ 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 961 of file command.c.

962{
963 if (active_branch)
965
966 return PSQL_CMD_SKIP_LINE;
967}
void print_copyright(void)
Definition: help.c:743

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

974{
976
977 if (active_branch)
978 {
979 int i;
980
981 for (i = 0; i < lengthof(pset.ctv_args); i++)
983 OT_NORMAL, NULL, true);
984 pset.crosstab_flag = true;
985 status = PSQL_CMD_SEND;
986 }
987 else
988 ignore_slash_options(scan_state);
989
990 return status;
991}
char * ctv_args[4]
Definition: settings.h:133
bool crosstab_flag
Definition: settings.h:132

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

998{
1000 bool success = true;
1001
1002 if (active_branch)
1003 {
1004 char *pattern;
1005 bool show_verbose,
1006 show_system;
1007 unsigned short int save_expanded;
1008
1009 /* We don't do SQLID reduction on the pattern yet */
1010 pattern = psql_scan_slash_option(scan_state,
1011 OT_NORMAL, NULL, true);
1012
1013 show_verbose = strchr(cmd, '+') ? true : false;
1014 show_system = strchr(cmd, 'S') ? true : false;
1015
1016 /*
1017 * The 'x' option turns expanded mode on for this command only. This
1018 * is allowed in all \d* commands, except \d by itself, since \dx is a
1019 * separate command. So the 'x' option cannot appear immediately after
1020 * \d, but it can appear after \d followed by other options.
1021 */
1022 save_expanded = pset.popt.topt.expanded;
1023 if (cmd[1] != '\0' && strchr(&cmd[2], 'x'))
1024 pset.popt.topt.expanded = 1;
1025
1026 switch (cmd[1])
1027 {
1028 case '\0':
1029 case '+':
1030 case 'S':
1031 if (pattern)
1032 success = describeTableDetails(pattern, show_verbose, show_system);
1033 else
1034 /* standard listing of interesting things */
1035 success = listTables("tvmsE", NULL, show_verbose, show_system);
1036 break;
1037 case 'A':
1038 {
1039 char *pattern2 = NULL;
1040
1041 if (pattern && cmd[2] != '\0' && cmd[2] != '+' && cmd[2] != 'x')
1042 pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
1043
1044 switch (cmd[2])
1045 {
1046 case '\0':
1047 case '+':
1048 case 'x':
1049 success = describeAccessMethods(pattern, show_verbose);
1050 break;
1051 case 'c':
1052 success = listOperatorClasses(pattern, pattern2, show_verbose);
1053 break;
1054 case 'f':
1055 success = listOperatorFamilies(pattern, pattern2, show_verbose);
1056 break;
1057 case 'o':
1058 success = listOpFamilyOperators(pattern, pattern2, show_verbose);
1059 break;
1060 case 'p':
1061 success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
1062 break;
1063 default:
1064 status = PSQL_CMD_UNKNOWN;
1065 break;
1066 }
1067
1068 free(pattern2);
1069 }
1070 break;
1071 case 'a':
1072 success = describeAggregates(pattern, show_verbose, show_system);
1073 break;
1074 case 'b':
1075 success = describeTablespaces(pattern, show_verbose);
1076 break;
1077 case 'c':
1078 if (strncmp(cmd, "dconfig", 7) == 0)
1080 show_verbose,
1081 show_system);
1082 else
1083 success = listConversions(pattern,
1084 show_verbose,
1085 show_system);
1086 break;
1087 case 'C':
1088 success = listCasts(pattern, show_verbose);
1089 break;
1090 case 'd':
1091 if (strncmp(cmd, "ddp", 3) == 0)
1092 success = listDefaultACLs(pattern);
1093 else
1094 success = objectDescription(pattern, show_system);
1095 break;
1096 case 'D':
1097 success = listDomains(pattern, show_verbose, show_system);
1098 break;
1099 case 'f': /* function subsystem */
1100 switch (cmd[2])
1101 {
1102 case '\0':
1103 case '+':
1104 case 'S':
1105 case 'a':
1106 case 'n':
1107 case 'p':
1108 case 't':
1109 case 'w':
1110 case 'x':
1111 success = exec_command_dfo(scan_state, cmd, pattern,
1112 show_verbose, show_system);
1113 break;
1114 default:
1115 status = PSQL_CMD_UNKNOWN;
1116 break;
1117 }
1118 break;
1119 case 'g':
1120 /* no longer distinct from \du */
1121 success = describeRoles(pattern, show_verbose, show_system);
1122 break;
1123 case 'l':
1124 success = listLargeObjects(show_verbose);
1125 break;
1126 case 'L':
1127 success = listLanguages(pattern, show_verbose, show_system);
1128 break;
1129 case 'n':
1130 success = listSchemas(pattern, show_verbose, show_system);
1131 break;
1132 case 'o':
1133 success = exec_command_dfo(scan_state, cmd, pattern,
1134 show_verbose, show_system);
1135 break;
1136 case 'O':
1137 success = listCollations(pattern, show_verbose, show_system);
1138 break;
1139 case 'p':
1140 success = permissionsList(pattern, show_system);
1141 break;
1142 case 'P':
1143 {
1144 switch (cmd[2])
1145 {
1146 case '\0':
1147 case '+':
1148 case 't':
1149 case 'i':
1150 case 'n':
1151 case 'x':
1152 success = listPartitionedTables(&cmd[2], pattern, show_verbose);
1153 break;
1154 default:
1155 status = PSQL_CMD_UNKNOWN;
1156 break;
1157 }
1158 }
1159 break;
1160 case 'T':
1161 success = describeTypes(pattern, show_verbose, show_system);
1162 break;
1163 case 't':
1164 case 'v':
1165 case 'm':
1166 case 'i':
1167 case 's':
1168 case 'E':
1169 success = listTables(&cmd[1], pattern, show_verbose, show_system);
1170 break;
1171 case 'r':
1172 if (cmd[2] == 'd' && cmd[3] == 's')
1173 {
1174 char *pattern2 = NULL;
1175
1176 if (pattern)
1177 pattern2 = psql_scan_slash_option(scan_state,
1178 OT_NORMAL, NULL, true);
1179 success = listDbRoleSettings(pattern, pattern2);
1180
1181 free(pattern2);
1182 }
1183 else if (cmd[2] == 'g')
1184 success = describeRoleGrants(pattern, show_system);
1185 else
1186 status = PSQL_CMD_UNKNOWN;
1187 break;
1188 case 'R':
1189 switch (cmd[2])
1190 {
1191 case 'p':
1192 if (show_verbose)
1193 success = describePublications(pattern);
1194 else
1195 success = listPublications(pattern);
1196 break;
1197 case 's':
1198 success = describeSubscriptions(pattern, show_verbose);
1199 break;
1200 default:
1201 status = PSQL_CMD_UNKNOWN;
1202 }
1203 break;
1204 case 'u':
1205 success = describeRoles(pattern, show_verbose, show_system);
1206 break;
1207 case 'F': /* text search subsystem */
1208 switch (cmd[2])
1209 {
1210 case '\0':
1211 case '+':
1212 case 'x':
1213 success = listTSConfigs(pattern, show_verbose);
1214 break;
1215 case 'p':
1216 success = listTSParsers(pattern, show_verbose);
1217 break;
1218 case 'd':
1219 success = listTSDictionaries(pattern, show_verbose);
1220 break;
1221 case 't':
1222 success = listTSTemplates(pattern, show_verbose);
1223 break;
1224 default:
1225 status = PSQL_CMD_UNKNOWN;
1226 break;
1227 }
1228 break;
1229 case 'e': /* SQL/MED subsystem */
1230 switch (cmd[2])
1231 {
1232 case 's':
1233 success = listForeignServers(pattern, show_verbose);
1234 break;
1235 case 'u':
1236 success = listUserMappings(pattern, show_verbose);
1237 break;
1238 case 'w':
1239 success = listForeignDataWrappers(pattern, show_verbose);
1240 break;
1241 case 't':
1242 success = listForeignTables(pattern, show_verbose);
1243 break;
1244 default:
1245 status = PSQL_CMD_UNKNOWN;
1246 break;
1247 }
1248 break;
1249 case 'x': /* Extensions */
1250 if (show_verbose)
1251 success = listExtensionContents(pattern);
1252 else
1253 success = listExtensions(pattern);
1254 break;
1255 case 'X': /* Extended Statistics */
1256 success = listExtendedStats(pattern);
1257 break;
1258 case 'y': /* Event Triggers */
1259 success = listEventTriggers(pattern, show_verbose);
1260 break;
1261 default:
1262 status = PSQL_CMD_UNKNOWN;
1263 }
1264
1265 /* Restore original expanded mode */
1266 pset.popt.topt.expanded = save_expanded;
1267
1268 free(pattern);
1269 }
1270 else
1271 ignore_slash_options(scan_state);
1272
1273 if (!success)
1274 status = PSQL_CMD_ERROR;
1275
1276 return status;
1277}
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:1281
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:6055
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:5704
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3716
bool listOpFamilyFunctions(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:7195
bool listPublications(const char *pattern)
Definition: describe.c:6400
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5327
bool listExtensionContents(const char *pattern)
Definition: describe.c:6236
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:78
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:5908
bool listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
Definition: describe.c:4266
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:6746
bool describeRoleGrants(const char *pattern, bool showSystem)
Definition: describe.c:3932
bool listExtendedStats(const char *pattern)
Definition: describe.c:4863
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:638
bool listOperatorFamilies(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6999
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:5979
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1483
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4552
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:5574
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3863
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5083
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:5206
bool listExtensions(const char *pattern)
Definition: describe.c:6182
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4011
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:5639
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:222
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:4959
bool listOpFamilyOperators(const char *access_method_pattern, const char *family_pattern, bool verbose)
Definition: describe.c:7088
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6898
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:6110
bool describeConfigurationParameters(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4715
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:4783
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1213
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4635
bool permissionsList(const char *pattern, bool showSystem)
Definition: describe.c:1049
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:148
bool listLargeObjects(bool verbose)
Definition: describe.c:7284
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4476
bool describePublications(const char *pattern)
Definition: describe.c:6531
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1290
return true
Definition: isn.c:127

References describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describePublications(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), exec_command_dfo(), printTableOpt::expanded, 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(), _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, PSQL_CMD_UNKNOWN, psql_scan_slash_option(), success, printQueryOpt::topt, 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 1281 of file command.c.

1284{
1285 bool success;
1286 char *arg_patterns[FUNC_MAX_ARGS];
1287 int num_arg_patterns = 0;
1288
1289 /* Collect argument-type patterns too */
1290 if (pattern) /* otherwise it was just \df or \do */
1291 {
1292 char *ap;
1293
1294 while ((ap = psql_scan_slash_option(scan_state,
1295 OT_NORMAL, NULL, true)) != NULL)
1296 {
1297 arg_patterns[num_arg_patterns++] = ap;
1298 if (num_arg_patterns >= FUNC_MAX_ARGS)
1299 break; /* protect limited-size array */
1300 }
1301 }
1302
1303 if (cmd[1] == 'f')
1304 success = describeFunctions(&cmd[2], pattern,
1305 arg_patterns, num_arg_patterns,
1306 show_verbose, show_system);
1307 else
1308 success = describeOperators(pattern,
1309 arg_patterns, num_arg_patterns,
1310 show_verbose, show_system);
1311
1312 while (--num_arg_patterns >= 0)
1313 free(arg_patterns[num_arg_patterns]);
1314
1315 return success;
1316}
bool describeFunctions(const char *functypes, const char *func_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:295
bool describeOperators(const char *oper_pattern, char **arg_patterns, int num_arg_patterns, bool verbose, bool showSystem)
Definition: describe.c:793
#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 1535 of file command.c.

1536{
1537 if (active_branch)
1538 {
1539 char *value;
1540 char quoted;
1541 bool no_newline = false;
1542 bool first = true;
1543 FILE *fout;
1544
1545 if (strcmp(cmd, "qecho") == 0)
1546 fout = pset.queryFout;
1547 else if (strcmp(cmd, "warn") == 0)
1548 fout = stderr;
1549 else
1550 fout = stdout;
1551
1552 while ((value = psql_scan_slash_option(scan_state,
1553 OT_NORMAL, &quoted, false)))
1554 {
1555 if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1556 no_newline = true;
1557 else
1558 {
1559 if (first)
1560 first = false;
1561 else
1562 fputc(' ', fout);
1563 fputs(value, fout);
1564 }
1565 free(value);
1566 }
1567 if (!no_newline)
1568 fputs("\n", fout);
1569 }
1570 else
1571 ignore_slash_options(scan_state);
1572
1573 return PSQL_CMD_SKIP_LINE;
1574}

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

1325{
1327
1328 if (active_branch)
1329 {
1330 if (!query_buf)
1331 {
1332 pg_log_error("no query buffer");
1333 status = PSQL_CMD_ERROR;
1334 }
1335 else
1336 {
1337 char *fname;
1338 char *ln = NULL;
1339 int lineno = -1;
1340
1341 fname = psql_scan_slash_option(scan_state,
1342 OT_NORMAL, NULL, true);
1343 if (fname)
1344 {
1345 /* try to get separate lineno arg */
1346 ln = psql_scan_slash_option(scan_state,
1347 OT_NORMAL, NULL, true);
1348 if (ln == NULL)
1349 {
1350 /* only one arg; maybe it is lineno not fname */
1351 if (fname[0] &&
1352 strspn(fname, "0123456789") == strlen(fname))
1353 {
1354 /* all digits, so assume it is lineno */
1355 ln = fname;
1356 fname = NULL;
1357 }
1358 }
1359 }
1360 if (ln)
1361 {
1362 lineno = atoi(ln);
1363 if (lineno < 1)
1364 {
1365 pg_log_error("invalid line number: %s", ln);
1366 status = PSQL_CMD_ERROR;
1367 }
1368 }
1369 if (status != PSQL_CMD_ERROR)
1370 {
1371 bool discard_on_quit;
1372
1373 expand_tilde(&fname);
1374 if (fname)
1375 {
1377 /* Always clear buffer if the file isn't modified */
1378 discard_on_quit = true;
1379 }
1380 else
1381 {
1382 /*
1383 * If query_buf is empty, recall previous query for
1384 * editing. But in that case, the query buffer should be
1385 * emptied if editing doesn't modify the file.
1386 */
1387 discard_on_quit = copy_previous_query(query_buf,
1388 previous_buf);
1389 }
1390
1391 if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1392 status = PSQL_CMD_NEWEDIT;
1393 else
1394 status = PSQL_CMD_ERROR;
1395 }
1396
1397 /*
1398 * On error while editing or if specifying an incorrect line
1399 * number, reset the query buffer.
1400 */
1401 if (status == PSQL_CMD_ERROR)
1402 resetPQExpBuffer(query_buf);
1403
1404 free(fname);
1405 free(ln);
1406 }
1407 }
1408 else
1409 ignore_slash_options(scan_state);
1410
1411 return status;
1412}
void expand_tilde(char **filename)
Definition: common.c:2497
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:4623
@ PSQL_CMD_NEWEDIT
Definition: command.h:21
void canonicalize_path_enc(char *path, int encoding)
Definition: path.c:344

References canonicalize_path_enc(), copy_previous_query(), do_edit(), _psqlSettings::encoding, expand_tilde(), free, ignore_slash_options(), OT_NORMAL, pg_log_error, pset, 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 1419 of file command.c.

1421{
1423
1424 if (active_branch)
1425 {
1426 char *obj_desc = psql_scan_slash_option(scan_state,
1428 NULL, true);
1429 int lineno = -1;
1430
1431 if (!query_buf)
1432 {
1433 pg_log_error("no query buffer");
1434 status = PSQL_CMD_ERROR;
1435 }
1436 else
1437 {
1438 Oid obj_oid = InvalidOid;
1440
1441 lineno = strip_lineno_from_objdesc(obj_desc);
1442 if (lineno == 0)
1443 {
1444 /* error already reported */
1445 status = PSQL_CMD_ERROR;
1446 }
1447 else if (!obj_desc)
1448 {
1449 /* set up an empty command to fill in */
1450 resetPQExpBuffer(query_buf);
1451 if (is_func)
1452 appendPQExpBufferStr(query_buf,
1453 "CREATE FUNCTION ( )\n"
1454 " RETURNS \n"
1455 " LANGUAGE \n"
1456 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1457 "AS $function$\n"
1458 "\n$function$\n");
1459 else
1460 appendPQExpBufferStr(query_buf,
1461 "CREATE VIEW AS\n"
1462 " SELECT \n"
1463 " -- something...\n");
1464 }
1465 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1466 {
1467 /* error already reported */
1468 status = PSQL_CMD_ERROR;
1469 }
1470 else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1471 {
1472 /* error already reported */
1473 status = PSQL_CMD_ERROR;
1474 }
1475 else if (is_func && lineno > 0)
1476 {
1477 /*
1478 * lineno "1" should correspond to the first line of the
1479 * function body. We expect that pg_get_functiondef() will
1480 * emit that on a line beginning with "AS ", "BEGIN ", or
1481 * "RETURN ", and that there can be no such line before the
1482 * real start of the function body. Increment lineno by the
1483 * number of lines before that line, so that it becomes
1484 * relative to the first line of the function definition.
1485 */
1486 const char *lines = query_buf->data;
1487
1488 while (*lines != '\0')
1489 {
1490 if (strncmp(lines, "AS ", 3) == 0 ||
1491 strncmp(lines, "BEGIN ", 6) == 0 ||
1492 strncmp(lines, "RETURN ", 7) == 0)
1493 break;
1494 lineno++;
1495 /* find start of next line */
1496 lines = strchr(lines, '\n');
1497 if (!lines)
1498 break;
1499 lines++;
1500 }
1501 }
1502 }
1503
1504 if (status != PSQL_CMD_ERROR)
1505 {
1506 bool edited = false;
1507
1508 if (!do_edit(NULL, query_buf, lineno, true, &edited))
1509 status = PSQL_CMD_ERROR;
1510 else if (!edited)
1511 puts(_("No changes"));
1512 else
1513 status = PSQL_CMD_NEWEDIT;
1514 }
1515
1516 /*
1517 * On error while doing object lookup or while editing, or if
1518 * specifying an incorrect line number, reset the query buffer.
1519 */
1520 if (status == PSQL_CMD_ERROR)
1521 resetPQExpBuffer(query_buf);
1522
1523 free(obj_desc);
1524 }
1525 else
1526 ignore_slash_whole_line(scan_state);
1527
1528 return status;
1529}
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:6104
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:6044
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:6264
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30

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

2128{
2129 bool success = true;
2130
2131 switch (conditional_stack_peek(cstack))
2132 {
2133 case IFSTATE_TRUE:
2134
2135 /*
2136 * Just finished active branch of this \if block. Update saved
2137 * state so we will keep whatever data was put in query_buf by the
2138 * active branch.
2139 */
2140 save_query_text_state(scan_state, cstack, query_buf);
2141
2142 /*
2143 * Discard \elif expression and ignore the rest until \endif.
2144 * Switch state before reading expression to ensure proper lexer
2145 * behavior.
2146 */
2148 ignore_boolean_expression(scan_state);
2149 break;
2150 case IFSTATE_FALSE:
2151
2152 /*
2153 * Discard any query text added by the just-skipped branch.
2154 */
2155 discard_query_text(scan_state, cstack, query_buf);
2156
2157 /*
2158 * Have not yet found a true expression in this \if block, so this
2159 * might be the first. We have to change state before examining
2160 * the expression, or the lexer won't do the right thing.
2161 */
2163 if (!is_true_boolean_expression(scan_state, "\\elif expression"))
2165 break;
2166 case IFSTATE_IGNORED:
2167
2168 /*
2169 * Discard any query text added by the just-skipped branch.
2170 */
2171 discard_query_text(scan_state, cstack, query_buf);
2172
2173 /*
2174 * Skip expression and move on. Either the \if block already had
2175 * an active section, or whole block is being skipped.
2176 */
2177 ignore_boolean_expression(scan_state);
2178 break;
2179 case IFSTATE_ELSE_TRUE:
2180 case IFSTATE_ELSE_FALSE:
2181 pg_log_error("\\elif: cannot occur after \\else");
2182 success = false;
2183 break;
2184 case IFSTATE_NONE:
2185 /* no \if to elif from */
2186 pg_log_error("\\elif: no matching \\if");
2187 success = false;
2188 break;
2189 }
2190
2192}
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3727
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3626
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:3609
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3707
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 2202 of file command.c.

2204{
2205 bool success = true;
2206
2207 switch (conditional_stack_peek(cstack))
2208 {
2209 case IFSTATE_TRUE:
2210
2211 /*
2212 * Just finished active branch of this \if block. Update saved
2213 * state so we will keep whatever data was put in query_buf by the
2214 * active branch.
2215 */
2216 save_query_text_state(scan_state, cstack, query_buf);
2217
2218 /* Now skip the \else branch */
2220 break;
2221 case IFSTATE_FALSE:
2222
2223 /*
2224 * Discard any query text added by the just-skipped branch.
2225 */
2226 discard_query_text(scan_state, cstack, query_buf);
2227
2228 /*
2229 * We've not found any true \if or \elif expression, so execute
2230 * the \else branch.
2231 */
2233 break;
2234 case IFSTATE_IGNORED:
2235
2236 /*
2237 * Discard any query text added by the just-skipped branch.
2238 */
2239 discard_query_text(scan_state, cstack, query_buf);
2240
2241 /*
2242 * Either we previously processed the active branch of this \if,
2243 * or the whole \if block is being skipped. Either way, skip the
2244 * \else branch.
2245 */
2247 break;
2248 case IFSTATE_ELSE_TRUE:
2249 case IFSTATE_ELSE_FALSE:
2250 pg_log_error("\\else: cannot occur after \\else");
2251 success = false;
2252 break;
2253 case IFSTATE_NONE:
2254 /* no \if to else from */
2255 pg_log_error("\\else: no matching \\if");
2256 success = false;
2257 break;
2258 }
2259
2261}

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

1581{
1582 if (active_branch)
1583 {
1584 char *encoding = psql_scan_slash_option(scan_state,
1585 OT_NORMAL, NULL, false);
1586
1587 if (!encoding)
1588 {
1589 /* show encoding */
1591 }
1592 else
1593 {
1594 /* set encoding */
1595 if (PQsetClientEncoding(pset.db, encoding) == -1)
1596 pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1597 else
1598 {
1599 /* save encoding info into psql internal data */
1603 SetVariable(pset.vars, "ENCODING",
1605 }
1606 free(encoding);
1607 }
1608 }
1609 else
1610 ignore_slash_options(scan_state);
1611
1612 return PSQL_CMD_SKIP_LINE;
1613}
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7643
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7651
int32 encoding
Definition: pg_database.h:41
#define pg_encoding_to_char
Definition: pg_wchar.h:630
void setFmtEncoding(int encoding)
Definition: string_utils.c:69
VariableSpace vars
Definition: settings.h:151
int encoding
Definition: print.h:138
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:281

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(), setFmtEncoding(), 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 2267 of file command.c.

2269{
2270 bool success = true;
2271
2272 switch (conditional_stack_peek(cstack))
2273 {
2274 case IFSTATE_TRUE:
2275 case IFSTATE_ELSE_TRUE:
2276 /* Close the \if block, keeping the query text */
2278 Assert(success);
2279 break;
2280 case IFSTATE_FALSE:
2281 case IFSTATE_IGNORED:
2282 case IFSTATE_ELSE_FALSE:
2283
2284 /*
2285 * Discard any query text added by the just-skipped branch.
2286 */
2287 discard_query_text(scan_state, cstack, query_buf);
2288
2289 /* Close the \if block */
2291 Assert(success);
2292 break;
2293 case IFSTATE_NONE:
2294 /* no \if to end */
2295 pg_log_error("\\endif: no matching \\if");
2296 success = false;
2297 break;
2298 }
2299
2301}
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_endpipeline()

static backslashResult exec_command_endpipeline ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 3044 of file command.c.

3045{
3047
3048 if (active_branch)
3049 {
3051 status = PSQL_CMD_SEND;
3052 }
3053 else
3054 ignore_slash_options(scan_state);
3055
3056 return status;
3057}
@ PSQL_SEND_END_PIPELINE_MODE
Definition: settings.h:80

References ignore_slash_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_END_PIPELINE_MODE, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_errverbose()

static backslashResult exec_command_errverbose ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1619 of file command.c.

1620{
1621 if (active_branch)
1622 {
1624 {
1625 char *msg;
1626
1630 if (msg)
1631 {
1632 pg_log_error("%s", msg);
1633 PQfreemem(msg);
1634 }
1635 else
1636 puts(_("out of memory"));
1637 }
1638 else
1639 puts(_("There is no previous error."));
1640 }
1641
1642 return PSQL_CMD_SKIP_LINE;
1643}
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3435
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:166
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:158
PGresult * last_error_result
Definition: settings.h:110

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

1650{
1651 bool success = true;
1652
1653 if (active_branch)
1654 {
1655 char *fname = psql_scan_slash_option(scan_state,
1656 OT_NORMAL, NULL, false);
1657
1658 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1659 free(fname);
1660 }
1661 else
1662 ignore_slash_options(scan_state);
1663
1665}

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

static backslashResult exec_command_flush ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1671 of file command.c.

1672{
1674
1675 if (active_branch)
1676 {
1678 status = PSQL_CMD_SEND;
1679 }
1680 else
1681 ignore_slash_options(scan_state);
1682
1683 return status;
1684}
@ PSQL_SEND_FLUSH
Definition: settings.h:81

References ignore_slash_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_FLUSH, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_flushrequest()

static backslashResult exec_command_flushrequest ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1690 of file command.c.

1691{
1693
1694 if (active_branch)
1695 {
1697 status = PSQL_CMD_SEND;
1698 }
1699 else
1700 ignore_slash_options(scan_state);
1701
1702 return status;
1703}
@ PSQL_SEND_FLUSH_REQUEST
Definition: settings.h:82

References ignore_slash_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_FLUSH_REQUEST, and _psqlSettings::send_mode.

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

1716{
1718 char *fname;
1719
1720 /*
1721 * Because the option processing for this is fairly complicated, we do it
1722 * and then decide whether the branch is active.
1723 */
1724 fname = psql_scan_slash_option(scan_state,
1725 OT_FILEPIPE, NULL, false);
1726
1727 if (fname && fname[0] == '(')
1728 {
1729 /* Consume pset options through trailing ')' ... */
1730 status = process_command_g_options(fname + 1, scan_state,
1731 active_branch, cmd);
1732 free(fname);
1733 /* ... and again attempt to scan the filename. */
1734 fname = psql_scan_slash_option(scan_state,
1735 OT_FILEPIPE, NULL, false);
1736 }
1737
1738 if (status == PSQL_CMD_SKIP_LINE && active_branch)
1739 {
1741 {
1742 pg_log_error("\\%s not allowed in pipeline mode", cmd);
1744 free(fname);
1745 return PSQL_CMD_ERROR;
1746 }
1747
1748 if (!fname)
1749 pset.gfname = NULL;
1750 else
1751 {
1752 expand_tilde(&fname);
1753 pset.gfname = pg_strdup(fname);
1754 }
1755 if (strcmp(cmd, "gx") == 0)
1756 {
1757 /* save settings if not done already, then force expanded=on */
1758 if (pset.gsavepopt == NULL)
1760 pset.popt.topt.expanded = 1;
1761 }
1762 status = PSQL_CMD_SEND;
1763 }
1764
1765 free(fname);
1766
1767 return status;
1768}
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:5524
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1776
PGpipelineStatus PQpipelineStatus(const PGconn *conn)
Definition: fe-connect.c:7597
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:187
@ OT_FILEPIPE
Definition: psqlscanslash.h:20
printQueryOpt * gsavepopt
Definition: settings.h:115
char * gfname
Definition: settings.h:114

References clean_extended_state(), _psqlSettings::db, expand_tilde(), printTableOpt::expanded, free, _psqlSettings::gfname, _psqlSettings::gsavepopt, OT_FILEPIPE, pg_log_error, pg_strdup(), _psqlSettings::popt, PQ_PIPELINE_OFF, PQpipelineStatus(), process_command_g_options(), pset, PSQL_CMD_ERROR, 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 1851 of file command.c.

1852{
1854
1855 if (active_branch)
1856 {
1857 pset.gdesc_flag = true;
1858 status = PSQL_CMD_SEND;
1859 }
1860
1861 return status;
1862}
bool gdesc_flag
Definition: settings.h:118

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

1870{
1871 bool success = true;
1872
1873 if (active_branch)
1874 {
1875 char *myvar = psql_scan_slash_option(scan_state,
1876 OT_NORMAL, NULL, false);
1877 char *envvar = psql_scan_slash_option(scan_state,
1878 OT_NORMAL, NULL, false);
1879
1880 if (!myvar || !envvar)
1881 {
1882 pg_log_error("\\%s: missing required argument", cmd);
1883 success = false;
1884 }
1885 else
1886 {
1887 char *envval = getenv(envvar);
1888
1889 if (envval && !SetVariable(pset.vars, myvar, envval))
1890 success = false;
1891 }
1892 free(myvar);
1893 free(envvar);
1894 }
1895 else
1896 ignore_slash_options(scan_state);
1897
1899}

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

static backslashResult exec_command_getresults ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1905 of file command.c.

1906{
1908
1909 if (active_branch)
1910 {
1911 char *opt;
1912 int num_results;
1913
1915 status = PSQL_CMD_SEND;
1916 opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1917
1919 if (opt != NULL)
1920 {
1921 num_results = atoi(opt);
1922 if (num_results < 0)
1923 {
1924 pg_log_error("\\getresults: invalid number of requested results");
1925 return PSQL_CMD_SKIP_LINE;
1926 }
1927 pset.requested_results = num_results;
1928 }
1929 }
1930 else
1931 ignore_slash_options(scan_state);
1932
1933 return status;
1934}
@ PSQL_SEND_GET_RESULTS
Definition: settings.h:83
int requested_results
Definition: settings.h:129

References ignore_slash_options(), OT_NORMAL, pg_log_error, pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), PSQL_SEND_GET_RESULTS, _psqlSettings::requested_results, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_gexec()

static backslashResult exec_command_gexec ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1941 of file command.c.

1942{
1944
1945 if (active_branch)
1946 {
1948 {
1949 pg_log_error("\\gexec not allowed in pipeline mode");
1951 return PSQL_CMD_ERROR;
1952 }
1953 pset.gexec_flag = true;
1954 status = PSQL_CMD_SEND;
1955 }
1956
1957 return status;
1958}
bool gexec_flag
Definition: settings.h:119

References clean_extended_state(), _psqlSettings::db, _psqlSettings::gexec_flag, pg_log_error, PQ_PIPELINE_OFF, PQpipelineStatus(), pset, PSQL_CMD_ERROR, 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 1964 of file command.c.

1965{
1967
1968 if (active_branch)
1969 {
1970 char *prefix = psql_scan_slash_option(scan_state,
1971 OT_NORMAL, NULL, false);
1972
1974 {
1975 pg_log_error("\\gset not allowed in pipeline mode");
1977 return PSQL_CMD_ERROR;
1978 }
1979
1980 if (prefix)
1981 pset.gset_prefix = prefix;
1982 else
1983 {
1984 /* we must set a non-NULL prefix to trigger storing */
1986 }
1987 /* gset_prefix is freed later */
1988 status = PSQL_CMD_SEND;
1989 }
1990 else
1991 ignore_slash_options(scan_state);
1992
1993 return status;
1994}
char * gset_prefix
Definition: settings.h:117

References clean_extended_state(), _psqlSettings::db, _psqlSettings::gset_prefix, ignore_slash_options(), OT_NORMAL, pg_log_error, pg_strdup(), PQ_PIPELINE_OFF, PQpipelineStatus(), pset, PSQL_CMD_ERROR, 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 2000 of file command.c.

2001{
2002 if (active_branch)
2003 {
2004 char *opt = psql_scan_slash_option(scan_state,
2005 OT_WHOLE_LINE, NULL, true);
2006
2007 helpSQL(opt, pset.popt.topt.pager);
2008 free(opt);
2009 }
2010 else
2011 ignore_slash_whole_line(scan_state);
2012
2013 return PSQL_CMD_SKIP_LINE;
2014}
void helpSQL(const char *topic, unsigned short int pager)
Definition: help.c:581

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

2021{
2022 bool success = true;
2023
2024 if (active_branch)
2025 {
2027 success = do_pset("format", "html", &pset.popt, pset.quiet);
2028 else
2029 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
2030 }
2031
2033}

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

2082{
2083 if (conditional_active(cstack))
2084 {
2085 /*
2086 * First, push a new active stack entry; this ensures that the lexer
2087 * will perform variable substitution and backtick evaluation while
2088 * scanning the expression. (That should happen anyway, since we know
2089 * we're in an active outer branch, but let's be sure.)
2090 */
2092
2093 /* Remember current query state in case we need to restore later */
2094 save_query_text_state(scan_state, cstack, query_buf);
2095
2096 /*
2097 * Evaluate the expression; if it's false, change to inactive state.
2098 */
2099 if (!is_true_boolean_expression(scan_state, "\\if expression"))
2101 }
2102 else
2103 {
2104 /*
2105 * We're within an inactive outer branch, so this entire \if block
2106 * will be ignored. We don't want to evaluate the expression, so push
2107 * the "ignored" stack state before scanning it.
2108 */
2110
2111 /* Remember current query state in case we need to restore later */
2112 save_query_text_state(scan_state, cstack, query_buf);
2113
2114 ignore_boolean_expression(scan_state);
2115 }
2116
2117 return PSQL_CMD_SKIP_LINE;
2118}
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 2039 of file command.c.

2040{
2041 bool success = true;
2042
2043 if (active_branch)
2044 {
2045 char *fname = psql_scan_slash_option(scan_state,
2046 OT_NORMAL, NULL, true);
2047
2048 if (!fname)
2049 {
2050 pg_log_error("\\%s: missing required argument", cmd);
2051 success = false;
2052 }
2053 else
2054 {
2055 bool include_relative;
2056
2057 include_relative = (strcmp(cmd, "ir") == 0
2058 || strcmp(cmd, "include_relative") == 0);
2059 expand_tilde(&fname);
2060 success = (process_file(fname, include_relative) == EXIT_SUCCESS);
2061 free(fname);
2062 }
2063 }
2064 else
2065 ignore_slash_options(scan_state);
2066
2068}
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4818
#define EXIT_SUCCESS
Definition: settings.h:193

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

2308{
2309 bool success = true;
2310
2311 if (active_branch)
2312 {
2313 char *pattern;
2314 bool show_verbose;
2315 unsigned short int save_expanded;
2316
2317 pattern = psql_scan_slash_option(scan_state,
2318 OT_NORMAL, NULL, true);
2319
2320 show_verbose = strchr(cmd, '+') ? true : false;
2321
2322 /* if 'x' option specified, force expanded mode */
2323 save_expanded = pset.popt.topt.expanded;
2324 if (strchr(cmd, 'x'))
2325 pset.popt.topt.expanded = 1;
2326
2327 success = listAllDbs(pattern, show_verbose);
2328
2329 /* restore original expanded mode */
2330 pset.popt.topt.expanded = save_expanded;
2331
2332 free(pattern);
2333 }
2334 else
2335 ignore_slash_options(scan_state);
2336
2338}
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:945

References printTableOpt::expanded, free, ignore_slash_options(), listAllDbs(), OT_NORMAL, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), success, printQueryOpt::topt, 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 2344 of file command.c.

2345{
2347 bool success = true;
2348
2349 if (active_branch)
2350 {
2351 char *opt1,
2352 *opt2;
2353
2354 opt1 = psql_scan_slash_option(scan_state,
2355 OT_NORMAL, NULL, true);
2356 opt2 = psql_scan_slash_option(scan_state,
2357 OT_NORMAL, NULL, true);
2358
2359 if (strcmp(cmd + 3, "export") == 0)
2360 {
2361 if (!opt2)
2362 {
2363 pg_log_error("\\%s: missing required argument", cmd);
2364 success = false;
2365 }
2366 else
2367 {
2368 expand_tilde(&opt2);
2369 success = do_lo_export(opt1, opt2);
2370 }
2371 }
2372
2373 else if (strcmp(cmd + 3, "import") == 0)
2374 {
2375 if (!opt1)
2376 {
2377 pg_log_error("\\%s: missing required argument", cmd);
2378 success = false;
2379 }
2380 else
2381 {
2382 expand_tilde(&opt1);
2383 success = do_lo_import(opt1, opt2);
2384 }
2385 }
2386
2387 else if (strncmp(cmd + 3, "list", 4) == 0)
2388 {
2389 bool show_verbose;
2390 unsigned short int save_expanded;
2391
2392 show_verbose = strchr(cmd, '+') ? true : false;
2393
2394 /* if 'x' option specified, force expanded mode */
2395 save_expanded = pset.popt.topt.expanded;
2396 if (strchr(cmd, 'x'))
2397 pset.popt.topt.expanded = 1;
2398
2399 success = listLargeObjects(show_verbose);
2400
2401 /* restore original expanded mode */
2402 pset.popt.topt.expanded = save_expanded;
2403 }
2404
2405 else if (strcmp(cmd + 3, "unlink") == 0)
2406 {
2407 if (!opt1)
2408 {
2409 pg_log_error("\\%s: missing required argument", cmd);
2410 success = false;
2411 }
2412 else
2413 success = do_lo_unlink(opt1);
2414 }
2415
2416 else
2417 status = PSQL_CMD_UNKNOWN;
2418
2419 free(opt1);
2420 free(opt2);
2421 }
2422 else
2423 ignore_slash_options(scan_state);
2424
2425 if (!success)
2426 status = PSQL_CMD_ERROR;
2427
2428 return status;
2429}
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(), printTableOpt::expanded, free, ignore_slash_options(), listLargeObjects(), OT_NORMAL, pg_log_error, _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, PSQL_CMD_UNKNOWN, psql_scan_slash_option(), success, printQueryOpt::topt, and true.

Referenced by exec_command().

◆ exec_command_out()

static backslashResult exec_command_out ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2435 of file command.c.

2436{
2437 bool success = true;
2438
2439 if (active_branch)
2440 {
2441 char *fname = psql_scan_slash_option(scan_state,
2442 OT_FILEPIPE, NULL, true);
2443
2444 expand_tilde(&fname);
2445 success = setQFout(fname);
2446 free(fname);
2447 }
2448 else
2449 ignore_slash_filepipe(scan_state);
2450
2452}
bool setQFout(const char *fname)
Definition: common.c:144
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:3659

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

2486{
2488
2489 if (active_branch)
2490 {
2491 char *opt = psql_scan_slash_option(scan_state,
2492 OT_NORMAL, NULL, false);
2493
2495
2496 if (!opt)
2497 {
2498 pg_log_error("\\%s: missing required argument", cmd);
2499 status = PSQL_CMD_ERROR;
2500 }
2501 else
2502 {
2503 pset.stmtName = opt;
2505 status = PSQL_CMD_SEND;
2506 }
2507 }
2508 else
2509 ignore_slash_options(scan_state);
2510
2511 return status;
2512}
@ PSQL_SEND_EXTENDED_PARSE
Definition: settings.h:75

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

2519{
2520 bool success = true;
2521
2522 if (active_branch)
2523 {
2524 char *user = psql_scan_slash_option(scan_state,
2525 OT_SQLID, NULL, true);
2526 char *pw1 = NULL;
2527 char *pw2 = NULL;
2529 PromptInterruptContext prompt_ctx;
2530
2531 if (user == NULL)
2532 {
2533 /* By default, the command applies to CURRENT_USER */
2534 PGresult *res;
2535
2536 res = PSQLexec("SELECT CURRENT_USER");
2537 if (!res)
2538 return PSQL_CMD_ERROR;
2539
2540 user = pg_strdup(PQgetvalue(res, 0, 0));
2541 PQclear(res);
2542 }
2543
2544 /* Set up to let SIGINT cancel simple_prompt_extended() */
2545 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2546 prompt_ctx.enabled = &sigint_interrupt_enabled;
2547 prompt_ctx.canceled = false;
2548
2550 printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2551
2552 pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2553 if (!prompt_ctx.canceled)
2554 pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2555
2556 if (prompt_ctx.canceled)
2557 {
2558 /* fail silently */
2559 success = false;
2560 }
2561 else if (strcmp(pw1, pw2) != 0)
2562 {
2563 pg_log_error("Passwords didn't match.");
2564 success = false;
2565 }
2566 else
2567 {
2568 PGresult *res = PQchangePassword(pset.db, user, pw1);
2569
2570 if (PQresultStatus(res) != PGRES_COMMAND_OK)
2571 {
2573 success = false;
2574 }
2575
2576 PQclear(res);
2577 }
2578
2579 free(user);
2580 free(pw1);
2581 free(pw2);
2583 }
2584 else
2585 ignore_slash_options(scan_state);
2586
2588}
PGresult * PSQLexec(const char *query)
Definition: common.c:655
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:304
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:306
PGresult * PQchangePassword(PGconn *conn, const char *user, const char *passwd)
Definition: fe-auth.c:1531
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
void PQclear(PGresult *res)
Definition: fe-exec.c:721
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
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(), 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 2458 of file command.c.

2460{
2461 if (active_branch)
2462 {
2463 /*
2464 * We want to print the same thing \g would execute, but not to change
2465 * the query buffer state; so we can't use copy_previous_query().
2466 * Also, beware of possibility that buffer pointers are NULL.
2467 */
2468 if (query_buf && query_buf->len > 0)
2469 puts(query_buf->data);
2470 else if (previous_buf && previous_buf->len > 0)
2471 puts(previous_buf->data);
2472 else if (!pset.quiet)
2473 puts(_("Query buffer is empty."));
2474 fflush(stdout);
2475 }
2476
2477 return PSQL_CMD_SKIP_LINE;
2478}

References _, PQExpBufferData::data, 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 2594 of file command.c.

2596{
2597 bool success = true;
2598
2599 if (active_branch)
2600 {
2601 char *opt,
2602 *prompt_text = NULL;
2603 char *arg1,
2604 *arg2;
2605
2606 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2607 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2608
2609 if (!arg1)
2610 {
2611 pg_log_error("\\%s: missing required argument", cmd);
2612 success = false;
2613 }
2614 else
2615 {
2616 char *result;
2617 PromptInterruptContext prompt_ctx;
2618
2619 /* Set up to let SIGINT cancel simple_prompt_extended() */
2620 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2621 prompt_ctx.enabled = &sigint_interrupt_enabled;
2622 prompt_ctx.canceled = false;
2623
2624 if (arg2)
2625 {
2626 prompt_text = arg1;
2627 opt = arg2;
2628 }
2629 else
2630 opt = arg1;
2631
2632 if (!pset.inputfile)
2633 {
2634 result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2635 }
2636 else
2637 {
2638 if (prompt_text)
2639 {
2640 fputs(prompt_text, stdout);
2641 fflush(stdout);
2642 }
2643 result = gets_fromFile(stdin);
2644 if (!result)
2645 {
2646 pg_log_error("\\%s: could not read value for variable",
2647 cmd);
2648 success = false;
2649 }
2650 }
2651
2652 if (prompt_ctx.canceled ||
2653 (result && !SetVariable(pset.vars, opt, result)))
2654 success = false;
2655
2656 free(result);
2657 free(prompt_text);
2658 free(opt);
2659 }
2660 }
2661 else
2662 ignore_slash_options(scan_state);
2663
2665}
char * gets_fromFile(FILE *source)
Definition: input.c:186
char * inputfile
Definition: settings.h:143

References PromptInterruptContext::canceled, PromptInterruptContext::enabled, 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 2671 of file command.c.

2672{
2673 bool success = true;
2674
2675 if (active_branch)
2676 {
2677 char *opt0 = psql_scan_slash_option(scan_state,
2678 OT_NORMAL, NULL, false);
2679 char *opt1 = psql_scan_slash_option(scan_state,
2680 OT_NORMAL, NULL, false);
2681
2682 if (!opt0)
2683 {
2684 /* list all variables */
2685
2686 int i;
2687 static const char *const my_list[] = {
2688 "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2689 "fieldsep_zero", "footer", "format", "linestyle", "null",
2690 "numericlocale", "pager", "pager_min_lines",
2691 "recordsep", "recordsep_zero",
2692 "tableattr", "title", "tuples_only",
2693 "unicode_border_linestyle",
2694 "unicode_column_linestyle",
2695 "unicode_header_linestyle",
2696 "xheader_width",
2697 NULL
2698 };
2699
2700 for (i = 0; my_list[i] != NULL; i++)
2701 {
2702 char *val = pset_value_string(my_list[i], &pset.popt);
2703
2704 printf("%-24s %s\n", my_list[i], val);
2705 free(val);
2706 }
2707
2708 success = true;
2709 }
2710 else
2711 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2712
2713 free(opt0);
2714 free(opt1);
2715 }
2716 else
2717 ignore_slash_options(scan_state);
2718
2720}
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:5631
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 2726 of file command.c.

2727{
2729
2730 if (active_branch)
2731 status = PSQL_CMD_TERMINATE;
2732
2733 return status;
2734}
@ 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 2740 of file command.c.

2742{
2743 if (active_branch)
2744 {
2745 resetPQExpBuffer(query_buf);
2746 psql_scan_reset(scan_state);
2747 if (!pset.quiet)
2748 puts(_("Query buffer reset (cleared)."));
2749 }
2750
2751 return PSQL_CMD_SKIP_LINE;
2752}
void psql_scan_reset(PsqlScanState state)
Definition: psqlscan.l:1275

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

2759{
2760 bool success = true;
2761
2762 if (active_branch)
2763 {
2764 char *fname = psql_scan_slash_option(scan_state,
2765 OT_NORMAL, NULL, true);
2766
2767 expand_tilde(&fname);
2769 if (success && !pset.quiet && fname)
2770 printf(_("Wrote history to file \"%s\".\n"), fname);
2771 if (!fname)
2772 putchar('\n');
2773 free(fname);
2774 }
2775 else
2776 ignore_slash_options(scan_state);
2777
2779}
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_sendpipeline()

static backslashResult exec_command_sendpipeline ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2785 of file command.c.

2786{
2788
2789 if (active_branch)
2790 {
2792 {
2795 {
2796 status = PSQL_CMD_SEND;
2797 }
2798 else
2799 {
2800 pg_log_error("\\sendpipeline must be used after \\bind or \\bind_named");
2802 return PSQL_CMD_ERROR;
2803 }
2804 }
2805 else
2806 {
2807 pg_log_error("\\sendpipeline not allowed outside of pipeline mode");
2809 return PSQL_CMD_ERROR;
2810 }
2811 }
2812 else
2813 ignore_slash_options(scan_state);
2814
2815 return status;
2816}

References clean_extended_state(), _psqlSettings::db, ignore_slash_options(), pg_log_error, PQ_PIPELINE_OFF, PQpipelineStatus(), pset, PSQL_CMD_ERROR, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_EXTENDED_QUERY_PARAMS, PSQL_SEND_EXTENDED_QUERY_PREPARED, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2822 of file command.c.

2823{
2824 bool success = true;
2825
2826 if (active_branch)
2827 {
2828 char *opt0 = psql_scan_slash_option(scan_state,
2829 OT_NORMAL, NULL, false);
2830
2831 if (!opt0)
2832 {
2833 /* list all variables */
2835 success = true;
2836 }
2837 else
2838 {
2839 /*
2840 * Set variable to the concatenation of the arguments.
2841 */
2842 char *newval;
2843 char *opt;
2844
2845 opt = psql_scan_slash_option(scan_state,
2846 OT_NORMAL, NULL, false);
2847 newval = pg_strdup(opt ? opt : "");
2848 free(opt);
2849
2850 while ((opt = psql_scan_slash_option(scan_state,
2851 OT_NORMAL, NULL, false)))
2852 {
2853 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2854 strcat(newval, opt);
2855 free(opt);
2856 }
2857
2858 if (!SetVariable(pset.vars, opt0, newval))
2859 success = false;
2860
2861 free(newval);
2862 }
2863 free(opt0);
2864 }
2865 else
2866 ignore_slash_options(scan_state);
2867
2869}
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define newval
void PrintVariables(VariableSpace space)
Definition: variables.c:256

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

2877{
2878 bool success = true;
2879
2880 if (active_branch)
2881 {
2882 char *envvar = psql_scan_slash_option(scan_state,
2883 OT_NORMAL, NULL, false);
2884 char *envval = psql_scan_slash_option(scan_state,
2885 OT_NORMAL, NULL, false);
2886
2887 if (!envvar)
2888 {
2889 pg_log_error("\\%s: missing required argument", cmd);
2890 success = false;
2891 }
2892 else if (strchr(envvar, '=') != NULL)
2893 {
2894 pg_log_error("\\%s: environment variable name must not contain \"=\"",
2895 cmd);
2896 success = false;
2897 }
2898 else if (!envval)
2899 {
2900 /* No argument - unset the environment variable */
2901 unsetenv(envvar);
2902 success = true;
2903 }
2904 else
2905 {
2906 /* Set variable to the value of the next argument */
2907 setenv(envvar, envval, 1);
2908 success = true;
2909 }
2910 free(envvar);
2911 free(envval);
2912 }
2913 else
2914 ignore_slash_options(scan_state);
2915
2917}
#define unsetenv(x)
Definition: win32_port.h:546
#define setenv(x, y, z)
Definition: win32_port.h:545

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

2925{
2927
2928 if (active_branch)
2929 {
2930 bool show_linenumbers = (strchr(cmd, '+') != NULL);
2932 char *obj_desc;
2933 Oid obj_oid = InvalidOid;
2935
2937 obj_desc = psql_scan_slash_option(scan_state,
2938 OT_WHOLE_LINE, NULL, true);
2939 if (!obj_desc)
2940 {
2941 if (is_func)
2942 pg_log_error("function name is required");
2943 else
2944 pg_log_error("view name is required");
2945 status = PSQL_CMD_ERROR;
2946 }
2947 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2948 {
2949 /* error already reported */
2950 status = PSQL_CMD_ERROR;
2951 }
2952 else if (!get_create_object_cmd(eot, obj_oid, buf))
2953 {
2954 /* error already reported */
2955 status = PSQL_CMD_ERROR;
2956 }
2957 else
2958 {
2959 FILE *output;
2960 bool is_pager;
2961
2962 /* Select output stream: stdout, pager, or file */
2963 if (pset.queryFout == stdout)
2964 {
2965 /* count lines in function to see if pager is needed */
2966 int lineno = count_lines_in_buf(buf);
2967
2968 output = PageOutput(lineno, &(pset.popt.topt));
2969 is_pager = true;
2970 }
2971 else
2972 {
2973 /* use previously set output file, without pager */
2975 is_pager = false;
2976 }
2977
2978 if (show_linenumbers)
2979 {
2980 /* add line numbers */
2981 print_with_linenumbers(output, buf->data, is_func);
2982 }
2983 else
2984 {
2985 /* just send the definition to output */
2986 fputs(buf->data, output);
2987 }
2988
2989 if (is_pager)
2991 }
2992
2993 free(obj_desc);
2995 }
2996 else
2997 ignore_slash_whole_line(scan_state);
2998
2999 return status;
3000}
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:6322
static void print_with_linenumbers(FILE *output, char *lines, bool is_func)
Definition: command.c:6352
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:3089
void ClosePager(FILE *pagerpipe)
Definition: print.c:3141
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 3486 of file command.c.

3487{
3488 bool success = true;
3489
3490 if (active_branch)
3491 {
3492 char *opt = psql_scan_slash_option(scan_state,
3493 OT_WHOLE_LINE, NULL, false);
3494
3495 success = do_shell(opt);
3496 free(opt);
3497 }
3498 else
3499 ignore_slash_whole_line(scan_state);
3500
3502}
static bool do_shell(const char *command)
Definition: command.c:5720

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

3509{
3510 if (active_branch)
3511 {
3512 char *opt0 = psql_scan_slash_option(scan_state,
3513 OT_NORMAL, NULL, false);
3514
3515 if (!opt0 || strcmp(opt0, "commands") == 0)
3517 else if (strcmp(opt0, "options") == 0)
3519 else if (strcmp(opt0, "variables") == 0)
3521 else
3523
3524 free(opt0);
3525 }
3526 else
3527 ignore_slash_options(scan_state);
3528
3529 return PSQL_CMD_SKIP_LINE;
3530}
void helpVariables(unsigned short int pager)
Definition: help.c:366
void slashUsage(unsigned short int pager)
Definition: help.c:148
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_startpipeline()

static backslashResult exec_command_startpipeline ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 3006 of file command.c.

3007{
3009
3010 if (active_branch)
3011 {
3013 status = PSQL_CMD_SEND;
3014 }
3015 else
3016 ignore_slash_options(scan_state);
3017
3018 return status;
3019}
@ PSQL_SEND_START_PIPELINE_MODE
Definition: settings.h:79

References ignore_slash_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_START_PIPELINE_MODE, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_syncpipeline()

static backslashResult exec_command_syncpipeline ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 3025 of file command.c.

3026{
3028
3029 if (active_branch)
3030 {
3032 status = PSQL_CMD_SEND;
3033 }
3034 else
3035 ignore_slash_options(scan_state);
3036
3037 return status;
3038}
@ PSQL_SEND_PIPELINE_SYNC
Definition: settings.h:78

References ignore_slash_options(), pset, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_SEND_PIPELINE_SYNC, and _psqlSettings::send_mode.

Referenced by exec_command().

◆ exec_command_t()

static backslashResult exec_command_t ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 3063 of file command.c.

3064{
3065 bool success = true;
3066
3067 if (active_branch)
3068 {
3069 char *opt = psql_scan_slash_option(scan_state,
3070 OT_NORMAL, NULL, true);
3071
3072 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
3073 free(opt);
3074 }
3075 else
3076 ignore_slash_options(scan_state);
3077
3079}

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

3086{
3087 bool success = true;
3088
3089 if (active_branch)
3090 {
3091 char *value = psql_scan_slash_option(scan_state,
3092 OT_NORMAL, NULL, false);
3093
3094 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
3095 free(value);
3096 }
3097 else
3098 ignore_slash_options(scan_state);
3099
3101}

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

3108{
3109 bool success = true;
3110
3111 if (active_branch)
3112 {
3113 char *opt = psql_scan_slash_option(scan_state,
3114 OT_NORMAL, NULL, false);
3115
3116 if (opt)
3117 success = ParseVariableBool(opt, "\\timing", &pset.timing);
3118 else
3120 if (!pset.quiet)
3121 {
3122 if (pset.timing)
3123 puts(_("Timing is on."));
3124 else
3125 puts(_("Timing is off."));
3126 }
3127 free(opt);
3128 }
3129 else
3130 ignore_slash_options(scan_state);
3131
3133}

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

3141{
3142 bool success = true;
3143
3144 if (active_branch)
3145 {
3146 char *opt = psql_scan_slash_option(scan_state,
3147 OT_NORMAL, NULL, false);
3148
3149 if (!opt)
3150 {
3151 pg_log_error("\\%s: missing required argument", cmd);
3152 success = false;
3153 }
3154 else if (!SetVariable(pset.vars, opt, NULL))
3155 success = false;
3156
3157 free(opt);
3158 }
3159 else
3160 ignore_slash_options(scan_state);
3161
3163}

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

3273{
3274 bool success = true;
3275
3276 if (active_branch)
3277 {
3278 bool have_sleep = false;
3279 bool have_iter = false;
3280 bool have_min_rows = false;
3281 double sleep = pset.watch_interval;
3282 int iter = 0;
3283 int min_rows = 0;
3284
3286 {
3287 pg_log_error("\\watch not allowed in pipeline mode");
3289 success = false;
3290 }
3291
3292 /*
3293 * Parse arguments. We allow either an unlabeled interval or
3294 * "name=value", where name is from the set ('i', 'interval', 'c',
3295 * 'count', 'm', 'min_rows'). The parsing of interval value should be
3296 * kept in sync with ParseVariableDouble which is used for setting the
3297 * default interval value.
3298 */
3299 while (success)
3300 {
3301 char *opt = psql_scan_slash_option(scan_state,
3302 OT_NORMAL, NULL, true);
3303 char *valptr;
3304 char *opt_end;
3305
3306 if (!opt)
3307 break; /* no more arguments */
3308
3309 valptr = strchr(opt, '=');
3310 if (valptr)
3311 {
3312 /* Labeled argument */
3313 valptr++;
3314 if (strncmp("i=", opt, strlen("i=")) == 0 ||
3315 strncmp("interval=", opt, strlen("interval=")) == 0)
3316 {
3317 if (have_sleep)
3318 {
3319 pg_log_error("\\watch: interval value is specified more than once");
3320 success = false;
3321 }
3322 else
3323 {
3324 have_sleep = true;
3325 errno = 0;
3326 sleep = strtod(valptr, &opt_end);
3327 if (sleep < 0 || *opt_end || errno == ERANGE)
3328 {
3329 pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
3330 success = false;
3331 }
3332 }
3333 }
3334 else if (strncmp("c=", opt, strlen("c=")) == 0 ||
3335 strncmp("count=", opt, strlen("count=")) == 0)
3336 {
3337 if (have_iter)
3338 {
3339 pg_log_error("\\watch: iteration count is specified more than once");
3340 success = false;
3341 }
3342 else
3343 {
3344 have_iter = true;
3345 errno = 0;
3346 iter = strtoint(valptr, &opt_end, 10);
3347 if (iter <= 0 || *opt_end || errno == ERANGE)
3348 {
3349 pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
3350 success = false;
3351 }
3352 }
3353 }
3354 else if (strncmp("m=", opt, strlen("m=")) == 0 ||
3355 strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
3356 {
3357 if (have_min_rows)
3358 {
3359 pg_log_error("\\watch: minimum row count specified more than once");
3360 success = false;
3361 }
3362 else
3363 {
3364 have_min_rows = true;
3365 errno = 0;
3366 min_rows = strtoint(valptr, &opt_end, 10);
3367 if (min_rows <= 0 || *opt_end || errno == ERANGE)
3368 {
3369 pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
3370 success = false;
3371 }
3372 }
3373 }
3374 else
3375 {
3376 pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
3377 success = false;
3378 }
3379 }
3380 else
3381 {
3382 /* Unlabeled argument: take it as interval */
3383 if (have_sleep)
3384 {
3385 pg_log_error("\\watch: interval value is specified more than once");
3386 success = false;
3387 }
3388 else
3389 {
3390 have_sleep = true;
3391 errno = 0;
3392 sleep = strtod(opt, &opt_end);
3393 if (sleep < 0 || *opt_end || errno == ERANGE)
3394 {
3395 pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3396 success = false;
3397 }
3398 }
3399 }
3400
3401 free(opt);
3402 }
3403
3404 /* If we parsed arguments successfully, do the command */
3405 if (success)
3406 {
3407 /* If query_buf is empty, recall and execute previous query */
3408 (void) copy_previous_query(query_buf, previous_buf);
3409
3410 success = do_watch(query_buf, sleep, iter, min_rows);
3411 }
3412
3413 /* Reset the query buffer as though for \r */
3414 resetPQExpBuffer(query_buf);
3415 psql_scan_reset(scan_state);
3416 }
3417 else
3418 ignore_slash_options(scan_state);
3419
3421}
static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
Definition: command.c:5771
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
Definition: string.c:50
double watch_interval
Definition: settings.h:175

References clean_extended_state(), copy_previous_query(), _psqlSettings::db, do_watch(), free, ignore_slash_options(), OT_NORMAL, pg_log_error, PQ_PIPELINE_OFF, PQpipelineStatus(), pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_reset(), psql_scan_slash_option(), resetPQExpBuffer(), strtoint(), success, and _psqlSettings::watch_interval.

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

3172{
3174
3175 if (active_branch)
3176 {
3177 char *fname = psql_scan_slash_option(scan_state,
3178 OT_FILEPIPE, NULL, true);
3179 FILE *fd = NULL;
3180 bool is_pipe = false;
3181
3182 if (!query_buf)
3183 {
3184 pg_log_error("no query buffer");
3185 status = PSQL_CMD_ERROR;
3186 }
3187 else
3188 {
3189 if (!fname)
3190 {
3191 pg_log_error("\\%s: missing required argument", cmd);
3192 status = PSQL_CMD_ERROR;
3193 }
3194 else
3195 {
3196 expand_tilde(&fname);
3197 if (fname[0] == '|')
3198 {
3199 is_pipe = true;
3200 fflush(NULL);
3202 fd = popen(&fname[1], "w");
3203 }
3204 else
3205 {
3207 fd = fopen(fname, "w");
3208 }
3209 if (!fd)
3210 {
3211 pg_log_error("%s: %m", fname);
3212 status = PSQL_CMD_ERROR;
3213 }
3214 }
3215 }
3216
3217 if (fd)
3218 {
3219 int result;
3220
3221 /*
3222 * We want to print the same thing \g would execute, but not to
3223 * change the query buffer state; so we can't use
3224 * copy_previous_query(). Also, beware of possibility that buffer
3225 * pointers are NULL.
3226 */
3227 if (query_buf && query_buf->len > 0)
3228 fprintf(fd, "%s\n", query_buf->data);
3229 else if (previous_buf && previous_buf->len > 0)
3230 fprintf(fd, "%s\n", previous_buf->data);
3231
3232 if (is_pipe)
3233 {
3234 result = pclose(fd);
3235
3236 if (result != 0)
3237 {
3238 pg_log_error("%s: %s", fname, wait_result_to_str(result));
3239 status = PSQL_CMD_ERROR;
3240 }
3242 }
3243 else
3244 {
3245 result = fclose(fd);
3246
3247 if (result == EOF)
3248 {
3249 pg_log_error("%s: %m", fname);
3250 status = PSQL_CMD_ERROR;
3251 }
3252 }
3253 }
3254
3255 if (is_pipe)
3257
3258 free(fname);
3259 }
3260 else
3261 ignore_slash_filepipe(scan_state);
3262
3263 return status;
3264}
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33

References canonicalize_path_enc(), PQExpBufferData::data, disable_sigpipe_trap(), _psqlSettings::encoding, expand_tilde(), fd(), fprintf, free, ignore_slash_filepipe(), PQExpBufferData::len, OT_FILEPIPE, pg_log_error, pset, 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 3427 of file command.c.

3428{
3429 bool success = true;
3430
3431 if (active_branch)
3432 {
3433 char *opt = psql_scan_slash_option(scan_state,
3434 OT_NORMAL, NULL, true);
3435
3436 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3437 free(opt);
3438 }
3439 else
3440 ignore_slash_options(scan_state);
3441
3443}

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

3450{
3451 bool success = true;
3452
3453 if (active_branch)
3454 {
3455 char *pattern;
3456 bool show_system;
3457 unsigned short int save_expanded;
3458
3459 pattern = psql_scan_slash_option(scan_state,
3460 OT_NORMAL, NULL, true);
3461
3462 show_system = strchr(cmd, 'S') ? true : false;
3463
3464 /* if 'x' option specified, force expanded mode */
3465 save_expanded = pset.popt.topt.expanded;
3466 if (strchr(cmd, 'x'))
3467 pset.popt.topt.expanded = 1;
3468
3469 success = permissionsList(pattern, show_system);
3470
3471 /* restore original expanded mode */
3472 pset.popt.topt.expanded = save_expanded;
3473
3474 free(pattern);
3475 }
3476 else
3477 ignore_slash_options(scan_state);
3478
3480}

References printTableOpt::expanded, free, ignore_slash_options(), OT_NORMAL, permissionsList(), _psqlSettings::popt, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), success, printQueryOpt::topt, and true.

Referenced by exec_command().

◆ gather_boolean_expression()

static PQExpBuffer gather_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3579 of file command.c.

3580{
3581 PQExpBuffer exp_buf = createPQExpBuffer();
3582 int num_options = 0;
3583 char *value;
3584
3585 /* collect all arguments for the conditional command into exp_buf */
3586 while ((value = psql_scan_slash_option(scan_state,
3587 OT_NORMAL, NULL, false)) != NULL)
3588 {
3589 /* add spaces between tokens */
3590 if (num_options > 0)
3591 appendPQExpBufferChar(exp_buf, ' ');
3592 appendPQExpBufferStr(exp_buf, value);
3593 num_options++;
3594 free(value);
3595 }
3596
3597 return exp_buf;
3598}

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

6106{
6107 bool result = true;
6109 PGresult *res;
6110
6111 switch (obj_type)
6112 {
6113 case EditableFunction:
6114 printfPQExpBuffer(query,
6115 "SELECT pg_catalog.pg_get_functiondef(%u)",
6116 oid);
6117 break;
6118
6119 case EditableView:
6120
6121 /*
6122 * pg_get_viewdef() just prints the query, so we must prepend
6123 * CREATE for ourselves. We must fully qualify the view name to
6124 * ensure the right view gets replaced. Also, check relation kind
6125 * to be sure it's a view.
6126 *
6127 * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
6128 * CHECK OPTION. These are not part of the view definition
6129 * returned by pg_get_viewdef() and so need to be retrieved
6130 * separately. Materialized views (introduced in 9.3) may have
6131 * arbitrary storage parameter reloptions.
6132 */
6133 if (pset.sversion >= 90400)
6134 {
6135 printfPQExpBuffer(query,
6136 "SELECT nspname, relname, relkind, "
6137 "pg_catalog.pg_get_viewdef(c.oid, true), "
6138 "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6139 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6140 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
6141 "FROM pg_catalog.pg_class c "
6142 "LEFT JOIN pg_catalog.pg_namespace n "
6143 "ON c.relnamespace = n.oid WHERE c.oid = %u",
6144 oid);
6145 }
6146 else
6147 {
6148 printfPQExpBuffer(query,
6149 "SELECT nspname, relname, relkind, "
6150 "pg_catalog.pg_get_viewdef(c.oid, true), "
6151 "c.reloptions AS reloptions, "
6152 "NULL AS checkoption "
6153 "FROM pg_catalog.pg_class c "
6154 "LEFT JOIN pg_catalog.pg_namespace n "
6155 "ON c.relnamespace = n.oid WHERE c.oid = %u",
6156 oid);
6157 }
6158 break;
6159 }
6160
6161 if (!echo_hidden_command(query->data))
6162 {
6163 destroyPQExpBuffer(query);
6164 return false;
6165 }
6166 res = PQexec(pset.db, query->data);
6167 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6168 {
6170 switch (obj_type)
6171 {
6172 case EditableFunction:
6173 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
6174 break;
6175
6176 case EditableView:
6177 {
6178 char *nspname = PQgetvalue(res, 0, 0);
6179 char *relname = PQgetvalue(res, 0, 1);
6180 char *relkind = PQgetvalue(res, 0, 2);
6181 char *viewdef = PQgetvalue(res, 0, 3);
6182 char *reloptions = PQgetvalue(res, 0, 4);
6183 char *checkoption = PQgetvalue(res, 0, 5);
6184
6185 /*
6186 * If the backend ever supports CREATE OR REPLACE
6187 * MATERIALIZED VIEW, allow that here; but as of today it
6188 * does not, so editing a matview definition in this way
6189 * is impossible.
6190 */
6191 switch (relkind[0])
6192 {
6193#ifdef NOT_USED
6194 case RELKIND_MATVIEW:
6195 appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
6196 break;
6197#endif
6198 case RELKIND_VIEW:
6199 appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
6200 break;
6201 default:
6202 pg_log_error("\"%s.%s\" is not a view",
6203 nspname, relname);
6204 result = false;
6205 break;
6206 }
6207 appendPQExpBuffer(buf, "%s.", fmtId(nspname));
6209
6210 /* reloptions, if not an empty array "{}" */
6211 if (reloptions != NULL && strlen(reloptions) > 2)
6212 {
6213 appendPQExpBufferStr(buf, "\n WITH (");
6214 if (!appendReloptionsArray(buf, reloptions, "",
6215 pset.encoding,
6217 {
6218 pg_log_error("could not parse reloptions array");
6219 result = false;
6220 }
6222 }
6223
6224 /* View definition from pg_get_viewdef (a SELECT query) */
6225 appendPQExpBuffer(buf, " AS\n%s", viewdef);
6226
6227 /* Get rid of the semicolon that pg_get_viewdef appends */
6228 if (buf->len > 0 && buf->data[buf->len - 1] == ';')
6229 buf->data[--(buf->len)] = '\0';
6230
6231 /* WITH [LOCAL|CASCADED] CHECK OPTION */
6232 if (checkoption && checkoption[0] != '\0')
6233 appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
6234 checkoption);
6235 }
6236 break;
6237 }
6238 /* Make sure result ends with a newline */
6239 if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
6241 }
6242 else
6243 {
6245 result = false;
6246 }
6247
6248 PQclear(res);
6249 destroyPQExpBuffer(query);
6250
6251 return result;
6252}
bool standard_strings(void)
Definition: common.c:2456
static bool echo_hidden_command(const char *query)
Definition: command.c:6012
static void minimal_error_message(PGresult *res)
Definition: command.c:6394
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:128
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:248
bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
Definition: string_utils.c:966

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

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

References arg, Assert(), conditional_active(), conditional_stack_pop(), conditional_stack_push(), _psqlSettings::cur_cmd_interactive, exec_command(), 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 3626 of file command.c.

3627{
3629
3631}
static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3579

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

3660{
3661 char *arg = psql_scan_slash_option(scan_state,
3662 OT_FILEPIPE, NULL, false);
3663
3664 free(arg);
3665}

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

3680{
3681 char *arg = psql_scan_slash_option(scan_state,
3682 OT_WHOLE_LINE, NULL, false);
3683
3684 free(arg);
3685}

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

3692{
3693 return (strcmp(cmd, "if") == 0 ||
3694 strcmp(cmd, "elif") == 0 ||
3695 strcmp(cmd, "else") == 0 ||
3696 strcmp(cmd, "endif") == 0);
3697}

Referenced by exec_command().

◆ is_true_boolean_expression()

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

Definition at line 3609 of file command.c.

3610{
3612 bool value = false;
3613 bool success = ParseVariableBool(buf->data, name, &value);
3614
3616 return success && value;
3617}

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

6046{
6047 bool result = true;
6049 PGresult *res;
6050
6051 switch (obj_type)
6052 {
6053 case EditableFunction:
6054
6055 /*
6056 * We have a function description, e.g. "x" or "x(int)". Issue a
6057 * query to retrieve the function's OID using a cast to regproc or
6058 * regprocedure (as appropriate).
6059 */
6060 appendPQExpBufferStr(query, "SELECT ");
6061 appendStringLiteralConn(query, desc, pset.db);
6062 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
6063 strchr(desc, '(') ? "regprocedure" : "regproc");
6064 break;
6065
6066 case EditableView:
6067
6068 /*
6069 * Convert view name (possibly schema-qualified) to OID. Note:
6070 * this code doesn't check if the relation is actually a view.
6071 * We'll detect that in get_create_object_cmd().
6072 */
6073 appendPQExpBufferStr(query, "SELECT ");
6074 appendStringLiteralConn(query, desc, pset.db);
6075 appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
6076 break;
6077 }
6078
6079 if (!echo_hidden_command(query->data))
6080 {
6081 destroyPQExpBuffer(query);
6082 return false;
6083 }
6084 res = PQexec(pset.db, query->data);
6085 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6086 *obj_oid = atooid(PQgetvalue(res, 0, 0));
6087 else
6088 {
6090 result = false;
6091 }
6092
6093 PQclear(res);
6094 destroyPQExpBuffer(query);
6095
6096 return result;
6097}
#define atooid(x)
Definition: postgres_ext.h:41
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:446

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(), and pset.

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

6395{
6396 PQExpBuffer msg;
6397 const char *fld;
6398
6399 msg = createPQExpBuffer();
6400
6402 if (fld)
6403 printfPQExpBuffer(msg, "%s: ", fld);
6404 else
6405 printfPQExpBuffer(msg, "ERROR: ");
6407 if (fld)
6408 appendPQExpBufferStr(msg, fld);
6409 else
6410 appendPQExpBufferStr(msg, "(not available)");
6411 appendPQExpBufferChar(msg, '\n');
6412
6413 pg_log_error("%s", msg->data);
6414
6415 destroyPQExpBuffer(msg);
6416}
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:53
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:50

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

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

3800{
3801 if (new_val == NULL)
3802 return false;
3803
3804 if (old_val == NULL || strcmp(old_val, new_val) != 0)
3805 return true;
3806
3807 return false;
3808}

Referenced by do_connect().

◆ print_with_linenumbers()

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

Definition at line 6352 of file command.c.

6353{
6354 bool in_header = is_func;
6355 int lineno = 0;
6356
6357 while (*lines != '\0')
6358 {
6359 char *eol;
6360
6361 if (in_header &&
6362 (strncmp(lines, "AS ", 3) == 0 ||
6363 strncmp(lines, "BEGIN ", 6) == 0 ||
6364 strncmp(lines, "RETURN ", 7) == 0))
6365 in_header = false;
6366
6367 /* increment lineno only for body's lines */
6368 if (!in_header)
6369 lineno++;
6370
6371 /* find and mark end of current line */
6372 eol = strchr(lines, '\n');
6373 if (eol != NULL)
6374 *eol = '\0';
6375
6376 /* show current line as appropriate */
6377 if (in_header)
6378 fprintf(output, " %s\n", lines);
6379 else
6380 fprintf(output, "%-7d %s\n", lineno, lines);
6381
6382 /* advance to next line, if any */
6383 if (eol == NULL)
6384 break;
6385 lines = ++eol;
6386 }
6387}

References fprintf, and output.

Referenced by exec_command_sf_sv().

◆ printGSSInfo()

static void printGSSInfo ( void  )
static

Definition at line 4435 of file command.c.

4436{
4437 if (!PQgssEncInUse(pset.db))
4438 return; /* no GSSAPI encryption in use */
4439
4440 printf(_("GSSAPI-encrypted connection\n"));
4441}
int PQgssEncInUse(PGconn *conn)

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

Referenced by connection_warnings().

◆ printPsetInfo()

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

Definition at line 5324 of file command.c.

5325{
5326 Assert(param != NULL);
5327
5328 /* show border style/width */
5329 if (strcmp(param, "border") == 0)
5330 printf(_("Border style is %d.\n"), popt->topt.border);
5331
5332 /* show the target width for the wrapped format */
5333 else if (strcmp(param, "columns") == 0)
5334 {
5335 if (!popt->topt.columns)
5336 printf(_("Target width is unset.\n"));
5337 else
5338 printf(_("Target width is %d.\n"), popt->topt.columns);
5339 }
5340
5341 /* show expanded/vertical mode */
5342 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
5343 {
5344 if (popt->topt.expanded == 1)
5345 printf(_("Expanded display is on.\n"));
5346 else if (popt->topt.expanded == 2)
5347 printf(_("Expanded display is used automatically.\n"));
5348 else
5349 printf(_("Expanded display is off.\n"));
5350 }
5351
5352 /* show xheader width value */
5353 else if (strcmp(param, "xheader_width") == 0)
5354 {
5356 printf(_("Expanded header width is \"%s\".\n"), "full");
5358 printf(_("Expanded header width is \"%s\".\n"), "column");
5360 printf(_("Expanded header width is \"%s\".\n"), "page");
5362 printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
5363 }
5364
5365 /* show field separator for CSV format */
5366 else if (strcmp(param, "csv_fieldsep") == 0)
5367 {
5368 printf(_("Field separator for CSV is \"%s\".\n"),
5369 popt->topt.csvFieldSep);
5370 }
5371
5372 /* show field separator for unaligned text */
5373 else if (strcmp(param, "fieldsep") == 0)
5374 {
5375 if (popt->topt.fieldSep.separator_zero)
5376 printf(_("Field separator is zero byte.\n"));
5377 else
5378 printf(_("Field separator is \"%s\".\n"),
5379 popt->topt.fieldSep.separator);
5380 }
5381
5382 else if (strcmp(param, "fieldsep_zero") == 0)
5383 {
5384 printf(_("Field separator is zero byte.\n"));
5385 }
5386
5387 /* show disable "(x rows)" footer */
5388 else if (strcmp(param, "footer") == 0)
5389 {
5390 if (popt->topt.default_footer)
5391 printf(_("Default footer is on.\n"));
5392 else
5393 printf(_("Default footer is off.\n"));
5394 }
5395
5396 /* show format */
5397 else if (strcmp(param, "format") == 0)
5398 {
5399 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
5400 }
5401
5402 /* show table line style */
5403 else if (strcmp(param, "linestyle") == 0)
5404 {
5405 printf(_("Line style is %s.\n"),
5406 get_line_style(&popt->topt)->name);
5407 }
5408
5409 /* show null display */
5410 else if (strcmp(param, "null") == 0)
5411 {
5412 printf(_("Null display is \"%s\".\n"),
5413 popt->nullPrint ? popt->nullPrint : "");
5414 }
5415
5416 /* show locale-aware numeric output */
5417 else if (strcmp(param, "numericlocale") == 0)
5418 {
5419 if (popt->topt.numericLocale)
5420 printf(_("Locale-adjusted numeric output is on.\n"));
5421 else
5422 printf(_("Locale-adjusted numeric output is off.\n"));
5423 }
5424
5425 /* show toggle use of pager */
5426 else if (strcmp(param, "pager") == 0)
5427 {
5428 if (popt->topt.pager == 1)
5429 printf(_("Pager is used for long output.\n"));
5430 else if (popt->topt.pager == 2)
5431 printf(_("Pager is always used.\n"));
5432 else
5433 printf(_("Pager usage is off.\n"));
5434 }
5435
5436 /* show minimum lines for pager use */
5437 else if (strcmp(param, "pager_min_lines") == 0)
5438 {
5439 printf(ngettext("Pager won't be used for less than %d line.\n",
5440 "Pager won't be used for less than %d lines.\n",
5441 popt->topt.pager_min_lines),
5442 popt->topt.pager_min_lines);
5443 }
5444
5445 /* show record separator for unaligned text */
5446 else if (strcmp(param, "recordsep") == 0)
5447 {
5448 if (popt->topt.recordSep.separator_zero)
5449 printf(_("Record separator is zero byte.\n"));
5450 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
5451 printf(_("Record separator is <newline>.\n"));
5452 else
5453 printf(_("Record separator is \"%s\".\n"),
5454 popt->topt.recordSep.separator);
5455 }
5456
5457 else if (strcmp(param, "recordsep_zero") == 0)
5458 {
5459 printf(_("Record separator is zero byte.\n"));
5460 }
5461
5462 /* show HTML table tag options */
5463 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5464 {
5465 if (popt->topt.tableAttr)
5466 printf(_("Table attributes are \"%s\".\n"),
5467 popt->topt.tableAttr);
5468 else
5469 printf(_("Table attributes unset.\n"));
5470 }
5471
5472 /* show title override */
5473 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5474 {
5475 if (popt->title)
5476 printf(_("Title is \"%s\".\n"), popt->title);
5477 else
5478 printf(_("Title is unset.\n"));
5479 }
5480
5481 /* show toggle between full and tuples-only format */
5482 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5483 {
5484 if (popt->topt.tuples_only)
5485 printf(_("Tuples only is on.\n"));
5486 else
5487 printf(_("Tuples only is off.\n"));
5488 }
5489
5490 /* Unicode style formatting */
5491 else if (strcmp(param, "unicode_border_linestyle") == 0)
5492 {
5493 printf(_("Unicode border line style is \"%s\".\n"),
5495 }
5496
5497 else if (strcmp(param, "unicode_column_linestyle") == 0)
5498 {
5499 printf(_("Unicode column line style is \"%s\".\n"),
5501 }
5502
5503 else if (strcmp(param, "unicode_header_linestyle") == 0)
5504 {
5505 printf(_("Unicode header line style is \"%s\".\n"),
5507 }
5508
5509 else
5510 {
5511 pg_log_error("\\pset: unknown option: %s", param);
5512 return false;
5513 }
5514
5515 return true;
5516}
#define ngettext(s, p, n)
Definition: c.h:1152
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:4941
static const char * _align2string(enum printFormat in)
Definition: command.c:4885
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 4407 of file command.c.

4408{
4409 const char *protocol;
4410 const char *cipher;
4411 const char *compression;
4412 const char *alpn;
4413
4414 if (!PQsslInUse(pset.db))
4415 return; /* no SSL */
4416
4417 protocol = PQsslAttribute(pset.db, "protocol");
4418 cipher = PQsslAttribute(pset.db, "cipher");
4419 compression = PQsslAttribute(pset.db, "compression");
4420 alpn = PQsslAttribute(pset.db, "alpn");
4421
4422 printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
4423 protocol ? protocol : _("unknown"),
4424 cipher ? cipher : _("unknown"),
4425 (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4426 (alpn && alpn[0] != '\0') ? alpn : _("none"));
4427}

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

Referenced by connection_warnings().

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

1778{
1779 bool success = true;
1780 bool found_r_paren = false;
1781
1782 do
1783 {
1784 char *option;
1785 size_t optlen;
1786
1787 /* If not first time through, collect a new option */
1788 if (first_option)
1789 option = first_option;
1790 else
1791 {
1792 option = psql_scan_slash_option(scan_state,
1793 OT_NORMAL, NULL, false);
1794 if (!option)
1795 {
1796 if (active_branch)
1797 {
1798 pg_log_error("\\%s: missing right parenthesis", cmd);
1799 success = false;
1800 }
1801 break;
1802 }
1803 }
1804
1805 /* Check for terminating right paren, and remove it from string */
1806 optlen = strlen(option);
1807 if (optlen > 0 && option[optlen - 1] == ')')
1808 {
1809 option[--optlen] = '\0';
1810 found_r_paren = true;
1811 }
1812
1813 /* If there was anything besides parentheses, parse/execute it */
1814 if (optlen > 0)
1815 {
1816 /* We can have either "name" or "name=value" */
1817 char *valptr = strchr(option, '=');
1818
1819 if (valptr)
1820 *valptr++ = '\0';
1821 if (active_branch)
1822 {
1823 /* save settings if not done already, then apply option */
1824 if (pset.gsavepopt == NULL)
1826 success &= do_pset(option, valptr, &pset.popt, true);
1827 }
1828 }
1829
1830 /* Clean up after this option. We should not free first_option. */
1831 if (first_option)
1832 first_option = NULL;
1833 else
1834 free(option);
1835 } while (!found_r_paren);
1836
1837 /* If we failed after already changing some options, undo side-effects */
1838 if (!success && active_branch && pset.gsavepopt)
1839 {
1841 pset.gsavepopt = NULL;
1842 }
1843
1845}
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:5560

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

4819{
4820 FILE *fd;
4821 int result;
4822 char *oldfilename;
4823 char relpath[MAXPGPATH];
4824
4825 if (!filename)
4826 {
4827 fd = stdin;
4828 filename = NULL;
4829 }
4830 else if (strcmp(filename, "-") != 0)
4831 {
4833
4834 /*
4835 * If we were asked to resolve the pathname relative to the location
4836 * of the currently executing script, and there is one, and this is a
4837 * relative pathname, then prepend all but the last pathname component
4838 * of the current script to this pathname.
4839 */
4840 if (use_relative_path && pset.inputfile &&
4842 {
4847
4848 filename = relpath;
4849 }
4850
4851 fd = fopen(filename, PG_BINARY_R);
4852
4853 if (!fd)
4854 {
4855 pg_log_error("%s: %m", filename);
4856 return EXIT_FAILURE;
4857 }
4858 }
4859 else
4860 {
4861 fd = stdin;
4862 filename = "<stdin>"; /* for future error messages */
4863 }
4864
4865 oldfilename = pset.inputfile;
4867
4869
4870 result = MainLoop(fd);
4871
4872 if (fd != stdin)
4873 fclose(fd);
4874
4875 pset.inputfile = oldfilename;
4876
4878
4879 return result;
4880}
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:127
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:286
#define is_absolute_path(filename)
Definition: port.h:104
void get_parent_directory(char *path)
Definition: path.c:1068
bool has_drive_prefix(const char *path)
Definition: path.c:94
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define relpath(rlocator, forknum)
Definition: relpath.h:150
#define EXIT_FAILURE
Definition: settings.h:197

References canonicalize_path_enc(), _psqlSettings::encoding, 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 3771 of file command.c.

3772{
3773 char *result;
3774 PromptInterruptContext prompt_ctx;
3775
3776 /* Set up to let SIGINT cancel simple_prompt_extended() */
3777 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3778 prompt_ctx.enabled = &sigint_interrupt_enabled;
3779 prompt_ctx.canceled = false;
3780
3781 if (username == NULL || username[0] == '\0')
3782 result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3783 else
3784 {
3785 char *prompt_text;
3786
3787 prompt_text = psprintf(_("Password for user %s: "), username);
3788 result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3789 free(prompt_text);
3790 }
3791
3792 if (canceled)
3793 *canceled = prompt_ctx.canceled;
3794
3795 return result;
3796}
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 5586 of file command.c.

5587{
5588 return val ? "on" : "off";
5589}

References val.

Referenced by pset_value_string().

◆ pset_quoted_string()

static char * pset_quoted_string ( const char *  str)
static

Definition at line 5593 of file command.c.

5594{
5595 char *ret = pg_malloc(strlen(str) * 2 + 3);
5596 char *r = ret;
5597
5598 *r++ = '\'';
5599
5600 for (; *str; str++)
5601 {
5602 if (*str == '\n')
5603 {
5604 *r++ = '\\';
5605 *r++ = 'n';
5606 }
5607 else if (*str == '\'')
5608 {
5609 *r++ = '\\';
5610 *r++ = '\'';
5611 }
5612 else
5613 *r++ = *str;
5614 }
5615
5616 *r++ = '\'';
5617 *r = '\0';
5618
5619 return ret;
5620}
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 5631 of file command.c.

5632{
5633 Assert(param != NULL);
5634
5635 if (strcmp(param, "border") == 0)
5636 return psprintf("%d", popt->topt.border);
5637 else if (strcmp(param, "columns") == 0)
5638 return psprintf("%d", popt->topt.columns);
5639 else if (strcmp(param, "csv_fieldsep") == 0)
5640 return pset_quoted_string(popt->topt.csvFieldSep);
5641 else if (strcmp(param, "expanded") == 0)
5642 return pstrdup(popt->topt.expanded == 2
5643 ? "auto"
5644 : pset_bool_string(popt->topt.expanded));
5645 else if (strcmp(param, "fieldsep") == 0)
5647 ? popt->topt.fieldSep.separator
5648 : "");
5649 else if (strcmp(param, "fieldsep_zero") == 0)
5651 else if (strcmp(param, "footer") == 0)
5653 else if (strcmp(param, "format") == 0)
5654 return pstrdup(_align2string(popt->topt.format));
5655 else if (strcmp(param, "linestyle") == 0)
5656 return pstrdup(get_line_style(&popt->topt)->name);
5657 else if (strcmp(param, "null") == 0)
5658 return pset_quoted_string(popt->nullPrint
5659 ? popt->nullPrint
5660 : "");
5661 else if (strcmp(param, "numericlocale") == 0)
5663 else if (strcmp(param, "pager") == 0)
5664 return psprintf("%d", popt->topt.pager);
5665 else if (strcmp(param, "pager_min_lines") == 0)
5666 return psprintf("%d", popt->topt.pager_min_lines);
5667 else if (strcmp(param, "recordsep") == 0)
5669 ? popt->topt.recordSep.separator
5670 : "");
5671 else if (strcmp(param, "recordsep_zero") == 0)
5673 else if (strcmp(param, "tableattr") == 0)
5674 return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5675 else if (strcmp(param, "title") == 0)
5676 return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5677 else if (strcmp(param, "tuples_only") == 0)
5679 else if (strcmp(param, "unicode_border_linestyle") == 0)
5681 else if (strcmp(param, "unicode_column_linestyle") == 0)
5683 else if (strcmp(param, "unicode_header_linestyle") == 0)
5685 else if (strcmp(param, "xheader_width") == 0)
5686 {
5688 return pstrdup("full");
5690 return pstrdup("column");
5692 return pstrdup("page");
5693 else
5694 {
5695 /* must be PRINT_XHEADER_EXACT_WIDTH */
5696 char wbuff[32];
5697
5698 snprintf(wbuff, sizeof(wbuff), "%d",
5700 return pstrdup(wbuff);
5701 }
5702 }
5703 else
5704 return pstrdup("ERROR");
5705}
static char * pset_quoted_string(const char *str)
Definition: command.c:5593
static const char * pset_bool_string(bool val)
Definition: command.c:5586
char * pstrdup(const char *in)
Definition: mcxt.c:1699

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

3540{
3541 char *result;
3542 char quote;
3543
3544 /*
3545 * Ideally we should treat the arguments as SQL identifiers. But for
3546 * backwards compatibility with 7.2 and older pg_dump files, we have to
3547 * take unquoted arguments verbatim (don't downcase them). For now,
3548 * double-quoted arguments may be stripped of double quotes (as if SQL
3549 * identifiers). By 7.4 or so, pg_dump files can be expected to
3550 * double-quote all mixed-case \connect arguments, and then we can get rid
3551 * of OT_SQLIDHACK.
3552 */
3553 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
3554
3555 if (!result)
3556 return NULL;
3557
3558 if (quote)
3559 return result;
3560
3561 if (*result == '\0' || strcmp(result, "-") == 0)
3562 {
3563 free(result);
3564 return NULL;
3565 }
3566
3567 return result;
3568}
@ 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 5560 of file command.c.

5561{
5562 /* Free all the old data we're about to overwrite the pointers to. */
5563
5564 /* topt.line_style points to const data that need not be duplicated */
5565 free(popt->topt.fieldSep.separator);
5567 free(popt->topt.tableAttr);
5568 free(popt->nullPrint);
5569 free(popt->title);
5570
5571 /*
5572 * footers and translate_columns are never set in psql's print settings,
5573 * so we needn't write code to duplicate them.
5574 */
5575 Assert(popt->footers == NULL);
5576 Assert(popt->translate_columns == NULL);
5577
5578 /* Now we may flat-copy all the fields, including pointers. */
5579 memcpy(popt, save, sizeof(printQueryOpt));
5580
5581 /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5582 free(save);
5583}
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 3707 of file command.c.

3709{
3710 if (query_buf)
3711 conditional_stack_set_query_len(cstack, query_buf->len);
3713 psql_scan_get_paren_depth(scan_state));
3714}
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 5524 of file command.c.

5525{
5526 printQueryOpt *save;
5527
5528 save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
5529
5530 /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5531 memcpy(save, popt, sizeof(printQueryOpt));
5532
5533 /* topt.line_style points to const data that need not be duplicated */
5534 if (popt->topt.fieldSep.separator)
5536 if (popt->topt.recordSep.separator)
5538 if (popt->topt.tableAttr)
5539 save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5540 if (popt->nullPrint)
5541 save->nullPrint = pg_strdup(popt->nullPrint);
5542 if (popt->title)
5543 save->title = pg_strdup(popt->title);
5544
5545 /*
5546 * footers and translate_columns are never set in psql's print settings,
5547 * so we needn't write code to duplicate them.
5548 */
5549 Assert(popt->footers == NULL);
5550 Assert(popt->translate_columns == NULL);
5551
5552 return save;
5553}

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

4930{
4931 if (pg_strncasecmp("single", value, vallen) == 0)
4932 *linestyle = UNICODE_LINESTYLE_SINGLE;
4933 else if (pg_strncasecmp("double", value, vallen) == 0)
4934 *linestyle = UNICODE_LINESTYLE_DOUBLE;
4935 else
4936 return false;
4937 return true;
4938}

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

6265{
6266 char *c;
6267 int lineno;
6268
6269 if (!obj || obj[0] == '\0')
6270 return -1;
6271
6272 c = obj + strlen(obj) - 1;
6273
6274 /*
6275 * This business of parsing backwards is dangerous as can be in a
6276 * multibyte environment: there is no reason to believe that we are
6277 * looking at the first byte of a character, nor are we necessarily
6278 * working in a "safe" encoding. Fortunately the bitpatterns we are
6279 * looking for are unlikely to occur as non-first bytes, but beware of
6280 * trying to expand the set of cases that can be recognized. We must
6281 * guard the <ctype.h> macros by using isascii() first, too.
6282 */
6283
6284 /* skip trailing whitespace */
6285 while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
6286 c--;
6287
6288 /* must have a digit as last non-space char */
6289 if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
6290 return -1;
6291
6292 /* find start of digit string */
6293 while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
6294 c--;
6295
6296 /* digits must be separated from object name by space or closing paren */
6297 /* notice also that we are not allowing an empty object name ... */
6298 if (c == obj || !isascii((unsigned char) *c) ||
6299 !(isspace((unsigned char) *c) || *c == ')'))
6300 return -1;
6301
6302 /* parse digit string */
6303 c++;
6304 lineno = atoi(c);
6305 if (lineno < 1)
6306 {
6307 pg_log_error("invalid line number: %s", c);
6308 return 0;
6309 }
6310
6311 /* strip digit string from object name */
6312 *c = '\0';
6313
6314 return lineno;
6315}
char * c

References pg_log_error.

Referenced by exec_command_ef_ev().

◆ SyncVariables()

void SyncVariables ( void  )

Definition at line 4476 of file command.c.

4477{
4478 char vbuf[32];
4479 const char *server_version;
4480
4481 /* get stuff from connection */
4485
4487
4488 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4489 SetVariable(pset.vars, "SERVICE", PQservice(pset.db));
4490 SetVariable(pset.vars, "USER", PQuser(pset.db));
4491 SetVariable(pset.vars, "HOST", PQhost(pset.db));
4492 SetVariable(pset.vars, "PORT", PQport(pset.db));
4494
4495 /* this bit should match connection_warnings(): */
4496 /* Try to get full text form of version, might include "devel" etc */
4497 server_version = PQparameterStatus(pset.db, "server_version");
4498 /* Otherwise fall back on pset.sversion */
4499 if (!server_version)
4500 {
4501 formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4502 server_version = vbuf;
4503 }
4504 SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4505
4506 snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4507 SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4508
4509 /* send stuff to it, too */
4512}
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7543
char * PQservice(const PGconn *conn)
Definition: fe-connect.c:7389
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7705
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7693
PGVerbosity verbosity
Definition: settings.h:184
PGContextVisibility show_context
Definition: settings.h:186

References _psqlSettings::db, _psqlSettings::encoding, printTableOpt::encoding, formatPGVersionNumber(), pg_encoding_to_char, _psqlSettings::popt, PQclientEncoding(), PQdb(), PQhost(), PQparameterStatus(), PQport(), PQserverVersion(), PQservice(), PQsetErrorContextVisibility(), PQsetErrorVerbosity(), PQuser(), pset, server_version, setFmtEncoding(), 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 4520 of file command.c.

4521{
4522 SetVariable(pset.vars, "DBNAME", NULL);
4523 SetVariable(pset.vars, "SERVICE", NULL);
4524 SetVariable(pset.vars, "USER", NULL);
4525 SetVariable(pset.vars, "HOST", NULL);
4526 SetVariable(pset.vars, "PORT", NULL);
4527 SetVariable(pset.vars, "ENCODING", NULL);
4528 SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4529 SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
4530}

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

4287{
4288 bool forRead = false;
4289
4290 while (true)
4291 {
4292 int rc;
4293 int sock;
4295
4296 /*
4297 * On every iteration of the connection sequence, let's check if the
4298 * user has requested a cancellation.
4299 */
4300 if (cancel_pressed)
4301 break;
4302
4303 /*
4304 * Do not assume that the socket remains the same across
4305 * PQconnectPoll() calls.
4306 */
4307 sock = PQsocket(conn);
4308 if (sock == -1)
4309 break;
4310
4311 /*
4312 * If the user sends SIGINT between the cancel_pressed check, and
4313 * polling of the socket, it will not be recognized. Instead, we will
4314 * just wait until the next step in the connection sequence or
4315 * forever, which might require users to send SIGTERM or SIGQUIT.
4316 *
4317 * Some solutions would include the "self-pipe trick," using
4318 * pselect(2) and ppoll(2), or using a timeout.
4319 *
4320 * The self-pipe trick requires a bit of code to setup. pselect(2) and
4321 * ppoll(2) are not on all the platforms we support. The simplest
4322 * solution happens to just be adding a timeout, so let's wait for 1
4323 * second and check cancel_pressed again.
4324 */
4325 end_time = PQgetCurrentTimeUSec() + 1000000;
4326 rc = PQsocketPoll(sock, forRead, !forRead, end_time);
4327 if (rc == -1)
4328 return;
4329
4330 switch (PQconnectPoll(conn))
4331 {
4332 case PGRES_POLLING_OK:
4334 return;
4336 forRead = true;
4337 continue;
4339 forRead = false;
4340 continue;
4343 }
4344 }
4345}
#define pg_unreachable()
Definition: c.h:332
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2842
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7579
int PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time)
Definition: fe-misc.c:1115
pg_usec_time_t PQgetCurrentTimeUSec(void)
Definition: fe-misc.c:1209
int64_t pg_usec_time_t
Definition: libpq-fe.h:241
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:119
@ PGRES_POLLING_OK
Definition: libpq-fe.h:118
@ PGRES_POLLING_READING
Definition: libpq-fe.h:116
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:117
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:115
static int64 end_time
Definition: pgbench.c:176
PGconn * conn
Definition: streamutil.c:52

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