PostgreSQL Source Code  git master
common.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <pwd.h>
#include <signal.h>
#include <unistd.h>
#include "command.h"
#include "common.h"
#include "common/logging.h"
#include "copy.h"
#include "crosstabview.h"
#include "fe_utils/cancel.h"
#include "fe_utils/mbprint.h"
#include "fe_utils/string_utils.h"
#include "portability/instr_time.h"
#include "settings.h"
Include dependency graph for common.c:

Go to the source code of this file.

Functions

static bool DescribeQuery (const char *query, double *elapsed_msec)
 
static bool ExecQueryUsingCursor (const char *query, double *elapsed_msec)
 
static int ExecQueryAndProcessResults (const char *query, double *elapsed_msec, bool *svpt_gone_p, bool is_watch, const printQueryOpt *opt, FILE *printQueryFout)
 
static bool command_no_begin (const char *query)
 
static bool is_select_command (const char *query)
 
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)
 
static void psql_cancel_callback (void)
 
void psql_setup_cancel_handler (void)
 
static bool ConnectionUp (void)
 
static bool CheckConnection (void)
 
static bool AcceptResult (const PGresult *result, bool show_error)
 
static void SetResultVariables (PGresult *result, bool success)
 
static void ClearOrSaveResult (PGresult *result)
 
static void ClearOrSaveAllResults (void)
 
static void PrintTiming (double elapsed_msec)
 
PGresultPSQLexec (const char *query)
 
int PSQLexecWatch (const char *query, const printQueryOpt *opt, FILE *printQueryFout)
 
static void PrintNotifications (void)
 
static bool PrintQueryTuples (const PGresult *result, const printQueryOpt *opt, FILE *printQueryFout)
 
static bool StoreQueryTuple (const PGresult *result)
 
static bool ExecQueryTuples (const PGresult *result)
 
static bool HandleCopyResult (PGresult **resultp, FILE *copystream)
 
static void PrintQueryStatus (PGresult *result, FILE *printQueryFout)
 
static bool PrintQueryResult (PGresult *result, bool last, const printQueryOpt *opt, FILE *printQueryFout, FILE *printStatusFout)
 
bool SendQuery (const char *query)
 
static const char * skip_white_space (const char *query)
 
bool is_superuser (void)
 
bool standard_strings (void)
 
const char * session_username (void)
 
void expand_tilde (char **filename)
 
static int uri_prefix_length (const char *connstr)
 
bool recognized_connection_string (const char *connstr)
 

Variables

volatile sig_atomic_t sigint_interrupt_enabled = false
 
sigjmp_buf sigint_interrupt_jmp
 

Function Documentation

◆ AcceptResult()

static bool AcceptResult ( const PGresult result,
bool  show_error 
)
static

Definition at line 364 of file common.c.

365 {
366  bool OK;
367 
368  if (!result)
369  OK = false;
370  else
371  switch (PQresultStatus(result))
372  {
373  case PGRES_COMMAND_OK:
374  case PGRES_TUPLES_OK:
375  case PGRES_EMPTY_QUERY:
376  case PGRES_COPY_IN:
377  case PGRES_COPY_OUT:
378  /* Fine, do nothing */
379  OK = true;
380  break;
381 
382  case PGRES_BAD_RESPONSE:
384  case PGRES_FATAL_ERROR:
385  OK = false;
386  break;
387 
388  default:
389  OK = false;
390  pg_log_error("unexpected PQresultStatus: %d",
391  PQresultStatus(result));
392  break;
393  }
394 
395  if (!OK && show_error)
396  {
397  const char *error = PQerrorMessage(pset.db);
398 
399  if (strlen(error))
400  pg_log_info("%s", error);
401 
402  CheckConnection();
403  }
404 
405  return OK;
406 }
static bool CheckConnection(void)
Definition: common.c:303
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6743
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:105
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_info(...)
Definition: logging.h:124
PsqlSettings pset
Definition: startup.c:32
static void error(void)
Definition: sql-dyntest.c:147
PGconn * db
Definition: settings.h:82

References CheckConnection(), _psqlSettings::db, error(), pg_log_error, pg_log_info, PGRES_BAD_RESPONSE, PGRES_COMMAND_OK, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PGRES_TUPLES_OK, PQerrorMessage(), PQresultStatus(), and pset.

Referenced by DescribeQuery(), ExecQueryAndProcessResults(), ExecQueryUsingCursor(), and PSQLexec().

◆ CheckConnection()

static bool CheckConnection ( void  )
static

Definition at line 303 of file common.c.

304 {
305  bool OK;
306 
307  OK = ConnectionUp();
308  if (!OK)
309  {
311  {
312  pg_log_error("connection to server was lost");
314  }
315 
316  fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
317  PQreset(pset.db);
318  OK = ConnectionUp();
319  if (!OK)
320  {
321  fprintf(stderr, _("Failed.\n"));
322 
323  /*
324  * Transition to having no connection; but stash away the failed
325  * connection so that we can still refer to its parameters in a
326  * later \connect attempt. Keep the state cleanup here in sync
327  * with do_connect().
328  */
329  if (pset.dead_conn)
331  pset.dead_conn = pset.db;
332  pset.db = NULL;
333  ResetCancelConn();
334  UnsyncVariables();
335  }
336  else
337  {
338  fprintf(stderr, _("Succeeded.\n"));
339 
340  /*
341  * Re-sync, just in case anything changed. Keep this in sync with
342  * do_connect().
343  */
344  SyncVariables();
345  connection_warnings(false); /* Must be after SyncVariables */
346  }
347  }
348 
349  return OK;
350 }
static bool ConnectionUp(void)
Definition: common.c:285
void ResetCancelConn(void)
Definition: cancel.c:107
void UnsyncVariables(void)
Definition: command.c:3811
void SyncVariables(void)
Definition: command.c:3770
void connection_warnings(bool in_startup)
Definition: command.c:3645
#define _(x)
Definition: elog.c:91
void PQreset(PGconn *conn)
Definition: fe-connect.c:4144
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4130
exit(1)
#define fprintf
Definition: port.h:242
#define EXIT_BADCONN
Definition: settings.h:169
PGconn * dead_conn
Definition: settings.h:128
bool cur_cmd_interactive
Definition: settings.h:110

References _, connection_warnings(), ConnectionUp(), _psqlSettings::cur_cmd_interactive, _psqlSettings::db, _psqlSettings::dead_conn, exit(), EXIT_BADCONN, fprintf, pg_log_error, PQfinish(), PQreset(), pset, ResetCancelConn(), SyncVariables(), and UnsyncVariables().

Referenced by AcceptResult(), and ExecQueryAndProcessResults().

◆ ClearOrSaveAllResults()

static void ClearOrSaveAllResults ( void  )
static

Definition at line 487 of file common.c.

488 {
489  PGresult *result;
490 
491  while ((result = PQgetResult(pset.db)) != NULL)
492  ClearOrSaveResult(result);
493 }
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:463
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2031

References ClearOrSaveResult(), _psqlSettings::db, PQgetResult(), and pset.

Referenced by ExecQueryAndProcessResults().

◆ ClearOrSaveResult()

static void ClearOrSaveResult ( PGresult result)
static

Definition at line 463 of file common.c.

464 {
465  if (result)
466  {
467  switch (PQresultStatus(result))
468  {
470  case PGRES_FATAL_ERROR:
472  pset.last_error_result = result;
473  break;
474 
475  default:
476  PQclear(result);
477  break;
478  }
479  }
480 }
PGresult * last_error_result
Definition: settings.h:89

References _psqlSettings::last_error_result, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PQclear(), PQresultStatus(), and pset.

Referenced by ClearOrSaveAllResults(), DescribeQuery(), ExecQueryAndProcessResults(), ExecQueryUsingCursor(), PSQLexec(), and SendQuery().

◆ command_no_begin()

static bool command_no_begin ( const char *  query)
static

Definition at line 2006 of file common.c.

