PostgreSQL Source Code  git master
pg_backup_db.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <ctype.h>
#include "dumputils.h"
#include "fe_utils/connect.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 PGconn_connectDB (ArchiveHandle *AH, const char *newdbname, const char *newUser)
 
static void notice_processor (void *arg, const char *message)
 
void ReconnectToServer (ArchiveHandle *AH, const char *dbname, const char *username)
 
void ConnectDatabase (Archive *AHX, const char *dbname, const char *pghost, const char *pgport, const char *username, trivalue prompt_password)
 
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 DropBlobIfExists (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.

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

Referenced by _connectDB(), and ConnectDatabase().

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  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("server version: %s; %s version: %s",
54  remoteversion_str, progname, PG_VERSION);
55  fatal("aborting because of server version mismatch");
56  }
57 
58  /*
59  * When running against 9.0 or later, check if we are in recovery mode,
60  * which means we are on a hot standby.
61  */
62  if (remoteversion >= 90000)
63  {
64  res = ExecuteSqlQueryForSingleRow((Archive *) AH, "SELECT pg_catalog.pg_is_in_recovery()");
65 
66  AH->public.isStandby = (strcmp(PQgetvalue(res, 0, 0), "t") == 0);
67  PQclear(res);
68  }
69  else
70  AH->public.isStandby = false;
71 }
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6652
#define pg_log_error(...)
Definition: logging.h:79
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6677
const char * progname
Definition: pg_standby.c:36
int maxRemoteVersion
Definition: pg_backup.h:191
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:416
bool isStandby
Definition: pg_backup.h:188
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define fatal(...)
char * remoteVersionStr
Definition: pg_backup.h:186
int remoteVersion
Definition: pg_backup.h:187

◆ _connectDB()

static PGconn * _connectDB ( ArchiveHandle AH,
const char *  newdbname,
const char *  newUser 
)
static

Definition at line 118 of file pg_backup_db.c.

