PostgreSQL Source Code  git master
common.h File Reference
#include <setjmp.h>
#include "fe_utils/print.h"
#include "fe_utils/psqlscan.h"
#include "libpq-fe.h"
Include dependency graph for common.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

bool openQueryOutputFile (const char *fname, FILE **fout, bool *is_pipe)
 
bool setQFout (const char *fname)
 
char * psql_get_variable (const char *varname, PsqlScanQuoteType quote, void *passthrough)
 
void NoticeProcessor (void *arg, const char *message)
 
void psql_setup_cancel_handler (void)
 
PGresultPSQLexec (const char *query)
 
int PSQLexecWatch (const char *query, const printQueryOpt *opt)
 
bool SendQuery (const char *query)
 
bool is_superuser (void)
 
bool standard_strings (void)
 
const char * session_username (void)
 
void expand_tilde (char **filename)
 
bool recognized_connection_string (const char *connstr)
 

Variables

volatile bool sigint_interrupt_enabled
 
sigjmp_buf sigint_interrupt_jmp
 

Function Documentation

◆ expand_tilde()

void expand_tilde ( char **  filename)

Definition at line 2218 of file common.c.

References filename, fn(), free, get_home_path(), MAXPGPATH, psprintf(), and strlcpy().

Referenced by exec_command_edit(), exec_command_g(), exec_command_include(), exec_command_lo(), exec_command_out(), exec_command_s(), exec_command_write(), initializeInput(), parse_slash_copy(), and process_psqlrc().