2007 {
2008  int wordlen;
2009 
2010  /*
2011  * First we must advance over any whitespace and comments.
2012  */
2013  query = skip_white_space(query);
2014 
2015  /*
2016  * Check word length (since "beginx" is not "begin").
2017  */
2018  wordlen = 0;
2019  while (isalpha((unsigned char) query[wordlen]))
2020  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2021 
2022  /*
2023  * Transaction control commands. These should include every keyword that
2024  * gives rise to a TransactionStmt in the backend grammar, except for the
2025  * savepoint-related commands.
2026  *
2027  * (We assume that START must be START TRANSACTION, since there is
2028  * presently no other "START foo" command.)
2029  */
2030  if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2031  return true;
2032  if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2033  return true;
2034  if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2035  return true;
2036  if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2037  return true;
2038  if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2039  return true;
2040  if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2041  return true;
2042  if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2043  {
2044  /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2045  query += wordlen;
2046 
2047  query = skip_white_space(query);
2048 
2049  wordlen = 0;
2050  while (isalpha((unsigned char) query[wordlen]))
2051  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2052 
2053  if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2054  return true;
2055  return false;
2056  }
2057 
2058  /*
2059  * Commands not allowed within transactions. The statements checked for
2060  * here should be exactly those that call PreventInTransactionBlock() in
2061  * the backend.
2062  */
2063  if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2064  return true;
2065  if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2066  {
2067  /* CLUSTER with any arguments is allowed in transactions */
2068  query += wordlen;
2069 
2070  query = skip_white_space(query);
2071 
2072  if (isalpha((unsigned char) query[0]))
2073  return false; /* has additional words */
2074  return true; /* it's CLUSTER without arguments */
2075  }
2076 
2077  if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2078  {
2079  query += wordlen;
2080 
2081  query = skip_white_space(query);
2082 
2083  wordlen = 0;
2084  while (isalpha((unsigned char) query[wordlen]))
2085  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2086 
2087  if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2088  return true;
2089  if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2090  return true;
2091 
2092  /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2093  if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2094  {
2095  query += wordlen;
2096 
2097  query = skip_white_space(query);
2098 
2099  wordlen = 0;
2100  while (isalpha((unsigned char) query[wordlen]))
2101  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2102  }
2103 
2104  if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2105  {
2106  query += wordlen;
2107 
2108  query = skip_white_space(query);
2109 
2110  wordlen = 0;
2111  while (isalpha((unsigned char) query[wordlen]))
2112  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2113 
2114  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2115  return true;
2116  }
2117 
2118  return false;
2119  }
2120 
2121  if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2122  {
2123  query += wordlen;
2124 
2125  query = skip_white_space(query);
2126 
2127  wordlen = 0;
2128  while (isalpha((unsigned char) query[wordlen]))
2129  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2130 
2131  /* ALTER SYSTEM isn't allowed in xacts */
2132  if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2133  return true;
2134 
2135  return false;
2136  }
2137 
2138  /*
2139  * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2140  * aren't really valid commands so we don't care much. The other four
2141  * possible matches are correct.
2142  */
2143  if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2144  (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2145  {
2146  query += wordlen;
2147 
2148  query = skip_white_space(query);
2149 
2150  wordlen = 0;
2151  while (isalpha((unsigned char) query[wordlen]))
2152  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2153 
2154  if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2155  return true;
2156  if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2157  return true;
2158  if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2159  return true;
2160  if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
2161  pg_strncasecmp(query, "table", 5) == 0))
2162  {
2163  query += wordlen;
2164  query = skip_white_space(query);
2165  wordlen = 0;
2166  while (isalpha((unsigned char) query[wordlen]))
2167  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2168 
2169  /*
2170  * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2171  * xacts.
2172  */
2173  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2174  return true;
2175  }
2176 
2177  /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2178  if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2179  {
2180  query += wordlen;
2181 
2182  query = skip_white_space(query);
2183 
2184  wordlen = 0;
2185  while (isalpha((unsigned char) query[wordlen]))
2186  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2187 
2188  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2189  return true;
2190 
2191  return false;
2192  }
2193 
2194  return false;
2195  }
2196 
2197  /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2198  if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2199  {
2200  query += wordlen;
2201 
2202  query = skip_white_space(query);
2203 
2204  wordlen = 0;
2205  while (isalpha((unsigned char) query[wordlen]))
2206  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2207 
2208  if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2209  return true;
2210  return false;
2211  }
2212 
2213  return false;
2214 }
static const char * skip_white_space(const char *query)
Definition: common.c:1942
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1187
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
int encoding
Definition: settings.h:83

References _psqlSettings::encoding, pg_strncasecmp(), PQmblenBounded(), pset, and skip_white_space().

Referenced by SendQuery().

◆ ConnectionUp()

static bool ConnectionUp ( void  )
static

Definition at line 285 of file common.c.

286 {
287  return PQstatus(pset.db) != CONNECTION_BAD;
288 }
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6690
@ CONNECTION_BAD
Definition: libpq-fe.h:61

References CONNECTION_BAD, _psqlSettings::db, PQstatus(), and pset.

Referenced by CheckConnection(), and SendQuery().

◆ DescribeQuery()

static bool DescribeQuery ( const char *  query,
double *  elapsed_msec 
)
static

Definition at line 1267 of file common.c.

1268 {
1269  bool timing = pset.timing;
1270  PGresult *result;
1271  bool OK;
1273  after;
1274 
1275  *elapsed_msec = 0;
1276 
1277  if (timing)
1279  else
1281 
1282  /*
1283  * To parse the query but not execute it, we prepare it, using the unnamed
1284  * prepared statement. This is invisible to psql users, since there's no
1285  * way to access the unnamed prepared statement from psql user space. The
1286  * next Parse or Query protocol message would overwrite the statement
1287  * anyway. (So there's no great need to clear it when done, which is a
1288  * good thing because libpq provides no easy way to do that.)
1289  */
1290  result = PQprepare(pset.db, "", query, 0, NULL);
1291  if (PQresultStatus(result) != PGRES_COMMAND_OK)
1292  {
1294  SetResultVariables(result, false);
1295  ClearOrSaveResult(result);
1296  return false;
1297  }
1298  PQclear(result);
1299 
1300  result = PQdescribePrepared(pset.db, "");
1301  OK = AcceptResult(result, true) &&
1302  (PQresultStatus(result) == PGRES_COMMAND_OK);
1303  if (OK && result)
1304  {
1305  if (PQnfields(result) > 0)
1306  {
1308  int i;
1309 
1310  initPQExpBuffer(&buf);
1311 
1313  "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1314  "FROM (VALUES ",
1315  gettext_noop("Column"),
1316  gettext_noop("Type"));
1317 
1318  for (i = 0; i < PQnfields(result); i++)
1319  {
1320  const char *name;
1321  char *escname;
1322 
1323  if (i > 0)
1324  appendPQExpBufferStr(&buf, ",");
1325 
1326  name = PQfname(result, i);
1327  escname = PQescapeLiteral(pset.db, name, strlen(name));
1328 
1329  if (escname == NULL)
1330  {
1332  PQclear(result);
1333  termPQExpBuffer(&buf);
1334  return false;
1335  }
1336 
1337  appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1338  escname,
1339  PQftype(result, i),
1340  PQfmod(result, i));
1341 
1342  PQfreemem(escname);
1343  }
1344 
1345  appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1346  PQclear(result);
1347 
1348  result = PQexec(pset.db, buf.data);
1349  OK = AcceptResult(result, true);
1350 
1351  if (timing)
1352  {
1353  INSTR_TIME_SET_CURRENT(after);
1354  INSTR_TIME_SUBTRACT(after, before);
1355  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1356  }
1357 
1358  if (OK && result)
1359  OK = PrintQueryResult(result, true, NULL, NULL, NULL);
1360 
1361  termPQExpBuffer(&buf);
1362  }
1363  else
1365  _("The command has no result, or the result has no columns.\n"));
1366  }
1367 
1368  SetResultVariables(result, OK);
1369  ClearOrSaveResult(result);
1370 
1371  return OK;
1372 }
static bool PrintQueryResult(PGresult *result, bool last, const printQueryOpt *opt, FILE *printQueryFout, FILE *printStatusFout)
Definition: common.c:940
static void SetResultVariables(PGresult *result, bool success)
Definition: common.c:421
static bool AcceptResult(const PGresult *result, bool show_error)
Definition: common.c:364
#define gettext_noop(x)
Definition: c.h:1186
const char * name
Definition: encode.c:571
void PQfreemem(void *ptr)
Definition: fe-exec.c:3865
PGresult * PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:2269
Oid PQftype(const PGresult *res, int field_num)
Definition: fe-exec.c:3548
PGresult * PQdescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2418
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3396
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4137
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225
int PQfmod(const PGresult *res, int field_num)
Definition: fe-exec.c:3570
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:181
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:191
#define INSTR_TIME_SET_ZERO(t)
Definition: instr_time.h:172
int i
Definition: isn.c:73
static char * buf
Definition: pg_test_fsync.c:67
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
static int before(chr x, chr y)
Definition: regc_locale.c:492
FILE * queryFout
Definition: settings.h:84

References _, AcceptResult(), appendPQExpBuffer(), appendPQExpBufferStr(), before(), buf, ClearOrSaveResult(), _psqlSettings::db, fprintf, gettext_noop, i, initPQExpBuffer(), INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SET_ZERO, INSTR_TIME_SUBTRACT, name, pg_log_info, PGRES_COMMAND_OK, PQclear(), PQdescribePrepared(), PQerrorMessage(), PQescapeLiteral(), PQexec(), PQfmod(), PQfname(), PQfreemem(), PQftype(), PQnfields(), PQprepare(), PQresultStatus(), printfPQExpBuffer(), PrintQueryResult(), pset, _psqlSettings::queryFout, SetResultVariables(), termPQExpBuffer(), and _psqlSettings::timing.

Referenced by SendQuery().

◆ ExecQueryAndProcessResults()

static int ExecQueryAndProcessResults ( const char *  query,
double *  elapsed_msec,
bool svpt_gone_p,
bool  is_watch,
const printQueryOpt opt,
FILE *  printQueryFout 
)
static

Definition at line 1396 of file common.c.

