PostgreSQL Source Code  git master
pg_backup_db.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <ctype.h>
#include "common/connect.h"
#include "common/string.h"
#include "dumputils.h"
#include "fe_utils/string_utils.h"
#include "parallel.h"
#include "pg_backup_archiver.h"
#include "pg_backup_db.h"
#include "pg_backup_utils.h"
Include dependency graph for pg_backup_db.c:

Go to the source code of this file.

Functions

static void _check_database_version (ArchiveHandle *AH)
 
static void notice_processor (void *arg, const char *message)
 
void ReconnectToServer (ArchiveHandle *AH, const char *dbname)
 
void ConnectDatabase (Archive *AHX, const ConnParams *cparams, bool isReconnect)
 
void DisconnectDatabase (Archive *AHX)
 
PGconnGetConnection (Archive *AHX)
 
static void die_on_query_failure (ArchiveHandle *AH, const char *query)
 
void ExecuteSqlStatement (Archive *AHX, const char *query)
 
PGresultExecuteSqlQuery (Archive *AHX, const char *query, ExecStatusType status)
 
PGresultExecuteSqlQueryForSingleRow (Archive *fout, const char *query)
 
static void ExecuteSqlCommand (ArchiveHandle *AH, const char *qry, const char *desc)
 
static void ExecuteSimpleCommands (ArchiveHandle *AH, const char *buf, size_t bufLen)
 
int ExecuteSqlCommandBuf (Archive *AHX, const char *buf, size_t bufLen)
 
void EndDBCopyMode (Archive *AHX, const char *tocEntryTag)
 
void StartTransaction (Archive *AHX)
 
void CommitTransaction (Archive *AHX)
 
void IssueCommandPerBlob (ArchiveHandle *AH, TocEntry *te, const char *cmdBegin, const char *cmdEnd)
 
void IssueACLPerBlob (ArchiveHandle *AH, TocEntry *te)
 
void DropLOIfExists (ArchiveHandle *AH, Oid oid)
 

Function Documentation

◆ _check_database_version()

static void _check_database_version ( ArchiveHandle AH)
static

Definition at line 33 of file pg_backup_db.c.

34 {
35  const char *remoteversion_str;
36  int remoteversion;
37  PGresult *res;
38 
39  remoteversion_str = PQparameterStatus(AH->connection, "server_version");
40  remoteversion = PQserverVersion(AH->connection);
41  if (remoteversion == 0 || !remoteversion_str)
42  pg_fatal("could not get server_version from libpq");
43 
44  AH->public.remoteVersionStr = pg_strdup(remoteversion_str);
45  AH->public.remoteVersion = remoteversion;
46  if (!AH->archiveRemoteVersion)
48 
49  if (remoteversion != PG_VERSION_NUM
50  && (remoteversion < AH->public.minRemoteVersion ||
51  remoteversion > AH->public.maxRemoteVersion))
52  {
53  pg_log_error("aborting because of server version mismatch");
54  pg_log_error_detail("server version: %s; %s version: %s",
55  remoteversion_str, progname, PG_VERSION);
56  exit(1);
57  }
58 
59  /*
60  * Check if server is in recovery mode, which means we are on a hot
61  * standby.
62  */
64  "SELECT pg_catalog.pg_is_in_recovery()");
65  AH->public.isStandby = (strcmp(PQgetvalue(res, 0, 0), "t") == 0);
66  PQclear(res);
67 }
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7112
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7137
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_detail(...)
Definition: logging.h:109
const char * progname
Definition: main.c:44
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:305
#define pg_fatal(...)
int remoteVersion
Definition: pg_backup.h:219
char * remoteVersionStr
Definition: pg_backup.h:218
bool isStandby
Definition: pg_backup.h:220
int maxRemoteVersion
Definition: pg_backup.h:223

References _archiveHandle::archiveRemoteVersion, _archiveHandle::connection, ExecuteSqlQueryForSingleRow(), exit(), Archive::isStandby, Archive::maxRemoteVersion, pg_fatal, pg_log_error, pg_log_error_detail, pg_strdup(), PQclear(), PQgetvalue(), PQparameterStatus(), PQserverVersion(), progname, _archiveHandle::public, Archive::remoteVersion, Archive::remoteVersionStr, and res.

