PostgreSQL Source Code  git master
common.c File Reference
#include "postgres_fe.h"
#include <signal.h>
#include <unistd.h>
#include "common.h"
#include "common/logging.h"
#include "fe_utils/cancel.h"
#include "fe_utils/connect.h"
#include "fe_utils/string_utils.h"
Include dependency graph for common.c:

Go to the source code of this file.

Macros

#define ERRCODE_UNDEFINED_TABLE   "42P01"
 
#define PG_YESLETTER   gettext_noop("y")
 
#define PG_NOLETTER   gettext_noop("n")
 

Functions

void handle_help_version_opts (int argc, char *argv[], const char *fixed_progname, help_handler hlp)
 
PGconnconnectDatabase (const char *dbname, const char *pghost, const char *pgport, const char *pguser, enum trivalue prompt_password, const char *progname, bool echo, bool fail_ok, bool allow_password_reuse)
 
PGconnconnectMaintenanceDatabase (const char *maintenance_db, const char *pghost, const char *pgport, const char *pguser, enum trivalue prompt_password, const char *progname, bool echo)
 
void disconnectDatabase (PGconn *conn)
 
PGresultexecuteQuery (PGconn *conn, const char *query, bool echo)
 
void executeCommand (PGconn *conn, const char *query, bool echo)
 
bool executeMaintenanceCommand (PGconn *conn, const char *query, bool echo)
 
bool consumeQueryResult (PGconn *conn)
 
bool processQueryResult (PGconn *conn, PGresult *result)
 
void splitTableColumnsSpec (const char *spec, int encoding, char **table, const char **columns)
 
void appendQualifiedRelation (PQExpBuffer buf, const char *spec, PGconn *conn, bool echo)
 
bool yesno_prompt (const char *question)
 

Macro Definition Documentation

◆ ERRCODE_UNDEFINED_TABLE

#define ERRCODE_UNDEFINED_TABLE   "42P01"

Definition at line 26 of file common.c.

Referenced by processQueryResult().

◆ PG_NOLETTER

#define PG_NOLETTER   gettext_noop("n")

Definition at line 432 of file common.c.

Referenced by yesno_prompt().

◆ PG_YESLETTER

#define PG_YESLETTER   gettext_noop("y")

Definition at line 430 of file common.c.

Referenced by yesno_prompt().

Function Documentation

◆ appendQualifiedRelation()

void appendQualifiedRelation ( PQExpBuffer  buf,
const char *  spec,
PGconn conn,
bool  echo 
)

Definition at line 368 of file common.c.

References ALWAYS_SECURE_SEARCH_PATH_SQL, appendPQExpBufferStr(), appendStringLiteralConn(), PQExpBufferData::data, executeCommand(), executeQuery(), fmtQualifiedId(), initPQExpBuffer(), ngettext, pg_free(), pg_log_error, PQclear(), PQclientEncoding(), PQfinish(), PQgetvalue(), PQntuples(), splitTableColumnsSpec(), and termPQExpBuffer().

Referenced by cluster_one_database(), and run_reindex_command().

370 {
371  char *table;
372  const char *columns;
373  PQExpBufferData sql;
374  PGresult *res;
375  int ntups;
376 
377  splitTableColumnsSpec(spec, PQclientEncoding(conn), &table, &columns);
378 
379  /*
380  * Query must remain ABSOLUTELY devoid of unqualified names. This would
381  * be unnecessary given a regclassin() variant taking a search_path
382  * argument.
383  */
384  initPQExpBuffer(&sql);
386  "SELECT c.relname, ns.nspname\n"
387  " FROM pg_catalog.pg_class c,"
388  " pg_catalog.pg_namespace ns\n"
389  " WHERE c.relnamespace OPERATOR(pg_catalog.=) ns.oid\n"
390  " AND c.oid OPERATOR(pg_catalog.=) ");
391  appendStringLiteralConn(&sql, table, conn);
392  appendPQExpBufferStr(&sql, "::pg_catalog.regclass;");
393 
394  executeCommand(conn, "RESET search_path;", echo);
395 
396  /*
397  * One row is a typical result, as is a nonexistent relation ERROR.
398  * regclassin() unconditionally accepts all-digits input as an OID; if no
399  * relation has that OID; this query returns no rows. Catalog corruption
400  * might elicit other row counts.
401  */
402  res = executeQuery(conn, sql.data, echo);
403  ntups = PQntuples(res);
404  if (ntups != 1)
405  {
406  pg_log_error(ngettext("query returned %d row instead of one: %s",
407  "query returned %d rows instead of one: %s",
408  ntups),
409  ntups, sql.data);
410  PQfinish(conn);
411  exit(1);
412  }
414  fmtQualifiedId(PQgetvalue(res, 0, 1),
415  PQgetvalue(res, 0, 0)));
416  appendPQExpBufferStr(buf, columns);
417  PQclear(res);
418  termPQExpBuffer(&sql);
419  pg_free(table);
420 
422 }
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
PGresult * executeQuery(PGconn *conn, const char *query, bool echo)
Definition: common.c:203
void executeCommand(PGconn *conn, const char *query, bool echo)
Definition: common.c:228
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define pg_log_error(...)
Definition: logging.h:79
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4170
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6732
#define ngettext(s, p, n)
Definition: c.h:1152
void PQclear(PGresult *res)
Definition: fe-exec.c:694
const char * fmtQualifiedId(const char *schema, const char *id)
Definition: string_utils.c:145
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
void splitTableColumnsSpec(const char *spec, int encoding, char **table, const char **columns)
Definition: common.c:333
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ connectDatabase()