1400 {
1401  bool timing = pset.timing;
1402  bool success;
1404  after;
1405  PGresult *result;
1406  FILE *gfile_fout = NULL;
1407  bool gfile_is_pipe = false;
1408 
1409  if (timing)
1411  else
1413 
1414  if (pset.bind_flag)
1415  success = PQsendQueryParams(pset.db, query, pset.bind_nparams, NULL, (const char * const *) pset.bind_params, NULL, NULL, 0);
1416  else
1417  success = PQsendQuery(pset.db, query);
1418 
1419  if (!success)
1420  {
1421  const char *error = PQerrorMessage(pset.db);
1422 
1423  if (strlen(error))
1424  pg_log_info("%s", error);
1425 
1426  CheckConnection();
1427 
1428  return -1;
1429  }
1430 
1431  /*
1432  * If SIGINT is sent while the query is processing, the interrupt will be
1433  * consumed. The user's intention, though, is to cancel the entire watch
1434  * process, so detect a sent cancellation request and exit in this case.
1435  */
1436  if (is_watch && cancel_pressed)
1437  {
1439  return 0;
1440  }
1441 
1442  /* first result */
1443  result = PQgetResult(pset.db);
1444 
1445  while (result != NULL)
1446  {
1447  ExecStatusType result_status;
1448  PGresult *next_result;
1449  bool last;
1450 
1451  if (!AcceptResult(result, false))
1452  {
1453  /*
1454  * Some error occurred, either a server-side failure or a failure
1455  * to submit the command string. Record that.
1456  */
1457  const char *error = PQresultErrorMessage(result);
1458 
1459  if (strlen(error))
1460  pg_log_info("%s", error);
1461 
1462  CheckConnection();
1463  if (!is_watch)
1464  SetResultVariables(result, false);
1465 
1466  /* keep the result status before clearing it */
1467  result_status = PQresultStatus(result);
1468  ClearOrSaveResult(result);
1469  success = false;
1470 
1471  /*
1472  * switch to next result
1473  */
1474  if (result_status == PGRES_COPY_BOTH ||
1475  result_status == PGRES_COPY_OUT ||
1476  result_status == PGRES_COPY_IN)
1477 
1478  /*
1479  * For some obscure reason PQgetResult does *not* return a
1480  * NULL in copy cases despite the result having been cleared,
1481  * but keeps returning an "empty" result that we have to
1482  * ignore manually.
1483  */
1484  result = NULL;
1485  else
1486  result = PQgetResult(pset.db);
1487 
1488  /*
1489  * Get current timing measure in case an error occurs
1490  */
1491  if (timing)
1492  {
1493  INSTR_TIME_SET_CURRENT(after);
1494  INSTR_TIME_SUBTRACT(after, before);
1495  *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1496  }
1497 
1498  continue;
1499  }
1500  else if (svpt_gone_p && !*svpt_gone_p)
1501  {
1502  /*
1503  * Check if the user ran any command that would destroy our
1504  * internal savepoint: If the user did COMMIT AND CHAIN, RELEASE
1505  * or ROLLBACK, our savepoint is gone. If they issued a SAVEPOINT,
1506  * releasing ours would remove theirs.
1507  */
1508  const char *cmd = PQcmdStatus(result);
1509 
1510  *svpt_gone_p = (strcmp(cmd, "COMMIT") == 0 ||
1511  strcmp(cmd, "SAVEPOINT") == 0 ||
1512  strcmp(cmd, "RELEASE") == 0 ||
1513  strcmp(cmd, "ROLLBACK") == 0);
1514  }
1515 
1516  result_status = PQresultStatus(result);
1517 
1518  /* must handle COPY before changing the current result */
1519  Assert(result_status != PGRES_COPY_BOTH);
1520  if (result_status == PGRES_COPY_IN ||
1521  result_status == PGRES_COPY_OUT)
1522  {
1523  FILE *copy_stream = NULL;
1524 
1525  /*
1526  * For COPY OUT, direct the output to the default place (probably
1527  * a pager pipe) for \watch, or to pset.copyStream for \copy,
1528  * otherwise to pset.gfname if that's set, otherwise to
1529  * pset.queryFout.
1530  */
1531  if (result_status == PGRES_COPY_OUT)
1532  {
1533  if (is_watch)
1534  {
1535  /* invoked by \watch */
1536  copy_stream = printQueryFout ? printQueryFout : pset.queryFout;
1537  }
1538  else if (pset.copyStream)
1539  {
1540  /* invoked by \copy */
1541  copy_stream = pset.copyStream;
1542  }
1543  else if (pset.gfname)
1544  {
1545  /* send to \g file, which we may have opened already */
1546  if (gfile_fout == NULL)
1547  {
1549  &gfile_fout, &gfile_is_pipe))
1550  {
1551  if (gfile_is_pipe)
1553  copy_stream = gfile_fout;
1554  }
1555  else
1556  success = false;
1557  }
1558  else
1559  copy_stream = gfile_fout;
1560  }
1561  else
1562  {
1563  /* fall back to the generic query output stream */
1564  copy_stream = pset.queryFout;
1565  }
1566  }
1567 
1568  /*
1569  * Even if the output stream could not be opened, we call
1570  * HandleCopyResult() with a NULL output stream to collect and
1571  * discard the COPY data.
1572  */
1573  success &= HandleCopyResult(&result, copy_stream);
1574  }
1575 
1576  /*
1577  * Check PQgetResult() again. In the typical case of a single-command
1578  * string, it will return NULL. Otherwise, we'll have other results
1579  * to process. We need to do that to check whether this is the last.
1580  */
1581  next_result = PQgetResult(pset.db);
1582  last = (next_result == NULL);
1583 
1584  /*
1585  * Update current timing measure.
1586  *
1587  * It will include the display of previous results, if any. This
1588  * cannot be helped because the server goes on processing further
1589  * queries anyway while the previous ones are being displayed. The
1590  * parallel execution of the client display hides the server time when
1591  * it is shorter.
1592  *
1593  * With combined queries, timing must be understood as an upper bound
1594  * of the time spent processing them.
1595  */
1596  if (timing)
1597  {
1598  INSTR_TIME_SET_CURRENT(after);
1599  INSTR_TIME_SUBTRACT(after, before);
1600  *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1601  }
1602 
1603  /* this may or may not print something depending on settings */
1604  if (result != NULL)
1605  {
1606  /*
1607  * If results need to be printed into the file specified by \g,
1608  * open it, unless we already did. Note that when pset.gfname is
1609  * set, the passed-in value of printQueryFout is not used for
1610  * tuple output, but it's still used for status output.
1611  */
1612  FILE *tuples_fout = printQueryFout;
1613  bool do_print = true;
1614 
1615  if (PQresultStatus(result) == PGRES_TUPLES_OK &&
1616  pset.gfname)
1617  {
1618  if (gfile_fout == NULL)
1619  {
1621  &gfile_fout, &gfile_is_pipe))
1622  {
1623  if (gfile_is_pipe)
1625  }
1626  else
1627  success = do_print = false;
1628  }
1629  tuples_fout = gfile_fout;
1630  }
1631  if (do_print)
1632  success &= PrintQueryResult(result, last, opt,
1633  tuples_fout, printQueryFout);
1634  }
1635 
1636  /* set variables on last result if all went well */
1637  if (!is_watch && last && success)
1638  SetResultVariables(result, true);
1639 
1640  ClearOrSaveResult(result);
1641  result = next_result;
1642 
1643  if (cancel_pressed)
1644  {
1646  break;
1647  }
1648  }
1649 
1650  /* close \g file if we opened it */
1651  if (gfile_fout)
1652  {
1653  if (gfile_is_pipe)
1654  {
1655  pclose(gfile_fout);
1657  }
1658  else
1659  fclose(gfile_fout);
1660  }
1661 
1662  /* may need this to recover from conn loss during COPY */
1663  if (!CheckConnection())
1664  return -1;
1665 
1666  return cancel_pressed ? 0 : success ? 1 : -1;
1667 }
static void ClearOrSaveAllResults(void)
Definition: common.c:487
static bool HandleCopyResult(PGresult **resultp, FILE *copystream)
Definition: common.c:845
bool openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
Definition: common.c:57
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1494
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:3256
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3581
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1418
void restore_sigpipe_trap(void)
Definition: print.c:3061
void disable_sigpipe_trap(void)
Definition: print.c:3038
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
static bool success
Definition: initdb.c:170
ExecStatusType
Definition: libpq-fe.h:95
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
Assert(fmt[strlen(fmt) - 1] !='\n')
bool bind_flag
Definition: settings.h:99
FILE * copyStream
Definition: settings.h:87
char ** bind_params
Definition: settings.h:101
char * gfname
Definition: settings.h:93
int bind_nparams
Definition: settings.h:100

References AcceptResult(), Assert(), before(), _psqlSettings::bind_flag, _psqlSettings::bind_nparams, _psqlSettings::bind_params, cancel_pressed, CheckConnection(), ClearOrSaveAllResults(), ClearOrSaveResult(), _psqlSettings::copyStream, _psqlSettings::db, disable_sigpipe_trap(), error(), _psqlSettings::gfname, HandleCopyResult(), INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SET_ZERO, INSTR_TIME_SUBTRACT, openQueryOutputFile(), pg_log_info, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_TUPLES_OK, PQcmdStatus(), PQerrorMessage(), PQgetResult(), PQresultErrorMessage(), PQresultStatus(), PQsendQuery(), PQsendQueryParams(), PrintQueryResult(), pset, _psqlSettings::queryFout, restore_sigpipe_trap(), SetResultVariables(), success, and _psqlSettings::timing.

