PostgreSQL Source Code  git master
pg_backup_db.c File Reference
#include "postgres_fe.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 <unistd.h>
#include <ctype.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 *modulename, 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)
 

Variables

static const char * modulename = gettext_noop("archiver (db)")
 

Function Documentation

◆ _check_database_version()

static void _check_database_version ( ArchiveHandle AH)
static

Definition at line 37 of file pg_backup_db.c.

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

Referenced by _connectDB(), and ConnectDatabase().

38 {
39  const char *remoteversion_str;
40  int remoteversion;
41  PGresult *res;
42 
43  remoteversion_str = PQparameterStatus(AH->connection, "server_version");
44  remoteversion = PQserverVersion(AH->connection);
45  if (remoteversion == 0 || !remoteversion_str)
46  exit_horribly(modulename, "could not get server_version from libpq\n");
47 
48  AH->public.remoteVersionStr = pg_strdup(remoteversion_str);
49  AH->public.remoteVersion = remoteversion;
50  if (!AH->archiveRemoteVersion)
52 
53  if (remoteversion != PG_VERSION_NUM
54  && (remoteversion < AH->public.minRemoteVersion ||
55  remoteversion > AH->public.maxRemoteVersion))
56  {
57  write_msg(NULL, "server version: %s; %s version: %s\n",
58  remoteversion_str, progname, PG_VERSION);
59  exit_horribly(NULL, "aborting because of server version mismatch\n");
60  }
61 
62  /*
63  * When running against 9.0 or later, check if we are in recovery mode,
64  * which means we are on a hot standby.
65  */
66  if (remoteversion >= 90000)
67  {
68  res = ExecuteSqlQueryForSingleRow((Archive *) AH, "SELECT pg_catalog.pg_is_in_recovery()");
69 
70  AH->public.isStandby = (strcmp(PQgetvalue(res, 0, 0), "t") == 0);
71  PQclear(res);
72  }
73  else
74  AH->public.isStandby = false;
75 }
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3118
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6081
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6106
const char * progname
Definition: pg_standby.c:37
int maxRemoteVersion
Definition: pg_backup.h:192
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:420
bool isStandby
Definition: pg_backup.h:189
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static const char * modulename
Definition: pg_backup_db.c:30
void PQclear(PGresult *res)
Definition: fe-exec.c:671
void write_msg(const char *modulename, const char *fmt,...)
void exit_horribly(const char *modulename, const char *fmt,...)
char * remoteVersionStr
Definition: pg_backup.h:187
int remoteVersion
Definition: pg_backup.h:188

◆ _connectDB()

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

Definition at line 122 of file pg_backup_db.c.

References _check_database_version(), ahlog(), appendConnStrVal(), appendPQExpBuffer(), _archiveHandle::connection, CONNECTION_BAD, connstr, PQExpBufferData::data, exit_horribly(), free, initPQExpBuffer(), modulename, notice_processor(), password, 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().

123 {
125  PGconn *newConn;
126  const char *newdb;
127  const char *newuser;
128  char *password;
129  char passbuf[100];
130  bool new_pass;
131 
132  if (!reqdb)
133  newdb = PQdb(AH->connection);
134  else
135  newdb = reqdb;
136 
137  if (!requser || strlen(requser) == 0)
138  newuser = PQuser(AH->connection);
139  else
140  newuser = requser;
141 
142  ahlog(AH, 1, "connecting to database \"%s\" as user \"%s\"\n",
143  newdb, newuser);
144 
145  password = AH->savedPassword;
146 
147  if (AH->promptPassword == TRI_YES && password == NULL)
148  {
149  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
150  password = passbuf;
151  }
152 
153  initPQExpBuffer(&connstr);
154  appendPQExpBuffer(&connstr, "dbname=");
155  appendConnStrVal(&connstr, newdb);
156 
157  do
158  {
159  const char *keywords[7];
160  const char *values[7];
161 
162  keywords[0] = "host";
163  values[0] = PQhost(AH->connection);
164  keywords[1] = "port";
165  values[1] = PQport(AH->connection);
166  keywords[2] = "user";
167  values[2] = newuser;
168  keywords[3] = "password";
169  values[3] = password;
170  keywords[4] = "dbname";
171  values[4] = connstr.data;
172  keywords[5] = "fallback_application_name";
173  values[5] = progname;
174  keywords[6] = NULL;
175  values[6] = NULL;
176 
177  new_pass = false;
178  newConn = PQconnectdbParams(keywords, values, true);
179 
180  if (!newConn)
181  exit_horribly(modulename, "failed to reconnect to database\n");
182 
183  if (PQstatus(newConn) == CONNECTION_BAD)
184  {
185  if (!PQconnectionNeedsPassword(newConn))
186  exit_horribly(modulename, "could not reconnect to database: %s",
187  PQerrorMessage(newConn));
188  PQfinish(newConn);
189 
190  if (password)
191  fprintf(stderr, "Password incorrect\n");
192 
193  fprintf(stderr, "Connecting to %s as %s\n",
194  newdb, newuser);
195 
196  if (AH->promptPassword != TRI_NO)
197  {
198  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
199  password = passbuf;
200  }
201  else
202  exit_horribly(modulename, "connection needs password\n");
203 
204  new_pass = true;
205  }
206  } while (new_pass);
207 
208  /*
209  * We want to remember connection's actual password, whether or not we got
210  * it by prompting. So we don't just store the password variable.
211  */
212  if (PQconnectionUsedPassword(newConn))
213  {
214  if (AH->savedPassword)
215  free(AH->savedPassword);
216  AH->savedPassword = pg_strdup(PQpass(newConn));
217  }
218 
219  termPQExpBuffer(&connstr);
220 
221  /* check for version mismatch */
223 
224  PQsetNoticeProcessor(newConn, notice_processor, NULL);
225 
226  return newConn;
227 }
static char password[100]
Definition: streamutil.c:54
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6292
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:551
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3638
char * PQport(const PGconn *conn)
Definition: fe-connect.c:6035
const char * progname
Definition: pg_standby.c:37
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:536
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5991
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
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:5999
static void notice_processor(void *arg, const char *message)
Definition: pg_backup_db.c:378
static const char * modulename
Definition: pg_backup_db.c:30
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:6016
#define free(a)
Definition: header.h:65
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5983
void exit_horribly(const char *modulename, const char *fmt,...)
static Datum values[MAXATTR]
Definition: bootstrap.c:164
static void _check_database_version(ArchiveHandle *AH)
Definition: pg_backup_db.c:37
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6165
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6150
void ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6063
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static char * connstr
Definition: pg_dumpall.c:59