PGconn* connectDatabase ( const char *  dbname,
const char *  pghost,
const char *  pgport,
const char *  pguser,
enum trivalue  prompt_password,
const char *  progname,
bool  echo,
bool  fail_ok,
bool  allow_password_reuse 
)

Definition at line 64 of file common.c.

References ALWAYS_SECURE_SEARCH_PATH_SQL, conn, CONNECTION_BAD, dbname, executeQuery(), have_password, password, pg_log_error, pghost, pgport, PQclear(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQerrorMessage(), PQfinish(), PQstatus(), progname, simple_prompt(), TRI_NO, TRI_YES, and values.

Referenced by connectMaintenanceDatabase().

68 {
69  PGconn *conn;
70  bool new_pass;
71  static bool have_password = false;
72  static char password[100];
73 
74  if (!allow_password_reuse)
75  have_password = false;
76 
77  if (!have_password && prompt_password == TRI_YES)
78  {
79  simple_prompt("Password: ", password, sizeof(password), false);
80  have_password = true;
81  }
82 
83  /*
84  * Start the connection. Loop until we have a password if requested by
85  * backend.
86  */
87  do
88  {
89  const char *keywords[7];
90  const char *values[7];
91 
92  keywords[0] = "host";
93  values[0] = pghost;
94  keywords[1] = "port";
95  values[1] = pgport;
96  keywords[2] = "user";
97  values[2] = pguser;
98  keywords[3] = "password";
99  values[3] = have_password ? password : NULL;
100  keywords[4] = "dbname";
101  values[4] = dbname;
102  keywords[5] = "fallback_application_name";
103  values[5] = progname;
104  keywords[6] = NULL;
105  values[6] = NULL;
106 
107  new_pass = false;
108  conn = PQconnectdbParams(keywords, values, true);
109 
110  if (!conn)
111  {
112  pg_log_error("could not connect to database %s: out of memory",
113  dbname);
114  exit(1);
115  }
116 
117  /*
118  * No luck? Trying asking (again) for a password.
119  */
120  if (PQstatus(conn) == CONNECTION_BAD &&
122  prompt_password != TRI_NO)
123  {
124  PQfinish(conn);
125  simple_prompt("Password: ", password, sizeof(password), false);
126  have_password = true;
127  new_pass = true;
128  }
129  } while (new_pass);
130 
131  /* check to see that the backend connection was successfully made */
132  if (PQstatus(conn) == CONNECTION_BAD)
133  {
134  if (fail_ok)
135  {
136  PQfinish(conn);
137  return NULL;
138  }
139  pg_log_error("could not connect to database %s: %s",
140  dbname, PQerrorMessage(conn));
141  exit(1);
142  }
143 
145 
146  return conn;
147 }
static char password[100]
Definition: streamutil.c:53
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6672
PGresult * executeQuery(PGconn *conn, const char *query, bool echo)
Definition: common.c:203
#define pg_log_error(...)
Definition: logging.h:79
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4170
const char * progname
Definition: pg_standby.c:36
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:646
PGconn * conn
Definition: streamutil.c:54
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
char * pghost
Definition: pgbench.c:242
void PQclear(PGresult *res)
Definition: fe-exec.c:694
static bool have_password
Definition: streamutil.c:52
char * dbname
Definition: streamutil.c:50
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6706
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6619
char * pgport
Definition: pgbench.c:243

◆ connectMaintenanceDatabase()

PGconn* connectMaintenanceDatabase ( const char *  maintenance_db,
const char *  pghost,
const char *  pgport,
const char *  pguser,
enum trivalue  prompt_password,
const char *  progname,
bool  echo 
)

Definition at line 153 of file common.c.

References conn, and connectDatabase().

Referenced by cluster_all_databases(), main(), reindex_all_databases(), and vacuum_all_databases().

157 {
158  PGconn *conn;
159 
160  /* If a maintenance database name was specified, just connect to it. */
161  if (maintenance_db)
162  return connectDatabase(maintenance_db, pghost, pgport, pguser,
163  prompt_password, progname, echo, false, false);
164 
165  /* Otherwise, try postgres first and then template1. */
166  conn = connectDatabase("postgres", pghost, pgport, pguser, prompt_password,
167  progname, echo, true, false);
168  if (!conn)
169  conn = connectDatabase("template1", pghost, pgport, pguser,
170  prompt_password, progname, echo, false, false);
171 
172  return conn;
173 }
const char * progname
Definition: pg_standby.c:36
PGconn * conn
Definition: streamutil.c:54
char * pghost
Definition: pgbench.c:242
PGconn * connectDatabase(const char *dbname, const char *pghost, const char *pgport, const char *pguser, enum trivalue prompt_password, const char *progname, bool echo, bool fail_ok, bool allow_password_reuse)
Definition: common.c:64
char * pgport
Definition: pgbench.c:243

◆ consumeQueryResult()

bool consumeQueryResult ( PGconn conn)

Definition at line 281 of file common.c.

References PQgetResult(), processQueryResult(), ResetCancelConn(), and SetCancelConn().

Referenced by ParallelSlotsWaitCompletion().

282 {
283  bool ok = true;
284  PGresult *result;
285 
286  SetCancelConn(conn);
287  while ((result = PQgetResult(conn)) != NULL)
288  {
289  if (!processQueryResult(conn, result))
290  ok = false;
291  }
292  ResetCancelConn();
293  return ok;
294 }
bool processQueryResult(PGconn *conn, PGresult *result)
Definition: common.c:302
void ResetCancelConn(void)
Definition: cancel.c:100
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778

◆ disconnectDatabase()

void disconnectDatabase ( PGconn conn)

Definition at line 179 of file common.c.

References Assert, PQcancel(), PQfinish(), PQfreeCancel(), PQgetCancel(), PQTRANS_ACTIVE, and PQtransactionStatus().

Referenced by ParallelSlotsTerminate().

180 {
181  char errbuf[256];
182 
183  Assert(conn != NULL);
184 
185  if (PQtransactionStatus(conn) == PQTRANS_ACTIVE)
186  {
187  PGcancel *cancel;
188 
189  if ((cancel = PQgetCancel(conn)))
190  {
191  (void) PQcancel(cancel, errbuf, sizeof(errbuf));
192  PQfreeCancel(cancel);
193  }
194  }
195 
196  PQfinish(conn);
197 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4314
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4170
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4291
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6627
#define Assert(condition)
Definition: c.h:745
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4446

◆ executeCommand()

void executeCommand ( PGconn conn,
const char *  query,
bool  echo 
)

Definition at line 228 of file common.c.

References pg_log_error, pg_log_info, PGRES_COMMAND_OK, PQclear(), PQerrorMessage(), PQexec(), PQfinish(), PQresultStatus(), and printf.

Referenced by appendQualifiedRelation().

229 {
230  PGresult *res;
231 
232  if (echo)
233  printf("%s\n", query);
234 
235  res = PQexec(conn, query);
236  if (!res ||
238  {
239  pg_log_error("query failed: %s", PQerrorMessage(conn));
240  pg_log_info("query was: %s", query);
241  PQfinish(conn);
242  exit(1);
243  }
244 
245  PQclear(res);
246 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6672
#define pg_log_error(...)
Definition: logging.h:79
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4170
#define printf(...)
Definition: port.h:199
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
#define pg_log_info(...)
Definition: logging.h:87

◆ executeMaintenanceCommand()

bool executeMaintenanceCommand ( PGconn conn,
const char *  query,
bool  echo 
)

Definition at line 255 of file common.c.

References PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), printf, ResetCancelConn(), and SetCancelConn().

Referenced by cluster_one_database(), and run_reindex_command().

256 {
257  PGresult *res;
258  bool r;
259 
260  if (echo)
261  printf("%s\n", query);
262 
263  SetCancelConn(conn);
264  res = PQexec(conn, query);
265  ResetCancelConn();
266 
267  r = (res && PQresultStatus(res) == PGRES_COMMAND_OK);
268 
269  if (res)
270  PQclear(res);
271 
272  return r;
273 }
void ResetCancelConn(void)
Definition: cancel.c:100
#define printf(...)
Definition: port.h:199
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939

◆ executeQuery()

PGresult* executeQuery ( PGconn conn,
const char *  query,
bool  echo 
)

Definition at line 203 of file common.c.

References pg_log_error, pg_log_info, PGRES_TUPLES_OK, PQerrorMessage(), PQexec(), PQfinish(), PQresultStatus(), and printf.

Referenced by appendQualifiedRelation(), and connectDatabase().

204 {
205  PGresult *res;
206 
207  if (echo)
208  printf("%s\n", query);
209 
210  res = PQexec(conn, query);
211  if (!res ||
213  {
214  pg_log_error("query failed: %s", PQerrorMessage(conn));
215  pg_log_info("query was: %s", query);
216  PQfinish(conn);
217  exit(1);
218  }
219 
220  return res;
221 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6672
#define pg_log_error(...)
Definition: logging.h:79
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4170
#define printf(...)
Definition: port.h:199
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
#define pg_log_info(...)
Definition: logging.h:87

◆ handle_help_version_opts()

void handle_help_version_opts ( int  argc,
char *  argv[],
const char *  fixed_progname,
help_handler  hlp 
)

Definition at line 33 of file common.c.

References get_progname(), and printf.

Referenced by main().

35 {
36  if (argc > 1)
37  {
38  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
39  {
40  hlp(get_progname(argv[0]));
41  exit(0);
42  }
43  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
44  {
45  printf("%s (PostgreSQL) " PG_VERSION "\n", fixed_progname);
46  exit(0);
47  }
48  }
49 }
const char * get_progname(const char *argv0)
Definition: path.c:453
#define printf(...)
Definition: port.h:199

◆ processQueryResult()

bool processQueryResult ( PGconn conn,
PGresult result 
)

Definition at line 302 of file common.c.

References ERRCODE_UNDEFINED_TABLE, PG_DIAG_SQLSTATE, pg_log_error, PGRES_COMMAND_OK, PQclear(), PQdb(), PQerrorMessage(), PQresultErrorField(), and PQresultStatus().

Referenced by consumeQueryResult(), and ParallelSlotsGetIdle().

303 {
304  /*
305  * If it's an error, report it. Errors about a missing table are harmless
306  * so we continue processing; but die for other errors.
307  */
308  if (PQresultStatus(result) != PGRES_COMMAND_OK)
309  {
310  char *sqlState = PQresultErrorField(result, PG_DIAG_SQLSTATE);
311 
312  pg_log_error("processing of database \"%s\" failed: %s",
313  PQdb(conn), PQerrorMessage(conn));
314 
315  if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) != 0)
316  {
317  PQclear(result);
318  return false;
319  }
320  }
321 
322  PQclear(result);
323  return true;
324 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6672
#define pg_log_error(...)
Definition: logging.h:79
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
#define ERRCODE_UNDEFINED_TABLE
Definition: common.c:26
void PQclear(PGresult *res)
Definition: fe-exec.c:694
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6522
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2754

◆ splitTableColumnsSpec()

void splitTableColumnsSpec ( const char *  spec,
int  encoding,
char **  table,
const char **  columns 
)

Definition at line 333 of file common.c.

References pnstrdup(), and PQmblen().

Referenced by appendQualifiedRelation(), and vacuum_one_database().

335 {
336  bool inquotes = false;
337  const char *cp = spec;
338 
339  /*
340  * Find the first '(' not identifier-quoted. Based on
341  * dequote_downcase_identifier().
342  */
343  while (*cp && (*cp != '(' || inquotes))
344  {
345  if (*cp == '"')
346  {
347  if (inquotes && cp[1] == '"')
348  cp++; /* pair does not affect quoting */
349  else
350  inquotes = !inquotes;
351  cp++;
352  }
353  else
354  cp += PQmblen(cp, encoding);
355  }
356  *table = pnstrdup(spec, cp - spec);
357  *columns = cp;
358 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
int32 encoding
Definition: pg_database.h:41
int PQmblen(const char *s, int encoding)
Definition: fe-misc.c:1221

◆ yesno_prompt()

bool yesno_prompt ( const char *  question)

Definition at line 435 of file common.c.

References _, PG_NOLETTER, PG_YESLETTER, printf, simple_prompt(), and snprintf.

Referenced by main().

436 {
437  char prompt[256];
438 
439  /*------
440  translator: This is a question followed by the translated options for
441  "yes" and "no". */
442  snprintf(prompt, sizeof(prompt), _("%s (%s/%s) "),
443  _(question), _(PG_YESLETTER), _(PG_NOLETTER));
444 
445  for (;;)
446  {
447  char resp[10];
448 
449  simple_prompt(prompt, resp, sizeof(resp), true);
450 
451  if (strcmp(resp, _(PG_YESLETTER)) == 0)
452  return true;
453  if (strcmp(resp, _(PG_NOLETTER)) == 0)
454  return false;
455 
456  printf(_("Please answer \"%s\" or \"%s\".\n"),
458  }
459 }
#define PG_YESLETTER
Definition: common.c:430
#define printf(...)
Definition: port.h:199
#define PG_NOLETTER
Definition: common.c:432
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88