PostgreSQL Source Code git master
command.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <time.h>
#include <pwd.h>
#include <utime.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "catalog/pg_class_d.h"
#include "command.h"
#include "common.h"
#include "common/logging.h"
#include "common/string.h"
#include "copy.h"
#include "describe.h"
#include "fe_utils/cancel.h"
#include "fe_utils/print.h"
#include "fe_utils/string_utils.h"
#include "help.h"
#include "input.h"
#include "large_obj.h"
#include "libpq/pqcomm.h"
#include "mainloop.h"
#include "pqexpbuffer.h"
#include "psqlscanslash.h"
#include "settings.h"
#include "variables.h"
Include dependency graph for command.c:

Go to the source code of this file.

Macros

#define DEFAULT_SHELL   "/bin/sh"
 

Typedefs

typedef enum EditableObjectType EditableObjectType
 

Enumerations

enum  EditableObjectType { EditableFunction , EditableView }
 

Functions

static backslashResult exec_command (const char *cmd, PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_a (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_bind (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_bind_named (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_C (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_connect (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_cd (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_close (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_conninfo (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_copy (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_copyright (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_crosstabview (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_d (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static bool exec_command_dfo (PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
 
static backslashResult exec_command_edit (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_ef_ev (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
 
static backslashResult exec_command_echo (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_elif (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_else (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_endif (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_encoding (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_errverbose (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_f (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_g (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult process_command_g_options (char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_gdesc (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_getenv (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_gexec (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_gset (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_help (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_html (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_include (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_if (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static backslashResult exec_command_list (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_lo (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_out (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_print (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_parse (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_password (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_prompt (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_pset (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_quit (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_reset (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
 
static backslashResult exec_command_s (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_set (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_setenv (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_sf_sv (PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
 
static backslashResult exec_command_t (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_T (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_timing (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_unset (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_write (PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_watch (PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static backslashResult exec_command_x (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_z (PsqlScanState scan_state, bool active_branch, const char *cmd)
 
static backslashResult exec_command_shell_escape (PsqlScanState scan_state, bool active_branch)
 
static backslashResult exec_command_slash_command_help (PsqlScanState scan_state, bool active_branch)
 
static char * read_connect_arg (PsqlScanState scan_state)
 
static PQExpBuffer gather_boolean_expression (PsqlScanState scan_state)
 
static bool is_true_boolean_expression (PsqlScanState scan_state, const char *name)
 
static void ignore_boolean_expression (PsqlScanState scan_state)
 
static void ignore_slash_options (PsqlScanState scan_state)
 
static void ignore_slash_filepipe (PsqlScanState scan_state)
 
static void ignore_slash_whole_line (PsqlScanState scan_state)
 
static bool is_branching_command (const char *cmd)
 
static void save_query_text_state (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static void discard_query_text (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
 
static bool copy_previous_query (PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static bool do_connect (enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
 
static void wait_until_connected (PGconn *conn)
 
static bool do_edit (const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
 
static bool do_shell (const char *command)
 
static bool do_watch (PQExpBuffer query_buf, double sleep, int iter, int min_rows)
 
static bool lookup_object_oid (EditableObjectType obj_type, const char *desc, Oid *obj_oid)
 
static bool get_create_object_cmd (EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
 
static int strip_lineno_from_objdesc (char *obj)
 
static int count_lines_in_buf (PQExpBuffer buf)
 
static void print_with_linenumbers (FILE *output, char *lines, bool is_func)
 
static void minimal_error_message (PGresult *res)
 
static void printSSLInfo (void)
 
static void printGSSInfo (void)
 
static bool printPsetInfo (const char *param, printQueryOpt *popt)
 
static char * pset_value_string (const char *param, printQueryOpt *popt)
 
backslashResult HandleSlashCmds (PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
 
static char * prompt_for_password (const char *username, bool *canceled)
 
static bool param_is_newly_set (const char *old_val, const char *new_val)
 
void connection_warnings (bool in_startup)
 
void SyncVariables (void)
 
void UnsyncVariables (void)
 
static bool editFile (const char *fname, int lineno)
 
int process_file (char *filename, bool use_relative_path)
 
static const char * _align2string (enum printFormat in)
 
static bool set_unicode_line_style (const char *value, size_t vallen, unicode_linestyle *linestyle)
 
static const char * _unicode_linestyle2string (int linestyle)
 
bool do_pset (const char *param, const char *value, printQueryOpt *popt, bool quiet)
 
printQueryOptsavePsetInfo (const printQueryOpt *popt)
 
void restorePsetInfo (printQueryOpt *popt, printQueryOpt *save)
 
static const char * pset_bool_string (bool val)
 
static char * pset_quoted_string (const char *str)
 
static bool echo_hidden_command (const char *query)
 

Macro Definition Documentation

◆ DEFAULT_SHELL

#define DEFAULT_SHELL   "/bin/sh"

Definition at line 5363 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 4538 of file command.c.

4539{
4540 switch (in)
4541 {
4542 case PRINT_NOTHING:
4543 return "nothing";
4544 break;
4545 case PRINT_ALIGNED:
4546 return "aligned";
4547 break;
4548 case PRINT_ASCIIDOC:
4549 return "asciidoc";
4550 break;
4551 case PRINT_CSV:
4552 return "csv";
4553 break;
4554 case PRINT_HTML:
4555 return "html";
4556 break;
4557 case PRINT_LATEX:
4558 return "latex";
4559 break;
4561 return "latex-longtable";
4562 break;
4563 case PRINT_TROFF_MS:
4564 return "troff-ms";
4565 break;
4566 case PRINT_UNALIGNED:
4567 return "unaligned";
4568 break;
4569 case PRINT_WRAPPED:
4570 return "wrapped";
4571 break;
4572 }
4573 return "unknown";
4574}
@ 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 4594 of file command.c.

4595{
4596 switch (linestyle)
4597 {
4599 return "single";
4600 break;
4602 return "double";
4603 break;
4604 }
4605 return "unknown";
4606}
@ 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 4001 of file command.c.

4002{
4003 if (!pset.quiet && !pset.notty)
4004 {
4005 int client_ver = PG_VERSION_NUM;
4006 char cverbuf[32];
4007 char sverbuf[32];
4008
4009 if (pset.sversion != client_ver)
4010 {
4011 const char *server_version;
4012
4013 /* Try to get full text form, might include "devel" etc */
4014 server_version = PQparameterStatus(pset.db, "server_version");
4015 /* Otherwise fall back on pset.sversion */
4016 if (!server_version)
4017 {
4019 sverbuf, sizeof(sverbuf));
4020 server_version = sverbuf;
4021 }
4022
4023 printf(_("%s (%s, server %s)\n"),
4024 pset.progname, PG_VERSION, server_version);
4025 }
4026 /* For version match, only print psql banner on startup. */
4027 else if (in_startup)
4028 printf("%s (%s)\n", pset.progname, PG_VERSION);
4029
4030 /*
4031 * Warn if server's major version is newer than ours, or if server
4032 * predates our support cutoff (currently 9.2).
4033 */
4034 if (pset.sversion / 100 > client_ver / 100 ||
4035 pset.sversion < 90200)
4036 printf(_("WARNING: %s major version %s, server major version %s.\n"
4037 " Some psql features might not work.\n"),
4038 pset.progname,
4039 formatPGVersionNumber(client_ver, false,
4040 cverbuf, sizeof(cverbuf)),
4042 sverbuf, sizeof(sverbuf)));
4043
4044#ifdef WIN32
4045 if (in_startup)
4046 checkWin32Codepage();
4047#endif
4048 printSSLInfo();
4049 printGSSInfo();
4050 }
4051}
static void printSSLInfo(void)
Definition: command.c:4060
static void printGSSInfo(void)
Definition: command.c:4088
#define _(x)
Definition: elog.c:90
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7462
static int server_version
Definition: pg_dumpall.c:110
#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:91
const char * progname
Definition: settings.h:124

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

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

◆ copy_previous_query()

static bool copy_previous_query ( PQExpBuffer  query_buf,
PQExpBuffer  previous_buf 
)
static

Definition at line 3406 of file command.c.

3407{
3408 if (query_buf && query_buf->len == 0)
3409 {
3410 appendPQExpBufferStr(query_buf, previous_buf->data);
3411 return true;
3412 }
3413 return false;
3414}
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 5975 of file command.c.

5976{
5977 int lineno = 0;
5978 const char *lines = buf->data;
5979
5980 while (*lines != '\0')
5981 {
5982 lineno++;
5983 /* find start of next line */
5984 lines = strchr(lines, '\n');
5985 if (!lines)
5986 break;
5987 lines++;
5988 }
5989
5990 return lineno;
5991}
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 3380 of file command.c.

3382{
3383 if (query_buf)
3384 {
3385 int new_len = conditional_stack_get_query_len(cstack);
3386
3387 Assert(new_len >= 0 && new_len <= query_buf->len);
3388 query_buf->len = new_len;
3389 query_buf->data[new_len] = '\0';
3390 }
3391 psql_scan_set_paren_depth(scan_state,
3393}
#define Assert(condition)
Definition: c.h:815
int conditional_stack_get_query_len(ConditionalStack cstack)
Definition: conditional.c:162
int conditional_stack_get_paren_depth(ConditionalStack cstack)
Definition: conditional.c:184
const void size_t len
void psql_scan_set_paren_depth(PsqlScanState state, int depth)

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

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

◆ do_connect()

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

Definition at line 3475 of file command.c.

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

References _, Assert, CONNECTION_OK, connection_warnings(), _psqlSettings::cur_cmd_interactive, _psqlSettings::db, dbname, _psqlSettings::dead_conn, errmsg(), _psqlSettings::getPassword, is_unixsock_path(), _PQconninfoOption::keyword, 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 4276 of file command.c.

4278{
4279 char fnametmp[MAXPGPATH];
4280 FILE *stream = NULL;
4281 const char *fname;
4282 bool error = false;
4283 int fd;
4284 struct stat before,
4285 after;
4286
4287 if (filename_arg)
4288 fname = filename_arg;
4289 else
4290 {
4291 /* make a temp file to edit */
4292#ifndef WIN32
4293 const char *tmpdir = getenv("TMPDIR");
4294
4295 if (!tmpdir)
4296 tmpdir = "/tmp";
4297#else
4298 char tmpdir[MAXPGPATH];
4299 int ret;
4300
4301 ret = GetTempPath(MAXPGPATH, tmpdir);
4302 if (ret == 0 || ret > MAXPGPATH)
4303 {
4304 pg_log_error("could not locate temporary directory: %s",
4305 !ret ? strerror(errno) : "");
4306 return false;
4307 }
4308#endif
4309
4310 /*
4311 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4312 * current directory to the supplied path unless we use only
4313 * backslashes, so we do that.
4314 */
4315#ifndef WIN32
4316 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4317 "/", (int) getpid());
4318#else
4319 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4320 "" /* trailing separator already present */ , (int) getpid());
4321#endif
4322
4323 fname = (const char *) fnametmp;
4324
4325 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4326 if (fd != -1)
4327 stream = fdopen(fd, "w");
4328
4329 if (fd == -1 || !stream)
4330 {
4331 pg_log_error("could not open temporary file \"%s\": %m", fname);
4332 error = true;
4333 }
4334 else
4335 {
4336 unsigned int ql = query_buf->len;
4337
4338 /* force newline-termination of what we send to editor */
4339 if (ql > 0 && query_buf->data[ql - 1] != '\n')
4340 {
4341 appendPQExpBufferChar(query_buf, '\n');
4342 ql++;
4343 }
4344
4345 if (fwrite(query_buf->data, 1, ql, stream) != ql)
4346 {
4347 pg_log_error("%s: %m", fname);
4348
4349 if (fclose(stream) != 0)
4350 pg_log_error("%s: %m", fname);
4351
4352 if (remove(fname) != 0)
4353 pg_log_error("%s: %m", fname);
4354
4355 error = true;
4356 }
4357 else if (fclose(stream) != 0)
4358 {
4359 pg_log_error("%s: %m", fname);
4360 if (remove(fname) != 0)
4361 pg_log_error("%s: %m", fname);
4362 error = true;
4363 }
4364 else
4365 {
4366 struct utimbuf ut;
4367
4368 /*
4369 * Try to set the file modification time of the temporary file
4370 * a few seconds in the past. Otherwise, the low granularity
4371 * (one second, or even worse on some filesystems) that we can
4372 * portably measure with stat(2) could lead us to not
4373 * recognize a modification, if the user typed very quickly.
4374 *
4375 * This is a rather unlikely race condition, so don't error
4376 * out if the utime(2) call fails --- that would make the cure
4377 * worse than the disease.
4378 */
4379 ut.modtime = ut.actime = time(NULL) - 2;
4380 (void) utime(fname, &ut);
4381 }
4382 }
4383 }
4384
4385 if (!error && stat(fname, &before) != 0)
4386 {
4387 pg_log_error("%s: %m", fname);
4388 error = true;
4389 }
4390
4391 /* call editor */
4392 if (!error)
4393 error = !editFile(fname, lineno);
4394
4395 if (!error && stat(fname, &after) != 0)
4396 {
4397 pg_log_error("%s: %m", fname);
4398 error = true;
4399 }
4400
4401 /* file was edited if the size or modification time has changed */
4402 if (!error &&
4403 (before.st_size != after.st_size ||
4404 before.st_mtime != after.st_mtime))
4405 {
4406 stream = fopen(fname, PG_BINARY_R);
4407 if (!stream)
4408 {
4409 pg_log_error("%s: %m", fname);
4410 error = true;
4411 }
4412 else
4413 {
4414 /* read file back into query_buf */
4415 char line[1024];
4416
4417 resetPQExpBuffer(query_buf);
4418 while (fgets(line, sizeof(line), stream) != NULL)
4419 appendPQExpBufferStr(query_buf, line);
4420
4421 if (ferror(stream))
4422 {
4423 pg_log_error("%s: %m", fname);
4424 error = true;
4425 resetPQExpBuffer(query_buf);
4426 }
4427 else if (edited)
4428 {
4429 *edited = true;
4430 }
4431
4432 fclose(stream);
4433 }
4434 }
4435 else
4436 {
4437 /*
4438 * If the file was not modified, and the caller requested it, discard
4439 * the query buffer.
4440 */
4441 if (discard_on_quit)
4442 resetPQExpBuffer(query_buf);
4443 }
4444
4445 /* remove temp file */
4446 if (!filename_arg)
4447 {
4448 if (remove(fname) == -1)
4449 {
4450 pg_log_error("%s: %m", fname);
4451 error = true;
4452 }
4453 }
4454
4455 return !error;
4456}
#define PG_BINARY_R
Definition: c.h:1232
static bool editFile(const char *fname, int lineno)
Definition: command.c:4194
#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 4624 of file command.c.

4625{
4626 size_t vallen = 0;
4627
4628 Assert(param != NULL);
4629
4630 if (value)
4631 vallen = strlen(value);
4632
4633 /* set format */
4634 if (strcmp(param, "format") == 0)
4635 {
4636 static const struct fmt
4637 {
4638 const char *name;
4639 enum printFormat number;
4640 } formats[] =
4641 {
4642 /* remember to update error message below when adding more */
4643 {"aligned", PRINT_ALIGNED},
4644 {"asciidoc", PRINT_ASCIIDOC},
4645 {"csv", PRINT_CSV},
4646 {"html", PRINT_HTML},
4647 {"latex", PRINT_LATEX},
4648 {"troff-ms", PRINT_TROFF_MS},
4649 {"unaligned", PRINT_UNALIGNED},
4650 {"wrapped", PRINT_WRAPPED}
4651 };
4652
4653 if (!value)
4654 ;
4655 else
4656 {
4657 int match_pos = -1;
4658
4659 for (int i = 0; i < lengthof(formats); i++)
4660 {
4661 if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
4662 {
4663 if (match_pos < 0)
4664 match_pos = i;
4665 else
4666 {
4667 pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
4668 value,
4669 formats[match_pos].name, formats[i].name);
4670 return false;
4671 }
4672 }
4673 }
4674 if (match_pos >= 0)
4675 popt->topt.format = formats[match_pos].number;
4676 else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
4677 {
4678 /*
4679 * We must treat latex-longtable specially because latex is a
4680 * prefix of it; if both were in the table above, we'd think
4681 * "latex" is ambiguous.
4682 */
4684 }
4685 else
4686 {
4687 pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
4688 return false;
4689 }
4690 }
4691 }
4692
4693 /* set table line style */
4694 else if (strcmp(param, "linestyle") == 0)
4695 {
4696 if (!value)
4697 ;
4698 else if (pg_strncasecmp("ascii", value, vallen) == 0)
4700 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
4702 else if (pg_strncasecmp("unicode", value, vallen) == 0)
4703 popt->topt.line_style = &pg_utf8format;
4704 else
4705 {
4706 pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
4707 return false;
4708 }
4709 }
4710
4711 /* set unicode border line style */
4712 else if (strcmp(param, "unicode_border_linestyle") == 0)
4713 {
4714 if (!value)
4715 ;
4716 else if (set_unicode_line_style(value, vallen,
4718 refresh_utf8format(&(popt->topt));
4719 else
4720 {
4721 pg_log_error("\\pset: allowed Unicode border line styles are single, double");
4722 return false;
4723 }
4724 }
4725
4726 /* set unicode column line style */
4727 else if (strcmp(param, "unicode_column_linestyle") == 0)
4728 {
4729 if (!value)
4730 ;
4731 else if (set_unicode_line_style(value, vallen,
4733 refresh_utf8format(&(popt->topt));
4734 else
4735 {
4736 pg_log_error("\\pset: allowed Unicode column line styles are single, double");
4737 return false;
4738 }
4739 }
4740
4741 /* set unicode header line style */
4742 else if (strcmp(param, "unicode_header_linestyle") == 0)
4743 {
4744 if (!value)
4745 ;
4746 else if (set_unicode_line_style(value, vallen,
4748 refresh_utf8format(&(popt->topt));
4749 else
4750 {
4751 pg_log_error("\\pset: allowed Unicode header line styles are single, double");
4752 return false;
4753 }
4754 }
4755
4756 /* set border style/width */
4757 else if (strcmp(param, "border") == 0)
4758 {
4759 if (value)
4760 popt->topt.border = atoi(value);
4761 }
4762
4763 /* set expanded/vertical mode */
4764 else if (strcmp(param, "x") == 0 ||
4765 strcmp(param, "expanded") == 0 ||
4766 strcmp(param, "vertical") == 0)
4767 {
4768 if (value && pg_strcasecmp(value, "auto") == 0)
4769 popt->topt.expanded = 2;
4770 else if (value)
4771 {
4772 bool on_off;
4773
4774 if (ParseVariableBool(value, NULL, &on_off))
4775 popt->topt.expanded = on_off ? 1 : 0;
4776 else
4777 {
4778 PsqlVarEnumError(param, value, "on, off, auto");
4779 return false;
4780 }
4781 }
4782 else
4783 popt->topt.expanded = !popt->topt.expanded;
4784 }
4785
4786 /* header line width in expanded mode */
4787 else if (strcmp(param, "xheader_width") == 0)
4788 {
4789 if (!value)
4790 ;
4791 else if (pg_strcasecmp(value, "full") == 0)
4793 else if (pg_strcasecmp(value, "column") == 0)
4795 else if (pg_strcasecmp(value, "page") == 0)
4797 else
4798 {
4799 int intval = atoi(value);
4800
4801 if (intval == 0)
4802 {
4803 pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
4804 return false;
4805 }
4806
4808 popt->topt.expanded_header_exact_width = intval;
4809 }
4810 }
4811
4812 /* field separator for CSV format */
4813 else if (strcmp(param, "csv_fieldsep") == 0)
4814 {
4815 if (value)
4816 {
4817 /* CSV separator has to be a one-byte character */
4818 if (strlen(value) != 1)
4819 {
4820 pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
4821 return false;
4822 }
4823 if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
4824 {
4825 pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
4826 return false;
4827 }
4828 popt->topt.csvFieldSep[0] = value[0];
4829 }
4830 }
4831
4832 /* locale-aware numeric output */
4833 else if (strcmp(param, "numericlocale") == 0)
4834 {
4835 if (value)
4836 return ParseVariableBool(value, param, &popt->topt.numericLocale);
4837 else
4838 popt->topt.numericLocale = !popt->topt.numericLocale;
4839 }
4840
4841 /* null display */
4842 else if (strcmp(param, "null") == 0)
4843 {
4844 if (value)
4845 {
4846 free(popt->nullPrint);
4847 popt->nullPrint = pg_strdup(value);
4848 }
4849 }
4850
4851 /* field separator for unaligned text */
4852 else if (strcmp(param, "fieldsep") == 0)
4853 {
4854 if (value)
4855 {
4856 free(popt->topt.fieldSep.separator);
4858 popt->topt.fieldSep.separator_zero = false;
4859 }
4860 }
4861
4862 else if (strcmp(param, "fieldsep_zero") == 0)
4863 {
4864 free(popt->topt.fieldSep.separator);
4865 popt->topt.fieldSep.separator = NULL;
4866 popt->topt.fieldSep.separator_zero = true;
4867 }
4868
4869 /* record separator for unaligned text */
4870 else if (strcmp(param, "recordsep") == 0)
4871 {
4872 if (value)
4873 {
4876 popt->topt.recordSep.separator_zero = false;
4877 }
4878 }
4879
4880 else if (strcmp(param, "recordsep_zero") == 0)
4881 {
4883 popt->topt.recordSep.separator = NULL;
4884 popt->topt.recordSep.separator_zero = true;
4885 }
4886
4887 /* toggle between full and tuples-only format */
4888 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
4889 {
4890 if (value)
4891 return ParseVariableBool(value, param, &popt->topt.tuples_only);
4892 else
4893 popt->topt.tuples_only = !popt->topt.tuples_only;
4894 }
4895
4896 /* set title override */
4897 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
4898 {
4899 free(popt->title);
4900 if (!value)
4901 popt->title = NULL;
4902 else
4903 popt->title = pg_strdup(value);
4904 }
4905
4906 /* set HTML table tag options */
4907 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
4908 {
4909 free(popt->topt.tableAttr);
4910 if (!value)
4911 popt->topt.tableAttr = NULL;
4912 else
4913 popt->topt.tableAttr = pg_strdup(value);
4914 }
4915
4916 /* toggle use of pager */
4917 else if (strcmp(param, "pager") == 0)
4918 {
4919 if (value && pg_strcasecmp(value, "always") == 0)
4920 popt->topt.pager = 2;
4921 else if (value)
4922 {
4923 bool on_off;
4924
4925 if (!ParseVariableBool(value, NULL, &on_off))
4926 {
4927 PsqlVarEnumError(param, value, "on, off, always");
4928 return false;
4929 }
4930 popt->topt.pager = on_off ? 1 : 0;
4931 }
4932 else if (popt->topt.pager == 1)
4933 popt->topt.pager = 0;
4934 else
4935 popt->topt.pager = 1;
4936 }
4937
4938 /* set minimum lines for pager use */
4939 else if (strcmp(param, "pager_min_lines") == 0)
4940 {
4941 if (value &&
4942 !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
4943 return false;
4944 }
4945
4946 /* disable "(x rows)" footer */
4947 else if (strcmp(param, "footer") == 0)
4948 {
4949 if (value)
4950 return ParseVariableBool(value, param, &popt->topt.default_footer);
4951 else
4952 popt->topt.default_footer = !popt->topt.default_footer;
4953 }
4954
4955 /* set border style/width */
4956 else if (strcmp(param, "columns") == 0)
4957 {
4958 if (value)
4959 popt->topt.columns = atoi(value);
4960 }
4961 else
4962 {
4963 pg_log_error("\\pset: unknown option: %s", param);
4964 return false;
4965 }
4966
4967 if (!quiet)
4968 printPsetInfo(param, &pset.popt);
4969
4970 return true;
4971}
#define lengthof(array)
Definition: c.h:745
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:4581
static bool printPsetInfo(const char *param, printQueryOpt *popt)
Definition: command.c:4977
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 @162 value
int i
Definition: isn.c:72
static void const char * fmt
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
printQueryOpt popt
Definition: settings.h:100
printTableOpt topt
Definition: print.h:185
char * nullPrint
Definition: print.h:186
char * title
Definition: print.h:187
unsigned short int expanded
Definition: print.h:114
unicode_linestyle unicode_border_linestyle
Definition: print.h:141
bool tuples_only
Definition: print.h:126
int columns
Definition: print.h:140
enum printFormat format
Definition: print.h:113
struct separator fieldSep
Definition: print.h:132
int expanded_header_exact_width
Definition: print.h:118
struct separator recordSep
Definition: print.h:133
printXheaderWidthType expanded_header_width_type
Definition: print.h:116
char csvFieldSep[2]
Definition: print.h:134
const printTextFormat * line_style
Definition: print.h:131
bool default_footer
Definition: print.h:129
int pager_min_lines
Definition: print.h:124
unsigned short int pager
Definition: print.h:122
char * tableAttr
Definition: print.h:137
bool numericLocale
Definition: print.h:135
unsigned short int border
Definition: print.h:120
unicode_linestyle unicode_header_linestyle
Definition: print.h:143
unicode_linestyle unicode_column_linestyle
Definition: print.h:142
bool separator_zero
Definition: print.h:108
char * separator
Definition: print.h:107
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:416
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
bool ParseVariableNum(const char *value, const char *name, int *result)
Definition: variables.c:156
const char * name

References Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::csvFieldSep, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::expanded_header_exact_width, printTableOpt::expanded_header_width_type, printTableOpt::fieldSep, fmt, printTableOpt::format, free, i, lengthof, printTableOpt::line_style, name, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, ParseVariableBool(), ParseVariableNum(), pg_asciiformat, pg_asciiformat_old, pg_log_error, pg_strcasecmp(), pg_strdup(), pg_strncasecmp(), pg_utf8format, _psqlSettings::popt, PRINT_ALIGNED, PRINT_ASCIIDOC, PRINT_CSV, PRINT_HTML, PRINT_LATEX, PRINT_LATEX_LONGTABLE, PRINT_TROFF_MS, PRINT_UNALIGNED, PRINT_WRAPPED, PRINT_XHEADER_COLUMN, PRINT_XHEADER_EXACT_WIDTH, PRINT_XHEADER_FULL, PRINT_XHEADER_PAGE, printPsetInfo(), pset, PsqlVarEnumError(), printTableOpt::recordSep, refresh_utf8format(), separator::separator, separator::separator_zero, set_unicode_line_style(), printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, printTableOpt::unicode_header_linestyle, and value.

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

◆ do_shell()

static bool do_shell ( const char *  command)
static

Definition at line 5373 of file command.c.

5374{
5375 int result;
5376
5377 fflush(NULL);
5378 if (!command)
5379 {
5380 char *sys;
5381 const char *shellName;
5382
5383 shellName = getenv("SHELL");
5384#ifdef WIN32
5385 if (shellName == NULL)
5386 shellName = getenv("COMSPEC");
5387#endif
5388 if (shellName == NULL)
5389 shellName = DEFAULT_SHELL;
5390
5391 /* See EDITOR handling comment for an explanation */
5392#ifndef WIN32
5393 sys = psprintf("exec %s", shellName);
5394#else
5395 sys = psprintf("\"%s\"", shellName);
5396#endif
5397 result = system(sys);
5398 free(sys);
5399 }
5400 else
5401 result = system(command);
5402
5404
5405 if (result == 127 || result == -1)
5406 {
5407 pg_log_error("\\!: failed");
5408 return false;
5409 }
5410 return true;
5411}
void SetShellResultVariables(int wait_result)
Definition: common.c:501
#define DEFAULT_SHELL
Definition: command.c:5363
static void const char fflush(stdout)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43

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

Referenced by exec_command_shell_escape().

◆ do_watch()

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

Definition at line 5424 of file command.c.

5425{
5426 long sleep_ms = (long) (sleep * 1000);
5427 printQueryOpt myopt = pset.popt;
5428 const char *strftime_fmt;
5429 const char *user_title;
5430 char *title;
5431 const char *pagerprog = NULL;
5432 FILE *pagerpipe = NULL;
5433 int title_len;
5434 int res = 0;
5435 bool done = false;
5436#ifndef WIN32
5437 sigset_t sigalrm_sigchld_sigint;
5438 sigset_t sigalrm_sigchld;
5439 sigset_t sigint;
5440 struct itimerval interval;
5441#endif
5442
5443 if (!query_buf || query_buf->len <= 0)
5444 {
5445 pg_log_error("\\watch cannot be used with an empty query");
5446 return false;
5447 }
5448
5449#ifndef WIN32
5450 sigemptyset(&sigalrm_sigchld_sigint);
5451 sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5452 sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5453 sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5454
5455 sigemptyset(&sigalrm_sigchld);
5456 sigaddset(&sigalrm_sigchld, SIGCHLD);
5457 sigaddset(&sigalrm_sigchld, SIGALRM);
5458
5459 sigemptyset(&sigint);
5460 sigaddset(&sigint, SIGINT);
5461
5462 /*
5463 * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5464 * configured), to avoid races. sigwait() will receive them.
5465 */
5466 sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5467
5468 /*
5469 * Set a timer to interrupt sigwait() so we can run the query at the
5470 * requested intervals.
5471 */
5472 interval.it_value.tv_sec = sleep_ms / 1000;
5473 interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5474 interval.it_interval = interval.it_value;
5475 if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5476 {
5477 pg_log_error("could not set timer: %m");
5478 done = true;
5479 }
5480#endif
5481
5482 /*
5483 * For \watch, we ignore the size of the result and always use the pager
5484 * as long as we're talking to a terminal and "\pset pager" is enabled.
5485 * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5486 * ignore the regular PSQL_PAGER or PAGER environment variables, because
5487 * traditional pagers probably won't be very useful for showing a stream
5488 * of results.
5489 */
5490#ifndef WIN32
5491 pagerprog = getenv("PSQL_WATCH_PAGER");
5492 /* if variable is empty or all-white-space, don't use pager */
5493 if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5494 pagerprog = NULL;
5495#endif
5496 if (pagerprog && myopt.topt.pager &&
5497 isatty(fileno(stdin)) && isatty(fileno(stdout)))
5498 {
5499 fflush(NULL);
5501 pagerpipe = popen(pagerprog, "w");
5502
5503 if (!pagerpipe)
5504 /* silently proceed without pager */
5506 }
5507
5508 /*
5509 * Choose format for timestamps. We might eventually make this a \pset
5510 * option. In the meantime, using a variable for the format suppresses
5511 * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5512 */
5513 strftime_fmt = "%c";
5514
5515 /*
5516 * Set up rendering options, in particular, disable the pager unless
5517 * PSQL_WATCH_PAGER was successfully launched.
5518 */
5519 if (!pagerpipe)
5520 myopt.topt.pager = 0;
5521
5522 /*
5523 * If there's a title in the user configuration, make sure we have room
5524 * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5525 * bytes for the rest.
5526 */
5527 user_title = myopt.title;
5528 title_len = (user_title ? strlen(user_title) : 0) + 256;
5529 title = pg_malloc(title_len);
5530
5531 /* Loop to run query and then sleep awhile */
5532 while (!done)
5533 {
5534 time_t timer;
5535 char timebuf[128];
5536
5537 /*
5538 * Prepare title for output. Note that we intentionally include a
5539 * newline at the end of the title; this is somewhat historical but it
5540 * makes for reasonably nicely formatted output in simple cases.
5541 */
5542 timer = time(NULL);
5543 strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5544
5545 if (user_title)
5546 snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5547 user_title, timebuf, sleep_ms / 1000.0);
5548 else
5549 snprintf(title, title_len, _("%s (every %gs)\n"),
5550 timebuf, sleep_ms / 1000.0);
5551 myopt.title = title;
5552
5553 /* Run the query and print out the result */
5554 res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
5555
5556 /*
5557 * PSQLexecWatch handles the case where we can no longer repeat the
5558 * query, and returns 0 or -1.
5559 */
5560 if (res <= 0)
5561 break;
5562
5563 /* If we have iteration count, check that it's not exceeded yet */
5564 if (iter && (--iter <= 0))
5565 break;
5566
5567 /* Quit if error on pager pipe (probably pager has quit) */
5568 if (pagerpipe && ferror(pagerpipe))
5569 break;
5570
5571 /* Tight loop, no wait needed */
5572 if (sleep_ms == 0)
5573 continue;
5574
5575#ifdef WIN32
5576
5577 /*
5578 * Wait a while before running the query again. Break the sleep into
5579 * short intervals (at most 1s); that's probably unnecessary since
5580 * pg_usleep is interruptible on Windows, but it's cheap insurance.
5581 */
5582 for (long i = sleep_ms; i > 0;)
5583 {
5584 long s = Min(i, 1000L);
5585
5586 pg_usleep(s * 1000L);
5587 if (cancel_pressed)
5588 {
5589 done = true;
5590 break;
5591 }
5592 i -= s;
5593 }
5594#else
5595 /* sigwait() will handle SIGINT. */
5596 sigprocmask(SIG_BLOCK, &sigint, NULL);
5597 if (cancel_pressed)
5598 done = true;
5599
5600 /* Wait for SIGINT, SIGCHLD or SIGALRM. */
5601 while (!done)
5602 {
5603 int signal_received;
5604
5605 errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
5606 if (errno != 0)
5607 {
5608 /* Some other signal arrived? */
5609 if (errno == EINTR)
5610 continue;
5611 else
5612 {
5613 pg_log_error("could not wait for signals: %m");
5614 done = true;
5615 break;
5616 }
5617 }
5618 /* On ^C or pager exit, it's time to stop running the query. */
5619 if (signal_received == SIGINT || signal_received == SIGCHLD)
5620 done = true;
5621 /* Otherwise, we must have SIGALRM. Time to run the query again. */
5622 break;
5623 }
5624
5625 /* Unblock SIGINT so that slow queries can be interrupted. */
5626 sigprocmask(SIG_UNBLOCK, &sigint, NULL);
5627#endif
5628 }
5629
5630 if (pagerpipe)
5631 {
5632 pclose(pagerpipe);
5634 }
5635 else
5636 {
5637 /*
5638 * If the terminal driver echoed "^C", libedit/libreadline might be
5639 * confused about the cursor position. Therefore, inject a newline
5640 * before the next prompt is displayed. We only do this when not
5641 * using a pager, because pagers are expected to restore the screen to
5642 * a sane state on exit.
5643 */
5644 fprintf(stdout, "\n");
5645 fflush(stdout);
5646 }
5647
5648#ifndef WIN32
5649 /* Disable the interval timer. */
5650 memset(&interval, 0, sizeof(interval));
5652 /* Unblock SIGINT, SIGCHLD and SIGALRM. */
5653 sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
5654#endif
5655
5656 pg_free(title);
5657 return (res >= 0);
5658}
int PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
Definition: common.c:675
#define Min(x, y)
Definition: c.h:961
#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, fflush(), fprintf, i, ITIMER_REAL, PQExpBufferData::len, Min, printTableOpt::pager, pg_free(), pg_log_error, pg_malloc(), pg_usleep(), _psqlSettings::popt, pset, PSQLexecWatch(), res, restore_sigpipe_trap(), setitimer(), SIGALRM, SIGCHLD, sleep_ms, snprintf, generate_unaccent_rules::stdout, printQueryOpt::title, and printQueryOpt::topt.

Referenced by exec_command_watch().

◆ echo_hidden_command()

static bool echo_hidden_command ( const char *  query)
static

Definition at line 5665 of file command.c.

5666{
5668 {
5669 printf(_("/******** QUERY *********/\n"
5670 "%s\n"
5671 "/************************/\n\n"), query);
5672 fflush(stdout);
5673 if (pset.logfile)
5674 {
5676 _("/******** QUERY *********/\n"
5677 "%s\n"
5678 "/************************/\n\n"), query);
5680 }
5681
5683 return false;
5684 }
5685 return true;
5686}
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
FILE * logfile
Definition: settings.h:131
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:158

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

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ editFile()

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

Definition at line 4194 of file command.c.

4195{
4196 const char *editorName;
4197 const char *editor_lineno_arg = NULL;
4198 char *sys;
4199 int result;
4200
4201 Assert(fname != NULL);
4202
4203 /* Find an editor to use */
4204 editorName = getenv("PSQL_EDITOR");
4205 if (!editorName)
4206 editorName = getenv("EDITOR");
4207 if (!editorName)
4208 editorName = getenv("VISUAL");
4209 if (!editorName)
4210 editorName = DEFAULT_EDITOR;
4211
4212 /* Get line number argument, if we need it. */
4213 if (lineno > 0)
4214 {
4215 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4216#ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4217 if (!editor_lineno_arg)
4218 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4219#endif
4220 if (!editor_lineno_arg)
4221 {
4222 pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4223 return false;
4224 }
4225 }
4226
4227 /*
4228 * On Unix the EDITOR value should *not* be quoted, since it might include
4229 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4230 * if necessary. But this policy is not very workable on Windows, due to
4231 * severe brain damage in their command shell plus the fact that standard
4232 * program paths include spaces.
4233 */
4234#ifndef WIN32
4235 if (lineno > 0)
4236 sys = psprintf("exec %s %s%d '%s'",
4237 editorName, editor_lineno_arg, lineno, fname);
4238 else
4239 sys = psprintf("exec %s '%s'",
4240 editorName, fname);
4241#else
4242 if (lineno > 0)
4243 sys = psprintf("\"%s\" %s%d \"%s\"",
4244 editorName, editor_lineno_arg, lineno, fname);
4245 else
4246 sys = psprintf("\"%s\" \"%s\"",
4247 editorName, fname);
4248#endif
4249 fflush(NULL);
4250 result = system(sys);
4251 if (result == -1)
4252 pg_log_error("could not start editor \"%s\"", editorName);
4253 else if (result == 127)
4254 pg_log_error("could not start /bin/sh");
4255 free(sys);
4256
4257 return result == 0;
4258}
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23
#define DEFAULT_EDITOR
Definition: settings.h:22

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

Referenced by do_edit().

◆ exec_command()

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

Definition at line 291 of file command.c.

296{
297 backslashResult status;
298 bool active_branch = conditional_active(cstack);
299
300 /*
301 * In interactive mode, warn when we're ignoring a command within a false
302 * \if-branch. But we continue on, so as to parse and discard the right
303 * amount of parameter text. Each individual backslash command subroutine
304 * is responsible for doing nothing after discarding appropriate
305 * arguments, if !active_branch.
306 */
307 if (pset.cur_cmd_interactive && !active_branch &&
309 {
310 pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
311 cmd);
312 }
313
314 if (strcmp(cmd, "a") == 0)
315 status = exec_command_a(scan_state, active_branch);
316 else if (strcmp(cmd, "bind") == 0)
317 status = exec_command_bind(scan_state, active_branch);
318 else if (strcmp(cmd, "bind_named") == 0)
319 status = exec_command_bind_named(scan_state, active_branch, cmd);
320 else if (strcmp(cmd, "C") == 0)
321 status = exec_command_C(scan_state, active_branch);
322 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
323 status = exec_command_connect(scan_state, active_branch);
324 else if (strcmp(cmd, "cd") == 0)
325 status = exec_command_cd(scan_state, active_branch, cmd);
326 else if (strcmp(cmd, "close") == 0)
327 status = exec_command_close(scan_state, active_branch, cmd);
328 else if (strcmp(cmd, "conninfo") == 0)
329 status = exec_command_conninfo(scan_state, active_branch);
330 else if (pg_strcasecmp(cmd, "copy") == 0)
331 status = exec_command_copy(scan_state, active_branch);
332 else if (strcmp(cmd, "copyright") == 0)
333 status = exec_command_copyright(scan_state, active_branch);
334 else if (strcmp(cmd, "crosstabview") == 0)
335 status = exec_command_crosstabview(scan_state, active_branch);
336 else if (cmd[0] == 'd')
337 status = exec_command_d(scan_state, active_branch, cmd);
338 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
339 status = exec_command_edit(scan_state, active_branch,
340 query_buf, previous_buf);
341 else if (strcmp(cmd, "ef") == 0)
342 status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
343 else if (strcmp(cmd, "ev") == 0)
344 status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
345 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
346 strcmp(cmd, "warn") == 0)
347 status = exec_command_echo(scan_state, active_branch, cmd);
348 else if (strcmp(cmd, "elif") == 0)
349 status = exec_command_elif(scan_state, cstack, query_buf);
350 else if (strcmp(cmd, "else") == 0)
351 status = exec_command_else(scan_state, cstack, query_buf);
352 else if (strcmp(cmd, "endif") == 0)
353 status = exec_command_endif(scan_state, cstack, query_buf);
354 else if (strcmp(cmd, "encoding") == 0)
355 status = exec_command_encoding(scan_state, active_branch);
356 else if (strcmp(cmd, "errverbose") == 0)
357 status = exec_command_errverbose(scan_state, active_branch);
358 else if (strcmp(cmd, "f") == 0)
359 status = exec_command_f(scan_state, active_branch);
360 else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
361 status = exec_command_g(scan_state, active_branch, cmd);
362 else if (strcmp(cmd, "gdesc") == 0)
363 status = exec_command_gdesc(scan_state, active_branch);
364 else if (strcmp(cmd, "getenv") == 0)
365 status = exec_command_getenv(scan_state, active_branch, cmd);
366 else if (strcmp(cmd, "gexec") == 0)
367 status = exec_command_gexec(scan_state, active_branch);
368 else if (strcmp(cmd, "gset") == 0)
369 status = exec_command_gset(scan_state, active_branch);
370 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
371 status = exec_command_help(scan_state, active_branch);
372 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
373 status = exec_command_html(scan_state, active_branch);
374 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
375 strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
376 status = exec_command_include(scan_state, active_branch, cmd);
377 else if (strcmp(cmd, "if") == 0)
378 status = exec_command_if(scan_state, cstack, query_buf);
379 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
380 strcmp(cmd, "lx") == 0 || strcmp(cmd, "listx") == 0 ||
381 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0 ||
382 strcmp(cmd, "lx+") == 0 || strcmp(cmd, "listx+") == 0 ||
383 strcmp(cmd, "l+x") == 0 || strcmp(cmd, "list+x") == 0)
384 status = exec_command_list(scan_state, active_branch, cmd);
385 else if (strncmp(cmd, "lo_", 3) == 0)
386 status = exec_command_lo(scan_state, active_branch, cmd);
387 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
388 status = exec_command_out(scan_state, active_branch);
389 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
390 status = exec_command_print(scan_state, active_branch,
391 query_buf, previous_buf);
392 else if (strcmp(cmd, "parse") == 0)
393 status = exec_command_parse(scan_state, active_branch, cmd);
394 else if (strcmp(cmd, "password") == 0)
395 status = exec_command_password(scan_state, active_branch);
396 else if (strcmp(cmd, "prompt") == 0)
397 status = exec_command_prompt(scan_state, active_branch, cmd);
398 else if (strcmp(cmd, "pset") == 0)
399 status = exec_command_pset(scan_state, active_branch);
400 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
401 status = exec_command_quit(scan_state, active_branch);
402 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
403 status = exec_command_reset(scan_state, active_branch, query_buf);
404 else if (strcmp(cmd, "s") == 0)
405 status = exec_command_s(scan_state, active_branch);
406 else if (strcmp(cmd, "set") == 0)
407 status = exec_command_set(scan_state, active_branch);
408 else if (strcmp(cmd, "setenv") == 0)
409 status = exec_command_setenv(scan_state, active_branch, cmd);
410 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
411 status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
412 else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
413 status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
414 else if (strcmp(cmd, "t") == 0)
415 status = exec_command_t(scan_state, active_branch);
416 else if (strcmp(cmd, "T") == 0)
417 status = exec_command_T(scan_state, active_branch);
418 else if (strcmp(cmd, "timing") == 0)
419 status = exec_command_timing(scan_state, active_branch);
420 else if (strcmp(cmd, "unset") == 0)
421 status = exec_command_unset(scan_state, active_branch, cmd);
422 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
423 status = exec_command_write(scan_state, active_branch, cmd,
424 query_buf, previous_buf);
425 else if (strcmp(cmd, "watch") == 0)
426 status = exec_command_watch(scan_state, active_branch,
427 query_buf, previous_buf);
428 else if (strcmp(cmd, "x") == 0)
429 status = exec_command_x(scan_state, active_branch);
430 else if (strcmp(cmd, "z") == 0 ||
431 strcmp(cmd, "zS") == 0 || strcmp(cmd, "zx") == 0 ||
432 strcmp(cmd, "zSx") == 0 || strcmp(cmd, "zxS") == 0)
433 status = exec_command_z(scan_state, active_branch, cmd);
434 else if (strcmp(cmd, "!") == 0)
435 status = exec_command_shell_escape(scan_state, active_branch);
436 else if (strcmp(cmd, "?") == 0)
437 status = exec_command_slash_command_help(scan_state, active_branch);
438 else
439 status = PSQL_CMD_UNKNOWN;
440
441 /*
442 * All the commands that return PSQL_CMD_SEND want to execute previous_buf
443 * if query_buf is empty. For convenience we implement that here, not in
444 * the individual command subroutines.
445 */
446 if (status == PSQL_CMD_SEND)
447 (void) copy_previous_query(query_buf, previous_buf);
448
449 return status;
450}
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:2023
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch)
Definition: command.c:812
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1470
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2214
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1776
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:3406
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1528
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2747
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1656
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1756
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch)
Definition: command.c:459
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch)
Definition: command.c:478
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2274
static backslashResult exec_command_bind_named(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:514
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3080
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1836
static backslashResult exec_command_close(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:713
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1882
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1500
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf)
Definition: command.c:2496
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2191
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1386
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:848
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3139
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:649
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1727
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, bool is_func)
Definition: command.c:1270
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2801
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2541
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2514
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2350
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2933
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1795
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2063
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2769
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch)
Definition: command.c:563
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1431
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:1174
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:1958
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
Definition: command.c:746
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch)
Definition: command.c:790
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
Definition: command.c:3161
static backslashResult exec_command_parse(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2240
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
Definition: command.c:824
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2427
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2725
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch, const char *cmd, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:2831
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch, const char *cmd, bool is_func)
Definition: command.c:2642
static bool is_branching_command(const char *cmd)
Definition: command.c:3344
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch)
Definition: command.c:596
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch)
Definition: command.c:1710
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:3102
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2100
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1673
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch)
Definition: command.c:2482
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:2594
@ PSQL_CMD_UNKNOWN
Definition: command.h:17
@ PSQL_CMD_SEND
Definition: command.h:18
enum _backslashResult backslashResult
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:140
#define pg_log_warning(...)
Definition: pgfnames.c:24

References conditional_active(), copy_previous_query(), _psqlSettings::cur_cmd_interactive, exec_command_a(), exec_command_bind(), exec_command_bind_named(), exec_command_C(), exec_command_cd(), exec_command_close(), exec_command_connect(), exec_command_conninfo(), exec_command_copy(), exec_command_copyright(), exec_command_crosstabview(), exec_command_d(), exec_command_echo(), exec_command_edit(), exec_command_ef_ev(), exec_command_elif(), exec_command_else(), exec_command_encoding(), exec_command_endif(), exec_command_errverbose(), exec_command_f(), exec_command_g(), exec_command_gdesc(), exec_command_getenv(), exec_command_gexec(), exec_command_gset(), exec_command_help(), exec_command_html(), exec_command_if(), exec_command_include(), exec_command_list(), exec_command_lo(), exec_command_out(), exec_command_parse(), exec_command_password(), exec_command_print(), exec_command_prompt(), exec_command_pset(), exec_command_quit(), exec_command_reset(), exec_command_s(), exec_command_set(), exec_command_setenv(), exec_command_sf_sv(), exec_command_shell_escape(), exec_command_slash_command_help(), exec_command_t(), exec_command_T(), exec_command_timing(), exec_command_unset(), exec_command_watch(), exec_command_write(), exec_command_x(), exec_command_z(), is_branching_command(), pg_log_warning, pg_strcasecmp(), pset, PSQL_CMD_SEND, and PSQL_CMD_UNKNOWN.

Referenced by HandleSlashCmds().

◆ exec_command_a()

static backslashResult exec_command_a ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 459 of file command.c.

460{
461 bool success = true;
462
463 if (active_branch)
464 {
466 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
467 else
468 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
469 }
470
472}
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4624
@ 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 478 of file command.c.

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

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

Referenced by exec_command().

◆ exec_command_bind_named()

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

Definition at line 514 of file command.c.

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

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

Referenced by exec_command().

◆ exec_command_C()

static backslashResult exec_command_C ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 563 of file command.c.

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

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

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

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

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

Referenced by exec_command().

◆ exec_command_connect()

static backslashResult exec_command_connect ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 596 of file command.c.

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

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

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

Referenced by exec_command().

◆ exec_command_copy()

static backslashResult exec_command_copy ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 790 of file command.c.

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

813{
814 if (active_branch)
816
817 return PSQL_CMD_SKIP_LINE;
818}
void print_copyright(void)
Definition: help.c:733

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

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

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

Referenced by exec_command().

◆ exec_command_d()

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

Definition at line 848 of file command.c.

849{
851 bool success = true;
852
853 if (active_branch)
854 {
855 char *pattern;
856 bool show_verbose,
857 show_system;
858 unsigned short int save_expanded;
859
860 /* We don't do SQLID reduction on the pattern yet */
861 pattern = psql_scan_slash_option(scan_state,
862 OT_NORMAL, NULL, true);
863
864 show_verbose = strchr(cmd, '+') ? true : false;
865 show_system = strchr(cmd, 'S') ? true : false;
866
867 /*
868 * The 'x' option turns expanded mode on for this command only. This
869 * is allowed in all \d* commands, except \d by itself, since \dx is a
870 * separate command. So the 'x' option cannot appear immediately after
871 * \d, but it can appear after \d followed by other options.
872 */
873 save_expanded = pset.popt.topt.expanded;
874 if (cmd[1] != '\0' && strchr(&cmd[2], 'x'))
876
877 switch (cmd[1])
878 {
879 case '\0':
880 case '+':
881 case 'S':
882 if (pattern)
883 success = describeTableDetails(pattern, show_verbose, show_system);
884 else
885 /* standard listing of interesting things */
886 success = listTables("tvmsE", NULL, show_verbose, show_system);
887 break;
888 case 'A':
889 {
890 char *pattern2 = NULL;
891
892 if (pattern && cmd[2] != '\0' && cmd[2] != '+' && cmd[2] != 'x')
893 pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
894
895 switch (cmd[2])
896 {
897 case '\0':
898 case '+':
899 case 'x':
900 success = describeAccessMethods(pattern, show_verbose);
901 break;
902 case 'c':
903 success = listOperatorClasses(pattern, pattern2, show_verbose);
904 break;
905 case 'f':
906 success = listOperatorFamilies(pattern, pattern2, show_verbose);
907 break;
908 case 'o':
909 success = listOpFamilyOperators(pattern, pattern2, show_verbose);
910 break;
911 case 'p':
912 success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
913 break;
914 default:
915 status = PSQL_CMD_UNKNOWN;
916 break;
917 }
918
919 free(pattern2);
920 }
921 break;
922 case 'a':
923 success = describeAggregates(pattern, show_verbose, show_system);
924 break;
925 case 'b':
926 success = describeTablespaces(pattern, show_verbose);
927 break;
928 case 'c':
929 if (strncmp(cmd, "dconfig", 7) == 0)
931 show_verbose,
932 show_system);
933 else
934 success = listConversions(pattern,
935 show_verbose,
936 show_system);
937 break;
938 case 'C':
939 success = listCasts(pattern, show_verbose);
940 break;
941 case 'd':
942 if (strncmp(cmd, "ddp", 3) == 0)
943 success = listDefaultACLs(pattern);
944 else
945 success = objectDescription(pattern, show_system);
946 break;
947 case 'D':
948 success = listDomains(pattern, show_verbose, show_system);
949 break;
950 case 'f': /* function subsystem */
951 switch (cmd[2])
952 {
953 case '\0':
954 case '+':
955 case 'S':
956 case 'a':
957 case 'n':
958 case 'p':
959 case 't':
960 case 'w':
961 case 'x':
962 success = exec_command_dfo(scan_state, cmd, pattern,
963 show_verbose, show_system);
964 break;
965 default:
966 status = PSQL_CMD_UNKNOWN;
967 break;
968 }
969 break;
970 case 'g':
971 /* no longer distinct from \du */
972 success = describeRoles(pattern, show_verbose, show_system);
973 break;
974 case 'l':
975 success = listLargeObjects(show_verbose);
976 break;
977 case 'L':
978 success = listLanguages(pattern, show_verbose, show_system);
979 break;
980 case 'n':
981 success = listSchemas(pattern, show_verbose, show_system);
982 break;
983 case 'o':
984 success = exec_command_dfo(scan_state, cmd, pattern,
985 show_verbose, show_system);
986 break;
987 case 'O':
988 success = listCollations(pattern, show_verbose, show_system);
989 break;
990 case 'p':
991 success = permissionsList(pattern, show_system);
992 break;
993 case 'P':
994 {
995 switch (cmd[2])
996 {
997 case '\0':
998 case '+':
999 case 't':
1000 case 'i':
1001 case 'n':
1002 case 'x':
1003 success = listPartitionedTables(&cmd[2], pattern, show_verbose);
1004 break;
1005 default:
1006 status = PSQL_CMD_UNKNOWN;
1007 break;
1008 }
1009 }
1010 break;
1011 case 'T':
1012 success = describeTypes(pattern, show_verbose, show_system);
1013 break;
1014 case 't':
1015 case 'v':
1016 case 'm':
1017 case 'i':
1018 case 's':
1019 case 'E':
1020 success = listTables(&cmd[1], pattern, show_verbose, show_system);
1021 break;
1022 case 'r':
1023 if (cmd[2] == 'd' && cmd[3] == 's')
1024 {
1025 char *pattern2 = NULL;
1026
1027 if (pattern)
1028 pattern2 = psql_scan_slash_option(scan_state,
1029 OT_NORMAL, NULL, true);
1030 success = listDbRoleSettings(pattern, pattern2);
1031
1032 free(pattern2);
1033 }
1034 else if (cmd[2] == 'g')
1035 success = describeRoleGrants(pattern, show_system);
1036 else
1037 status = PSQL_CMD_UNKNOWN;
1038 break;
1039 case 'R':
1040 switch (cmd[2])
1041 {
1042 case 'p':
1043 if (show_verbose)
1044 success = describePublications(pattern);
1045 else
1046 success = listPublications(pattern);
1047 break;
1048 case 's':
1049 success = describeSubscriptions(pattern, show_verbose);
1050 break;
1051 default:
1052 status = PSQL_CMD_UNKNOWN;
1053 }
1054 break;
1055 case 'u':
1056 success = describeRoles(pattern, show_verbose, show_system);
1057 break;
1058 case 'F': /* text search subsystem */
1059 switch (cmd[2])
1060 {
1061 case '\0':
1062 case '+':
1063 case 'x':
1064 success = listTSConfigs(pattern, show_verbose);
1065 break;
1066 case 'p':
1067 success = listTSParsers(pattern, show_verbose);
1068 break;
1069 case 'd':
1070 success = listTSDictionaries(pattern, show_verbose);
1071 break;
1072 case 't':
1073 success = listTSTemplates(pattern, show_verbose);
1074 break;
1075 default:
1076 status = PSQL_CMD_UNKNOWN;
1077 break;
1078 }
1079 break;
1080 case 'e': /* SQL/MED subsystem */
1081 switch (cmd[2])
1082 {
1083 case 's':
1084 success = listForeignServers(pattern, show_verbose);
1085 break;
1086 case 'u':
1087 success = listUserMappings(pattern, show_verbose);
1088 break;
1089 case 'w':
1090 success = listForeignDataWrappers(pattern, show_verbose);
1091 break;
1092 case 't':
1093 success = listForeignTables(pattern, show_verbose);
1094 break;
1095 default:
1096 status = PSQL_CMD_UNKNOWN;
1097 break;
1098 }
1099 break;
1100 case 'x': /* Extensions */
1101 if (show_verbose)
1102 success = listExtensionContents(pattern);
1103 else
1104 success = listExtensions(pattern);
1105 break;
1106 case 'X': /* Extended Statistics */
1107 success = listExtendedStats(pattern);
1108 break;
1109 case 'y': /* Event Triggers */
1110 success = listEventTriggers(pattern, show_verbose);
1111 break;
1112 default:
1113 status = PSQL_CMD_UNKNOWN;
1114 }
1115
1116 /* Restore original expanded mode */
1117 pset.popt.topt.expanded = save_expanded;
1118
1119 free(pattern);
1120 }
1121 else
1122 ignore_slash_options(scan_state);
1123
1124 if (!success)
1125 status = PSQL_CMD_ERROR;
1126
1127 return status;
1128}
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd, const char *pattern, bool show_verbose, bool show_system)
Definition: command.c:1132
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:7192
bool listPublications(const char *pattern)
Definition: describe.c:6397
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:5327
bool listExtensionContents(const char *pattern)
Definition: describe.c:6233
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:6743
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:6996
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:7085
bool listOperatorClasses(const char *access_method_pattern, const char *type_pattern, bool verbose)
Definition: describe.c:6895
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:7281
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:4476
bool describePublications(const char *pattern)
Definition: describe.c:6528
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1290
return true
Definition: isn.c:125

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

1135{
1136 bool success;
1137 char *arg_patterns[FUNC_MAX_ARGS];
1138 int num_arg_patterns = 0;
1139
1140 /* Collect argument-type patterns too */
1141 if (pattern) /* otherwise it was just \df or \do */
1142 {
1143 char *ap;
1144
1145 while ((ap = psql_scan_slash_option(scan_state,
1146 OT_NORMAL, NULL, true)) != NULL)
1147 {
1148 arg_patterns[num_arg_patterns++] = ap;
1149 if (num_arg_patterns >= FUNC_MAX_ARGS)
1150 break; /* protect limited-size array */
1151 }
1152 }
1153
1154 if (cmd[1] == 'f')
1155 success = describeFunctions(&cmd[2], pattern,
1156 arg_patterns, num_arg_patterns,
1157 show_verbose, show_system);
1158 else
1159 success = describeOperators(pattern,
1160 arg_patterns, num_arg_patterns,
1161 show_verbose, show_system);
1162
1163 while (--num_arg_patterns >= 0)
1164 free(arg_patterns[num_arg_patterns]);
1165
1166 return success;
1167}
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 1386 of file command.c.

1387{
1388 if (active_branch)
1389 {
1390 char *value;
1391 char quoted;
1392 bool no_newline = false;
1393 bool first = true;
1394 FILE *fout;
1395
1396 if (strcmp(cmd, "qecho") == 0)
1397 fout = pset.queryFout;
1398 else if (strcmp(cmd, "warn") == 0)
1399 fout = stderr;
1400 else
1401 fout = stdout;
1402
1403 while ((value = psql_scan_slash_option(scan_state,
1404 OT_NORMAL, &quoted, false)))
1405 {
1406 if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1407 no_newline = true;
1408 else
1409 {
1410 if (first)
1411 first = false;
1412 else
1413 fputc(' ', fout);
1414 fputs(value, fout);
1415 }
1416 free(value);
1417 }
1418 if (!no_newline)
1419 fputs("\n", fout);
1420 }
1421 else
1422 ignore_slash_options(scan_state);
1423
1424 return PSQL_CMD_SKIP_LINE;
1425}
FILE * queryFout
Definition: settings.h:93

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

Referenced by exec_command().

◆ exec_command_edit()

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

Definition at line 1174 of file command.c.

1176{
1178
1179 if (active_branch)
1180 {
1181 if (!query_buf)
1182 {
1183 pg_log_error("no query buffer");
1184 status = PSQL_CMD_ERROR;
1185 }
1186 else
1187 {
1188 char *fname;
1189 char *ln = NULL;
1190 int lineno = -1;
1191
1192 fname = psql_scan_slash_option(scan_state,
1193 OT_NORMAL, NULL, true);
1194 if (fname)
1195 {
1196 /* try to get separate lineno arg */
1197 ln = psql_scan_slash_option(scan_state,
1198 OT_NORMAL, NULL, true);
1199 if (ln == NULL)
1200 {
1201 /* only one arg; maybe it is lineno not fname */
1202 if (fname[0] &&
1203 strspn(fname, "0123456789") == strlen(fname))
1204 {
1205 /* all digits, so assume it is lineno */
1206 ln = fname;
1207 fname = NULL;
1208 }
1209 }
1210 }
1211 if (ln)
1212 {
1213 lineno = atoi(ln);
1214 if (lineno < 1)
1215 {
1216 pg_log_error("invalid line number: %s", ln);
1217 status = PSQL_CMD_ERROR;
1218 }
1219 }
1220 if (status != PSQL_CMD_ERROR)
1221 {
1222 bool discard_on_quit;
1223
1224 expand_tilde(&fname);
1225 if (fname)
1226 {
1228 /* Always clear buffer if the file isn't modified */
1229 discard_on_quit = true;
1230 }
1231 else
1232 {
1233 /*
1234 * If query_buf is empty, recall previous query for
1235 * editing. But in that case, the query buffer should be
1236 * emptied if editing doesn't modify the file.
1237 */
1238 discard_on_quit = copy_previous_query(query_buf,
1239 previous_buf);
1240 }
1241
1242 if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1243 status = PSQL_CMD_NEWEDIT;
1244 else
1245 status = PSQL_CMD_ERROR;
1246 }
1247
1248 /*
1249 * On error while editing or if specifying an incorrect line
1250 * number, reset the query buffer.
1251 */
1252 if (status == PSQL_CMD_ERROR)
1253 resetPQExpBuffer(query_buf);
1254
1255 free(fname);
1256 free(ln);
1257 }
1258 }
1259 else
1260 ignore_slash_options(scan_state);
1261
1262 return status;
1263}
void expand_tilde(char **filename)
Definition: common.c:2195
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool discard_on_quit, bool *edited)
Definition: command.c:4276
@ PSQL_CMD_NEWEDIT
Definition: command.h:21
void canonicalize_path_enc(char *path, int encoding)
Definition: path.c:344
int encoding
Definition: settings.h:92

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

1272{
1274
1275 if (active_branch)
1276 {
1277 char *obj_desc = psql_scan_slash_option(scan_state,
1279 NULL, true);
1280 int lineno = -1;
1281
1282 if (!query_buf)
1283 {
1284 pg_log_error("no query buffer");
1285 status = PSQL_CMD_ERROR;
1286 }
1287 else
1288 {
1289 Oid obj_oid = InvalidOid;
1291
1292 lineno = strip_lineno_from_objdesc(obj_desc);
1293 if (lineno == 0)
1294 {
1295 /* error already reported */
1296 status = PSQL_CMD_ERROR;
1297 }
1298 else if (!obj_desc)
1299 {
1300 /* set up an empty command to fill in */
1301 resetPQExpBuffer(query_buf);
1302 if (is_func)
1303 appendPQExpBufferStr(query_buf,
1304 "CREATE FUNCTION ( )\n"
1305 " RETURNS \n"
1306 " LANGUAGE \n"
1307 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1308 "AS $function$\n"
1309 "\n$function$\n");
1310 else
1311 appendPQExpBufferStr(query_buf,
1312 "CREATE VIEW AS\n"
1313 " SELECT \n"
1314 " -- something...\n");
1315 }
1316 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1317 {
1318 /* error already reported */
1319 status = PSQL_CMD_ERROR;
1320 }
1321 else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1322 {
1323 /* error already reported */
1324 status = PSQL_CMD_ERROR;
1325 }
1326 else if (is_func && lineno > 0)
1327 {
1328 /*
1329 * lineno "1" should correspond to the first line of the
1330 * function body. We expect that pg_get_functiondef() will
1331 * emit that on a line beginning with "AS ", "BEGIN ", or
1332 * "RETURN ", and that there can be no such line before the
1333 * real start of the function body. Increment lineno by the
1334 * number of lines before that line, so that it becomes
1335 * relative to the first line of the function definition.
1336 */
1337 const char *lines = query_buf->data;
1338
1339 while (*lines != '\0')
1340 {
1341 if (strncmp(lines, "AS ", 3) == 0 ||
1342 strncmp(lines, "BEGIN ", 6) == 0 ||
1343 strncmp(lines, "RETURN ", 7) == 0)
1344 break;
1345 lineno++;
1346 /* find start of next line */
1347 lines = strchr(lines, '\n');
1348 if (!lines)
1349 break;
1350 lines++;
1351 }
1352 }
1353 }
1354
1355 if (status != PSQL_CMD_ERROR)
1356 {
1357 bool edited = false;
1358
1359 if (!do_edit(NULL, query_buf, lineno, true, &edited))
1360 status = PSQL_CMD_ERROR;
1361 else if (!edited)
1362 puts(_("No changes"));
1363 else
1364 status = PSQL_CMD_NEWEDIT;
1365 }
1366
1367 /*
1368 * On error while doing object lookup or while editing, or if
1369 * specifying an incorrect line number, reset the query buffer.
1370 */
1371 if (status == PSQL_CMD_ERROR)
1372 resetPQExpBuffer(query_buf);
1373
1374 free(obj_desc);
1375 }
1376 else
1377 ignore_slash_whole_line(scan_state);
1378
1379 return status;
1380}
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:5757
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:5697
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:5917
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32

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

1884{
1885 bool success = true;
1886
1887 switch (conditional_stack_peek(cstack))
1888 {
1889 case IFSTATE_TRUE:
1890
1891 /*
1892 * Just finished active branch of this \if block. Update saved
1893 * state so we will keep whatever data was put in query_buf by the
1894 * active branch.
1895 */
1896 save_query_text_state(scan_state, cstack, query_buf);
1897
1898 /*
1899 * Discard \elif expression and ignore the rest until \endif.
1900 * Switch state before reading expression to ensure proper lexer
1901 * behavior.
1902 */
1904 ignore_boolean_expression(scan_state);
1905 break;
1906 case IFSTATE_FALSE:
1907
1908 /*
1909 * Discard any query text added by the just-skipped branch.
1910 */
1911 discard_query_text(scan_state, cstack, query_buf);
1912
1913 /*
1914 * Have not yet found a true expression in this \if block, so this
1915 * might be the first. We have to change state before examining
1916 * the expression, or the lexer won't do the right thing.
1917 */
1919 if (!is_true_boolean_expression(scan_state, "\\elif expression"))
1921 break;
1922 case IFSTATE_IGNORED:
1923
1924 /*
1925 * Discard any query text added by the just-skipped branch.
1926 */
1927 discard_query_text(scan_state, cstack, query_buf);
1928
1929 /*
1930 * Skip expression and move on. Either the \if block already had
1931 * an active section, or whole block is being skipped.
1932 */
1933 ignore_boolean_expression(scan_state);
1934 break;
1935 case IFSTATE_ELSE_TRUE:
1936 case IFSTATE_ELSE_FALSE:
1937 pg_log_error("\\elif: cannot occur after \\else");
1938 success = false;
1939 break;
1940 case IFSTATE_NONE:
1941 /* no \if to elif from */
1942 pg_log_error("\\elif: no matching \\if");
1943 success = false;
1944 break;
1945 }
1946
1948}
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3380
static void ignore_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3279
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name)
Definition: command.c:3262
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf)
Definition: command.c:3360
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 1958 of file command.c.

1960{
1961 bool success = true;
1962
1963 switch (conditional_stack_peek(cstack))
1964 {
1965 case IFSTATE_TRUE:
1966
1967 /*
1968 * Just finished active branch of this \if block. Update saved
1969 * state so we will keep whatever data was put in query_buf by the
1970 * active branch.
1971 */
1972 save_query_text_state(scan_state, cstack, query_buf);
1973
1974 /* Now skip the \else branch */
1976 break;
1977 case IFSTATE_FALSE:
1978
1979 /*
1980 * Discard any query text added by the just-skipped branch.
1981 */
1982 discard_query_text(scan_state, cstack, query_buf);
1983
1984 /*
1985 * We've not found any true \if or \elif expression, so execute
1986 * the \else branch.
1987 */
1989 break;
1990 case IFSTATE_IGNORED:
1991
1992 /*
1993 * Discard any query text added by the just-skipped branch.
1994 */
1995 discard_query_text(scan_state, cstack, query_buf);
1996
1997 /*
1998 * Either we previously processed the active branch of this \if,
1999 * or the whole \if block is being skipped. Either way, skip the
2000 * \else branch.
2001 */
2003 break;
2004 case IFSTATE_ELSE_TRUE:
2005 case IFSTATE_ELSE_FALSE:
2006 pg_log_error("\\else: cannot occur after \\else");
2007 success = false;
2008 break;
2009 case IFSTATE_NONE:
2010 /* no \if to else from */
2011 pg_log_error("\\else: no matching \\if");
2012 success = false;
2013 break;
2014 }
2015
2017}

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

1432{
1433 if (active_branch)
1434 {
1435 char *encoding = psql_scan_slash_option(scan_state,
1436 OT_NORMAL, NULL, false);
1437
1438 if (!encoding)
1439 {
1440 /* show encoding */
1442 }
1443 else
1444 {
1445 /* set encoding */
1446 if (PQsetClientEncoding(pset.db, encoding) == -1)
1447 pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1448 else
1449 {
1450 /* save encoding info into psql internal data */
1454 SetVariable(pset.vars, "ENCODING",
1456 }
1457 free(encoding);
1458 }
1459 }
1460 else
1461 ignore_slash_options(scan_state);
1462
1463 return PSQL_CMD_SKIP_LINE;
1464}
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7597
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7605
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:133
int encoding
Definition: print.h:138
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211

References _psqlSettings::db, _psqlSettings::encoding, encoding, printTableOpt::encoding, free, ignore_slash_options(), OT_NORMAL, pg_encoding_to_char, pg_log_error, _psqlSettings::popt, PQclientEncoding(), PQsetClientEncoding(), pset, PSQL_CMD_SKIP_LINE, psql_scan_slash_option(), 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 2023 of file command.c.

2025{
2026 bool success = true;
2027
2028 switch (conditional_stack_peek(cstack))
2029 {
2030 case IFSTATE_TRUE:
2031 case IFSTATE_ELSE_TRUE:
2032 /* Close the \if block, keeping the query text */
2034 Assert(success);
2035 break;
2036 case IFSTATE_FALSE:
2037 case IFSTATE_IGNORED:
2038 case IFSTATE_ELSE_FALSE:
2039
2040 /*
2041 * Discard any query text added by the just-skipped branch.
2042 */
2043 discard_query_text(scan_state, cstack, query_buf);
2044
2045 /* Close the \if block */
2047 Assert(success);
2048 break;
2049 case IFSTATE_NONE:
2050 /* no \if to end */
2051 pg_log_error("\\endif: no matching \\if");
2052 success = false;
2053 break;
2054 }
2055
2057}
bool conditional_stack_pop(ConditionalStack cstack)
Definition: conditional.c:69

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

Referenced by exec_command().

◆ exec_command_errverbose()

static backslashResult exec_command_errverbose ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1470 of file command.c.

1471{
1472 if (active_branch)
1473 {
1475 {
1476 char *msg;
1477
1481 if (msg)
1482 {
1483 pg_log_error("%s", msg);
1484 PQfreemem(msg);
1485 }
1486 else
1487 puts(_("out of memory"));
1488 }
1489 else
1490 puts(_("There is no previous error."));
1491 }
1492
1493 return PSQL_CMD_SKIP_LINE;
1494}
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3435
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:163
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:155
PGresult * last_error_result
Definition: settings.h:98

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

Referenced by exec_command().

◆ exec_command_f()

static backslashResult exec_command_f ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1500 of file command.c.

1501{
1502 bool success = true;
1503
1504 if (active_branch)
1505 {
1506 char *fname = psql_scan_slash_option(scan_state,
1507 OT_NORMAL, NULL, false);
1508
1509 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1510 free(fname);
1511 }
1512 else
1513 ignore_slash_options(scan_state);
1514
1516}

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

Referenced by exec_command().

◆ exec_command_g()

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

Definition at line 1528 of file command.c.

1529{
1531 char *fname;
1532
1533 /*
1534 * Because the option processing for this is fairly complicated, we do it
1535 * and then decide whether the branch is active.
1536 */
1537 fname = psql_scan_slash_option(scan_state,
1538 OT_FILEPIPE, NULL, false);
1539
1540 if (fname && fname[0] == '(')
1541 {
1542 /* Consume pset options through trailing ')' ... */
1543 status = process_command_g_options(fname + 1, scan_state,
1544 active_branch, cmd);
1545 free(fname);
1546 /* ... and again attempt to scan the filename. */
1547 fname = psql_scan_slash_option(scan_state,
1548 OT_FILEPIPE, NULL, false);
1549 }
1550
1551 if (status == PSQL_CMD_SKIP_LINE && active_branch)
1552 {
1553 if (!fname)
1554 pset.gfname = NULL;
1555 else
1556 {
1557 expand_tilde(&fname);
1558 pset.gfname = pg_strdup(fname);
1559 }
1560 if (strcmp(cmd, "gx") == 0)
1561 {
1562 /* save settings if not done already, then force expanded=on */
1563 if (pset.gsavepopt == NULL)
1565 pset.popt.topt.expanded = 1;
1566 }
1567 status = PSQL_CMD_SEND;
1568 }
1569
1570 free(fname);
1571
1572 return status;
1573}
printQueryOpt * savePsetInfo(const printQueryOpt *popt)
Definition: command.c:5177
static backslashResult process_command_g_options(char *first_option, PsqlScanState scan_state, bool active_branch, const char *cmd)
Definition: command.c:1581
@ OT_FILEPIPE
Definition: psqlscanslash.h:20
printQueryOpt * gsavepopt
Definition: settings.h:103
char * gfname
Definition: settings.h:102

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

Referenced by exec_command().

◆ exec_command_gdesc()

static backslashResult exec_command_gdesc ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1656 of file command.c.

1657{
1659
1660 if (active_branch)
1661 {
1662 pset.gdesc_flag = true;
1663 status = PSQL_CMD_SEND;
1664 }
1665
1666 return status;
1667}
bool gdesc_flag
Definition: settings.h:106

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

Referenced by exec_command().

◆ exec_command_getenv()

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

Definition at line 1673 of file command.c.

1675{
1676 bool success = true;
1677
1678 if (active_branch)
1679 {
1680 char *myvar = psql_scan_slash_option(scan_state,
1681 OT_NORMAL, NULL, false);
1682 char *envvar = psql_scan_slash_option(scan_state,
1683 OT_NORMAL, NULL, false);
1684
1685 if (!myvar || !envvar)
1686 {
1687 pg_log_error("\\%s: missing required argument", cmd);
1688 success = false;
1689 }
1690 else
1691 {
1692 char *envval = getenv(envvar);
1693
1694 if (envval && !SetVariable(pset.vars, myvar, envval))
1695 success = false;
1696 }
1697 free(myvar);
1698 free(envvar);
1699 }
1700 else
1701 ignore_slash_options(scan_state);
1702
1704}

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

Referenced by exec_command().

◆ exec_command_gexec()

static backslashResult exec_command_gexec ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1710 of file command.c.

1711{
1713
1714 if (active_branch)
1715 {
1716 pset.gexec_flag = true;
1717 status = PSQL_CMD_SEND;
1718 }
1719
1720 return status;
1721}
bool gexec_flag
Definition: settings.h:107

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

Referenced by exec_command().

◆ exec_command_gset()

static backslashResult exec_command_gset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1727 of file command.c.

1728{
1730
1731 if (active_branch)
1732 {
1733 char *prefix = psql_scan_slash_option(scan_state,
1734 OT_NORMAL, NULL, false);
1735
1736 if (prefix)
1737 pset.gset_prefix = prefix;
1738 else
1739 {
1740 /* we must set a non-NULL prefix to trigger storing */
1742 }
1743 /* gset_prefix is freed later */
1744 status = PSQL_CMD_SEND;
1745 }
1746 else
1747 ignore_slash_options(scan_state);
1748
1749 return status;
1750}
char * gset_prefix
Definition: settings.h:105

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

Referenced by exec_command().

◆ exec_command_help()

static backslashResult exec_command_help ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 1756 of file command.c.

1757{
1758 if (active_branch)
1759 {
1760 char *opt = psql_scan_slash_option(scan_state,
1761 OT_WHOLE_LINE, NULL, true);
1762
1763 helpSQL(opt, pset.popt.topt.pager);
1764 free(opt);
1765 }
1766 else
1767 ignore_slash_whole_line(scan_state);
1768
1769 return PSQL_CMD_SKIP_LINE;
1770}
void helpSQL(const char *topic, unsigned short int pager)
Definition: help.c:571

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

1777{
1778 bool success = true;
1779
1780 if (active_branch)
1781 {
1783 success = do_pset("format", "html", &pset.popt, pset.quiet);
1784 else
1785 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
1786 }
1787
1789}

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

1838{
1839 if (conditional_active(cstack))
1840 {
1841 /*
1842 * First, push a new active stack entry; this ensures that the lexer
1843 * will perform variable substitution and backtick evaluation while
1844 * scanning the expression. (That should happen anyway, since we know
1845 * we're in an active outer branch, but let's be sure.)
1846 */
1848
1849 /* Remember current query state in case we need to restore later */
1850 save_query_text_state(scan_state, cstack, query_buf);
1851
1852 /*
1853 * Evaluate the expression; if it's false, change to inactive state.
1854 */
1855 if (!is_true_boolean_expression(scan_state, "\\if expression"))
1857 }
1858 else
1859 {
1860 /*
1861 * We're within an inactive outer branch, so this entire \if block
1862 * will be ignored. We don't want to evaluate the expression, so push
1863 * the "ignored" stack state before scanning it.
1864 */
1866
1867 /* Remember current query state in case we need to restore later */
1868 save_query_text_state(scan_state, cstack, query_buf);
1869
1870 ignore_boolean_expression(scan_state);
1871 }
1872
1873 return PSQL_CMD_SKIP_LINE;
1874}
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 1795 of file command.c.

1796{
1797 bool success = true;
1798
1799 if (active_branch)
1800 {
1801 char *fname = psql_scan_slash_option(scan_state,
1802 OT_NORMAL, NULL, true);
1803
1804 if (!fname)
1805 {
1806 pg_log_error("\\%s: missing required argument", cmd);
1807 success = false;
1808 }
1809 else
1810 {
1811 bool include_relative;
1812
1813 include_relative = (strcmp(cmd, "ir") == 0
1814 || strcmp(cmd, "include_relative") == 0);
1815 expand_tilde(&fname);
1816 success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1817 free(fname);
1818 }
1819 }
1820 else
1821 ignore_slash_options(scan_state);
1822
1824}
int process_file(char *filename, bool use_relative_path)
Definition: command.c:4471
#define EXIT_SUCCESS
Definition: settings.h:174

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

Referenced by exec_command().

◆ exec_command_list()

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

Definition at line 2063 of file command.c.

2064{
2065 bool success = true;
2066
2067 if (active_branch)
2068 {
2069 char *pattern;
2070 bool show_verbose;
2071 unsigned short int save_expanded;
2072
2073 pattern = psql_scan_slash_option(scan_state,
2074 OT_NORMAL, NULL, true);
2075
2076 show_verbose = strchr(cmd, '+') ? true : false;
2077
2078 /* if 'x' option specified, force expanded mode */
2079 save_expanded = pset.popt.topt.expanded;
2080 if (strchr(cmd, 'x'))
2081 pset.popt.topt.expanded = 1;
2082
2083 success = listAllDbs(pattern, show_verbose);
2084
2085 /* restore original expanded mode */
2086 pset.popt.topt.expanded = save_expanded;
2087
2088 free(pattern);
2089 }
2090 else
2091 ignore_slash_options(scan_state);
2092
2094}
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 2100 of file command.c.

2101{
2103 bool success = true;
2104
2105 if (active_branch)
2106 {
2107 char *opt1,
2108 *opt2;
2109
2110 opt1 = psql_scan_slash_option(scan_state,
2111 OT_NORMAL, NULL, true);
2112 opt2 = psql_scan_slash_option(scan_state,
2113 OT_NORMAL, NULL, true);
2114
2115 if (strcmp(cmd + 3, "export") == 0)
2116 {
2117 if (!opt2)
2118 {
2119 pg_log_error("\\%s: missing required argument", cmd);
2120 success = false;
2121 }
2122 else
2123 {
2124 expand_tilde(&opt2);
2125 success = do_lo_export(opt1, opt2);
2126 }
2127 }
2128
2129 else if (strcmp(cmd + 3, "import") == 0)
2130 {
2131 if (!opt1)
2132 {
2133 pg_log_error("\\%s: missing required argument", cmd);
2134 success = false;
2135 }
2136 else
2137 {
2138 expand_tilde(&opt1);
2139 success = do_lo_import(opt1, opt2);
2140 }
2141 }
2142
2143 else if (strncmp(cmd + 3, "list", 4) == 0)
2144 {
2145 bool show_verbose;
2146 unsigned short int save_expanded;
2147
2148 show_verbose = strchr(cmd, '+') ? true : false;
2149
2150 /* if 'x' option specified, force expanded mode */
2151 save_expanded = pset.popt.topt.expanded;
2152 if (strchr(cmd, 'x'))
2153 pset.popt.topt.expanded = 1;
2154
2155 success = listLargeObjects(show_verbose);
2156
2157 /* restore original expanded mode */
2158 pset.popt.topt.expanded = save_expanded;
2159 }
2160
2161 else if (strcmp(cmd + 3, "unlink") == 0)
2162 {
2163 if (!opt1)
2164 {
2165 pg_log_error("\\%s: missing required argument", cmd);
2166 success = false;
2167 }
2168 else
2169 success = do_lo_unlink(opt1);
2170 }
2171
2172 else
2173 status = PSQL_CMD_UNKNOWN;
2174
2175 free(opt1);
2176 free(opt2);
2177 }
2178 else
2179 ignore_slash_options(scan_state);
2180
2181 if (!success)
2182 status = PSQL_CMD_ERROR;
2183
2184 return status;
2185}
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 2191 of file command.c.

2192{
2193 bool success = true;
2194
2195 if (active_branch)
2196 {
2197 char *fname = psql_scan_slash_option(scan_state,
2198 OT_FILEPIPE, NULL, true);
2199
2200 expand_tilde(&fname);
2201 success = setQFout(fname);
2202 free(fname);
2203 }
2204 else
2205 ignore_slash_filepipe(scan_state);
2206
2208}
bool setQFout(const char *fname)
Definition: common.c:132
static void ignore_slash_filepipe(PsqlScanState scan_state)
Definition: command.c:3312

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

2242{
2244
2245 if (active_branch)
2246 {
2247 char *opt = psql_scan_slash_option(scan_state,
2248 OT_NORMAL, NULL, false);
2249
2251
2252 if (!opt)
2253 {
2254 pg_log_error("\\%s: missing required argument", cmd);
2255 status = PSQL_CMD_ERROR;
2256 }
2257 else
2258 {
2259 pset.stmtName = opt;
2261 status = PSQL_CMD_SEND;
2262 }
2263 }
2264 else
2265 ignore_slash_options(scan_state);
2266
2267 return status;
2268}
@ PSQL_SEND_EXTENDED_PARSE
Definition: settings.h:69

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

Referenced by exec_command().

◆ exec_command_password()

static backslashResult exec_command_password ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2274 of file command.c.

2275{
2276 bool success = true;
2277
2278 if (active_branch)
2279 {
2280 char *user = psql_scan_slash_option(scan_state,
2281 OT_SQLID, NULL, true);
2282 char *pw1 = NULL;
2283 char *pw2 = NULL;
2285 PromptInterruptContext prompt_ctx;
2286
2287 if (user == NULL)
2288 {
2289 /* By default, the command applies to CURRENT_USER */
2290 PGresult *res;
2291
2292 res = PSQLexec("SELECT CURRENT_USER");
2293 if (!res)
2294 return PSQL_CMD_ERROR;
2295
2296 user = pg_strdup(PQgetvalue(res, 0, 0));
2297 PQclear(res);
2298 }
2299
2300 /* Set up to let SIGINT cancel simple_prompt_extended() */
2301 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2302 prompt_ctx.enabled = &sigint_interrupt_enabled;
2303 prompt_ctx.canceled = false;
2304
2306 printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2307
2308 pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2309 if (!prompt_ctx.canceled)
2310 pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2311
2312 if (prompt_ctx.canceled)
2313 {
2314 /* fail silently */
2315 success = false;
2316 }
2317 else if (strcmp(pw1, pw2) != 0)
2318 {
2319 pg_log_error("Passwords didn't match.");
2320 success = false;
2321 }
2322 else
2323 {
2325
2327 {
2329 success = false;
2330 }
2331
2332 PQclear(res);
2333 }
2334
2335 free(user);
2336 free(pw1);
2337 free(pw2);
2339 }
2340 else
2341 ignore_slash_options(scan_state);
2342
2344}
PGresult * PSQLexec(const char *query)
Definition: common.c:620
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:292
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:294
PGresult * PQchangePassword(PGconn *conn, const char *user, const char *passwd)
Definition: fe-auth.c:1529
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
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:122
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
@ OT_SQLID
Definition: psqlscanslash.h:18
char * simple_prompt_extended(const char *prompt, bool echo, PromptInterruptContext *prompt_ctx)
Definition: sprompt.c:53
volatile sig_atomic_t * enabled
Definition: string.h:21

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

Referenced by exec_command().

◆ exec_command_print()

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

Definition at line 2214 of file command.c.

2216{
2217 if (active_branch)
2218 {
2219 /*
2220 * We want to print the same thing \g would execute, but not to change
2221 * the query buffer state; so we can't use copy_previous_query().
2222 * Also, beware of possibility that buffer pointers are NULL.
2223 */
2224 if (query_buf && query_buf->len > 0)
2225 puts(query_buf->data);
2226 else if (previous_buf && previous_buf->len > 0)
2227 puts(previous_buf->data);
2228 else if (!pset.quiet)
2229 puts(_("Query buffer is empty."));
2230 fflush(stdout);
2231 }
2232
2233 return PSQL_CMD_SKIP_LINE;
2234}

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

Referenced by exec_command().

◆ exec_command_prompt()

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

Definition at line 2350 of file command.c.

2352{
2353 bool success = true;
2354
2355 if (active_branch)
2356 {
2357 char *opt,
2358 *prompt_text = NULL;
2359 char *arg1,
2360 *arg2;
2361
2362 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2363 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2364
2365 if (!arg1)
2366 {
2367 pg_log_error("\\%s: missing required argument", cmd);
2368 success = false;
2369 }
2370 else
2371 {
2372 char *result;
2373 PromptInterruptContext prompt_ctx;
2374
2375 /* Set up to let SIGINT cancel simple_prompt_extended() */
2376 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2377 prompt_ctx.enabled = &sigint_interrupt_enabled;
2378 prompt_ctx.canceled = false;
2379
2380 if (arg2)
2381 {
2382 prompt_text = arg1;
2383 opt = arg2;
2384 }
2385 else
2386 opt = arg1;
2387
2388 if (!pset.inputfile)
2389 {
2390 result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2391 }
2392 else
2393 {
2394 if (prompt_text)
2395 {
2396 fputs(prompt_text, stdout);
2397 fflush(stdout);
2398 }
2399 result = gets_fromFile(stdin);
2400 if (!result)
2401 {
2402 pg_log_error("\\%s: could not read value for variable",
2403 cmd);
2404 success = false;
2405 }
2406 }
2407
2408 if (prompt_ctx.canceled ||
2409 (result && !SetVariable(pset.vars, opt, result)))
2410 success = false;
2411
2412 free(result);
2413 free(prompt_text);
2414 free(opt);
2415 }
2416 }
2417 else
2418 ignore_slash_options(scan_state);
2419
2421}
char * gets_fromFile(FILE *source)
Definition: input.c:186
char * inputfile
Definition: settings.h:125

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

Referenced by exec_command().

◆ exec_command_pset()

static backslashResult exec_command_pset ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2427 of file command.c.

2428{
2429 bool success = true;
2430
2431 if (active_branch)
2432 {
2433 char *opt0 = psql_scan_slash_option(scan_state,
2434 OT_NORMAL, NULL, false);
2435 char *opt1 = psql_scan_slash_option(scan_state,
2436 OT_NORMAL, NULL, false);
2437
2438 if (!opt0)
2439 {
2440 /* list all variables */
2441
2442 int i;
2443 static const char *const my_list[] = {
2444 "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2445 "fieldsep_zero", "footer", "format", "linestyle", "null",
2446 "numericlocale", "pager", "pager_min_lines",
2447 "recordsep", "recordsep_zero",
2448 "tableattr", "title", "tuples_only",
2449 "unicode_border_linestyle",
2450 "unicode_column_linestyle",
2451 "unicode_header_linestyle",
2452 "xheader_width",
2453 NULL
2454 };
2455
2456 for (i = 0; my_list[i] != NULL; i++)
2457 {
2458 char *val = pset_value_string(my_list[i], &pset.popt);
2459
2460 printf("%-24s %s\n", my_list[i], val);
2461 free(val);
2462 }
2463
2464 success = true;
2465 }
2466 else
2467 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2468
2469 free(opt0);
2470 free(opt1);
2471 }
2472 else
2473 ignore_slash_options(scan_state);
2474
2476}
static char * pset_value_string(const char *param, printQueryOpt *popt)
Definition: command.c:5284
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 2482 of file command.c.

2483{
2485
2486 if (active_branch)
2487 status = PSQL_CMD_TERMINATE;
2488
2489 return status;
2490}
@ 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 2496 of file command.c.

2498{
2499 if (active_branch)
2500 {
2501 resetPQExpBuffer(query_buf);
2502 psql_scan_reset(scan_state);
2503 if (!pset.quiet)
2504 puts(_("Query buffer reset (cleared)."));
2505 }
2506
2507 return PSQL_CMD_SKIP_LINE;
2508}
void psql_scan_reset(PsqlScanState state)
Definition: psqlscan.l:1267

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

2515{
2516 bool success = true;
2517
2518 if (active_branch)
2519 {
2520 char *fname = psql_scan_slash_option(scan_state,
2521 OT_NORMAL, NULL, true);
2522
2523 expand_tilde(&fname);
2525 if (success && !pset.quiet && fname)
2526 printf(_("Wrote history to file \"%s\".\n"), fname);
2527 if (!fname)
2528 putchar('\n');
2529 free(fname);
2530 }
2531 else
2532 ignore_slash_options(scan_state);
2533
2535}
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:494

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

Referenced by exec_command().

◆ exec_command_set()

static backslashResult exec_command_set ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2541 of file command.c.

2542{
2543 bool success = true;
2544
2545 if (active_branch)
2546 {
2547 char *opt0 = psql_scan_slash_option(scan_state,
2548 OT_NORMAL, NULL, false);
2549
2550 if (!opt0)
2551 {
2552 /* list all variables */
2554 success = true;
2555 }
2556 else
2557 {
2558 /*
2559 * Set variable to the concatenation of the arguments.
2560 */
2561 char *newval;
2562 char *opt;
2563
2564 opt = psql_scan_slash_option(scan_state,
2565 OT_NORMAL, NULL, false);
2566 newval = pg_strdup(opt ? opt : "");
2567 free(opt);
2568
2569 while ((opt = psql_scan_slash_option(scan_state,
2570 OT_NORMAL, NULL, false)))
2571 {
2572 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2573 strcat(newval, opt);
2574 free(opt);
2575 }
2576
2577 if (!SetVariable(pset.vars, opt0, newval))
2578 success = false;
2579
2580 free(newval);
2581 }
2582 free(opt0);
2583 }
2584 else
2585 ignore_slash_options(scan_state);
2586
2588}
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define newval
void PrintVariables(VariableSpace space)
Definition: variables.c:186

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

Referenced by exec_command().

◆ exec_command_setenv()

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

Definition at line 2594 of file command.c.

2596{
2597 bool success = true;
2598
2599 if (active_branch)
2600 {
2601 char *envvar = psql_scan_slash_option(scan_state,
2602 OT_NORMAL, NULL, false);
2603 char *envval = psql_scan_slash_option(scan_state,
2604 OT_NORMAL, NULL, false);
2605
2606 if (!envvar)
2607 {
2608 pg_log_error("\\%s: missing required argument", cmd);
2609 success = false;
2610 }
2611 else if (strchr(envvar, '=') != NULL)
2612 {
2613 pg_log_error("\\%s: environment variable name must not contain \"=\"",
2614 cmd);
2615 success = false;
2616 }
2617 else if (!envval)
2618 {
2619 /* No argument - unset the environment variable */
2620 unsetenv(envvar);
2621 success = true;
2622 }
2623 else
2624 {
2625 /* Set variable to the value of the next argument */
2626 setenv(envvar, envval, 1);
2627 success = true;
2628 }
2629 free(envvar);
2630 free(envval);
2631 }
2632 else
2633 ignore_slash_options(scan_state);
2634
2636}
#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 2642 of file command.c.

2644{
2646
2647 if (active_branch)
2648 {
2649 bool show_linenumbers = (strchr(cmd, '+') != NULL);
2651 char *obj_desc;
2652 Oid obj_oid = InvalidOid;
2654
2656 obj_desc = psql_scan_slash_option(scan_state,
2657 OT_WHOLE_LINE, NULL, true);
2658 if (!obj_desc)
2659 {
2660 if (is_func)
2661 pg_log_error("function name is required");
2662 else
2663 pg_log_error("view name is required");
2664 status = PSQL_CMD_ERROR;
2665 }
2666 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
2667 {
2668 /* error already reported */
2669 status = PSQL_CMD_ERROR;
2670 }
2671 else if (!get_create_object_cmd(eot, obj_oid, buf))
2672 {
2673 /* error already reported */
2674 status = PSQL_CMD_ERROR;
2675 }
2676 else
2677 {
2678 FILE *output;
2679 bool is_pager;
2680
2681 /* Select output stream: stdout, pager, or file */
2682 if (pset.queryFout == stdout)
2683 {
2684 /* count lines in function to see if pager is needed */
2685 int lineno = count_lines_in_buf(buf);
2686
2687 output = PageOutput(lineno, &(pset.popt.topt));
2688 is_pager = true;
2689 }
2690 else
2691 {
2692 /* use previously set output file, without pager */
2694 is_pager = false;
2695 }
2696
2697 if (show_linenumbers)
2698 {
2699 /* add line numbers */
2700 print_with_linenumbers(output, buf->data, is_func);
2701 }
2702 else
2703 {
2704 /* just send the definition to output */
2705 fputs(buf->data, output);
2706 }
2707
2708 if (is_pager)
2710 }
2711
2712 free(obj_desc);
2714 }
2715 else
2716 ignore_slash_whole_line(scan_state);
2717
2718 return status;
2719}
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:5975
static void print_with_linenumbers(FILE *output, char *lines, bool is_func)
Definition: command.c:6005
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 3139 of file command.c.

3140{
3141 bool success = true;
3142
3143 if (active_branch)
3144 {
3145 char *opt = psql_scan_slash_option(scan_state,
3146 OT_WHOLE_LINE, NULL, false);
3147
3148 success = do_shell(opt);
3149 free(opt);
3150 }
3151 else
3152 ignore_slash_whole_line(scan_state);
3153
3155}
static bool do_shell(const char *command)
Definition: command.c:5373

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

3162{
3163 if (active_branch)
3164 {
3165 char *opt0 = psql_scan_slash_option(scan_state,
3166 OT_NORMAL, NULL, false);
3167
3168 if (!opt0 || strcmp(opt0, "commands") == 0)
3170 else if (strcmp(opt0, "options") == 0)
3172 else if (strcmp(opt0, "variables") == 0)
3174 else
3176
3177 free(opt0);
3178 }
3179 else
3180 ignore_slash_options(scan_state);
3181
3182 return PSQL_CMD_SKIP_LINE;
3183}
void helpVariables(unsigned short int pager)
Definition: help.c:358
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_t()

static backslashResult exec_command_t ( PsqlScanState  scan_state,
bool  active_branch 
)
static

Definition at line 2725 of file command.c.

2726{
2727 bool success = true;
2728
2729 if (active_branch)
2730 {
2731 char *opt = psql_scan_slash_option(scan_state,
2732 OT_NORMAL, NULL, true);
2733
2734 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
2735 free(opt);
2736 }
2737 else
2738 ignore_slash_options(scan_state);
2739
2741}

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

2748{
2749 bool success = true;
2750
2751 if (active_branch)
2752 {
2753 char *value = psql_scan_slash_option(scan_state,
2754 OT_NORMAL, NULL, false);
2755
2756 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
2757 free(value);
2758 }
2759 else
2760 ignore_slash_options(scan_state);
2761
2763}

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

2770{
2771 bool success = true;
2772
2773 if (active_branch)
2774 {
2775 char *opt = psql_scan_slash_option(scan_state,
2776 OT_NORMAL, NULL, false);
2777
2778 if (opt)
2779 success = ParseVariableBool(opt, "\\timing", &pset.timing);
2780 else
2782 if (!pset.quiet)
2783 {
2784 if (pset.timing)
2785 puts(_("Timing is on."));
2786 else
2787 puts(_("Timing is off."));
2788 }
2789 free(opt);
2790 }
2791 else
2792 ignore_slash_options(scan_state);
2793
2795}

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

2803{
2804 bool success = true;
2805
2806 if (active_branch)
2807 {
2808 char *opt = psql_scan_slash_option(scan_state,
2809 OT_NORMAL, NULL, false);
2810
2811 if (!opt)
2812 {
2813 pg_log_error("\\%s: missing required argument", cmd);
2814 success = false;
2815 }
2816 else if (!SetVariable(pset.vars, opt, NULL))
2817 success = false;
2818
2819 free(opt);
2820 }
2821 else
2822 ignore_slash_options(scan_state);
2823
2825}

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

2935{
2936 bool success = true;
2937
2938 if (active_branch)
2939 {
2940 bool have_sleep = false;
2941 bool have_iter = false;
2942 bool have_min_rows = false;
2943 double sleep = 2;
2944 int iter = 0;
2945 int min_rows = 0;
2946
2947 /*
2948 * Parse arguments. We allow either an unlabeled interval or
2949 * "name=value", where name is from the set ('i', 'interval', 'c',
2950 * 'count', 'm', 'min_rows').
2951 */
2952 while (success)
2953 {
2954 char *opt = psql_scan_slash_option(scan_state,
2955 OT_NORMAL, NULL, true);
2956 char *valptr;
2957 char *opt_end;
2958
2959 if (!opt)
2960 break; /* no more arguments */
2961
2962 valptr = strchr(opt, '=');
2963 if (valptr)
2964 {
2965 /* Labeled argument */
2966 valptr++;
2967 if (strncmp("i=", opt, strlen("i=")) == 0 ||
2968 strncmp("interval=", opt, strlen("interval=")) == 0)
2969 {
2970 if (have_sleep)
2971 {
2972 pg_log_error("\\watch: interval value is specified more than once");
2973 success = false;
2974 }
2975 else
2976 {
2977 have_sleep = true;
2978 errno = 0;
2979 sleep = strtod(valptr, &opt_end);
2980 if (sleep < 0 || *opt_end || errno == ERANGE)
2981 {
2982 pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
2983 success = false;
2984 }
2985 }
2986 }
2987 else if (strncmp("c=", opt, strlen("c=")) == 0 ||
2988 strncmp("count=", opt, strlen("count=")) == 0)
2989 {
2990 if (have_iter)
2991 {
2992 pg_log_error("\\watch: iteration count is specified more than once");
2993 success = false;
2994 }
2995 else
2996 {
2997 have_iter = true;
2998 errno = 0;
2999 iter = strtoint(valptr, &opt_end, 10);
3000 if (iter <= 0 || *opt_end || errno == ERANGE)
3001 {
3002 pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
3003 success = false;
3004 }
3005 }
3006 }
3007 else if (strncmp("m=", opt, strlen("m=")) == 0 ||
3008 strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
3009 {
3010 if (have_min_rows)
3011 {
3012 pg_log_error("\\watch: minimum row count specified more than once");
3013 success = false;
3014 }
3015 else
3016 {
3017 have_min_rows = true;
3018 errno = 0;
3019 min_rows = strtoint(valptr, &opt_end, 10);
3020 if (min_rows <= 0 || *opt_end || errno == ERANGE)
3021 {
3022 pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
3023 success = false;
3024 }
3025 }
3026 }
3027 else
3028 {
3029 pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
3030 success = false;
3031 }
3032 }
3033 else
3034 {
3035 /* Unlabeled argument: take it as interval */
3036 if (have_sleep)
3037 {
3038 pg_log_error("\\watch: interval value is specified more than once");
3039 success = false;
3040 }
3041 else
3042 {
3043 have_sleep = true;
3044 errno = 0;
3045 sleep = strtod(opt, &opt_end);
3046 if (sleep < 0 || *opt_end || errno == ERANGE)
3047 {
3048 pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3049 success = false;
3050 }
3051 }
3052 }
3053
3054 free(opt);
3055 }
3056
3057 /* If we parsed arguments successfully, do the command */
3058 if (success)
3059 {
3060 /* If query_buf is empty, recall and execute previous query */
3061 (void) copy_previous_query(query_buf, previous_buf);
3062
3063 success = do_watch(query_buf, sleep, iter, min_rows);
3064 }
3065
3066 /* Reset the query buffer as though for \r */
3067 resetPQExpBuffer(query_buf);
3068 psql_scan_reset(scan_state);
3069 }
3070 else
3071 ignore_slash_options(scan_state);
3072
3074}
static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
Definition: command.c:5424
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
Definition: string.c:50

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

Referenced by exec_command().

◆ exec_command_write()

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

Definition at line 2831 of file command.c.

2834{
2836
2837 if (active_branch)
2838 {
2839 char *fname = psql_scan_slash_option(scan_state,
2840 OT_FILEPIPE, NULL, true);
2841 FILE *fd = NULL;
2842 bool is_pipe = false;
2843
2844 if (!query_buf)
2845 {
2846 pg_log_error("no query buffer");
2847 status = PSQL_CMD_ERROR;
2848 }
2849 else
2850 {
2851 if (!fname)
2852 {
2853 pg_log_error("\\%s: missing required argument", cmd);
2854 status = PSQL_CMD_ERROR;
2855 }
2856 else
2857 {
2858 expand_tilde(&fname);
2859 if (fname[0] == '|')
2860 {
2861 is_pipe = true;
2862 fflush(NULL);
2864 fd = popen(&fname[1], "w");
2865 }
2866 else
2867 {
2869 fd = fopen(fname, "w");
2870 }
2871 if (!fd)
2872 {
2873 pg_log_error("%s: %m", fname);
2874 status = PSQL_CMD_ERROR;
2875 }
2876 }
2877 }
2878
2879 if (fd)
2880 {
2881 int result;
2882
2883 /*
2884 * We want to print the same thing \g would execute, but not to
2885 * change the query buffer state; so we can't use
2886 * copy_previous_query(). Also, beware of possibility that buffer
2887 * pointers are NULL.
2888 */
2889 if (query_buf && query_buf->len > 0)
2890 fprintf(fd, "%s\n", query_buf->data);
2891 else if (previous_buf && previous_buf->len > 0)
2892 fprintf(fd, "%s\n", previous_buf->data);
2893
2894 if (is_pipe)
2895 {
2896 result = pclose(fd);
2897
2898 if (result != 0)
2899 {
2900 pg_log_error("%s: %s", fname, wait_result_to_str(result));
2901 status = PSQL_CMD_ERROR;
2902 }
2904 }
2905 else
2906 {
2907 result = fclose(fd);
2908
2909 if (result == EOF)
2910 {
2911 pg_log_error("%s: %m", fname);
2912 status = PSQL_CMD_ERROR;
2913 }
2914 }
2915 }
2916
2917 if (is_pipe)
2919
2920 free(fname);
2921 }
2922 else
2923 ignore_slash_filepipe(scan_state);
2924
2925 return status;
2926}
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(), fflush(), 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 3080 of file command.c.

3081{
3082 bool success = true;
3083
3084 if (active_branch)
3085 {
3086 char *opt = psql_scan_slash_option(scan_state,
3087 OT_NORMAL, NULL, true);
3088
3089 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3090 free(opt);
3091 }
3092 else
3093 ignore_slash_options(scan_state);
3094
3096}

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

3103{
3104 bool success = true;
3105
3106 if (active_branch)
3107 {
3108 char *pattern;
3109 bool show_system;
3110 unsigned short int save_expanded;
3111
3112 pattern = psql_scan_slash_option(scan_state,
3113 OT_NORMAL, NULL, true);
3114
3115 show_system = strchr(cmd, 'S') ? true : false;
3116
3117 /* if 'x' option specified, force expanded mode */
3118 save_expanded = pset.popt.topt.expanded;
3119 if (strchr(cmd, 'x'))
3120 pset.popt.topt.expanded = 1;
3121
3122 success = permissionsList(pattern, show_system);
3123
3124 /* restore original expanded mode */
3125 pset.popt.topt.expanded = save_expanded;
3126
3127 free(pattern);
3128 }
3129 else
3130 ignore_slash_options(scan_state);
3131
3133}

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

3233{
3234 PQExpBuffer exp_buf = createPQExpBuffer();
3235 int num_options = 0;
3236 char *value;
3237
3238 /* collect all arguments for the conditional command into exp_buf */
3239 while ((value = psql_scan_slash_option(scan_state,
3240 OT_NORMAL, NULL, false)) != NULL)
3241 {
3242 /* add spaces between tokens */
3243 if (num_options > 0)
3244 appendPQExpBufferChar(exp_buf, ' ');
3245 appendPQExpBufferStr(exp_buf, value);
3246 num_options++;
3247 free(value);
3248 }
3249
3250 return exp_buf;
3251}

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

5759{
5760 bool result = true;
5762 PGresult *res;
5763
5764 switch (obj_type)
5765 {
5766 case EditableFunction:
5767 printfPQExpBuffer(query,
5768 "SELECT pg_catalog.pg_get_functiondef(%u)",
5769 oid);
5770 break;
5771
5772 case EditableView:
5773
5774 /*
5775 * pg_get_viewdef() just prints the query, so we must prepend
5776 * CREATE for ourselves. We must fully qualify the view name to
5777 * ensure the right view gets replaced. Also, check relation kind
5778 * to be sure it's a view.
5779 *
5780 * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
5781 * CHECK OPTION. These are not part of the view definition
5782 * returned by pg_get_viewdef() and so need to be retrieved
5783 * separately. Materialized views (introduced in 9.3) may have
5784 * arbitrary storage parameter reloptions.
5785 */
5786 if (pset.sversion >= 90400)
5787 {
5788 printfPQExpBuffer(query,
5789 "SELECT nspname, relname, relkind, "
5790 "pg_catalog.pg_get_viewdef(c.oid, true), "
5791 "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5792 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5793 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
5794 "FROM pg_catalog.pg_class c "
5795 "LEFT JOIN pg_catalog.pg_namespace n "
5796 "ON c.relnamespace = n.oid WHERE c.oid = %u",
5797 oid);
5798 }
5799 else
5800 {
5801 printfPQExpBuffer(query,
5802 "SELECT nspname, relname, relkind, "
5803 "pg_catalog.pg_get_viewdef(c.oid, true), "
5804 "c.reloptions AS reloptions, "
5805 "NULL AS checkoption "
5806 "FROM pg_catalog.pg_class c "
5807 "LEFT JOIN pg_catalog.pg_namespace n "
5808 "ON c.relnamespace = n.oid WHERE c.oid = %u",
5809 oid);
5810 }
5811 break;
5812 }
5813
5814 if (!echo_hidden_command(query->data))
5815 {
5816 destroyPQExpBuffer(query);
5817 return false;
5818 }
5819 res = PQexec(pset.db, query->data);
5821 {
5823 switch (obj_type)
5824 {
5825 case EditableFunction:
5827 break;
5828
5829 case EditableView:
5830 {
5831 char *nspname = PQgetvalue(res, 0, 0);
5832 char *relname = PQgetvalue(res, 0, 1);
5833 char *relkind = PQgetvalue(res, 0, 2);
5834 char *viewdef = PQgetvalue(res, 0, 3);
5835 char *reloptions = PQgetvalue(res, 0, 4);
5836 char *checkoption = PQgetvalue(res, 0, 5);
5837
5838 /*
5839 * If the backend ever supports CREATE OR REPLACE
5840 * MATERIALIZED VIEW, allow that here; but as of today it
5841 * does not, so editing a matview definition in this way
5842 * is impossible.
5843 */
5844 switch (relkind[0])
5845 {
5846#ifdef NOT_USED
5847 case RELKIND_MATVIEW:
5848 appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
5849 break;
5850#endif
5851 case RELKIND_VIEW:
5852 appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
5853 break;
5854 default:
5855 pg_log_error("\"%s.%s\" is not a view",
5856 nspname, relname);
5857 result = false;
5858 break;
5859 }
5860 appendPQExpBuffer(buf, "%s.", fmtId(nspname));
5862
5863 /* reloptions, if not an empty array "{}" */
5864 if (reloptions != NULL && strlen(reloptions) > 2)
5865 {
5866 appendPQExpBufferStr(buf, "\n WITH (");
5867 if (!appendReloptionsArray(buf, reloptions, "",
5868 pset.encoding,
5870 {
5871 pg_log_error("could not parse reloptions array");
5872 result = false;
5873 }
5875 }
5876
5877 /* View definition from pg_get_viewdef (a SELECT query) */
5878 appendPQExpBuffer(buf, " AS\n%s", viewdef);
5879
5880 /* Get rid of the semicolon that pg_get_viewdef appends */
5881 if (buf->len > 0 && buf->data[buf->len - 1] == ';')
5882 buf->data[--(buf->len)] = '\0';
5883
5884 /* WITH [LOCAL|CASCADED] CHECK OPTION */
5885 if (checkoption && checkoption[0] != '\0')
5886 appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
5887 checkoption);
5888 }
5889 break;
5890 }
5891 /* Make sure result ends with a newline */
5892 if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
5894 }
5895 else
5896 {
5898 result = false;
5899 }
5900
5901 PQclear(res);
5902 destroyPQExpBuffer(query);
5903
5904 return result;
5905}
bool standard_strings(void)
Definition: common.c:2154
static bool echo_hidden_command(const char *query)
Definition: command.c:5665
static void minimal_error_message(PGresult *res)
Definition: command.c:6047
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:125
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, res, resetPQExpBuffer(), standard_strings(), and _psqlSettings::sversion.

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ HandleSlashCmds()

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

Definition at line 218 of file command.c.

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

Referenced by main(), and MainLoop().

◆ ignore_boolean_expression()

static void ignore_boolean_expression ( PsqlScanState  scan_state)
static

Definition at line 3279 of file command.c.

3280{
3282
3284}
static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state)
Definition: command.c:3232

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

3313{
3314 char *arg = psql_scan_slash_option(scan_state,
3315 OT_FILEPIPE, NULL, false);
3316
3317 free(arg);
3318}

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

3333{
3334 char *arg = psql_scan_slash_option(scan_state,
3335 OT_WHOLE_LINE, NULL, false);
3336
3337 free(arg);
3338}

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

3345{
3346 return (strcmp(cmd, "if") == 0 ||
3347 strcmp(cmd, "elif") == 0 ||
3348 strcmp(cmd, "else") == 0 ||
3349 strcmp(cmd, "endif") == 0);
3350}

Referenced by exec_command().

◆ is_true_boolean_expression()

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

Definition at line 3262 of file command.c.

3263{
3265 bool value = false;
3266 bool success = ParseVariableBool(buf->data, name, &value);
3267
3269 return success && value;
3270}

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

5699{
5700 bool result = true;
5702 PGresult *res;
5703
5704 switch (obj_type)
5705 {
5706 case EditableFunction:
5707
5708 /*
5709 * We have a function description, e.g. "x" or "x(int)". Issue a
5710 * query to retrieve the function's OID using a cast to regproc or
5711 * regprocedure (as appropriate).
5712 */
5713 appendPQExpBufferStr(query, "SELECT ");
5714 appendStringLiteralConn(query, desc, pset.db);
5715 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
5716 strchr(desc, '(') ? "regprocedure" : "regproc");
5717 break;
5718
5719 case EditableView:
5720
5721 /*
5722 * Convert view name (possibly schema-qualified) to OID. Note:
5723 * this code doesn't check if the relation is actually a view.
5724 * We'll detect that in get_create_object_cmd().
5725 */
5726 appendPQExpBufferStr(query, "SELECT ");
5727 appendStringLiteralConn(query, desc, pset.db);
5728 appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
5729 break;
5730 }
5731
5732 if (!echo_hidden_command(query->data))
5733 {
5734 destroyPQExpBuffer(query);
5735 return false;
5736 }
5737 res = PQexec(pset.db, query->data);
5739 *obj_oid = atooid(PQgetvalue(res, 0, 0));
5740 else
5741 {
5743 result = false;
5744 }
5745
5746 PQclear(res);
5747 destroyPQExpBuffer(query);
5748
5749 return result;
5750}
#define atooid(x)
Definition: postgres_ext.h:43
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(), pset, and res.

Referenced by exec_command_ef_ev(), and exec_command_sf_sv().

◆ minimal_error_message()

static void minimal_error_message ( PGresult res)
static

Definition at line 6047 of file command.c.

6048{
6049 PQExpBuffer msg;
6050 const char *fld;
6051
6052 msg = createPQExpBuffer();
6053
6055 if (fld)
6056 printfPQExpBuffer(msg, "%s: ", fld);
6057 else
6058 printfPQExpBuffer(msg, "ERROR: ");
6060 if (fld)
6061 appendPQExpBufferStr(msg, fld);
6062 else
6063 appendPQExpBufferStr(msg, "(not available)");
6064 appendPQExpBufferChar(msg, '\n');
6065
6066 pg_log_error("%s", msg->data);
6067
6068 destroyPQExpBuffer(msg);
6069}
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55

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

Referenced by get_create_object_cmd(), and lookup_object_oid().

◆ param_is_newly_set()

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

Definition at line 3452 of file command.c.

3453{
3454 if (new_val == NULL)
3455 return false;
3456
3457 if (old_val == NULL || strcmp(old_val, new_val) != 0)
3458 return true;
3459
3460 return false;
3461}

Referenced by do_connect().

◆ print_with_linenumbers()

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

Definition at line 6005 of file command.c.

6006{
6007 bool in_header = is_func;
6008 int lineno = 0;
6009
6010 while (*lines != '\0')
6011 {
6012 char *eol;
6013
6014 if (in_header &&
6015 (strncmp(lines, "AS ", 3) == 0 ||
6016 strncmp(lines, "BEGIN ", 6) == 0 ||
6017 strncmp(lines, "RETURN ", 7) == 0))
6018 in_header = false;
6019
6020 /* increment lineno only for body's lines */
6021 if (!in_header)
6022 lineno++;
6023
6024 /* find and mark end of current line */
6025 eol = strchr(lines, '\n');
6026 if (eol != NULL)
6027 *eol = '\0';
6028
6029 /* show current line as appropriate */
6030 if (in_header)
6031 fprintf(output, " %s\n", lines);
6032 else
6033 fprintf(output, "%-7d %s\n", lineno, lines);
6034
6035 /* advance to next line, if any */
6036 if (eol == NULL)
6037 break;
6038 lines = ++eol;
6039 }
6040}

References fprintf, and output.

Referenced by exec_command_sf_sv().

◆ printGSSInfo()

static void printGSSInfo ( void  )
static

Definition at line 4088 of file command.c.

4089{
4090 if (!PQgssEncInUse(pset.db))
4091 return; /* no GSSAPI encryption in use */
4092
4093 printf(_("GSSAPI-encrypted connection\n"));
4094}
int PQgssEncInUse(PGconn *conn)

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

Referenced by connection_warnings(), and exec_command_conninfo().

◆ printPsetInfo()

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

Definition at line 4977 of file command.c.

4978{
4979 Assert(param != NULL);
4980
4981 /* show border style/width */
4982 if (strcmp(param, "border") == 0)
4983 printf(_("Border style is %d.\n"), popt->topt.border);
4984
4985 /* show the target width for the wrapped format */
4986 else if (strcmp(param, "columns") == 0)
4987 {
4988 if (!popt->topt.columns)
4989 printf(_("Target width is unset.\n"));
4990 else
4991 printf(_("Target width is %d.\n"), popt->topt.columns);
4992 }
4993
4994 /* show expanded/vertical mode */
4995 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
4996 {
4997 if (popt->topt.expanded == 1)
4998 printf(_("Expanded display is on.\n"));
4999 else if (popt->topt.expanded == 2)
5000 printf(_("Expanded display is used automatically.\n"));
5001 else
5002 printf(_("Expanded display is off.\n"));
5003 }
5004
5005 /* show xheader width value */
5006 else if (strcmp(param, "xheader_width") == 0)
5007 {
5009 printf(_("Expanded header width is \"%s\".\n"), "full");
5011 printf(_("Expanded header width is \"%s\".\n"), "column");
5013 printf(_("Expanded header width is \"%s\".\n"), "page");
5015 printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
5016 }
5017
5018 /* show field separator for CSV format */
5019 else if (strcmp(param, "csv_fieldsep") == 0)
5020 {
5021 printf(_("Field separator for CSV is \"%s\".\n"),
5022 popt->topt.csvFieldSep);
5023 }
5024
5025 /* show field separator for unaligned text */
5026 else if (strcmp(param, "fieldsep") == 0)
5027 {
5028 if (popt->topt.fieldSep.separator_zero)
5029 printf(_("Field separator is zero byte.\n"));
5030 else
5031 printf(_("Field separator is \"%s\".\n"),
5032 popt->topt.fieldSep.separator);
5033 }
5034
5035 else if (strcmp(param, "fieldsep_zero") == 0)
5036 {
5037 printf(_("Field separator is zero byte.\n"));
5038 }
5039
5040 /* show disable "(x rows)" footer */
5041 else if (strcmp(param, "footer") == 0)
5042 {
5043 if (popt->topt.default_footer)
5044 printf(_("Default footer is on.\n"));
5045 else
5046 printf(_("Default footer is off.\n"));
5047 }
5048
5049 /* show format */
5050 else if (strcmp(param, "format") == 0)
5051 {
5052 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
5053 }
5054
5055 /* show table line style */
5056 else if (strcmp(param, "linestyle") == 0)
5057 {
5058 printf(_("Line style is %s.\n"),
5059 get_line_style(&popt->topt)->name);
5060 }
5061
5062 /* show null display */
5063 else if (strcmp(param, "null") == 0)
5064 {
5065 printf(_("Null display is \"%s\".\n"),
5066 popt->nullPrint ? popt->nullPrint : "");
5067 }
5068
5069 /* show locale-aware numeric output */
5070 else if (strcmp(param, "numericlocale") == 0)
5071 {
5072 if (popt->topt.numericLocale)
5073 printf(_("Locale-adjusted numeric output is on.\n"));
5074 else
5075 printf(_("Locale-adjusted numeric output is off.\n"));
5076 }
5077
5078 /* show toggle use of pager */
5079 else if (strcmp(param, "pager") == 0)
5080 {
5081 if (popt->topt.pager == 1)
5082 printf(_("Pager is used for long output.\n"));
5083 else if (popt->topt.pager == 2)
5084 printf(_("Pager is always used.\n"));
5085 else
5086 printf(_("Pager usage is off.\n"));
5087 }
5088
5089 /* show minimum lines for pager use */
5090 else if (strcmp(param, "pager_min_lines") == 0)
5091 {
5092 printf(ngettext("Pager won't be used for less than %d line.\n",
5093 "Pager won't be used for less than %d lines.\n",
5094 popt->topt.pager_min_lines),
5095 popt->topt.pager_min_lines);
5096 }
5097
5098 /* show record separator for unaligned text */
5099 else if (strcmp(param, "recordsep") == 0)
5100 {
5101 if (popt->topt.recordSep.separator_zero)
5102 printf(_("Record separator is zero byte.\n"));
5103 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
5104 printf(_("Record separator is <newline>.\n"));
5105 else
5106 printf(_("Record separator is \"%s\".\n"),
5107 popt->topt.recordSep.separator);
5108 }
5109
5110 else if (strcmp(param, "recordsep_zero") == 0)
5111 {
5112 printf(_("Record separator is zero byte.\n"));
5113 }
5114
5115 /* show HTML table tag options */
5116 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5117 {
5118 if (popt->topt.tableAttr)
5119 printf(_("Table attributes are \"%s\".\n"),
5120 popt->topt.tableAttr);
5121 else
5122 printf(_("Table attributes unset.\n"));
5123 }
5124
5125 /* show title override */
5126 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5127 {
5128 if (popt->title)
5129 printf(_("Title is \"%s\".\n"), popt->title);
5130 else
5131 printf(_("Title is unset.\n"));
5132 }
5133
5134 /* show toggle between full and tuples-only format */
5135 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5136 {
5137 if (popt->topt.tuples_only)
5138 printf(_("Tuples only is on.\n"));
5139 else
5140 printf(_("Tuples only is off.\n"));
5141 }
5142
5143 /* Unicode style formatting */
5144 else if (strcmp(param, "unicode_border_linestyle") == 0)
5145 {
5146 printf(_("Unicode border line style is \"%s\".\n"),
5148 }
5149
5150 else if (strcmp(param, "unicode_column_linestyle") == 0)
5151 {
5152 printf(_("Unicode column line style is \"%s\".\n"),
5154 }
5155
5156 else if (strcmp(param, "unicode_header_linestyle") == 0)
5157 {
5158 printf(_("Unicode header line style is \"%s\".\n"),
5160 }
5161
5162 else
5163 {
5164 pg_log_error("\\pset: unknown option: %s", param);
5165 return false;
5166 }
5167
5168 return true;
5169}
#define ngettext(s, p, n)
Definition: c.h:1138
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:4594
static const char * _align2string(enum printFormat in)
Definition: command.c:4538
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 4060 of file command.c.

4061{
4062 const char *protocol;
4063 const char *cipher;
4064 const char *compression;
4065 const char *alpn;
4066
4067 if (!PQsslInUse(pset.db))
4068 return; /* no SSL */
4069
4070 protocol = PQsslAttribute(pset.db, "protocol");
4071 cipher = PQsslAttribute(pset.db, "cipher");
4072 compression = PQsslAttribute(pset.db, "compression");
4073 alpn = PQsslAttribute(pset.db, "alpn");
4074
4075 printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
4076 protocol ? protocol : _("unknown"),
4077 cipher ? cipher : _("unknown"),
4078 (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4079 (alpn && alpn[0] != '\0') ? alpn : _("none"));
4080}
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:103

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

Referenced by connection_warnings(), and exec_command_conninfo().

◆ process_command_g_options()

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

Definition at line 1581 of file command.c.

1583{
1584 bool success = true;
1585 bool found_r_paren = false;
1586
1587 do
1588 {
1589 char *option;
1590 size_t optlen;
1591
1592 /* If not first time through, collect a new option */
1593 if (first_option)
1594 option = first_option;
1595 else
1596 {
1597 option = psql_scan_slash_option(scan_state,
1598 OT_NORMAL, NULL, false);
1599 if (!option)
1600 {
1601 if (active_branch)
1602 {
1603 pg_log_error("\\%s: missing right parenthesis", cmd);
1604 success = false;
1605 }
1606 break;
1607 }
1608 }
1609
1610 /* Check for terminating right paren, and remove it from string */
1611 optlen = strlen(option);
1612 if (optlen > 0 && option[optlen - 1] == ')')
1613 {
1614 option[--optlen] = '\0';
1615 found_r_paren = true;
1616 }
1617
1618 /* If there was anything besides parentheses, parse/execute it */
1619 if (optlen > 0)
1620 {
1621 /* We can have either "name" or "name=value" */
1622 char *valptr = strchr(option, '=');
1623
1624 if (valptr)
1625 *valptr++ = '\0';
1626 if (active_branch)
1627 {
1628 /* save settings if not done already, then apply option */
1629 if (pset.gsavepopt == NULL)
1631 success &= do_pset(option, valptr, &pset.popt, true);
1632 }
1633 }
1634
1635 /* Clean up after this option. We should not free first_option. */
1636 if (first_option)
1637 first_option = NULL;
1638 else
1639 free(option);
1640 } while (!found_r_paren);
1641
1642 /* If we failed after already changing some options, undo side-effects */
1643 if (!success && active_branch && pset.gsavepopt)
1644 {
1646 pset.gsavepopt = NULL;
1647 }
1648
1650}
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:5213

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

4472{
4473 FILE *fd;
4474 int result;
4475 char *oldfilename;
4476 char relpath[MAXPGPATH];
4477
4478 if (!filename)
4479 {
4480 fd = stdin;
4481 filename = NULL;
4482 }
4483 else if (strcmp(filename, "-") != 0)
4484 {
4486
4487 /*
4488 * If we were asked to resolve the pathname relative to the location
4489 * of the currently executing script, and there is one, and this is a
4490 * relative pathname, then prepend all but the last pathname component
4491 * of the current script to this pathname.
4492 */
4493 if (use_relative_path && pset.inputfile &&
4495 {
4500
4501 filename = relpath;
4502 }
4503
4504 fd = fopen(filename, PG_BINARY_R);
4505
4506 if (!fd)
4507 {
4508 pg_log_error("%s: %m", filename);
4509 return EXIT_FAILURE;
4510 }
4511 }
4512 else
4513 {
4514 fd = stdin;
4515 filename = "<stdin>"; /* for future error messages */
4516 }
4517
4518 oldfilename = pset.inputfile;
4520
4522
4523 result = MainLoop(fd);
4524
4525 if (fd != stdin)
4526 fclose(fd);
4527
4528 pset.inputfile = oldfilename;
4529
4531
4532 return result;
4533}
void pg_logging_config(int new_flags)
Definition: logging.c:166
#define PG_LOG_FLAG_TERSE
Definition: logging.h:86
int MainLoop(FILE *source)
Definition: mainloop.c:33
static char * filename
Definition: pg_dumpall.c:119
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c: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:102
#define EXIT_FAILURE
Definition: settings.h:178

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

3425{
3426 char *result;
3427 PromptInterruptContext prompt_ctx;
3428
3429 /* Set up to let SIGINT cancel simple_prompt_extended() */
3430 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3431 prompt_ctx.enabled = &sigint_interrupt_enabled;
3432 prompt_ctx.canceled = false;
3433
3434 if (username == NULL || username[0] == '\0')
3435 result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3436 else
3437 {
3438 char *prompt_text;
3439
3440 prompt_text = psprintf(_("Password for user %s: "), username);
3441 result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3442 free(prompt_text);
3443 }
3444
3445 if (canceled)
3446 *canceled = prompt_ctx.canceled;
3447
3448 return result;
3449}
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 5239 of file command.c.

5240{
5241 return val ? "on" : "off";
5242}

References val.

Referenced by pset_value_string().

◆ pset_quoted_string()

static char * pset_quoted_string ( const char *  str)
static

Definition at line 5246 of file command.c.

5247{
5248 char *ret = pg_malloc(strlen(str) * 2 + 3);
5249 char *r = ret;
5250
5251 *r++ = '\'';
5252
5253 for (; *str; str++)
5254 {
5255 if (*str == '\n')
5256 {
5257 *r++ = '\\';
5258 *r++ = 'n';
5259 }
5260 else if (*str == '\'')
5261 {
5262 *r++ = '\\';
5263 *r++ = '\'';
5264 }
5265 else
5266 *r++ = *str;
5267 }
5268
5269 *r++ = '\'';
5270 *r = '\0';
5271
5272 return ret;
5273}
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 5284 of file command.c.

5285{
5286 Assert(param != NULL);
5287
5288 if (strcmp(param, "border") == 0)
5289 return psprintf("%d", popt->topt.border);
5290 else if (strcmp(param, "columns") == 0)
5291 return psprintf("%d", popt->topt.columns);
5292 else if (strcmp(param, "csv_fieldsep") == 0)
5293 return pset_quoted_string(popt->topt.csvFieldSep);
5294 else if (strcmp(param, "expanded") == 0)
5295 return pstrdup(popt->topt.expanded == 2
5296 ? "auto"
5297 : pset_bool_string(popt->topt.expanded));
5298 else if (strcmp(param, "fieldsep") == 0)
5300 ? popt->topt.fieldSep.separator
5301 : "");
5302 else if (strcmp(param, "fieldsep_zero") == 0)
5304 else if (strcmp(param, "footer") == 0)
5306 else if (strcmp(param, "format") == 0)
5307 return pstrdup(_align2string(popt->topt.format));
5308 else if (strcmp(param, "linestyle") == 0)
5309 return pstrdup(get_line_style(&popt->topt)->name);
5310 else if (strcmp(param, "null") == 0)
5311 return pset_quoted_string(popt->nullPrint
5312 ? popt->nullPrint
5313 : "");
5314 else if (strcmp(param, "numericlocale") == 0)
5316 else if (strcmp(param, "pager") == 0)
5317 return psprintf("%d", popt->topt.pager);
5318 else if (strcmp(param, "pager_min_lines") == 0)
5319 return psprintf("%d", popt->topt.pager_min_lines);
5320 else if (strcmp(param, "recordsep") == 0)
5322 ? popt->topt.recordSep.separator
5323 : "");
5324 else if (strcmp(param, "recordsep_zero") == 0)
5326 else if (strcmp(param, "tableattr") == 0)
5327 return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5328 else if (strcmp(param, "title") == 0)
5329 return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5330 else if (strcmp(param, "tuples_only") == 0)
5332 else if (strcmp(param, "unicode_border_linestyle") == 0)
5334 else if (strcmp(param, "unicode_column_linestyle") == 0)
5336 else if (strcmp(param, "unicode_header_linestyle") == 0)
5338 else if (strcmp(param, "xheader_width") == 0)
5339 {
5341 return pstrdup("full");
5343 return pstrdup("column");
5345 return pstrdup("page");
5346 else
5347 {
5348 /* must be PRINT_XHEADER_EXACT_WIDTH */
5349 char wbuff[32];
5350
5351 snprintf(wbuff, sizeof(wbuff), "%d",
5353 return pstrdup(wbuff);
5354 }
5355 }
5356 else
5357 return pstrdup("ERROR");
5358}
static char * pset_quoted_string(const char *str)
Definition: command.c:5246
static const char * pset_bool_string(bool val)
Definition: command.c:5239
char * pstrdup(const char *in)
Definition: mcxt.c:1696

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

Referenced by exec_command_pset().

◆ read_connect_arg()

static char * read_connect_arg ( PsqlScanState  scan_state)
static

Definition at line 3192 of file command.c.

3193{
3194 char *result;
3195 char quote;
3196
3197 /*
3198 * Ideally we should treat the arguments as SQL identifiers. But for
3199 * backwards compatibility with 7.2 and older pg_dump files, we have to
3200 * take unquoted arguments verbatim (don't downcase them). For now,
3201 * double-quoted arguments may be stripped of double quotes (as if SQL
3202 * identifiers). By 7.4 or so, pg_dump files can be expected to
3203 * double-quote all mixed-case \connect arguments, and then we can get rid
3204 * of OT_SQLIDHACK.
3205 */
3206 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
3207
3208 if (!result)
3209 return NULL;
3210
3211 if (quote)
3212 return result;
3213
3214 if (*result == '\0' || strcmp(result, "-") == 0)
3215 {
3216 free(result);
3217 return NULL;
3218 }
3219
3220 return result;
3221}
@ 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 5213 of file command.c.

5214{
5215 /* Free all the old data we're about to overwrite the pointers to. */
5216
5217 /* topt.line_style points to const data that need not be duplicated */
5218 free(popt->topt.fieldSep.separator);
5220 free(popt->topt.tableAttr);
5221 free(popt->nullPrint);
5222 free(popt->title);
5223
5224 /*
5225 * footers and translate_columns are never set in psql's print settings,
5226 * so we needn't write code to duplicate them.
5227 */
5228 Assert(popt->footers == NULL);
5229 Assert(popt->translate_columns == NULL);
5230
5231 /* Now we may flat-copy all the fields, including pointers. */
5232 memcpy(popt, save, sizeof(printQueryOpt));
5233
5234 /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5235 free(save);
5236}
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 3360 of file command.c.

3362{
3363 if (query_buf)
3364 conditional_stack_set_query_len(cstack, query_buf->len);
3366 psql_scan_get_paren_depth(scan_state));
3367}
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 5177 of file command.c.

5178{
5179 printQueryOpt *save;
5180
5181 save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
5182
5183 /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5184 memcpy(save, popt, sizeof(printQueryOpt));
5185
5186 /* topt.line_style points to const data that need not be duplicated */
5187 if (popt->topt.fieldSep.separator)
5189 if (popt->topt.recordSep.separator)
5191 if (popt->topt.tableAttr)
5192 save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5193 if (popt->nullPrint)
5194 save->nullPrint = pg_strdup(popt->nullPrint);
5195 if (popt->title)
5196 save->title = pg_strdup(popt->title);
5197
5198 /*
5199 * footers and translate_columns are never set in psql's print settings,
5200 * so we needn't write code to duplicate them.
5201 */
5202 Assert(popt->footers == NULL);
5203 Assert(popt->translate_columns == NULL);
5204
5205 return save;
5206}

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

4583{
4584 if (pg_strncasecmp("single", value, vallen) == 0)
4585 *linestyle = UNICODE_LINESTYLE_SINGLE;
4586 else if (pg_strncasecmp("double", value, vallen) == 0)
4587 *linestyle = UNICODE_LINESTYLE_DOUBLE;
4588 else
4589 return false;
4590 return true;
4591}

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

5918{
5919 char *c;
5920 int lineno;
5921
5922 if (!obj || obj[0] == '\0')
5923 return -1;
5924
5925 c = obj + strlen(obj) - 1;
5926
5927 /*
5928 * This business of parsing backwards is dangerous as can be in a
5929 * multibyte environment: there is no reason to believe that we are
5930 * looking at the first byte of a character, nor are we necessarily
5931 * working in a "safe" encoding. Fortunately the bitpatterns we are
5932 * looking for are unlikely to occur as non-first bytes, but beware of
5933 * trying to expand the set of cases that can be recognized. We must
5934 * guard the <ctype.h> macros by using isascii() first, too.
5935 */
5936
5937 /* skip trailing whitespace */
5938 while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
5939 c--;
5940
5941 /* must have a digit as last non-space char */
5942 if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
5943 return -1;
5944
5945 /* find start of digit string */
5946 while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
5947 c--;
5948
5949 /* digits must be separated from object name by space or closing paren */
5950 /* notice also that we are not allowing an empty object name ... */
5951 if (c == obj || !isascii((unsigned char) *c) ||
5952 !(isspace((unsigned char) *c) || *c == ')'))
5953 return -1;
5954
5955 /* parse digit string */
5956 c++;
5957 lineno = atoi(c);
5958 if (lineno < 1)
5959 {
5960 pg_log_error("invalid line number: %s", c);
5961 return 0;
5962 }
5963
5964 /* strip digit string from object name */
5965 *c = '\0';
5966
5967 return lineno;
5968}
char * c

References pg_log_error.

Referenced by exec_command_ef_ev().

◆ SyncVariables()

void SyncVariables ( void  )

Definition at line 4129 of file command.c.

4130{
4131 char vbuf[32];
4132 const char *server_version;
4133
4134 /* get stuff from connection */
4138
4140
4141 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4142 SetVariable(pset.vars, "SERVICE", PQservice(pset.db));
4143 SetVariable(pset.vars, "USER", PQuser(pset.db));
4144 SetVariable(pset.vars, "HOST", PQhost(pset.db));
4145 SetVariable(pset.vars, "PORT", PQport(pset.db));
4147
4148 /* this bit should match connection_warnings(): */
4149 /* Try to get full text form of version, might include "devel" etc */
4150 server_version = PQparameterStatus(pset.db, "server_version");
4151 /* Otherwise fall back on pset.sversion */
4152 if (!server_version)
4153 {
4154 formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4155 server_version = vbuf;
4156 }
4157 SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4158
4159 snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4160 SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4161
4162 /* send stuff to it, too */
4165}
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7497
char * PQservice(const PGconn *conn)
Definition: fe-connect.c:7343
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7659
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7647
PGVerbosity verbosity
Definition: settings.h:165
PGContextVisibility show_context
Definition: settings.h:167

References _psqlSettings::db, _psqlSettings::encoding, printTableOpt::encoding, formatPGVersionNumber(), pg_encoding_to_char, _psqlSettings::popt, PQclientEncoding(), PQdb(), PQhost(), PQparameterStatus(), PQport(), PQserverVersion(), 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 4173 of file command.c.

4174{
4175 SetVariable(pset.vars, "DBNAME", NULL);
4176 SetVariable(pset.vars, "SERVICE", NULL);
4177 SetVariable(pset.vars, "USER", NULL);
4178 SetVariable(pset.vars, "HOST", NULL);
4179 SetVariable(pset.vars, "PORT", NULL);
4180 SetVariable(pset.vars, "ENCODING", NULL);
4181 SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4182 SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
4183}

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

3940{
3941 bool forRead = false;
3942
3943 while (true)
3944 {
3945 int rc;
3946 int sock;
3948
3949 /*
3950 * On every iteration of the connection sequence, let's check if the
3951 * user has requested a cancellation.
3952 */
3953 if (cancel_pressed)
3954 break;
3955
3956 /*
3957 * Do not assume that the socket remains the same across
3958 * PQconnectPoll() calls.
3959 */
3960 sock = PQsocket(conn);
3961 if (sock == -1)
3962 break;
3963
3964 /*
3965 * If the user sends SIGINT between the cancel_pressed check, and
3966 * polling of the socket, it will not be recognized. Instead, we will
3967 * just wait until the next step in the connection sequence or
3968 * forever, which might require users to send SIGTERM or SIGQUIT.
3969 *
3970 * Some solutions would include the "self-pipe trick," using
3971 * pselect(2) and ppoll(2), or using a timeout.
3972 *
3973 * The self-pipe trick requires a bit of code to setup. pselect(2) and
3974 * ppoll(2) are not on all the platforms we support. The simplest
3975 * solution happens to just be adding a timeout, so let's wait for 1
3976 * second and check cancel_pressed again.
3977 */
3978 end_time = PQgetCurrentTimeUSec() + 1000000;
3979 rc = PQsocketPoll(sock, forRead, !forRead, end_time);
3980 if (rc == -1)
3981 return;
3982
3983 switch (PQconnectPoll(conn))
3984 {
3985 case PGRES_POLLING_OK:
3987 return;
3989 forRead = true;
3990 continue;
3992 forRead = false;
3993 continue;
3996 }
3997 }
3998}
#define pg_unreachable()
Definition: c.h:318
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2818
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7533
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
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:116
@ PGRES_POLLING_OK
Definition: libpq-fe.h:115
@ PGRES_POLLING_READING
Definition: libpq-fe.h:113
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:114
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:112
pg_int64 pg_usec_time_t
Definition: libpq-fe.h:228
static int64 end_time
Definition: pgbench.c:176
PGconn * conn
Definition: streamutil.c:53

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

Referenced by do_connect().