Referenced by PSQLexecWatch(), and SendQuery().

◆ ExecQueryTuples()

static bool ExecQueryTuples ( const PGresult result)
static

Definition at line 766 of file common.c.

767 {
768  bool success = true;
769  int nrows = PQntuples(result);
770  int ncolumns = PQnfields(result);
771  int r,
772  c;
773 
774  /*
775  * We must turn off gexec_flag to avoid infinite recursion. Note that
776  * this allows ExecQueryUsingCursor to be applied to the individual query
777  * results. SendQuery prevents it from being applied when fetching the
778  * queries-to-execute, because it can't handle recursion either.
779  */
780  pset.gexec_flag = false;
781 
782  for (r = 0; r < nrows; r++)
783  {
784  for (c = 0; c < ncolumns; c++)
785  {
786  if (!PQgetisnull(result, r, c))
787  {
788  const char *query = PQgetvalue(result, r, c);
789 
790  /* Abandon execution if cancel_pressed */
791  if (cancel_pressed)
792  goto loop_exit;
793 
794  /*
795  * ECHO_ALL mode should echo these queries, but SendQuery
796  * assumes that MainLoop did that, so we have to do it here.
797  */
799  {
800  puts(query);
801  fflush(stdout);
802  }
803 
804  if (!SendQuery(query))
805  {
806  /* Error - abandon execution if ON_ERROR_STOP */
807  success = false;
808  if (pset.on_error_stop)
809  goto loop_exit;
810  }
811  }
812  }
813  }
814 
815 loop_exit:
816 
817  /*
818  * Restore state. We know gexec_flag was on, else we'd not be here. (We
819  * also know it'll get turned off at end of command, but that's not ours
820  * to do here.)
821  */
822  pset.gexec_flag = true;
823 
824  /* Return true if all queries were successful */
825  return success;
826 }
bool SendQuery(const char *query)
Definition: common.c:1022
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3730
static void const char fflush(stdout)
char * c
@ PSQL_ECHO_ALL
Definition: settings.h:40
bool on_error_stop
Definition: settings.h:136
PSQL_ECHO echo
Definition: settings.h:145
bool singlestep
Definition: settings.h:139
bool gexec_flag
Definition: settings.h:98

References cancel_pressed, _psqlSettings::echo, fflush(), _psqlSettings::gexec_flag, _psqlSettings::on_error_stop, PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), pset, PSQL_ECHO_ALL, SendQuery(), _psqlSettings::singlestep, generate_unaccent_rules::stdout, and success.

Referenced by PrintQueryResult().

◆ ExecQueryUsingCursor()

static bool ExecQueryUsingCursor ( const char *  query,
double *  elapsed_msec 
)
static

Definition at line 1681 of file common.c.

