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:90
bool get_home_path(char *ret_path)
Definition: path.c:807

◆ is_superuser()

bool is_superuser ( void  )

Definition at line 2152 of file common.c.

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

2153 {
2154  const char *val;
2155 
2156  if (!pset.db)
2157  return false;
2158 
2159  val = PQparameterStatus(pset.db, "is_superuser");
2160 
2161  if (val && strcmp(val, "on") == 0)
2162  return true;
2163 
2164  return false;
2165 }
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:6588
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:6623
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 276 of file common.c.

References psql_cancel_callback(), and setup_cancel_handler().

Referenced by main().

277 {
279 }
static void setup_cancel_handler(void)
Definition: parallel.c:617
static void psql_cancel_callback(void)
Definition: common.c:252

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

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

547 {
548  PGresult *res;
549 
550  if (!pset.db)
551  {
552  pg_log_error("You are currently not connected to a database.");
553  return NULL;
554  }
555 
557  {
558  printf(_("********* QUERY **********\n"
559  "%s\n"
560  "**************************\n\n"), query);
561  fflush(stdout);
562  if (pset.logfile)
563  {
565  _("********* QUERY **********\n"
566  "%s\n"
567  "**************************\n\n"), query);
568  fflush(pset.logfile);
569  }
570 
572  return NULL;
573  }
574 
576 
577  res = PQexec(pset.db, query);
578 
579  ResetCancelConn();
580 
581  if (!AcceptResult(res))
582  {
583  ClearOrSaveResult(res);
584  res = NULL;
585  }
586 
587  return res;
588 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:31
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:461
#define pg_log_error(...)
Definition: logging.h:79
void ResetCancelConn(void)
Definition: cancel.c:89
#define printf(...)
Definition: port.h:198
#define fprintf
Definition: port.h:196
static bool AcceptResult(const PGresult *result)
Definition: common.c:362
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:134
void SetCancelConn(PGconn *conn)
Definition: cancel.c:59
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 601 of file common.c.

References AcceptResult(), before(), CancelRequested, 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().

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

◆ SendQuery()

bool SendQuery ( const char *  query)

Definition at line 1181 of file common.c.

References _, _psqlSettings::autocommit, before(), buf, CancelRequested, 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().

