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.96 2004/08/30 19:44:14 tgl 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 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
54 static void fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte,
55 RestoreOptions *ropt);
56 static void _doSetFixedOutputState(ArchiveHandle *AH);
57 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
58 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
59 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname, const char *user);
60 static void _becomeUser(ArchiveHandle *AH, const char *user);
61 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
62 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
64 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool acl_pass);
65 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
66 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
67 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
68 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
69 static int _discoverArchiveFormat(ArchiveHandle *AH);
71 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
72 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
74 static int _canRestoreBlobs(ArchiveHandle *AH);
75 static int _restoringToDB(ArchiveHandle *AH);
81 * The objective it to make writing new formats and dumpers as simple
82 * as possible, if necessary at the expense of extra function calls etc.
87 /* Create a new archive */
90 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
91 const int compression)
94 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
96 return (Archive *) AH;
99 /* Open an existing archive */
102 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
104 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
106 return (Archive *) AH;
111 CloseArchive(Archive *AHX)
114 ArchiveHandle *AH = (ArchiveHandle *) AHX;
116 (*AH->ClosePtr) (AH);
118 /* Close the output */
120 res = GZCLOSE(AH->OF);
121 else if (AH->OF != stdout)
122 res = fclose(AH->OF);
125 die_horribly(AH, modulename, "could not close output archive file\n");
130 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
132 ArchiveHandle *AH = (ArchiveHandle *) AHX;
133 TocEntry *te = AH->toc->next;
140 AH->stage = STAGE_INITIALIZING;
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);
172 * If we're talking to the DB directly, don't send comments since
173 * they obscure SQL when displaying errors
175 AH->noTocComments = 1;
179 * Work out if we have an implied data-only restore. This can happen
180 * if the dump was data only or if the user has used a toc list to
181 * exclude all of the schema data. All we do is look for schema
182 * entries - if none are found then we set the dataOnly flag.
184 * We could scan for wanted TABLE entries, but that is not the same as
185 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
191 while (te != AH->toc)
193 reqs = _tocEntryRequired(te, ropt, false);
194 if ((reqs & REQ_SCHEMA) != 0)
195 { /* It's schema, and it's wanted */
203 ropt->dataOnly = impliedDataOnly;
204 ahlog(AH, 1, "implied data-only restore\n");
209 * Setup the output file if necessary.
211 if (ropt->filename || ropt->compression)
212 sav = SetOutput(AH, ropt->filename, ropt->compression);
214 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
217 * Establish important parameter values right away.
219 _doSetFixedOutputState(AH);
221 AH->stage = STAGE_PROCESSING;
224 * Drop the items at the start, in reverse order
226 if (ropt->dropSchema)
231 while (te != AH->toc)
233 reqs = _tocEntryRequired(te, ropt, false);
234 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
236 /* We want the schema */
237 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
238 /* Select owner and schema as necessary */
239 _becomeOwner(AH, te);
240 _selectOutputSchema(AH, te->namespace);
242 ahprintf(AH, "%s", te->dropStmt);
249 * Now process each TOC entry
252 while (te != AH->toc)
256 /* Work out what, if anything, we want from this entry */
257 reqs = _tocEntryRequired(te, ropt, false);
259 /* Dump any relevant dump warnings to stderr */
260 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
262 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
263 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
264 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
265 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
270 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
272 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
274 _printTocEntry(AH, te, ropt, false, false);
277 /* If we created a DB, connect to it... */
278 if (strcmp(te->desc, "DATABASE") == 0)
280 ahlog(AH, 1, "connecting to new database \"%s\" as user \"%s\"\n", te->tag, te->owner);
281 _reconnectToDB(AH, te->tag, te->owner);
286 * If we have a data component, then process it
288 if ((reqs & REQ_DATA) != 0)
291 * hadDumper will be set if there is genuine data component
292 * for this node. Otherwise, we need to check the defn field
293 * for statements that need to be executed in data-only
299 * If we can output the data, then restore it.
301 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
304 if (AH->compression != 0)
305 die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
308 _printTocEntry(AH, te, ropt, true, false);
311 * Maybe we can't do BLOBS, so check if this node is
314 if ((strcmp(te->desc, "BLOBS") == 0) &&
315 !_canRestoreBlobs(AH))
317 ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
320 * This is a bit nasty - we assume, for the
321 * moment, that if a custom output is used, then
322 * we don't want warnings.
324 if (!AH->CustomOutPtr)
325 write_msg(modulename, "WARNING: skipping large-object restoration\n");
329 _disableTriggersIfNecessary(AH, te, ropt);
331 /* Select owner and schema as necessary */
332 _becomeOwner(AH, te);
333 _selectOutputSchema(AH, te->namespace);
335 ahlog(AH, 1, "restoring data for table \"%s\"\n", te->tag);
338 * If we have a copy statement, use it. As of
339 * V1.3, these are separate to allow easy import
340 * from withing a database connection. Pre 1.3
341 * archives can not use DB connections and are
342 * sent to output only.
344 * For V1.3+, the table data MUST have a copy
345 * statement so that we can go into appropriate
348 if (te->copyStmt && strlen(te->copyStmt) > 0)
349 ahprintf(AH, te->copyStmt);
351 (*AH->PrintTocDataPtr) (AH, te, ropt);
354 * If we just restored blobs, fix references in
355 * previously-loaded tables; otherwise, if we
356 * previously restored blobs, fix references in
357 * this table. Note that in standard cases the
358 * BLOBS entry comes after all TABLE DATA entries,
359 * but we should cope with other orders in case
360 * the user demands reordering.
362 if (strcmp(te->desc, "BLOBS") == 0)
363 fixPriorBlobRefs(AH, te, ropt);
364 else if (AH->createdBlobXref &&
365 strcmp(te->desc, "TABLE DATA") == 0)
367 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
368 FixupBlobRefs(AH, te);
371 _enableTriggersIfNecessary(AH, te, ropt);
375 else if (!defnDumped)
377 /* If we haven't already dumped the defn part, do so now */
378 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
379 _printTocEntry(AH, te, ropt, false, false);
383 } /* end loop over TOC entries */
386 * Scan TOC again to output ownership commands and ACLs
389 while (te != AH->toc)
393 /* Work out what, if anything, we want from this entry */
394 reqs = _tocEntryRequired(te, ropt, true);
396 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
398 ahlog(AH, 1, "setting owner and acl for %s %s\n",
400 _printTocEntry(AH, te, ropt, false, true);
407 * Clean up & we're done.
409 AH->stage = STAGE_FINALIZING;
411 if (ropt->filename || ropt->compression)
412 ResetOutput(AH, sav);
416 PQfinish(AH->connection);
417 AH->connection = NULL;
419 if (AH->blobConnection)
421 PQfinish(AH->blobConnection);
422 AH->blobConnection = NULL;
426 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
430 * After restoring BLOBS, fix all blob references in previously-restored
431 * tables. (Normally, the BLOBS entry should appear after all TABLE DATA
432 * entries, so this will in fact handle all blob references.)
435 fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte, RestoreOptions *ropt)
440 if (AH->createdBlobXref)
442 /* NULL parameter means disable ALL user triggers */
443 _disableTriggersIfNecessary(AH, NULL, ropt);
445 for (te = AH->toc->next; te != blobte; te = te->next)
447 if (strcmp(te->desc, "TABLE DATA") == 0)
449 reqs = _tocEntryRequired(te, ropt, false);
451 if ((reqs & REQ_DATA) != 0) /* We loaded the data */
453 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
454 FixupBlobRefs(AH, te);
459 /* NULL parameter means enable ALL user triggers */
460 _enableTriggersIfNecessary(AH, NULL, ropt);
465 * Allocate a new RestoreOptions block.
466 * This is mainly so we can initialize it, but also for future expansion,
469 NewRestoreOptions(void)
471 RestoreOptions *opts;
473 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
475 opts->format = archUnknown;
476 opts->suppressDumpWarnings = false;
477 opts->exit_on_error = false;
483 * Returns true if we're restoring directly to the database (and
484 * aren't just making a psql script that can do the restoration).
487 _restoringToDB(ArchiveHandle *AH)
489 return (AH->ropt->useDB && AH->connection);
493 _canRestoreBlobs(ArchiveHandle *AH)
495 return _restoringToDB(AH);
499 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
501 /* This hack is only needed in a data-only restore */
502 if (!ropt->dataOnly || !ropt->disable_triggers)
505 /* Don't do it for the BLOBS TocEntry, either */
506 if (te && strcmp(te->desc, "BLOBS") == 0)
510 * Become superuser if possible, since they are the only ones who can
511 * update pg_class. If -S was not given, assume the initial user
512 * identity is a superuser.
514 _becomeUser(AH, ropt->superuser);
516 ahlog(AH, 1, "disabling triggers\n");
519 * Disable them. This is a hack. Needs to be done via an appropriate
520 * 'SET' command when one is available.
522 ahprintf(AH, "-- Disable triggers\n");
525 * Just update the AFFECTED table, if known. Otherwise update all
528 if (te && te->tag && strlen(te->tag) > 0)
529 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
530 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
533 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
534 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
538 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
540 /* This hack is only needed in a data-only restore */
541 if (!ropt->dataOnly || !ropt->disable_triggers)
544 /* Don't do it for the BLOBS TocEntry, either */
545 if (te && strcmp(te->desc, "BLOBS") == 0)
549 * Become superuser if possible, since they are the only ones who can
550 * update pg_class. If -S was not given, assume the initial user
551 * identity is a superuser.
553 _becomeUser(AH, ropt->superuser);
555 ahlog(AH, 1, "enabling triggers\n");
558 * Enable them. This is a hack. Needs to be done via an appropriate
559 * 'SET' command when one is available.
561 ahprintf(AH, "-- Enable triggers\n");
564 * Just update the AFFECTED table, if known. Otherwise update all
567 if (te && te->tag && strlen(te->tag) > 0)
568 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
569 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
570 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
573 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
574 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
575 "FROM pg_catalog.pg_namespace "
576 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
580 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
585 WriteData(Archive *AHX, const void *data, size_t dLen)
587 ArchiveHandle *AH = (ArchiveHandle *) AHX;
590 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
592 return (*AH->WriteDataPtr) (AH, data, dLen);
596 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
597 * repository for all metadata. But the name has stuck.
602 ArchiveEntry(Archive *AHX,
603 CatalogId catalogId, DumpId dumpId,
605 const char *namespace, const char *owner, bool withOids,
606 const char *desc, const char *defn,
607 const char *dropStmt, const char *copyStmt,
608 const DumpId *deps, int nDeps,
609 DataDumperPtr dumpFn, void *dumpArg)
611 ArchiveHandle *AH = (ArchiveHandle *) AHX;
614 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
616 die_horribly(AH, modulename, "out of memory\n");
619 if (dumpId > AH->maxDumpId)
620 AH->maxDumpId = dumpId;
622 newToc->prev = AH->toc->prev;
623 newToc->next = AH->toc;
624 AH->toc->prev->next = newToc;
625 AH->toc->prev = newToc;
627 newToc->catalogId = catalogId;
628 newToc->dumpId = dumpId;
630 newToc->tag = strdup(tag);
631 newToc->namespace = namespace ? strdup(namespace) : NULL;
632 newToc->owner = strdup(owner);
633 newToc->withOids = withOids;
634 newToc->desc = strdup(desc);
635 newToc->defn = strdup(defn);
636 newToc->dropStmt = strdup(dropStmt);
637 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
641 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
642 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
643 newToc->nDeps = nDeps;
647 newToc->dependencies = NULL;
651 newToc->dataDumper = dumpFn;
652 newToc->dataDumperArg = dumpArg;
653 newToc->hadDumper = dumpFn ? true : false;
655 newToc->formatData = NULL;
657 if (AH->ArchiveEntryPtr !=NULL)
658 (*AH->ArchiveEntryPtr) (AH, newToc);
663 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
665 ArchiveHandle *AH = (ArchiveHandle *) AHX;
666 TocEntry *te = AH->toc->next;
671 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
673 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
674 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
675 AH->archdbname, AH->tocCount, AH->compression);
692 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
693 ahprintf(AH, "; Format: %s\n", fmtName);
694 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
695 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
697 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
699 while (te != AH->toc)
701 if (_tocEntryRequired(te, ropt, false) != 0)
702 ahprintf(AH, "%d; %u %u %s %s %s\n", te->dumpId,
703 te->catalogId.tableoid, te->catalogId.oid,
704 te->desc, te->tag, te->owner);
709 ResetOutput(AH, sav);
716 /* Called by a dumper to signal start of a BLOB */
718 StartBlob(Archive *AHX, Oid oid)
720 ArchiveHandle *AH = (ArchiveHandle *) AHX;
722 if (!AH->StartBlobPtr)
723 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
725 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
730 /* Called by a dumper to signal end of a BLOB */
732 EndBlob(Archive *AHX, Oid oid)
734 ArchiveHandle *AH = (ArchiveHandle *) AHX;
737 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
747 * Called by a format handler before any blobs are restored
750 StartRestoreBlobs(ArchiveHandle *AH)
756 * Called by a format handler after all blobs are restored
759 EndRestoreBlobs(ArchiveHandle *AH)
763 ahlog(AH, 2, "committing large-object transactions\n");
764 CommitTransaction(AH);
767 if (AH->blobTxActive)
768 CommitTransactionXref(AH);
770 if (AH->createdBlobXref)
771 CreateBlobXrefIndex(AH);
773 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
778 * Called by a format handler to initiate restoration of a blob
781 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
787 if (!AH->createdBlobXref)
790 die_horribly(AH, modulename, "cannot restore large objects without a database connection\n");
792 CreateBlobXrefTable(AH);
793 AH->createdBlobXref = 1;
796 /* Initialize the LO Buffer */
800 * Start long-running TXs if necessary
804 ahlog(AH, 2, "starting large-object transactions\n");
805 StartTransaction(AH);
807 if (!AH->blobTxActive)
808 StartTransactionXref(AH);
810 loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
812 die_horribly(AH, modulename, "could not create large object\n");
814 ahlog(AH, 2, "restoring large object with OID %u as %u\n", oid, loOid);
816 InsertBlobXref(AH, oid, loOid);
818 AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
820 die_horribly(AH, modulename, "could not open large object\n");
826 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
828 if (AH->lo_buf_used > 0)
830 /* Write remaining bytes from the LO buffer */
833 res = lo_write(AH->connection, AH->loFd, (void *) AH->lo_buf, AH->lo_buf_used);
835 ahlog(AH, 5, "wrote remaining %lu bytes of large-object data (result = %lu)\n",
836 (unsigned long) AH->lo_buf_used, (unsigned long) res);
837 if (res != AH->lo_buf_used)
838 die_horribly(AH, modulename, "could not write to large object (result: %lu, expected: %lu)\n",
839 (unsigned long) res, (unsigned long) AH->lo_buf_used);
843 lo_close(AH->connection, AH->loFd);
847 * Commit every BLOB_BATCH_SIZE blobs...
849 if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
851 ahlog(AH, 2, "committing large-object transactions\n");
852 CommitTransaction(AH);
853 CommitTransactionXref(AH);
858 * Sorting and Reordering
862 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
864 ArchiveHandle *AH = (ArchiveHandle *) AHX;
873 /* Allocate space for the 'wanted' array, and init it */
874 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
875 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
876 ropt->limitToList = true;
878 /* Set prev entry as head of list */
882 fh = fopen(ropt->tocFile, PG_BINARY_R);
884 die_horribly(AH, modulename, "could not open TOC file\n");
886 while (fgets(buf, 1024, fh) != NULL)
889 cmnt = strchr(buf, ';');
893 /* End string at comment */
897 /* Skip if all spaces */
898 if (strspn(buf, " \t") == strlen(buf))
902 id = strtol(buf, &endptr, 10);
903 if (endptr == buf || id <= 0 || id > AH->maxDumpId)
905 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
910 te = getTocEntryByDumpId(AH, id);
912 die_horribly(AH, modulename, "could not find entry for ID %d\n",
915 ropt->idWanted[id - 1] = true;
917 _moveAfter(AH, tePrev, te);
922 die_horribly(AH, modulename, "could not close TOC file: %s\n",
926 /**********************
927 * 'Convenience functions that look like standard IO functions
928 * for writing data when in dump mode.
929 **********************/
933 archputs(const char *s, Archive *AH)
935 return WriteData(AH, s, strlen(s));
940 archprintf(Archive *AH, const char *fmt,...)
944 int bSize = strlen(fmt) + 256;
948 * This is paranoid: deal with the possibility that vsnprintf is
949 * willing to ignore trailing null or returns > 0 even if string does
950 * not fit. It may be the case that it returns cnt = bufsize
952 while (cnt < 0 || cnt >= (bSize - 1))
957 p = (char *) malloc(bSize);
959 exit_horribly(AH, modulename, "out of memory\n");
961 cnt = vsnprintf(p, bSize, fmt, ap);
964 WriteData(AH, p, cnt);
970 /*******************************
971 * Stuff below here should be 'private' to the archiver routines
972 *******************************/
975 SetOutput(ArchiveHandle *AH, char *filename, int compression)
980 /* Replace the AH output file handle */
982 sav.gzOut = AH->gzOut;
991 filename = AH->fSpec;
996 /* If compression explicitly requested, use gzopen */
998 if (compression != 0)
1002 /* Don't use PG_BINARY_x since this is zlib */
1003 sprintf(fmode, "wb%d", compression);
1005 AH->OF = gzdopen(dup(fn), fmode);
1007 AH->OF = gzopen(filename, fmode);
1014 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1016 AH->OF = fopen(filename, PG_BINARY_W);
1021 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
1027 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1032 res = GZCLOSE(AH->OF);
1034 res = fclose(AH->OF);
1037 die_horribly(AH, modulename, "could not close output file: %s\n",
1040 AH->gzOut = sav.gzOut;
1047 * Print formatted text to the output file (usually stdout).
1050 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1054 int bSize = strlen(fmt) + 256; /* Should be enough */
1058 * This is paranoid: deal with the possibility that vsnprintf is
1059 * willing to ignore trailing null
1063 * or returns > 0 even if string does not fit. It may be the case that
1064 * it returns cnt = bufsize
1066 while (cnt < 0 || cnt >= (bSize - 1))
1071 p = (char *) malloc(bSize);
1073 die_horribly(AH, modulename, "out of memory\n");
1075 cnt = vsnprintf(p, bSize, fmt, ap);
1078 ahwrite(p, 1, cnt, AH);
1084 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1088 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1092 _write_msg(NULL, fmt, ap);
1097 * Single place for logic which says 'We are restoring to a direct DB connection'.
1100 RestoringToDB(ArchiveHandle *AH)
1102 return (AH->ropt && AH->ropt->useDB && AH->connection);
1106 * Write buffer to the output file (usually stdout). This is user for
1107 * outputting 'restore' scripts etc. It is even possible for an archive
1108 * format to create a custom output routine to 'fake' a restore if it
1109 * wants to generate a script (see TAR output).
1112 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1116 if (AH->writingBlob)
1118 if (AH->lo_buf_used + size * nmemb > AH->lo_buf_size)
1120 /* Split LO buffer */
1121 size_t remaining = AH->lo_buf_size - AH->lo_buf_used;
1122 size_t slack = nmemb * size - remaining;
1124 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1125 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_size);
1126 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1127 (unsigned long) AH->lo_buf_size, (unsigned long) res);
1128 if (res != AH->lo_buf_size)
1129 die_horribly(AH, modulename,
1130 "could not write to large object (result: %lu, expected: %lu)\n",
1131 (unsigned long) res, (unsigned long) AH->lo_buf_size);
1132 memcpy(AH->lo_buf, (char *) ptr + remaining, slack);
1133 AH->lo_buf_used = slack;
1137 /* LO Buffer is still large enough, buffer it */
1138 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, size * nmemb);
1139 AH->lo_buf_used += size * nmemb;
1142 return size * nmemb;
1146 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1147 if (res != (nmemb * size))
1148 die_horribly(AH, modulename, "could not write to compressed archive\n");
1151 else if (AH->CustomOutPtr)
1153 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1155 if (res != (nmemb * size))
1156 die_horribly(AH, modulename, "could not write to custom output routine\n");
1162 * If we're doing a restore, and it's direct to DB, and we're
1163 * connected then send it to the DB.
1165 if (RestoringToDB(AH))
1166 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1169 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1171 die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
1172 (unsigned long) res, (unsigned long) nmemb);
1178 /* Common exit code */
1180 _write_msg(const char *modulename, const char *fmt, va_list ap)
1183 fprintf(stderr, "%s: [%s] ", progname, gettext(modulename));
1185 fprintf(stderr, "%s: ", progname);
1186 vfprintf(stderr, gettext(fmt), ap);
1190 write_msg(const char *modulename, const char *fmt,...)
1195 _write_msg(modulename, fmt, ap);
1201 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1203 _write_msg(modulename, fmt, ap);
1207 if (AH->public.verbose)
1208 write_msg(NULL, "*** aborted because of error\n");
1210 PQfinish(AH->connection);
1211 if (AH->blobConnection)
1212 PQfinish(AH->blobConnection);
1220 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1225 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1229 /* Archiver use (just different arg declaration) */
1231 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1236 _die_horribly(AH, modulename, fmt, ap);
1240 /* on some error, we may decide to go on... */
1242 warn_or_die_horribly(ArchiveHandle *AH,
1243 const char *modulename, const char *fmt,...)
1251 /* Do nothing special */
1254 case STAGE_INITIALIZING:
1255 if (AH->stage != AH->lastErrorStage)
1256 write_msg(modulename, "Error while INITIALIZING:\n");
1259 case STAGE_PROCESSING:
1260 if (AH->stage != AH->lastErrorStage)
1261 write_msg(modulename, "Error while PROCESSING TOC:\n");
1264 case STAGE_FINALIZING:
1265 if (AH->stage != AH->lastErrorStage)
1266 write_msg(modulename, "Error while FINALIZING:\n");
1269 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1271 write_msg(modulename, "Error from TOC Entry %d; %u %u %s %s %s\n", AH->currentTE->dumpId,
1272 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1273 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1275 AH->lastErrorStage = AH->stage;
1276 AH->lastErrorTE = AH->currentTE;
1279 if (AH->public.exit_on_error)
1280 _die_horribly(AH, modulename, fmt, ap);
1283 _write_msg(modulename, fmt, ap);
1284 AH->public.n_errors++;
1290 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1292 te->prev->next = te->next;
1293 te->next->prev = te->prev;
1296 te->next = pos->next;
1298 pos->next->prev = te;
1305 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1307 te->prev->next = te->next;
1308 te->next->prev = te->prev;
1310 te->prev = pos->prev;
1312 pos->prev->next = te;
1318 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1323 while (te != AH->toc)
1325 if (te->dumpId == id)
1333 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1335 TocEntry *te = getTocEntryByDumpId(AH, id);
1340 return _tocEntryRequired(te, ropt, false);
1344 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1349 (*AH->WriteBytePtr) (AH, wasSet);
1351 /* Write out off_t smallest byte first, prevents endian mismatch */
1352 for (off = 0; off < sizeof(off_t); off++)
1354 (*AH->WriteBytePtr) (AH, o & 0xFF);
1357 return sizeof(off_t) + 1;
1361 ReadOffset(ArchiveHandle *AH, off_t *o)
1367 /* Initialize to zero */
1370 /* Check for old version */
1371 if (AH->version < K_VERS_1_7)
1373 /* Prior versions wrote offsets using WriteInt */
1375 /* -1 means not set */
1377 return K_OFFSET_POS_NOT_SET;
1379 return K_OFFSET_NO_DATA;
1381 /* Cast to off_t because it was written as an int. */
1383 return K_OFFSET_POS_SET;
1387 * Read the flag indicating the state of the data pointer. Check if
1388 * valid and die if not.
1390 * This used to be handled by a negative or zero pointer, now we use an
1391 * extra byte specifically for the state.
1393 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1397 case K_OFFSET_POS_NOT_SET:
1398 case K_OFFSET_NO_DATA:
1399 case K_OFFSET_POS_SET:
1404 die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1410 for (off = 0; off < AH->offSize; off++)
1412 if (off < sizeof(off_t))
1413 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1416 if ((*AH->ReadBytePtr) (AH) != 0)
1417 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1425 WriteInt(ArchiveHandle *AH, int i)
1430 * This is a bit yucky, but I don't want to make the binary format
1431 * very dependent on representation, and not knowing much about it, I
1432 * write out a sign byte. If you change this, don't forget to change
1433 * the file version #, and modify readInt to read the new format AS
1434 * WELL AS the old formats.
1440 (*AH->WriteBytePtr) (AH, 1);
1444 (*AH->WriteBytePtr) (AH, 0);
1446 for (b = 0; b < AH->intSize; b++)
1448 (*AH->WriteBytePtr) (AH, i & 0xFF);
1452 return AH->intSize + 1;
1456 ReadInt(ArchiveHandle *AH)
1461 int sign = 0; /* Default positive */
1464 if (AH->version > K_VERS_1_0)
1465 /* Read a sign byte */
1466 sign = (*AH->ReadBytePtr) (AH);
1468 for (b = 0; b < AH->intSize; b++)
1470 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1472 res = res + (bv << bitShift);
1483 WriteStr(ArchiveHandle *AH, const char *c)
1489 res = WriteInt(AH, strlen(c));
1490 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1493 res = WriteInt(AH, -1);
1499 ReadStr(ArchiveHandle *AH)
1509 buf = (char *) malloc(l + 1);
1511 die_horribly(AH, modulename, "out of memory\n");
1513 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1521 _discoverArchiveFormat(ArchiveHandle *AH)
1524 char sig[6]; /* More than enough */
1529 write_msg(modulename, "attempting to ascertain archive format\n");
1533 free(AH->lookahead);
1535 AH->lookaheadSize = 512;
1536 AH->lookahead = calloc(1, 512);
1537 AH->lookaheadLen = 0;
1538 AH->lookaheadPos = 0;
1543 fh = fopen(AH->fSpec, PG_BINARY_R);
1549 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1551 cnt = fread(sig, 1, 5, fh);
1556 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1558 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1559 (unsigned long) cnt);
1562 /* Save it, just in case we need it later */
1563 strncpy(&AH->lookahead[0], sig, 5);
1564 AH->lookaheadLen = 5;
1566 if (strncmp(sig, "PGDMP", 5) == 0)
1568 AH->vmaj = fgetc(fh);
1569 AH->vmin = fgetc(fh);
1571 /* Save these too... */
1572 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1573 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1575 /* Check header version; varies from V1.0 */
1576 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1578 AH->vrev = fgetc(fh);
1579 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1584 /* Make a convenient integer <maj><min><rev>00 */
1585 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1587 AH->intSize = fgetc(fh);
1588 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1590 if (AH->version >= K_VERS_1_7)
1592 AH->offSize = fgetc(fh);
1593 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1596 AH->offSize = AH->intSize;
1598 AH->format = fgetc(fh);
1599 AH->lookahead[AH->lookaheadLen++] = AH->format;
1604 * *Maybe* we have a tar archive format file... So, read first 512
1607 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1608 AH->lookaheadLen += cnt;
1610 if (AH->lookaheadLen != 512)
1611 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1613 if (!isValidTarHeader(AH->lookahead))
1614 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1616 AH->format = archTar;
1619 /* If we can't seek, then mark the header as read */
1620 if (fseeko(fh, 0, SEEK_SET) != 0)
1623 * NOTE: Formats that use the lookahead buffer can unset this in
1624 * their Init routine.
1629 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1632 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1633 (unsigned long) AH->lookaheadLen);
1636 /* Close the file */
1638 if (fclose(fh) != 0)
1639 die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
1647 * Allocate an archive handle
1649 static ArchiveHandle *
1650 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1651 const int compression, ArchiveMode mode)
1656 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1659 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1661 die_horribly(AH, modulename, "out of memory\n");
1663 /* AH->debugLevel = 100; */
1665 AH->vmaj = K_VERS_MAJOR;
1666 AH->vmin = K_VERS_MINOR;
1667 AH->vrev = K_VERS_REV;
1669 AH->createDate = time(NULL);
1671 AH->intSize = sizeof(int);
1672 AH->offSize = sizeof(off_t);
1675 AH->fSpec = strdup(FileSpec);
1678 * Not used; maybe later....
1680 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1681 * i--) if (AH->workDir[i-1] == '/')
1687 AH->currUser = strdup(""); /* So it's valid, but we can free() it
1688 * later if necessary */
1689 AH->currSchema = strdup(""); /* ditto */
1690 AH->currWithOids = -1; /* force SET */
1692 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1694 die_horribly(AH, modulename, "out of memory\n");
1696 AH->toc->next = AH->toc;
1697 AH->toc->prev = AH->toc;
1700 AH->compression = compression;
1702 AH->pgCopyBuf = createPQExpBuffer();
1703 AH->sqlBuf = createPQExpBuffer();
1705 /* Open stdout with no compression for AH output handle */
1710 write_msg(modulename, "archive format is %d\n", fmt);
1713 if (fmt == archUnknown)
1714 AH->format = _discoverArchiveFormat(AH);
1722 InitArchiveFmt_Custom(AH);
1726 InitArchiveFmt_Files(AH);
1730 InitArchiveFmt_Null(AH);
1734 InitArchiveFmt_Tar(AH);
1738 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1741 /* sql error handling */
1742 AH->public.exit_on_error = true;
1743 AH->public.n_errors = 0;
1750 WriteDataChunks(ArchiveHandle *AH)
1752 TocEntry *te = AH->toc->next;
1753 StartDataPtr startPtr;
1756 while (te != AH->toc)
1758 if (te->dataDumper != NULL)
1761 /* printf("Writing data for %d (%x)\n", te->id, te); */
1763 if (strcmp(te->desc, "BLOBS") == 0)
1765 startPtr = AH->StartBlobsPtr;
1766 endPtr = AH->EndBlobsPtr;
1770 startPtr = AH->StartDataPtr;
1771 endPtr = AH->EndDataPtr;
1774 if (startPtr != NULL)
1775 (*startPtr) (AH, te);
1778 * printf("Dumper arg for %d is %x\n", te->id,
1779 * te->dataDumperArg);
1783 * The user-provided DataDumper routine needs to call
1786 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1797 WriteToc(ArchiveHandle *AH)
1803 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1805 WriteInt(AH, AH->tocCount);
1807 for (te = AH->toc->next; te != AH->toc; te = te->next)
1809 WriteInt(AH, te->dumpId);
1810 WriteInt(AH, te->dataDumper ? 1 : 0);
1812 /* OID is recorded as a string for historical reasons */
1813 sprintf(workbuf, "%u", te->catalogId.tableoid);
1814 WriteStr(AH, workbuf);
1815 sprintf(workbuf, "%u", te->catalogId.oid);
1816 WriteStr(AH, workbuf);
1818 WriteStr(AH, te->tag);
1819 WriteStr(AH, te->desc);
1820 WriteStr(AH, te->defn);
1821 WriteStr(AH, te->dropStmt);
1822 WriteStr(AH, te->copyStmt);
1823 WriteStr(AH, te->namespace);
1824 WriteStr(AH, te->owner);
1825 WriteStr(AH, te->withOids ? "true" : "false");
1827 /* Dump list of dependencies */
1828 for (i = 0; i < te->nDeps; i++)
1830 sprintf(workbuf, "%d", te->dependencies[i]);
1831 WriteStr(AH, workbuf);
1833 WriteStr(AH, NULL); /* Terminate List */
1835 if (AH->WriteExtraTocPtr)
1836 (*AH->WriteExtraTocPtr) (AH, te);
1841 ReadToc(ArchiveHandle *AH)
1849 TocEntry *te = AH->toc->next;
1851 AH->tocCount = ReadInt(AH);
1854 for (i = 0; i < AH->tocCount; i++)
1856 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1857 te->dumpId = ReadInt(AH);
1859 if (te->dumpId > AH->maxDumpId)
1860 AH->maxDumpId = te->dumpId;
1863 if (te->dumpId <= 0)
1864 die_horribly(AH, modulename,
1865 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1868 te->hadDumper = ReadInt(AH);
1870 if (AH->version >= K_VERS_1_8)
1873 sscanf(tmp, "%u", &te->catalogId.tableoid);
1877 te->catalogId.tableoid = InvalidOid;
1879 sscanf(tmp, "%u", &te->catalogId.oid);
1882 te->tag = ReadStr(AH);
1883 te->desc = ReadStr(AH);
1884 te->defn = ReadStr(AH);
1885 te->dropStmt = ReadStr(AH);
1887 if (AH->version >= K_VERS_1_3)
1888 te->copyStmt = ReadStr(AH);
1890 if (AH->version >= K_VERS_1_6)
1891 te->namespace = ReadStr(AH);
1893 te->owner = ReadStr(AH);
1894 if (AH->version >= K_VERS_1_9)
1896 if (strcmp(ReadStr(AH), "true") == 0)
1897 te->withOids = true;
1899 te->withOids = false;
1902 te->withOids = true;
1904 /* Read TOC entry dependencies */
1905 if (AH->version >= K_VERS_1_5)
1908 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1914 break; /* end of list */
1915 if (depIdx >= depSize)
1918 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1920 sscanf(tmp, "%d", &deps[depIdx]);
1925 if (depIdx > 0) /* We have a non-null entry */
1927 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1928 te->dependencies = deps;
1934 te->dependencies = NULL;
1940 te->dependencies = NULL;
1944 if (AH->ReadExtraTocPtr)
1945 (*AH->ReadExtraTocPtr) (AH, te);
1947 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1948 i, te->dumpId, te->desc, te->tag);
1950 te->prev = AH->toc->prev;
1951 AH->toc->prev->next = te;
1958 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool acl_pass)
1960 teReqs res = 3; /* Schema = 1, Data = 2, Both = 3 */
1962 /* ENCODING objects are dumped specially, so always reject here */
1963 if (strcmp(te->desc, "ENCODING") == 0)
1966 /* If it's an ACL, maybe ignore it */
1967 if ((!acl_pass || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1970 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1973 /* Check if tablename only is wanted */
1976 if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1978 if (!ropt->selTable)
1980 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1983 else if (strcmp(te->desc, "INDEX") == 0)
1985 if (!ropt->selIndex)
1987 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1990 else if (strcmp(te->desc, "FUNCTION") == 0)
1992 if (!ropt->selFunction)
1994 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1997 else if (strcmp(te->desc, "TRIGGER") == 0)
1999 if (!ropt->selTrigger)
2001 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2009 * Check if we had a dataDumper. Indicates if the entry is schema or
2015 * Special Case: If 'SEQUENCE SET' then it is considered a data
2018 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2019 res = res & REQ_DATA;
2021 res = res & ~REQ_DATA;
2025 * Special case: <Init> type with <Max OID> tag; this is part of a
2026 * DATA restore even though it has SQL.
2028 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2031 /* Mask it if we only want schema */
2032 if (ropt->schemaOnly)
2033 res = res & REQ_SCHEMA;
2035 /* Mask it we only want data */
2037 res = res & REQ_DATA;
2039 /* Mask it if we don't have a schema contribution */
2040 if (!te->defn || strlen(te->defn) == 0)
2041 res = res & ~REQ_SCHEMA;
2043 /* Finally, if we used a list, limit based on that as well */
2044 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2051 * Issue SET commands for parameters that we want to have set the same way
2052 * at all times during execution of a restore script.
2055 _doSetFixedOutputState(ArchiveHandle *AH)
2059 /* If we have an encoding setting, emit that */
2061 while (te != AH->toc)
2063 if (strcmp(te->desc, "ENCODING") == 0)
2065 ahprintf(AH, "%s", te->defn);
2071 /* Make sure function checking is disabled */
2072 ahprintf(AH, "SET check_function_bodies = false;\n");
2074 /* Avoid annoying notices etc */
2075 ahprintf(AH, "SET client_min_messages = warning;\n");
2081 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2082 * for updating state if appropriate. If user is NULL or an empty string,
2083 * the specification DEFAULT will be used.
2086 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2088 PQExpBuffer cmd = createPQExpBuffer();
2090 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2093 * SQL requires a string literal here. Might as well be correct.
2096 appendStringLiteral(cmd, user, false);
2098 appendPQExpBuffer(cmd, "DEFAULT");
2099 appendPQExpBuffer(cmd, ";");
2101 if (RestoringToDB(AH))
2105 res = PQexec(AH->connection, cmd->data);
2107 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2108 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2109 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2110 user, PQerrorMessage(AH->connection));
2115 ahprintf(AH, "%s\n\n", cmd->data);
2117 destroyPQExpBuffer(cmd);
2122 * Issue a SET default_with_oids command. Caller is responsible
2123 * for updating state if appropriate.
2126 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2128 PQExpBuffer cmd = createPQExpBuffer();
2130 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2133 if (RestoringToDB(AH))
2137 res = PQexec(AH->connection, cmd->data);
2139 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2140 warn_or_die_horribly(AH, modulename,
2141 "could not set default_with_oids: %s",
2142 PQerrorMessage(AH->connection));
2147 ahprintf(AH, "%s\n\n", cmd->data);
2149 destroyPQExpBuffer(cmd);
2154 * Issue the commands to connect to the specified database
2155 * as the specified user.
2157 * If we're currently restoring right into a database, this will
2158 * actually establish a connection. Otherwise it puts a \connect into
2159 * the script output.
2162 _reconnectToDB(ArchiveHandle *AH, const char *dbname, const char *user)
2164 if (RestoringToDB(AH))
2165 ReconnectToServer(AH, dbname, user);
2168 PQExpBuffer qry = createPQExpBuffer();
2170 appendPQExpBuffer(qry, "\\connect %s",
2171 dbname ? fmtId(dbname) : "-");
2172 appendPQExpBuffer(qry, " %s\n\n",
2175 ahprintf(AH, qry->data);
2177 destroyPQExpBuffer(qry);
2181 * NOTE: currUser keeps track of what the imaginary session user in
2187 AH->currUser = strdup(user);
2189 /* don't assume we still know the output schema */
2191 free(AH->currSchema);
2192 AH->currSchema = strdup("");
2193 AH->currWithOids = -1;
2195 /* re-establish fixed state */
2196 _doSetFixedOutputState(AH);
2200 * Become the specified user, and update state to avoid redundant commands
2202 * NULL or empty argument is taken to mean restoring the session default
2205 _becomeUser(ArchiveHandle *AH, const char *user)
2208 user = ""; /* avoid null pointers */
2210 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2211 return; /* no need to do anything */
2213 _doSetSessionAuth(AH, user);
2216 * NOTE: currUser keeps track of what the imaginary session user in
2222 AH->currUser = strdup(user);
2226 * Become the owner of the the given TOC entry object. If
2227 * changes in ownership are not allowed, this doesn't do anything.
2230 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2232 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2235 _becomeUser(AH, te->owner);
2240 * Set the proper default_with_oids value for the table.
2243 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2245 if (AH->currWithOids != te->withOids)
2247 _doSetWithOids(AH, te->withOids);
2248 AH->currWithOids = te->withOids;
2254 * Issue the commands to select the specified schema as the current schema
2255 * in the target database.
2258 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2262 if (!schemaName || *schemaName == '\0' ||
2263 strcmp(AH->currSchema, schemaName) == 0)
2264 return; /* no need to do anything */
2266 qry = createPQExpBuffer();
2268 appendPQExpBuffer(qry, "SET search_path = %s",
2270 if (strcmp(schemaName, "pg_catalog") != 0)
2271 appendPQExpBuffer(qry, ", pg_catalog");
2273 if (RestoringToDB(AH))
2277 res = PQexec(AH->connection, qry->data);
2279 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2280 warn_or_die_horribly(AH, modulename,
2281 "could not set search_path to \"%s\": %s",
2282 schemaName, PQerrorMessage(AH->connection));
2287 ahprintf(AH, "%s;\n\n", qry->data);
2290 free(AH->currSchema);
2291 AH->currSchema = strdup(schemaName);
2293 destroyPQExpBuffer(qry);
2298 * Parses the dropStmt part of a TOC entry and returns
2299 * a newly allocated string that is the object identifier
2300 * The caller must free the result.
2303 _getObjectFromDropStmt(const char *dropStmt, const char *type)
2305 /* Chop "DROP" off the front and make a copy */
2306 char *first = strdup(dropStmt + 5);
2307 char *last = first + strlen(first) - 1; /* Points to the last
2308 * real char in extract */
2312 * Loop from the end of the string until last char is no longer '\n'
2315 while (last >= first && (*last == '\n' || *last == ';'))
2318 /* Insert end of string one place after last */
2322 * Take off CASCADE if necessary. Only TYPEs seem to have this, but
2323 * may as well check for all
2325 if ((last - first) >= 8)
2327 if (strcmp(last - 7, " CASCADE") == 0)
2331 /* Insert end of string one place after last */
2334 /* Special case VIEWs and SEQUENCEs. They must use ALTER TABLE. */
2335 if (strcmp(type, "VIEW") == 0 && (last - first) >= 5)
2337 int len = 6 + strlen(first + 5) + 1;
2340 snprintf(buf, len, "TABLE %s", first + 5);
2343 else if (strcmp(type, "SEQUENCE") == 0 && (last - first) >= 9)
2345 int len = 6 + strlen(first + 9) + 1;
2348 snprintf(buf, len, "TABLE %s", first + 9);
2358 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2360 /* ACLs are dumped only during acl pass */
2363 if (strcmp(te->desc, "ACL") != 0)
2368 if (strcmp(te->desc, "ACL") == 0)
2373 * Avoid dumping the public schema, as it will already be created ...
2374 * unless we are using --clean mode, in which case it's been deleted
2375 * and we'd better recreate it.
2377 if (!ropt->dropSchema &&
2378 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2381 /* Select owner and schema as necessary */
2382 _becomeOwner(AH, te);
2383 _selectOutputSchema(AH, te->namespace);
2385 /* Set up OID mode too */
2386 if (strcmp(te->desc, "TABLE") == 0)
2387 _setWithOids(AH, te);
2389 /* Emit header comment for item */
2390 if (!AH->noTocComments)
2399 ahprintf(AH, "--\n");
2400 if (AH->public.verbose)
2402 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2403 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2408 ahprintf(AH, "-- Dependencies:");
2409 for (i = 0; i < te->nDeps; i++)
2410 ahprintf(AH, " %d", te->dependencies[i]);
2414 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s\n",
2415 pfx, te->tag, te->desc,
2416 te->namespace ? te->namespace : "-",
2418 if (AH->PrintExtraTocPtr != NULL)
2419 (*AH->PrintExtraTocPtr) (AH, te);
2420 ahprintf(AH, "--\n\n");
2424 * Actually print the definition.
2426 * Really crude hack for suppressing AUTHORIZATION clause of CREATE
2427 * SCHEMA when --no-owner mode is selected. This is ugly, but I see
2428 * no other good way ...
2430 if (AH->ropt && AH->ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2432 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", te->tag);
2436 if (strlen(te->defn) > 0)
2437 ahprintf(AH, "%s\n\n", te->defn);
2441 * If we aren't using SET SESSION AUTH to determine ownership, we must
2442 * instead issue an ALTER OWNER command. Ugly, since we have to cons
2443 * one up based on the dropStmt. We don't need this for schemas
2444 * (since we use CREATE SCHEMA AUTHORIZATION instead), nor for some
2445 * other object types.
2447 if (!ropt->noOwner && !ropt->use_setsessauth &&
2448 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0 &&
2449 (strcmp(te->desc, "AGGREGATE") == 0 ||
2450 strcmp(te->desc, "CONVERSION") == 0 ||
2451 strcmp(te->desc, "DOMAIN") == 0 ||
2452 strcmp(te->desc, "FUNCTION") == 0 ||
2453 strcmp(te->desc, "OPERATOR") == 0 ||
2454 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2455 strcmp(te->desc, "TABLE") == 0 ||
2456 strcmp(te->desc, "TYPE") == 0 ||
2457 strcmp(te->desc, "VIEW") == 0 ||
2458 strcmp(te->desc, "SEQUENCE") == 0))
2460 char *temp = _getObjectFromDropStmt(te->dropStmt, te->desc);
2462 ahprintf(AH, "ALTER %s OWNER TO %s;\n\n", temp, fmtId(te->owner));
2467 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2468 * commands, so we can no longer assume we know the current auth
2471 if (strncmp(te->desc, "ACL", 3) == 0)
2475 AH->currUser = NULL;
2480 WriteHead(ArchiveHandle *AH)
2484 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2485 (*AH->WriteBytePtr) (AH, AH->vmaj);
2486 (*AH->WriteBytePtr) (AH, AH->vmin);
2487 (*AH->WriteBytePtr) (AH, AH->vrev);
2488 (*AH->WriteBytePtr) (AH, AH->intSize);
2489 (*AH->WriteBytePtr) (AH, AH->offSize);
2490 (*AH->WriteBytePtr) (AH, AH->format);
2493 if (AH->compression != 0)
2494 write_msg(modulename, "WARNING: requested compression not available in this "
2495 "installation -- archive will be uncompressed\n");
2497 AH->compression = 0;
2500 WriteInt(AH, AH->compression);
2502 crtm = *localtime(&AH->createDate);
2503 WriteInt(AH, crtm.tm_sec);
2504 WriteInt(AH, crtm.tm_min);
2505 WriteInt(AH, crtm.tm_hour);
2506 WriteInt(AH, crtm.tm_mday);
2507 WriteInt(AH, crtm.tm_mon);
2508 WriteInt(AH, crtm.tm_year);
2509 WriteInt(AH, crtm.tm_isdst);
2510 WriteStr(AH, PQdb(AH->connection));
2514 ReadHead(ArchiveHandle *AH)
2520 /* If we haven't already read the header... */
2521 if (!AH->readHeader)
2524 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2526 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2527 die_horribly(AH, modulename, "did not find magic string in file header\n");
2529 AH->vmaj = (*AH->ReadBytePtr) (AH);
2530 AH->vmin = (*AH->ReadBytePtr) (AH);
2532 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2533 AH->vrev = (*AH->ReadBytePtr) (AH);
2537 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2540 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2541 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2542 AH->vmaj, AH->vmin);
2544 AH->intSize = (*AH->ReadBytePtr) (AH);
2545 if (AH->intSize > 32)
2546 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2547 (unsigned long) AH->intSize);
2549 if (AH->intSize > sizeof(int))
2550 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2552 if (AH->version >= K_VERS_1_7)
2553 AH->offSize = (*AH->ReadBytePtr) (AH);
2555 AH->offSize = AH->intSize;
2557 fmt = (*AH->ReadBytePtr) (AH);
2559 if (AH->format != fmt)
2560 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2564 if (AH->version >= K_VERS_1_2)
2566 if (AH->version < K_VERS_1_4)
2567 AH->compression = (*AH->ReadBytePtr) (AH);
2569 AH->compression = ReadInt(AH);
2572 AH->compression = Z_DEFAULT_COMPRESSION;
2575 if (AH->compression != 0)
2576 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2579 if (AH->version >= K_VERS_1_4)
2581 crtm.tm_sec = ReadInt(AH);
2582 crtm.tm_min = ReadInt(AH);
2583 crtm.tm_hour = ReadInt(AH);
2584 crtm.tm_mday = ReadInt(AH);
2585 crtm.tm_mon = ReadInt(AH);
2586 crtm.tm_year = ReadInt(AH);
2587 crtm.tm_isdst = ReadInt(AH);
2589 AH->archdbname = ReadStr(AH);
2591 AH->createDate = mktime(&crtm);
2593 if (AH->createDate == (time_t) -1)
2594 write_msg(modulename, "WARNING: invalid creation date in header\n");
2602 * check to see if fseek can be performed.
2609 if (fseeko(fp, 0, SEEK_CUR) != 0)
2611 else if (sizeof(off_t) > sizeof(long))
2614 * At this point, off_t is too large for long, so we return based
2615 * on whether an off_t version of fseek is available.