◆ CommitTransaction()

void CommitTransaction ( Archive AHX)

Definition at line 653 of file pg_backup_db.c.

References ExecuteSqlCommand().

654 {
655  ArchiveHandle *AH = (ArchiveHandle *) AHX;
656 
657  ExecuteSqlCommand(AH, "COMMIT", "could not commit database transaction");
658 }
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:444

◆ ConnectDatabase()

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

Definition at line 240 of file pg_backup_db.c.

References _check_database_version(), ALWAYS_SECURE_SEARCH_PATH_SQL, _archiveHandle::connection, CONNECTION_BAD, dbname, ExecuteSqlQueryForSingleRow(), exit_horribly(), free, modulename, 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().

246 {
247  ArchiveHandle *AH = (ArchiveHandle *) AHX;
248  char *password;
249  char passbuf[100];
250  bool new_pass;
251 
252  if (AH->connection)
253  exit_horribly(modulename, "already connected to a database\n");
254 
255  password = AH->savedPassword;
256 
257  if (prompt_password == TRI_YES && password == NULL)
258  {
259  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
260  password = passbuf;
261  }
262  AH->promptPassword = prompt_password;
263 
264  /*
265  * Start the connection. Loop until we have a password if requested by
266  * backend.
267  */
268  do
269  {
270  const char *keywords[7];
271  const char *values[7];
272 
273  keywords[0] = "host";
274  values[0] = pghost;
275  keywords[1] = "port";
276  values[1] = pgport;
277  keywords[2] = "user";
278  values[2] = username;
279  keywords[3] = "password";
280  values[3] = password;
281  keywords[4] = "dbname";
282  values[4] = dbname;
283  keywords[5] = "fallback_application_name";
284  values[5] = progname;
285  keywords[6] = NULL;
286  values[6] = NULL;
287 
288  new_pass = false;
289  AH->connection = PQconnectdbParams(keywords, values, true);
290 
291  if (!AH->connection)
292  exit_horribly(modulename, "failed to connect to database\n");
293 
294  if (PQstatus(AH->connection) == CONNECTION_BAD &&
296  password == NULL &&
297  prompt_password != TRI_NO)
298  {
299  PQfinish(AH->connection);
300  simple_prompt("Password: ", passbuf, sizeof(passbuf), false);
301  password = passbuf;
302  new_pass = true;
303  }
304  } while (new_pass);
305 
306  /* check to see that the backend connection was successfully made */
307  if (PQstatus(AH->connection) == CONNECTION_BAD)
308  exit_horribly(modulename, "connection to database \"%s\" failed: %s",
309  PQdb(AH->connection) ? PQdb(AH->connection) : "",
311 
312  /* Start strict; later phases may override this. */
315 
316  /*
317  * We want to remember connection's actual password, whether or not we got
318  * it by prompting. So we don't just store the password variable.
319  */
321  {
322  if (AH->savedPassword)
323  free(AH->savedPassword);
325  }
326 
327  /* check for version mismatch */
329 
331 
332  /* arrange for SIGINT to issue a query cancel on this connection */
334 }
static char password[100]
Definition: streamutil.c:54
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6292
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3638
const char * progname
Definition: pg_standby.c:37
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:536
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:420
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:5999
static void notice_processor(void *arg, const char *message)
Definition: pg_backup_db.c:378
char * pghost
Definition: pgbench.c:193
static const char * modulename
Definition: pg_backup_db.c:30
static char * username
Definition: initdb.c:132
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define free(a)
Definition: header.h:65
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5983
char * dbname
Definition: streamutil.c:51
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
void exit_horribly(const char *modulename, const char *fmt,...)
static Datum values[MAXATTR]
Definition: bootstrap.c:164
static void _check_database_version(ArchiveHandle *AH)
Definition: pg_backup_db.c:37
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6165
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6150
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:744
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6063
char * pgport
Definition: pgbench.c:194

◆ die_on_query_failure()

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

Definition at line 385 of file pg_backup_db.c.

References _archiveHandle::connection, exit_horribly(), PQerrorMessage(), and write_msg().

Referenced by ExecuteSqlQuery(), and ExecuteSqlStatement().

386 {
387  write_msg(modulename, "query failed: %s",
389  exit_horribly(modulename, "query was: %s\n", query);
390 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
static const char * modulename
Definition: pg_backup_db.c:30
void write_msg(const char *modulename, const char *fmt,...)
void exit_horribly(const char *modulename, const char *fmt,...)

◆ DisconnectDatabase()

void DisconnectDatabase ( Archive AHX)

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

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

◆ DropBlobIfExists()

void DropBlobIfExists ( ArchiveHandle AH,
Oid  oid 
)

Definition at line 661 of file pg_backup_db.c.

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

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

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

◆ EndDBCopyMode()

void EndDBCopyMode ( Archive AHX,
const char *  tocEntryTag 
)

Definition at line 616 of file pg_backup_db.c.

References _archiveHandle::connection, exit_horribly(), modulename, _archiveHandle::pgCopyIn, PGRES_COMMAND_OK, PQclear(), PQerrorMessage(), PQgetResult(), PQputCopyEnd(), PQresultStatus(), warn_or_exit_horribly(), and write_msg().

Referenced by restore_toc_entry().

617 {
618  ArchiveHandle *AH = (ArchiveHandle *) AHX;
619 
620  if (AH->pgCopyIn)
621  {
622  PGresult *res;
623 
624  if (PQputCopyEnd(AH->connection, NULL) <= 0)
625  exit_horribly(modulename, "error returned by PQputCopyEnd: %s",
627 
628  /* Check command status and return to normal libpq state */
629  res = PQgetResult(AH->connection);
630  if (PQresultStatus(res) != PGRES_COMMAND_OK)
631  warn_or_exit_horribly(AH, modulename, "COPY failed for table \"%s\": %s",
632  tocEntryTag, PQerrorMessage(AH->connection));
633  PQclear(res);
634 
635  /* Do this to ensure we've pumped libpq back to idle state */
636  if (PQgetResult(AH->connection) != NULL)
637  write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
638  tocEntryTag);
639 
640  AH->pgCopyIn = false;
641  }
642 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2339
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
void warn_or_exit_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
static const char * modulename
Definition: pg_backup_db.c:30
void PQclear(PGresult *res)
Definition: fe-exec.c:671
void write_msg(const char *modulename, const char *fmt,...)
void exit_horribly(const char *modulename, const char *fmt,...)
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1753

◆ ExecuteSimpleCommands()

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

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

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

◆ ExecuteSqlCommand()

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

Definition at line 444 of file pg_backup_db.c.

References conn, _archiveHandle::connection, modulename, _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().

445 {
446  PGconn *conn = AH->connection;
447  PGresult *res;
448 
449 #ifdef NOT_USED
450  fprintf(stderr, "Executing: '%s'\n\n", qry);
451 #endif
452  res = PQexec(conn, qry);
453 
454  switch (PQresultStatus(res))
455  {
456  case PGRES_COMMAND_OK:
457  case PGRES_TUPLES_OK:
458  case PGRES_EMPTY_QUERY:
459  /* A-OK */
460  break;
461  case PGRES_COPY_IN:
462  /* Assume this is an expected result */
463  AH->pgCopyIn = true;
464  break;
465  default:
466  /* trouble */
467  warn_or_exit_horribly(AH, modulename, "%s: %s Command was: %s\n",
468  desc, PQerrorMessage(conn), qry);
469  break;
470  }
471 
472  PQclear(res);
473 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
void warn_or_exit_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
PGconn * conn
Definition: streamutil.c:55
static const char * modulename
Definition: pg_backup_db.c:30
void PQclear(PGresult *res)
Definition: fe-exec.c:671
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897

◆ ExecuteSqlCommandBuf()

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

Definition at line 561 of file pg_backup_db.c.

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

Referenced by ahwrite().

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

◆ ExecuteSqlQuery()

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

Definition at line 405 of file pg_backup_db.c.

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

Referenced by buildMatViewRefreshDependencies(), collectComments(), collectSecLabels(), createViewAsClause(), dumpBlobs(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabase(), dumpDatabaseConfig(), dumpEnumType(), dumpOpclass(), dumpOpfamily(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTSConfig(), dumpUserMappings(), ExecuteSqlQueryForSingleRow(), 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().

406 {
407  ArchiveHandle *AH = (ArchiveHandle *) AHX;
408  PGresult *res;
409 
410  res = PQexec(AH->connection, query);
411  if (PQresultStatus(res) != status)
412  die_on_query_failure(AH, modulename, query);
413  return res;
414 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
static const char * modulename
Definition: pg_backup_db.c:30
static void die_on_query_failure(ArchiveHandle *AH, const char *modulename, const char *query)
Definition: pg_backup_db.c:385
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897
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 420 of file pg_backup_db.c.

References ExecuteSqlQuery(), exit_horribly(), 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().

421 {
422  PGresult *res;
423  int ntups;
424 
425  res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
426 
427  /* Expecting a single result only */
428  ntups = PQntuples(res);
429  if (ntups != 1)
430  exit_horribly(NULL,
431  ngettext("query returned %d row instead of one: %s\n",
432  "query returned %d rows instead of one: %s\n",
433  ntups),
434  ntups, query);
435 
436  return res;
437 }
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2724
#define ngettext(s, p, n)
Definition: c.h:1022
void exit_horribly(const char *modulename, const char *fmt,...)
PGresult * ExecuteSqlQuery(Archive *AHX, const char *query, ExecStatusType status)
Definition: pg_backup_db.c:405

◆ ExecuteSqlStatement()

void ExecuteSqlStatement ( Archive AHX,
const char *  query 
)

Definition at line 393 of file pg_backup_db.c.

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

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

394 {
395  ArchiveHandle *AH = (ArchiveHandle *) AHX;
396  PGresult *res;
397 
398  res = PQexec(AH->connection, query);
399  if (PQresultStatus(res) != PGRES_COMMAND_OK)
400  die_on_query_failure(AH, modulename, query);
401  PQclear(res);
402 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
static const char * modulename
Definition: pg_backup_db.c:30
static void die_on_query_failure(ArchiveHandle *AH, const char *modulename, const char *query)
Definition: pg_backup_db.c:385
void PQclear(PGresult *res)
Definition: fe-exec.c:671
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897

◆ GetConnection()

PGconn* GetConnection ( Archive AHX)

Definition at line 370 of file pg_backup_db.c.

References _archiveHandle::connection.

371 {
372  ArchiveHandle *AH = (ArchiveHandle *) AHX;
373 
374  return AH->connection;
375 }

◆ notice_processor()

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

Definition at line 378 of file pg_backup_db.c.

References write_msg().

Referenced by _connectDB(), and ConnectDatabase().

379 {
380  write_msg(NULL, "%s", message);
381 }
void write_msg(const char *modulename, const char *fmt,...)

◆ ReconnectToServer()

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

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

84 {
85  PGconn *newConn;
86  const char *newdbname;
87  const char *newusername;
88 
89  if (!dbname)
90  newdbname = PQdb(AH->connection);
91  else
92  newdbname = dbname;
93 
94  if (!username)
95  newusername = PQuser(AH->connection);
96  else
97  newusername = username;
98 
99  newConn = _connectDB(AH, newdbname, newusername);
100 
101  /* Update ArchiveHandle's connCancel before closing old connection */
102  set_archive_cancel_info(AH, newConn);
103 
104  PQfinish(AH->connection);
105  AH->connection = newConn;
106 
107  /* Start strict; later phases may override this. */
110 }
static PGconn * _connectDB(ArchiveHandle *AH, const char *newdbname, const char *newUser)
Definition: pg_backup_db.c:122
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3638
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5991
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:420
static char * username
Definition: initdb.c:132
void PQclear(PGresult *res)
Definition: fe-exec.c:671
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5983
char * dbname
Definition: streamutil.c:51
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:744

◆ StartTransaction()

void StartTransaction ( Archive AHX)

Definition at line 645 of file pg_backup_db.c.

References ExecuteSqlCommand().

646 {
647  ArchiveHandle *AH = (ArchiveHandle *) AHX;
648 
649  ExecuteSqlCommand(AH, "BEGIN", "could not start database transaction");
650 }
static void ExecuteSqlCommand(ArchiveHandle *AH, const char *qry, const char *desc)
Definition: pg_backup_db.c:444

Variable Documentation

◆ modulename