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 2220 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().

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

◆ is_superuser()

bool is_superuser ( void  )

Definition at line 2159 of file common.c.

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

2160 {
2161  const char *val;
2162 
2163  if (!pset.db)
2164  return false;
2165 
2166  val = PQparameterStatus(pset.db, "is_superuser");
2167 
2168  if (val && strcmp(val, "on") == 0)
2169  return true;
2170 
2171  return false;
2172 }
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:6700
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:6735
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
PsqlSettings pset
Definition: startup.c:32
static struct @142 value
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:4003
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:71
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3997
#define free(a)
Definition: header.h:65
void PQfreemem(void *ptr)
Definition: fe-exec.c:3724
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:613
static void psql_cancel_callback(void)
Definition: common.c:250

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

Definition at line 540 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(), listExtendedStats(), 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().

541 {
542  PGresult *res;
543 
544  if (!pset.db)
545  {
546  pg_log_error("You are currently not connected to a database.");
547  return NULL;
548  }
549 
551  {
552  printf(_("********* QUERY **********\n"
553  "%s\n"
554  "**************************\n\n"), query);
555  fflush(stdout);
556  if (pset.logfile)
557  {
559  _("********* QUERY **********\n"
560  "%s\n"
561  "**************************\n\n"), query);
562  fflush(pset.logfile);
563  }
564 
566  return NULL;
567  }
568 
570 
571  res = PQexec(pset.db, query);
572 
573  ResetCancelConn();
574 
575  if (!AcceptResult(res))
576  {
577  ClearOrSaveResult(res);
578  res = NULL;
579  }
580 
581  return res;
582 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:32
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:455
#define pg_log_error(...)
Definition: logging.h:80
void ResetCancelConn(void)
Definition: cancel.c:100
#define printf(...)
Definition: port.h:222
#define fprintf
Definition: port.h:220
static bool AcceptResult(const PGresult *result)
Definition: common.c:356
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:143
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:2151
#define _(x)
Definition: elog.c:89

◆ PSQLexecWatch()

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

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

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

◆ recognized_connection_string()

bool recognized_connection_string ( const char *  connstr)

Definition at line 2305 of file common.c.

References uri_prefix_length().

Referenced by do_connect().

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

◆ SendQuery()

bool SendQuery ( const char *  query)

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