1682 {
1683  bool OK = true;
1684  PGresult *result;
1686  printQueryOpt my_popt = pset.popt;
1687  bool timing = pset.timing;
1688  FILE *fout;
1689  bool is_pipe;
1690  bool is_pager = false;
1691  bool started_txn = false;
1692  int64 total_tuples = 0;
1693  int ntuples;
1694  int fetch_count;
1695  char fetch_cmd[64];
1697  after;
1698  int flush_error;
1699 
1700  *elapsed_msec = 0;
1701 
1702  /* initialize print options for partial table output */
1703  my_popt.topt.start_table = true;
1704  my_popt.topt.stop_table = false;
1705  my_popt.topt.prior_records = 0;
1706 
1707  if (timing)
1709  else
1711 
1712  /* if we're not in a transaction, start one */
1714  {
1715  result = PQexec(pset.db, "BEGIN");
1716  OK = AcceptResult(result, true) &&
1717  (PQresultStatus(result) == PGRES_COMMAND_OK);
1718  ClearOrSaveResult(result);
1719  if (!OK)
1720  return false;
1721  started_txn = true;
1722  }
1723 
1724  /* Send DECLARE CURSOR */
1725  initPQExpBuffer(&buf);
1726  appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1727  query);
1728 
1729  result = PQexec(pset.db, buf.data);
1730  OK = AcceptResult(result, true) &&
1731  (PQresultStatus(result) == PGRES_COMMAND_OK);
1732  if (!OK)
1733  SetResultVariables(result, OK);
1734  ClearOrSaveResult(result);
1735  termPQExpBuffer(&buf);
1736  if (!OK)
1737  goto cleanup;
1738 
1739  if (timing)
1740  {
1741  INSTR_TIME_SET_CURRENT(after);
1742  INSTR_TIME_SUBTRACT(after, before);
1743  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1744  }
1745 
1746  /*
1747  * In \gset mode, we force the fetch count to be 2, so that we will throw
1748  * the appropriate error if the query returns more than one row.
1749  */
1750  if (pset.gset_prefix)
1751  fetch_count = 2;
1752  else
1753  fetch_count = pset.fetch_count;
1754 
1755  snprintf(fetch_cmd, sizeof(fetch_cmd),
1756  "FETCH FORWARD %d FROM _psql_cursor",
1757  fetch_count);
1758 
1759  /* prepare to write output to \g argument, if any */
1760  if (pset.gfname)
1761  {
1762  if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1763  {
1764  OK = false;
1765  goto cleanup;
1766  }
1767  if (is_pipe)
1769  }
1770  else
1771  {
1772  fout = pset.queryFout;
1773  is_pipe = false; /* doesn't matter */
1774  }
1775 
1776  /* clear any pre-existing error indication on the output stream */
1777  clearerr(fout);
1778 
1779  for (;;)
1780  {
1781  if (timing)
1783 
1784  /* get fetch_count tuples at a time */
1785  result = PQexec(pset.db, fetch_cmd);
1786 
1787  if (timing)
1788  {
1789  INSTR_TIME_SET_CURRENT(after);
1790  INSTR_TIME_SUBTRACT(after, before);
1791  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1792  }
1793 
1794  if (PQresultStatus(result) != PGRES_TUPLES_OK)
1795  {
1796  /* shut down pager before printing error message */
1797  if (is_pager)
1798  {
1799  ClosePager(fout);
1800  is_pager = false;
1801  }
1802 
1803  OK = AcceptResult(result, true);
1804  Assert(!OK);
1805  SetResultVariables(result, OK);
1806  ClearOrSaveResult(result);
1807  break;
1808  }
1809 
1810  if (pset.gset_prefix)
1811  {
1812  /* StoreQueryTuple will complain if not exactly one row */
1813  OK = StoreQueryTuple(result);
1814  ClearOrSaveResult(result);
1815  break;
1816  }
1817 
1818  /*
1819  * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1820  */
1821 
1822  ntuples = PQntuples(result);
1823  total_tuples += ntuples;
1824 
1825  if (ntuples < fetch_count)
1826  {
1827  /* this is the last result set, so allow footer decoration */
1828  my_popt.topt.stop_table = true;
1829  }
1830  else if (fout == stdout && !is_pager)
1831  {
1832  /*
1833  * If query requires multiple result sets, hack to ensure that
1834  * only one pager instance is used for the whole mess
1835  */
1836  fout = PageOutput(INT_MAX, &(my_popt.topt));
1837  is_pager = true;
1838  }
1839 
1840  printQuery(result, &my_popt, fout, is_pager, pset.logfile);
1841 
1842  ClearOrSaveResult(result);
1843 
1844  /* after the first result set, disallow header decoration */
1845  my_popt.topt.start_table = false;
1846  my_popt.topt.prior_records += ntuples;
1847 
1848  /*
1849  * Make sure to flush the output stream, so intermediate results are
1850  * visible to the client immediately. We check the results because if
1851  * the pager dies/exits/etc, there's no sense throwing more data at
1852  * it.
1853  */
1854  flush_error = fflush(fout);
1855 
1856  /*
1857  * Check if we are at the end, if a cancel was pressed, or if there
1858  * were any errors either trying to flush out the results, or more
1859  * generally on the output stream at all. If we hit any errors
1860  * writing things to the stream, we presume $PAGER has disappeared and
1861  * stop bothering to pull down more data.
1862  */
1863  if (ntuples < fetch_count || cancel_pressed || flush_error ||
1864  ferror(fout))
1865  break;
1866  }
1867 
1868  if (pset.gfname)
1869  {
1870  /* close \g argument file/pipe */
1871  if (is_pipe)
1872  {
1873  pclose(fout);
1875  }
1876  else
1877  fclose(fout);
1878  }
1879  else if (is_pager)
1880  {
1881  /* close transient pager */
1882  ClosePager(fout);
1883  }
1884 
1885  if (OK)
1886  {
1887  /*
1888  * We don't have a PGresult here, and even if we did it wouldn't have
1889  * the right row count, so fake SetResultVariables(). In error cases,
1890  * we already set the result variables above.
1891  */
1892  char buf[32];
1893 
1894  SetVariable(pset.vars, "ERROR", "false");
1895  SetVariable(pset.vars, "SQLSTATE", "00000");
1896  snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1897  SetVariable(pset.vars, "ROW_COUNT", buf);
1898  }
1899 
1900 cleanup:
1901  if (timing)
1903 
1904  /*
1905  * We try to close the cursor on either success or failure, but on failure
1906  * ignore the result (it's probably just a bleat about being in an aborted
1907  * transaction)
1908  */
1909  result = PQexec(pset.db, "CLOSE _psql_cursor");
1910  if (OK)
1911  {
1912  OK = AcceptResult(result, true) &&
1913  (PQresultStatus(result) == PGRES_COMMAND_OK);
1914  ClearOrSaveResult(result);
1915  }
1916  else
1917  PQclear(result);
1918 
1919  if (started_txn)
1920  {
1921  result = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1922  OK &= AcceptResult(result, true) &&
1923  (PQresultStatus(result) == PGRES_COMMAND_OK);
1924  ClearOrSaveResult(result);
1925  }
1926 
1927  if (timing)
1928  {
1929  INSTR_TIME_SET_CURRENT(after);
1930  INSTR_TIME_SUBTRACT(after, before);
1931  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1932  }
1933 
1934  return OK;
1935 }
static bool StoreQueryTuple(const PGresult *result)
Definition: common.c:702
static void cleanup(void)
Definition: bootstrap.c:696
#define INT64_FORMAT
Definition: c.h:532
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6698
void printQuery(const PGresult *result, const printQueryOpt *opt, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3534
void ClosePager(FILE *pagerpipe)
Definition: print.c:3140
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:3088
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
#define snprintf
Definition: port.h:238
printQueryOpt popt
Definition: settings.h:91
char * gset_prefix
Definition: settings.h:96
VariableSpace vars
Definition: settings.h:121
FILE * logfile
Definition: settings.h:119
int fetch_count
Definition: settings.h:142
printTableOpt topt
Definition: print.h:180
bool start_table
Definition: print.h:122
unsigned long prior_records
Definition: print.h:125
bool stop_table
Definition: print.h:123
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211

References AcceptResult(), appendPQExpBuffer(), Assert(), before(), buf, cancel_pressed, cleanup(), ClearOrSaveResult(), ClosePager(), _psqlSettings::db, disable_sigpipe_trap(), _psqlSettings::fetch_count, fflush(), _psqlSettings::gfname, _psqlSettings::gset_prefix, initPQExpBuffer(), INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SET_ZERO, INSTR_TIME_SUBTRACT, INT64_FORMAT, _psqlSettings::logfile, openQueryOutputFile(), PageOutput(), PGRES_COMMAND_OK, PGRES_TUPLES_OK, _psqlSettings::popt, PQclear(), PQexec(), PQntuples(), PQresultStatus(), PQTRANS_IDLE, PQtransactionStatus(), printQuery(), printTableOpt::prior_records, pset, _psqlSettings::queryFout, restore_sigpipe_trap(), SetResultVariables(), SetVariable(), snprintf, printTableOpt::start_table, generate_unaccent_rules::stdout, printTableOpt::stop_table, StoreQueryTuple(), termPQExpBuffer(), _psqlSettings::timing, printQueryOpt::topt, and _psqlSettings::vars.

Referenced by SendQuery().

◆ expand_tilde()

void expand_tilde ( char **  filename)

Definition at line 2319 of file common.c.

2320 {
2321  if (!filename || !(*filename))
2322  return;
2323 
2324  /*
2325  * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2326  * for short versions of long file names, though the tilde is usually
2327  * toward the end, not at the beginning.
2328  */
2329 #ifndef WIN32
2330 
2331  /* try tilde expansion */
2332  if (**filename == '~')
2333  {
2334  char *fn;
2335  char oldp,
2336  *p;
2337  struct passwd *pw;
2338  char home[MAXPGPATH];
2339 
2340  fn = *filename;
2341  *home = '\0';
2342 
2343  p = fn + 1;
2344  while (*p != '/' && *p != '\0')
2345  p++;
2346 
2347  oldp = *p;
2348  *p = '\0';
2349 
2350  if (*(fn + 1) == '\0')
2351  get_home_path(home); /* ~ or ~/ only */
2352  else if ((pw = getpwnam(fn + 1)) != NULL)
2353  strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2354 
2355  *p = oldp;
2356  if (strlen(home) != 0)
2357  {
2358  char *newfn;
2359 
2360  newfn = psprintf("%s%s", home, p);
2361  free(fn);
2362  *filename = newfn;
2363  }
2364  }
2365 #endif
2366 }
#define free(a)
Definition: header.h:65
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:119
bool get_home_path(char *ret_path)
Definition: path.c:928
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void * fn(void *arg)

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

◆ HandleCopyResult()

static bool HandleCopyResult ( PGresult **  resultp,
FILE *  copystream 
)
static

Definition at line 845 of file common.c.

846 {
847  bool success;
848  PGresult *copy_result;
849  ExecStatusType result_status = PQresultStatus(*resultp);
850 
851  Assert(result_status == PGRES_COPY_OUT ||
852  result_status == PGRES_COPY_IN);
853 
855 
856  if (result_status == PGRES_COPY_OUT)
857  {
859  copystream,
860  &copy_result)
861  && (copystream != NULL);
862 
863  /*
864  * Suppress status printing if the report would go to the same place
865  * as the COPY data just went. Note this doesn't prevent error
866  * reporting, since handleCopyOut did that.
867  */
868  if (copystream == pset.queryFout)
869  {
870  PQclear(copy_result);
871  copy_result = NULL;
872  }
873  }
874  else
875  {
876  /* COPY IN */
877  /* Ignore the copystream argument passed to the function */
880  copystream,
881  PQbinaryTuples(*resultp),
882  &copy_result);
883  }
884  ResetCancelConn();
885 
886  /*
887  * Replace the PGRES_COPY_OUT/IN result with COPY command's exit status,
888  * or with NULL if we want to suppress printing anything.
889  */
890  PQclear(*resultp);
891  *resultp = copy_result;
892 
893  return success;
894 }
bool handleCopyOut(PGconn *conn, FILE *copystream, PGresult **res)
Definition: copy.c:433
bool handleCopyIn(PGconn *conn, FILE *copystream, bool isbinary, PGresult **res)
Definition: copy.c:510
void SetCancelConn(PGconn *conn)
Definition: cancel.c:77
int PQbinaryTuples(const PGresult *res)
Definition: fe-exec.c:3326
FILE * cur_cmd_source
Definition: settings.h:108

References Assert(), _psqlSettings::copyStream, _psqlSettings::cur_cmd_source, _psqlSettings::db, handleCopyIn(), handleCopyOut(), PGRES_COPY_IN, PGRES_COPY_OUT, PQbinaryTuples(), PQclear(), PQresultStatus(), pset, _psqlSettings::queryFout, ResetCancelConn(), SetCancelConn(), and success.

Referenced by ExecQueryAndProcessResults().

◆ is_select_command()

static bool is_select_command ( const char *  query)
static

Definition at line 2221 of file common.c.

2222 {
2223  int wordlen;
2224 
2225  /*
2226  * First advance over any whitespace, comments and left parentheses.
2227  */
2228  for (;;)
2229  {
2230  query = skip_white_space(query);
2231  if (query[0] == '(')
2232  query++;
2233  else
2234  break;
2235  }
2236 
2237  /*
2238  * Check word length (since "selectx" is not "select").
2239  */
2240  wordlen = 0;
2241  while (isalpha((unsigned char) query[wordlen]))
2242  wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2243 
2244  if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2245  return true;
2246 
2247  if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2248  return true;
2249 
2250  return false;
2251 }

References _psqlSettings::encoding, pg_strncasecmp(), PQmblenBounded(), pset, and skip_white_space().

Referenced by SendQuery().

◆ is_superuser()

bool is_superuser ( void  )

Definition at line 2258 of file common.c.

2259 {
2260  const char *val;
2261 
2262  if (!pset.db)
2263  return false;
2264 
2265  val = PQparameterStatus(pset.db, "is_superuser");
2266 
2267  if (val && strcmp(val, "on") == 0)
2268  return true;
2269 
2270  return false;
2271 }
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6708
long val
Definition: informix.c:664

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

◆ NoticeProcessor()

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

Definition at line 228 of file common.c.

229 {
230  (void) arg; /* not used */
231  pg_log_info("%s", message);
232 }
void * arg

References arg, and pg_log_info.

Referenced by do_connect(), and main().

◆ openQueryOutputFile()

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

Definition at line 57 of file common.c.

58 {
59  if (!fname || fname[0] == '\0')
60  {
61  *fout = stdout;
62  *is_pipe = false;
63  }
64  else if (*fname == '|')
65  {
66  fflush(NULL);
67  *fout = popen(fname + 1, "w");
68  *is_pipe = true;
69  }
70  else
71  {
72  *fout = fopen(fname, "w");
73  *is_pipe = false;
74  }
75 
76  if (*fout == NULL)
77  {
78  pg_log_error("%s: %m", fname);
79  return false;
80  }
81 
82  return true;
83 }