Referenced by ConnectDatabase().

◆ CommitTransaction()

void CommitTransaction ( Archive AHX)

Definition at line 537 of file pg_backup_db.c.

538 {
539  ArchiveHandle *AH = (ArchiveHandle *) AHX;
540 
541  ExecuteSqlCommand(AH, "COMMIT", "could not commit database transaction");
542 }
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:328

References ExecuteSqlCommand().

Referenced by IssueCommandPerBlob().

◆ ConnectDatabase()

void ConnectDatabase ( Archive AHX,
const ConnParams cparams,
bool  isReconnect 
)

Definition at line 110 of file pg_backup_db.c.

113 {
114  ArchiveHandle *AH = (ArchiveHandle *) AHX;
115  trivalue prompt_password;
116  char *password;
117  bool new_pass;
118 
119  if (AH->connection)
120  pg_fatal("already connected to a database");
121 
122  /* Never prompt for a password during a reconnection */
123  prompt_password = isReconnect ? TRI_NO : cparams->promptPassword;
124 
125  password = AH->savedPassword;
126 
127  if (prompt_password == TRI_YES && password == NULL)
128  password = simple_prompt("Password: ", false);
129 
130  /*
131  * Start the connection. Loop until we have a password if requested by
132  * backend.
133  */
134  do
135  {
136  const char *keywords[8];
137  const char *values[8];
138  int i = 0;
139 
140  /*
141  * If dbname is a connstring, its entries can override the other
142  * values obtained from cparams; but in turn, override_dbname can
143  * override the dbname component of it.
144  */
145  keywords[i] = "host";
146  values[i++] = cparams->pghost;
147  keywords[i] = "port";
148  values[i++] = cparams->pgport;
149  keywords[i] = "user";
150  values[i++] = cparams->username;
151  keywords[i] = "password";
152  values[i++] = password;
153  keywords[i] = "dbname";
154  values[i++] = cparams->dbname;
155  if (cparams->override_dbname)
156  {
157  keywords[i] = "dbname";
158  values[i++] = cparams->override_dbname;
159  }
160  keywords[i] = "fallback_application_name";
161  values[i++] = progname;
162  keywords[i] = NULL;
163  values[i++] = NULL;
164  Assert(i <= lengthof(keywords));
165 
166  new_pass = false;
167  AH->connection = PQconnectdbParams(keywords, values, true);
168 
169  if (!AH->connection)
170  pg_fatal("could not connect to database");
171 
172  if (PQstatus(AH->connection) == CONNECTION_BAD &&
174  password == NULL &&
175  prompt_password != TRI_NO)
176  {
177  PQfinish(AH->connection);
178  password = simple_prompt("Password: ", false);
179  new_pass = true;
180  }
181  } while (new_pass);
182 
183  /* check to see that the backend connection was successfully made */
184  if (PQstatus(AH->connection) == CONNECTION_BAD)
185  {
186  if (isReconnect)
187  pg_fatal("reconnection failed: %s",
189  else
190  pg_fatal("%s",
192  }
193 
194  /* Start strict; later phases may override this. */
197 
198  if (password && password != AH->savedPassword)
199  free(password);
200 
201  /*
202  * We want to remember connection's actual password, whether or not we got
203  * it by prompting. So we don't just store the password variable.
204  */
206  {
207  free(AH->savedPassword);
209  }
210 
211  /* check for version mismatch */
213 
215 
216  /* arrange for SIGINT to issue a query cancel on this connection */
218 }
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:730
static Datum values[MAXATTR]
Definition: bootstrap.c:152
#define Assert(condition)
Definition: c.h:858
#define lengthof(array)
Definition: c.h:788
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:689
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7213
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7198
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7147
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7094
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4868
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7009
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7326
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
@ CONNECTION_BAD
Definition: libpq-fe.h:62
static void _check_database_version(ArchiveHandle *AH)
Definition: pg_backup_db.c:33
static void notice_processor(void *arg, const char *message)
Definition: pg_backup_db.c:262
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static char * password
Definition: streamutil.c:54
char * override_dbname
Definition: pg_backup.h:91
char * pgport
Definition: pg_backup.h:85
char * pghost
Definition: pg_backup.h:86
trivalue promptPassword
Definition: pg_backup.h:88
char * username
Definition: pg_backup.h:87
char * dbname
Definition: pg_backup.h:84
trivalue
Definition: vacuumlo.c:35
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37

References _check_database_version(), ALWAYS_SECURE_SEARCH_PATH_SQL, Assert, _archiveHandle::connection, CONNECTION_BAD, _connParams::dbname, ExecuteSqlQueryForSingleRow(), free, i, lengthof, notice_processor(), _connParams::override_dbname, password, pg_fatal, pg_strdup(), _connParams::pghost, _connParams::pgport, PQclear(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQconnectionUsedPassword(), PQerrorMessage(), PQfinish(), PQpass(), PQsetNoticeProcessor(), PQstatus(), progname, _connParams::promptPassword, _archiveHandle::savedPassword, set_archive_cancel_info(), simple_prompt(), TRI_NO, TRI_YES, _connParams::username, and values.

Referenced by CloneArchive(), main(), ReconnectToServer(), restore_toc_entries_postfork(), and RestoreArchive().

◆ die_on_query_failure()

static void die_on_query_failure ( ArchiveHandle AH,
const char *  query 
)
static

Definition at line 269 of file pg_backup_db.c.

270 {
271  pg_log_error("query failed: %s",
273  pg_log_error_detail("Query was: %s", query);
274  exit(1);
275 }

References _archiveHandle::connection, exit(), pg_log_error, pg_log_error_detail, and PQerrorMessage().

Referenced by ExecuteSqlQuery(), and ExecuteSqlStatement().

◆ DisconnectDatabase()

void DisconnectDatabase ( Archive AHX)

Definition at line 225 of file pg_backup_db.c.

226 {
227  ArchiveHandle *AH = (ArchiveHandle *) AHX;
228  char errbuf[1];
229 
230  if (!AH->connection)
231  return;
232 
233  if (AH->connCancel)
234  {
235  /*
236  * If we have an active query, send a cancel before closing, ignoring
237  * any errors. This is of no use for a normal exit, but might be
238  * helpful during pg_fatal().
239  */
241  (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf));
242 
243  /*
244  * Prevent signal handler from sending a cancel after this.
245  */
246  set_archive_cancel_info(AH, NULL);
247  }
248 
249  PQfinish(AH->connection);
250  AH->connection = NULL;
251 }
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-cancel.c:462
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7102
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:123
PGcancel *volatile connCancel

References _archiveHandle::connCancel, _archiveHandle::connection, PQcancel(), PQfinish(), PQTRANS_ACTIVE, PQtransactionStatus(), and set_archive_cancel_info().

Referenced by archive_close_connection(), restore_toc_entries_prefork(), RestoreArchive(), and RunWorker().

◆ DropLOIfExists()

void DropLOIfExists ( ArchiveHandle AH,
Oid  oid 
)

Definition at line 673 of file pg_backup_db.c.

674 {
675  ahprintf(AH,
676  "SELECT pg_catalog.lo_unlink(oid) "
677  "FROM pg_catalog.pg_largeobject_metadata "
678  "WHERE oid = '%u';\n",
679  oid);
680 }
int ahprintf(ArchiveHandle *AH, const char *fmt,...)

References ahprintf().

Referenced by _StartLO(), RestoreArchive(), and StartRestoreLO().

◆ EndDBCopyMode()

void EndDBCopyMode ( Archive AHX,
const char *  tocEntryTag 
)

Definition at line 500 of file pg_backup_db.c.

501 {
502  ArchiveHandle *AH = (ArchiveHandle *) AHX;
503 
504  if (AH->pgCopyIn)
505  {
506  PGresult *res;
507 
508  if (PQputCopyEnd(AH->connection, NULL) <= 0)
509  pg_fatal("error returned by PQputCopyEnd: %s",
511 
512  /* Check command status and return to normal libpq state */
513  res = PQgetResult(AH->connection);
515  warn_or_exit_horribly(AH, "COPY failed for table \"%s\": %s",
516  tocEntryTag, PQerrorMessage(AH->connection));
517  PQclear(res);
518 
519  /* Do this to ensure we've pumped libpq back to idle state */
520  if (PQgetResult(AH->connection) != NULL)
521  pg_log_warning("unexpected extra results during COPY of table \"%s\"",
522  tocEntryTag);
523 
524  AH->pgCopyIn = false;
525  }
526 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2749
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
void warn_or_exit_horribly(ArchiveHandle *AH, const char *fmt,...)
#define pg_log_warning(...)
Definition: pgfnames.c:24

References _archiveHandle::connection, pg_fatal, pg_log_warning, _archiveHandle::pgCopyIn, PGRES_COMMAND_OK, PQclear(), PQerrorMessage(), PQgetResult(), PQputCopyEnd(), PQresultStatus(), res, and warn_or_exit_horribly().

Referenced by restore_toc_entry().

◆ ExecuteSimpleCommands()

static void ExecuteSimpleCommands ( ArchiveHandle AH,
const char *  buf,
size_t  bufLen 
)
static

Definition at line 380 of file pg_backup_db.c.

381 {
382  const char *qry = buf;
383  const char *eos = buf + bufLen;
384 
385  /* initialize command buffer if first time through */
386  if (AH->sqlparse.curCmd == NULL)
388 
389  for (; qry < eos; qry++)
390  {
391  char ch = *qry;
392 
393  /* For neatness, we skip any newlines between commands */
394  if (!(ch == '\n' && AH->sqlparse.curCmd->len == 0))
396 
397  switch (AH->sqlparse.state)
398  {
399  case SQL_SCAN: /* Default state == 0, set in _allocAH */
400  if (ch == ';')
401  {
402  /*
403  * We've found the end of a statement. Send it and reset
404  * the buffer.
405  */
407  "could not execute query");
409  }
410  else if (ch == '\'')
411  {
413  AH->sqlparse.backSlash = false;
414  }
415  else if (ch == '"')
416  {
418  }
419  break;
420 
421  case SQL_IN_SINGLE_QUOTE:
422  /* We needn't handle '' specially */
423  if (ch == '\'' && !AH->sqlparse.backSlash)
424  AH->sqlparse.state = SQL_SCAN;
425  else if (ch == '\\' && !AH->public.std_strings)
427  else
428  AH->sqlparse.backSlash = false;
429  break;
430 
431  case SQL_IN_DOUBLE_QUOTE:
432  /* We needn't handle "" specially */
433  if (ch == '"')
434  AH->sqlparse.state = SQL_SCAN;
435  break;
436  }
437  }
438 }
@ SQL_IN_DOUBLE_QUOTE
@ SQL_IN_SINGLE_QUOTE
@ SQL_SCAN
static char * buf
Definition: pg_test_fsync.c:73
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
bool std_strings
Definition: pg_backup.h:230
sqlparseInfo sqlparse
PQExpBuffer curCmd
sqlparseState state

References appendPQExpBufferChar(), sqlparseInfo::backSlash, buf, createPQExpBuffer(), sqlparseInfo::curCmd, PQExpBufferData::data, ExecuteSqlCommand(), PQExpBufferData::len, _archiveHandle::public, resetPQExpBuffer(), SQL_IN_DOUBLE_QUOTE, SQL_IN_SINGLE_QUOTE, SQL_SCAN, _archiveHandle::sqlparse, sqlparseInfo::state, and Archive::std_strings.

Referenced by ExecuteSqlCommandBuf().

◆ ExecuteSqlCommand()

static void ExecuteSqlCommand ( ArchiveHandle AH,
const char *  qry,
const char *  desc 
)
static

Definition at line 328 of file pg_backup_db.c.

329 {
330  PGconn *conn = AH->connection;
331  PGresult *res;
332 
333 #ifdef NOT_USED
334  fprintf(stderr, "Executing: '%s'\n\n", qry);
335 #endif
336  res = PQexec(conn, qry);
337 
338  switch (PQresultStatus(res))
339  {
340  case PGRES_COMMAND_OK:
341  case PGRES_TUPLES_OK:
342  case PGRES_EMPTY_QUERY:
343  /* A-OK */
344  break;
345  case PGRES_COPY_IN:
346  /* Assume this is an expected result */
347  AH->pgCopyIn = true;
348  break;
349  default:
350  /* trouble */
351  warn_or_exit_horribly(AH, "%s: %sCommand was: %s",
352  desc, PQerrorMessage(conn), qry);
353  break;
354  }
355 
356  PQclear(res);
357 }
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_COPY_IN
Definition: libpq-fe.h:107
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:99
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
#define fprintf
Definition: port.h:242
PGconn * conn
Definition: streamutil.c:55

References conn, _archiveHandle::connection, fprintf, _archiveHandle::pgCopyIn, PGRES_COMMAND_OK, PGRES_COPY_IN, PGRES_EMPTY_QUERY, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQexec(), PQresultStatus(), res, and warn_or_exit_horribly().

Referenced by CommitTransaction(), ExecuteSimpleCommands(), ExecuteSqlCommandBuf(), and StartTransaction().

◆ ExecuteSqlCommandBuf()

int ExecuteSqlCommandBuf ( Archive AHX,
const char *  buf,
size_t  bufLen 
)

Definition at line 445 of file pg_backup_db.c.

446 {
447  ArchiveHandle *AH = (ArchiveHandle *) AHX;
448 
449  if (AH->outputKind == OUTPUT_COPYDATA)
450  {
451  /*
452  * COPY data.
453  *
454  * We drop the data on the floor if libpq has failed to enter COPY
455  * mode; this allows us to behave reasonably when trying to continue
456  * after an error in a COPY command.
457  */
458  if (AH->pgCopyIn &&
459  PQputCopyData(AH->connection, buf, bufLen) <= 0)
460  pg_fatal("error returned by PQputCopyData: %s",
462  }
463  else if (AH->outputKind == OUTPUT_OTHERDATA)
464  {
465  /*
466  * Table data expressed as INSERT commands; or, in old dump files,
467  * BLOB COMMENTS data (which is expressed as COMMENT ON commands).
468  */
469  ExecuteSimpleCommands(AH, buf, bufLen);
470  }
471  else
472  {
473  /*
474  * General SQL commands; we assume that commands will not be split
475  * across calls.
476  *
477  * In most cases the data passed to us will be a null-terminated
478  * string, but if it's not, we have to add a trailing null.
479  */
480  if (buf[bufLen] == '\0')
481  ExecuteSqlCommand(AH, buf, "could not execute query");
482  else
483  {
484  char *str = (char *) pg_malloc(bufLen + 1);
485 
486  memcpy(str, buf, bufLen);
487  str[bufLen] = '\0';
488  ExecuteSqlCommand(AH, str, "could not execute query");
489  free(str);
490  }
491  }
492 
493  return bufLen;
494 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2695
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
const char * str
@ OUTPUT_COPYDATA
@ OUTPUT_OTHERDATA
static void ExecuteSimpleCommands(ArchiveHandle *AH, const char *buf, size_t bufLen)
Definition: pg_backup_db.c:380
ArchiverOutput outputKind

References buf, _archiveHandle::connection, ExecuteSimpleCommands(), ExecuteSqlCommand(), free, OUTPUT_COPYDATA, OUTPUT_OTHERDATA, _archiveHandle::outputKind, pg_fatal, pg_malloc(), _archiveHandle::pgCopyIn, PQerrorMessage(), PQputCopyData(), and str.

Referenced by ahwrite().

◆ ExecuteSqlQuery()

PGresult* ExecuteSqlQuery ( Archive AHX,
const char *  query,
ExecStatusType  status 
)

Definition at line 290 of file pg_backup_db.c.

291 {
292  ArchiveHandle *AH = (ArchiveHandle *) AHX;
293  PGresult *res;
294 
295  res = PQexec(AH->connection, query);
296  if (PQresultStatus(res) != status)
297  die_on_query_failure(AH, query);
298  return res;
299 }
static void die_on_query_failure(ArchiveHandle *AH, const char *query)
Definition: pg_backup_db.c:269

References _archiveHandle::connection, die_on_query_failure(), PQexec(), PQresultStatus(), and res.

Referenced by append_depends_on_extension(), buildMatViewRefreshDependencies(), collectComments(), collectRoleNames(), collectSecLabels(), createViewAsClause(), dumpCompositeType(), dumpDatabase(), dumpDatabaseConfig(), dumpEnumType(), dumpOpclass(), dumpOpfamily(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTSConfig(), dumpUserMappings(), ExecuteSqlQueryForSingleRow(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), and processExtensionTables().

◆ ExecuteSqlQueryForSingleRow()

PGresult* ExecuteSqlQueryForSingleRow ( Archive fout,
const char *  query 
)

Definition at line 305 of file pg_backup_db.c.

306 {
307  PGresult *res;
308  int ntups;
309 
310  res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
311 
312  /* Expecting a single result only */
313  ntups = PQntuples(res);
314  if (ntups != 1)
315  pg_fatal(ngettext("query returned %d row instead of one: %s",
316  "query returned %d rows instead of one: %s",
317  ntups),
318  ntups, query);
319 
320  return res;
321 }
#define ngettext(s, p, n)
Definition: c.h:1181
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
PGresult * ExecuteSqlQuery(Archive *AHX, const char *query, ExecStatusType status)
Definition: pg_backup_db.c:290

References ExecuteSqlQuery(), ngettext, pg_fatal, PGRES_TUPLES_OK, PQntuples(), and res.

Referenced by _check_database_version(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_type_oid(), ConnectDatabase(), convertTSFunction(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpSearchPath(), dumpStatisticsExt(), dumpTableAttach(), dumpTableSchema(), dumpTSConfig(), dumpTSDictionary(), expand_table_name_patterns(), get_language_name(), get_next_possible_free_pg_type_oid(), get_synchronized_snapshot(), getFormattedTypeName(), and setup_connection().

◆ ExecuteSqlStatement()

◆ GetConnection()

PGconn* GetConnection ( Archive AHX)

Definition at line 254 of file pg_backup_db.c.

255 {
256  ArchiveHandle *AH = (ArchiveHandle *) AHX;
257 
258  return AH->connection;
259 }

References _archiveHandle::connection.

◆ IssueACLPerBlob()

void IssueACLPerBlob ( ArchiveHandle AH,
TocEntry te 
)

Definition at line 599 of file pg_backup_db.c.

600 {
601  TocEntry *blobte = getTocEntryByDumpId(AH, te->dependencies[0]);
602  char *buf;
603  char *st;
604  char *st2;
605  char *en;
606  bool inquotes;
607 
608  if (!blobte)
609  pg_fatal("could not find entry for ID %d", te->dependencies[0]);
610  Assert(strcmp(blobte->desc, "BLOB METADATA") == 0);
611 
612  /* Make a writable copy of the ACL commands string */
613  buf = pg_strdup(te->defn);
614 
615  /*
616  * We have to parse out the commands sufficiently to locate the blob OIDs
617  * and find the command-ending semicolons. The commands should not
618  * contain anything hard to parse except for double-quoted role names,
619  * which are easy to ignore. Once we've split apart the first and second
620  * halves of a command, apply IssueCommandPerBlob. (This means the
621  * updates on the blobs are interleaved if there's multiple commands, but
622  * that should cause no trouble.)
623  */
624  inquotes = false;
625  st = en = buf;
626  st2 = NULL;
627  while (*en)
628  {
629  /* Ignore double-quoted material */
630  if (*en == '"')
631  inquotes = !inquotes;
632  if (inquotes)
633  {
634  en++;
635  continue;
636  }
637  /* If we found "LARGE OBJECT", that's the end of the first half */
638  if (strncmp(en, "LARGE OBJECT ", 13) == 0)
639  {
640  /* Terminate the first-half string */
641  en += 13;
642  Assert(isdigit((unsigned char) *en));
643  *en++ = '\0';
644  /* Skip the rest of the blob OID */
645  while (isdigit((unsigned char) *en))
646  en++;
647  /* Second half starts here */
648  Assert(st2 == NULL);
649  st2 = en;
650  }
651  /* If we found semicolon, that's the end of the second half */
652  else if (*en == ';')
653  {
654  /* Terminate the second-half string */
655  *en++ = '\0';
656  Assert(st2 != NULL);
657  /* Issue this command for each blob */
658  IssueCommandPerBlob(AH, blobte, st, st2);
659  /* For neatness, skip whitespace before the next command */
660  while (isspace((unsigned char) *en))
661  en++;
662  /* Reset for new command */
663  st = en;
664  st2 = NULL;
665  }
666  else
667  en++;
668  }
669  pg_free(buf);
670 }
void pg_free(void *ptr)
Definition: fe_memutils.c:105
TocEntry * getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
void IssueCommandPerBlob(ArchiveHandle *AH, TocEntry *te, const char *cmdBegin, const char *cmdEnd)
Definition: pg_backup_db.c:552
DumpId * dependencies

References Assert, buf, _tocEntry::defn, _tocEntry::dependencies, _tocEntry::desc, getTocEntryByDumpId(), IssueCommandPerBlob(), pg_fatal, pg_free(), and pg_strdup().

Referenced by _printTocEntry().

◆ IssueCommandPerBlob()

void IssueCommandPerBlob ( ArchiveHandle AH,
TocEntry te,
const char *  cmdBegin,
const char *  cmdEnd 
)

Definition at line 552 of file pg_backup_db.c.

554 {
555  /* Make a writable copy of the command string */
556  char *buf = pg_strdup(te->defn);
557  RestoreOptions *ropt = AH->public.ropt;
558  char *st;
559  char *en;
560 
561  st = buf;
562  while ((en = strchr(st, '\n')) != NULL)
563  {
564  *en++ = '\0';
565  ahprintf(AH, "%s%s%s;\n", cmdBegin, st, cmdEnd);
566 
567  /* In --transaction-size mode, count each command as an action */
568  if (ropt && ropt->txn_size > 0)
569  {
570  if (++AH->txnCount >= ropt->txn_size)
571  {
572  if (AH->connection)
573  {
575  StartTransaction(&AH->public);
576  }
577  else
578  ahprintf(AH, "COMMIT;\nBEGIN;\n\n");
579  AH->txnCount = 0;
580  }
581  }
582 
583  st = en;
584  }
585  ahprintf(AH, "\n");
586  pg_free(buf);
587 }
void StartTransaction(Archive *AHX)
Definition: pg_backup_db.c:529
void CommitTransaction(Archive *AHX)
Definition: pg_backup_db.c:537
RestoreOptions * ropt
Definition: pg_backup.h:215

References ahprintf(), buf, CommitTransaction(), _archiveHandle::connection, _tocEntry::defn, pg_free(), pg_strdup(), _archiveHandle::public, Archive::ropt, StartTransaction(), _restoreOptions::txn_size, and _archiveHandle::txnCount.

Referenced by _printTocEntry(), IssueACLPerBlob(), and RestoreArchive().

◆ notice_processor()

static void notice_processor ( void *  arg,
const char *  message 
)
static

Definition at line 262 of file pg_backup_db.c.

263 {
264  pg_log_info("%s", message);
265 }
#define pg_log_info(...)
Definition: logging.h:124

References pg_log_info.

Referenced by ConnectDatabase().

◆ ReconnectToServer()

void ReconnectToServer ( ArchiveHandle AH,
const char *  dbname 
)

Definition at line 74 of file pg_backup_db.c.

75 {
76  PGconn *oldConn = AH->connection;
77  RestoreOptions *ropt = AH->public.ropt;
78 
79  /*
80  * Save the dbname, if given, in override_dbname so that it will also
81  * affect any later reconnection attempt.
82  */
83  if (dbname)
85 
86  /*
87  * Note: we want to establish the new connection, and in particular update
88  * ArchiveHandle's connCancel, before closing old connection. Otherwise
89  * an ill-timed SIGINT could try to access a dead connection.
90  */
91  AH->connection = NULL; /* dodge error check in ConnectDatabase */
92 
93  ConnectDatabase((Archive *) AH, &ropt->cparams, true);
94 
95  PQfinish(oldConn);
96 }
void ConnectDatabase(Archive *AHX, const ConnParams *cparams, bool isReconnect)
Definition: pg_backup_db.c:110
char * dbname
Definition: streamutil.c:52
ConnParams cparams
Definition: pg_backup.h:144

References ConnectDatabase(), _archiveHandle::connection, _restoreOptions::cparams, dbname, _connParams::override_dbname, pg_strdup(), PQfinish(), _archiveHandle::public, and Archive::ropt.

Referenced by _reconnectToDB().

◆ StartTransaction()

void StartTransaction ( Archive AHX)

Definition at line 529 of file pg_backup_db.c.

530 {
531  ArchiveHandle *AH = (ArchiveHandle *) AHX;
532 
533  ExecuteSqlCommand(AH, "BEGIN", "could not start database transaction");
534 }

References ExecuteSqlCommand().

Referenced by IssueCommandPerBlob().