1 /*-------------------------------------------------------------------------
5 * Private implementation of the archiver routines.
7 * See the headers to pg_restore for more details.
9 * Copyright (c) 2000, Philip Warner
10 * Rights are granted to use this software in any way so long
11 * as this notice is not removed.
13 * The author is not responsible for loss or damages that may
14 * result from its use.
18 * $PostgreSQL: pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.90 2004/07/19 21:39:47 momjian Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup.h"
25 #include "pg_backup_archiver.h"
26 #include "pg_backup_db.h"
27 #include "dumputils.h"
33 #include "pqexpbuffer.h"
34 #include "libpq/libpq-fs.h"
41 REQ_ALL = REQ_SCHEMA + REQ_DATA
45 static char *modulename = gettext_noop("archiver");
48 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
49 const int compression, ArchiveMode mode);
50 static char *_getObjectFromDropStmt(const char *dropStmt, const char *type);
51 static void _printTocHeader(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData);
52 static int _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool ownerAndACL);
55 static void fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte,
56 RestoreOptions *ropt);
57 static void _doSetFixedOutputState(ArchiveHandle *AH);
58 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
59 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
60 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname, const char *user);
61 static void _becomeUser(ArchiveHandle *AH, const char *user);
62 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
63 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
65 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool ownerAndACL);
66 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
67 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
68 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
69 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
70 static int _discoverArchiveFormat(ArchiveHandle *AH);
72 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
73 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
75 static int _canRestoreBlobs(ArchiveHandle *AH);
76 static int _restoringToDB(ArchiveHandle *AH);
82 * The objective it to make writing new formats and dumpers as simple
83 * as possible, if necessary at the expense of extra function calls etc.
88 /* Create a new archive */
91 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
92 const int compression)
95 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
97 return (Archive *) AH;
100 /* Open an existing archive */
103 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
105 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
107 return (Archive *) AH;
112 CloseArchive(Archive *AHX)
115 ArchiveHandle *AH = (ArchiveHandle *) AHX;
117 (*AH->ClosePtr) (AH);
119 /* Close the output */
121 res = GZCLOSE(AH->OF);
122 else if (AH->OF != stdout)
123 res = fclose(AH->OF);
126 die_horribly(AH, modulename, "could not close output archive file\n");
131 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
133 ArchiveHandle *AH = (ArchiveHandle *) AHX;
134 TocEntry *te = AH->toc->next;
143 * Check for nonsensical option combinations.
145 * NB: create+dropSchema is useless because if you're creating the DB,
146 * there's no need to drop individual items in it. Moreover, if we
147 * tried to do that then we'd issue the drops in the database
148 * initially connected to, not the one we will create, which is very
151 if (ropt->create && ropt->dropSchema)
152 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
155 * If we're using a DB connection, then connect it.
159 ahlog(AH, 1, "connecting to database for restore\n");
160 if (AH->version < K_VERS_1_3)
161 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
163 /* XXX Should get this from the archive */
164 AHX->minRemoteVersion = 070100;
165 AHX->maxRemoteVersion = 999999;
167 ConnectDatabase(AHX, ropt->dbname,
168 ropt->pghost, ropt->pgport, ropt->username,
169 ropt->requirePassword, ropt->ignoreVersion);
173 * Work out if we have an implied data-only restore. This can happen
174 * if the dump was data only or if the user has used a toc list to
175 * exclude all of the schema data. All we do is look for schema
176 * entries - if none are found then we set the dataOnly flag.
178 * We could scan for wanted TABLE entries, but that is not the same as
179 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
185 while (te != AH->toc)
187 reqs = _tocEntryRequired(te, ropt, false);
188 if ((reqs & REQ_SCHEMA) != 0)
189 { /* It's schema, and it's wanted */
197 ropt->dataOnly = impliedDataOnly;
198 ahlog(AH, 1, "implied data-only restore\n");
203 * Setup the output file if necessary.
205 if (ropt->filename || ropt->compression)
206 sav = SetOutput(AH, ropt->filename, ropt->compression);
208 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
211 * Establish important parameter values right away.
213 _doSetFixedOutputState(AH);
216 * Drop the items at the start, in reverse order
218 if (ropt->dropSchema)
221 while (te != AH->toc)
223 reqs = _tocEntryRequired(te, ropt, false);
224 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
226 /* We want the schema */
227 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
228 /* Select owner and schema as necessary */
229 _becomeOwner(AH, te);
230 _selectOutputSchema(AH, te->namespace);
232 ahprintf(AH, "%s", te->dropStmt);
239 * Now process each TOC entry
242 while (te != AH->toc)
244 /* Work out what, if anything, we want from this entry */
245 reqs = _tocEntryRequired(te, ropt, false);
247 /* Dump any relevant dump warnings to stderr */
248 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
250 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
251 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
252 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
253 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
258 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
260 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
262 _printTocEntry(AH, te, ropt, false, false);
265 /* If we created a DB, connect to it... */
266 if (strcmp(te->desc, "DATABASE") == 0)
268 ahlog(AH, 1, "connecting to new database \"%s\" as user \"%s\"\n", te->tag, te->owner);
269 _reconnectToDB(AH, te->tag, te->owner);
274 * If we have a data component, then process it
276 if ((reqs & REQ_DATA) != 0)
279 * hadDumper will be set if there is genuine data component
280 * for this node. Otherwise, we need to check the defn field
281 * for statements that need to be executed in data-only
287 * If we can output the data, then restore it.
289 if (AH->PrintTocDataPtr != NULL && (reqs & REQ_DATA) != 0)
292 if (AH->compression != 0)
293 die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
296 _printTocEntry(AH, te, ropt, true, false);
299 * Maybe we can't do BLOBS, so check if this node is
302 if ((strcmp(te->desc, "BLOBS") == 0) &&
303 !_canRestoreBlobs(AH))
305 ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
308 * This is a bit nasty - we assume, for the
309 * moment, that if a custom output is used, then
310 * we don't want warnings.
312 if (!AH->CustomOutPtr)
313 write_msg(modulename, "WARNING: skipping large-object restoration\n");
317 _disableTriggersIfNecessary(AH, te, ropt);
319 /* Select owner and schema as necessary */
320 _becomeOwner(AH, te);
321 _selectOutputSchema(AH, te->namespace);
323 ahlog(AH, 1, "restoring data for table \"%s\"\n", te->tag);
326 * If we have a copy statement, use it. As of
327 * V1.3, these are separate to allow easy import
328 * from withing a database connection. Pre 1.3
329 * archives can not use DB connections and are
330 * sent to output only.
332 * For V1.3+, the table data MUST have a copy
333 * statement so that we can go into appropriate
336 if (te->copyStmt && strlen(te->copyStmt) > 0)
337 ahprintf(AH, te->copyStmt);
339 (*AH->PrintTocDataPtr) (AH, te, ropt);
342 * If we just restored blobs, fix references in
343 * previously-loaded tables; otherwise, if we
344 * previously restored blobs, fix references in
345 * this table. Note that in standard cases the BLOBS
346 * entry comes after all TABLE DATA entries, but
347 * we should cope with other orders in case the
348 * user demands reordering.
350 if (strcmp(te->desc, "BLOBS") == 0)
351 fixPriorBlobRefs(AH, te, ropt);
352 else if (AH->createdBlobXref &&
353 strcmp(te->desc, "TABLE DATA") == 0)
355 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
356 FixupBlobRefs(AH, te);
359 _enableTriggersIfNecessary(AH, te, ropt);
363 else if (!defnDumped)
365 /* If we haven't already dumped the defn part, do so now */
366 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
367 _printTocEntry(AH, te, ropt, false, false);
371 } /* end loop over TOC entries */
374 * Scan TOC again to output ownership commands and ACLs
377 while (te != AH->toc)
379 /* Work out what, if anything, we want from this entry */
380 reqs = _tocEntryRequired(te, ropt, true);
384 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
386 ahlog(AH, 1, "setting owner and acl for %s %s\n", te->desc, te->tag);
388 _printTocEntry(AH, te, ropt, false, true);
396 * Clean up & we're done.
398 if (ropt->filename || ropt->compression)
399 ResetOutput(AH, sav);
403 PQfinish(AH->connection);
404 AH->connection = NULL;
406 if (AH->blobConnection)
408 PQfinish(AH->blobConnection);
409 AH->blobConnection = NULL;
413 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
417 * After restoring BLOBS, fix all blob references in previously-restored
418 * tables. (Normally, the BLOBS entry should appear after all TABLE DATA
419 * entries, so this will in fact handle all blob references.)
422 fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte, RestoreOptions *ropt)
427 if (AH->createdBlobXref)
429 /* NULL parameter means disable ALL user triggers */
430 _disableTriggersIfNecessary(AH, NULL, ropt);
432 for (te = AH->toc->next; te != blobte; te = te->next)
434 if (strcmp(te->desc, "TABLE DATA") == 0)
436 reqs = _tocEntryRequired(te, ropt, false);
438 if ((reqs & REQ_DATA) != 0) /* We loaded the data */
440 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
441 FixupBlobRefs(AH, te);
446 /* NULL parameter means enable ALL user triggers */
447 _enableTriggersIfNecessary(AH, NULL, ropt);
452 * Allocate a new RestoreOptions block.
453 * This is mainly so we can initialize it, but also for future expansion,
456 NewRestoreOptions(void)
458 RestoreOptions *opts;
460 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
462 opts->format = archUnknown;
463 opts->suppressDumpWarnings = false;
469 * Returns true if we're restoring directly to the database (and
470 * aren't just making a psql script that can do the restoration).
473 _restoringToDB(ArchiveHandle *AH)
475 return (AH->ropt->useDB && AH->connection);
479 _canRestoreBlobs(ArchiveHandle *AH)
481 return _restoringToDB(AH);
485 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
487 /* This hack is only needed in a data-only restore */
488 if (!ropt->dataOnly || !ropt->disable_triggers)
491 /* Don't do it for the BLOBS TocEntry, either */
492 if (te && strcmp(te->desc, "BLOBS") == 0)
496 * Become superuser if possible, since they are the only ones who can
497 * update pg_class. If -S was not given, assume the initial user identity
500 _becomeUser(AH, ropt->superuser);
502 ahlog(AH, 1, "disabling triggers\n");
505 * Disable them. This is a hack. Needs to be done via an appropriate
506 * 'SET' command when one is available.
508 ahprintf(AH, "-- Disable triggers\n");
511 * Just update the AFFECTED table, if known. Otherwise update all
514 if (te && te->tag && strlen(te->tag) > 0)
515 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
516 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
519 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
520 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
524 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
526 /* This hack is only needed in a data-only restore */
527 if (!ropt->dataOnly || !ropt->disable_triggers)
530 /* Don't do it for the BLOBS TocEntry, either */
531 if (te && strcmp(te->desc, "BLOBS") == 0)
535 * Become superuser if possible, since they are the only ones who can
536 * update pg_class. If -S was not given, assume the initial user identity
539 _becomeUser(AH, ropt->superuser);
541 ahlog(AH, 1, "enabling triggers\n");
544 * Enable them. This is a hack. Needs to be done via an appropriate
545 * 'SET' command when one is available.
547 ahprintf(AH, "-- Enable triggers\n");
550 * Just update the AFFECTED table, if known. Otherwise update all
553 if (te && te->tag && strlen(te->tag) > 0)
554 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
555 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
556 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
559 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
560 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
561 "FROM pg_catalog.pg_namespace "
562 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
566 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
571 WriteData(Archive *AHX, const void *data, size_t dLen)
573 ArchiveHandle *AH = (ArchiveHandle *) AHX;
576 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
578 return (*AH->WriteDataPtr) (AH, data, dLen);
582 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
583 * repository for all metadata. But the name has stuck.
588 ArchiveEntry(Archive *AHX,
589 CatalogId catalogId, DumpId dumpId,
591 const char *namespace, const char *owner, bool withOids,
592 const char *desc, const char *defn,
593 const char *dropStmt, const char *copyStmt,
594 const DumpId *deps, int nDeps,
595 DataDumperPtr dumpFn, void *dumpArg)
597 ArchiveHandle *AH = (ArchiveHandle *) AHX;
600 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
602 die_horribly(AH, modulename, "out of memory\n");
605 if (dumpId > AH->maxDumpId)
606 AH->maxDumpId = dumpId;
608 newToc->prev = AH->toc->prev;
609 newToc->next = AH->toc;
610 AH->toc->prev->next = newToc;
611 AH->toc->prev = newToc;
613 newToc->catalogId = catalogId;
614 newToc->dumpId = dumpId;
616 newToc->tag = strdup(tag);
617 newToc->namespace = namespace ? strdup(namespace) : NULL;
618 newToc->owner = strdup(owner);
619 newToc->withOids = withOids;
620 newToc->desc = strdup(desc);
621 newToc->defn = strdup(defn);
622 newToc->dropStmt = strdup(dropStmt);
623 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
627 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
628 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
629 newToc->nDeps = nDeps;
633 newToc->dependencies = NULL;
637 newToc->dataDumper = dumpFn;
638 newToc->dataDumperArg = dumpArg;
639 newToc->hadDumper = dumpFn ? true : false;
641 newToc->formatData = NULL;
643 if (AH->ArchiveEntryPtr != NULL)
644 (*AH->ArchiveEntryPtr) (AH, newToc);
649 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
651 ArchiveHandle *AH = (ArchiveHandle *) AHX;
652 TocEntry *te = AH->toc->next;
657 sav = SetOutput(AH, ropt->filename, 0 /* no compression */);
659 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
660 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
661 AH->archdbname, AH->tocCount, AH->compression);
678 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
679 ahprintf(AH, "; Format: %s\n", fmtName);
680 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
681 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
683 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
685 while (te != AH->toc)
687 if (_tocEntryRequired(te, ropt, false) != 0)
688 ahprintf(AH, "%d; %u %u %s %s %s\n", te->dumpId,
689 te->catalogId.tableoid, te->catalogId.oid,
690 te->desc, te->tag, te->owner);
695 ResetOutput(AH, sav);
702 /* Called by a dumper to signal start of a BLOB */
704 StartBlob(Archive *AHX, Oid oid)
706 ArchiveHandle *AH = (ArchiveHandle *) AHX;
708 if (!AH->StartBlobPtr)
709 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
711 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
716 /* Called by a dumper to signal end of a BLOB */
718 EndBlob(Archive *AHX, Oid oid)
720 ArchiveHandle *AH = (ArchiveHandle *) AHX;
723 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
733 * Called by a format handler before any blobs are restored
736 StartRestoreBlobs(ArchiveHandle *AH)
742 * Called by a format handler after all blobs are restored
745 EndRestoreBlobs(ArchiveHandle *AH)
749 ahlog(AH, 2, "committing large-object transactions\n");
750 CommitTransaction(AH);
753 if (AH->blobTxActive)
754 CommitTransactionXref(AH);
756 if (AH->createdBlobXref)
757 CreateBlobXrefIndex(AH);
759 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
764 * Called by a format handler to initiate restoration of a blob
767 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
773 if (!AH->createdBlobXref)
776 die_horribly(AH, modulename, "cannot restore large objects without a database connection\n");
778 CreateBlobXrefTable(AH);
779 AH->createdBlobXref = 1;
782 /* Initialize the LO Buffer */
786 * Start long-running TXs if necessary
790 ahlog(AH, 2, "starting large-object transactions\n");
791 StartTransaction(AH);
793 if (!AH->blobTxActive)
794 StartTransactionXref(AH);
796 loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
798 die_horribly(AH, modulename, "could not create large object\n");
800 ahlog(AH, 2, "restoring large object with OID %u as %u\n", oid, loOid);
802 InsertBlobXref(AH, oid, loOid);
804 AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
806 die_horribly(AH, modulename, "could not open large object\n");
812 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
814 if (AH->lo_buf_used > 0)
816 /* Write remaining bytes from the LO buffer */
819 res = lo_write(AH->connection, AH->loFd, (void *) AH->lo_buf, AH->lo_buf_used);
821 ahlog(AH, 5, "wrote remaining %lu bytes of large-object data (result = %lu)\n",
822 (unsigned long) AH->lo_buf_used, (unsigned long) res);
823 if (res != AH->lo_buf_used)
824 die_horribly(AH, modulename, "could not write to large object (result: %lu, expected: %lu)\n",
825 (unsigned long) res, (unsigned long) AH->lo_buf_used);
829 lo_close(AH->connection, AH->loFd);
833 * Commit every BLOB_BATCH_SIZE blobs...
835 if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
837 ahlog(AH, 2, "committing large-object transactions\n");
838 CommitTransaction(AH);
839 CommitTransactionXref(AH);
844 * Sorting and Reordering
848 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
850 ArchiveHandle *AH = (ArchiveHandle *) AHX;
859 /* Allocate space for the 'wanted' array, and init it */
860 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
861 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
862 ropt->limitToList = true;
864 /* Set prev entry as head of list */
868 fh = fopen(ropt->tocFile, PG_BINARY_R);
870 die_horribly(AH, modulename, "could not open TOC file\n");
872 while (fgets(buf, 1024, fh) != NULL)
875 cmnt = strchr(buf, ';');
879 /* End string at comment */
883 /* Skip if all spaces */
884 if (strspn(buf, " \t") == strlen(buf))
888 id = strtol(buf, &endptr, 10);
889 if (endptr == buf || id <= 0 || id > AH->maxDumpId)
891 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
896 te = getTocEntryByDumpId(AH, id);
898 die_horribly(AH, modulename, "could not find entry for ID %d\n",
901 ropt->idWanted[id - 1] = true;
903 _moveAfter(AH, tePrev, te);
908 die_horribly(AH, modulename, "could not close TOC file: %s\n",
912 /**********************
913 * 'Convenience functions that look like standard IO functions
914 * for writing data when in dump mode.
915 **********************/
919 archputs(const char *s, Archive *AH)
921 return WriteData(AH, s, strlen(s));
926 archprintf(Archive *AH, const char *fmt,...)
930 int bSize = strlen(fmt) + 256;
934 * This is paranoid: deal with the possibility that vsnprintf is
935 * willing to ignore trailing null
936 * or returns > 0 even if string does not fit. It may be the case that
937 * it returns cnt = bufsize
939 while (cnt < 0 || cnt >= (bSize - 1))
944 p = (char *) malloc(bSize);
946 exit_horribly(AH, modulename, "out of memory\n");
948 cnt = vsnprintf(p, bSize, fmt, ap);
951 WriteData(AH, p, cnt);
957 /*******************************
958 * Stuff below here should be 'private' to the archiver routines
959 *******************************/
962 SetOutput(ArchiveHandle *AH, char *filename, int compression)
967 /* Replace the AH output file handle */
969 sav.gzOut = AH->gzOut;
978 filename = AH->fSpec;
983 /* If compression explicitly requested, use gzopen */
985 if (compression != 0)
989 /* Don't use PG_BINARY_x since this is zlib */
990 sprintf(fmode, "wb%d", compression);
992 AH->OF = gzdopen(dup(fn), fmode);
994 AH->OF = gzopen(filename, fmode);
1001 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1003 AH->OF = fopen(filename, PG_BINARY_W);
1008 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
1014 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1019 res = GZCLOSE(AH->OF);
1021 res = fclose(AH->OF);
1024 die_horribly(AH, modulename, "could not close output file: %s\n",
1027 AH->gzOut = sav.gzOut;
1034 * Print formatted text to the output file (usually stdout).
1037 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1041 int bSize = strlen(fmt) + 256; /* Should be enough */
1045 * This is paranoid: deal with the possibility that vsnprintf is
1046 * willing to ignore trailing null
1050 * or returns > 0 even if string does not fit. It may be the case that
1051 * it returns cnt = bufsize
1053 while (cnt < 0 || cnt >= (bSize - 1))
1058 p = (char *) malloc(bSize);
1060 die_horribly(AH, modulename, "out of memory\n");
1062 cnt = vsnprintf(p, bSize, fmt, ap);
1065 ahwrite(p, 1, cnt, AH);
1071 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1075 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1079 _write_msg(NULL, fmt, ap);
1084 * Single place for logic which says 'We are restoring to a direct DB connection'.
1087 RestoringToDB(ArchiveHandle *AH)
1089 return (AH->ropt && AH->ropt->useDB && AH->connection);
1093 * Write buffer to the output file (usually stdout). This is user for
1094 * outputting 'restore' scripts etc. It is even possible for an archive
1095 * format to create a custom output routine to 'fake' a restore if it
1096 * wants to generate a script (see TAR output).
1099 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1103 if (AH->writingBlob)
1105 if (AH->lo_buf_used + size * nmemb > AH->lo_buf_size)
1107 /* Split LO buffer */
1108 size_t remaining = AH->lo_buf_size - AH->lo_buf_used;
1109 size_t slack = nmemb * size - remaining;
1111 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1112 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_size);
1113 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1114 (unsigned long) AH->lo_buf_size, (unsigned long) res);
1115 if (res != AH->lo_buf_size)
1116 die_horribly(AH, modulename,
1117 "could not write to large object (result: %lu, expected: %lu)\n",
1118 (unsigned long) res, (unsigned long) AH->lo_buf_size);
1119 memcpy(AH->lo_buf, (char *) ptr + remaining, slack);
1120 AH->lo_buf_used = slack;
1124 /* LO Buffer is still large enough, buffer it */
1125 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, size * nmemb);
1126 AH->lo_buf_used += size * nmemb;
1129 return size * nmemb;
1133 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1134 if (res != (nmemb * size))
1135 die_horribly(AH, modulename, "could not write to compressed archive\n");
1138 else if (AH->CustomOutPtr)
1140 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1142 if (res != (nmemb * size))
1143 die_horribly(AH, modulename, "could not write to custom output routine\n");
1149 * If we're doing a restore, and it's direct to DB, and we're
1150 * connected then send it to the DB.
1152 if (RestoringToDB(AH))
1153 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1156 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1158 die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
1159 (unsigned long) res, (unsigned long) nmemb);
1165 /* Common exit code */
1167 _write_msg(const char *modulename, const char *fmt, va_list ap)
1170 fprintf(stderr, "%s: [%s] ", progname, gettext(modulename));
1172 fprintf(stderr, "%s: ", progname);
1173 vfprintf(stderr, gettext(fmt), ap);
1177 write_msg(const char *modulename, const char *fmt,...)
1182 _write_msg(modulename, fmt, ap);
1188 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1190 _write_msg(modulename, fmt, ap);
1194 if (AH->public.verbose)
1195 write_msg(NULL, "*** aborted because of error\n");
1197 PQfinish(AH->connection);
1198 if (AH->blobConnection)
1199 PQfinish(AH->blobConnection);
1207 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1212 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1216 /* Archiver use (just different arg declaration) */
1218 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1223 _die_horribly(AH, modulename, fmt, ap);
1227 /* on some error, we may decide to go on... */
1229 warn_or_die_horribly(ArchiveHandle *AH,
1230 const char *modulename, const char *fmt, ...)
1234 if (AH->public.die_on_errors)
1236 _die_horribly(AH, modulename, fmt, ap);
1240 _write_msg(modulename, fmt, ap);
1241 AH->public.n_errors++;
1247 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1249 te->prev->next = te->next;
1250 te->next->prev = te->prev;
1253 te->next = pos->next;
1255 pos->next->prev = te;
1262 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1264 te->prev->next = te->next;
1265 te->next->prev = te->prev;
1267 te->prev = pos->prev;
1269 pos->prev->next = te;
1276 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1281 while (te != AH->toc)
1283 if (te->dumpId == id)
1291 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1293 TocEntry *te = getTocEntryByDumpId(AH, id);
1298 return _tocEntryRequired(te, ropt, false);
1302 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1307 (*AH->WriteBytePtr) (AH, wasSet);
1309 /* Write out off_t smallest byte first, prevents endian mismatch */
1310 for (off = 0; off < sizeof(off_t); off++)
1312 (*AH->WriteBytePtr) (AH, o & 0xFF);
1315 return sizeof(off_t) + 1;
1319 ReadOffset(ArchiveHandle *AH, off_t *o)
1325 /* Initialize to zero */
1328 /* Check for old version */
1329 if (AH->version < K_VERS_1_7)
1331 /* Prior versions wrote offsets using WriteInt */
1333 /* -1 means not set */
1335 return K_OFFSET_POS_NOT_SET;
1337 return K_OFFSET_NO_DATA;
1339 /* Cast to off_t because it was written as an int. */
1341 return K_OFFSET_POS_SET;
1345 * Read the flag indicating the state of the data pointer. Check if
1346 * valid and die if not.
1348 * This used to be handled by a negative or zero pointer, now we use an
1349 * extra byte specifically for the state.
1351 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1355 case K_OFFSET_POS_NOT_SET:
1356 case K_OFFSET_NO_DATA:
1357 case K_OFFSET_POS_SET:
1362 die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1368 for (off = 0; off < AH->offSize; off++)
1370 if (off < sizeof(off_t))
1371 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1374 if ((*AH->ReadBytePtr) (AH) != 0)
1375 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1383 WriteInt(ArchiveHandle *AH, int i)
1388 * This is a bit yucky, but I don't want to make the binary format
1389 * very dependent on representation, and not knowing much about it, I
1390 * write out a sign byte. If you change this, don't forget to change
1391 * the file version #, and modify readInt to read the new format AS
1392 * WELL AS the old formats.
1398 (*AH->WriteBytePtr) (AH, 1);
1402 (*AH->WriteBytePtr) (AH, 0);
1404 for (b = 0; b < AH->intSize; b++)
1406 (*AH->WriteBytePtr) (AH, i & 0xFF);
1410 return AH->intSize + 1;
1414 ReadInt(ArchiveHandle *AH)
1419 int sign = 0; /* Default positive */
1422 if (AH->version > K_VERS_1_0)
1423 /* Read a sign byte */
1424 sign = (*AH->ReadBytePtr) (AH);
1426 for (b = 0; b < AH->intSize; b++)
1428 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1430 res = res + (bv << bitShift);
1441 WriteStr(ArchiveHandle *AH, const char *c)
1447 res = WriteInt(AH, strlen(c));
1448 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1451 res = WriteInt(AH, -1);
1457 ReadStr(ArchiveHandle *AH)
1467 buf = (char *) malloc(l + 1);
1469 die_horribly(AH, modulename, "out of memory\n");
1471 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1479 _discoverArchiveFormat(ArchiveHandle *AH)
1482 char sig[6]; /* More than enough */
1487 write_msg(modulename, "attempting to ascertain archive format\n");
1491 free(AH->lookahead);
1493 AH->lookaheadSize = 512;
1494 AH->lookahead = calloc(1, 512);
1495 AH->lookaheadLen = 0;
1496 AH->lookaheadPos = 0;
1501 fh = fopen(AH->fSpec, PG_BINARY_R);
1507 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1509 cnt = fread(sig, 1, 5, fh);
1514 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1516 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1517 (unsigned long) cnt);
1520 /* Save it, just in case we need it later */
1521 strncpy(&AH->lookahead[0], sig, 5);
1522 AH->lookaheadLen = 5;
1524 if (strncmp(sig, "PGDMP", 5) == 0)
1526 AH->vmaj = fgetc(fh);
1527 AH->vmin = fgetc(fh);
1529 /* Save these too... */
1530 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1531 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1533 /* Check header version; varies from V1.0 */
1534 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1536 AH->vrev = fgetc(fh);
1537 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1542 /* Make a convenient integer <maj><min><rev>00 */
1543 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1545 AH->intSize = fgetc(fh);
1546 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1548 if (AH->version >= K_VERS_1_7)
1550 AH->offSize = fgetc(fh);
1551 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1554 AH->offSize = AH->intSize;
1556 AH->format = fgetc(fh);
1557 AH->lookahead[AH->lookaheadLen++] = AH->format;
1562 * *Maybe* we have a tar archive format file... So, read first 512
1565 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1566 AH->lookaheadLen += cnt;
1568 if (AH->lookaheadLen != 512)
1569 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1571 if (!isValidTarHeader(AH->lookahead))
1572 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1574 AH->format = archTar;
1577 /* If we can't seek, then mark the header as read */
1578 if (fseeko(fh, 0, SEEK_SET) != 0)
1581 * NOTE: Formats that use the lookahead buffer can unset this in
1582 * their Init routine.
1587 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1590 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1591 (unsigned long) AH->lookaheadLen);
1594 /* Close the file */
1596 if (fclose(fh) != 0)
1597 die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
1605 * Allocate an archive handle
1607 static ArchiveHandle *
1608 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1609 const int compression, ArchiveMode mode)
1614 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1617 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1619 die_horribly(AH, modulename, "out of memory\n");
1621 /* AH->debugLevel = 100; */
1623 AH->vmaj = K_VERS_MAJOR;
1624 AH->vmin = K_VERS_MINOR;
1625 AH->vrev = K_VERS_REV;
1627 AH->createDate = time(NULL);
1629 AH->intSize = sizeof(int);
1630 AH->offSize = sizeof(off_t);
1633 AH->fSpec = strdup(FileSpec);
1636 * Not used; maybe later....
1638 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1639 * i--) if (AH->workDir[i-1] == '/')
1645 AH->currUser = strdup(""); /* So it's valid, but we can free() it
1646 * later if necessary */
1647 AH->currSchema = strdup(""); /* ditto */
1648 AH->currWithOids = -1; /* force SET */
1650 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1652 die_horribly(AH, modulename, "out of memory\n");
1654 AH->toc->next = AH->toc;
1655 AH->toc->prev = AH->toc;
1658 AH->compression = compression;
1660 AH->pgCopyBuf = createPQExpBuffer();
1661 AH->sqlBuf = createPQExpBuffer();
1663 /* Open stdout with no compression for AH output handle */
1668 write_msg(modulename, "archive format is %d\n", fmt);
1671 if (fmt == archUnknown)
1672 AH->format = _discoverArchiveFormat(AH);
1680 InitArchiveFmt_Custom(AH);
1684 InitArchiveFmt_Files(AH);
1688 InitArchiveFmt_Null(AH);
1692 InitArchiveFmt_Tar(AH);
1696 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1699 /* sql error handling */
1700 AH->public.die_on_errors = true;
1701 AH->public.n_errors = 0;
1708 WriteDataChunks(ArchiveHandle *AH)
1710 TocEntry *te = AH->toc->next;
1711 StartDataPtr startPtr;
1714 while (te != AH->toc)
1716 if (te->dataDumper != NULL)
1719 /* printf("Writing data for %d (%x)\n", te->id, te); */
1721 if (strcmp(te->desc, "BLOBS") == 0)
1723 startPtr = AH->StartBlobsPtr;
1724 endPtr = AH->EndBlobsPtr;
1728 startPtr = AH->StartDataPtr;
1729 endPtr = AH->EndDataPtr;
1732 if (startPtr != NULL)
1733 (*startPtr) (AH, te);
1736 * printf("Dumper arg for %d is %x\n", te->id,
1737 * te->dataDumperArg);
1741 * The user-provided DataDumper routine needs to call
1744 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1755 WriteToc(ArchiveHandle *AH)
1761 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1763 WriteInt(AH, AH->tocCount);
1765 for (te = AH->toc->next; te != AH->toc; te = te->next)
1767 WriteInt(AH, te->dumpId);
1768 WriteInt(AH, te->dataDumper ? 1 : 0);
1770 /* OID is recorded as a string for historical reasons */
1771 sprintf(workbuf, "%u", te->catalogId.tableoid);
1772 WriteStr(AH, workbuf);
1773 sprintf(workbuf, "%u", te->catalogId.oid);
1774 WriteStr(AH, workbuf);
1776 WriteStr(AH, te->tag);
1777 WriteStr(AH, te->desc);
1778 WriteStr(AH, te->defn);
1779 WriteStr(AH, te->dropStmt);
1780 WriteStr(AH, te->copyStmt);
1781 WriteStr(AH, te->namespace);
1782 WriteStr(AH, te->owner);
1783 WriteStr(AH, te->withOids ? "true" : "false");
1785 /* Dump list of dependencies */
1786 for (i = 0; i < te->nDeps; i++)
1788 sprintf(workbuf, "%d", te->dependencies[i]);
1789 WriteStr(AH, workbuf);
1791 WriteStr(AH, NULL); /* Terminate List */
1793 if (AH->WriteExtraTocPtr)
1794 (*AH->WriteExtraTocPtr) (AH, te);
1799 ReadToc(ArchiveHandle *AH)
1807 TocEntry *te = AH->toc->next;
1809 AH->tocCount = ReadInt(AH);
1812 for (i = 0; i < AH->tocCount; i++)
1814 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1815 te->dumpId = ReadInt(AH);
1817 if (te->dumpId > AH->maxDumpId)
1818 AH->maxDumpId = te->dumpId;
1821 if (te->dumpId <= 0)
1822 die_horribly(AH, modulename,
1823 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1826 te->hadDumper = ReadInt(AH);
1828 if (AH->version >= K_VERS_1_8)
1831 sscanf(tmp, "%u", &te->catalogId.tableoid);
1835 te->catalogId.tableoid = InvalidOid;
1837 sscanf(tmp, "%u", &te->catalogId.oid);
1840 te->tag = ReadStr(AH);
1841 te->desc = ReadStr(AH);
1842 te->defn = ReadStr(AH);
1843 te->dropStmt = ReadStr(AH);
1845 if (AH->version >= K_VERS_1_3)
1846 te->copyStmt = ReadStr(AH);
1848 if (AH->version >= K_VERS_1_6)
1849 te->namespace = ReadStr(AH);
1851 te->owner = ReadStr(AH);
1852 if (AH->version >= K_VERS_1_9)
1854 if (strcmp(ReadStr(AH), "true") == 0)
1855 te->withOids = true;
1857 te->withOids = false;
1860 te->withOids = true;
1862 /* Read TOC entry dependencies */
1863 if (AH->version >= K_VERS_1_5)
1866 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1872 break; /* end of list */
1873 if (depIdx >= depSize)
1876 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1878 sscanf(tmp, "%d", &deps[depIdx]);
1883 if (depIdx > 0) /* We have a non-null entry */
1885 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1886 te->dependencies = deps;
1892 te->dependencies = NULL;
1898 te->dependencies = NULL;
1902 if (AH->ReadExtraTocPtr)
1903 (*AH->ReadExtraTocPtr) (AH, te);
1905 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1906 i, te->dumpId, te->desc, te->tag);
1908 te->prev = AH->toc->prev;
1909 AH->toc->prev->next = te;
1916 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool ownerAndACL)
1918 teReqs res = 3; /* Schema = 1, Data = 2, Both = 3 */
1920 /* ENCODING objects are dumped specially, so always reject here */
1921 if (strcmp(te->desc, "ENCODING") == 0)
1924 /* If it's an ACL, maybe ignore it */
1925 if ((!ownerAndACL || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1928 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1931 /* Check if tablename only is wanted */
1934 if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1936 if (!ropt->selTable)
1938 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1941 else if (strcmp(te->desc, "INDEX") == 0)
1943 if (!ropt->selIndex)
1945 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1948 else if (strcmp(te->desc, "FUNCTION") == 0)
1950 if (!ropt->selFunction)
1952 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1955 else if (strcmp(te->desc, "TRIGGER") == 0)
1957 if (!ropt->selTrigger)
1959 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
1967 * Check if we had a dataDumper. Indicates if the entry is schema or
1973 * Special Case: If 'SEQUENCE SET' then it is considered a data
1976 if (strcmp(te->desc, "SEQUENCE SET") == 0)
1977 res = res & REQ_DATA;
1979 res = res & ~REQ_DATA;
1983 * Special case: <Init> type with <Max OID> tag; this is part of a
1984 * DATA restore even though it has SQL.
1986 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
1989 /* Mask it if we only want schema */
1990 if (ropt->schemaOnly)
1991 res = res & REQ_SCHEMA;
1993 /* Mask it we only want data */
1995 res = res & REQ_DATA;
1997 /* Mask it if we don't have a schema contribution */
1998 if (!te->defn || strlen(te->defn) == 0)
1999 res = res & ~REQ_SCHEMA;
2001 /* Finally, if we used a list, limit based on that as well */
2002 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2009 * Issue SET commands for parameters that we want to have set the same way
2010 * at all times during execution of a restore script.
2013 _doSetFixedOutputState(ArchiveHandle *AH)
2017 /* If we have an encoding setting, emit that */
2019 while (te != AH->toc)
2021 if (strcmp(te->desc, "ENCODING") == 0)
2023 ahprintf(AH, "%s", te->defn);
2029 /* Make sure function checking is disabled */
2030 ahprintf(AH, "SET check_function_bodies = false;\n");
2036 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2037 * for updating state if appropriate. If user is NULL or an empty string,
2038 * the specification DEFAULT will be used.
2041 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2043 PQExpBuffer cmd = createPQExpBuffer();
2045 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2048 * SQL requires a string literal here. Might as well be correct.
2051 appendStringLiteral(cmd, user, false);
2053 appendPQExpBuffer(cmd, "DEFAULT");
2054 appendPQExpBuffer(cmd, ";");
2056 if (RestoringToDB(AH))
2060 res = PQexec(AH->connection, cmd->data);
2062 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2063 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2064 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2065 user, PQerrorMessage(AH->connection));
2070 ahprintf(AH, "%s\n\n", cmd->data);
2072 destroyPQExpBuffer(cmd);
2077 * Issue a SET default_with_oids command. Caller is responsible
2078 * for updating state if appropriate.
2081 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2083 PQExpBuffer cmd = createPQExpBuffer();
2085 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2088 if (RestoringToDB(AH))
2092 res = PQexec(AH->connection, cmd->data);
2094 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2095 warn_or_die_horribly(AH, modulename,
2096 "could not set default_with_oids: %s",
2097 PQerrorMessage(AH->connection));
2102 ahprintf(AH, "%s\n\n", cmd->data);
2104 destroyPQExpBuffer(cmd);
2109 * Issue the commands to connect to the specified database
2110 * as the specified user.
2112 * If we're currently restoring right into a database, this will
2113 * actually establish a connection. Otherwise it puts a \connect into
2114 * the script output.
2117 _reconnectToDB(ArchiveHandle *AH, const char *dbname, const char *user)
2119 if (RestoringToDB(AH))
2120 ReconnectToServer(AH, dbname, user);
2123 PQExpBuffer qry = createPQExpBuffer();
2125 appendPQExpBuffer(qry, "\\connect %s",
2126 dbname ? fmtId(dbname) : "-");
2127 appendPQExpBuffer(qry, " %s\n\n",
2130 ahprintf(AH, qry->data);
2132 destroyPQExpBuffer(qry);
2136 * NOTE: currUser keeps track of what the imaginary session user in
2142 AH->currUser = strdup(user);
2144 /* don't assume we still know the output schema */
2146 free(AH->currSchema);
2147 AH->currSchema = strdup("");
2148 AH->currWithOids = -1;
2150 /* re-establish fixed state */
2151 _doSetFixedOutputState(AH);
2155 * Become the specified user, and update state to avoid redundant commands
2157 * NULL or empty argument is taken to mean restoring the session default
2160 _becomeUser(ArchiveHandle *AH, const char *user)
2163 user = ""; /* avoid null pointers */
2165 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2166 return; /* no need to do anything */
2168 _doSetSessionAuth(AH, user);
2171 * NOTE: currUser keeps track of what the imaginary session user in
2177 AH->currUser = strdup(user);
2181 * Become the owner of the the given TOC entry object. If
2182 * changes in ownership are not allowed, this doesn't do anything.
2185 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2187 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2190 _becomeUser(AH, te->owner);
2195 * Set the proper default_with_oids value for the table.
2198 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2200 if (AH->currWithOids != te->withOids)
2202 _doSetWithOids(AH, te->withOids);
2203 AH->currWithOids = te->withOids;
2209 * Issue the commands to select the specified schema as the current schema
2210 * in the target database.
2213 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2217 if (!schemaName || *schemaName == '\0' ||
2218 strcmp(AH->currSchema, schemaName) == 0)
2219 return; /* no need to do anything */
2221 qry = createPQExpBuffer();
2223 appendPQExpBuffer(qry, "SET search_path = %s",
2225 if (strcmp(schemaName, "pg_catalog") != 0)
2226 appendPQExpBuffer(qry, ", pg_catalog");
2228 if (RestoringToDB(AH))
2232 res = PQexec(AH->connection, qry->data);
2234 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2235 warn_or_die_horribly(AH, modulename,
2236 "could not set search_path to \"%s\": %s",
2237 schemaName, PQerrorMessage(AH->connection));
2242 ahprintf(AH, "%s;\n\n", qry->data);
2245 free(AH->currSchema);
2246 AH->currSchema = strdup(schemaName);
2248 destroyPQExpBuffer(qry);
2253 * Parses the dropStmt part of a TOC entry and returns
2254 * a newly allocated string that is the object identifier
2255 * The caller must free the result.
2258 _getObjectFromDropStmt(const char *dropStmt, const char *type)
2260 /* Chop "DROP" off the front and make a copy */
2261 char *first = strdup(dropStmt + 5);
2262 char *last = first + strlen(first) - 1; /* Points to the last real char in extract */
2265 /* Loop from the end of the string until last char is no longer '\n' or ';' */
2266 while (last >= first && (*last == '\n' || *last == ';')) {
2270 /* Insert end of string one place after last */
2273 /* Take off CASCADE if necessary. Only TYPEs seem to have this, but may
2274 * as well check for all */
2275 if ((last - first) >= 8) {
2276 if (strcmp(last - 7, " CASCADE") == 0)
2280 /* Insert end of string one place after last */
2283 /* Special case VIEWs and SEQUENCEs. They must use ALTER TABLE. */
2284 if (strcmp(type, "VIEW") == 0 && (last - first) >= 5)
2286 int len = 6 + strlen(first + 5) + 1;
2288 snprintf(buf, len, "TABLE %s", first + 5);
2291 else if (strcmp(type, "SEQUENCE") == 0 && (last - first) >= 9)
2293 int len = 6 + strlen(first + 9) + 1;
2295 snprintf(buf, len, "TABLE %s", first + 9);
2307 _printTocHeader(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData)
2316 ahprintf(AH, "--\n");
2317 if (AH->public.verbose)
2319 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2320 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2325 ahprintf(AH, "-- Dependencies:");
2326 for (i = 0; i < te->nDeps; i++)
2327 ahprintf(AH, " %d", te->dependencies[i]);
2331 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s\n",
2332 pfx, te->tag, te->desc,
2333 te->namespace ? te->namespace : "-",
2335 if (AH->PrintExtraTocPtr != NULL)
2336 (*AH->PrintExtraTocPtr) (AH, te);
2337 ahprintf(AH, "--\n\n");
2341 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool ownerAndACL)
2343 /* Select schema as necessary */
2344 _becomeOwner(AH, te);
2345 _selectOutputSchema(AH, te->namespace);
2346 if (strcmp(te->desc, "TABLE") == 0 && !ownerAndACL)
2347 _setWithOids(AH, te);
2349 if (!ropt->noOwner && !ropt->use_setsessauth && ownerAndACL && strlen(te->owner) > 0 && strlen(te->dropStmt) > 0 && (
2350 strcmp(te->desc, "AGGREGATE") == 0 ||
2351 strcmp(te->desc, "CONVERSION") == 0 ||
2352 strcmp(te->desc, "DOMAIN") == 0 ||
2353 strcmp(te->desc, "FUNCTION") == 0 ||
2354 strcmp(te->desc, "OPERATOR") == 0 ||
2355 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2356 strcmp(te->desc, "TABLE") == 0 ||
2357 strcmp(te->desc, "TYPE") == 0 ||
2358 strcmp(te->desc, "VIEW") == 0 ||
2359 strcmp(te->desc, "SEQUENCE") == 0 ||
2360 (strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0) /* Only public schema */
2363 char *temp = _getObjectFromDropStmt(te->dropStmt, te->desc);
2364 _printTocHeader(AH, te, ropt, isData);
2365 ahprintf(AH, "ALTER %s OWNER TO %s;\n\n", temp, fmtId(te->owner));
2368 else if (ownerAndACL && strcmp(te->desc, "ACL") == 0)
2370 _printTocHeader(AH, te, ropt, isData);
2371 ahprintf(AH, "%s\n\n", te->defn);
2373 else if (!ownerAndACL && strlen(te->defn) > 0)
2375 _printTocHeader(AH, te, ropt, isData);
2378 * Really crude hack for suppressing AUTHORIZATION clause of CREATE SCHEMA
2379 * when --no-owner mode is selected. This is ugly, but I see no other
2380 * good way ... Also, avoid dumping the public schema as it will already be
2383 if (strcmp(te->tag, "public") != 0) {
2384 if (AH->ropt && AH->ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2386 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", te->tag);
2390 ahprintf(AH, "%s\n\n", te->defn);
2395 _printTocHeader(AH, te, ropt, isData);
2399 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2400 * commands, so we can no longer assume we know the current auth setting.
2402 if (strncmp(te->desc, "ACL", 3) == 0)
2406 AH->currUser = NULL;
2413 WriteHead(ArchiveHandle *AH)
2417 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2418 (*AH->WriteBytePtr) (AH, AH->vmaj);
2419 (*AH->WriteBytePtr) (AH, AH->vmin);
2420 (*AH->WriteBytePtr) (AH, AH->vrev);
2421 (*AH->WriteBytePtr) (AH, AH->intSize);
2422 (*AH->WriteBytePtr) (AH, AH->offSize);
2423 (*AH->WriteBytePtr) (AH, AH->format);
2426 if (AH->compression != 0)
2427 write_msg(modulename, "WARNING: requested compression not available in this "
2428 "installation -- archive will be uncompressed\n");
2430 AH->compression = 0;
2433 WriteInt(AH, AH->compression);
2435 crtm = *localtime(&AH->createDate);
2436 WriteInt(AH, crtm.tm_sec);
2437 WriteInt(AH, crtm.tm_min);
2438 WriteInt(AH, crtm.tm_hour);
2439 WriteInt(AH, crtm.tm_mday);
2440 WriteInt(AH, crtm.tm_mon);
2441 WriteInt(AH, crtm.tm_year);
2442 WriteInt(AH, crtm.tm_isdst);
2443 WriteStr(AH, PQdb(AH->connection));
2447 ReadHead(ArchiveHandle *AH)
2453 /* If we haven't already read the header... */
2454 if (!AH->readHeader)
2457 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2459 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2460 die_horribly(AH, modulename, "did not find magic string in file header\n");
2462 AH->vmaj = (*AH->ReadBytePtr) (AH);
2463 AH->vmin = (*AH->ReadBytePtr) (AH);
2465 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2466 AH->vrev = (*AH->ReadBytePtr) (AH);
2470 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2473 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2474 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2475 AH->vmaj, AH->vmin);
2477 AH->intSize = (*AH->ReadBytePtr) (AH);
2478 if (AH->intSize > 32)
2479 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2480 (unsigned long) AH->intSize);
2482 if (AH->intSize > sizeof(int))
2483 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2485 if (AH->version >= K_VERS_1_7)
2486 AH->offSize = (*AH->ReadBytePtr) (AH);
2488 AH->offSize = AH->intSize;
2490 fmt = (*AH->ReadBytePtr) (AH);
2492 if (AH->format != fmt)
2493 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2497 if (AH->version >= K_VERS_1_2)
2499 if (AH->version < K_VERS_1_4)
2500 AH->compression = (*AH->ReadBytePtr) (AH);
2502 AH->compression = ReadInt(AH);
2505 AH->compression = Z_DEFAULT_COMPRESSION;
2508 if (AH->compression != 0)
2509 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2512 if (AH->version >= K_VERS_1_4)
2514 crtm.tm_sec = ReadInt(AH);
2515 crtm.tm_min = ReadInt(AH);
2516 crtm.tm_hour = ReadInt(AH);
2517 crtm.tm_mday = ReadInt(AH);
2518 crtm.tm_mon = ReadInt(AH);
2519 crtm.tm_year = ReadInt(AH);
2520 crtm.tm_isdst = ReadInt(AH);
2522 AH->archdbname = ReadStr(AH);
2524 AH->createDate = mktime(&crtm);
2526 if (AH->createDate == (time_t) -1)
2527 write_msg(modulename, "WARNING: invalid creation date in header\n");
2535 * check to see if fseek can be performed.
2542 if (fseeko(fp, 0, SEEK_CUR) != 0)
2544 else if (sizeof(off_t) > sizeof(long))
2547 * At this point, off_t is too large for long, so we return based
2548 * on whether an off_t version of fseek is available.