References fflush(), pg_log_error, and generate_unaccent_rules::stdout.

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

◆ PrintNotifications()

static void PrintNotifications ( void  )
static

Definition at line 645 of file common.c.

646 {
647  PGnotify *notify;
648 
650  while ((notify = PQnotifies(pset.db)) != NULL)
651  {
652  /* for backward compatibility, only show payload if nonempty */
653  if (notify->extra[0])
654  fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
655  notify->relname, notify->extra, notify->be_pid);
656  else
657  fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
658  notify->relname, notify->be_pid);
660  PQfreemem(notify);
662  }
663 }
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2548
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1953
int be_pid
Definition: libpq-fe.h:190
char * relname
Definition: libpq-fe.h:189
char * extra
Definition: libpq-fe.h:191

References _, pgNotify::be_pid, _psqlSettings::db, pgNotify::extra, fflush(), fprintf, PQconsumeInput(), PQfreemem(), PQnotifies(), pset, _psqlSettings::queryFout, and pgNotify::relname.

Referenced by SendQuery().

◆ PrintQueryResult()

static bool PrintQueryResult ( PGresult result,
bool  last,
const printQueryOpt opt,
FILE *  printQueryFout,
FILE *  printStatusFout 
)
static

Definition at line 940 of file common.c.

943 {
944  bool success;
945  const char *cmdstatus;
946 
947  if (!result)
948  return false;
949 
950  switch (PQresultStatus(result))
951  {
952  case PGRES_TUPLES_OK:
953  /* store or execute or print the data ... */
954  if (last && pset.gset_prefix)
955  success = StoreQueryTuple(result);
956  else if (last && pset.gexec_flag)
957  success = ExecQueryTuples(result);
958  else if (last && pset.crosstab_flag)
959  success = PrintResultInCrosstab(result);
960  else if (last || pset.show_all_results)
961  success = PrintQueryTuples(result, opt, printQueryFout);
962  else
963  success = true;
964 
965  /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
966  if (last || pset.show_all_results)
967  {
968  cmdstatus = PQcmdStatus(result);
969  if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
970  strncmp(cmdstatus, "UPDATE", 6) == 0 ||
971  strncmp(cmdstatus, "DELETE", 6) == 0)
972  PrintQueryStatus(result, printStatusFout);
973  }
974 
975  break;
976 
977  case PGRES_COMMAND_OK:
978  if (last || pset.show_all_results)
979  PrintQueryStatus(result, printStatusFout);
980  success = true;
981  break;
982 
983  case PGRES_EMPTY_QUERY:
984  success = true;
985  break;
986 
987  case PGRES_COPY_OUT:
988  case PGRES_COPY_IN:
989  /* nothing to do here: already processed */
990  success = true;
991  break;
992 
993  case PGRES_BAD_RESPONSE:
995  case PGRES_FATAL_ERROR:
996  success = false;
997  break;
998 
999  default:
1000  success = false;
1001  pg_log_error("unexpected PQresultStatus: %d",
1002  PQresultStatus(result));
1003  break;
1004  }
1005 
1006  return success;
1007 }
static void PrintQueryStatus(PGresult *result, FILE *printQueryFout)
Definition: common.c:902
static bool ExecQueryTuples(const PGresult *result)
Definition: common.c:766
static bool PrintQueryTuples(const PGresult *result, const printQueryOpt *opt, FILE *printQueryFout)
Definition: common.c:678
bool PrintResultInCrosstab(const PGresult *res)
Definition: crosstabview.c:103
bool show_all_results
Definition: settings.h:154
bool crosstab_flag
Definition: settings.h:102

References _psqlSettings::crosstab_flag, ExecQueryTuples(), _psqlSettings::gexec_flag, _psqlSettings::gset_prefix, pg_log_error, PGRES_BAD_RESPONSE, PGRES_COMMAND_OK, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PGRES_TUPLES_OK, PQcmdStatus(), PQresultStatus(), PrintQueryStatus(), PrintQueryTuples(), PrintResultInCrosstab(), pset, _psqlSettings::show_all_results, StoreQueryTuple(), and success.

Referenced by DescribeQuery(), and ExecQueryAndProcessResults().

◆ PrintQueryStatus()

static void PrintQueryStatus ( PGresult result,
FILE *  printQueryFout 
)
static

Definition at line 902 of file common.c.

903 {
904  char buf[16];
905  FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
906 
907  if (!pset.quiet)
908  {
909  if (pset.popt.topt.format == PRINT_HTML)
910  {
911  fputs("<p>", fout);
912  html_escaped_print(PQcmdStatus(result), fout);
913  fputs("</p>\n", fout);
914  }
915  else
916  fprintf(fout, "%s\n", PQcmdStatus(result));
917  fflush(fout);
918  }
919 
920  if (pset.logfile)
921  fprintf(pset.logfile, "%s\n", PQcmdStatus(result));
922 
923  snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(result));
924  SetVariable(pset.vars, "LASTOID", buf);
925 }
Oid PQoidValue(const PGresult *res)
Definition: fe-exec.c:3622
void html_escaped_print(const char *in, FILE *fout)
Definition: print.c:1951
@ PRINT_HTML
Definition: print.h:34
enum printFormat format
Definition: print.h:110

References buf, fflush(), printTableOpt::format, fprintf, html_escaped_print(), _psqlSettings::logfile, _psqlSettings::popt, PQcmdStatus(), PQoidValue(), PRINT_HTML, pset, _psqlSettings::queryFout, _psqlSettings::quiet, SetVariable(), snprintf, printQueryOpt::topt, and _psqlSettings::vars.

Referenced by PrintQueryResult().

◆ PrintQueryTuples()

static bool PrintQueryTuples ( const PGresult result,
const printQueryOpt opt,
FILE *  printQueryFout 
)
static

Definition at line 678 of file common.c.

680 {
681  bool ok = true;
682  FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
683 
684  printQuery(result, opt ? opt : &pset.popt, fout, false, pset.logfile);
685  fflush(fout);
686  if (ferror(fout))
687  {
688  pg_log_error("could not print result table: %m");
689  ok = false;
690  }
691 
692  return ok;
693 }

References fflush(), _psqlSettings::logfile, pg_log_error, _psqlSettings::popt, printQuery(), pset, and _psqlSettings::queryFout.

Referenced by PrintQueryResult().

◆ PrintTiming()

static void PrintTiming ( double  elapsed_msec)
static

Definition at line 501 of file common.c.

502 {
503  double seconds;
504  double minutes;
505  double hours;
506  double days;
507 
508  if (elapsed_msec < 1000.0)
509  {
510  /* This is the traditional (pre-v10) output format */
511  printf(_("Time: %.3f ms\n"), elapsed_msec);
512  return;
513  }
514 
515  /*
516  * Note: we could print just seconds, in a format like %06.3f, when the
517  * total is less than 1min. But that's hard to interpret unless we tack
518  * on "s" or otherwise annotate it. Forcing the display to include
519  * minutes seems like a better solution.
520  */
521  seconds = elapsed_msec / 1000.0;
522  minutes = floor(seconds / 60.0);
523  seconds -= 60.0 * minutes;
524  if (minutes < 60.0)
525  {
526  printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
527  elapsed_msec, (int) minutes, seconds);
528  return;
529  }
530 
531  hours = floor(minutes / 60.0);
532  minutes -= 60.0 * hours;
533  if (hours < 24.0)
534  {
535  printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
536  elapsed_msec, (int) hours, (int) minutes, seconds);
537  return;
538  }
539 
540  days = floor(hours / 24.0);
541  hours -= 24.0 * days;
542  printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
543  elapsed_msec, days, (int) hours, (int) minutes, seconds);
544 }
const char *const days[]
Definition: datetime.c:85
#define printf(...)
Definition: port.h:244

References _, days, and printf.

Referenced by PSQLexecWatch(), and SendQuery().

◆ psql_cancel_callback()

static void psql_cancel_callback ( void  )
static

Definition at line 258 of file common.c.

259 {
260 #ifndef WIN32
261  /* if we are waiting for input, longjmp out of it */
263  {
264  sigint_interrupt_enabled = false;
265  siglongjmp(sigint_interrupt_jmp, 1);
266  }
267 #endif
268 
269  /* else, set cancel flag to stop any long-running loops */
270  cancel_pressed = true;
271 }
volatile sig_atomic_t sigint_interrupt_enabled
Definition: common.c:253
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:255

References cancel_pressed, sigint_interrupt_enabled, and sigint_interrupt_jmp.

Referenced by psql_setup_cancel_handler().

◆ psql_get_variable()

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

Definition at line 137 of file common.c.

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

References appendShellStringNoError(), buf, conditional_active(), _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.

◆ psql_setup_cancel_handler()

void psql_setup_cancel_handler ( void  )

Definition at line 274 of file common.c.

275 {
277 }
static void setup_cancel_handler(void)
Definition: parallel.c:608
static void psql_cancel_callback(void)
Definition: common.c:258

References psql_cancel_callback(), and setup_cancel_handler().

Referenced by main().

◆ PSQLexec()

PGresult* PSQLexec ( const char *  query)

Definition at line 560 of file common.c.

