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

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

◆ is_superuser()

bool is_superuser ( void  )

Definition at line 2142 of file common.c.

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

2143 {
2144  const char *val;
2145 
2146  if (!pset.db)
2147  return false;
2148 
2149  val = PQparameterStatus(pset.db, "is_superuser");
2150 
2151  if (val && strcmp(val, "on") == 0)
2152  return true;
2153 
2154  return false;
2155 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:31
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6596
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:87

◆ 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:79

◆ 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:6631
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
PsqlSettings pset
Definition: startup.c:31
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:441
static struct @145 value
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3570
static char * buf
Definition: pg_test_fsync.c:67
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
const char * GetVariable(VariableSpace space, const char *name)
Definition: variables.c:71
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3564
#define free(a)
Definition: header.h:65
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define pg_log_info(...)
Definition: logging.h:87
VariableSpace vars
Definition: settings.h:117

◆ 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:617
static void psql_cancel_callback(void)
Definition: common.c:250

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

Definition at line 536 of file common.c.

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

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

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

◆ PSQLexecWatch()

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

Definition at line 591 of file common.c.

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

Referenced by do_watch().

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

◆ recognized_connection_string()

bool recognized_connection_string ( const char *  connstr)

Definition at line 2295 of file common.c.

References uri_prefix_length().

Referenced by do_connect().

2296 {
2297  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2298 }
static int uri_prefix_length(const char *connstr)
Definition: common.c:2268
static char * connstr
Definition: pg_dumpall.c:61

◆ SendQuery()

bool SendQuery ( const char *  query)

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

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

◆ session_username()

const char* session_username ( void  )

Definition at line 2189 of file common.c.

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

Referenced by get_prompt().

2190 {
2191  const char *val;
2192 
2193  if (!pset.db)
2194  return NULL;
2195 
2196  val = PQparameterStatus(pset.db, "session_authorization");
2197  if (val)
2198  return val;
2199  else
2200  return PQuser(pset.db);
2201 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:31
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6596
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6489
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:31
bool queryFoutPipe
Definition: settings.h:85
FILE * queryFout
Definition: settings.h:84
void set_sigpipe_trap_state(bool ignore)
Definition: print.c:2977
void restore_sigpipe_trap(void)
Definition: print.c:2964
bool openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
Definition: common.c:50

◆ standard_strings()

bool standard_strings ( void  )

Definition at line 2165 of file common.c.

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

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

2166 {
2167  const char *val;
2168 
2169  if (!pset.db)
2170  return false;
2171 
2172  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2173 
2174  if (val && strcmp(val, "on") == 0)
2175  return true;
2176 
2177  return false;
2178 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:31
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6596
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().