1182 {
1183  PGresult *results;
1184  PGTransactionStatusType transaction_status;
1185  double elapsed_msec = 0;
1186  bool OK = false;
1187  int i;
1188  bool on_error_rollback_savepoint = false;
1189  static bool on_error_rollback_warning = false;
1190 
1191  if (!pset.db)
1192  {
1193  pg_log_error("You are currently not connected to a database.");
1194  goto sendquery_cleanup;
1195  }
1196 
1197  if (pset.singlestep)
1198  {
1199  char buf[3];
1200 
1201  fflush(stderr);
1202  printf(_("***(Single step mode: verify command)*******************************************\n"
1203  "%s\n"
1204  "***(press return to proceed or enter x and return to cancel)********************\n"),
1205  query);
1206  fflush(stdout);
1207  if (fgets(buf, sizeof(buf), stdin) != NULL)
1208  if (buf[0] == 'x')
1209  goto sendquery_cleanup;
1210  if (CancelRequested)
1211  goto sendquery_cleanup;
1212  }
1213  else if (pset.echo == PSQL_ECHO_QUERIES)
1214  {
1215  puts(query);
1216  fflush(stdout);
1217  }
1218 
1219  if (pset.logfile)
1220  {
1222  _("********* QUERY **********\n"
1223  "%s\n"
1224  "**************************\n\n"), query);
1225  fflush(pset.logfile);
1226  }
1227 
1229 
1230  transaction_status = PQtransactionStatus(pset.db);
1231 
1232  if (transaction_status == PQTRANS_IDLE &&
1233  !pset.autocommit &&
1234  !command_no_begin(query))
1235  {
1236  results = PQexec(pset.db, "BEGIN");
1237  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1238  {
1240  ClearOrSaveResult(results);
1241  ResetCancelConn();
1242  goto sendquery_cleanup;
1243  }
1244  ClearOrSaveResult(results);
1245  transaction_status = PQtransactionStatus(pset.db);
1246  }
1247 
1248  if (transaction_status == PQTRANS_INTRANS &&
1252  {
1253  if (on_error_rollback_warning == false && pset.sversion < 80000)
1254  {
1255  char sverbuf[32];
1256 
1257  pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1259  sverbuf, sizeof(sverbuf)));
1260  on_error_rollback_warning = true;
1261  }
1262  else
1263  {
1264  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1265  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1266  {
1268  ClearOrSaveResult(results);
1269  ResetCancelConn();
1270  goto sendquery_cleanup;
1271  }
1272  ClearOrSaveResult(results);
1273  on_error_rollback_savepoint = true;
1274  }
1275  }
1276 
1277  if (pset.gdesc_flag)
1278  {
1279  /* Describe query's result columns, without executing it */
1280  OK = DescribeQuery(query, &elapsed_msec);
1281  ResetCancelConn();
1282  results = NULL; /* PQclear(NULL) does nothing */
1283  }
1284  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1286  {
1287  /* Default fetch-it-all-and-print mode */
1289  after;
1290 
1291  if (pset.timing)
1292  INSTR_TIME_SET_CURRENT(before);
1293 
1294  results = PQexec(pset.db, query);
1295 
1296  /* these operations are included in the timing result: */
1297  ResetCancelConn();
1298  OK = ProcessResult(&results);
1299 
1300  if (pset.timing)
1301  {
1302  INSTR_TIME_SET_CURRENT(after);
1303  INSTR_TIME_SUBTRACT(after, before);
1304  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1305  }
1306 
1307  /* but printing results isn't: */
1308  if (OK && results)
1309  OK = PrintQueryResults(results);
1310  }
1311  else
1312  {
1313  /* Fetch-in-segments mode */
1314  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1315  ResetCancelConn();
1316  results = NULL; /* PQclear(NULL) does nothing */
1317  }
1318 
1319  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1320  pg_log_info("STATEMENT: %s", query);
1321 
1322  /* If we made a temporary savepoint, possibly release/rollback */
1323  if (on_error_rollback_savepoint)
1324  {
1325  const char *svptcmd = NULL;
1326 
1327  transaction_status = PQtransactionStatus(pset.db);
1328 
1329  switch (transaction_status)
1330  {
1331  case PQTRANS_INERROR:
1332  /* We always rollback on an error */
1333  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1334  break;
1335 
1336  case PQTRANS_IDLE:
1337  /* If they are no longer in a transaction, then do nothing */
1338  break;
1339 
1340  case PQTRANS_INTRANS:
1341 
1342  /*
1343  * Do nothing if they are messing with savepoints themselves:
1344  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1345  * If they issued a SAVEPOINT, releasing ours would remove
1346  * theirs.
1347  */
1348  if (results &&
1349  (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1350  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1351  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1352  svptcmd = NULL;
1353  else
1354  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1355  break;
1356 
1357  case PQTRANS_ACTIVE:
1358  case PQTRANS_UNKNOWN:
1359  default:
1360  OK = false;
1361  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1362  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1363  pg_log_error("unexpected transaction status (%d)",
1364  transaction_status);
1365  break;
1366  }
1367 
1368  if (svptcmd)
1369  {
1370  PGresult *svptres;
1371 
1372  svptres = PQexec(pset.db, svptcmd);
1373  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1374  {
1376  ClearOrSaveResult(svptres);
1377  OK = false;
1378 
1379  PQclear(results);
1380  ResetCancelConn();
1381  goto sendquery_cleanup;
1382  }
1383  PQclear(svptres);
1384  }
1385  }
1386 
1387  ClearOrSaveResult(results);
1388 
1389  /* Possible microtiming output */
1390  if (pset.timing)
1391  PrintTiming(elapsed_msec);
1392 
1393  /* check for events that may occur during query execution */
1394 
1395  if (pset.encoding != PQclientEncoding(pset.db) &&
1396  PQclientEncoding(pset.db) >= 0)
1397  {
1398  /* track effects of SET CLIENT_ENCODING */
1401  SetVariable(pset.vars, "ENCODING",
1403  }
1404 
1406 
1407  /* perform cleanup that should occur after any attempted query */
1408 
1409 sendquery_cleanup:
1410 
1411  /* reset \g's output-to-filename trigger */
1412  if (pset.gfname)
1413  {
1414  free(pset.gfname);
1415  pset.gfname = NULL;
1416  }
1417 
1418  /* reset \gx's expanded-mode flag */
1419  pset.g_expanded = false;
1420 
1421  /* reset \gset trigger */
1422  if (pset.gset_prefix)
1423  {
1425  pset.gset_prefix = NULL;
1426  }
1427 
1428  /* reset \gdesc trigger */
1429  pset.gdesc_flag = false;
1430 
1431  /* reset \gexec trigger */
1432  pset.gexec_flag = false;
1433 
1434  /* reset \crosstabview trigger */
1435  pset.crosstab_flag = false;
1436  for (i = 0; i < lengthof(pset.ctv_args); i++)
1437  {
1438  pg_free(pset.ctv_args[i]);
1439  pset.ctv_args[i] = NULL;
1440  }
1441 
1442  return OK;
1443 }
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:1106
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6623
int encoding
Definition: print.h:120
PsqlSettings pset
Definition: startup.c:31
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:461
#define pg_log_error(...)
Definition: logging.h:79
void ResetCancelConn(void)
Definition: cancel.c:89
#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:167
static void PrintTiming(double elapsed_msec)
Definition: common.c:487
#define printf(...)
Definition: port.h:198
static bool ConnectionUp(void)
Definition: common.c:287
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:6683
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static void PrintNotifications(void)
Definition: common.c:691
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:2112
#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:901
void SetCancelConn(PGconn *conn)
Definition: cancel.c:59
bool g_expanded
Definition: settings.h:94
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1571
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6578
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1455
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3040
char * gfname
Definition: settings.h:93
FILE * logfile
Definition: settings.h:115
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:607
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
bool CancelRequested
Definition: cancel.c:41
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:1897
#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 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:31
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6588
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6481
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:2978
void restore_sigpipe_trap(void)
Definition: print.c:2965
bool openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
Definition: common.c:50

◆ standard_strings()

bool standard_strings ( void  )

Definition at line 2175 of file common.c.

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

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

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