561 {
562  PGresult *res;
563 
564  if (!pset.db)
565  {
566  pg_log_error("You are currently not connected to a database.");
567  return NULL;
568  }
569 
571  {
572  printf(_("********* QUERY **********\n"
573  "%s\n"
574  "**************************\n\n"), query);
575  fflush(stdout);
576  if (pset.logfile)
577  {
579  _("********* QUERY **********\n"
580  "%s\n"
581  "**************************\n\n"), query);
583  }
584 
586  return NULL;
587  }
588 
590 
591  res = PQexec(pset.db, query);
592 
593  ResetCancelConn();
594 
595  if (!AcceptResult(res, true))
596  {
598  res = NULL;
599  }
600 
601  return res;
602 }
@ PSQL_ECHO_HIDDEN_NOEXEC
Definition: settings.h:47
@ PSQL_ECHO_HIDDEN_OFF
Definition: settings.h:45
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:146

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

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

◆ PSQLexecWatch()

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

Definition at line 615 of file common.c.

616 {
617  bool timing = pset.timing;
618  double elapsed_msec = 0;
619  int res;
620 
621  if (!pset.db)
622  {
623  pg_log_error("You are currently not connected to a database.");
624  return 0;
625  }
626 
628 
629  res = ExecQueryAndProcessResults(query, &elapsed_msec, NULL, true, opt, printQueryFout);
630 
631  ResetCancelConn();
632 
633  /* Possible microtiming output */
634  if (timing)
635  PrintTiming(elapsed_msec);
636 
637  return res;
638 }
static int ExecQueryAndProcessResults(const char *query, double *elapsed_msec, bool *svpt_gone_p, bool is_watch, const printQueryOpt *opt, FILE *printQueryFout)
Definition: common.c:1396
static void PrintTiming(double elapsed_msec)
Definition: common.c:501

References _psqlSettings::db, ExecQueryAndProcessResults(), pg_log_error, PrintTiming(), pset, res, ResetCancelConn(), SetCancelConn(), and _psqlSettings::timing.

Referenced by do_watch().

◆ recognized_connection_string()

static bool recognized_connection_string ( const char *  connstr)

Definition at line 2404 of file common.c.

2405 {
2406  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2407 }
static int uri_prefix_length(const char *connstr)
Definition: common.c:2377
static char * connstr
Definition: pg_dumpall.c:88

References connstr, and uri_prefix_length().

Referenced by do_connect().

◆ SendQuery()

bool SendQuery ( const char *  query)

Definition at line 1022 of file common.c.

