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.93 2004/08/20 04:20:22 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 _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;
142 * Check for nonsensical option combinations.
144 * NB: create+dropSchema is useless because if you're creating the DB,
145 * there's no need to drop individual items in it. Moreover, if we
146 * tried to do that then we'd issue the drops in the database
147 * initially connected to, not the one we will create, which is very
150 if (ropt->create && ropt->dropSchema)
151 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
154 * If we're using a DB connection, then connect it.
158 ahlog(AH, 1, "connecting to database for restore\n");
159 if (AH->version < K_VERS_1_3)
160 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
162 /* XXX Should get this from the archive */
163 AHX->minRemoteVersion = 070100;
164 AHX->maxRemoteVersion = 999999;
166 ConnectDatabase(AHX, ropt->dbname,
167 ropt->pghost, ropt->pgport, ropt->username,
168 ropt->requirePassword, ropt->ignoreVersion);
172 * Work out if we have an implied data-only restore. This can happen
173 * if the dump was data only or if the user has used a toc list to
174 * exclude all of the schema data. All we do is look for schema
175 * entries - if none are found then we set the dataOnly flag.
177 * We could scan for wanted TABLE entries, but that is not the same as
178 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
184 while (te != AH->toc)
186 reqs = _tocEntryRequired(te, ropt, false);
187 if ((reqs & REQ_SCHEMA) != 0)
188 { /* It's schema, and it's wanted */
196 ropt->dataOnly = impliedDataOnly;
197 ahlog(AH, 1, "implied data-only restore\n");
202 * Setup the output file if necessary.
204 if (ropt->filename || ropt->compression)
205 sav = SetOutput(AH, ropt->filename, ropt->compression);
207 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
210 * Establish important parameter values right away.
212 _doSetFixedOutputState(AH);
215 * Drop the items at the start, in reverse order
217 if (ropt->dropSchema)
220 while (te != AH->toc)
222 reqs = _tocEntryRequired(te, ropt, false);
223 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
225 /* We want the schema */
226 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
227 /* Select owner and schema as necessary */
228 _becomeOwner(AH, te);
229 _selectOutputSchema(AH, te->namespace);
231 ahprintf(AH, "%s", te->dropStmt);
238 * Now process each TOC entry
241 while (te != AH->toc)
243 /* Work out what, if anything, we want from this entry */
244 reqs = _tocEntryRequired(te, ropt, false);
246 /* Dump any relevant dump warnings to stderr */
247 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
249 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
250 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
251 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
252 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
257 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
259 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
261 _printTocEntry(AH, te, ropt, false, false);
264 /* If we created a DB, connect to it... */
265 if (strcmp(te->desc, "DATABASE") == 0)
267 ahlog(AH, 1, "connecting to new database \"%s\" as user \"%s\"\n", te->tag, te->owner);
268 _reconnectToDB(AH, te->tag, te->owner);
273 * If we have a data component, then process it
275 if ((reqs & REQ_DATA) != 0)
278 * hadDumper will be set if there is genuine data component
279 * for this node. Otherwise, we need to check the defn field
280 * for statements that need to be executed in data-only
286 * If we can output the data, then restore it.
288 if (AH->PrintTocDataPtr != NULL && (reqs & REQ_DATA) != 0)
291 if (AH->compression != 0)
292 die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
295 _printTocEntry(AH, te, ropt, true, false);
298 * Maybe we can't do BLOBS, so check if this node is
301 if ((strcmp(te->desc, "BLOBS") == 0) &&
302 !_canRestoreBlobs(AH))
304 ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
307 * This is a bit nasty - we assume, for the
308 * moment, that if a custom output is used, then
309 * we don't want warnings.
311 if (!AH->CustomOutPtr)
312 write_msg(modulename, "WARNING: skipping large-object restoration\n");
316 _disableTriggersIfNecessary(AH, te, ropt);
318 /* Select owner and schema as necessary */
319 _becomeOwner(AH, te);
320 _selectOutputSchema(AH, te->namespace);
322 ahlog(AH, 1, "restoring data for table \"%s\"\n", te->tag);
325 * If we have a copy statement, use it. As of
326 * V1.3, these are separate to allow easy import
327 * from withing a database connection. Pre 1.3
328 * archives can not use DB connections and are
329 * sent to output only.
331 * For V1.3+, the table data MUST have a copy
332 * statement so that we can go into appropriate
335 if (te->copyStmt && strlen(te->copyStmt) > 0)
336 ahprintf(AH, te->copyStmt);
338 (*AH->PrintTocDataPtr) (AH, te, ropt);
341 * If we just restored blobs, fix references in
342 * previously-loaded tables; otherwise, if we
343 * previously restored blobs, fix references in
344 * this table. Note that in standard cases the BLOBS
345 * entry comes after all TABLE DATA entries, but
346 * we should cope with other orders in case the
347 * user demands reordering.
349 if (strcmp(te->desc, "BLOBS") == 0)
350 fixPriorBlobRefs(AH, te, ropt);
351 else if (AH->createdBlobXref &&
352 strcmp(te->desc, "TABLE DATA") == 0)
354 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
355 FixupBlobRefs(AH, te);
358 _enableTriggersIfNecessary(AH, te, ropt);
362 else if (!defnDumped)
364 /* If we haven't already dumped the defn part, do so now */
365 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
366 _printTocEntry(AH, te, ropt, false, false);
370 } /* end loop over TOC entries */
373 * Scan TOC again to output ownership commands and ACLs
376 while (te != AH->toc)
378 /* Work out what, if anything, we want from this entry */
379 reqs = _tocEntryRequired(te, ropt, true);
381 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
383 ahlog(AH, 1, "setting owner and acl for %s %s\n",
385 _printTocEntry(AH, te, ropt, false, true);
392 * Clean up & we're done.
394 if (ropt->filename || ropt->compression)
395 ResetOutput(AH, sav);
399 PQfinish(AH->connection);
400 AH->connection = NULL;
402 if (AH->blobConnection)
404 PQfinish(AH->blobConnection);
405 AH->blobConnection = NULL;
409 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
413 * After restoring BLOBS, fix all blob references in previously-restored
414 * tables. (Normally, the BLOBS entry should appear after all TABLE DATA
415 * entries, so this will in fact handle all blob references.)
418 fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte, RestoreOptions *ropt)
423 if (AH->createdBlobXref)
425 /* NULL parameter means disable ALL user triggers */
426 _disableTriggersIfNecessary(AH, NULL, ropt);
428 for (te = AH->toc->next; te != blobte; te = te->next)
430 if (strcmp(te->desc, "TABLE DATA") == 0)
432 reqs = _tocEntryRequired(te, ropt, false);
434 if ((reqs & REQ_DATA) != 0) /* We loaded the data */
436 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
437 FixupBlobRefs(AH, te);
442 /* NULL parameter means enable ALL user triggers */
443 _enableTriggersIfNecessary(AH, NULL, ropt);
448 * Allocate a new RestoreOptions block.
449 * This is mainly so we can initialize it, but also for future expansion,
452 NewRestoreOptions(void)
454 RestoreOptions *opts;
456 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
458 opts->format = archUnknown;
459 opts->suppressDumpWarnings = false;
460 opts->exit_on_error = false;
466 * Returns true if we're restoring directly to the database (and
467 * aren't just making a psql script that can do the restoration).
470 _restoringToDB(ArchiveHandle *AH)
472 return (AH->ropt->useDB && AH->connection);
476 _canRestoreBlobs(ArchiveHandle *AH)
478 return _restoringToDB(AH);
482 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
484 /* This hack is only needed in a data-only restore */
485 if (!ropt->dataOnly || !ropt->disable_triggers)
488 /* Don't do it for the BLOBS TocEntry, either */
489 if (te && strcmp(te->desc, "BLOBS") == 0)
493 * Become superuser if possible, since they are the only ones who can
494 * update pg_class. If -S was not given, assume the initial user identity
497 _becomeUser(AH, ropt->superuser);
499 ahlog(AH, 1, "disabling triggers\n");
502 * Disable them. This is a hack. Needs to be done via an appropriate
503 * 'SET' command when one is available.
505 ahprintf(AH, "-- Disable triggers\n");
508 * Just update the AFFECTED table, if known. Otherwise update all
511 if (te && te->tag && strlen(te->tag) > 0)
512 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
513 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
516 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
517 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
521 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
523 /* This hack is only needed in a data-only restore */
524 if (!ropt->dataOnly || !ropt->disable_triggers)
527 /* Don't do it for the BLOBS TocEntry, either */
528 if (te && strcmp(te->desc, "BLOBS") == 0)
532 * Become superuser if possible, since they are the only ones who can
533 * update pg_class. If -S was not given, assume the initial user identity
536 _becomeUser(AH, ropt->superuser);
538 ahlog(AH, 1, "enabling triggers\n");
541 * Enable them. This is a hack. Needs to be done via an appropriate
542 * 'SET' command when one is available.
544 ahprintf(AH, "-- Enable triggers\n");
547 * Just update the AFFECTED table, if known. Otherwise update all
550 if (te && te->tag && strlen(te->tag) > 0)
551 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
552 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
553 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
556 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
557 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
558 "FROM pg_catalog.pg_namespace "
559 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
563 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
568 WriteData(Archive *AHX, const void *data, size_t dLen)
570 ArchiveHandle *AH = (ArchiveHandle *) AHX;
573 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
575 return (*AH->WriteDataPtr) (AH, data, dLen);
579 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
580 * repository for all metadata. But the name has stuck.
585 ArchiveEntry(Archive *AHX,
586 CatalogId catalogId, DumpId dumpId,
588 const char *namespace, const char *owner, bool withOids,
589 const char *desc, const char *defn,
590 const char *dropStmt, const char *copyStmt,
591 const DumpId *deps, int nDeps,
592 DataDumperPtr dumpFn, void *dumpArg)
594 ArchiveHandle *AH = (ArchiveHandle *) AHX;
597 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
599 die_horribly(AH, modulename, "out of memory\n");
602 if (dumpId > AH->maxDumpId)
603 AH->maxDumpId = dumpId;
605 newToc->prev = AH->toc->prev;
606 newToc->next = AH->toc;
607 AH->toc->prev->next = newToc;
608 AH->toc->prev = newToc;
610 newToc->catalogId = catalogId;
611 newToc->dumpId = dumpId;
613 newToc->tag = strdup(tag);
614 newToc->namespace = namespace ? strdup(namespace) : NULL;
615 newToc->owner = strdup(owner);
616 newToc->withOids = withOids;
617 newToc->desc = strdup(desc);
618 newToc->defn = strdup(defn);
619 newToc->dropStmt = strdup(dropStmt);
620 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
624 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
625 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
626 newToc->nDeps = nDeps;
630 newToc->dependencies = NULL;
634 newToc->dataDumper = dumpFn;
635 newToc->dataDumperArg = dumpArg;
636 newToc->hadDumper = dumpFn ? true : false;
638 newToc->formatData = NULL;
640 if (AH->ArchiveEntryPtr != NULL)
641 (*AH->ArchiveEntryPtr) (AH, newToc);
646 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
648 ArchiveHandle *AH = (ArchiveHandle *) AHX;
649 TocEntry *te = AH->toc->next;
654 sav = SetOutput(AH, ropt->filename, 0 /* no compression */);
656 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
657 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
658 AH->archdbname, AH->tocCount, AH->compression);
675 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
676 ahprintf(AH, "; Format: %s\n", fmtName);
677 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
678 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
680 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
682 while (te != AH->toc)
684 if (_tocEntryRequired(te, ropt, false) != 0)
685 ahprintf(AH, "%d; %u %u %s %s %s\n", te->dumpId,
686 te->catalogId.tableoid, te->catalogId.oid,
687 te->desc, te->tag, te->owner);
692 ResetOutput(AH, sav);
699 /* Called by a dumper to signal start of a BLOB */
701 StartBlob(Archive *AHX, Oid oid)
703 ArchiveHandle *AH = (ArchiveHandle *) AHX;
705 if (!AH->StartBlobPtr)
706 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
708 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
713 /* Called by a dumper to signal end of a BLOB */
715 EndBlob(Archive *AHX, Oid oid)
717 ArchiveHandle *AH = (ArchiveHandle *) AHX;
720 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
730 * Called by a format handler before any blobs are restored
733 StartRestoreBlobs(ArchiveHandle *AH)
739 * Called by a format handler after all blobs are restored
742 EndRestoreBlobs(ArchiveHandle *AH)
746 ahlog(AH, 2, "committing large-object transactions\n");
747 CommitTransaction(AH);
750 if (AH->blobTxActive)
751 CommitTransactionXref(AH);
753 if (AH->createdBlobXref)
754 CreateBlobXrefIndex(AH);
756 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
761 * Called by a format handler to initiate restoration of a blob
764 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
770 if (!AH->createdBlobXref)
773 die_horribly(AH, modulename, "cannot restore large objects without a database connection\n");
775 CreateBlobXrefTable(AH);
776 AH->createdBlobXref = 1;
779 /* Initialize the LO Buffer */
783 * Start long-running TXs if necessary
787 ahlog(AH, 2, "starting large-object transactions\n");
788 StartTransaction(AH);
790 if (!AH->blobTxActive)
791 StartTransactionXref(AH);
793 loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
795 die_horribly(AH, modulename, "could not create large object\n");
797 ahlog(AH, 2, "restoring large object with OID %u as %u\n", oid, loOid);
799 InsertBlobXref(AH, oid, loOid);
801 AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
803 die_horribly(AH, modulename, "could not open large object\n");
809 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
811 if (AH->lo_buf_used > 0)
813 /* Write remaining bytes from the LO buffer */
816 res = lo_write(AH->connection, AH->loFd, (void *) AH->lo_buf, AH->lo_buf_used);
818 ahlog(AH, 5, "wrote remaining %lu bytes of large-object data (result = %lu)\n",
819 (unsigned long) AH->lo_buf_used, (unsigned long) res);
820 if (res != AH->lo_buf_used)
821 die_horribly(AH, modulename, "could not write to large object (result: %lu, expected: %lu)\n",
822 (unsigned long) res, (unsigned long) AH->lo_buf_used);
826 lo_close(AH->connection, AH->loFd);
830 * Commit every BLOB_BATCH_SIZE blobs...
832 if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
834 ahlog(AH, 2, "committing large-object transactions\n");
835 CommitTransaction(AH);
836 CommitTransactionXref(AH);
841 * Sorting and Reordering
845 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
847 ArchiveHandle *AH = (ArchiveHandle *) AHX;
856 /* Allocate space for the 'wanted' array, and init it */
857 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
858 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
859 ropt->limitToList = true;
861 /* Set prev entry as head of list */
865 fh = fopen(ropt->tocFile, PG_BINARY_R);
867 die_horribly(AH, modulename, "could not open TOC file\n");
869 while (fgets(buf, 1024, fh) != NULL)
872 cmnt = strchr(buf, ';');
876 /* End string at comment */
880 /* Skip if all spaces */
881 if (strspn(buf, " \t") == strlen(buf))
885 id = strtol(buf, &endptr, 10);
886 if (endptr == buf || id <= 0 || id > AH->maxDumpId)
888 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
893 te = getTocEntryByDumpId(AH, id);
895 die_horribly(AH, modulename, "could not find entry for ID %d\n",
898 ropt->idWanted[id - 1] = true;
900 _moveAfter(AH, tePrev, te);
905 die_horribly(AH, modulename, "could not close TOC file: %s\n",
909 /**********************
910 * 'Convenience functions that look like standard IO functions
911 * for writing data when in dump mode.
912 **********************/
916 archputs(const char *s, Archive *AH)
918 return WriteData(AH, s, strlen(s));
923 archprintf(Archive *AH, const char *fmt,...)
927 int bSize = strlen(fmt) + 256;
931 * This is paranoid: deal with the possibility that vsnprintf is
932 * willing to ignore trailing null
933 * or returns > 0 even if string does not fit. It may be the case that
934 * it returns cnt = bufsize
936 while (cnt < 0 || cnt >= (bSize - 1))
941 p = (char *) malloc(bSize);
943 exit_horribly(AH, modulename, "out of memory\n");
945 cnt = vsnprintf(p, bSize, fmt, ap);
948 WriteData(AH, p, cnt);
954 /*******************************
955 * Stuff below here should be 'private' to the archiver routines
956 *******************************/
959 SetOutput(ArchiveHandle *AH, char *filename, int compression)
964 /* Replace the AH output file handle */
966 sav.gzOut = AH->gzOut;
975 filename = AH->fSpec;
980 /* If compression explicitly requested, use gzopen */
982 if (compression != 0)
986 /* Don't use PG_BINARY_x since this is zlib */
987 sprintf(fmode, "wb%d", compression);
989 AH->OF = gzdopen(dup(fn), fmode);
991 AH->OF = gzopen(filename, fmode);
998 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1000 AH->OF = fopen(filename, PG_BINARY_W);
1005 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
1011 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1016 res = GZCLOSE(AH->OF);
1018 res = fclose(AH->OF);
1021 die_horribly(AH, modulename, "could not close output file: %s\n",
1024 AH->gzOut = sav.gzOut;
1031 * Print formatted text to the output file (usually stdout).
1034 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1038 int bSize = strlen(fmt) + 256; /* Should be enough */
1042 * This is paranoid: deal with the possibility that vsnprintf is
1043 * willing to ignore trailing null
1047 * or returns > 0 even if string does not fit. It may be the case that
1048 * it returns cnt = bufsize
1050 while (cnt < 0 || cnt >= (bSize - 1))
1055 p = (char *) malloc(bSize);
1057 die_horribly(AH, modulename, "out of memory\n");
1059 cnt = vsnprintf(p, bSize, fmt, ap);
1062 ahwrite(p, 1, cnt, AH);
1068 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1072 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1076 _write_msg(NULL, fmt, ap);
1081 * Single place for logic which says 'We are restoring to a direct DB connection'.
1084 RestoringToDB(ArchiveHandle *AH)
1086 return (AH->ropt && AH->ropt->useDB && AH->connection);
1090 * Write buffer to the output file (usually stdout). This is user for
1091 * outputting 'restore' scripts etc. It is even possible for an archive
1092 * format to create a custom output routine to 'fake' a restore if it
1093 * wants to generate a script (see TAR output).
1096 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1100 if (AH->writingBlob)
1102 if (AH->lo_buf_used + size * nmemb > AH->lo_buf_size)
1104 /* Split LO buffer */
1105 size_t remaining = AH->lo_buf_size - AH->lo_buf_used;
1106 size_t slack = nmemb * size - remaining;
1108 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1109 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_size);
1110 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1111 (unsigned long) AH->lo_buf_size, (unsigned long) res);
1112 if (res != AH->lo_buf_size)
1113 die_horribly(AH, modulename,
1114 "could not write to large object (result: %lu, expected: %lu)\n",
1115 (unsigned long) res, (unsigned long) AH->lo_buf_size);
1116 memcpy(AH->lo_buf, (char *) ptr + remaining, slack);
1117 AH->lo_buf_used = slack;
1121 /* LO Buffer is still large enough, buffer it */
1122 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, size * nmemb);
1123 AH->lo_buf_used += size * nmemb;
1126 return size * nmemb;
1130 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1131 if (res != (nmemb * size))
1132 die_horribly(AH, modulename, "could not write to compressed archive\n");
1135 else if (AH->CustomOutPtr)
1137 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1139 if (res != (nmemb * size))
1140 die_horribly(AH, modulename, "could not write to custom output routine\n");
1146 * If we're doing a restore, and it's direct to DB, and we're
1147 * connected then send it to the DB.
1149 if (RestoringToDB(AH))
1150 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1153 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1155 die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
1156 (unsigned long) res, (unsigned long) nmemb);
1162 /* Common exit code */
1164 _write_msg(const char *modulename, const char *fmt, va_list ap)
1167 fprintf(stderr, "%s: [%s] ", progname, gettext(modulename));
1169 fprintf(stderr, "%s: ", progname);
1170 vfprintf(stderr, gettext(fmt), ap);
1174 write_msg(const char *modulename, const char *fmt,...)
1179 _write_msg(modulename, fmt, ap);
1185 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1187 _write_msg(modulename, fmt, ap);
1191 if (AH->public.verbose)
1192 write_msg(NULL, "*** aborted because of error\n");
1194 PQfinish(AH->connection);
1195 if (AH->blobConnection)
1196 PQfinish(AH->blobConnection);
1204 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1209 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1213 /* Archiver use (just different arg declaration) */
1215 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1220 _die_horribly(AH, modulename, fmt, ap);
1224 /* on some error, we may decide to go on... */
1226 warn_or_die_horribly(ArchiveHandle *AH,
1227 const char *modulename, const char *fmt, ...)
1231 if (AH->public.exit_on_error)
1233 _die_horribly(AH, modulename, fmt, ap);
1237 _write_msg(modulename, fmt, ap);
1238 AH->public.n_errors++;
1244 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1246 te->prev->next = te->next;
1247 te->next->prev = te->prev;
1250 te->next = pos->next;
1252 pos->next->prev = te;
1259 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1261 te->prev->next = te->next;
1262 te->next->prev = te->prev;
1264 te->prev = pos->prev;
1266 pos->prev->next = te;
1273 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1278 while (te != AH->toc)
1280 if (te->dumpId == id)
1288 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1290 TocEntry *te = getTocEntryByDumpId(AH, id);
1295 return _tocEntryRequired(te, ropt, false);
1299 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1304 (*AH->WriteBytePtr) (AH, wasSet);
1306 /* Write out off_t smallest byte first, prevents endian mismatch */
1307 for (off = 0; off < sizeof(off_t); off++)
1309 (*AH->WriteBytePtr) (AH, o & 0xFF);
1312 return sizeof(off_t) + 1;
1316 ReadOffset(ArchiveHandle *AH, off_t *o)
1322 /* Initialize to zero */
1325 /* Check for old version */
1326 if (AH->version < K_VERS_1_7)
1328 /* Prior versions wrote offsets using WriteInt */
1330 /* -1 means not set */
1332 return K_OFFSET_POS_NOT_SET;
1334 return K_OFFSET_NO_DATA;
1336 /* Cast to off_t because it was written as an int. */
1338 return K_OFFSET_POS_SET;
1342 * Read the flag indicating the state of the data pointer. Check if
1343 * valid and die if not.
1345 * This used to be handled by a negative or zero pointer, now we use an
1346 * extra byte specifically for the state.
1348 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1352 case K_OFFSET_POS_NOT_SET:
1353 case K_OFFSET_NO_DATA:
1354 case K_OFFSET_POS_SET:
1359 die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1365 for (off = 0; off < AH->offSize; off++)
1367 if (off < sizeof(off_t))
1368 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1371 if ((*AH->ReadBytePtr) (AH) != 0)
1372 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1380 WriteInt(ArchiveHandle *AH, int i)
1385 * This is a bit yucky, but I don't want to make the binary format
1386 * very dependent on representation, and not knowing much about it, I
1387 * write out a sign byte. If you change this, don't forget to change
1388 * the file version #, and modify readInt to read the new format AS
1389 * WELL AS the old formats.
1395 (*AH->WriteBytePtr) (AH, 1);
1399 (*AH->WriteBytePtr) (AH, 0);
1401 for (b = 0; b < AH->intSize; b++)
1403 (*AH->WriteBytePtr) (AH, i & 0xFF);
1407 return AH->intSize + 1;
1411 ReadInt(ArchiveHandle *AH)
1416 int sign = 0; /* Default positive */
1419 if (AH->version > K_VERS_1_0)
1420 /* Read a sign byte */
1421 sign = (*AH->ReadBytePtr) (AH);
1423 for (b = 0; b < AH->intSize; b++)
1425 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1427 res = res + (bv << bitShift);
1438 WriteStr(ArchiveHandle *AH, const char *c)
1444 res = WriteInt(AH, strlen(c));
1445 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1448 res = WriteInt(AH, -1);
1454 ReadStr(ArchiveHandle *AH)
1464 buf = (char *) malloc(l + 1);
1466 die_horribly(AH, modulename, "out of memory\n");
1468 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1476 _discoverArchiveFormat(ArchiveHandle *AH)
1479 char sig[6]; /* More than enough */
1484 write_msg(modulename, "attempting to ascertain archive format\n");
1488 free(AH->lookahead);
1490 AH->lookaheadSize = 512;
1491 AH->lookahead = calloc(1, 512);
1492 AH->lookaheadLen = 0;
1493 AH->lookaheadPos = 0;
1498 fh = fopen(AH->fSpec, PG_BINARY_R);
1504 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1506 cnt = fread(sig, 1, 5, fh);
1511 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1513 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1514 (unsigned long) cnt);
1517 /* Save it, just in case we need it later */
1518 strncpy(&AH->lookahead[0], sig, 5);
1519 AH->lookaheadLen = 5;
1521 if (strncmp(sig, "PGDMP", 5) == 0)
1523 AH->vmaj = fgetc(fh);
1524 AH->vmin = fgetc(fh);
1526 /* Save these too... */
1527 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1528 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1530 /* Check header version; varies from V1.0 */
1531 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1533 AH->vrev = fgetc(fh);
1534 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1539 /* Make a convenient integer <maj><min><rev>00 */
1540 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1542 AH->intSize = fgetc(fh);
1543 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1545 if (AH->version >= K_VERS_1_7)
1547 AH->offSize = fgetc(fh);
1548 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1551 AH->offSize = AH->intSize;
1553 AH->format = fgetc(fh);
1554 AH->lookahead[AH->lookaheadLen++] = AH->format;
1559 * *Maybe* we have a tar archive format file... So, read first 512
1562 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1563 AH->lookaheadLen += cnt;
1565 if (AH->lookaheadLen != 512)
1566 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1568 if (!isValidTarHeader(AH->lookahead))
1569 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1571 AH->format = archTar;
1574 /* If we can't seek, then mark the header as read */
1575 if (fseeko(fh, 0, SEEK_SET) != 0)
1578 * NOTE: Formats that use the lookahead buffer can unset this in
1579 * their Init routine.
1584 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1587 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1588 (unsigned long) AH->lookaheadLen);
1591 /* Close the file */
1593 if (fclose(fh) != 0)
1594 die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
1602 * Allocate an archive handle
1604 static ArchiveHandle *
1605 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1606 const int compression, ArchiveMode mode)
1611 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1614 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1616 die_horribly(AH, modulename, "out of memory\n");
1618 /* AH->debugLevel = 100; */
1620 AH->vmaj = K_VERS_MAJOR;
1621 AH->vmin = K_VERS_MINOR;
1622 AH->vrev = K_VERS_REV;
1624 AH->createDate = time(NULL);
1626 AH->intSize = sizeof(int);
1627 AH->offSize = sizeof(off_t);
1630 AH->fSpec = strdup(FileSpec);
1633 * Not used; maybe later....
1635 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1636 * i--) if (AH->workDir[i-1] == '/')
1642 AH->currUser = strdup(""); /* So it's valid, but we can free() it
1643 * later if necessary */
1644 AH->currSchema = strdup(""); /* ditto */
1645 AH->currWithOids = -1; /* force SET */
1647 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1649 die_horribly(AH, modulename, "out of memory\n");
1651 AH->toc->next = AH->toc;
1652 AH->toc->prev = AH->toc;
1655 AH->compression = compression;
1657 AH->pgCopyBuf = createPQExpBuffer();
1658 AH->sqlBuf = createPQExpBuffer();
1660 /* Open stdout with no compression for AH output handle */
1665 write_msg(modulename, "archive format is %d\n", fmt);
1668 if (fmt == archUnknown)
1669 AH->format = _discoverArchiveFormat(AH);
1677 InitArchiveFmt_Custom(AH);
1681 InitArchiveFmt_Files(AH);
1685 InitArchiveFmt_Null(AH);
1689 InitArchiveFmt_Tar(AH);
1693 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1696 /* sql error handling */
1697 AH->public.exit_on_error = true;
1698 AH->public.n_errors = 0;
1705 WriteDataChunks(ArchiveHandle *AH)
1707 TocEntry *te = AH->toc->next;
1708 StartDataPtr startPtr;
1711 while (te != AH->toc)
1713 if (te->dataDumper != NULL)
1716 /* printf("Writing data for %d (%x)\n", te->id, te); */
1718 if (strcmp(te->desc, "BLOBS") == 0)
1720 startPtr = AH->StartBlobsPtr;
1721 endPtr = AH->EndBlobsPtr;
1725 startPtr = AH->StartDataPtr;
1726 endPtr = AH->EndDataPtr;
1729 if (startPtr != NULL)
1730 (*startPtr) (AH, te);
1733 * printf("Dumper arg for %d is %x\n", te->id,
1734 * te->dataDumperArg);
1738 * The user-provided DataDumper routine needs to call
1741 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1752 WriteToc(ArchiveHandle *AH)
1758 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1760 WriteInt(AH, AH->tocCount);
1762 for (te = AH->toc->next; te != AH->toc; te = te->next)
1764 WriteInt(AH, te->dumpId);
1765 WriteInt(AH, te->dataDumper ? 1 : 0);
1767 /* OID is recorded as a string for historical reasons */
1768 sprintf(workbuf, "%u", te->catalogId.tableoid);
1769 WriteStr(AH, workbuf);
1770 sprintf(workbuf, "%u", te->catalogId.oid);
1771 WriteStr(AH, workbuf);
1773 WriteStr(AH, te->tag);
1774 WriteStr(AH, te->desc);
1775 WriteStr(AH, te->defn);
1776 WriteStr(AH, te->dropStmt);
1777 WriteStr(AH, te->copyStmt);
1778 WriteStr(AH, te->namespace);
1779 WriteStr(AH, te->owner);
1780 WriteStr(AH, te->withOids ? "true" : "false");
1782 /* Dump list of dependencies */
1783 for (i = 0; i < te->nDeps; i++)
1785 sprintf(workbuf, "%d", te->dependencies[i]);
1786 WriteStr(AH, workbuf);
1788 WriteStr(AH, NULL); /* Terminate List */
1790 if (AH->WriteExtraTocPtr)
1791 (*AH->WriteExtraTocPtr) (AH, te);
1796 ReadToc(ArchiveHandle *AH)
1804 TocEntry *te = AH->toc->next;
1806 AH->tocCount = ReadInt(AH);
1809 for (i = 0; i < AH->tocCount; i++)
1811 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1812 te->dumpId = ReadInt(AH);
1814 if (te->dumpId > AH->maxDumpId)
1815 AH->maxDumpId = te->dumpId;
1818 if (te->dumpId <= 0)
1819 die_horribly(AH, modulename,
1820 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1823 te->hadDumper = ReadInt(AH);
1825 if (AH->version >= K_VERS_1_8)
1828 sscanf(tmp, "%u", &te->catalogId.tableoid);
1832 te->catalogId.tableoid = InvalidOid;
1834 sscanf(tmp, "%u", &te->catalogId.oid);
1837 te->tag = ReadStr(AH);
1838 te->desc = ReadStr(AH);
1839 te->defn = ReadStr(AH);
1840 te->dropStmt = ReadStr(AH);
1842 if (AH->version >= K_VERS_1_3)
1843 te->copyStmt = ReadStr(AH);
1845 if (AH->version >= K_VERS_1_6)
1846 te->namespace = ReadStr(AH);
1848 te->owner = ReadStr(AH);
1849 if (AH->version >= K_VERS_1_9)
1851 if (strcmp(ReadStr(AH), "true") == 0)
1852 te->withOids = true;
1854 te->withOids = false;
1857 te->withOids = true;
1859 /* Read TOC entry dependencies */
1860 if (AH->version >= K_VERS_1_5)
1863 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1869 break; /* end of list */
1870 if (depIdx >= depSize)
1873 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1875 sscanf(tmp, "%d", &deps[depIdx]);
1880 if (depIdx > 0) /* We have a non-null entry */
1882 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1883 te->dependencies = deps;
1889 te->dependencies = NULL;
1895 te->dependencies = NULL;
1899 if (AH->ReadExtraTocPtr)
1900 (*AH->ReadExtraTocPtr) (AH, te);
1902 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1903 i, te->dumpId, te->desc, te->tag);
1905 te->prev = AH->toc->prev;
1906 AH->toc->prev->next = te;
1913 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool acl_pass)
1915 teReqs res = 3; /* Schema = 1, Data = 2, Both = 3 */
1917 /* ENCODING objects are dumped specially, so always reject here */
1918 if (strcmp(te->desc, "ENCODING") == 0)
1921 /* If it's an ACL, maybe ignore it */
1922 if ((!acl_pass || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1925 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1928 /* Check if tablename only is wanted */
1931 if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1933 if (!ropt->selTable)
1935 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1938 else if (strcmp(te->desc, "INDEX") == 0)
1940 if (!ropt->selIndex)
1942 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1945 else if (strcmp(te->desc, "FUNCTION") == 0)
1947 if (!ropt->selFunction)
1949 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1952 else if (strcmp(te->desc, "TRIGGER") == 0)
1954 if (!ropt->selTrigger)
1956 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
1964 * Check if we had a dataDumper. Indicates if the entry is schema or
1970 * Special Case: If 'SEQUENCE SET' then it is considered a data
1973 if (strcmp(te->desc, "SEQUENCE SET") == 0)
1974 res = res & REQ_DATA;
1976 res = res & ~REQ_DATA;
1980 * Special case: <Init> type with <Max OID> tag; this is part of a
1981 * DATA restore even though it has SQL.
1983 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
1986 /* Mask it if we only want schema */
1987 if (ropt->schemaOnly)
1988 res = res & REQ_SCHEMA;
1990 /* Mask it we only want data */
1992 res = res & REQ_DATA;
1994 /* Mask it if we don't have a schema contribution */
1995 if (!te->defn || strlen(te->defn) == 0)
1996 res = res & ~REQ_SCHEMA;
1998 /* Finally, if we used a list, limit based on that as well */
1999 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2006 * Issue SET commands for parameters that we want to have set the same way
2007 * at all times during execution of a restore script.
2010 _doSetFixedOutputState(ArchiveHandle *AH)
2014 /* If we have an encoding setting, emit that */
2016 while (te != AH->toc)
2018 if (strcmp(te->desc, "ENCODING") == 0)
2020 ahprintf(AH, "%s", te->defn);
2026 /* Make sure function checking is disabled */
2027 ahprintf(AH, "SET check_function_bodies = false;\n");
2033 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2034 * for updating state if appropriate. If user is NULL or an empty string,
2035 * the specification DEFAULT will be used.
2038 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2040 PQExpBuffer cmd = createPQExpBuffer();
2042 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2045 * SQL requires a string literal here. Might as well be correct.
2048 appendStringLiteral(cmd, user, false);
2050 appendPQExpBuffer(cmd, "DEFAULT");
2051 appendPQExpBuffer(cmd, ";");
2053 if (RestoringToDB(AH))
2057 res = PQexec(AH->connection, cmd->data);
2059 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2060 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2061 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2062 user, PQerrorMessage(AH->connection));
2067 ahprintf(AH, "%s\n\n", cmd->data);
2069 destroyPQExpBuffer(cmd);
2074 * Issue a SET default_with_oids command. Caller is responsible
2075 * for updating state if appropriate.
2078 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2080 PQExpBuffer cmd = createPQExpBuffer();
2082 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2085 if (RestoringToDB(AH))
2089 res = PQexec(AH->connection, cmd->data);
2091 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2092 warn_or_die_horribly(AH, modulename,
2093 "could not set default_with_oids: %s",
2094 PQerrorMessage(AH->connection));
2099 ahprintf(AH, "%s\n\n", cmd->data);
2101 destroyPQExpBuffer(cmd);
2106 * Issue the commands to connect to the specified database
2107 * as the specified user.
2109 * If we're currently restoring right into a database, this will
2110 * actually establish a connection. Otherwise it puts a \connect into
2111 * the script output.
2114 _reconnectToDB(ArchiveHandle *AH, const char *dbname, const char *user)
2116 if (RestoringToDB(AH))
2117 ReconnectToServer(AH, dbname, user);
2120 PQExpBuffer qry = createPQExpBuffer();
2122 appendPQExpBuffer(qry, "\\connect %s",
2123 dbname ? fmtId(dbname) : "-");
2124 appendPQExpBuffer(qry, " %s\n\n",
2127 ahprintf(AH, qry->data);
2129 destroyPQExpBuffer(qry);
2133 * NOTE: currUser keeps track of what the imaginary session user in
2139 AH->currUser = strdup(user);
2141 /* don't assume we still know the output schema */
2143 free(AH->currSchema);
2144 AH->currSchema = strdup("");
2145 AH->currWithOids = -1;
2147 /* re-establish fixed state */
2148 _doSetFixedOutputState(AH);
2152 * Become the specified user, and update state to avoid redundant commands
2154 * NULL or empty argument is taken to mean restoring the session default
2157 _becomeUser(ArchiveHandle *AH, const char *user)
2160 user = ""; /* avoid null pointers */
2162 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2163 return; /* no need to do anything */
2165 _doSetSessionAuth(AH, user);
2168 * NOTE: currUser keeps track of what the imaginary session user in
2174 AH->currUser = strdup(user);
2178 * Become the owner of the the given TOC entry object. If
2179 * changes in ownership are not allowed, this doesn't do anything.
2182 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2184 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2187 _becomeUser(AH, te->owner);
2192 * Set the proper default_with_oids value for the table.
2195 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2197 if (AH->currWithOids != te->withOids)
2199 _doSetWithOids(AH, te->withOids);
2200 AH->currWithOids = te->withOids;
2206 * Issue the commands to select the specified schema as the current schema
2207 * in the target database.
2210 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2214 if (!schemaName || *schemaName == '\0' ||
2215 strcmp(AH->currSchema, schemaName) == 0)
2216 return; /* no need to do anything */
2218 qry = createPQExpBuffer();
2220 appendPQExpBuffer(qry, "SET search_path = %s",
2222 if (strcmp(schemaName, "pg_catalog") != 0)
2223 appendPQExpBuffer(qry, ", pg_catalog");
2225 if (RestoringToDB(AH))
2229 res = PQexec(AH->connection, qry->data);
2231 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2232 warn_or_die_horribly(AH, modulename,
2233 "could not set search_path to \"%s\": %s",
2234 schemaName, PQerrorMessage(AH->connection));
2239 ahprintf(AH, "%s;\n\n", qry->data);
2242 free(AH->currSchema);
2243 AH->currSchema = strdup(schemaName);
2245 destroyPQExpBuffer(qry);
2250 * Parses the dropStmt part of a TOC entry and returns
2251 * a newly allocated string that is the object identifier
2252 * The caller must free the result.
2255 _getObjectFromDropStmt(const char *dropStmt, const char *type)
2257 /* Chop "DROP" off the front and make a copy */
2258 char *first = strdup(dropStmt + 5);
2259 char *last = first + strlen(first) - 1; /* Points to the last real char in extract */
2262 /* Loop from the end of the string until last char is no longer '\n' or ';' */
2263 while (last >= first && (*last == '\n' || *last == ';')) {
2267 /* Insert end of string one place after last */
2270 /* Take off CASCADE if necessary. Only TYPEs seem to have this, but may
2271 * as well check for all */
2272 if ((last - first) >= 8) {
2273 if (strcmp(last - 7, " CASCADE") == 0)
2277 /* Insert end of string one place after last */
2280 /* Special case VIEWs and SEQUENCEs. They must use ALTER TABLE. */
2281 if (strcmp(type, "VIEW") == 0 && (last - first) >= 5)
2283 int len = 6 + strlen(first + 5) + 1;
2285 snprintf(buf, len, "TABLE %s", first + 5);
2288 else if (strcmp(type, "SEQUENCE") == 0 && (last - first) >= 9)
2290 int len = 6 + strlen(first + 9) + 1;
2292 snprintf(buf, len, "TABLE %s", first + 9);
2304 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2308 /* ACLs are dumped only during acl pass */
2311 if (strcmp(te->desc, "ACL") != 0)
2316 if (strcmp(te->desc, "ACL") == 0)
2321 * Avoid dumping the public schema, as it will already be created ...
2322 * unless we are using --clean mode, in which case it's been deleted
2323 * and we'd better recreate it.
2325 if (!ropt->dropSchema &&
2326 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2329 /* Select owner and schema as necessary */
2330 _becomeOwner(AH, te);
2331 _selectOutputSchema(AH, te->namespace);
2333 /* Set up OID mode too */
2334 if (strcmp(te->desc, "TABLE") == 0)
2335 _setWithOids(AH, te);
2337 /* Emit header comment for item */
2343 ahprintf(AH, "--\n");
2344 if (AH->public.verbose)
2346 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2347 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2352 ahprintf(AH, "-- Dependencies:");
2353 for (i = 0; i < te->nDeps; i++)
2354 ahprintf(AH, " %d", te->dependencies[i]);
2358 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s\n",
2359 pfx, te->tag, te->desc,
2360 te->namespace ? te->namespace : "-",
2362 if (AH->PrintExtraTocPtr != NULL)
2363 (*AH->PrintExtraTocPtr) (AH, te);
2364 ahprintf(AH, "--\n\n");
2367 * Actually print the definition.
2369 * Really crude hack for suppressing AUTHORIZATION clause of CREATE SCHEMA
2370 * when --no-owner mode is selected. This is ugly, but I see no other
2373 if (AH->ropt && AH->ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2375 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", te->tag);
2379 if (strlen(te->defn) > 0)
2380 ahprintf(AH, "%s\n\n", te->defn);
2384 * If we aren't using SET SESSION AUTH to determine ownership, we must
2385 * instead issue an ALTER OWNER command. Ugly, since we have to
2386 * cons one up based on the dropStmt. We don't need this for schemas
2387 * (since we use CREATE SCHEMA AUTHORIZATION instead), nor for some other
2390 if (!ropt->noOwner && !ropt->use_setsessauth &&
2391 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0 &&
2392 (strcmp(te->desc, "AGGREGATE") == 0 ||
2393 strcmp(te->desc, "CONVERSION") == 0 ||
2394 strcmp(te->desc, "DOMAIN") == 0 ||
2395 strcmp(te->desc, "FUNCTION") == 0 ||
2396 strcmp(te->desc, "OPERATOR") == 0 ||
2397 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2398 strcmp(te->desc, "TABLE") == 0 ||
2399 strcmp(te->desc, "TYPE") == 0 ||
2400 strcmp(te->desc, "VIEW") == 0 ||
2401 strcmp(te->desc, "SEQUENCE") == 0))
2403 char *temp = _getObjectFromDropStmt(te->dropStmt, te->desc);
2405 ahprintf(AH, "ALTER %s OWNER TO %s;\n\n", temp, fmtId(te->owner));
2410 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2411 * commands, so we can no longer assume we know the current auth setting.
2413 if (strncmp(te->desc, "ACL", 3) == 0)
2417 AH->currUser = NULL;
2422 WriteHead(ArchiveHandle *AH)
2426 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2427 (*AH->WriteBytePtr) (AH, AH->vmaj);
2428 (*AH->WriteBytePtr) (AH, AH->vmin);
2429 (*AH->WriteBytePtr) (AH, AH->vrev);
2430 (*AH->WriteBytePtr) (AH, AH->intSize);
2431 (*AH->WriteBytePtr) (AH, AH->offSize);
2432 (*AH->WriteBytePtr) (AH, AH->format);
2435 if (AH->compression != 0)
2436 write_msg(modulename, "WARNING: requested compression not available in this "
2437 "installation -- archive will be uncompressed\n");
2439 AH->compression = 0;
2442 WriteInt(AH, AH->compression);
2444 crtm = *localtime(&AH->createDate);
2445 WriteInt(AH, crtm.tm_sec);
2446 WriteInt(AH, crtm.tm_min);
2447 WriteInt(AH, crtm.tm_hour);
2448 WriteInt(AH, crtm.tm_mday);
2449 WriteInt(AH, crtm.tm_mon);
2450 WriteInt(AH, crtm.tm_year);
2451 WriteInt(AH, crtm.tm_isdst);
2452 WriteStr(AH, PQdb(AH->connection));
2456 ReadHead(ArchiveHandle *AH)
2462 /* If we haven't already read the header... */
2463 if (!AH->readHeader)
2466 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2468 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2469 die_horribly(AH, modulename, "did not find magic string in file header\n");
2471 AH->vmaj = (*AH->ReadBytePtr) (AH);
2472 AH->vmin = (*AH->ReadBytePtr) (AH);
2474 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2475 AH->vrev = (*AH->ReadBytePtr) (AH);
2479 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2482 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2483 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2484 AH->vmaj, AH->vmin);
2486 AH->intSize = (*AH->ReadBytePtr) (AH);
2487 if (AH->intSize > 32)
2488 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2489 (unsigned long) AH->intSize);
2491 if (AH->intSize > sizeof(int))
2492 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2494 if (AH->version >= K_VERS_1_7)
2495 AH->offSize = (*AH->ReadBytePtr) (AH);
2497 AH->offSize = AH->intSize;
2499 fmt = (*AH->ReadBytePtr) (AH);
2501 if (AH->format != fmt)
2502 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2506 if (AH->version >= K_VERS_1_2)
2508 if (AH->version < K_VERS_1_4)
2509 AH->compression = (*AH->ReadBytePtr) (AH);
2511 AH->compression = ReadInt(AH);
2514 AH->compression = Z_DEFAULT_COMPRESSION;
2517 if (AH->compression != 0)
2518 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2521 if (AH->version >= K_VERS_1_4)
2523 crtm.tm_sec = ReadInt(AH);
2524 crtm.tm_min = ReadInt(AH);
2525 crtm.tm_hour = ReadInt(AH);
2526 crtm.tm_mday = ReadInt(AH);
2527 crtm.tm_mon = ReadInt(AH);
2528 crtm.tm_year = ReadInt(AH);
2529 crtm.tm_isdst = ReadInt(AH);
2531 AH->archdbname = ReadStr(AH);
2533 AH->createDate = mktime(&crtm);
2535 if (AH->createDate == (time_t) -1)
2536 write_msg(modulename, "WARNING: invalid creation date in header\n");
2544 * check to see if fseek can be performed.
2551 if (fseeko(fp, 0, SEEK_CUR) != 0)
2553 else if (sizeof(off_t) > sizeof(long))
2556 * At this point, off_t is too large for long, so we return based
2557 * on whether an off_t version of fseek is available.