PostgreSQL Source Code  git master
common.h File Reference
#include <setjmp.h>
#include "libpq-fe.h"
#include "fe_utils/print.h"
#include "fe_utils/psqlscan.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 setup_cancel_handler (void)
 
void SetCancelConn (void)
 
void ResetCancelConn (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 2357 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().

2358 {
2359  if (!filename || !(*filename))
2360  return;
2361 
2362  /*
2363  * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2364  * for short versions of long file names, though the tilde is usually
2365  * toward the end, not at the beginning.
2366  */
2367 #ifndef WIN32
2368 
2369  /* try tilde expansion */
2370  if (**filename == '~')
2371  {
2372  char *fn;
2373  char oldp,
2374  *p;
2375  struct passwd *pw;
2376  char home[MAXPGPATH];
2377 
2378  fn = *filename;
2379  *home = '\0';
2380 
2381  p = fn + 1;
2382  while (*p != '/' && *p != '\0')
2383  p++;
2384 
2385  oldp = *p;
2386  *p = '\0';
2387 
2388  if (*(fn + 1) == '\0')
2389  get_home_path(home); /* ~ or ~/ only */
2390  else if ((pw = getpwnam(fn + 1)) != NULL)
2391  strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2392 
2393  *p = oldp;
2394  if (strlen(home) != 0)
2395  {
2396  char *newfn;
2397 
2398  newfn = psprintf("%s%s", home, p);
2399  free(fn);
2400  *filename = newfn;
2401  }
2402  }
2403 #endif
2404 
2405  return;
2406 }
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 2289 of file common.c.

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

2290 {
2291  const char *val;
2292 
2293  if (!pset.db)
2294  return false;
2295 
2296  val = PQparameterStatus(pset.db, "is_superuser");
2297 
2298  if (val && strcmp(val, "on") == 0)
2299  return true;
2300 
2301  return false;
2302 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6561
long val
Definition: informix.c:684

◆ NoticeProcessor()

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

Definition at line 221 of file common.c.

References pg_log_info.

Referenced by do_connect(), and main().

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

◆ openQueryOutputFile()

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

Definition at line 51 of file common.c.

References pg_log_error, and generate_unaccent_rules::stdout.

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

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

◆ psql_get_variable()

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

Definition at line 130 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.

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

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

Definition at line 683 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(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), main(), objectDescription(), permissionsList(), and start_lo_xact().

684 {
685  PGresult *res;
686 
687  if (!pset.db)
688  {
689  pg_log_error("You are currently not connected to a database.");
690  return NULL;
691  }
692 
694  {
695  printf(_("********* QUERY **********\n"
696  "%s\n"
697  "**************************\n\n"), query);
698  fflush(stdout);
699  if (pset.logfile)
700  {
702  _("********* QUERY **********\n"
703  "%s\n"
704  "**************************\n\n"), query);
705  fflush(pset.logfile);
706  }
707 
709  return NULL;
710  }
711 
712  SetCancelConn();
713 
714  res = PQexec(pset.db, query);
715 
716  ResetCancelConn();
717 
718  if (!AcceptResult(res))
719  {
720  ClearOrSaveResult(res);
721  res = NULL;
722  }
723 
724  return res;
725 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:598
#define pg_log_error(...)
Definition: logging.h:79
#define printf(...)
Definition: port.h:198
#define fprintf
Definition: port.h:196
static bool AcceptResult(const PGresult *result)
Definition: common.c:499
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:135
void SetCancelConn(void)
Definition: common.c:439
FILE * logfile
Definition: settings.h:116
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940
void ResetCancelConn(void)
Definition: common.c:469
#define _(x)
Definition: elog.c:84

◆ PSQLexecWatch()

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

Definition at line 738 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().

739 {
740  PGresult *res;
741  double elapsed_msec = 0;
743  instr_time after;
744 
745  if (!pset.db)
746  {
747  pg_log_error("You are currently not connected to a database.");
748  return 0;
749  }
750 
751  SetCancelConn();
752 
753  if (pset.timing)
754  INSTR_TIME_SET_CURRENT(before);
755 
756  res = PQexec(pset.db, query);
757 
758  ResetCancelConn();
759 
760  if (!AcceptResult(res))
761  {
762  ClearOrSaveResult(res);
763  return 0;
764  }
765 
766  if (pset.timing)
767  {
768  INSTR_TIME_SET_CURRENT(after);
769  INSTR_TIME_SUBTRACT(after, before);
770  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
771  }
772 
773  /*
774  * If SIGINT is sent while the query is processing, the interrupt will be
775  * consumed. The user's intention, though, is to cancel the entire watch
776  * process, so detect a sent cancellation request and exit in this case.
777  */
778  if (cancel_pressed)
779  {
780  PQclear(res);
781  return 0;
782  }
783 
784  switch (PQresultStatus(res))
785  {
786  case PGRES_TUPLES_OK:
787  printQuery(res, opt, pset.queryFout, false, pset.logfile);
788  break;
789 
790  case PGRES_COMMAND_OK:
791  fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
792  break;
793 
794  case PGRES_EMPTY_QUERY:
795  pg_log_error("\\watch cannot be used with an empty query");
796  PQclear(res);
797  return -1;
798 
799  case PGRES_COPY_OUT:
800  case PGRES_COPY_IN:
801  case PGRES_COPY_BOTH:
802  pg_log_error("\\watch cannot be used with COPY");
803  PQclear(res);
804  return -1;
805 
806  default:
807  pg_log_error("unexpected result status for \\watch");
808  PQclear(res);
809  return -1;
810  }
811 
812  PQclear(res);
813 
814  fflush(pset.queryFout);
815 
816  /* Possible microtiming output */
817  if (pset.timing)
818  PrintTiming(elapsed_msec);
819 
820  return 1;
821 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:598
#define pg_log_error(...)
Definition: logging.h:79
#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:624
FILE * queryFout
Definition: settings.h:85
#define fprintf
Definition: port.h:196
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
static bool AcceptResult(const PGresult *result)
Definition: common.c:499
volatile bool cancel_pressed
Definition: print.c:46
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(void)
Definition: common.c:439
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3041
FILE * logfile
Definition: settings.h:116
void PQclear(PGresult *res)
Definition: fe-exec.c:695
char * title
Definition: print.h:169
void printQuery(const PGresult *result, const printQueryOpt *opt, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3436
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940
void ResetCancelConn(void)
Definition: common.c:469

◆ recognized_connection_string()

bool recognized_connection_string ( const char *  connstr)

Definition at line 2444 of file common.c.

References uri_prefix_length().

Referenced by do_connect().

2445 {
2446  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2447 }
static int uri_prefix_length(const char *connstr)
Definition: common.c:2417
static char * connstr
Definition: pg_dumpall.c:62

◆ ResetCancelConn()

void ResetCancelConn ( void  )

Definition at line 469 of file common.c.

470 {
471  PGcancel *oldCancelConn;
472 
473 #ifdef WIN32
474  EnterCriticalSection(&cancelConnLock);
475 #endif
476 
477  oldCancelConn = cancelConn;
478  /* be sure handle_sigint doesn't use pointer while freeing */
479  cancelConn = NULL;
480 
481  if (oldCancelConn != NULL)
482  PQfreeCancel(oldCancelConn);
483 
484 #ifdef WIN32
485  LeaveCriticalSection(&cancelConnLock);
486 #endif
487 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4242
static PGcancel *volatile cancelConn
Definition: common.c:257

◆ SendQuery()

bool SendQuery ( const char *  query)

Definition at line 1318 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::g_expanded, _psqlSettings::gdesc_flag, _psqlSettings::gexec_flag, _psqlSettings::gfname, _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(), 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().

1319 {
1320  PGresult *results;
1321  PGTransactionStatusType transaction_status;
1322  double elapsed_msec = 0;
1323  bool OK = false;
1324  int i;
1325  bool on_error_rollback_savepoint = false;
1326  static bool on_error_rollback_warning = false;
1327 
1328  if (!pset.db)
1329  {
1330  pg_log_error("You are currently not connected to a database.");
1331  goto sendquery_cleanup;
1332  }
1333 
1334  if (pset.singlestep)
1335  {
1336  char buf[3];
1337 
1338  fflush(stderr);
1339  printf(_("***(Single step mode: verify command)*******************************************\n"
1340  "%s\n"
1341  "***(press return to proceed or enter x and return to cancel)********************\n"),
1342  query);
1343  fflush(stdout);
1344  if (fgets(buf, sizeof(buf), stdin) != NULL)
1345  if (buf[0] == 'x')
1346  goto sendquery_cleanup;
1347  if (cancel_pressed)
1348  goto sendquery_cleanup;
1349  }
1350  else if (pset.echo == PSQL_ECHO_QUERIES)
1351  {
1352  puts(query);
1353  fflush(stdout);
1354  }
1355 
1356  if (pset.logfile)
1357  {
1359  _("********* QUERY **********\n"
1360  "%s\n"
1361  "**************************\n\n"), query);
1362  fflush(pset.logfile);
1363  }
1364 
1365  SetCancelConn();
1366 
1367  transaction_status = PQtransactionStatus(pset.db);
1368 
1369  if (transaction_status == PQTRANS_IDLE &&
1370  !pset.autocommit &&
1371  !command_no_begin(query))
1372  {
1373  results = PQexec(pset.db, "BEGIN");
1374  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1375  {
1377  ClearOrSaveResult(results);
1378  ResetCancelConn();
1379  goto sendquery_cleanup;
1380  }
1381  ClearOrSaveResult(results);
1382  transaction_status = PQtransactionStatus(pset.db);
1383  }
1384 
1385  if (transaction_status == PQTRANS_INTRANS &&
1389  {
1390  if (on_error_rollback_warning == false && pset.sversion < 80000)
1391  {
1392  char sverbuf[32];
1393 
1394  pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1396  sverbuf, sizeof(sverbuf)));
1397  on_error_rollback_warning = true;
1398  }
1399  else
1400  {
1401  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1402  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1403  {
1405  ClearOrSaveResult(results);
1406  ResetCancelConn();
1407  goto sendquery_cleanup;
1408  }
1409  ClearOrSaveResult(results);
1410  on_error_rollback_savepoint = true;
1411  }
1412  }
1413 
1414  if (pset.gdesc_flag)
1415  {
1416  /* Describe query's result columns, without executing it */
1417  OK = DescribeQuery(query, &elapsed_msec);
1418  ResetCancelConn();
1419  results = NULL; /* PQclear(NULL) does nothing */
1420  }
1421  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1423  {
1424  /* Default fetch-it-all-and-print mode */
1426  after;
1427 
1428  if (pset.timing)
1429  INSTR_TIME_SET_CURRENT(before);
1430 
1431  results = PQexec(pset.db, query);
1432 
1433  /* these operations are included in the timing result: */
1434  ResetCancelConn();
1435  OK = ProcessResult(&results);
1436 
1437  if (pset.timing)
1438  {
1439  INSTR_TIME_SET_CURRENT(after);
1440  INSTR_TIME_SUBTRACT(after, before);
1441  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1442  }
1443 
1444  /* but printing results isn't: */
1445  if (OK && results)
1446  OK = PrintQueryResults(results);
1447  }
1448  else
1449  {
1450  /* Fetch-in-segments mode */
1451  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1452  ResetCancelConn();
1453  results = NULL; /* PQclear(NULL) does nothing */
1454  }
1455 
1456  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1457  pg_log_info("STATEMENT: %s", query);
1458 
1459  /* If we made a temporary savepoint, possibly release/rollback */
1460  if (on_error_rollback_savepoint)
1461  {
1462  const char *svptcmd = NULL;
1463 
1464  transaction_status = PQtransactionStatus(pset.db);
1465 
1466  switch (transaction_status)
1467  {
1468  case PQTRANS_INERROR:
1469  /* We always rollback on an error */
1470  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1471  break;
1472 
1473  case PQTRANS_IDLE:
1474  /* If they are no longer in a transaction, then do nothing */
1475  break;
1476 
1477  case PQTRANS_INTRANS:
1478 
1479  /*
1480  * Do nothing if they are messing with savepoints themselves:
1481  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1482  * If they issued a SAVEPOINT, releasing ours would remove
1483  * theirs.
1484  */
1485  if (results &&
1486  (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1487  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1488  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1489  svptcmd = NULL;
1490  else
1491  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1492  break;
1493 
1494  case PQTRANS_ACTIVE:
1495  case PQTRANS_UNKNOWN:
1496  default:
1497  OK = false;
1498  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1499  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1500  pg_log_error("unexpected transaction status (%d)",
1501  transaction_status);
1502  break;
1503  }
1504 
1505  if (svptcmd)
1506  {
1507  PGresult *svptres;
1508 
1509  svptres = PQexec(pset.db, svptcmd);
1510  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1511  {
1513  ClearOrSaveResult(svptres);
1514  OK = false;
1515 
1516  PQclear(results);
1517  ResetCancelConn();
1518  goto sendquery_cleanup;
1519  }
1520  PQclear(svptres);
1521  }
1522  }
1523 
1524  ClearOrSaveResult(results);
1525 
1526  /* Possible microtiming output */
1527  if (pset.timing)
1528  PrintTiming(elapsed_msec);
1529 
1530  /* check for events that may occur during query execution */
1531 
1532  if (pset.encoding != PQclientEncoding(pset.db) &&
1533  PQclientEncoding(pset.db) >= 0)
1534  {
1535  /* track effects of SET CLIENT_ENCODING */
1538  SetVariable(pset.vars, "ENCODING",
1540  }
1541 
1543 
1544  /* perform cleanup that should occur after any attempted query */
1545 
1546 sendquery_cleanup:
1547 
1548  /* reset \g's output-to-filename trigger */
1549  if (pset.gfname)
1550  {
1551  free(pset.gfname);
1552  pset.gfname = NULL;
1553  }
1554 
1555  /* reset \gx's expanded-mode flag */
1556  pset.g_expanded = false;
1557 
1558  /* reset \gset trigger */
1559  if (pset.gset_prefix)
1560  {
1562  pset.gset_prefix = NULL;
1563  }
1564 
1565  /* reset \gdesc trigger */
1566  pset.gdesc_flag = false;
1567 
1568  /* reset \gexec trigger */
1569  pset.gexec_flag = false;
1570 
1571  /* reset \crosstabview trigger */
1572  pset.crosstab_flag = false;
1573  for (i = 0; i < lengthof(pset.ctv_args); i++)
1574  {
1575  pg_free(pset.ctv_args[i]);
1576  pset.ctv_args[i] = NULL;
1577  }
1578 
1579  return OK;
1580 }
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:1243
PGconn * db
Definition: settings.h:83
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6596
int encoding
Definition: print.h:120
PsqlSettings pset
Definition: startup.c:35
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:598
#define pg_log_error(...)
Definition: logging.h:79
#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:167
static void PrintTiming(double elapsed_msec)
Definition: common.c:624
#define printf(...)
Definition: port.h:198
static bool ConnectionUp(void)
Definition: common.c:368
bool autocommit
Definition: settings.h:125
#define lengthof(array)
Definition: c.h:662
#define fprintf
Definition: port.h:196
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:136
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6656
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
volatile bool cancel_pressed
Definition: print.c:46
static void PrintNotifications(void)
Definition: common.c:828
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:2249
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
bool gdesc_flag
Definition: settings.h:97
static char * buf
Definition: pg_test_fsync.c:68
int fetch_count
Definition: settings.h:131
static bool ProcessResult(PGresult **results)
Definition: common.c:1038
bool g_expanded
Definition: settings.h:95
void SetCancelConn(void)
Definition: common.c:439
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1708
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6551
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1592
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3041
char * gfname
Definition: settings.h:94
FILE * logfile
Definition: settings.h:116
void PQclear(PGresult *res)
Definition: fe-exec.c:695
#define free(a)
Definition: header.h:65
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:607
PGTransactionStatusType
Definition: libpq-fe.h:103
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:213
printQueryOpt popt
Definition: settings.h:92
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:1940
#define pg_log_warning(...)
Definition: pgfnames.c:24
int encoding
Definition: settings.h:84
static bool command_no_begin(const char *query)
Definition: common.c:2034
void ResetCancelConn(void)
Definition: common.c:469
#define _(x)
Definition: elog.c:84
#define pg_log_info(...)
Definition: logging.h:87
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:179
VariableSpace vars
Definition: settings.h:118

◆ session_username()

const char* session_username ( void  )

Definition at line 2336 of file common.c.

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

Referenced by get_prompt().

2337 {
2338  const char *val;
2339 
2340  if (!pset.db)
2341  return NULL;
2342 
2343  val = PQparameterStatus(pset.db, "session_authorization");
2344  if (val)
2345  return val;
2346  else
2347  return PQuser(pset.db);
2348 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6561
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6454
long val
Definition: informix.c:684

◆ SetCancelConn()

void SetCancelConn ( void  )

Definition at line 439 of file common.c.

References cancelConn, _psqlSettings::db, PQfreeCancel(), PQgetCancel(), and pset.

Referenced by consumeQueryResult(), do_lo_export(), do_lo_import(), do_lo_unlink(), executeMaintenanceCommand(), ParallelSlotsGetIdle(), ProcessResult(), PSQLexec(), PSQLexecWatch(), and SendQuery().

440 {
441  PGcancel *oldCancelConn;
442 
443 #ifdef WIN32
444  EnterCriticalSection(&cancelConnLock);
445 #endif
446 
447  /* Free the old one if we have one */
448  oldCancelConn = cancelConn;
449  /* be sure handle_sigint doesn't use pointer while freeing */
450  cancelConn = NULL;
451 
452  if (oldCancelConn != NULL)
453  PQfreeCancel(oldCancelConn);
454 
456 
457 #ifdef WIN32
458  LeaveCriticalSection(&cancelConnLock);
459 #endif
460 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4242
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4219
static PGcancel *volatile cancelConn
Definition: common.c:257

◆ setQFout()

bool setQFout ( const char *  fname)

Definition at line 86 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().

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

◆ setup_cancel_handler()

void setup_cancel_handler ( void  )

Definition at line 311 of file common.c.

312 {
313  pqsignal(SIGINT, handle_sigint);
314 }
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static void handle_sigint(SIGNAL_ARGS)
Definition: common.c:280

◆ standard_strings()

bool standard_strings ( void  )

Definition at line 2312 of file common.c.

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

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

2313 {
2314  const char *val;
2315 
2316  if (!pset.db)
2317  return false;
2318 
2319  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2320 
2321  if (val && strcmp(val, "on") == 0)
2322  return true;
2323 
2324  return false;
2325 }
PGconn * db
Definition: settings.h:83
PsqlSettings pset
Definition: startup.c:35
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6561
long val
Definition: informix.c:684

Variable Documentation

◆ sigint_interrupt_enabled

volatile bool sigint_interrupt_enabled

◆ sigint_interrupt_jmp

sigjmp_buf sigint_interrupt_jmp

Definition at line 255 of file common.c.

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