1023 {
1024  bool timing = pset.timing;
1025  PGTransactionStatusType transaction_status;
1026  double elapsed_msec = 0;
1027  bool OK = false;
1028  int i;
1029  bool on_error_rollback_savepoint = false;
1030  bool svpt_gone = false;
1031 
1032  if (!pset.db)
1033  {
1034  pg_log_error("You are currently not connected to a database.");
1035  goto sendquery_cleanup;
1036  }
1037 
1038  if (pset.singlestep)
1039  {
1040  char buf[3];
1041 
1042  fflush(stderr);
1043  printf(_("***(Single step mode: verify command)*******************************************\n"
1044  "%s\n"
1045  "***(press return to proceed or enter x and return to cancel)********************\n"),
1046  query);
1047  fflush(stdout);
1048  if (fgets(buf, sizeof(buf), stdin) != NULL)
1049  if (buf[0] == 'x')
1050  goto sendquery_cleanup;
1051  if (cancel_pressed)
1052  goto sendquery_cleanup;
1053  }
1054  else if (pset.echo == PSQL_ECHO_QUERIES)
1055  {
1056  puts(query);
1057  fflush(stdout);
1058  }
1059 
1060  if (pset.logfile)
1061  {
1063  _("********* QUERY **********\n"
1064  "%s\n"
1065  "**************************\n\n"), query);
1066  fflush(pset.logfile);
1067  }
1068 
1070 
1071  transaction_status = PQtransactionStatus(pset.db);
1072 
1073  if (transaction_status == PQTRANS_IDLE &&
1074  !pset.autocommit &&
1075  !command_no_begin(query))
1076  {
1077  PGresult *result;
1078 
1079  result = PQexec(pset.db, "BEGIN");
1080  if (PQresultStatus(result) != PGRES_COMMAND_OK)
1081  {
1083  ClearOrSaveResult(result);
1084  goto sendquery_cleanup;
1085  }
1086  ClearOrSaveResult(result);
1087  transaction_status = PQtransactionStatus(pset.db);
1088  }
1089 
1090  if (transaction_status == PQTRANS_INTRANS &&
1094  {
1095  PGresult *result;
1096 
1097  result = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1098  if (PQresultStatus(result) != PGRES_COMMAND_OK)
1099  {
1101  ClearOrSaveResult(result);
1102  goto sendquery_cleanup;
1103  }
1104  ClearOrSaveResult(result);
1105  on_error_rollback_savepoint = true;
1106  }
1107 
1108  if (pset.gdesc_flag)
1109  {
1110  /* Describe query's result columns, without executing it */
1111  OK = DescribeQuery(query, &elapsed_msec);
1112  }
1113  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1115  {
1116  /* Default fetch-it-all-and-print mode */
1117  OK = (ExecQueryAndProcessResults(query, &elapsed_msec, &svpt_gone, false, NULL, NULL) > 0);
1118  }
1119  else
1120  {
1121  /* Fetch-in-segments mode */
1122  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1123  }
1124 
1125  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1126  pg_log_info("STATEMENT: %s", query);
1127 
1128  /* If we made a temporary savepoint, possibly release/rollback */
1129  if (on_error_rollback_savepoint)
1130  {
1131  const char *svptcmd = NULL;
1132 
1133  transaction_status = PQtransactionStatus(pset.db);
1134 
1135  switch (transaction_status)
1136  {
1137  case PQTRANS_INERROR:
1138  /* We always rollback on an error */
1139  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1140  break;
1141 
1142  case PQTRANS_IDLE:
1143  /* If they are no longer in a transaction, then do nothing */
1144  break;
1145 
1146  case PQTRANS_INTRANS:
1147 
1148  /*
1149  * Release our savepoint, but do nothing if they are messing
1150  * with savepoints themselves
1151  */
1152  if (!svpt_gone)
1153  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1154  break;
1155 
1156  case PQTRANS_ACTIVE:
1157  case PQTRANS_UNKNOWN:
1158  default:
1159  OK = false;
1160  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1161  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1162  pg_log_error("unexpected transaction status (%d)",
1163  transaction_status);
1164  break;
1165  }
1166 
1167  if (svptcmd)
1168  {
1169  PGresult *svptres;
1170 
1171  svptres = PQexec(pset.db, svptcmd);
1172  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1173  {
1175  ClearOrSaveResult(svptres);
1176  OK = false;
1177 
1178  goto sendquery_cleanup;
1179  }
1180  PQclear(svptres);
1181  }
1182  }
1183 
1184  /* Possible microtiming output */
1185  if (timing)
1186  PrintTiming(elapsed_msec);
1187 
1188  /* check for events that may occur during query execution */
1189 
1190  if (pset.encoding != PQclientEncoding(pset.db) &&
1191  PQclientEncoding(pset.db) >= 0)
1192  {
1193  /* track effects of SET CLIENT_ENCODING */
1196  SetVariable(pset.vars, "ENCODING",
1198  }
1199 
1201 
1202  /* perform cleanup that should occur after any attempted query */
1203 
1204 sendquery_cleanup:
1205 
1206  /* global cancellation reset */
1207  ResetCancelConn();
1208 
1209  /* reset \g's output-to-filename trigger */
1210  if (pset.gfname)
1211  {
1212  free(pset.gfname);
1213  pset.gfname = NULL;
1214  }
1215 
1216  /* restore print settings if \g changed them */
1217  if (pset.gsavepopt)
1218  {
1220  pset.gsavepopt = NULL;
1221  }
1222 
1223  /* clean up after \bind */
1224  if (pset.bind_flag)
1225  {
1226  for (i = 0; i < pset.bind_nparams; i++)
1227  free(pset.bind_params[i]);
1229  pset.bind_params = NULL;
1230  pset.bind_flag = false;
1231  }
1232 
1233  /* reset \gset trigger */
1234  if (pset.gset_prefix)
1235  {
1237  pset.gset_prefix = NULL;
1238  }
1239 
1240  /* reset \gdesc trigger */
1241  pset.gdesc_flag = false;
1242 
1243  /* reset \gexec trigger */
1244  pset.gexec_flag = false;
1245 
1246  /* reset \crosstabview trigger */
1247  pset.crosstab_flag = false;
1248  for (i = 0; i < lengthof(pset.ctv_args); i++)
1249  {
1250  pg_free(pset.ctv_args[i]);
1251  pset.ctv_args[i] = NULL;
1252  }
1253 
1254  return OK;
1255 }
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1267
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1681
static void PrintNotifications(void)
Definition: common.c:645
static bool is_select_command(const char *query)
Definition: common.c:2221
static bool command_no_begin(const char *query)
Definition: common.c:2006
#define lengthof(array)
Definition: c.h:772
void restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
Definition: command.c:4846
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6820
void pg_free(void *ptr)
Definition: fe_memutils.c:105
PGTransactionStatusType
Definition: libpq-fe.h:117
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:119
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121
@ PSQL_ERROR_ROLLBACK_ON
Definition: settings.h:54
@ PSQL_ERROR_ROLLBACK_OFF
Definition: settings.h:52
@ PSQL_ECHO_ERRORS
Definition: settings.h:39
@ PSQL_ECHO_QUERIES
Definition: settings.h:38
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:147
bool autocommit
Definition: settings.h:135
char * ctv_args[4]
Definition: settings.h:103
printQueryOpt * gsavepopt
Definition: settings.h:94
bool gdesc_flag
Definition: settings.h:97
int encoding
Definition: print.h:133

References _, _psqlSettings::autocommit, _psqlSettings::bind_flag, _psqlSettings::bind_nparams, _psqlSettings::bind_params, 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, ExecQueryAndProcessResults(), ExecQueryUsingCursor(), _psqlSettings::fetch_count, fflush(), fprintf, free, _psqlSettings::gdesc_flag, _psqlSettings::gexec_flag, _psqlSettings::gfname, _psqlSettings::gsavepopt, _psqlSettings::gset_prefix, i, is_select_command(), lengthof, _psqlSettings::logfile, _psqlSettings::on_error_rollback, pg_encoding_to_char(), pg_free(), pg_log_error, pg_log_info, PGRES_COMMAND_OK, _psqlSettings::popt, PQclear(), PQclientEncoding(), PQerrorMessage(), PQexec(), PQresultStatus(), PQTRANS_ACTIVE, PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, PQtransactionStatus(), printf, PrintNotifications(), PrintTiming(), 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::timing, printQueryOpt::topt, and _psqlSettings::vars.

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

◆ session_username()

const char* session_username ( void  )

Definition at line 2298 of file common.c.

2299 {
2300  const char *val;
2301 
2302  if (!pset.db)
2303  return NULL;
2304 
2305  val = PQparameterStatus(pset.db, "session_authorization");
2306  if (val)
2307  return val;
2308  else
2309  return PQuser(pset.db);
2310 }
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6597

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

Referenced by get_prompt().

◆ setQFout()

bool setQFout ( const char *  fname)

Definition at line 93 of file common.c.

94 {
95  FILE *fout;
96  bool is_pipe;
97 
98  /* First make sure we can open the new output file/pipe */
99  if (!openQueryOutputFile(fname, &fout, &is_pipe))
100  return false;
101 
102  /* Close old file/pipe */
103  if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
104  {
105  if (pset.queryFoutPipe)
106  pclose(pset.queryFout);
107  else
108  fclose(pset.queryFout);
109  }
110 
111  pset.queryFout = fout;
112  pset.queryFoutPipe = is_pipe;
113 
114  /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
115  set_sigpipe_trap_state(is_pipe);
117 
118  return true;
119 }
void set_sigpipe_trap_state(bool ignore)
Definition: print.c:3074
bool queryFoutPipe
Definition: settings.h:85

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

◆ SetResultVariables()

static void SetResultVariables ( PGresult result,
bool  success 
)
static

Definition at line 421 of file common.c.

422 {
423  if (success)
424  {
425  const char *ntuples = PQcmdTuples(result);
426 
427  SetVariable(pset.vars, "ERROR", "false");
428  SetVariable(pset.vars, "SQLSTATE", "00000");
429  SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
430  }
431  else
432  {
433  const char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
434  const char *mesg = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
435 
436  SetVariable(pset.vars, "ERROR", "true");
437 
438  /*
439  * If there is no SQLSTATE code, use an empty string. This can happen
440  * for libpq-detected errors (e.g., lost connection, ENOMEM).
441  */
442  if (code == NULL)
443  code = "";
444  SetVariable(pset.vars, "SQLSTATE", code);
445  SetVariable(pset.vars, "ROW_COUNT", "0");
446  SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
447  SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
448  }
449 }
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3651
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3295
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57

References PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SQLSTATE, PQcmdTuples(), PQresultErrorField(), pset, SetVariable(), success, and _psqlSettings::vars.

Referenced by DescribeQuery(), ExecQueryAndProcessResults(), and ExecQueryUsingCursor().

◆ skip_white_space()

static const char* skip_white_space ( const char *  query)
static

Definition at line 1942 of file common.c.

1943 {
1944  int cnestlevel = 0; /* slash-star comment nest level */
1945 
1946  while (*query)
1947  {
1948  int mblen = PQmblenBounded(query, pset.encoding);
1949 
1950  /*
1951  * Note: we assume the encoding is a superset of ASCII, so that for
1952  * example "query[0] == '/'" is meaningful. However, we do NOT assume
1953  * that the second and subsequent bytes of a multibyte character
1954  * couldn't look like ASCII characters; so it is critical to advance
1955  * by mblen, not 1, whenever we haven't exactly identified the
1956  * character we are skipping over.
1957  */
1958  if (isspace((unsigned char) *query))
1959  query += mblen;
1960  else if (query[0] == '/' && query[1] == '*')
1961  {
1962  cnestlevel++;
1963  query += 2;
1964  }
1965  else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1966  {
1967  cnestlevel--;
1968  query += 2;
1969  }
1970  else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
1971  {
1972  query += 2;
1973 
1974  /*
1975  * We have to skip to end of line since any slash-star inside the
1976  * -- comment does NOT start a slash-star comment.
1977  */
1978  while (*query)
1979  {
1980  if (*query == '\n')
1981  {
1982  query++;
1983  break;
1984  }
1985  query += PQmblenBounded(query, pset.encoding);
1986  }
1987  }
1988  else if (cnestlevel > 0)
1989  query += mblen;
1990  else
1991  break; /* found first token */
1992  }
1993 
1994  return query;
1995 }

References _psqlSettings::encoding, PQmblenBounded(), and pset.

Referenced by command_no_begin(), and is_select_command().

◆ standard_strings()

bool standard_strings ( void  )

Definition at line 2278 of file common.c.

2279 {
2280  const char *val;
2281 
2282  if (!pset.db)
2283  return false;
2284 
2285  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2286 
2287  if (val && strcmp(val, "on") == 0)
2288  return true;
2289 
2290  return false;
2291 }

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

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

◆ StoreQueryTuple()

static bool StoreQueryTuple ( const PGresult result)
static

Definition at line 702 of file common.c.

703 {
704  bool success = true;
705 
706  if (PQntuples(result) < 1)
707  {
708  pg_log_error("no rows returned for \\gset");
709  success = false;
710  }
711  else if (PQntuples(result) > 1)
712  {
713  pg_log_error("more than one row returned for \\gset");
714  success = false;
715  }
716  else
717  {
718  int i;
719 
720  for (i = 0; i < PQnfields(result); i++)
721  {
722  char *colname = PQfname(result, i);
723  char *varname;
724  char *value;
725 
726  /* concatenate prefix and column name */
727  varname = psprintf("%s%s", pset.gset_prefix, colname);
728 
729  if (VariableHasHook(pset.vars, varname))
730  {
731  pg_log_warning("attempt to \\gset into specially treated variable \"%s\" ignored",
732  varname);
733  continue;
734  }
735 
736  if (!PQgetisnull(result, 0, i))
737  value = PQgetvalue(result, 0, i);
738  else
739  {
740  /* for NULL value, unset rather than set the variable */
741  value = NULL;
742  }
743 
744  if (!SetVariable(pset.vars, varname, value))
745  {
746  free(varname);
747  success = false;
748  break;
749  }
750 
751  free(varname);
752  }
753  }
754 
755  return success;
756 }
#define pg_log_warning(...)
Definition: pgfnames.c:24
bool VariableHasHook(VariableSpace space, const char *name)
Definition: variables.c:367

References free, _psqlSettings::gset_prefix, i, pg_log_error, pg_log_warning, PQfname(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), pset, psprintf(), SetVariable(), success, value, VariableHasHook(), and _psqlSettings::vars.

Referenced by ExecQueryUsingCursor(), and PrintQueryResult().

◆ uri_prefix_length()

static int uri_prefix_length ( const char *  connstr)
static

Definition at line 2377 of file common.c.

2378 {
2379  /* The connection URI must start with either of the following designators: */
2380  static const char uri_designator[] = "postgresql://";
2381  static const char short_uri_designator[] = "postgres://";
2382 
2383  if (strncmp(connstr, uri_designator,
2384  sizeof(uri_designator) - 1) == 0)
2385  return sizeof(uri_designator) - 1;
2386 
2387  if (strncmp(connstr, short_uri_designator,
2388  sizeof(short_uri_designator) - 1) == 0)
2389  return sizeof(short_uri_designator) - 1;
2390 
2391  return 0;
2392 }
static const char short_uri_designator[]
Definition: fe-connect.c:369
static const char uri_designator[]
Definition: fe-connect.c:368

References connstr, short_uri_designator, and uri_designator.

Referenced by recognized_connection_string().

Variable Documentation

◆ sigint_interrupt_enabled

volatile sig_atomic_t sigint_interrupt_enabled = false

◆ sigint_interrupt_jmp

sigjmp_buf sigint_interrupt_jmp