2219 {
2220  if (!filename || !(*filename))
2221  return;
2222 
2223  /*
2224  * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2225  * for short versions of long file names, though the tilde is usually
2226  * toward the end, not at the beginning.
2227  */
2228 #ifndef WIN32
2229 
2230  /* try tilde expansion */
2231  if (**filename == '~')
2232  {
2233  char *fn;
2234  char oldp,
2235  *p;
2236  struct passwd *pw;
2237  char home[MAXPGPATH];
2238 
2239  fn = *filename;
2240  *home = '\0';
2241 
2242  p = fn + 1;
2243  while (*p != '/' && *p != '\0')
2244  p++;
2245 
2246  oldp = *p;
2247  *p = '\0';
2248 
2249  if (*(fn + 1) == '\0')
2250  get_home_path(home); /* ~ or ~/ only */
2251  else if ((pw = getpwnam(fn + 1)) != NULL)
2252  strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2253 
2254  *p = oldp;
2255  if (strlen(home) != 0)
2256  {
2257  char *newfn;
2258 
2259  newfn = psprintf("%s%s", home, p);
2260  free(fn);
2261  *filename = newfn;
2262  }
2263  }
2264 #endif
2265 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define MAXPGPATH
static void * fn(void *arg)
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static char * filename
Definition: pg_dumpall.c:91
bool get_home_path(char *ret_path)
Definition: path.c:807

◆ is_superuser()

bool is_superuser ( void  )

Definition at line 2150 of file common.c.

References _psqlSettings::db, PQparameterStatus(), pset, and val.

2151 {
2152  const char *val;
2153 
2154  if (!pset.db)
2155  return false;
2156 
2157  val = PQparameterStatus(pset.db, "is_superuser");
2158 
2159  if (val && strcmp(val, "on") == 0)
2160  return true;
2161 
2162  return false;
2163 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6631
long val
Definition: informix.c:664

◆ NoticeProcessor()

void NoticeProcessor ( void *  arg,
const char *  message 
)

Definition at line 220 of file common.c.

References pg_log_info.

Referenced by do_connect(), and main().

221 {
222  (void) arg; /* not used */
223  pg_log_info("%s", message);
224 }
void * arg
#define pg_log_info(...)
Definition: logging.h:88

◆ openQueryOutputFile()

bool openQueryOutputFile ( const char *  fname,
FILE **  fout,
bool is_pipe 
)

Definition at line 50 of file common.c.

References pg_log_error, and generate_unaccent_rules::stdout.

Referenced by ExecQueryUsingCursor(), PrintQueryTuples(), ProcessResult(), and setQFout().

51 {
52  if (!fname || fname[0] == '\0')
53  {
54  *fout = stdout;
55  *is_pipe = false;
56  }
57  else if (*fname == '|')
58  {
59  *fout = popen(fname + 1, "w");
60  *is_pipe = true;
61  }
62  else
63  {
64  *fout = fopen(fname, "w");
65  *is_pipe = false;
66  }
67 
68  if (*fout == NULL)
69  {
70  pg_log_error("%s: %m", fname);
71  return false;
72  }
73 
74  return true;
75 }
#define pg_log_error(...)
Definition: logging.h:80

◆ psql_get_variable()

char* psql_get_variable ( const char *  varname,
PsqlScanQuoteType  quote,
void *  passthrough 
)

Definition at line 129 of file common.c.

References appendShellStringNoError(), buf, conditional_active(), PQExpBufferData::data, _psqlSettings::db, error(), free, GetVariable(), initPQExpBuffer(), pg_log_error, pg_log_info, pg_strdup(), PQerrorMessage(), PQescapeIdentifier(), PQescapeLiteral(), PQfreemem(), PQUOTE_PLAIN, PQUOTE_SHELL_ARG, PQUOTE_SQL_IDENT, PQUOTE_SQL_LITERAL, pset, value, and _psqlSettings::vars.

131 {
132  char *result = NULL;
133  const char *value;
134 
135  /* In an inactive \if branch, suppress all variable substitutions */
136  if (passthrough && !conditional_active((ConditionalStack) passthrough))
137  return NULL;
138 
139  value = GetVariable(pset.vars, varname);
140  if (!value)
141  return NULL;
142 
143  switch (quote)
144  {
145  case PQUOTE_PLAIN:
146  result = pg_strdup(value);
147  break;
148  case PQUOTE_SQL_LITERAL:
149  case PQUOTE_SQL_IDENT:
150  {
151  /*
152  * For these cases, we use libpq's quoting functions, which
153  * assume the string is in the connection's client encoding.
154  */
155  char *escaped_value;
156 
157  if (!pset.db)
158  {
159  pg_log_error("cannot escape without active connection");
160  return NULL;
161  }
162 
163  if (quote == PQUOTE_SQL_LITERAL)
164  escaped_value =
165  PQescapeLiteral(pset.db, value, strlen(value));
166  else
167  escaped_value =
168  PQescapeIdentifier(pset.db, value, strlen(value));
169 
170  if (escaped_value == NULL)
171  {
172  const char *error = PQerrorMessage(pset.db);
173 
174  pg_log_info("%s", error);
175  return NULL;
176  }
177 
178  /*
179  * Rather than complicate the lexer's API with a notion of
180  * which free() routine to use, just pay the price of an extra
181  * strdup().
182  */
183  result = pg_strdup(escaped_value);
184  PQfreemem(escaped_value);
185  break;
186  }
187  case PQUOTE_SHELL_ARG:
188  {
189  /*
190  * For this we use appendShellStringNoError, which is
191  * encoding-agnostic, which is fine since the shell probably
192  * is too. In any case, the only special character is "'",
193  * which is not known to appear in valid multibyte characters.
194  */
196 
197  initPQExpBuffer(&buf);
198  if (!appendShellStringNoError(&buf, value))
199  {
200  pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
201  value);
202  free(buf.data);
203  return NULL;
204  }
205  result = buf.data;
206  break;
207  }
208 
209  /* No default: we want a compiler warning for missing cases */
210  }
211 
212  return result;
213 }
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6666
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
PsqlSettings pset
Definition: startup.c:32
static void error(void)
Definition: sql-dyntest.c:147
#define pg_log_error(...)
Definition: logging.h:80
bool appendShellStringNoError(PQExpBuffer buf, const char *str)
Definition: string_utils.c:441
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3570
static char * buf
Definition: pg_test_fsync.c:67
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
const char * GetVariable(VariableSpace space, const char *name)
Definition: variables.c:71
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3564
static struct @143 value
#define free(a)
Definition: header.h:65
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define pg_log_info(...)
Definition: logging.h:88
VariableSpace vars
Definition: settings.h:118

◆ psql_setup_cancel_handler()

void psql_setup_cancel_handler ( void  )

Definition at line 266 of file common.c.

References psql_cancel_callback(), and setup_cancel_handler().

Referenced by main().

267 {
269 }
static void setup_cancel_handler(void)
Definition: parallel.c:627
static void psql_cancel_callback(void)
Definition: common.c:250

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

Definition at line 536 of file common.c.

References _, AcceptResult(), ClearOrSaveResult(), _psqlSettings::db, _psqlSettings::echo_hidden, fprintf, _psqlSettings::logfile, pg_log_error, PQexec(), printf, pset, PSQL_ECHO_HIDDEN_NOEXEC, PSQL_ECHO_HIDDEN_OFF, ResetCancelConn(), SetCancelConn(), and generate_unaccent_rules::stdout.

Referenced by add_tablespace_footer(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_lo_import(), do_lo_list(), exec_command_password(), fail_lo_xact(), finish_lo_xact(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), main(), objectDescription(), permissionsList(), and start_lo_xact().

537 {
538  PGresult *res;
539 
540  if (!pset.db)
541  {
542  pg_log_error("You are currently not connected to a database.");
543  return NULL;
544  }
545 
547  {
548  printf(_("********* QUERY **********\n"
549  "%s\n"
550  "**************************\n\n"), query);
551  fflush(stdout);
552  if (pset.logfile)
553  {
555  _("********* QUERY **********\n"
556  "%s\n"
557  "**************************\n\n"), query);
558  fflush(pset.logfile);
559  }
560 
562  return NULL;
563  }
564 
566 
567  res = PQexec(pset.db, query);
568 
569  ResetCancelConn();
570 
571  if (!AcceptResult(res))
572  {
573  ClearOrSaveResult(res);
574  res = NULL;
575  }
576 
577  return res;
578 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:451
#define pg_log_error(...)
Definition: logging.h:80
void ResetCancelConn(void)
Definition: cancel.c:100
#define printf(...)
Definition: port.h:199
#define fprintf
Definition: port.h:197
static bool AcceptResult(const PGresult *result)
Definition: common.c:352
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:135
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
FILE * logfile
Definition: settings.h:116
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
#define _(x)
Definition: elog.c:88

◆ PSQLexecWatch()

int PSQLexecWatch ( const char *  query,
const printQueryOpt opt 
)

Definition at line 591 of file common.c.

References AcceptResult(), before(), cancel_pressed, ClearOrSaveResult(), _psqlSettings::db, fprintf, INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, _psqlSettings::logfile, pg_log_error, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQexec(), PQresultStatus(), printQuery(), PrintTiming(), pset, _psqlSettings::queryFout, ResetCancelConn(), SetCancelConn(), _psqlSettings::timing, and printQueryOpt::title.

Referenced by do_watch().

592 {
593  PGresult *res;
594  double elapsed_msec = 0;
596  instr_time after;
597 
598  if (!pset.db)
599  {
600  pg_log_error("You are currently not connected to a database.");
601  return 0;
602  }
603 
605 
606  if (pset.timing)
607  INSTR_TIME_SET_CURRENT(before);
608 
609  res = PQexec(pset.db, query);
610 
611  ResetCancelConn();
612 
613  if (!AcceptResult(res))
614  {
615  ClearOrSaveResult(res);
616  return 0;
617  }
618 
619  if (pset.timing)
620  {
621  INSTR_TIME_SET_CURRENT(after);
622  INSTR_TIME_SUBTRACT(after, before);
623  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
624  }
625 
626  /*
627  * If SIGINT is sent while the query is processing, the interrupt will be
628  * consumed. The user's intention, though, is to cancel the entire watch
629  * process, so detect a sent cancellation request and exit in this case.
630  */
631  if (cancel_pressed)
632  {
633  PQclear(res);
634  return 0;
635  }
636 
637  switch (PQresultStatus(res))
638  {
639  case PGRES_TUPLES_OK:
640  printQuery(res, opt, pset.queryFout, false, pset.logfile);
641  break;
642 
643  case PGRES_COMMAND_OK:
644  fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
645  break;
646 
647  case PGRES_EMPTY_QUERY:
648  pg_log_error("\\watch cannot be used with an empty query");
649  PQclear(res);
650  return -1;
651 
652  case PGRES_COPY_OUT:
653  case PGRES_COPY_IN:
654  case PGRES_COPY_BOTH:
655  pg_log_error("\\watch cannot be used with COPY");
656  PQclear(res);
657  return -1;
658 
659  default:
660  pg_log_error("unexpected result status for \\watch");
661  PQclear(res);
662  return -1;
663  }
664 
665  PQclear(res);
666 
667  fflush(pset.queryFout);
668 
669  /* Possible microtiming output */
670  if (pset.timing)
671  PrintTiming(elapsed_msec);
672 
673  return 1;
674 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:451
#define pg_log_error(...)
Definition: logging.h:80
void ResetCancelConn(void)
Definition: cancel.c:100
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:202
struct timeval instr_time
Definition: instr_time.h:150
static void PrintTiming(double elapsed_msec)
Definition: common.c:477
FILE * queryFout
Definition: settings.h:84
#define fprintf
Definition: port.h:197
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static bool AcceptResult(const PGresult *result)
Definition: common.c:352
static int before(chr x, chr y)
Definition: regc_locale.c:496
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3040
FILE * logfile
Definition: settings.h:116
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
void PQclear(PGresult *res)
Definition: fe-exec.c:694
char * title
Definition: print.h:171
void printQuery(const PGresult *result, const printQueryOpt *opt, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3417
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939

◆ recognized_connection_string()

bool recognized_connection_string ( const char *  connstr)

Definition at line 2303 of file common.c.

References uri_prefix_length().

Referenced by do_connect().

2304 {
2305  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2306 }
static int uri_prefix_length(const char *connstr)
Definition: common.c:2276
static char * connstr
Definition: pg_dumpall.c:62

◆ SendQuery()

bool SendQuery ( const char *  query)

Definition at line 1179 of file common.c.

References _, _psqlSettings::autocommit, before(), buf, cancel_pressed, ClearOrSaveResult(), command_no_begin(), ConnectionUp(), _psqlSettings::crosstab_flag, _psqlSettings::ctv_args, _psqlSettings::cur_cmd_interactive, _psqlSettings::db, DescribeQuery(), _psqlSettings::echo, _psqlSettings::encoding, printTableOpt::encoding, ExecQueryUsingCursor(), _psqlSettings::fetch_count, formatPGVersionNumber(), fprintf, free, _psqlSettings::gdesc_flag, _psqlSettings::gexec_flag, _psqlSettings::gfname, _psqlSettings::gsavepopt, _psqlSettings::gset_prefix, i, INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, is_select_command(), lengthof, _psqlSettings::logfile, _psqlSettings::on_error_rollback, pg_encoding_to_char(), pg_free(), pg_log_error, pg_log_info, pg_log_warning, PGRES_COMMAND_OK, _psqlSettings::popt, PQclear(), PQclientEncoding(), PQcmdStatus(), PQerrorMessage(), PQexec(), PQresultStatus(), PQTRANS_ACTIVE, PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, PQtransactionStatus(), printf, PrintNotifications(), PrintQueryResults(), PrintTiming(), ProcessResult(), pset, PSQL_ECHO_ERRORS, PSQL_ECHO_QUERIES, PSQL_ERROR_ROLLBACK_OFF, PSQL_ERROR_ROLLBACK_ON, ResetCancelConn(), restorePsetInfo(), SetCancelConn(), SetVariable(), _psqlSettings::singlestep, generate_unaccent_rules::stdout, _psqlSettings::sversion, _psqlSettings::timing, printQueryOpt::topt, and _psqlSettings::vars.

Referenced by do_copy(), ExecQueryTuples(), main(), and MainLoop().

1180 {
1181  PGresult *results;
1182  PGTransactionStatusType transaction_status;
1183  double elapsed_msec = 0;
1184  bool OK = false;
1185  int i;
1186  bool on_error_rollback_savepoint = false;
1187  static bool on_error_rollback_warning = false;
1188 
1189  if (!pset.db)
1190  {
1191  pg_log_error("You are currently not connected to a database.");
1192  goto sendquery_cleanup;
1193  }
1194 
1195  if (pset.singlestep)
1196  {
1197  char buf[3];
1198 
1199  fflush(stderr);
1200  printf(_("***(Single step mode: verify command)*******************************************\n"
1201  "%s\n"
1202  "***(press return to proceed or enter x and return to cancel)********************\n"),
1203  query);
1204  fflush(stdout);
1205  if (fgets(buf, sizeof(buf), stdin) != NULL)
1206  if (buf[0] == 'x')
1207  goto sendquery_cleanup;
1208  if (cancel_pressed)
1209  goto sendquery_cleanup;
1210  }
1211  else if (pset.echo == PSQL_ECHO_QUERIES)
1212  {
1213  puts(query);
1214  fflush(stdout);
1215  }
1216 
1217  if (pset.logfile)
1218  {
1220  _("********* QUERY **********\n"
1221  "%s\n"
1222  "**************************\n\n"), query);
1223  fflush(pset.logfile);
1224  }
1225 
1227 
1228  transaction_status = PQtransactionStatus(pset.db);
1229 
1230  if (transaction_status == PQTRANS_IDLE &&
1231  !pset.autocommit &&
1232  !command_no_begin(query))
1233  {
1234  results = PQexec(pset.db, "BEGIN");
1235  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1236  {
1238  ClearOrSaveResult(results);
1239  ResetCancelConn();
1240  goto sendquery_cleanup;
1241  }
1242  ClearOrSaveResult(results);
1243  transaction_status = PQtransactionStatus(pset.db);
1244  }
1245 
1246  if (transaction_status == PQTRANS_INTRANS &&
1250  {
1251  if (on_error_rollback_warning == false && pset.sversion < 80000)
1252  {
1253  char sverbuf[32];
1254 
1255  pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1257  sverbuf, sizeof(sverbuf)));
1258  on_error_rollback_warning = true;
1259  }
1260  else
1261  {
1262  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1263  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1264  {
1266  ClearOrSaveResult(results);
1267  ResetCancelConn();
1268  goto sendquery_cleanup;
1269  }
1270  ClearOrSaveResult(results);
1271  on_error_rollback_savepoint = true;
1272  }
1273  }
1274 
1275  if (pset.gdesc_flag)
1276  {
1277  /* Describe query's result columns, without executing it */
1278  OK = DescribeQuery(query, &elapsed_msec);
1279  ResetCancelConn();
1280  results = NULL; /* PQclear(NULL) does nothing */
1281  }
1282  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1284  {
1285  /* Default fetch-it-all-and-print mode */
1287  after;
1288 
1289  if (pset.timing)
1290  INSTR_TIME_SET_CURRENT(before);
1291 
1292  results = PQexec(pset.db, query);
1293 
1294  /* these operations are included in the timing result: */
1295  ResetCancelConn();
1296  OK = ProcessResult(&results);
1297 
1298  if (pset.timing)
1299  {
1300  INSTR_TIME_SET_CURRENT(after);
1301  INSTR_TIME_SUBTRACT(after, before);
1302  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1303  }
1304 
1305  /* but printing results isn't: */
1306  if (OK && results)
1307  OK = PrintQueryResults(results);
1308  }
1309  else
1310  {
1311  /* Fetch-in-segments mode */
1312  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1313  ResetCancelConn();
1314  results = NULL; /* PQclear(NULL) does nothing */
1315  }
1316 
1317  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1318  pg_log_info("STATEMENT: %s", query);
1319 
1320  /* If we made a temporary savepoint, possibly release/rollback */
1321  if (on_error_rollback_savepoint)
1322  {
1323  const char *svptcmd = NULL;
1324 
1325  transaction_status = PQtransactionStatus(pset.db);
1326 
1327  switch (transaction_status)
1328  {
1329  case PQTRANS_INERROR:
1330  /* We always rollback on an error */
1331  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1332  break;
1333 
1334  case PQTRANS_IDLE:
1335  /* If they are no longer in a transaction, then do nothing */
1336  break;
1337 
1338  case PQTRANS_INTRANS:
1339 
1340  /*
1341  * Do nothing if they are messing with savepoints themselves:
1342  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1343  * If they issued a SAVEPOINT, releasing ours would remove
1344  * theirs.
1345  */
1346  if (results &&
1347  (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1348  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1349  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1350  svptcmd = NULL;
1351  else
1352  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1353  break;
1354 
1355  case PQTRANS_ACTIVE:
1356  case PQTRANS_UNKNOWN:
1357  default:
1358  OK = false;
1359  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1360  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1361  pg_log_error("unexpected transaction status (%d)",
1362  transaction_status);
1363  break;
1364  }
1365 
1366  if (svptcmd)
1367  {
1368  PGresult *svptres;
1369 
1370  svptres = PQexec(pset.db, svptcmd);
1371  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1372  {
1374  ClearOrSaveResult(svptres);
1375  OK = false;
1376 
1377  PQclear(results);
1378  ResetCancelConn();
1379  goto sendquery_cleanup;
1380  }
1381  PQclear(svptres);
1382  }
1383  }
1384 
1385  ClearOrSaveResult(results);
1386 
1387  /* Possible microtiming output */
1388  if (pset.timing)
1389  PrintTiming(elapsed_msec);
1390 
1391  /* check for events that may occur during query execution */
1392 
1393  if (pset.encoding != PQclientEncoding(pset.db) &&
1394  PQclientEncoding(pset.db) >= 0)
1395  {
1396  /* track effects of SET CLIENT_ENCODING */
1399  SetVariable(pset.vars, "ENCODING",
1401  }
1402 
1404 
1405  /* perform cleanup that should occur after any attempted query */
1406 
1407 sendquery_cleanup:
1408 
1409  /* reset \g's output-to-filename trigger */
1410  if (pset.gfname)
1411  {
1412  free(pset.gfname);
1413  pset.gfname = NULL;
1414  }
1415 
1416  /* restore print settings if \g changed them */
1417  if (pset.gsavepopt)
1418  {
1420  pset.gsavepopt = NULL;
1421  }
1422 
1423  /* reset \gset trigger */
1424  if (pset.gset_prefix)
1425  {
1427  pset.gset_prefix = NULL;
1428  }
1429 
1430  /* reset \gdesc trigger */
1431  pset.gdesc_flag = false;
1432 
1433  /* reset \gexec trigger */
1434  pset.gexec_flag = false;
1435 
1436  /* reset \crosstabview trigger */
1437  pset.crosstab_flag = false;
1438  for (i = 0; i < lengthof(pset.ctv_args); i++)
1439  {
1440  pg_free(pset.ctv_args[i]);
1441  pset.ctv_args[i] = NULL;
1442  }
1443 
1444  return OK;
1445 }
PSQL_ECHO echo
Definition: settings.h:134
bool singlestep
Definition: settings.h:129
char * gset_prefix
Definition: settings.h:96
static bool PrintQueryResults(PGresult *results)
Definition: common.c:1104
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6666
int encoding
Definition: print.h:122
PsqlSettings pset
Definition: startup.c:32
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:451
#define pg_log_error(...)
Definition: logging.h:80
void ResetCancelConn(void)
Definition: cancel.c:100
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:202
struct timeval instr_time
Definition: instr_time.h:150
bool gexec_flag
Definition: settings.h:98
printTableOpt topt
Definition: print.h:169
static void PrintTiming(double elapsed_msec)
Definition: common.c:477
printQueryOpt * gsavepopt
Definition: settings.h:94
#define printf(...)
Definition: port.h:199
static bool ConnectionUp(void)
Definition: common.c:277
bool autocommit
Definition: settings.h:125
#define lengthof(array)
Definition: c.h:675
#define fprintf
Definition: port.h:197
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:136
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6726
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static void PrintNotifications(void)
Definition: common.c:681
char * ctv_args[4]
Definition: settings.h:100
static int before(chr x, chr y)
Definition: regc_locale.c:496
bool cur_cmd_interactive
Definition: settings.h:107
static bool is_select_command(const char *query)
Definition: common.c:2110
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:4458
bool gdesc_flag
Definition: settings.h:97
static char * buf
Definition: pg_test_fsync.c:67
int fetch_count
Definition: settings.h:131
static bool ProcessResult(PGresult **results)
Definition: common.c:899
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1573
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6621
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1457
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3040
char * gfname
Definition: settings.h:93
FILE * logfile
Definition: settings.h:116
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define free(a)
Definition: header.h:65
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
PGTransactionStatusType
Definition: libpq-fe.h:103
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
printQueryOpt popt
Definition: settings.h:91
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
int i
bool crosstab_flag
Definition: settings.h:99
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
#define pg_log_warning(...)
Definition: pgfnames.c:24
int encoding
Definition: settings.h:83
static bool command_no_begin(const char *query)
Definition: common.c:1895
#define _(x)
Definition: elog.c:88
#define pg_log_info(...)
Definition: logging.h:88
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177
VariableSpace vars
Definition: settings.h:118

◆ session_username()

const char* session_username ( void  )

Definition at line 2197 of file common.c.

References _psqlSettings::db, PQparameterStatus(), PQuser(), pset, and val.

Referenced by get_prompt().

2198 {
2199  const char *val;
2200 
2201  if (!pset.db)
2202  return NULL;
2203 
2204  val = PQparameterStatus(pset.db, "session_authorization");
2205  if (val)
2206  return val;
2207  else
2208  return PQuser(pset.db);
2209 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6631
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6524
long val
Definition: informix.c:664

◆ setQFout()

bool setQFout ( const char *  fname)

Definition at line 85 of file common.c.

References openQueryOutputFile(), pset, _psqlSettings::queryFout, _psqlSettings::queryFoutPipe, restore_sigpipe_trap(), set_sigpipe_trap_state(), and generate_unaccent_rules::stdout.

Referenced by exec_command_out(), main(), and parse_psql_options().

86 {
87  FILE *fout;
88  bool is_pipe;
89 
90  /* First make sure we can open the new output file/pipe */
91  if (!openQueryOutputFile(fname, &fout, &is_pipe))
92  return false;
93 
94  /* Close old file/pipe */
95  if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
96  {
97  if (pset.queryFoutPipe)
98  pclose(pset.queryFout);
99  else
100  fclose(pset.queryFout);
101  }
102 
103  pset.queryFout = fout;
104  pset.queryFoutPipe = is_pipe;
105 
106  /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
107  set_sigpipe_trap_state(is_pipe);
109 
110  return true;
111 }
PsqlSettings pset
Definition: startup.c:32
bool queryFoutPipe
Definition: settings.h:85
FILE * queryFout
Definition: settings.h:84
void set_sigpipe_trap_state(bool ignore)
Definition: print.c:2961
void restore_sigpipe_trap(void)
Definition: print.c:2948
bool openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
Definition: common.c:50

◆ standard_strings()

bool standard_strings ( void  )

Definition at line 2173 of file common.c.

References _psqlSettings::db, PQparameterStatus(), pset, and val.

Referenced by get_create_object_cmd(), main(), MainLoop(), and parse_slash_copy().

2174 {
2175  const char *val;
2176 
2177  if (!pset.db)
2178  return false;
2179 
2180  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2181 
2182  if (val && strcmp(val, "on") == 0)
2183  return true;
2184 
2185  return false;
2186 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6631
long val
Definition: informix.c:664

Variable Documentation

◆ sigint_interrupt_enabled

volatile bool sigint_interrupt_enabled

◆ sigint_interrupt_jmp

sigjmp_buf sigint_interrupt_jmp

Definition at line 247 of file common.c.

Referenced by do_watch(), handleCopyIn(), MainLoop(), and psql_cancel_callback().