PostgreSQL Source Code  git master
startup.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include "command.h"
#include "common.h"
#include "common/logging.h"
#include "common/string.h"
#include "describe.h"
#include "fe_utils/print.h"
#include "getopt_long.h"
#include "help.h"
#include "input.h"
#include "mainloop.h"
#include "settings.h"
Include dependency graph for startup.c:

Go to the source code of this file.

Data Structures

struct  SimpleActionListCell
 
struct  SimpleActionList
 
struct  adhoc_opts
 

Macros

#define SYSPSQLRC   "psqlrc"
 
#define PSQLRC   ".psqlrc"
 
#define NOPAGER   0
 
#define PARAMS_ARRAY_SIZE   8
 

Typedefs

typedef struct SimpleActionListCell SimpleActionListCell
 
typedef struct SimpleActionList SimpleActionList
 

Enumerations

enum  _actions { ACT_SINGLE_QUERY , ACT_SINGLE_SLASH , ACT_FILE }
 

Functions

static void parse_psql_options (int argc, char *argv[], struct adhoc_opts *options)
 
static void simple_action_list_append (SimpleActionList *list, enum _actions action, const char *val)
 
static void process_psqlrc (char *argv0)
 
static void process_psqlrc_file (char *filename)
 
static void showVersion (void)
 
static void EstablishVariableSpace (void)
 
static void log_pre_callback (void)
 
static void log_locus_callback (const char **filename, uint64 *lineno)
 
int main (int argc, char *argv[])
 
static char * bool_substitute_hook (char *newval)
 
static bool autocommit_hook (const char *newval)
 
static bool on_error_stop_hook (const char *newval)
 
static bool quiet_hook (const char *newval)
 
static bool singleline_hook (const char *newval)
 
static bool singlestep_hook (const char *newval)
 
static char * fetch_count_substitute_hook (char *newval)
 
static bool fetch_count_hook (const char *newval)
 
static bool histfile_hook (const char *newval)
 
static char * histsize_substitute_hook (char *newval)
 
static bool histsize_hook (const char *newval)
 
static char * ignoreeof_substitute_hook (char *newval)
 
static bool ignoreeof_hook (const char *newval)
 
static char * echo_substitute_hook (char *newval)
 
static bool echo_hook (const char *newval)
 
static bool echo_hidden_hook (const char *newval)
 
static bool on_error_rollback_hook (const char *newval)
 
static char * comp_keyword_case_substitute_hook (char *newval)
 
static bool comp_keyword_case_hook (const char *newval)
 
static char * histcontrol_substitute_hook (char *newval)
 
static bool histcontrol_hook (const char *newval)
 
static bool prompt1_hook (const char *newval)
 
static bool prompt2_hook (const char *newval)
 
static bool prompt3_hook (const char *newval)
 
static char * verbosity_substitute_hook (char *newval)
 
static bool verbosity_hook (const char *newval)
 
static bool show_all_results_hook (const char *newval)
 
static char * show_context_substitute_hook (char *newval)
 
static bool show_context_hook (const char *newval)
 
static bool hide_compression_hook (const char *newval)
 
static bool hide_tableam_hook (const char *newval)
 

Variables

PsqlSettings pset
 

Macro Definition Documentation

◆ NOPAGER

#define NOPAGER   0

Definition at line 89 of file startup.c.

◆ PARAMS_ARRAY_SIZE

#define PARAMS_ARRAY_SIZE   8

◆ PSQLRC

#define PSQLRC   ".psqlrc"

Definition at line 36 of file startup.c.

◆ SYSPSQLRC

#define SYSPSQLRC   "psqlrc"

Definition at line 35 of file startup.c.

Typedef Documentation

◆ SimpleActionList

◆ SimpleActionListCell

Enumeration Type Documentation

◆ _actions

enum _actions
Enumerator
ACT_SINGLE_QUERY 
ACT_SINGLE_SLASH 
ACT_FILE 

Definition at line 46 of file startup.c.

47 {
50  ACT_FILE
51 };
@ ACT_SINGLE_SLASH
Definition: startup.c:49
@ ACT_FILE
Definition: startup.c:50
@ ACT_SINGLE_QUERY
Definition: startup.c:48

Function Documentation

◆ autocommit_hook()

static bool autocommit_hook ( const char *  newval)
static

Definition at line 868 of file startup.c.

869 {
870  return ParseVariableBool(newval, "AUTOCOMMIT", &pset.autocommit);
871 }
PsqlSettings pset
Definition: startup.c:32
#define newval
bool autocommit
Definition: settings.h:132
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107

References _psqlSettings::autocommit, newval, ParseVariableBool(), and pset.

Referenced by EstablishVariableSpace().

◆ bool_substitute_hook()

static char* bool_substitute_hook ( char *  newval)
static

Definition at line 851 of file startup.c.

852 {
853  if (newval == NULL)
854  {
855  /* "\unset FOO" becomes "\set FOO off" */
856  newval = pg_strdup("off");
857  }
858  else if (newval[0] == '\0')
859  {
860  /* "\set FOO" becomes "\set FOO on" */
861  pg_free(newval);
862  newval = pg_strdup("on");
863  }
864  return newval;
865 }
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void pg_free(void *ptr)
Definition: fe_memutils.c:105

References newval, pg_free(), and pg_strdup().

Referenced by EstablishVariableSpace().

◆ comp_keyword_case_hook()

static bool comp_keyword_case_hook ( const char *  newval)
static

Definition at line 1041 of file startup.c.

1042 {
1043  Assert(newval != NULL); /* else substitute hook messed up */
1044  if (pg_strcasecmp(newval, "preserve-upper") == 0)
1046  else if (pg_strcasecmp(newval, "preserve-lower") == 0)
1048  else if (pg_strcasecmp(newval, "upper") == 0)
1050  else if (pg_strcasecmp(newval, "lower") == 0)
1052  else
1053  {
1054  PsqlVarEnumError("COMP_KEYWORD_CASE", newval,
1055  "lower, upper, preserve-lower, preserve-upper");
1056  return false;
1057  }
1058  return true;
1059 }
Assert(fmt[strlen(fmt) - 1] !='\n')
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
@ PSQL_COMP_CASE_PRESERVE_LOWER
Definition: settings.h:60
@ PSQL_COMP_CASE_LOWER
Definition: settings.h:62
@ PSQL_COMP_CASE_PRESERVE_UPPER
Definition: settings.h:59
@ PSQL_COMP_CASE_UPPER
Definition: settings.h:61
PSQL_COMP_CASE comp_case
Definition: settings.h:145
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:417

References Assert(), _psqlSettings::comp_case, newval, pg_strcasecmp(), pset, PSQL_COMP_CASE_LOWER, PSQL_COMP_CASE_PRESERVE_LOWER, PSQL_COMP_CASE_PRESERVE_UPPER, PSQL_COMP_CASE_UPPER, and PsqlVarEnumError().

Referenced by EstablishVariableSpace().

◆ comp_keyword_case_substitute_hook()

static char* comp_keyword_case_substitute_hook ( char *  newval)
static

Definition at line 1033 of file startup.c.