1191 {
1192  PGresult *results;
1193  PGTransactionStatusType transaction_status;
1194  double elapsed_msec = 0;
1195  bool OK = false;
1196  int i;
1197  bool on_error_rollback_savepoint = false;
1198  static bool on_error_rollback_warning = false;
1199 
1200  if (!pset.db)
1201  {
1202  pg_log_error("You are currently not connected to a database.");
1203  goto sendquery_cleanup;
1204  }
1205 
1206  if (pset.singlestep)
1207  {
1208  char buf[3];
1209 
1210  fflush(stderr);
1211  printf(_("***(Single step mode: verify command)*******************************************\n"
1212  "%s\n"
1213  "***(press return to proceed or enter x and return to cancel)********************\n"),
1214  query);
1215  fflush(stdout);
1216  if (fgets(buf, sizeof(buf), stdin) != NULL)
1217  if (buf[0] == 'x')
1218  goto sendquery_cleanup;
1219  if (cancel_pressed)
1220  goto sendquery_cleanup;
1221  }
1222  else if (pset.echo == PSQL_ECHO_QUERIES)
1223  {
1224  puts(query);
1225  fflush(stdout);
1226  }
1227 
1228  if (pset.logfile)
1229  {
1231  _("********* QUERY **********\n"
1232  "%s\n"
1233  "**************************\n\n"), query);
1234  fflush(pset.logfile);
1235  }
1236 
1238 
1239  transaction_status = PQtransactionStatus(pset.db);
1240 
1241  if (transaction_status == PQTRANS_IDLE &&
1242  !pset.autocommit &&
1243  !command_no_begin(query))
1244  {
1245  results = PQexec(pset.db, "BEGIN");
1246  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1247  {
1249  ClearOrSaveResult(results);
1250  ResetCancelConn();
1251  goto sendquery_cleanup;
1252  }
1253  ClearOrSaveResult(results);
1254  transaction_status = PQtransactionStatus(pset.db);
1255  }
1256 
1257  if (transaction_status == PQTRANS_INTRANS &&
1261  {
1262  if (on_error_rollback_warning == false && pset.sversion < 80000)
1263  {
1264  char sverbuf[32];
1265 
1266  pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1268  sverbuf, sizeof(sverbuf)));
1269  on_error_rollback_warning = true;
1270  }
1271  else
1272  {
1273  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1274  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1275  {
1277  ClearOrSaveResult(results);
1278  ResetCancelConn();
1279  goto sendquery_cleanup;
1280  }
1281  ClearOrSaveResult(results);
1282  on_error_rollback_savepoint = true;
1283  }
1284  }
1285 
1286  if (pset.gdesc_flag)
1287  {
1288  /* Describe query's result columns, without executing it */
1289  OK = DescribeQuery(query, &elapsed_msec);
1290  ResetCancelConn();
1291  results = NULL; /* PQclear(NULL) does nothing */
1292  }
1293  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1295  {
1296  /* Default fetch-it-all-and-print mode */
1298  after;
1299 
1300  if (pset.timing)
1301  INSTR_TIME_SET_CURRENT(before);
1302 
1303  results = PQexec(pset.db, query);
1304 
1305  /* these operations are included in the timing result: */
1306  ResetCancelConn();
1307  OK = ProcessResult(&results);
1308 
1309  if (pset.timing)
1310  {
1311  INSTR_TIME_SET_CURRENT(after);
1312  INSTR_TIME_SUBTRACT(after, before);
1313  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1314  }
1315 
1316  /* but printing results isn't: */
1317  if (OK && results)
1318  OK = PrintQueryResults(results);
1319  }
1320  else
1321  {
1322  /* Fetch-in-segments mode */
1323  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1324  ResetCancelConn();
1325  results = NULL; /* PQclear(NULL) does nothing */
1326  }
1327 
1328  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1329  pg_log_info("STATEMENT: %s", query);
1330 
1331  /* If we made a temporary savepoint, possibly release/rollback */
1332  if (on_error_rollback_savepoint)
1333  {
1334  const char *svptcmd = NULL;
1335 
1336  transaction_status = PQtransactionStatus(pset.db);
1337 
1338  switch (transaction_status)
1339  {
1340  case PQTRANS_INERROR:
1341  /* We always rollback on an error */
1342  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1343  break;
1344 
1345  case PQTRANS_IDLE:
1346  /* If they are no longer in a transaction, then do nothing */
1347  break;
1348 
1349  case PQTRANS_INTRANS:
1350 
1351  /*
1352  * Do nothing if they are messing with savepoints themselves:
1353  * If the user did COMMIT AND CHAIN, RELEASE or ROLLBACK, our
1354  * savepoint is gone. If they issued a SAVEPOINT, releasing
1355  * ours would remove theirs.
1356  */
1357  if (results &&
1358  (strcmp(PQcmdStatus(results), "COMMIT") == 0 ||
1359  strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1360  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1361  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1362  svptcmd = NULL;
1363  else
1364  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1365  break;
1366 
1367  case PQTRANS_ACTIVE:
1368  case PQTRANS_UNKNOWN:
1369  default:
1370  OK = false;
1371  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1372  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1373  pg_log_error("unexpected transaction status (%d)",
1374  transaction_status);
1375  break;
1376  }
1377 
1378  if (svptcmd)
1379  {
1380  PGresult *svptres;
1381 
1382  svptres = PQexec(pset.db, svptcmd);
1383  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1384  {
1386  ClearOrSaveResult(svptres);
1387  OK = false;
1388 
1389  PQclear(results);
1390  ResetCancelConn();
1391  goto sendquery_cleanup;
1392  }
1393  PQclear(svptres);
1394  }
1395  }
1396 
1397  ClearOrSaveResult(results);
1398 
1399  /* Possible microtiming output */
1400  if (pset.timing)
1401  PrintTiming(elapsed_msec);
1402 
1403  /* check for events that may occur during query execution */
1404 
1405  if (pset.encoding != PQclientEncoding(pset.db) &&
1406  PQclientEncoding(pset.db) >= 0)
1407  {
1408  /* track effects of SET CLIENT_ENCODING */
1411  SetVariable(pset.vars, "ENCODING",
1413  }
1414 
1416 
1417  /* perform cleanup that should occur after any attempted query */
1418 
1419 sendquery_cleanup:
1420 
1421  /* reset \g's output-to-filename trigger */
1422  if (pset.gfname)
1423  {
1424  free(pset.gfname);
1425  pset.gfname = NULL;
1426  }
1427 
1428  /* restore print settings if \g changed them */
1429  if (pset.gsavepopt)
1430  {
1432  pset.gsavepopt = NULL;
1433  }
1434 
1435  /* reset \gset trigger */
1436  if (pset.gset_prefix)
1437  {
1439  pset.gset_prefix = NULL;
1440  }
1441 
1442  /* reset \gdesc trigger */
1443  pset.gdesc_flag = false;
1444 
1445  /* reset \gexec trigger */
1446  pset.gexec_flag = false;
1447 
1448  /* reset \crosstabview trigger */
1449  pset.crosstab_flag = false;
1450  for (i = 0; i < lengthof(pset.ctv_args); i++)
1451  {
1452  pg_free(pset.ctv_args[i]);
1453  pset.ctv_args[i] = NULL;
1454  }
1455 
1456  return OK;
1457 }
PSQL_ECHO echo
Definition: settings.h:142
bool singlestep
Definition: settings.h:136
char * gset_prefix
Definition: settings.h:96
static bool PrintQueryResults(PGresult *results)
Definition: common.c:1115
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
int encoding
Definition: print.h:122
PsqlSettings pset
Definition: startup.c:32
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:455
#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:481
printQueryOpt * gsavepopt
Definition: settings.h:94
#define printf(...)
Definition: port.h:222
static bool ConnectionUp(void)
Definition: common.c:277
bool autocommit
Definition: settings.h:132
#define lengthof(array)
Definition: c.h:734
#define fprintf
Definition: port.h:220
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:144
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6804
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3106
static void PrintNotifications(void)
Definition: common.c:685
char * ctv_args[4]
Definition: settings.h:100
static int before(chr x, chr y)
Definition: regc_locale.c:492
bool cur_cmd_interactive
Definition: settings.h:107
static bool is_select_command(const char *query)
Definition: common.c:2122
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:4699
bool gdesc_flag
Definition: settings.h:97
static char * buf
Definition: pg_test_fsync.c:68
int fetch_count
Definition: settings.h:139
static bool ProcessResult(PGresult **results)
Definition: common.c:910
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1585
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6690
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1469
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3447
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:680
#define free(a)
Definition: header.h:65
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
PGTransactionStatusType
Definition: libpq-fe.h:105
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:2151
#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:1907
#define _(x)
Definition: elog.c:89
#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 2199 of file common.c.

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

Referenced by get_prompt().

2200 {
2201  const char *val;
2202 
2203  if (!pset.db)
2204  return NULL;
2205 
2206  val = PQparameterStatus(pset.db, "session_authorization");
2207  if (val)
2208  return val;
2209  else
2210  return PQuser(pset.db);
2211 }
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:6700
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6589
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 2179 of file common.c.

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

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

2180 {
2181  const char *val;
2182 
2183  if (!pset.db)
2184  return false;
2185 
2186  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2187 
2188  if (val && strcmp(val, "on") == 0)
2189  return true;
2190 
2191  return false;
2192 }
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:6700
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().