PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 psql_error (const char *fmt,...) pg_attribute_printf(1
 
void 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

void expand_tilde ( char **  filename)

Definition at line 2103 of file common.c.

References filename, fn(), free, get_home_path(), MAXPGPATH, NULL, 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().

2104 {
2105  if (!filename || !(*filename))
2106  return;
2107 
2108  /*
2109  * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2110  * for short versions of long file names, though the tilde is usually
2111  * toward the end, not at the beginning.
2112  */
2113 #ifndef WIN32
2114 
2115  /* try tilde expansion */
2116  if (**filename == '~')
2117  {
2118  char *fn;
2119  char oldp,
2120  *p;
2121  struct passwd *pw;
2122  char home[MAXPGPATH];
2123 
2124  fn = *filename;
2125  *home = '\0';
2126 
2127  p = fn + 1;
2128  while (*p != '/' && *p != '\0')
2129  p++;
2130 
2131  oldp = *p;
2132  *p = '\0';
2133 
2134  if (*(fn + 1) == '\0')
2135  get_home_path(home); /* ~ or ~/ only */
2136  else if ((pw = getpwnam(fn + 1)) != NULL)
2137  strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2138 
2139  *p = oldp;
2140  if (strlen(home) != 0)
2141  {
2142  char *newfn;
2143 
2144  newfn = psprintf("%s%s", home, p);
2145  free(fn);
2146  *filename = newfn;
2147  }
2148  }
2149 #endif
2150 
2151  return;
2152 }
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
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:90
bool get_home_path(char *ret_path)
Definition: path.c:807
bool is_superuser ( void  )

Definition at line 2035 of file common.c.

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

2036 {
2037  const char *val;
2038 
2039  if (!pset.db)
2040  return false;
2041 
2042  val = PQparameterStatus(pset.db, "is_superuser");
2043 
2044  if (val && strcmp(val, "on") == 0)
2045  return true;
2046 
2047  return false;
2048 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6062
long val
Definition: informix.c:689
void void NoticeProcessor ( void *  arg,
const char *  message 
)

Definition at line 241 of file common.c.

References psql_error().

Referenced by do_connect(), and main().

242 {
243  (void) arg; /* not used */
244  psql_error("%s", message);
245 }
void psql_error(const char *fmt,...)
Definition: common.c:220
void * arg
bool openQueryOutputFile ( const char *  fname,
FILE **  fout,
bool is_pipe 
)

Definition at line 49 of file common.c.

References NULL, psql_error(), and strerror().

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

50 {
51  if (!fname || fname[0] == '\0')
52  {
53  *fout = stdout;
54  *is_pipe = false;
55  }
56  else if (*fname == '|')
57  {
58  *fout = popen(fname + 1, "w");
59  *is_pipe = true;
60  }
61  else
62  {
63  *fout = fopen(fname, "w");
64  *is_pipe = false;
65  }
66 
67  if (*fout == NULL)
68  {
69  psql_error("%s: %s\n", fname, strerror(errno));
70  return false;
71  }
72 
73  return true;
74 }
void psql_error(const char *fmt,...)
Definition: common.c:220
#define NULL
Definition: c.h:229
const char * strerror(int errnum)
Definition: strerror.c:19
void psql_error ( const char *  fmt,
  ... 
)
char* psql_get_variable ( const char *  varname,
PsqlScanQuoteType  quote,
void *  passthrough 
)

Definition at line 128 of file common.c.

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

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

Definition at line 642 of file common.c.

References _, AcceptResult(), ClearOrSaveResult(), _psqlSettings::db, _psqlSettings::echo_hidden, _psqlSettings::logfile, NULL, PQexec(), pset, PSQL_ECHO_HIDDEN_NOEXEC, PSQL_ECHO_HIDDEN_OFF, psql_error(), ResetCancelConn(), and SetCancelConn().

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

643 {
644  PGresult *res;
645 
646  if (!pset.db)
647  {
648  psql_error("You are currently not connected to a database.\n");
649  return NULL;
650  }
651 
653  {
654  printf(_("********* QUERY **********\n"
655  "%s\n"
656  "**************************\n\n"), query);
657  fflush(stdout);
658  if (pset.logfile)
659  {
660  fprintf(pset.logfile,
661  _("********* QUERY **********\n"
662  "%s\n"
663  "**************************\n\n"), query);
664  fflush(pset.logfile);
665  }
666 
668  return NULL;
669  }
670 
671  SetCancelConn();
672 
673  res = PQexec(pset.db, query);
674 
675  ResetCancelConn();
676 
677  if (!AcceptResult(res))
678  {
679  ClearOrSaveResult(res);
680  res = NULL;
681  }
682 
683  return res;
684 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:557
static bool AcceptResult(const PGresult *result)
Definition: common.c:505
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:132
void SetCancelConn(void)
Definition: common.c:445
void psql_error(const char *fmt,...)
Definition: common.c:220
FILE * logfile
Definition: settings.h:114
#define NULL
Definition: c.h:229
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
void ResetCancelConn(void)
Definition: common.c:475
#define _(x)
Definition: elog.c:84
int PSQLexecWatch ( const char *  query,
const printQueryOpt opt 
)

Definition at line 697 of file common.c.

References _, AcceptResult(), before(), cancel_pressed, ClearOrSaveResult(), _psqlSettings::db, INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, _psqlSettings::logfile, 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, psql_error(), _psqlSettings::queryFout, ResetCancelConn(), SetCancelConn(), _psqlSettings::timing, and printQueryOpt::title.

Referenced by do_watch().

698 {
699  PGresult *res;
700  double elapsed_msec = 0;
702  instr_time after;
703 
704  if (!pset.db)
705  {
706  psql_error("You are currently not connected to a database.\n");
707  return 0;
708  }
709 
710  SetCancelConn();
711 
712  if (pset.timing)
713  INSTR_TIME_SET_CURRENT(before);
714 
715  res = PQexec(pset.db, query);
716 
717  ResetCancelConn();
718 
719  if (!AcceptResult(res))
720  {
721  ClearOrSaveResult(res);
722  return 0;
723  }
724 
725  if (pset.timing)
726  {
727  INSTR_TIME_SET_CURRENT(after);
728  INSTR_TIME_SUBTRACT(after, before);
729  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
730  }
731 
732  /*
733  * If SIGINT is sent while the query is processing, the interrupt will be
734  * consumed. The user's intention, though, is to cancel the entire watch
735  * process, so detect a sent cancellation request and exit in this case.
736  */
737  if (cancel_pressed)
738  {
739  PQclear(res);
740  return 0;
741  }
742 
743  switch (PQresultStatus(res))
744  {
745  case PGRES_TUPLES_OK:
746  printQuery(res, opt, pset.queryFout, false, pset.logfile);
747  break;
748 
749  case PGRES_COMMAND_OK:
750  fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
751  break;
752 
753  case PGRES_EMPTY_QUERY:
754  psql_error(_("\\watch cannot be used with an empty query\n"));
755  PQclear(res);
756  return -1;
757 
758  case PGRES_COPY_OUT:
759  case PGRES_COPY_IN:
760  case PGRES_COPY_BOTH:
761  psql_error(_("\\watch cannot be used with COPY\n"));
762  PQclear(res);
763  return -1;
764 
765  default:
766  psql_error(_("unexpected result status for \\watch\n"));
767  PQclear(res);
768  return -1;
769  }
770 
771  PQclear(res);
772 
773  fflush(pset.queryFout);
774 
775  /* Possible microtiming output */
776  if (pset.timing)
777  PrintTiming(elapsed_msec);
778 
779  return 1;
780 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:557
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:199
struct timeval instr_time
Definition: instr_time.h:147
static void PrintTiming(double elapsed_msec)
Definition: common.c:583
FILE * queryFout
Definition: settings.h:84
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static bool AcceptResult(const PGresult *result)
Definition: common.c:505
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:167
void SetCancelConn(void)
Definition: common.c:445
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2944
void psql_error(const char *fmt,...)
Definition: common.c:220
FILE * logfile
Definition: settings.h:114
void PQclear(PGresult *res)
Definition: fe-exec.c:650
char * title
Definition: print.h:167
void printQuery(const PGresult *result, const printQueryOpt *opt, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3285
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
void ResetCancelConn(void)
Definition: common.c:475
#define _(x)
Definition: elog.c:84
bool recognized_connection_string ( const char *  connstr)

Definition at line 2190 of file common.c.

References NULL, and uri_prefix_length().

Referenced by do_connect().

2191 {
2192  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2193 }
static int uri_prefix_length(const char *connstr)
Definition: common.c:2163
#define NULL
Definition: c.h:229
static char * connstr
Definition: pg_dumpall.c:64
void ResetCancelConn ( void  )

Definition at line 475 of file common.c.

476 {
477  PGcancel *oldCancelConn;
478 
479 #ifdef WIN32
480  EnterCriticalSection(&cancelConnLock);
481 #endif
482 
483  oldCancelConn = cancelConn;
484  /* be sure handle_sigint doesn't use pointer while freeing */
485  cancelConn = NULL;
486 
487  if (oldCancelConn != NULL)
488  PQfreeCancel(oldCancelConn);
489 
490 #ifdef WIN32
491  LeaveCriticalSection(&cancelConnLock);
492 #endif
493 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3774
static PGcancel *volatile cancelConn
Definition: common.c:277
#define NULL
Definition: c.h:229
bool SendQuery ( const char *  query)

Definition at line 1230 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, _psqlSettings::echo, _psqlSettings::encoding, printTableOpt::encoding, ExecQueryUsingCursor(), _psqlSettings::fetch_count, formatPGVersionNumber(), free, _psqlSettings::g_expanded, _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, NULL, _psqlSettings::on_error_rollback, pg_encoding_to_char(), pg_free(), PGRES_COMMAND_OK, _psqlSettings::popt, PQclear(), PQclientEncoding(), PQcmdStatus(), PQerrorMessage(), PQexec(), PQresultStatus(), PQTRANS_ACTIVE, PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, PQtransactionStatus(), PrintNotifications(), PrintQueryResults(), PrintTiming(), ProcessResult(), pset, PSQL_ECHO_ERRORS, PSQL_ECHO_QUERIES, psql_error(), PSQL_ERROR_ROLLBACK_OFF, PSQL_ERROR_ROLLBACK_ON, ResetCancelConn(), SetCancelConn(), SetVariable(), _psqlSettings::singlestep, _psqlSettings::sversion, _psqlSettings::timing, printQueryOpt::topt, and _psqlSettings::vars.

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

1231 {
1232  PGresult *results;
1233  PGTransactionStatusType transaction_status;
1234  double elapsed_msec = 0;
1235  bool OK = false;
1236  int i;
1237  bool on_error_rollback_savepoint = false;
1238  static bool on_error_rollback_warning = false;
1239 
1240  if (!pset.db)
1241  {
1242  psql_error("You are currently not connected to a database.\n");
1243  goto sendquery_cleanup;
1244  }
1245 
1246  if (pset.singlestep)
1247  {
1248  char buf[3];
1249 
1250  fflush(stderr);
1251  printf(_("***(Single step mode: verify command)*******************************************\n"
1252  "%s\n"
1253  "***(press return to proceed or enter x and return to cancel)********************\n"),
1254  query);
1255  fflush(stdout);
1256  if (fgets(buf, sizeof(buf), stdin) != NULL)
1257  if (buf[0] == 'x')
1258  goto sendquery_cleanup;
1259  if (cancel_pressed)
1260  goto sendquery_cleanup;
1261  }
1262  else if (pset.echo == PSQL_ECHO_QUERIES)
1263  {
1264  puts(query);
1265  fflush(stdout);
1266  }
1267 
1268  if (pset.logfile)
1269  {
1270  fprintf(pset.logfile,
1271  _("********* QUERY **********\n"
1272  "%s\n"
1273  "**************************\n\n"), query);
1274  fflush(pset.logfile);
1275  }
1276 
1277  SetCancelConn();
1278 
1279  transaction_status = PQtransactionStatus(pset.db);
1280 
1281  if (transaction_status == PQTRANS_IDLE &&
1282  !pset.autocommit &&
1283  !command_no_begin(query))
1284  {
1285  results = PQexec(pset.db, "BEGIN");
1286  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1287  {
1288  psql_error("%s", PQerrorMessage(pset.db));
1289  ClearOrSaveResult(results);
1290  ResetCancelConn();
1291  goto sendquery_cleanup;
1292  }
1293  ClearOrSaveResult(results);
1294  transaction_status = PQtransactionStatus(pset.db);
1295  }
1296 
1297  if (transaction_status == PQTRANS_INTRANS &&
1301  {
1302  if (on_error_rollback_warning == false && pset.sversion < 80000)
1303  {
1304  char sverbuf[32];
1305 
1306  psql_error("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.\n",
1308  sverbuf, sizeof(sverbuf)));
1309  on_error_rollback_warning = true;
1310  }
1311  else
1312  {
1313  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1314  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1315  {
1316  psql_error("%s", PQerrorMessage(pset.db));
1317  ClearOrSaveResult(results);
1318  ResetCancelConn();
1319  goto sendquery_cleanup;
1320  }
1321  ClearOrSaveResult(results);
1322  on_error_rollback_savepoint = true;
1323  }
1324  }
1325 
1326  if (pset.fetch_count <= 0 || pset.gexec_flag ||
1328  {
1329  /* Default fetch-it-all-and-print mode */
1331  after;
1332 
1333  if (pset.timing)
1334  INSTR_TIME_SET_CURRENT(before);
1335 
1336  results = PQexec(pset.db, query);
1337 
1338  /* these operations are included in the timing result: */
1339  ResetCancelConn();
1340  OK = ProcessResult(&results);
1341 
1342  if (pset.timing)
1343  {
1344  INSTR_TIME_SET_CURRENT(after);
1345  INSTR_TIME_SUBTRACT(after, before);
1346  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1347  }
1348 
1349  /* but printing results isn't: */
1350  if (OK && results)
1351  OK = PrintQueryResults(results);
1352  }
1353  else
1354  {
1355  /* Fetch-in-segments mode */
1356  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1357  ResetCancelConn();
1358  results = NULL; /* PQclear(NULL) does nothing */
1359  }
1360 
1361  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1362  psql_error("STATEMENT: %s\n", query);
1363 
1364  /* If we made a temporary savepoint, possibly release/rollback */
1365  if (on_error_rollback_savepoint)
1366  {
1367  const char *svptcmd = NULL;
1368 
1369  transaction_status = PQtransactionStatus(pset.db);
1370 
1371  switch (transaction_status)
1372  {
1373  case PQTRANS_INERROR:
1374  /* We always rollback on an error */
1375  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1376  break;
1377 
1378  case PQTRANS_IDLE:
1379  /* If they are no longer in a transaction, then do nothing */
1380  break;
1381 
1382  case PQTRANS_INTRANS:
1383 
1384  /*
1385  * Do nothing if they are messing with savepoints themselves:
1386  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1387  * If they issued a SAVEPOINT, releasing ours would remove
1388  * theirs.
1389  */
1390  if (results &&
1391  (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1392  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1393  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1394  svptcmd = NULL;
1395  else
1396  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1397  break;
1398 
1399  case PQTRANS_ACTIVE:
1400  case PQTRANS_UNKNOWN:
1401  default:
1402  OK = false;
1403  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1404  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1405  psql_error("unexpected transaction status (%d)\n",
1406  transaction_status);
1407  break;
1408  }
1409 
1410  if (svptcmd)
1411  {
1412  PGresult *svptres;
1413 
1414  svptres = PQexec(pset.db, svptcmd);
1415  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1416  {
1417  psql_error("%s", PQerrorMessage(pset.db));
1418  ClearOrSaveResult(svptres);
1419  OK = false;
1420 
1421  PQclear(results);
1422  ResetCancelConn();
1423  goto sendquery_cleanup;
1424  }
1425  PQclear(svptres);
1426  }
1427  }
1428 
1429  ClearOrSaveResult(results);
1430 
1431  /* Possible microtiming output */
1432  if (pset.timing)
1433  PrintTiming(elapsed_msec);
1434 
1435  /* check for events that may occur during query execution */
1436 
1437  if (pset.encoding != PQclientEncoding(pset.db) &&
1438  PQclientEncoding(pset.db) >= 0)
1439  {
1440  /* track effects of SET CLIENT_ENCODING */
1443  SetVariable(pset.vars, "ENCODING",
1445  }
1446 
1448 
1449  /* perform cleanup that should occur after any attempted query */
1450 
1451 sendquery_cleanup:
1452 
1453  /* reset \g's output-to-filename trigger */
1454  if (pset.gfname)
1455  {
1456  free(pset.gfname);
1457  pset.gfname = NULL;
1458  }
1459 
1460  /* reset \gx's expanded-mode flag */
1461  pset.g_expanded = false;
1462 
1463  /* reset \gset trigger */
1464  if (pset.gset_prefix)
1465  {
1467  pset.gset_prefix = NULL;
1468  }
1469 
1470  /* reset \gexec trigger */
1471  pset.gexec_flag = false;
1472 
1473  /* reset \crosstabview trigger */
1474  pset.crosstab_flag = false;
1475  for (i = 0; i < lengthof(pset.ctv_args); i++)
1476  {
1477  pg_free(pset.ctv_args[i]);
1478  pset.ctv_args[i] = NULL;
1479  }
1480 
1481  return OK;
1482 }
PSQL_ECHO echo
Definition: settings.h:131
bool singlestep
Definition: settings.h:127
char * gset_prefix
Definition: settings.h:95
static bool PrintQueryResults(PGresult *results)
Definition: common.c:1155
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
int encoding
Definition: print.h:118
PsqlSettings pset
Definition: startup.c:33
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:557
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:199
struct timeval instr_time
Definition: instr_time.h:147
bool gexec_flag
Definition: settings.h:96
printTableOpt topt
Definition: print.h:165
static void PrintTiming(double elapsed_msec)
Definition: common.c:583
static bool ConnectionUp(void)
Definition: common.c:388
bool autocommit
Definition: settings.h:123
#define lengthof(array)
Definition: c.h:562
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:133
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6157
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
volatile bool cancel_pressed
Definition: print.c:46
static void PrintNotifications(void)
Definition: common.c:787
char * ctv_args[4]
Definition: settings.h:98
static int before(chr x, chr y)
Definition: regc_locale.c:496
bool cur_cmd_interactive
Definition: settings.h:105
static bool is_select_command(const char *query)
Definition: common.c:1995
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
static char * buf
Definition: pg_test_fsync.c:66
int fetch_count
Definition: settings.h:128
static bool ProcessResult(PGresult **results)
Definition: common.c:995
bool g_expanded
Definition: settings.h:94
void SetCancelConn(void)
Definition: common.c:445
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1496
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6052
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2944
void psql_error(const char *fmt,...)
Definition: common.c:220
char * gfname
Definition: settings.h:93
FILE * logfile
Definition: settings.h:114
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define free(a)
Definition: header.h:65
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:607
PGTransactionStatusType
Definition: libpq-fe.h:101
#define NULL
Definition: c.h:229
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:153
int i
bool crosstab_flag
Definition: settings.h:97
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
int encoding
Definition: settings.h:83
static bool command_no_begin(const char *query)
Definition: common.c:1796
void ResetCancelConn(void)
Definition: common.c:475
#define _(x)
Definition: elog.c:84
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:182
VariableSpace vars
Definition: settings.h:116
const char* session_username ( void  )

Definition at line 2082 of file common.c.

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

Referenced by get_prompt().

2083 {
2084  const char *val;
2085 
2086  if (!pset.db)
2087  return NULL;
2088 
2089  val = PQparameterStatus(pset.db, "session_authorization");
2090  if (val)
2091  return val;
2092  else
2093  return PQuser(pset.db);
2094 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6062
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5973
#define NULL
Definition: c.h:229
long val
Definition: informix.c:689
void SetCancelConn ( void  )

Definition at line 445 of file common.c.

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

Referenced by do_lo_export(), do_lo_import(), do_lo_unlink(), executeMaintenanceCommand(), GetIdleSlot(), GetQueryResult(), ProcessResult(), PSQLexec(), PSQLexecWatch(), and SendQuery().

446 {
447  PGcancel *oldCancelConn;
448 
449 #ifdef WIN32
450  EnterCriticalSection(&cancelConnLock);
451 #endif
452 
453  /* Free the old one if we have one */
454  oldCancelConn = cancelConn;
455  /* be sure handle_sigint doesn't use pointer while freeing */
456  cancelConn = NULL;
457 
458  if (oldCancelConn != NULL)
459  PQfreeCancel(oldCancelConn);
460 
462 
463 #ifdef WIN32
464  LeaveCriticalSection(&cancelConnLock);
465 #endif
466 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3774
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3751
static PGcancel *volatile cancelConn
Definition: common.c:277
#define NULL
Definition: c.h:229
bool setQFout ( const char *  fname)

Definition at line 84 of file common.c.

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

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

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

Definition at line 331 of file common.c.

332 {
333  pqsignal(SIGINT, handle_sigint);
334 }
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
static void handle_sigint(SIGNAL_ARGS)
Definition: common.c:300
bool standard_strings ( void  )

Definition at line 2058 of file common.c.

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

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

2059 {
2060  const char *val;
2061 
2062  if (!pset.db)
2063  return false;
2064 
2065  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2066 
2067  if (val && strcmp(val, "on") == 0)
2068  return true;
2069 
2070  return false;
2071 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:33
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6062
long val
Definition: informix.c:689

Variable Documentation

volatile bool sigint_interrupt_enabled
sigjmp_buf sigint_interrupt_jmp

Definition at line 275 of file common.c.

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