1034 {
1035  if (newval == NULL)
1036  newval = pg_strdup("preserve-upper");
1037  return newval;
1038 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ echo_hidden_hook()

static bool echo_hidden_hook ( const char *  newval)
static

Definition at line 991 of file startup.c.

992 {
993  Assert(newval != NULL); /* else substitute hook messed up */
994  if (pg_strcasecmp(newval, "noexec") == 0)
996  else
997  {
998  bool on_off;
999 
1000  if (ParseVariableBool(newval, NULL, &on_off))
1002  else
1003  {
1004  PsqlVarEnumError("ECHO_HIDDEN", newval, "on, off, noexec");
1005  return false;
1006  }
1007  }
1008  return true;
1009 }
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
@ PSQL_ECHO_HIDDEN_ON
Definition: settings.h:46
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:143

References Assert(), _psqlSettings::echo_hidden, newval, ParseVariableBool(), pg_strcasecmp(), pset, PSQL_ECHO_HIDDEN_NOEXEC, PSQL_ECHO_HIDDEN_OFF, PSQL_ECHO_HIDDEN_ON, and PsqlVarEnumError().

Referenced by EstablishVariableSpace().

◆ echo_hook()

static bool echo_hook ( const char *  newval)
static

Definition at line 971 of file startup.c.

972 {
973  Assert(newval != NULL); /* else substitute hook messed up */
974  if (pg_strcasecmp(newval, "queries") == 0)
976  else if (pg_strcasecmp(newval, "errors") == 0)
978  else if (pg_strcasecmp(newval, "all") == 0)
980  else if (pg_strcasecmp(newval, "none") == 0)
982  else
983  {
984  PsqlVarEnumError("ECHO", newval, "none, errors, queries, all");
985  return false;
986  }
987  return true;
988 }
@ PSQL_ECHO_ALL
Definition: settings.h:40
@ PSQL_ECHO_ERRORS
Definition: settings.h:39
@ PSQL_ECHO_NONE
Definition: settings.h:37
@ PSQL_ECHO_QUERIES
Definition: settings.h:38
PSQL_ECHO echo
Definition: settings.h:142

References Assert(), _psqlSettings::echo, newval, pg_strcasecmp(), pset, PSQL_ECHO_ALL, PSQL_ECHO_ERRORS, PSQL_ECHO_NONE, PSQL_ECHO_QUERIES, and PsqlVarEnumError().

Referenced by EstablishVariableSpace().

◆ echo_substitute_hook()

static char* echo_substitute_hook ( char *  newval)
static

Definition at line 963 of file startup.c.

964 {
965  if (newval == NULL)
966  newval = pg_strdup("none");
967  return newval;
968 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ EstablishVariableSpace()

static void EstablishVariableSpace ( void  )
static

Definition at line 1191 of file startup.c.

1192 {
1194 
1195  SetVariableHooks(pset.vars, "AUTOCOMMIT",
1197  autocommit_hook);
1198  SetVariableHooks(pset.vars, "ON_ERROR_STOP",
1201  SetVariableHooks(pset.vars, "QUIET",
1203  quiet_hook);
1204  SetVariableHooks(pset.vars, "SINGLELINE",
1206  singleline_hook);
1207  SetVariableHooks(pset.vars, "SINGLESTEP",
1209  singlestep_hook);
1210  SetVariableHooks(pset.vars, "FETCH_COUNT",
1213  SetVariableHooks(pset.vars, "HISTFILE",
1214  NULL,
1215  histfile_hook);
1216  SetVariableHooks(pset.vars, "HISTSIZE",
1218  histsize_hook);
1219  SetVariableHooks(pset.vars, "IGNOREEOF",
1221  ignoreeof_hook);
1222  SetVariableHooks(pset.vars, "ECHO",
1224  echo_hook);
1225  SetVariableHooks(pset.vars, "ECHO_HIDDEN",
1228  SetVariableHooks(pset.vars, "ON_ERROR_ROLLBACK",
1231  SetVariableHooks(pset.vars, "COMP_KEYWORD_CASE",
1234  SetVariableHooks(pset.vars, "HISTCONTROL",
1237  SetVariableHooks(pset.vars, "PROMPT1",
1238  NULL,
1239  prompt1_hook);
1240  SetVariableHooks(pset.vars, "PROMPT2",
1241  NULL,
1242  prompt2_hook);
1243  SetVariableHooks(pset.vars, "PROMPT3",
1244  NULL,
1245  prompt3_hook);
1246  SetVariableHooks(pset.vars, "VERBOSITY",
1248  verbosity_hook);
1249  SetVariableHooks(pset.vars, "SHOW_ALL_RESULTS",
1252  SetVariableHooks(pset.vars, "SHOW_CONTEXT",
1255  SetVariableHooks(pset.vars, "HIDE_TOAST_COMPRESSION",
1258  SetVariableHooks(pset.vars, "HIDE_TABLEAM",
1261 }
static bool show_context_hook(const char *newval)
Definition: startup.c:1157
static bool hide_tableam_hook(const char *newval)
Definition: startup.c:1185
static bool quiet_hook(const char *newval)
Definition: startup.c:880
static bool singleline_hook(const char *newval)
Definition: startup.c:886
static bool prompt2_hook(const char *newval)
Definition: startup.c:1098
static bool comp_keyword_case_hook(const char *newval)
Definition: startup.c:1041
static char * histsize_substitute_hook(char *newval)
Definition: startup.c:922
static char * ignoreeof_substitute_hook(char *newval)
Definition: startup.c:936
static bool histcontrol_hook(const char *newval)
Definition: startup.c:1070
static bool prompt1_hook(const char *newval)
Definition: startup.c:1091
static bool verbosity_hook(const char *newval)
Definition: startup.c:1120
static bool show_all_results_hook(const char *newval)
Definition: startup.c:1143
static bool fetch_count_hook(const char *newval)
Definition: startup.c:906
static bool histsize_hook(const char *newval)
Definition: startup.c:930
static char * echo_substitute_hook(char *newval)
Definition: startup.c:963
static bool hide_compression_hook(const char *newval)
Definition: startup.c:1178
static bool singlestep_hook(const char *newval)
Definition: startup.c:892
static char * histcontrol_substitute_hook(char *newval)
Definition: startup.c:1062
static bool histfile_hook(const char *newval)
Definition: startup.c:912
static bool prompt3_hook(const char *newval)
Definition: startup.c:1105
static bool on_error_rollback_hook(const char *newval)
Definition: startup.c:1012
static bool on_error_stop_hook(const char *newval)
Definition: startup.c:874
static char * fetch_count_substitute_hook(char *newval)
Definition: startup.c:898
static bool autocommit_hook(const char *newval)
Definition: startup.c:868
static bool ignoreeof_hook(const char *newval)
Definition: startup.c:957
static bool echo_hidden_hook(const char *newval)
Definition: startup.c:991
static char * verbosity_substitute_hook(char *newval)
Definition: startup.c:1112
static bool echo_hook(const char *newval)
Definition: startup.c:971
static char * bool_substitute_hook(char *newval)
Definition: startup.c:851
static char * show_context_substitute_hook(char *newval)
Definition: startup.c:1149
static char * comp_keyword_case_substitute_hook(char *newval)
Definition: startup.c:1033
VariableSpace vars
Definition: settings.h:118
void SetVariableHooks(VariableSpace space, const char *name, VariableSubstituteHook shook, VariableAssignHook ahook)
Definition: variables.c:315
VariableSpace CreateVariableSpace(void)
Definition: variables.c:51

References autocommit_hook(), bool_substitute_hook(), comp_keyword_case_hook(), comp_keyword_case_substitute_hook(), CreateVariableSpace(), echo_hidden_hook(), echo_hook(), echo_substitute_hook(), fetch_count_hook(), fetch_count_substitute_hook(), hide_compression_hook(), hide_tableam_hook(), histcontrol_hook(), histcontrol_substitute_hook(), histfile_hook(), histsize_hook(), histsize_substitute_hook(), ignoreeof_hook(), ignoreeof_substitute_hook(), on_error_rollback_hook(), on_error_stop_hook(), prompt1_hook(), prompt2_hook(), prompt3_hook(), pset, quiet_hook(), SetVariableHooks(), show_all_results_hook(), show_context_hook(), show_context_substitute_hook(), singleline_hook(), singlestep_hook(), _psqlSettings::vars, verbosity_hook(), and verbosity_substitute_hook().

Referenced by main().

◆ fetch_count_hook()

static bool fetch_count_hook ( const char *  newval)
static

Definition at line 906 of file startup.c.

907 {
908  return ParseVariableNum(newval, "FETCH_COUNT", &pset.fetch_count);
909 }
int fetch_count
Definition: settings.h:139
bool ParseVariableNum(const char *value, const char *name, int *result)
Definition: variables.c:156

References _psqlSettings::fetch_count, newval, ParseVariableNum(), and pset.

Referenced by EstablishVariableSpace().

◆ fetch_count_substitute_hook()

static char* fetch_count_substitute_hook ( char *  newval)
static

Definition at line 898 of file startup.c.

899 {
900  if (newval == NULL)
901  newval = pg_strdup("0");
902  return newval;
903 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ hide_compression_hook()

static bool hide_compression_hook ( const char *  newval)
static

Definition at line 1178 of file startup.c.

1179 {
1180  return ParseVariableBool(newval, "HIDE_TOAST_COMPRESSION",
1182 }
bool hide_compression
Definition: settings.h:137

References _psqlSettings::hide_compression, newval, ParseVariableBool(), and pset.

Referenced by EstablishVariableSpace().

◆ hide_tableam_hook()

static bool hide_tableam_hook ( const char *  newval)
static

Definition at line 1185 of file startup.c.

1186 {
1187  return ParseVariableBool(newval, "HIDE_TABLEAM", &pset.hide_tableam);
1188 }
bool hide_tableam
Definition: settings.h:138

References _psqlSettings::hide_tableam, newval, ParseVariableBool(), and pset.

Referenced by EstablishVariableSpace().

◆ histcontrol_hook()

static bool histcontrol_hook ( const char *  newval)
static

Definition at line 1070 of file startup.c.

1071 {
1072  Assert(newval != NULL); /* else substitute hook messed up */
1073  if (pg_strcasecmp(newval, "ignorespace") == 0)
1075  else if (pg_strcasecmp(newval, "ignoredups") == 0)
1077  else if (pg_strcasecmp(newval, "ignoreboth") == 0)
1079  else if (pg_strcasecmp(newval, "none") == 0)
1081  else
1082  {
1083  PsqlVarEnumError("HISTCONTROL", newval,
1084  "none, ignorespace, ignoredups, ignoreboth");
1085  return false;
1086  }
1087  return true;
1088 }
@ hctl_ignoredups
Definition: settings.h:69
@ hctl_ignoreboth
Definition: settings.h:70
@ hctl_none
Definition: settings.h:67
@ hctl_ignorespace
Definition: settings.h:68
HistControl histcontrol
Definition: settings.h:146

References Assert(), hctl_ignoreboth, hctl_ignoredups, hctl_ignorespace, hctl_none, _psqlSettings::histcontrol, newval, pg_strcasecmp(), pset, and PsqlVarEnumError().

Referenced by EstablishVariableSpace().

◆ histcontrol_substitute_hook()

static char* histcontrol_substitute_hook ( char *  newval)
static

Definition at line 1062 of file startup.c.

1063 {
1064  if (newval == NULL)
1065  newval = pg_strdup("none");
1066  return newval;
1067 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ histfile_hook()

static bool histfile_hook ( const char *  newval)
static

Definition at line 912 of file startup.c.

913 {
914  /*
915  * Someday we might try to validate the filename, but for now, this is
916  * just a placeholder to ensure HISTFILE is known to tab completion.
917  */
918  return true;
919 }

Referenced by EstablishVariableSpace().

◆ histsize_hook()

static bool histsize_hook ( const char *  newval)
static

Definition at line 930 of file startup.c.

931 {
932  return ParseVariableNum(newval, "HISTSIZE", &pset.histsize);
933 }

References _psqlSettings::histsize, newval, ParseVariableNum(), and pset.

Referenced by EstablishVariableSpace().

◆ histsize_substitute_hook()

static char* histsize_substitute_hook ( char *  newval)
static

Definition at line 922 of file startup.c.

923 {
924  if (newval == NULL)
925  newval = pg_strdup("500");
926  return newval;
927 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ ignoreeof_hook()

static bool ignoreeof_hook ( const char *  newval)
static

Definition at line 957 of file startup.c.

958 {
959  return ParseVariableNum(newval, "IGNOREEOF", &pset.ignoreeof);
960 }

References _psqlSettings::ignoreeof, newval, ParseVariableNum(), and pset.

Referenced by EstablishVariableSpace().

◆ ignoreeof_substitute_hook()

static char* ignoreeof_substitute_hook ( char *  newval)
static

Definition at line 936 of file startup.c.

937 {
938  int dummy;
939 
940  /*
941  * This tries to mimic the behavior of bash, to wit "If set, the value is
942  * the number of consecutive EOF characters which must be typed as the
943  * first characters on an input line before bash exits. If the variable
944  * exists but does not have a numeric value, or has no value, the default
945  * value is 10. If it does not exist, EOF signifies the end of input to
946  * the shell." Unlike bash, however, we insist on the stored value
947  * actually being a valid integer.
948  */
949  if (newval == NULL)
950  newval = pg_strdup("0");
951  else if (!ParseVariableNum(newval, NULL, &dummy))
952  newval = pg_strdup("10");
953  return newval;
954 }

References newval, ParseVariableNum(), and pg_strdup().

Referenced by EstablishVariableSpace().

◆ log_locus_callback()

static void log_locus_callback ( const char **  filename,
uint64 *  lineno 
)
static

Definition at line 99 of file startup.c.

100 {
101  if (pset.inputfile)
102  {
104  *lineno = pset.lineno;
105  }
106  else
107  {
108  *filename = NULL;
109  *lineno = 0;
110  }
111 }
static char * filename
Definition: pg_dumpall.c:94
uint64 lineno
Definition: settings.h:111
char * inputfile
Definition: settings.h:110

References filename, _psqlSettings::inputfile, _psqlSettings::lineno, and pset.

Referenced by main().

◆ log_pre_callback()

static void log_pre_callback ( void  )
static

Definition at line 92 of file startup.c.

93 {
96 }
static void const char fflush(stdout)
FILE * queryFout
Definition: settings.h:84

References fflush(), pset, _psqlSettings::queryFout, and generate_unaccent_rules::stdout.

Referenced by main().

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 126 of file startup.c.

127 {
128  struct adhoc_opts options;
129  int successResult;
130  char *password = NULL;
131  bool new_pass;
132 
133  pg_logging_init(argv[0]);
136  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("psql"));
137 
138  if (argc > 1)
139  {
140  if ((strcmp(argv[1], "-?") == 0) || (argc == 2 && (strcmp(argv[1], "--help") == 0)))
141  {
142  usage(NOPAGER);
144  }
145  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
146  {
147  showVersion();
149  }
150  }
151 
152  pset.progname = get_progname(argv[0]);
153 
154  pset.db = NULL;
155  pset.dead_conn = NULL;
159  pset.queryFoutPipe = false;
160  pset.copyStream = NULL;
161  pset.last_error_result = NULL;
162  pset.cur_cmd_source = stdin;
163  pset.cur_cmd_interactive = false;
164 
165  /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
167  pset.popt.topt.border = 1;
168  pset.popt.topt.pager = 1;
170  pset.popt.topt.start_table = true;
171  pset.popt.topt.stop_table = true;
172  pset.popt.topt.default_footer = true;
173 
175  pset.popt.topt.csvFieldSep[1] = '\0';
176 
180 
182 
183  /* We must get COLUMNS here before readline() sets it */
184  pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;
185 
186  pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
187 
189 
191 
192  /* Create variables showing psql version number */
193  SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
194  SetVariable(pset.vars, "VERSION_NAME", PG_VERSION);
195  SetVariable(pset.vars, "VERSION_NUM", CppAsString2(PG_VERSION_NUM));
196 
197  /* Initialize variables for last error */
198  SetVariable(pset.vars, "LAST_ERROR_MESSAGE", "");
199  SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", "00000");
200 
201  /* Default values for variables (that don't match the result of \unset) */
202  SetVariableBool(pset.vars, "AUTOCOMMIT");
203  SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
204  SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
205  SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
206  SetVariableBool(pset.vars, "SHOW_ALL_RESULTS");
207 
208  parse_psql_options(argc, argv, &options);
209 
210  /*
211  * If no action was specified and we're in non-interactive mode, treat it
212  * as if the user had specified "-f -". This lets single-transaction mode
213  * work in this case.
214  */
215  if (options.actions.head == NULL && pset.notty)
216  simple_action_list_append(&options.actions, ACT_FILE, NULL);
217 
218  /* Bail out if -1 was specified but will be ignored. */
219  if (options.single_txn && options.actions.head == NULL)
220  pg_fatal("-1 can only be used in non-interactive mode");
221 
224  {
227  }
230  {
233  }
234 
235  if (pset.getPassword == TRI_YES)
236  {
237  /*
238  * We can't be sure yet of the username that will be used, so don't
239  * offer a potentially wrong one. Typical uses of this option are
240  * noninteractive anyway. (Note: since we've not yet set up our
241  * cancel handler, there's no need to use simple_prompt_extended.)
242  */
243  password = simple_prompt("Password: ", false);
244  }
245 
246  /* loop until we have a password if requested by backend */
247  do
248  {
249 #define PARAMS_ARRAY_SIZE 8
250  const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
251  const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
252 
253  keywords[0] = "host";
254  values[0] = options.host;
255  keywords[1] = "port";
256  values[1] = options.port;
257  keywords[2] = "user";
258  values[2] = options.username;
259  keywords[3] = "password";
260  values[3] = password;
261  keywords[4] = "dbname"; /* see do_connect() */
262  values[4] = (options.list_dbs && options.dbname == NULL) ?
263  "postgres" : options.dbname;
264  keywords[5] = "fallback_application_name";
265  values[5] = pset.progname;
266  keywords[6] = "client_encoding";
267  values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
268  keywords[7] = NULL;
269  values[7] = NULL;
270 
271  new_pass = false;
272  pset.db = PQconnectdbParams(keywords, values, true);
273  free(keywords);
274  free(values);
275 
276  if (PQstatus(pset.db) == CONNECTION_BAD &&
278  !password &&
280  {
281  /*
282  * Before closing the old PGconn, extract the user name that was
283  * actually connected with --- it might've come out of a URI or
284  * connstring "database name" rather than options.username.
285  */
286  const char *realusername = PQuser(pset.db);
287  char *password_prompt;
288 
289  if (realusername && realusername[0])
290  password_prompt = psprintf(_("Password for user %s: "),
291  realusername);
292  else
293  password_prompt = pg_strdup(_("Password: "));
294  PQfinish(pset.db);
295 
296  password = simple_prompt(password_prompt, false);
297  free(password_prompt);
298  new_pass = true;
299  }
300  } while (new_pass);
301 
302  if (PQstatus(pset.db) == CONNECTION_BAD)
303  {
305  PQfinish(pset.db);
307  }
308 
310 
311 #ifdef HAVE_POSIX_DECL_SIGWAIT
312 
313  /*
314  * do_watch() needs signal handlers installed (otherwise sigwait() will
315  * filter them out on some platforms), but doesn't need them to do
316  * anything, and they shouldn't ever run (unless perhaps a stray SIGALRM
317  * arrives due to a race when do_watch() cancels an itimer).
318  */
319  pqsignal(SIGCHLD, empty_signal_handler);
320  pqsignal(SIGALRM, empty_signal_handler);
321 #endif
322 
324 
325  SyncVariables();
326 
327  if (options.list_dbs)
328  {
329  int success;
330 
331  if (!options.no_psqlrc)
332  process_psqlrc(argv[0]);
333 
334  success = listAllDbs(NULL, false);
335  PQfinish(pset.db);
337  }
338 
339  if (options.logfilename)
340  {
341  pset.logfile = fopen(options.logfilename, "a");
342  if (!pset.logfile)
343  pg_fatal("could not open log file \"%s\": %m",
344  options.logfilename);
345  }
346 
347  if (!options.no_psqlrc)
348  process_psqlrc(argv[0]);
349 
350  /*
351  * If any actions were given by user, process them in the order in which
352  * they were specified. Note single_txn is only effective in this mode.
353  */
354  if (options.actions.head != NULL)
355  {
356  PGresult *res;
357  SimpleActionListCell *cell;
358 
359  successResult = EXIT_SUCCESS; /* silence compiler */
360 
361  if (options.single_txn)
362  {
363  if ((res = PSQLexec("BEGIN")) == NULL)
364  {
365  if (pset.on_error_stop)
366  {
367  successResult = EXIT_USER;
368  goto error;
369  }
370  }
371  else
372  PQclear(res);
373  }
374 
375  for (cell = options.actions.head; cell; cell = cell->next)
376  {
377  if (cell->action == ACT_SINGLE_QUERY)
378  {
380 
381  if (pset.echo == PSQL_ECHO_ALL)
382  puts(cell->val);
383 
384  successResult = SendQuery(cell->val)
386  }
387  else if (cell->action == ACT_SINGLE_SLASH)
388  {
389  PsqlScanState scan_state;
390  ConditionalStack cond_stack;
391 
393 
394  if (pset.echo == PSQL_ECHO_ALL)
395  puts(cell->val);
396 
397  scan_state = psql_scan_create(&psqlscan_callbacks);
398  psql_scan_setup(scan_state,
399  cell->val, strlen(cell->val),
401  cond_stack = conditional_stack_create();
402  psql_scan_set_passthrough(scan_state, (void *) cond_stack);
403 
404  successResult = HandleSlashCmds(scan_state,
405  cond_stack,
406  NULL,
407  NULL) != PSQL_CMD_ERROR
409 
410  psql_scan_destroy(scan_state);
411  conditional_stack_destroy(cond_stack);
412  }
413  else if (cell->action == ACT_FILE)
414  {
415  successResult = process_file(cell->val, false);
416  }
417  else
418  {
419  /* should never come here */
420  Assert(false);
421  }
422 
423  if (successResult != EXIT_SUCCESS && pset.on_error_stop)
424  break;
425  }
426 
427  if (options.single_txn)
428  {
429  if ((res = PSQLexec("COMMIT")) == NULL)
430  {
431  if (pset.on_error_stop)
432  {
433  successResult = EXIT_USER;
434  goto error;
435  }
436  }
437  else
438  PQclear(res);
439  }
440 
441 error:
442  ;
443  }
444 
445  /*
446  * or otherwise enter interactive main loop
447  */
448  else
449  {
451  connection_warnings(true);
452  if (!pset.quiet)
453  printf(_("Type \"help\" for help.\n\n"));
454  initializeInput(options.no_readline ? 0 : 1);
455  successResult = MainLoop(stdin);
456  }
457 
458  /* clean up */
459  if (pset.logfile)
460  fclose(pset.logfile);
461  if (pset.db)
462  PQfinish(pset.db);
463  if (pset.dead_conn)
465  setQFout(NULL);
466 
467  return successResult;
468 }
void psql_setup_cancel_handler(void)
Definition: common.c:269
PGresult * PSQLexec(const char *query)
Definition: common.c:556
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:223
bool standard_strings(void)
Definition: common.c:2281
bool setQFout(const char *fname)
Definition: common.c:88
bool SendQuery(const char *query)
Definition: common.c:1115
static void process_psqlrc(char *argv0)
Definition: startup.c:767
static void EstablishVariableSpace(void)
Definition: startup.c:1191
static void log_pre_callback(void)
Definition: startup.c:92
#define NOPAGER
Definition: startup.c:89
#define PARAMS_ARRAY_SIZE
static void log_locus_callback(const char **filename, uint64 *lineno)
Definition: startup.c:99
static void simple_action_list_append(SimpleActionList *list, enum _actions action, const char *val)
Definition: startup.c:741
static void parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
Definition: startup.c:476
static void showVersion(void)
Definition: startup.c:832
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
#define CppAsString2(x)
Definition: c.h:289
backslashResult HandleSlashCmds(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:213
void SyncVariables(void)
Definition: command.c:3739
void connection_warnings(bool in_startup)
Definition: command.c:3614
@ PSQL_CMD_ERROR
Definition: command.h:22
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:446
ConditionalStack conditional_stack_create(void)
Definition: conditional.c:18
void conditional_stack_destroy(ConditionalStack cstack)
Definition: conditional.c:43
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:902
#define _(x)
Definition: elog.c:89
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:658
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6959
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6908
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6855
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4261
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6762
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7076
void PQclear(PGresult *res)
Definition: fe-exec.c:718
int PQenv2encoding(void)
Definition: fe-misc.c:1214
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3632
void setDecimalLocale(void)
Definition: print.c:3582
@ UNICODE_LINESTYLE_SINGLE
Definition: print.h:89
@ PRINT_ALIGNED
Definition: print.h:31
#define free(a)
Definition: header.h:65
static bool success
Definition: initdb.c:169
void initializeInput(int flags)
Definition: input.c:346
@ CONNECTION_BAD
Definition: libpq-fe.h:61
exit(1)
void pg_logging_init(const char *argv0)
Definition: logging.c:83
void pg_logging_set_locus_callback(void(*cb)(const char **filename, uint64 *lineno))
Definition: logging.c:199
void pg_logging_config(int new_flags)
Definition: logging.c:163
void pg_logging_set_pre_callback(void(*cb)(void))
Definition: logging.c:193
#define pg_log_error(...)
Definition: logging.h:106
#define PG_LOG_FLAG_TERSE
Definition: logging.h:86
const PsqlScanCallbacks psqlscan_callbacks
Definition: mainloop.c:20
int MainLoop(FILE *source)
Definition: mainloop.c:33
#define pg_fatal(...)
static void process_file(const char *filename, int weight)
Definition: pgbench.c:5969
const char * get_progname(const char *argv0)
Definition: path.c:574
#define printf(...)
Definition: port.h:231
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void psql_scan_destroy(PsqlScanState state)
PsqlScanState psql_scan_create(const PsqlScanCallbacks *callbacks)
void psql_scan_set_passthrough(PsqlScanState state, void *passthrough)
void psql_scan_setup(PsqlScanState state, const char *line, int line_len, int encoding, bool std_strings)
#define DEFAULT_PROMPT1
Definition: settings.h:26
#define DEFAULT_PROMPT3
Definition: settings.h:28
#define DEFAULT_RECORD_SEP
Definition: settings.h:16
#define DEFAULT_FIELD_SEP
Definition: settings.h:15
#define EXIT_SUCCESS
Definition: settings.h:159
#define EXIT_FAILURE
Definition: settings.h:163
#define EXIT_BADCONN
Definition: settings.h:166
#define DEFAULT_PROMPT2
Definition: settings.h:27
#define EXIT_USER
Definition: settings.h:168
#define DEFAULT_CSV_FIELD_SEP
Definition: settings.h:14
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static void error(void)
Definition: sql-dyntest.c:147
static char * password
Definition: streamutil.c:53
struct SimpleActionListCell * next
Definition: startup.c:55
enum _actions action
Definition: startup.c:56
printQueryOpt popt
Definition: settings.h:91
int encoding
Definition: settings.h:83
FILE * logfile
Definition: settings.h:116
bool on_error_stop
Definition: settings.h:133
PGconn * dead_conn
Definition: settings.h:125
PGresult * last_error_result
Definition: settings.h:89
FILE * copyStream
Definition: settings.h:87
PGconn * db
Definition: settings.h:82
bool queryFoutPipe
Definition: settings.h:85
enum trivalue getPassword
Definition: settings.h:104
bool cur_cmd_interactive
Definition: settings.h:107
FILE * cur_cmd_source
Definition: settings.h:105
const char * progname
Definition: settings.h:109
char * username
Definition: oid2name.c:45
char * dbname
Definition: oid2name.c:42
char * port
Definition: oid2name.c:44
printTableOpt topt
Definition: print.h:169
bool start_table
Definition: print.h:111
unicode_linestyle unicode_border_linestyle
Definition: print.h:125
enum printFormat format
Definition: print.h:101
struct separator fieldSep
Definition: print.h:116
struct separator recordSep
Definition: print.h:117
char csvFieldSep[2]
Definition: print.h:118
bool default_footer
Definition: print.h:113
int pager_min_lines
Definition: print.h:108
unsigned short int pager
Definition: print.h:106
unsigned short int border
Definition: print.h:104
unicode_linestyle unicode_header_linestyle
Definition: print.h:127
int env_columns
Definition: print.h:123
unicode_linestyle unicode_column_linestyle
Definition: print.h:126
bool stop_table
Definition: print.h:112
bool separator_zero
Definition: print.h:96
char * separator
Definition: print.h:95
static void usage(const char *progname)
Definition: vacuumlo.c:417
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_DEFAULT
Definition: vacuumlo.c:36
@ TRI_NO
Definition: vacuumlo.c:37
bool SetVariableBool(VariableSpace space, const char *name)
Definition: variables.c:393
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
#define SIGCHLD
Definition: win32_port.h:177
#define SIGALRM
Definition: win32_port.h:173

References _, ACT_FILE, ACT_SINGLE_QUERY, ACT_SINGLE_SLASH, SimpleActionListCell::action, Assert(), printTableOpt::border, conditional_stack_create(), conditional_stack_destroy(), CONNECTION_BAD, connection_warnings(), _psqlSettings::copyStream, CppAsString2, printTableOpt::csvFieldSep, _psqlSettings::cur_cmd_interactive, _psqlSettings::cur_cmd_source, _psqlSettings::db, options::dbname, _psqlSettings::dead_conn, DEFAULT_CSV_FIELD_SEP, DEFAULT_FIELD_SEP, printTableOpt::default_footer, DEFAULT_PROMPT1, DEFAULT_PROMPT2, DEFAULT_PROMPT3, DEFAULT_RECORD_SEP, _psqlSettings::echo, _psqlSettings::encoding, printTableOpt::env_columns, error(), EstablishVariableSpace(), exit(), EXIT_BADCONN, EXIT_FAILURE, EXIT_SUCCESS, EXIT_USER, printTableOpt::fieldSep, printTableOpt::format, free, get_progname(), _psqlSettings::getPassword, HandleSlashCmds(), initializeInput(), _psqlSettings::last_error_result, listAllDbs(), log_locus_callback(), log_pre_callback(), _psqlSettings::logfile, MainLoop(), SimpleActionListCell::next, NOPAGER, NoticeProcessor(), _psqlSettings::notty, _psqlSettings::on_error_stop, printTableOpt::pager, printTableOpt::pager_min_lines, PARAMS_ARRAY_SIZE, parse_psql_options(), password, pg_fatal, pg_log_error, PG_LOG_FLAG_TERSE, pg_logging_config(), pg_logging_init(), pg_logging_set_locus_callback(), pg_logging_set_pre_callback(), pg_malloc(), pg_strdup(), PG_TEXTDOMAIN, _psqlSettings::popt, options::port, PQclear(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQenv2encoding(), PQerrorMessage(), PQfinish(), PQsetNoticeProcessor(), pqsignal(), PQstatus(), PQuser(), PRINT_ALIGNED, printf, process_file(), process_psqlrc(), _psqlSettings::progname, pset, psprintf(), PSQL_CMD_ERROR, PSQL_ECHO_ALL, psql_scan_create(), psql_scan_destroy(), psql_scan_set_passthrough(), psql_scan_setup(), psql_setup_cancel_handler(), PSQLexec(), psqlscan_callbacks, _psqlSettings::queryFout, _psqlSettings::queryFoutPipe, _psqlSettings::quiet, printTableOpt::recordSep, refresh_utf8format(), res, SendQuery(), separator::separator, separator::separator_zero, set_pglocale_pgservice(), setDecimalLocale(), setQFout(), SetVariable(), SetVariableBool(), showVersion(), SIGALRM, SIGCHLD, simple_action_list_append(), simple_prompt(), standard_strings(), printTableOpt::start_table, generate_unaccent_rules::stdout, printTableOpt::stop_table, success, SyncVariables(), printQueryOpt::topt, TRI_DEFAULT, TRI_NO, TRI_YES, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, printTableOpt::unicode_header_linestyle, UNICODE_LINESTYLE_SINGLE, usage(), options::username, SimpleActionListCell::val, values, and _psqlSettings::vars.

◆ on_error_rollback_hook()

static bool on_error_rollback_hook ( const char *  newval)
static

Definition at line 1012 of file startup.c.

1013 {
1014  Assert(newval != NULL); /* else substitute hook messed up */
1015  if (pg_strcasecmp(newval, "interactive") == 0)
1017  else
1018  {
1019  bool on_off;
1020 
1021  if (ParseVariableBool(newval, NULL, &on_off))
1023  else
1024  {
1025  PsqlVarEnumError("ON_ERROR_ROLLBACK", newval, "on, off, interactive");
1026  return false;
1027  }
1028  }
1029  return true;
1030 }
@ PSQL_ERROR_ROLLBACK_INTERACTIVE
Definition: settings.h:53
@ PSQL_ERROR_ROLLBACK_ON
Definition: settings.h:54
@ PSQL_ERROR_ROLLBACK_OFF
Definition: settings.h:52
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:144

References Assert(), newval, _psqlSettings::on_error_rollback, ParseVariableBool(), pg_strcasecmp(), pset, PSQL_ERROR_ROLLBACK_INTERACTIVE, PSQL_ERROR_ROLLBACK_OFF, PSQL_ERROR_ROLLBACK_ON, and PsqlVarEnumError().

Referenced by EstablishVariableSpace().

◆ on_error_stop_hook()

static bool on_error_stop_hook ( const char *  newval)
static

Definition at line 874 of file startup.c.

875 {
876  return ParseVariableBool(newval, "ON_ERROR_STOP", &pset.on_error_stop);
877 }

References newval, _psqlSettings::on_error_stop, ParseVariableBool(), and pset.

Referenced by EstablishVariableSpace().

◆ parse_psql_options()

static void parse_psql_options ( int  argc,
char *  argv[],
struct adhoc_opts options 
)
static

Definition at line 476 of file startup.c.

477 {
478  static struct option long_options[] =
479  {
480  {"echo-all", no_argument, NULL, 'a'},
481  {"no-align", no_argument, NULL, 'A'},
482  {"command", required_argument, NULL, 'c'},
483  {"dbname", required_argument, NULL, 'd'},
484  {"echo-queries", no_argument, NULL, 'e'},
485  {"echo-errors", no_argument, NULL, 'b'},
486  {"echo-hidden", no_argument, NULL, 'E'},
487  {"file", required_argument, NULL, 'f'},
488  {"field-separator", required_argument, NULL, 'F'},
489  {"field-separator-zero", no_argument, NULL, 'z'},
490  {"host", required_argument, NULL, 'h'},
491  {"html", no_argument, NULL, 'H'},
492  {"list", no_argument, NULL, 'l'},
493  {"log-file", required_argument, NULL, 'L'},
494  {"no-readline", no_argument, NULL, 'n'},
495  {"single-transaction", no_argument, NULL, '1'},
496  {"output", required_argument, NULL, 'o'},
497  {"port", required_argument, NULL, 'p'},
498  {"pset", required_argument, NULL, 'P'},
499  {"quiet", no_argument, NULL, 'q'},
500  {"record-separator", required_argument, NULL, 'R'},
501  {"record-separator-zero", no_argument, NULL, '0'},
502  {"single-step", no_argument, NULL, 's'},
503  {"single-line", no_argument, NULL, 'S'},
504  {"tuples-only", no_argument, NULL, 't'},
505  {"table-attr", required_argument, NULL, 'T'},
506  {"username", required_argument, NULL, 'U'},
507  {"set", required_argument, NULL, 'v'},
508  {"variable", required_argument, NULL, 'v'},
509  {"version", no_argument, NULL, 'V'},
510  {"no-password", no_argument, NULL, 'w'},
511  {"password", no_argument, NULL, 'W'},
512  {"expanded", no_argument, NULL, 'x'},
513  {"no-psqlrc", no_argument, NULL, 'X'},
514  {"help", optional_argument, NULL, 1},
515  {"csv", no_argument, NULL, 2},
516  {NULL, 0, NULL, 0}
517  };
518 
519  int optindex;
520  int c;
521 
522  memset(options, 0, sizeof *options);
523 
524  while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
525  long_options, &optindex)) != -1)
526  {
527  switch (c)
528  {
529  case 'a':
530  SetVariable(pset.vars, "ECHO", "all");
531  break;
532  case 'A':
534  break;
535  case 'b':
536  SetVariable(pset.vars, "ECHO", "errors");
537  break;
538  case 'c':
539  if (optarg[0] == '\\')
542  optarg + 1);
543  else
546  optarg);
547  break;
548  case 'd':
550  break;
551  case 'e':
552  SetVariable(pset.vars, "ECHO", "queries");
553  break;
554  case 'E':
555  SetVariableBool(pset.vars, "ECHO_HIDDEN");
556  break;
557  case 'f':
559  ACT_FILE,
560  optarg);
561  break;
562  case 'F':
565  break;
566  case 'h':
567  options->host = pg_strdup(optarg);
568  break;
569  case 'H':
571  break;
572  case 'l':
573  options->list_dbs = true;
574  break;
575  case 'L':
576  options->logfilename = pg_strdup(optarg);
577  break;
578  case 'n':
579  options->no_readline = true;
580  break;
581  case 'o':
582  if (!setQFout(optarg))
584  break;
585  case 'p':
587  break;
588  case 'P':
589  {
590  char *value;
591  char *equal_loc;
592  bool result;
593 
595  equal_loc = strchr(value, '=');
596  if (!equal_loc)
597  result = do_pset(value, NULL, &pset.popt, true);
598  else
599  {
600  *equal_loc = '\0';
601  result = do_pset(value, equal_loc + 1, &pset.popt, true);
602  }
603 
604  if (!result)
605  pg_fatal("could not set printing parameter \"%s\"", value);
606 
607  free(value);
608  break;
609  }
610  case 'q':
611  SetVariableBool(pset.vars, "QUIET");
612  break;
613  case 'R':
616  break;
617  case 's':
618  SetVariableBool(pset.vars, "SINGLESTEP");
619  break;
620  case 'S':
621  SetVariableBool(pset.vars, "SINGLELINE");
622  break;
623  case 't':
624  pset.popt.topt.tuples_only = true;
625  break;
626  case 'T':
628  break;
629  case 'U':
631  break;
632  case 'v':
633  {
634  char *value;
635  char *equal_loc;
636 
638  equal_loc = strchr(value, '=');
639  if (!equal_loc)
640  {
641  if (!DeleteVariable(pset.vars, value))
642  exit(EXIT_FAILURE); /* error already printed */
643  }
644  else
645  {
646  *equal_loc = '\0';
647  if (!SetVariable(pset.vars, value, equal_loc + 1))
648  exit(EXIT_FAILURE); /* error already printed */
649  }
650 
651  free(value);
652  break;
653  }
654  case 'V':
655  showVersion();
657  case 'w':
659  break;
660  case 'W':
662  break;
663  case 'x':
664  pset.popt.topt.expanded = true;
665  break;
666  case 'X':
667  options->no_psqlrc = true;
668  break;
669  case 'z':
671  break;
672  case '0':
674  break;
675  case '1':
676  options->single_txn = true;
677  break;
678  case '?':
679  if (optind <= argc &&
680  strcmp(argv[optind - 1], "-?") == 0)
681  {
682  /* actual help option given */
683  usage(NOPAGER);
685  }
686  else
687  {
688  /* getopt error (unknown option or missing argument) */
689  goto unknown_option;
690  }
691  break;
692  case 1:
693  {
694  if (!optarg || strcmp(optarg, "options") == 0)
695  usage(NOPAGER);
696  else if (optarg && strcmp(optarg, "commands") == 0)
698  else if (optarg && strcmp(optarg, "variables") == 0)
700  else
701  goto unknown_option;
702 
704  }
705  break;
706  case 2:
708  break;
709  default:
710  unknown_option:
711  /* getopt_long already emitted a complaint */
712  pg_log_error_hint("Try \"%s --help\" for more information.",
713  pset.progname);
715  }
716  }
717 
718  /*
719  * if we still have arguments, use it as the database name and username
720  */
721  while (argc - optind >= 1)
722  {
723  if (!options->dbname)
724  options->dbname = argv[optind];
725  else if (!options->username)
726  options->username = argv[optind];
727  else if (!pset.quiet)
728  pg_log_warning("extra command-line argument \"%s\" ignored",
729  argv[optind]);
730 
731  optind++;
732  }
733 }
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4229
@ PRINT_CSV
Definition: print.h:33
@ PRINT_UNALIGNED
Definition: print.h:38
@ PRINT_HTML
Definition: print.h:34
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
#define optional_argument
Definition: getopt_long.h:26
void helpVariables(unsigned short int pager)
Definition: help.c:339
void slashUsage(unsigned short int pager)
Definition: help.c:154
static struct @151 value
#define pg_log_error_hint(...)
Definition: logging.h:112
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define pg_log_warning(...)
Definition: pgfnames.c:24
char * c
unsigned short int expanded
Definition: print.h:102
bool tuples_only
Definition: print.h:110
char * tableAttr
Definition: print.h:121
bool DeleteVariable(VariableSpace space, const char *name)
Definition: variables.c:405

References ACT_FILE, ACT_SINGLE_QUERY, ACT_SINGLE_SLASH, options::dbname, DeleteVariable(), do_pset(), exit(), EXIT_FAILURE, EXIT_SUCCESS, printTableOpt::expanded, printTableOpt::fieldSep, printTableOpt::format, free, getopt_long(), _psqlSettings::getPassword, helpVariables(), no_argument, NOPAGER, optarg, optind, optional_argument, pg_fatal, pg_log_error_hint, pg_log_warning, pg_strdup(), _psqlSettings::popt, options::port, PRINT_CSV, PRINT_HTML, PRINT_UNALIGNED, _psqlSettings::progname, pset, _psqlSettings::quiet, printTableOpt::recordSep, required_argument, separator::separator, separator::separator_zero, setQFout(), SetVariable(), SetVariableBool(), showVersion(), simple_action_list_append(), slashUsage(), printTableOpt::tableAttr, printQueryOpt::topt, TRI_NO, TRI_YES, printTableOpt::tuples_only, usage(), options::username, value, and _psqlSettings::vars.

Referenced by main().

◆ process_psqlrc()

static void process_psqlrc ( char *  argv0)
static

Definition at line 767 of file startup.c.

768 {
769  char home[MAXPGPATH];
770  char rc_file[MAXPGPATH];
771  char my_exec_path[MAXPGPATH];
772  char etc_path[MAXPGPATH];
773  char *envrc = getenv("PSQLRC");
774 
775  if (find_my_exec(argv0, my_exec_path) < 0)
776  pg_fatal("could not find own program executable");
777 
778  get_etc_path(my_exec_path, etc_path);
779 
780  snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
781  process_psqlrc_file(rc_file);
782 
783  if (envrc != NULL && strlen(envrc) > 0)
784  {
785  /* might need to free() this */
786  char *envrc_alloc = pstrdup(envrc);
787 
788  expand_tilde(&envrc_alloc);
789  process_psqlrc_file(envrc_alloc);
790  }
791  else if (get_home_path(home))
792  {
793  snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
794  process_psqlrc_file(rc_file);
795  }
796 }
void expand_tilde(char **filename)
Definition: common.c:2322
#define SYSPSQLRC
Definition: startup.c:35
#define PSQLRC
Definition: startup.c:36
static void process_psqlrc_file(char *filename)
Definition: startup.c:801
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:140
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
char * pstrdup(const char *in)
Definition: mcxt.c:1305
#define MAXPGPATH
static char * argv0
Definition: pg_ctl.c:97
bool get_home_path(char *ret_path)
Definition: path.c:928
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:834
#define snprintf
Definition: port.h:225

References argv0, expand_tilde(), find_my_exec(), get_etc_path(), get_home_path(), MAXPGPATH, my_exec_path, pg_fatal, process_psqlrc_file(), PSQLRC, pstrdup(), snprintf, and SYSPSQLRC.

Referenced by main().

◆ process_psqlrc_file()

static void process_psqlrc_file ( char *  filename)
static

Definition at line 801 of file startup.c.

802 {
803  char *psqlrc_minor,
804  *psqlrc_major;
805 
806 #if defined(WIN32) && (!defined(__MINGW32__))
807 #define R_OK 4
808 #endif
809 
810  psqlrc_minor = psprintf("%s-%s", filename, PG_VERSION);
811  psqlrc_major = psprintf("%s-%s", filename, PG_MAJORVERSION);
812 
813  /* check for minor version first, then major, then no version */
814  if (access(psqlrc_minor, R_OK) == 0)
815  (void) process_file(psqlrc_minor, false);
816  else if (access(psqlrc_major, R_OK) == 0)
817  (void) process_file(psqlrc_major, false);
818  else if (access(filename, R_OK) == 0)
819  (void) process_file(filename, false);
820 
821  free(psqlrc_minor);
822  free(psqlrc_major);
823 }

References filename, free, process_file(), and psprintf().

Referenced by process_psqlrc().

◆ prompt1_hook()

static bool prompt1_hook ( const char *  newval)
static

Definition at line 1091 of file startup.c.

1092 {
1093  pset.prompt1 = newval ? newval : "";
1094  return true;
1095 }
const char * prompt1
Definition: settings.h:147

References newval, _psqlSettings::prompt1, and pset.

Referenced by EstablishVariableSpace().

◆ prompt2_hook()

static bool prompt2_hook ( const char *  newval)
static

Definition at line 1098 of file startup.c.

1099 {
1100  pset.prompt2 = newval ? newval : "";
1101  return true;
1102 }
const char * prompt2
Definition: settings.h:148

References newval, _psqlSettings::prompt2, and pset.

Referenced by EstablishVariableSpace().

◆ prompt3_hook()

static bool prompt3_hook ( const char *  newval)
static

Definition at line 1105 of file startup.c.

1106 {
1107  pset.prompt3 = newval ? newval : "";
1108  return true;
1109 }
const char * prompt3
Definition: settings.h:149

References newval, _psqlSettings::prompt3, and pset.

Referenced by EstablishVariableSpace().

◆ quiet_hook()

static bool quiet_hook ( const char *  newval)
static

Definition at line 880 of file startup.c.

881 {
882  return ParseVariableBool(newval, "QUIET", &pset.quiet);
883 }

References newval, ParseVariableBool(), pset, and _psqlSettings::quiet.

Referenced by EstablishVariableSpace().

◆ show_all_results_hook()

static bool show_all_results_hook ( const char *  newval)
static

Definition at line 1143 of file startup.c.

1144 {
1145  return ParseVariableBool(newval, "SHOW_ALL_RESULTS", &pset.show_all_results);
1146 }
bool show_all_results
Definition: settings.h:151

References newval, ParseVariableBool(), pset, and _psqlSettings::show_all_results.

Referenced by EstablishVariableSpace().

◆ show_context_hook()

static bool show_context_hook ( const char *  newval)
static

Definition at line 1157 of file startup.c.

1158 {
1159  Assert(newval != NULL); /* else substitute hook messed up */
1160  if (pg_strcasecmp(newval, "never") == 0)
1162  else if (pg_strcasecmp(newval, "errors") == 0)
1164  else if (pg_strcasecmp(newval, "always") == 0)
1166  else
1167  {
1168  PsqlVarEnumError("SHOW_CONTEXT", newval, "never, errors, always");
1169  return false;
1170  }
1171 
1172  if (pset.db)
1174  return true;
1175 }
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7047
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:135
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136
PGContextVisibility show_context
Definition: settings.h:152

References Assert(), _psqlSettings::db, newval, pg_strcasecmp(), PQsetErrorContextVisibility(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, PQSHOW_CONTEXT_NEVER, pset, PsqlVarEnumError(), and _psqlSettings::show_context.

Referenced by EstablishVariableSpace().

◆ show_context_substitute_hook()

static char* show_context_substitute_hook ( char *  newval)
static

Definition at line 1149 of file startup.c.

1150 {
1151  if (newval == NULL)
1152  newval = pg_strdup("errors");
1153  return newval;
1154 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

◆ showVersion()

static void showVersion ( void  )
static

Definition at line 832 of file startup.c.

833 {
834  puts("psql (PostgreSQL) " PG_VERSION);
835 }

Referenced by main(), and parse_psql_options().

◆ simple_action_list_append()

static void simple_action_list_append ( SimpleActionList list,
enum _actions  action,
const char *  val 
)
static

Definition at line 741 of file startup.c.

743 {
744  SimpleActionListCell *cell;
745 
747 
748  cell->next = NULL;
749  cell->action = action;
750  if (val)
751  cell->val = pg_strdup(val);
752  else
753  cell->val = NULL;
754 
755  if (list->tail)
756  list->tail->next = cell;
757  else
758  list->head = cell;
759  list->tail = cell;
760 }
long val
Definition: informix.c:664

References generate_unaccent_rules::action, SimpleActionListCell::action, sort-test::list, SimpleActionListCell::next, pg_malloc(), pg_strdup(), SimpleActionListCell::val, and val.

Referenced by main(), and parse_psql_options().

◆ singleline_hook()

static bool singleline_hook ( const char *  newval)
static

Definition at line 886 of file startup.c.

887 {
888  return ParseVariableBool(newval, "SINGLELINE", &pset.singleline);
889 }
bool singleline
Definition: settings.h:135

References newval, ParseVariableBool(), pset, and _psqlSettings::singleline.

Referenced by EstablishVariableSpace().

◆ singlestep_hook()

static bool singlestep_hook ( const char *  newval)
static

Definition at line 892 of file startup.c.

893 {
894  return ParseVariableBool(newval, "SINGLESTEP", &pset.singlestep);
895 }
bool singlestep
Definition: settings.h:136

References newval, ParseVariableBool(), pset, and _psqlSettings::singlestep.

Referenced by EstablishVariableSpace().

◆ verbosity_hook()

static bool verbosity_hook ( const char *  newval)
static

Definition at line 1120 of file startup.c.

1121 {
1122  Assert(newval != NULL); /* else substitute hook messed up */
1123  if (pg_strcasecmp(newval, "default") == 0)
1125  else if (pg_strcasecmp(newval, "verbose") == 0)
1127  else if (pg_strcasecmp(newval, "terse") == 0)
1129  else if (pg_strcasecmp(newval, "sqlstate") == 0)
1131  else
1132  {
1133  PsqlVarEnumError("VERBOSITY", newval, "default, verbose, terse, sqlstate");
1134  return false;
1135  }
1136 
1137  if (pset.db)
1139  return true;
1140 }
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7035
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:128
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130
PGVerbosity verbosity
Definition: settings.h:150

References Assert(), _psqlSettings::db, newval, pg_strcasecmp(), PQERRORS_DEFAULT, PQERRORS_SQLSTATE, PQERRORS_TERSE, PQERRORS_VERBOSE, PQsetErrorVerbosity(), pset, PsqlVarEnumError(), and _psqlSettings::verbosity.

Referenced by EstablishVariableSpace().

◆ verbosity_substitute_hook()

static char* verbosity_substitute_hook ( char *  newval)
static

Definition at line 1112 of file startup.c.

1113 {
1114  if (newval == NULL)
1115  newval = pg_strdup("default");
1116  return newval;
1117 }

References newval, and pg_strdup().

Referenced by EstablishVariableSpace().

Variable Documentation

◆ pset

Definition at line 32 of file startup.c.

Referenced by AcceptResult(), autocommit_hook(), CheckConnection(), ClearOrSaveAllResults(), ClearOrSaveResult(), command_no_begin(), comp_keyword_case_hook(), connection_warnings(), ConnectionUp(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_connect(), do_copy(), do_lo_export(), do_lo_import(), do_lo_unlink(), do_pset(), do_watch(), echo_hidden_command(), echo_hidden_hook(), echo_hook(), EstablishVariableSpace(), exec_command(), exec_command_a(), exec_command_C(), exec_command_conninfo(), exec_command_crosstabview(), exec_command_echo(), exec_command_encoding(), 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_password(), exec_command_print(), exec_command_prompt(), exec_command_pset(), exec_command_reset(), exec_command_s(), exec_command_set(), exec_command_sf_sv(), exec_command_slash_command_help(), exec_command_t(), exec_command_T(), exec_command_timing(), exec_command_unset(), exec_command_x(), ExecQueryAndProcessResults(), ExecQueryTuples(), ExecQueryUsingCursor(), fail_lo_xact(), fetch_count_hook(), finish_lo_xact(), finishInput(), get_create_object_cmd(), get_prompt(), handleCopyIn(), HandleCopyResult(), HandleSlashCmds(), helpSQL(), helpVariables(), hide_compression_hook(), hide_tableam_hook(), histcontrol_hook(), histsize_hook(), ignoreeof_hook(), indexOfColumn(), initializeInput(), is_select_command(), is_superuser(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), log_locus_callback(), log_pre_callback(), lookup_object_oid(), main(), MainLoop(), objectDescription(), on_error_rollback_hook(), on_error_stop_hook(), parse_psql_options(), parse_slash_copy(), permissionsList(), pg_send_history(), print_lo_result(), printCrosstab(), printGSSInfo(), printHistory(), PrintNotifications(), PrintQueryResult(), PrintQueryStatus(), PrintQueryTuples(), PrintResultInCrosstab(), printSSLInfo(), process_command_g_options(), process_file(), prompt1_hook(), prompt2_hook(), prompt3_hook(), psql_get_variable(), PSQLexec(), PSQLexecWatch(), quiet_hook(), SendQuery(), session_username(), setQFout(), SetResultVariables(), show_all_results_hook(), show_context_hook(), singleline_hook(), singlestep_hook(), skip_white_space(), slashUsage(), standard_strings(), start_lo_xact(), StoreQueryTuple(), SyncVariables(), UnsyncVariables(), usage(), validateSQLNamePattern(), and verbosity_hook().