References _check_database_version(), appendConnStrVal(), appendPQExpBufferStr(), _archiveHandle::connection, CONNECTION_BAD, connstr, PQExpBufferData::data, fatal, fprintf, free, initPQExpBuffer(), notice_processor(), password, pg_log_info, pg_strdup(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQconnectionUsedPassword(), PQdb(), PQerrorMessage(), PQfinish(), PQhost(), PQpass(), PQport(), PQsetNoticeProcessor(), PQstatus(), PQuser(), progname, _archiveHandle::promptPassword, _archiveHandle::savedPassword, simple_prompt(), termPQExpBuffer(), TRI_NO, TRI_YES, and values.

Referenced by ReconnectToServer().

119 {
121  PGconn *newConn;
122  const char *newdb;
123  const char *newuser;
124  char *password;
125  char passbuf[100];
126  bool new_pass;
127 
128  if (!reqdb)
129  newdb = PQdb(AH->connection);
130  else
131  newdb = reqdb;
132 
133  if (!requser || strlen(requser) == 0)
134  newuser = PQuser(AH->connection);
135  else
136  newuser = requser;
137 
138  pg_log_info("connecting to database \"%s\" as user \"%s\"",
139  newdb, newuser);
140 
141  password = AH->savedPassword;
142 
143  if (AH->promptPassword == TRI_YES && password == NULL)
144  {
145  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
146  password = passbuf;
147  }
148 
149  initPQExpBuffer(&connstr);
150  appendPQExpBufferStr(&connstr, "dbname=");
151  appendConnStrVal(&connstr, newdb);
152 
153  do
154  {
155  const char *keywords[7];
156  const char *values[7];
157 
158  keywords[0] = "host";
159  values[0] = PQhost(AH->connection);
160  keywords[1] = "port";
161  values[1] = PQport(AH->connection);
162  keywords[2] = "user";
163  values[2] = newuser;
164  keywords[3] = "password";
165  values[3] = password;
166  keywords[4] = "dbname";
167  values[4] = connstr.data;
168  keywords[5] = "fallback_application_name";
169  values[5] = progname;
170  keywords[6] = NULL;
171  values[6] = NULL;
172 
173  new_pass = false;
174  newConn = PQconnectdbParams(keywords, values, true);
175 
176  if (!newConn)
177  fatal("could not reconnect to database");
178 
179  if (PQstatus(newConn) == CONNECTION_BAD)
180  {
181  if (!PQconnectionNeedsPassword(newConn))
182  fatal("could not reconnect to database: %s",
183  PQerrorMessage(newConn));
184  PQfinish(newConn);
185 
186  if (password)
187  fprintf(stderr, "Password incorrect\n");
188 
189  fprintf(stderr, "Connecting to %s as %s\n",
190  newdb, newuser);
191 
192  if (AH->promptPassword != TRI_NO)
193  {
194  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
195  password = passbuf;
196  }
197  else
198  fatal("connection needs password");
199 
200  new_pass = true;
201  }
202  } while (new_pass);
203 
204  /*
205  * We want to remember connection's actual password, whether or not we got
206  * it by prompting. So we don't just store the password variable.
207  */
208  if (PQconnectionUsedPassword(newConn))
209  {
210  if (AH->savedPassword)
211  free(AH->savedPassword);
212  AH->savedPassword = pg_strdup(PQpass(newConn));
213  }
214 
215  termPQExpBuffer(&connstr);
216 
217  /* check for version mismatch */
219 
220  PQsetNoticeProcessor(newConn, notice_processor, NULL);
221 
222  return newConn;
223 }
static char password[100]
Definition: streamutil.c:53
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6863
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:545
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
char * PQport(const PGconn *conn)
Definition: fe-connect.c:6606
const char * progname
Definition: pg_standby.c:36
#define fprintf
Definition: port.h:197
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:640
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6545
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6553
static void notice_processor(void *arg, const char *message)
Definition: pg_backup_db.c:374
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6570
#define free(a)
Definition: header.h:65
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6537
#define fatal(...)
static Datum values[MAXATTR]
Definition: bootstrap.c:167
static void _check_database_version(ArchiveHandle *AH)
Definition: pg_backup_db.c:33
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6736
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6721
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6634
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define pg_log_info(...)
Definition: logging.h:87
static char * connstr
Definition: pg_dumpall.c:61

◆ CommitTransaction()

void CommitTransaction ( Archive AHX)

Definition at line 648 of file pg_backup_db.c.

References ExecuteSqlCommand().

649 {
650  ArchiveHandle *AH = (ArchiveHandle *) AHX;
651 
652  ExecuteSqlCommand(AH, "COMMIT", "could not commit database transaction");
653 }
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:439

◆ ConnectDatabase()

void ConnectDatabase ( Archive AHX,
const char *  dbname,
const char *  pghost,
const char *  pgport,
const char *  username,
trivalue  prompt_password 
)

Definition at line 236 of file pg_backup_db.c.

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

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

242 {
243  ArchiveHandle *AH = (ArchiveHandle *) AHX;
244  char *password;
245  char passbuf[100];
246  bool new_pass;
247 
248  if (AH->connection)
249  fatal("already connected to a database");
250 
251  password = AH->savedPassword;
252 
253  if (prompt_password == TRI_YES && password == NULL)
254  {
255  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
256  password = passbuf;
257  }
258  AH->promptPassword = prompt_password;
259 
260  /*
261  * Start the connection. Loop until we have a password if requested by
262  * backend.
263  */
264  do
265  {
266  const char *keywords[7];
267  const char *values[7];
268 
269  keywords[0] = "host";
270  values[0] = pghost;
271  keywords[1] = "port";
272  values[1] = pgport;
273  keywords[2] = "user";
274  values[2] = username;
275  keywords[3] = "password";
276  values[3] = password;
277  keywords[4] = "dbname";
278  values[4] = dbname;
279  keywords[5] = "fallback_application_name";
280  values[5] = progname;
281  keywords[6] = NULL;
282  values[6] = NULL;
283 
284  new_pass = false;
285  AH->connection = PQconnectdbParams(keywords, values, true);
286 
287  if (!AH->connection)
288  fatal("could not connect to database");
289 
290  if (PQstatus(AH->connection) == CONNECTION_BAD &&
292  password == NULL &&
293  prompt_password != TRI_NO)
294  {
295  PQfinish(AH->connection);
296  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
297  password = passbuf;
298  new_pass = true;
299  }
300  } while (new_pass);
301 
302  /* check to see that the backend connection was successfully made */
303  if (PQstatus(AH->connection) == CONNECTION_BAD)
304  fatal("connection to database \"%s\" failed: %s",
305  PQdb(AH->connection) ? PQdb(AH->connection) : "",
307 
308  /* Start strict; later phases may override this. */
311 
312  /*
313  * We want to remember connection's actual password, whether or not we got
314  * it by prompting. So we don't just store the password variable.
315  */
317  {
318  if (AH->savedPassword)
319  free(AH->savedPassword);
321  }
322 
323  /* check for version mismatch */
325 
327 
328  /* arrange for SIGINT to issue a query cancel on this connection */
330 }
static char password[100]
Definition: streamutil.c:53
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6863
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
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:640
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:416
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6553
static void notice_processor(void *arg, const char *message)
Definition: pg_backup_db.c:374
char * pghost
Definition: pgbench.c:242
static char * username
Definition: initdb.c:133
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define free(a)
Definition: header.h:65
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6537
char * dbname
Definition: streamutil.c:50
#define fatal(...)
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
static Datum values[MAXATTR]
Definition: bootstrap.c:167
static void _check_database_version(ArchiveHandle *AH)
Definition: pg_backup_db.c:33
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6736
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6721
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:749
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6634
char * pgport
Definition: pgbench.c:243

◆ die_on_query_failure()

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

Definition at line 381 of file pg_backup_db.c.

References _archiveHandle::connection, fatal, pg_log_error, and PQerrorMessage().

Referenced by ExecuteSqlQuery(), and ExecuteSqlStatement().

382 {
383  pg_log_error("query failed: %s",
385  fatal("query was: %s", query);
386 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
#define pg_log_error(...)
Definition: logging.h:79
#define fatal(...)

◆ DisconnectDatabase()

void DisconnectDatabase ( Archive AHX)

Definition at line 337 of file pg_backup_db.c.

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

338 {
339  ArchiveHandle *AH = (ArchiveHandle *) AHX;
340  char errbuf[1];
341 
342  if (!AH->connection)
343  return;
344 
345  if (AH->connCancel)
346  {
347  /*
348  * If we have an active query, send a cancel before closing, ignoring
349  * any errors. This is of no use for a normal exit, but might be
350  * helpful during fatal().
351  */
353  (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf));
354 
355  /*
356  * Prevent signal handler from sending a cancel after this.
357  */
358  set_archive_cancel_info(AH, NULL);
359  }
360 
361  PQfinish(AH->connection);
362  AH->connection = NULL;
363 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
PGcancel *volatile connCancel
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6642
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4461
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:749

◆ DropBlobIfExists()

void DropBlobIfExists ( ArchiveHandle AH,
Oid  oid 
)

Definition at line 656 of file pg_backup_db.c.

References ahprintf(), _archiveHandle::connection, and PQserverVersion().

Referenced by _StartBlob(), RestoreArchive(), and StartRestoreBlob().

657 {
658  /*
659  * If we are not restoring to a direct database connection, we have to
660  * guess about how to detect whether the blob exists. Assume new-style.
661  */
662  if (AH->connection == NULL ||
663  PQserverVersion(AH->connection) >= 90000)
664  {
665  ahprintf(AH,
666  "SELECT pg_catalog.lo_unlink(oid) "
667  "FROM pg_catalog.pg_largeobject_metadata "
668  "WHERE oid = '%u';\n",
669  oid);
670  }
671  else
672  {
673  /* Restoring to pre-9.0 server, so do it the old way */
674  ahprintf(AH,
675  "SELECT CASE WHEN EXISTS("
676  "SELECT 1 FROM pg_catalog.pg_largeobject WHERE loid = '%u'"
677  ") THEN pg_catalog.lo_unlink('%u') END;\n",
678  oid, oid);
679  }
680 }
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6677
int ahprintf(ArchiveHandle *AH, const char *fmt,...)

◆ EndDBCopyMode()

void EndDBCopyMode ( Archive AHX,
const char *  tocEntryTag 
)

Definition at line 611 of file pg_backup_db.c.

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

Referenced by restore_toc_entry().

612 {
613  ArchiveHandle *AH = (ArchiveHandle *) AHX;
614 
615  if (AH->pgCopyIn)
616  {
617  PGresult *res;
618 
619  if (PQputCopyEnd(AH->connection, NULL) <= 0)
620  fatal("error returned by PQputCopyEnd: %s",
622 
623  /* Check command status and return to normal libpq state */
624  res = PQgetResult(AH->connection);
625  if (PQresultStatus(res) != PGRES_COMMAND_OK)
626  warn_or_exit_horribly(AH, "COPY failed for table \"%s\": %s",
627  tocEntryTag, PQerrorMessage(AH->connection));
628  PQclear(res);
629 
630  /* Do this to ensure we've pumped libpq back to idle state */
631  if (PQgetResult(AH->connection) != NULL)
632  pg_log_warning("unexpected extra results during COPY of table \"%s\"",
633  tocEntryTag);
634 
635  AH->pgCopyIn = false;
636  }
637 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
void warn_or_exit_horribly(ArchiveHandle *AH, const char *fmt,...)
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2384
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define fatal(...)
#define pg_log_warning(...)
Definition: pgfnames.c:24
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778

◆ ExecuteSimpleCommands()

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

Definition at line 491 of file pg_backup_db.c.

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

492 {
493  const char *qry = buf;
494  const char *eos = buf + bufLen;
495 
496  /* initialize command buffer if first time through */
497  if (AH->sqlparse.curCmd == NULL)
499 
500  for (; qry < eos; qry++)
501  {
502  char ch = *qry;
503 
504  /* For neatness, we skip any newlines between commands */
505  if (!(ch == '\n' && AH->sqlparse.curCmd->len == 0))
507 
508  switch (AH->sqlparse.state)
509  {
510  case SQL_SCAN: /* Default state == 0, set in _allocAH */
511  if (ch == ';')
512  {
513  /*
514  * We've found the end of a statement. Send it and reset
515  * the buffer.
516  */
518  "could not execute query");
520  }
521  else if (ch == '\'')
522  {
524  AH->sqlparse.backSlash = false;
525  }
526  else if (ch == '"')
527  {
529  }
530  break;
531 
532  case SQL_IN_SINGLE_QUOTE:
533  /* We needn't handle '' specially */
534  if (ch == '\'' && !AH->sqlparse.backSlash)
535  AH->sqlparse.state = SQL_SCAN;
536  else if (ch == '\\' && !AH->public.std_strings)
538  else
539  AH->sqlparse.backSlash = false;
540  break;
541 
542  case SQL_IN_DOUBLE_QUOTE:
543  /* We needn't handle "" specially */
544  if (ch == '"')
545  AH->sqlparse.state = SQL_SCAN;
546  break;
547  }
548  }
549 }
PQExpBuffer curCmd
sqlparseState state
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:439
static char * buf
Definition: pg_test_fsync.c:67
sqlparseInfo sqlparse
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
bool std_strings
Definition: pg_backup.h:198

◆ ExecuteSqlCommand()

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

Definition at line 439 of file pg_backup_db.c.

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

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

440 {
441  PGconn *conn = AH->connection;
442  PGresult *res;
443 
444 #ifdef NOT_USED
445  fprintf(stderr, "Executing: '%s'\n\n", qry);
446 #endif
447  res = PQexec(conn, qry);
448 
449  switch (PQresultStatus(res))
450  {
451  case PGRES_COMMAND_OK:
452  case PGRES_TUPLES_OK:
453  case PGRES_EMPTY_QUERY:
454  /* A-OK */
455  break;
456  case PGRES_COPY_IN:
457  /* Assume this is an expected result */
458  AH->pgCopyIn = true;
459  break;
460  default:
461  /* trouble */
462  warn_or_exit_horribly(AH, "%s: %sCommand was: %s",
463  desc, PQerrorMessage(conn), qry);
464  break;
465  }
466 
467  PQclear(res);
468 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
void warn_or_exit_horribly(ArchiveHandle *AH, const char *fmt,...)
#define fprintf
Definition: port.h:197
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
PGconn * conn
Definition: streamutil.c:54
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939

◆ ExecuteSqlCommandBuf()

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

Definition at line 556 of file pg_backup_db.c.

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

Referenced by ahwrite().

557 {
558  ArchiveHandle *AH = (ArchiveHandle *) AHX;
559 
560  if (AH->outputKind == OUTPUT_COPYDATA)
561  {
562  /*
563  * COPY data.
564  *
565  * We drop the data on the floor if libpq has failed to enter COPY
566  * mode; this allows us to behave reasonably when trying to continue
567  * after an error in a COPY command.
568  */
569  if (AH->pgCopyIn &&
570  PQputCopyData(AH->connection, buf, bufLen) <= 0)
571  fatal("error returned by PQputCopyData: %s",
573  }
574  else if (AH->outputKind == OUTPUT_OTHERDATA)
575  {
576  /*
577  * Table data expressed as INSERT commands; or, in old dump files,
578  * BLOB COMMENTS data (which is expressed as COMMENT ON commands).
579  */
580  ExecuteSimpleCommands(AH, buf, bufLen);
581  }
582  else
583  {
584  /*
585  * General SQL commands; we assume that commands will not be split
586  * across calls.
587  *
588  * In most cases the data passed to us will be a null-terminated
589  * string, but if it's not, we have to add a trailing null.
590  */
591  if (buf[bufLen] == '\0')
592  ExecuteSqlCommand(AH, buf, "could not execute query");
593  else
594  {
595  char *str = (char *) pg_malloc(bufLen + 1);
596 
597  memcpy(str, buf, bufLen);
598  str[bufLen] = '\0';
599  ExecuteSqlCommand(AH, str, "could not execute query");
600  free(str);
601  }
602  }
603 
604  return bufLen;
605 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2317
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:439
static char * buf
Definition: pg_test_fsync.c:67
static void ExecuteSimpleCommands(ArchiveHandle *AH, const char *buf, size_t bufLen)
Definition: pg_backup_db.c:491
#define free(a)
Definition: header.h:65
#define fatal(...)
ArchiverOutput outputKind

◆ ExecuteSqlQuery()

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

Definition at line 401 of file pg_backup_db.c.

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

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

402 {
403  ArchiveHandle *AH = (ArchiveHandle *) AHX;
404  PGresult *res;
405 
406  res = PQexec(AH->connection, query);
407  if (PQresultStatus(res) != status)
408  die_on_query_failure(AH, query);
409  return res;
410 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static void die_on_query_failure(ArchiveHandle *AH, const char *query)
Definition: pg_backup_db.c:381
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

◆ ExecuteSqlQueryForSingleRow()

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

Definition at line 416 of file pg_backup_db.c.

References ExecuteSqlQuery(), fatal, ngettext, PGRES_TUPLES_OK, and PQntuples().

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

417 {
418  PGresult *res;
419  int ntups;
420 
421  res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
422 
423  /* Expecting a single result only */
424  ntups = PQntuples(res);
425  if (ntups != 1)
426  fatal(ngettext("query returned %d row instead of one: %s",
427  "query returned %d rows instead of one: %s",
428  ntups),
429  ntups, query);
430 
431  return res;
432 }
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
#define ngettext(s, p, n)
Definition: c.h:1146
#define fatal(...)
PGresult * ExecuteSqlQuery(Archive *AHX, const char *query, ExecStatusType status)
Definition: pg_backup_db.c:401

◆ ExecuteSqlStatement()

void ExecuteSqlStatement ( Archive AHX,
const char *  query 
)

Definition at line 389 of file pg_backup_db.c.

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

Referenced by dumpBlobs(), dumpTableData_insert(), expand_table_name_patterns(), getTables(), and setup_connection().

390 {
391  ArchiveHandle *AH = (ArchiveHandle *) AHX;
392  PGresult *res;
393 
394  res = PQexec(AH->connection, query);
395  if (PQresultStatus(res) != PGRES_COMMAND_OK)
396  die_on_query_failure(AH, query);
397  PQclear(res);
398 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
static void die_on_query_failure(ArchiveHandle *AH, const char *query)
Definition: pg_backup_db.c:381
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939

◆ GetConnection()

PGconn* GetConnection ( Archive AHX)

Definition at line 366 of file pg_backup_db.c.

References _archiveHandle::connection.

367 {
368  ArchiveHandle *AH = (ArchiveHandle *) AHX;
369 
370  return AH->connection;
371 }

◆ notice_processor()

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

Definition at line 374 of file pg_backup_db.c.

References pg_log_generic(), and PG_LOG_INFO.

Referenced by _connectDB(), and ConnectDatabase().

375 {
376  pg_log_generic(PG_LOG_INFO, "%s", message);
377 }
void pg_log_generic(enum pg_log_level level, const char *pg_restrict fmt,...)
Definition: logging.c:174

◆ ReconnectToServer()

void ReconnectToServer ( ArchiveHandle AH,
const char *  dbname,
const char *  username 
)

Definition at line 79 of file pg_backup_db.c.

References _connectDB(), ALWAYS_SECURE_SEARCH_PATH_SQL, _archiveHandle::connection, dbname, ExecuteSqlQueryForSingleRow(), PQclear(), PQdb(), PQfinish(), PQuser(), set_archive_cancel_info(), and username.

Referenced by _reconnectToDB().

80 {
81  PGconn *newConn;
82  const char *newdbname;
83  const char *newusername;
84 
85  if (!dbname)
86  newdbname = PQdb(AH->connection);
87  else
88  newdbname = dbname;
89 
90  if (!username)
91  newusername = PQuser(AH->connection);
92  else
93  newusername = username;
94 
95  newConn = _connectDB(AH, newdbname, newusername);
96 
97  /* Update ArchiveHandle's connCancel before closing old connection */
98  set_archive_cancel_info(AH, newConn);
99 
100  PQfinish(AH->connection);
101  AH->connection = newConn;
102 
103  /* Start strict; later phases may override this. */
106 }
static PGconn * _connectDB(ArchiveHandle *AH, const char *newdbname, const char *newUser)
Definition: pg_backup_db.c:118
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6545
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:416
static char * username
Definition: initdb.c:133
void PQclear(PGresult *res)
Definition: fe-exec.c:694
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6537
char * dbname
Definition: streamutil.c:50
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:749

◆ StartTransaction()

void StartTransaction ( Archive AHX)

Definition at line 640 of file pg_backup_db.c.

References ExecuteSqlCommand().

641 {
642  ArchiveHandle *AH = (ArchiveHandle *) AHX;
643 
644  ExecuteSqlCommand(AH, "BEGIN", "could not start database transaction");
645 }
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:439