1 /*-------------------------------------------------------------------------
4 *-------------------------------------------------------------------------
7 #include <unistd.h> /* for getopt() */
16 #include "access/attnum.h"
17 #include "access/htup.h"
18 #include "catalog/pg_index.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_trigger.h"
21 #include "catalog/pg_type.h"
24 #include <libpq/libpq-fs.h>
30 #include "pg_backup.h"
31 #include "pg_backup_archiver.h"
32 #include "pg_backup_db.h"
34 static const char *progname = "Archiver(db)";
36 static void _prompt_for_password(char *username, char *password);
37 static void _check_database_version(ArchiveHandle *AH, bool ignoreVersion);
38 static PGconn* _connectDB(ArchiveHandle *AH, const char* newdbname, char *newUser);
39 static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, char *desc);
43 _prompt_for_password(char *username, char *password)
50 struct termios t_orig,
55 * Allow for forcing a specific username
57 if (strlen(username) == 0)
59 fprintf(stderr, "Username: ");
61 if (fgets(username, 100, stdin) == NULL)
63 length = strlen(username);
64 if (length > 0 && username[length - 1] != '\n')
66 /* eat rest of the line */
69 if (fgets(buf, sizeof(buf), stdin) == NULL)
72 } while (buflen > 0 && buf[buflen - 1] != '\n');
74 if (length > 0 && username[length - 1] == '\n')
75 username[length - 1] = '\0';
82 tcsetattr(0, TCSADRAIN, &t);
84 fprintf(stderr, "Password: ");
86 if (fgets(password, 100, stdin) == NULL)
89 tcsetattr(0, TCSADRAIN, &t_orig);
92 length = strlen(password);
93 if (length > 0 && password[length - 1] != '\n')
95 /* eat rest of the line */
98 if (fgets(buf, sizeof(buf), stdin) == NULL)
100 buflen = strlen(buf);
101 } while (buflen > 0 && buf[buflen - 1] != '\n');
103 if (length > 0 && password[length - 1] == '\n')
104 password[length - 1] = '\0';
106 fprintf(stderr, "\n\n");
111 _check_database_version(ArchiveHandle *AH, bool ignoreVersion)
115 const char *remoteversion_str;
116 double remoteversion;
117 PGconn *conn = AH->connection;
119 myversion = strtod(PG_VERSION, NULL);
120 res = PQexec(conn, "SELECT version()");
122 PQresultStatus(res) != PGRES_TUPLES_OK ||
125 die_horribly(AH, "check_database_version(): command failed. "
126 "Explanation from backend: '%s'.\n", PQerrorMessage(conn));
128 remoteversion_str = PQgetvalue(res, 0, 0);
129 remoteversion = strtod(remoteversion_str + 11, NULL);
130 if (myversion != remoteversion)
132 fprintf(stderr, "Database version: %s\n%s version: %s\n",
133 remoteversion_str, progname, PG_VERSION);
135 fprintf(stderr, "Proceeding despite version mismatch.\n");
137 die_horribly(AH, "Aborting because of version mismatch.\n"
138 "Use --ignore-version if you think it's safe to proceed anyway.\n");
144 * Check if a given user is a superuser.
146 int UserIsSuperuser(ArchiveHandle *AH, char* user)
148 PQExpBuffer qry = createPQExpBuffer();
154 /* Get the superuser setting */
155 appendPQExpBuffer(qry, "select usesuper from pg_user where usename = '%s'", user);
156 res = PQexec(AH->connection, qry->data);
159 die_horribly(AH, "%s: null result checking superuser status of %s.\n",
162 if (PQresultStatus(res) != PGRES_TUPLES_OK)
163 die_horribly(AH, "%s: Could not check superuser status of %s. Explanation from backend: %s\n",
164 progname, user, PQerrorMessage(AH->connection));
166 ntups = PQntuples(res);
172 i_usesuper = PQfnumber(res, "usesuper");
173 isSuper = (strcmp(PQgetvalue(res, 0, i_usesuper), "t") == 0);
180 int ConnectedUserIsSuperuser(ArchiveHandle *AH)
182 return UserIsSuperuser(AH, PQuser(AH->connection));
185 char* ConnectedUser(ArchiveHandle *AH)
187 return PQuser(AH->connection);
191 * Reconnect the DB associated with the archive handle
193 int ReconnectDatabase(ArchiveHandle *AH, const char* newdbname, char *newUser)
198 if (!newdbname || (strcmp(newdbname, "-") == 0) )
199 dbname = PQdb(AH->connection);
201 dbname = (char*)newdbname;
203 /* Let's see if the request is already satisfied */
204 if (strcmp(PQuser(AH->connection), newUser) == 0 && strcmp(newdbname, PQdb(AH->connection)) == 0)
207 newConn = _connectDB(AH, dbname, newUser);
209 PQfinish(AH->connection);
210 AH->connection = newConn;
211 strcpy(AH->username, newUser);
217 * Connect to the db again.
219 static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser)
224 char *pwparam = NULL;
230 if (!reqdb || (strcmp(reqdb, "-") == 0) )
231 newdb = PQdb(AH->connection);
233 newdb = (char*)reqdb;
235 if (!requser || (strlen(requser) == 0))
236 newuser = PQuser(AH->connection);
238 newuser = (char*)requser;
240 ahlog(AH, 1, "Connecting to %s as %s\n", newdb, newuser);
245 newConn = PQsetdbLogin(PQhost(AH->connection), PQport(AH->connection),
249 die_horribly(AH, "%s: Failed to reconnect (PQsetdbLogin failed).\n", progname);
251 if (PQstatus(newConn) == CONNECTION_BAD)
253 noPwd = (strcmp(PQerrorMessage(newConn), "fe_sendauth: no password supplied\n") == 0);
254 badPwd = (strncmp(PQerrorMessage(newConn), "Password authentication failed for user", 39)
261 fprintf(stderr, "Password incorrect\n");
263 fprintf(stderr, "Connecting to %s as %s\n", PQdb(AH->connection), newuser);
266 _prompt_for_password(newuser, password);
270 die_horribly(AH, "%s: Could not reconnect. %s\n", progname, PQerrorMessage(newConn));
279 PGconn* ConnectDatabase(Archive *AHX,
284 const int ignoreVersion)
286 ArchiveHandle *AH = (ArchiveHandle*)AHX;
287 char connect_string[512] = "";
288 char tmp_string[128];
292 die_horribly(AH, "%s: already connected to database\n", progname);
294 if (!dbname && !(dbname = getenv("PGDATABASE")) )
295 die_horribly(AH, "%s: no database name specified\n", progname);
297 AH->dbname = strdup(dbname);
301 AH->pghost = strdup(pghost);
302 sprintf(tmp_string, "host=%s ", AH->pghost);
303 strcat(connect_string, tmp_string);
310 AH->pgport = strdup(pgport);
311 sprintf(tmp_string, "port=%s ", AH->pgport);
312 strcat(connect_string, tmp_string);
317 sprintf(tmp_string, "dbname=%s ", AH->dbname);
318 strcat(connect_string, tmp_string);
322 AH->username[0] = '\0';
323 _prompt_for_password(AH->username, password);
324 strcat(connect_string, "authtype=password ");
325 sprintf(tmp_string, "user=%s ", AH->username);
326 strcat(connect_string, tmp_string);
327 sprintf(tmp_string, "password=%s ", password);
328 strcat(connect_string, tmp_string);
329 MemSet(tmp_string, 0, sizeof(tmp_string));
330 MemSet(password, 0, sizeof(password));
332 AH->connection = PQconnectdb(connect_string);
333 MemSet(connect_string, 0, sizeof(connect_string));
335 /* check to see that the backend connection was successfully made */
336 if (PQstatus(AH->connection) == CONNECTION_BAD)
337 die_horribly(AH, "Connection to database '%s' failed.\n%s\n",
338 AH->dbname, PQerrorMessage(AH->connection));
340 /* check for version mismatch */
341 _check_database_version(AH, ignoreVersion);
344 * AH->currUser = PQuser(AH->connection);
346 * Removed because it prevented an initial \connect
347 * when dumping to SQL in pg_dump.
350 return AH->connection;
353 /* Public interface */
354 /* Convenience function to send a query. Monitors result to handle COPY statements */
355 int ExecuteSqlCommand(ArchiveHandle* AH, PQExpBuffer qry, char *desc)
357 return _executeSqlCommand(AH, AH->connection, qry, desc);
361 * Handle command execution. This is used to execute a command on more than one connection,
362 * but the 'pgCopyIn' setting assumes the COPY commands are ONLY executed on the primary
363 * setting...an error will be raised otherwise.
365 static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, char *desc)
369 /* fprintf(stderr, "Executing: '%s'\n\n", qry->data); */
370 res = PQexec(conn, qry->data);
372 die_horribly(AH, "%s: %s. No result from backend.\n", progname, desc);
374 if (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK)
376 if (PQresultStatus(res) == PGRES_COPY_IN)
378 if (conn != AH->connection)
379 die_horribly(AH, "%s: COPY command execute in non-primary connection.\n", progname);
384 die_horribly(AH, "%s: %s. Code = %d. Explanation from backend: '%s'.\n",
385 progname, desc, PQresultStatus(res), PQerrorMessage(AH->connection));
390 return strlen(qry->data);
393 /* Convenience function to send one or more queries. Monitors result to handle COPY statements */
394 int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen)
399 char *qry = (char*)qryv;
401 char *eos = qry + bufLen;
403 /* fprintf(stderr, "\n\n*****\n Buffer:\n\n%s\n*******************\n\n", qry); */
405 /* If we're in COPY IN mode, then just break it into lines and send... */
410 loc = strcspn(&qry[pos], "\n") + pos;
413 /* If no match, then wait */
414 if (loc >= (eos - qry)) /* None found */
416 appendBinaryPQExpBuffer(AH->pgCopyBuf, qry, (eos - qry));
420 /* fprintf(stderr, "Found cr at %d, prev char was %c, next was %c\n", loc, qry[loc-1], qry[loc+1]); */
422 /* Count the number of preceding slashes */
424 while (sPos > 0 && qry[sPos-1] == '\\')
429 /* If an odd number of preceding slashes, then \n was escaped
430 * so set the next search pos, and restart (if any left).
434 /* fprintf(stderr, "cr was escaped\n"); */
436 if (pos >= (eos - qry))
438 appendBinaryPQExpBuffer(AH->pgCopyBuf, qry, (eos - qry));
444 /* We got a good cr */
446 appendPQExpBuffer(AH->pgCopyBuf, "%s\n", qry);
448 isEnd = (strcmp(AH->pgCopyBuf->data, "\\.\n") == 0);
450 /* fprintf(stderr, "Sending '%s' via COPY (at end = %d)\n\n", AH->pgCopyBuf->data, isEnd); */
452 PQputline(AH->connection, AH->pgCopyBuf->data);
454 resetPQExpBuffer(AH->pgCopyBuf);
456 /* fprintf(stderr, "Buffer is '%s'\n", AH->pgCopyBuf->data); */
459 PQendcopy(AH->connection);
466 /* Make sure we're not past the original buffer end */
473 /* We may have finished Copy In, and have a non-empty buffer */
477 * The following is a mini state machine to assess then of of an SQL statement.
478 * It really only needs to parse good SQL, or at least that's the theory...
479 * End-of-statement is assumed to be an unquoted, un commented semi-colon.
482 /* fprintf(stderr, "Buffer at start is: '%s'\n\n", AH->sqlBuf->data); */
484 for(pos=0; pos < (eos - qry); pos++)
486 appendPQExpBufferChar(AH->sqlBuf, qry[pos]);
487 /* fprintf(stderr, " %c",qry[pos]); */
489 switch (AH->sqlparse.state) {
491 case SQL_SCAN: /* Default state == 0, set in _allocAH */
493 if (qry[pos] == ';' && AH->sqlparse.braceDepth == 0)
495 /* Send It & reset the buffer */
496 /* fprintf(stderr, " sending: '%s'\n\n", AH->sqlBuf->data); */
497 ExecuteSqlCommand(AH, AH->sqlBuf, "Could not execute query");
498 resetPQExpBuffer(AH->sqlBuf);
499 AH->sqlparse.lastChar = '\0';
503 if (qry[pos] == '"' || qry[pos] == '\'')
505 /* fprintf(stderr,"[startquote]\n"); */
506 AH->sqlparse.state = SQL_IN_QUOTE;
507 AH->sqlparse.quoteChar = qry[pos];
508 AH->sqlparse.backSlash = 0;
510 else if (qry[pos] == '-' && AH->sqlparse.lastChar == '-')
512 AH->sqlparse.state = SQL_IN_SQL_COMMENT;
514 else if (qry[pos] == '*' && AH->sqlparse.lastChar == '/')
516 AH->sqlparse.state = SQL_IN_EXT_COMMENT;
518 else if ( qry[pos] == '(' )
520 AH->sqlparse.braceDepth++;
522 else if (qry[pos] == ')')
524 AH->sqlparse.braceDepth--;
527 AH->sqlparse.lastChar = qry[pos];
532 case SQL_IN_SQL_COMMENT:
534 if (qry[pos] == '\n')
535 AH->sqlparse.state = SQL_SCAN;
538 case SQL_IN_EXT_COMMENT:
540 if (AH->sqlparse.lastChar == '*' && qry[pos] == '/')
541 AH->sqlparse.state = SQL_SCAN;
546 if (!AH->sqlparse.backSlash && AH->sqlparse.quoteChar == qry[pos])
548 /* fprintf(stderr,"[endquote]\n"); */
549 AH->sqlparse.state = SQL_SCAN;
554 if (qry[pos] == '\\')
556 if (AH->sqlparse.lastChar == '\\')
557 AH->sqlparse.backSlash = !AH->sqlparse.backSlash;
559 AH->sqlparse.backSlash = 1;
561 AH->sqlparse.backSlash = 0;
567 AH->sqlparse.lastChar = qry[pos];
568 /* fprintf(stderr, "\n"); */
576 void FixupBlobRefs(ArchiveHandle *AH, char *tablename)
578 PQExpBuffer tblQry = createPQExpBuffer();
579 PGresult *res, *uRes;
583 for(i=0 ; i < strlen(tablename) ; i++)
584 tablename[i] = tolower(tablename[i]);
586 if (strcmp(tablename, BLOB_XREF_TABLE) == 0)
589 appendPQExpBuffer(tblQry, "SELECT a.attname FROM pg_class c, pg_attribute a, pg_type t "
590 " WHERE a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid "
591 " AND t.typname = 'oid' AND c.relname = '%s';", tablename);
593 res = PQexec(AH->blobConnection, tblQry->data);
595 die_horribly(AH, "%s: could not find OID attrs of %s. Explanation from backend '%s'\n",
596 progname, tablename, PQerrorMessage(AH->connection));
598 if ((n = PQntuples(res)) == 0) {
600 ahlog(AH, 1, "No OID attributes in table %s\n", tablename);
605 for (i = 0 ; i < n ; i++)
607 attr = PQgetvalue(res, i, 0);
609 ahlog(AH, 1, " - %s.%s\n", tablename, attr);
611 resetPQExpBuffer(tblQry);
614 * We should use coalesce here (rather than 'exists'), but it seems to
615 * be broken in 7.0.2 (weird optimizer strategy)
617 appendPQExpBuffer(tblQry, "UPDATE \"%s\" SET \"%s\" = ",tablename, attr);
618 appendPQExpBuffer(tblQry, " (SELECT x.newOid FROM \"%s\" x WHERE x.oldOid = \"%s\".\"%s\")",
619 BLOB_XREF_TABLE, tablename, attr);
620 appendPQExpBuffer(tblQry, " where exists"
621 "(select * from %s x where x.oldOid = \"%s\".\"%s\");",
622 BLOB_XREF_TABLE, tablename, attr);
624 ahlog(AH, 10, " - sql:\n%s\n", tblQry->data);
626 uRes = PQexec(AH->blobConnection, tblQry->data);
628 die_horribly(AH, "%s: could not update attr %s of table %s. Explanation from backend '%s'\n",
629 progname, attr, tablename, PQerrorMessage(AH->blobConnection));
631 if ( PQresultStatus(uRes) != PGRES_COMMAND_OK )
632 die_horribly(AH, "%s: error while updating attr %s of table %s (result = %d)."
633 " Explanation from backend '%s'\n",
634 progname, attr, tablename, PQresultStatus(uRes),
635 PQerrorMessage(AH->blobConnection));
645 * Convenient SQL calls
647 void CreateBlobXrefTable(ArchiveHandle* AH)
649 PQExpBuffer qry = createPQExpBuffer();
651 /* IF we don't have a BLOB connection, then create one */
652 if (!AH->blobConnection)
654 AH->blobConnection = _connectDB(AH, NULL, NULL);
657 ahlog(AH, 1, "Creating table for BLOBS xrefs\n");
659 appendPQExpBuffer(qry, "Create Temporary Table %s(oldOid oid, newOid oid);", BLOB_XREF_TABLE);
661 _executeSqlCommand(AH, AH->blobConnection, qry, "can not create BLOB xref table '" BLOB_XREF_TABLE "'");
663 resetPQExpBuffer(qry);
665 appendPQExpBuffer(qry, "Create Unique Index %s_ix on %s(oldOid)", BLOB_XREF_TABLE, BLOB_XREF_TABLE);
666 _executeSqlCommand(AH, AH->blobConnection, qry, "can not create index on BLOB xref table '" BLOB_XREF_TABLE "'");
669 void InsertBlobXref(ArchiveHandle* AH, int old, int new)
671 PQExpBuffer qry = createPQExpBuffer();
673 appendPQExpBuffer(qry, "Insert Into %s(oldOid, newOid) Values (%d, %d);", BLOB_XREF_TABLE, old, new);
675 _executeSqlCommand(AH, AH->blobConnection, qry, "can not create BLOB xref entry");
678 void StartTransaction(ArchiveHandle* AH)
680 PQExpBuffer qry = createPQExpBuffer();
682 appendPQExpBuffer(qry, "Begin;");
684 ExecuteSqlCommand(AH, qry, "can not start database transaction");
688 void StartTransactionXref(ArchiveHandle* AH)
690 PQExpBuffer qry = createPQExpBuffer();
692 appendPQExpBuffer(qry, "Begin;");
694 _executeSqlCommand(AH, AH->blobConnection, qry, "can not start BLOB xref transaction");
695 AH->blobTxActive = true;
698 void CommitTransaction(ArchiveHandle* AH)
700 PQExpBuffer qry = createPQExpBuffer();
702 appendPQExpBuffer(qry, "Commit;");
704 ExecuteSqlCommand(AH, qry, "can not commit database transaction");
705 AH->txActive = false;
708 void CommitTransactionXref(ArchiveHandle* AH)
710 PQExpBuffer qry = createPQExpBuffer();
712 appendPQExpBuffer(qry, "Commit;");
714 _executeSqlCommand(AH, AH->blobConnection, qry, "can not commit BLOB xref transaction");
715 AH->blobTxActive = false;