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.107 2005/04/15 16:40:36 tgl Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup.h"
25 #include "pg_backup_archiver.h"
26 #include "pg_backup_db.h"
27 #include "dumputils.h"
36 #include "pqexpbuffer.h"
37 #include "libpq/libpq-fs.h"
42 static char *modulename = gettext_noop("archiver");
45 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
46 const int compression, ArchiveMode mode);
47 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
49 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
52 static void fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte,
53 RestoreOptions *ropt);
54 static void _doSetFixedOutputState(ArchiveHandle *AH);
55 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
56 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
57 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
58 static void _becomeUser(ArchiveHandle *AH, const char *user);
59 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
60 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
61 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
63 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
64 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
65 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
66 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
67 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
68 static int _discoverArchiveFormat(ArchiveHandle *AH);
70 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
71 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
73 static int _canRestoreBlobs(ArchiveHandle *AH);
74 static int _restoringToDB(ArchiveHandle *AH);
76 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
82 * The objective it to make writing new formats and dumpers as simple
83 * as possible, if necessary at the expense of extra function calls etc.
88 /* Create a new archive */
91 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
92 const int compression)
95 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
97 return (Archive *) AH;
100 /* Open an existing archive */
103 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
105 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
107 return (Archive *) AH;
112 CloseArchive(Archive *AHX)
115 ArchiveHandle *AH = (ArchiveHandle *) AHX;
117 (*AH->ClosePtr) (AH);
119 /* Close the output */
121 res = GZCLOSE(AH->OF);
122 else if (AH->OF != stdout)
123 res = fclose(AH->OF);
126 die_horribly(AH, modulename, "could not close output archive file\n");
131 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
133 ArchiveHandle *AH = (ArchiveHandle *) AHX;
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).
189 int impliedDataOnly = 1;
191 for (te = AH->toc->next; te != AH->toc; te = te->next)
193 reqs = _tocEntryRequired(te, ropt, true);
194 if ((reqs & REQ_SCHEMA) != 0)
195 { /* It's schema, and it's wanted */
202 ropt->dataOnly = impliedDataOnly;
203 ahlog(AH, 1, "implied data-only restore\n");
208 * Setup the output file if necessary.
210 if (ropt->filename || ropt->compression)
211 sav = SetOutput(AH, ropt->filename, ropt->compression);
213 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
215 if (AH->public.verbose)
216 dumpTimestamp(AH, "Started on", AH->createDate);
219 * Establish important parameter values right away.
221 _doSetFixedOutputState(AH);
223 AH->stage = STAGE_PROCESSING;
226 * Drop the items at the start, in reverse order
228 if (ropt->dropSchema)
230 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
234 reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */);
235 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
237 /* We want the schema */
238 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
239 /* Select owner and schema as necessary */
240 _becomeOwner(AH, te);
241 _selectOutputSchema(AH, te->namespace);
243 ahprintf(AH, "%s", te->dropStmt);
249 * Now process each non-ACL TOC entry
251 for (te = AH->toc->next; te != AH->toc; te = te->next)
255 /* Work out what, if anything, we want from this entry */
256 reqs = _tocEntryRequired(te, ropt, false);
258 /* Dump any relevant dump warnings to stderr */
259 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
261 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
262 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
263 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
264 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
269 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
271 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
273 _printTocEntry(AH, te, ropt, false, false);
276 /* If we created a DB, connect to it... */
277 if (strcmp(te->desc, "DATABASE") == 0)
279 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
280 _reconnectToDB(AH, te->tag);
285 * If we have a data component, then process it
287 if ((reqs & REQ_DATA) != 0)
290 * hadDumper will be set if there is genuine data component
291 * for this node. Otherwise, we need to check the defn field
292 * for statements that need to be executed in data-only
298 * If we can output the data, then restore it.
300 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
303 if (AH->compression != 0)
304 die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
307 _printTocEntry(AH, te, ropt, true, false);
310 * Maybe we can't do BLOBS, so check if this node is
313 if ((strcmp(te->desc, "BLOBS") == 0) &&
314 !_canRestoreBlobs(AH))
316 ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
319 * This is a bit nasty - we assume, for the
320 * moment, that if a custom output is used, then
321 * we don't want warnings.
323 if (!AH->CustomOutPtr)
324 write_msg(modulename, "WARNING: skipping large-object restoration\n");
328 _disableTriggersIfNecessary(AH, te, ropt);
330 /* Select owner and schema as necessary */
331 _becomeOwner(AH, te);
332 _selectOutputSchema(AH, te->namespace);
334 ahlog(AH, 1, "restoring data for table \"%s\"\n", te->tag);
337 * If we have a copy statement, use it. As of
338 * V1.3, these are separate to allow easy import
339 * from withing a database connection. Pre 1.3
340 * archives can not use DB connections and are
341 * sent to output only.
343 * For V1.3+, the table data MUST have a copy
344 * statement so that we can go into appropriate
347 if (te->copyStmt && strlen(te->copyStmt) > 0)
348 ahprintf(AH, te->copyStmt);
350 (*AH->PrintTocDataPtr) (AH, te, ropt);
353 * If we just restored blobs, fix references in
354 * previously-loaded tables; otherwise, if we
355 * previously restored blobs, fix references in
356 * this table. Note that in standard cases the
357 * BLOBS entry comes after all TABLE DATA entries,
358 * but we should cope with other orders in case
359 * the user demands reordering.
361 if (strcmp(te->desc, "BLOBS") == 0)
362 fixPriorBlobRefs(AH, te, ropt);
363 else if (AH->createdBlobXref &&
364 strcmp(te->desc, "TABLE DATA") == 0)
366 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
367 FixupBlobRefs(AH, te);
370 _enableTriggersIfNecessary(AH, te, ropt);
374 else if (!defnDumped)
376 /* If we haven't already dumped the defn part, do so now */
377 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
378 _printTocEntry(AH, te, ropt, false, false);
381 } /* end loop over TOC entries */
384 * Scan TOC again to output ownership commands and ACLs
386 for (te = AH->toc->next; te != AH->toc; te = te->next)
390 /* Work out what, if anything, we want from this entry */
391 reqs = _tocEntryRequired(te, ropt, true);
393 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
395 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
397 _printTocEntry(AH, te, ropt, false, true);
401 if (AH->public.verbose)
402 dumpTimestamp(AH, "Completed on", time(NULL));
404 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
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;
428 * After restoring BLOBS, fix all blob references in previously-restored
429 * tables. (Normally, the BLOBS entry should appear after all TABLE DATA
430 * entries, so this will in fact handle all blob references.)
433 fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte, RestoreOptions *ropt)
438 if (AH->createdBlobXref)
440 /* NULL parameter means disable ALL user triggers */
441 _disableTriggersIfNecessary(AH, NULL, ropt);
443 for (te = AH->toc->next; te != blobte; te = te->next)
445 if (strcmp(te->desc, "TABLE DATA") == 0)
447 reqs = _tocEntryRequired(te, ropt, false);
449 if ((reqs & REQ_DATA) != 0) /* We loaded the data */
451 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
452 FixupBlobRefs(AH, te);
457 /* NULL parameter means enable ALL user triggers */
458 _enableTriggersIfNecessary(AH, NULL, ropt);
463 * Allocate a new RestoreOptions block.
464 * This is mainly so we can initialize it, but also for future expansion,
467 NewRestoreOptions(void)
469 RestoreOptions *opts;
471 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
473 opts->format = archUnknown;
474 opts->suppressDumpWarnings = false;
475 opts->exit_on_error = false;
481 * Returns true if we're restoring directly to the database (and
482 * aren't just making a psql script that can do the restoration).
485 _restoringToDB(ArchiveHandle *AH)
487 return (AH->ropt->useDB && AH->connection);
491 _canRestoreBlobs(ArchiveHandle *AH)
493 return _restoringToDB(AH);
497 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
499 /* This hack is only needed in a data-only restore */
500 if (!ropt->dataOnly || !ropt->disable_triggers)
503 /* Don't do it for the BLOBS TocEntry, either */
504 if (te && strcmp(te->desc, "BLOBS") == 0)
508 * Become superuser if possible, since they are the only ones who can
509 * update pg_class. If -S was not given, assume the initial user
510 * identity is a superuser.
512 _becomeUser(AH, ropt->superuser);
514 ahlog(AH, 1, "disabling triggers\n");
517 * Disable them. This is a hack. Needs to be done via an appropriate
518 * 'SET' command when one is available.
520 ahprintf(AH, "-- Disable triggers\n");
523 * Just update the AFFECTED table, if known. Otherwise update all
526 if (te && te->tag && strlen(te->tag) > 0)
527 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
528 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
531 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
532 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
536 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
538 /* This hack is only needed in a data-only restore */
539 if (!ropt->dataOnly || !ropt->disable_triggers)
542 /* Don't do it for the BLOBS TocEntry, either */
543 if (te && strcmp(te->desc, "BLOBS") == 0)
547 * Become superuser if possible, since they are the only ones who can
548 * update pg_class. If -S was not given, assume the initial user
549 * identity is a superuser.
551 _becomeUser(AH, ropt->superuser);
553 ahlog(AH, 1, "enabling triggers\n");
556 * Enable them. This is a hack. Needs to be done via an appropriate
557 * 'SET' command when one is available.
559 ahprintf(AH, "-- Enable triggers\n");
562 * Just update the AFFECTED table, if known. Otherwise update all
565 if (te && te->tag && strlen(te->tag) > 0)
566 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
567 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
568 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
571 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
572 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
573 "FROM pg_catalog.pg_namespace "
574 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
578 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
583 WriteData(Archive *AHX, const void *data, size_t dLen)
585 ArchiveHandle *AH = (ArchiveHandle *) AHX;
588 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
590 return (*AH->WriteDataPtr) (AH, data, dLen);
594 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
595 * repository for all metadata. But the name has stuck.
600 ArchiveEntry(Archive *AHX,
601 CatalogId catalogId, DumpId dumpId,
603 const char *namespace,
604 const char *tablespace,
605 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->tablespace = tablespace ? strdup(tablespace) : NULL;
633 newToc->owner = strdup(owner);
634 newToc->withOids = withOids;
635 newToc->desc = strdup(desc);
636 newToc->defn = strdup(defn);
637 newToc->dropStmt = strdup(dropStmt);
638 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
642 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
643 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
644 newToc->nDeps = nDeps;
648 newToc->dependencies = NULL;
652 newToc->dataDumper = dumpFn;
653 newToc->dataDumperArg = dumpArg;
654 newToc->hadDumper = dumpFn ? true : false;
656 newToc->formatData = NULL;
658 if (AH->ArchiveEntryPtr !=NULL)
659 (*AH->ArchiveEntryPtr) (AH, newToc);
664 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
666 ArchiveHandle *AH = (ArchiveHandle *) AHX;
667 TocEntry *te = AH->toc->next;
672 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
674 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
675 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
676 AH->archdbname, AH->tocCount, AH->compression);
693 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
694 ahprintf(AH, "; Format: %s\n", fmtName);
695 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
696 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
697 if (AH->archiveRemoteVersion)
698 ahprintf(AH, "; Dumped from database version: %s\n",
699 AH->archiveRemoteVersion);
700 if (AH->archiveDumpVersion)
701 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
702 AH->archiveDumpVersion);
704 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
706 while (te != AH->toc)
708 if (_tocEntryRequired(te, ropt, true) != 0)
709 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
710 te->catalogId.tableoid, te->catalogId.oid,
711 te->desc, te->namespace ? te->namespace : "-",
717 ResetOutput(AH, sav);
724 /* Called by a dumper to signal start of a BLOB */
726 StartBlob(Archive *AHX, Oid oid)
728 ArchiveHandle *AH = (ArchiveHandle *) AHX;
730 if (!AH->StartBlobPtr)
731 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
733 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
738 /* Called by a dumper to signal end of a BLOB */
740 EndBlob(Archive *AHX, Oid oid)
742 ArchiveHandle *AH = (ArchiveHandle *) AHX;
745 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
755 * Called by a format handler before any blobs are restored
758 StartRestoreBlobs(ArchiveHandle *AH)
764 * Called by a format handler after all blobs are restored
767 EndRestoreBlobs(ArchiveHandle *AH)
771 ahlog(AH, 2, "committing large-object transactions\n");
772 CommitTransaction(AH);
775 if (AH->blobTxActive)
776 CommitTransactionXref(AH);
778 if (AH->createdBlobXref)
779 CreateBlobXrefIndex(AH);
781 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
786 * Called by a format handler to initiate restoration of a blob
789 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
795 if (!AH->createdBlobXref)
798 die_horribly(AH, modulename, "cannot restore large objects without a database connection\n");
800 CreateBlobXrefTable(AH);
801 AH->createdBlobXref = 1;
804 /* Initialize the LO Buffer */
808 * Start long-running TXs if necessary
812 ahlog(AH, 2, "starting large-object transactions\n");
813 StartTransaction(AH);
815 if (!AH->blobTxActive)
816 StartTransactionXref(AH);
818 loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
820 die_horribly(AH, modulename, "could not create large object\n");
822 ahlog(AH, 2, "restoring large object with OID %u as %u\n", oid, loOid);
824 InsertBlobXref(AH, oid, loOid);
826 AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
828 die_horribly(AH, modulename, "could not open large object\n");
834 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
836 if (AH->lo_buf_used > 0)
838 /* Write remaining bytes from the LO buffer */
841 res = lo_write(AH->connection, AH->loFd, (void *) AH->lo_buf, AH->lo_buf_used);
843 ahlog(AH, 5, "wrote remaining %lu bytes of large-object data (result = %lu)\n",
844 (unsigned long) AH->lo_buf_used, (unsigned long) res);
845 if (res != AH->lo_buf_used)
846 die_horribly(AH, modulename, "could not write to large object (result: %lu, expected: %lu)\n",
847 (unsigned long) res, (unsigned long) AH->lo_buf_used);
851 lo_close(AH->connection, AH->loFd);
855 * Commit every BLOB_BATCH_SIZE blobs...
857 if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
859 ahlog(AH, 2, "committing large-object transactions\n");
860 CommitTransaction(AH);
861 CommitTransactionXref(AH);
866 * Sorting and Reordering
870 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
872 ArchiveHandle *AH = (ArchiveHandle *) AHX;
881 /* Allocate space for the 'wanted' array, and init it */
882 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
883 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
884 ropt->limitToList = true;
886 /* Set prev entry as head of list */
890 fh = fopen(ropt->tocFile, PG_BINARY_R);
892 die_horribly(AH, modulename, "could not open TOC file\n");
894 while (fgets(buf, 1024, fh) != NULL)
897 cmnt = strchr(buf, ';');
901 /* End string at comment */
905 /* Skip if all spaces */
906 if (strspn(buf, " \t") == strlen(buf))
910 id = strtol(buf, &endptr, 10);
911 if (endptr == buf || id <= 0 || id > AH->maxDumpId)
913 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
918 te = getTocEntryByDumpId(AH, id);
920 die_horribly(AH, modulename, "could not find entry for ID %d\n",
923 ropt->idWanted[id - 1] = true;
925 _moveAfter(AH, tePrev, te);
930 die_horribly(AH, modulename, "could not close TOC file: %s\n",
934 /**********************
935 * 'Convenience functions that look like standard IO functions
936 * for writing data when in dump mode.
937 **********************/
941 archputs(const char *s, Archive *AH)
943 return WriteData(AH, s, strlen(s));
948 archprintf(Archive *AH, const char *fmt,...)
952 int bSize = strlen(fmt) + 256;
956 * This is paranoid: deal with the possibility that vsnprintf is
957 * willing to ignore trailing null or returns > 0 even if string does
958 * not fit. It may be the case that it returns cnt = bufsize
960 while (cnt < 0 || cnt >= (bSize - 1))
965 p = (char *) malloc(bSize);
967 exit_horribly(AH, modulename, "out of memory\n");
969 cnt = vsnprintf(p, bSize, fmt, ap);
972 WriteData(AH, p, cnt);
978 /*******************************
979 * Stuff below here should be 'private' to the archiver routines
980 *******************************/
983 SetOutput(ArchiveHandle *AH, char *filename, int compression)
988 /* Replace the AH output file handle */
990 sav.gzOut = AH->gzOut;
999 filename = AH->fSpec;
1002 fn = fileno(stdout);
1004 /* If compression explicitly requested, use gzopen */
1006 if (compression != 0)
1010 /* Don't use PG_BINARY_x since this is zlib */
1011 sprintf(fmode, "wb%d", compression);
1013 AH->OF = gzdopen(dup(fn), fmode);
1015 AH->OF = gzopen(filename, fmode);
1022 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1024 AH->OF = fopen(filename, PG_BINARY_W);
1029 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
1035 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1040 res = GZCLOSE(AH->OF);
1042 res = fclose(AH->OF);
1045 die_horribly(AH, modulename, "could not close output file: %s\n",
1048 AH->gzOut = sav.gzOut;
1055 * Print formatted text to the output file (usually stdout).
1058 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1062 int bSize = strlen(fmt) + 256; /* Should be enough */
1066 * This is paranoid: deal with the possibility that vsnprintf is
1067 * willing to ignore trailing null
1071 * or returns > 0 even if string does not fit. It may be the case that
1072 * it returns cnt = bufsize
1074 while (cnt < 0 || cnt >= (bSize - 1))
1079 p = (char *) malloc(bSize);
1081 die_horribly(AH, modulename, "out of memory\n");
1083 cnt = vsnprintf(p, bSize, fmt, ap);
1086 ahwrite(p, 1, cnt, AH);
1092 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1096 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1100 _write_msg(NULL, fmt, ap);
1105 * Single place for logic which says 'We are restoring to a direct DB connection'.
1108 RestoringToDB(ArchiveHandle *AH)
1110 return (AH->ropt && AH->ropt->useDB && AH->connection);
1114 * Write buffer to the output file (usually stdout). This is user for
1115 * outputting 'restore' scripts etc. It is even possible for an archive
1116 * format to create a custom output routine to 'fake' a restore if it
1117 * wants to generate a script (see TAR output).
1120 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1124 if (AH->writingBlob)
1126 if (AH->lo_buf_used + size * nmemb > AH->lo_buf_size)
1128 /* Split LO buffer */
1129 size_t remaining = AH->lo_buf_size - AH->lo_buf_used;
1130 size_t slack = nmemb * size - remaining;
1132 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1133 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_size);
1134 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1135 (unsigned long) AH->lo_buf_size, (unsigned long) res);
1136 if (res != AH->lo_buf_size)
1137 die_horribly(AH, modulename,
1138 "could not write to large object (result: %lu, expected: %lu)\n",
1139 (unsigned long) res, (unsigned long) AH->lo_buf_size);
1140 memcpy(AH->lo_buf, (char *) ptr + remaining, slack);
1141 AH->lo_buf_used = slack;
1145 /* LO Buffer is still large enough, buffer it */
1146 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, size * nmemb);
1147 AH->lo_buf_used += size * nmemb;
1150 return size * nmemb;
1154 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1155 if (res != (nmemb * size))
1156 die_horribly(AH, modulename, "could not write to compressed archive\n");
1159 else if (AH->CustomOutPtr)
1161 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1163 if (res != (nmemb * size))
1164 die_horribly(AH, modulename, "could not write to custom output routine\n");
1170 * If we're doing a restore, and it's direct to DB, and we're
1171 * connected then send it to the DB.
1173 if (RestoringToDB(AH))
1174 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1177 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1179 die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
1180 (unsigned long) res, (unsigned long) nmemb);
1186 /* Common exit code */
1188 _write_msg(const char *modulename, const char *fmt, va_list ap)
1191 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1193 fprintf(stderr, "%s: ", progname);
1194 vfprintf(stderr, _(fmt), ap);
1198 write_msg(const char *modulename, const char *fmt,...)
1203 _write_msg(modulename, fmt, ap);
1209 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1211 _write_msg(modulename, fmt, ap);
1215 if (AH->public.verbose)
1216 write_msg(NULL, "*** aborted because of error\n");
1218 PQfinish(AH->connection);
1219 if (AH->blobConnection)
1220 PQfinish(AH->blobConnection);
1228 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1233 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1237 /* Archiver use (just different arg declaration) */
1239 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1244 _die_horribly(AH, modulename, fmt, ap);
1248 /* on some error, we may decide to go on... */
1250 warn_or_die_horribly(ArchiveHandle *AH,
1251 const char *modulename, const char *fmt,...)
1259 /* Do nothing special */
1262 case STAGE_INITIALIZING:
1263 if (AH->stage != AH->lastErrorStage)
1264 write_msg(modulename, "Error while INITIALIZING:\n");
1267 case STAGE_PROCESSING:
1268 if (AH->stage != AH->lastErrorStage)
1269 write_msg(modulename, "Error while PROCESSING TOC:\n");
1272 case STAGE_FINALIZING:
1273 if (AH->stage != AH->lastErrorStage)
1274 write_msg(modulename, "Error while FINALIZING:\n");
1277 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1279 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1280 AH->currentTE->dumpId,
1281 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1282 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1284 AH->lastErrorStage = AH->stage;
1285 AH->lastErrorTE = AH->currentTE;
1288 if (AH->public.exit_on_error)
1289 _die_horribly(AH, modulename, fmt, ap);
1292 _write_msg(modulename, fmt, ap);
1293 AH->public.n_errors++;
1299 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1301 te->prev->next = te->next;
1302 te->next->prev = te->prev;
1305 te->next = pos->next;
1307 pos->next->prev = te;
1314 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1316 te->prev->next = te->next;
1317 te->next->prev = te->prev;
1319 te->prev = pos->prev;
1321 pos->prev->next = te;
1327 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1332 while (te != AH->toc)
1334 if (te->dumpId == id)
1342 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1344 TocEntry *te = getTocEntryByDumpId(AH, id);
1349 return _tocEntryRequired(te, ropt, true);
1353 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1358 (*AH->WriteBytePtr) (AH, wasSet);
1360 /* Write out off_t smallest byte first, prevents endian mismatch */
1361 for (off = 0; off < sizeof(off_t); off++)
1363 (*AH->WriteBytePtr) (AH, o & 0xFF);
1366 return sizeof(off_t) + 1;
1370 ReadOffset(ArchiveHandle *AH, off_t *o)
1376 /* Initialize to zero */
1379 /* Check for old version */
1380 if (AH->version < K_VERS_1_7)
1382 /* Prior versions wrote offsets using WriteInt */
1384 /* -1 means not set */
1386 return K_OFFSET_POS_NOT_SET;
1388 return K_OFFSET_NO_DATA;
1390 /* Cast to off_t because it was written as an int. */
1392 return K_OFFSET_POS_SET;
1396 * Read the flag indicating the state of the data pointer. Check if
1397 * valid and die if not.
1399 * This used to be handled by a negative or zero pointer, now we use an
1400 * extra byte specifically for the state.
1402 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1406 case K_OFFSET_POS_NOT_SET:
1407 case K_OFFSET_NO_DATA:
1408 case K_OFFSET_POS_SET:
1413 die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1419 for (off = 0; off < AH->offSize; off++)
1421 if (off < sizeof(off_t))
1422 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1425 if ((*AH->ReadBytePtr) (AH) != 0)
1426 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1434 WriteInt(ArchiveHandle *AH, int i)
1439 * This is a bit yucky, but I don't want to make the binary format
1440 * very dependent on representation, and not knowing much about it, I
1441 * write out a sign byte. If you change this, don't forget to change
1442 * the file version #, and modify readInt to read the new format AS
1443 * WELL AS the old formats.
1449 (*AH->WriteBytePtr) (AH, 1);
1453 (*AH->WriteBytePtr) (AH, 0);
1455 for (b = 0; b < AH->intSize; b++)
1457 (*AH->WriteBytePtr) (AH, i & 0xFF);
1461 return AH->intSize + 1;
1465 ReadInt(ArchiveHandle *AH)
1470 int sign = 0; /* Default positive */
1473 if (AH->version > K_VERS_1_0)
1474 /* Read a sign byte */
1475 sign = (*AH->ReadBytePtr) (AH);
1477 for (b = 0; b < AH->intSize; b++)
1479 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1481 res = res + (bv << bitShift);
1492 WriteStr(ArchiveHandle *AH, const char *c)
1498 res = WriteInt(AH, strlen(c));
1499 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1502 res = WriteInt(AH, -1);
1508 ReadStr(ArchiveHandle *AH)
1518 buf = (char *) malloc(l + 1);
1520 die_horribly(AH, modulename, "out of memory\n");
1522 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1530 _discoverArchiveFormat(ArchiveHandle *AH)
1533 char sig[6]; /* More than enough */
1538 write_msg(modulename, "attempting to ascertain archive format\n");
1542 free(AH->lookahead);
1544 AH->lookaheadSize = 512;
1545 AH->lookahead = calloc(1, 512);
1546 AH->lookaheadLen = 0;
1547 AH->lookaheadPos = 0;
1552 fh = fopen(AH->fSpec, PG_BINARY_R);
1558 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1560 cnt = fread(sig, 1, 5, fh);
1565 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1567 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1568 (unsigned long) cnt);
1571 /* Save it, just in case we need it later */
1572 strncpy(&AH->lookahead[0], sig, 5);
1573 AH->lookaheadLen = 5;
1575 if (strncmp(sig, "PGDMP", 5) == 0)
1577 AH->vmaj = fgetc(fh);
1578 AH->vmin = fgetc(fh);
1580 /* Save these too... */
1581 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1582 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1584 /* Check header version; varies from V1.0 */
1585 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1587 AH->vrev = fgetc(fh);
1588 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1593 /* Make a convenient integer <maj><min><rev>00 */
1594 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1596 AH->intSize = fgetc(fh);
1597 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1599 if (AH->version >= K_VERS_1_7)
1601 AH->offSize = fgetc(fh);
1602 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1605 AH->offSize = AH->intSize;
1607 AH->format = fgetc(fh);
1608 AH->lookahead[AH->lookaheadLen++] = AH->format;
1613 * *Maybe* we have a tar archive format file... So, read first 512
1616 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1617 AH->lookaheadLen += cnt;
1619 if (AH->lookaheadLen != 512)
1620 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1622 if (!isValidTarHeader(AH->lookahead))
1623 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1625 AH->format = archTar;
1628 /* If we can't seek, then mark the header as read */
1629 if (fseeko(fh, 0, SEEK_SET) != 0)
1632 * NOTE: Formats that use the lookahead buffer can unset this in
1633 * their Init routine.
1638 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1641 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1642 (unsigned long) AH->lookaheadLen);
1645 /* Close the file */
1647 if (fclose(fh) != 0)
1648 die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
1656 * Allocate an archive handle
1658 static ArchiveHandle *
1659 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1660 const int compression, ArchiveMode mode)
1665 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1668 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1670 die_horribly(AH, modulename, "out of memory\n");
1672 /* AH->debugLevel = 100; */
1674 AH->vmaj = K_VERS_MAJOR;
1675 AH->vmin = K_VERS_MINOR;
1676 AH->vrev = K_VERS_REV;
1678 AH->createDate = time(NULL);
1680 AH->intSize = sizeof(int);
1681 AH->offSize = sizeof(off_t);
1684 AH->fSpec = strdup(FileSpec);
1687 * Not used; maybe later....
1689 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1690 * i--) if (AH->workDir[i-1] == '/')
1696 AH->currUser = strdup(""); /* So it's valid, but we can free() it
1697 * later if necessary */
1698 AH->currSchema = strdup(""); /* ditto */
1699 AH->currWithOids = -1; /* force SET */
1701 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1703 die_horribly(AH, modulename, "out of memory\n");
1705 AH->toc->next = AH->toc;
1706 AH->toc->prev = AH->toc;
1709 AH->compression = compression;
1711 AH->pgCopyBuf = createPQExpBuffer();
1712 AH->sqlBuf = createPQExpBuffer();
1714 /* Open stdout with no compression for AH output handle */
1719 * On Windows, we need to use binary mode to read/write non-text archive
1720 * formats. Force stdin/stdout into binary mode in case that is what
1724 if (fmt != archNull)
1726 if (mode == archModeWrite)
1727 setmode(fileno(stdout), O_BINARY);
1729 setmode(fileno(stdin), O_BINARY);
1734 write_msg(modulename, "archive format is %d\n", fmt);
1737 if (fmt == archUnknown)
1738 AH->format = _discoverArchiveFormat(AH);
1745 InitArchiveFmt_Custom(AH);
1749 InitArchiveFmt_Files(AH);
1753 InitArchiveFmt_Null(AH);
1757 InitArchiveFmt_Tar(AH);
1761 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1764 /* sql error handling */
1765 AH->public.exit_on_error = true;
1766 AH->public.n_errors = 0;
1773 WriteDataChunks(ArchiveHandle *AH)
1775 TocEntry *te = AH->toc->next;
1776 StartDataPtr startPtr;
1779 while (te != AH->toc)
1781 if (te->dataDumper != NULL)
1784 /* printf("Writing data for %d (%x)\n", te->id, te); */
1786 if (strcmp(te->desc, "BLOBS") == 0)
1788 startPtr = AH->StartBlobsPtr;
1789 endPtr = AH->EndBlobsPtr;
1793 startPtr = AH->StartDataPtr;
1794 endPtr = AH->EndDataPtr;
1797 if (startPtr != NULL)
1798 (*startPtr) (AH, te);
1801 * printf("Dumper arg for %d is %x\n", te->id,
1802 * te->dataDumperArg);
1806 * The user-provided DataDumper routine needs to call
1809 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1820 WriteToc(ArchiveHandle *AH)
1826 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1828 WriteInt(AH, AH->tocCount);
1830 for (te = AH->toc->next; te != AH->toc; te = te->next)
1832 WriteInt(AH, te->dumpId);
1833 WriteInt(AH, te->dataDumper ? 1 : 0);
1835 /* OID is recorded as a string for historical reasons */
1836 sprintf(workbuf, "%u", te->catalogId.tableoid);
1837 WriteStr(AH, workbuf);
1838 sprintf(workbuf, "%u", te->catalogId.oid);
1839 WriteStr(AH, workbuf);
1841 WriteStr(AH, te->tag);
1842 WriteStr(AH, te->desc);
1843 WriteStr(AH, te->defn);
1844 WriteStr(AH, te->dropStmt);
1845 WriteStr(AH, te->copyStmt);
1846 WriteStr(AH, te->namespace);
1847 WriteStr(AH, te->tablespace);
1848 WriteStr(AH, te->owner);
1849 WriteStr(AH, te->withOids ? "true" : "false");
1851 /* Dump list of dependencies */
1852 for (i = 0; i < te->nDeps; i++)
1854 sprintf(workbuf, "%d", te->dependencies[i]);
1855 WriteStr(AH, workbuf);
1857 WriteStr(AH, NULL); /* Terminate List */
1859 if (AH->WriteExtraTocPtr)
1860 (*AH->WriteExtraTocPtr) (AH, te);
1865 ReadToc(ArchiveHandle *AH)
1873 TocEntry *te = AH->toc->next;
1875 AH->tocCount = ReadInt(AH);
1878 for (i = 0; i < AH->tocCount; i++)
1880 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1881 te->dumpId = ReadInt(AH);
1883 if (te->dumpId > AH->maxDumpId)
1884 AH->maxDumpId = te->dumpId;
1887 if (te->dumpId <= 0)
1888 die_horribly(AH, modulename,
1889 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1892 te->hadDumper = ReadInt(AH);
1894 if (AH->version >= K_VERS_1_8)
1897 sscanf(tmp, "%u", &te->catalogId.tableoid);
1901 te->catalogId.tableoid = InvalidOid;
1903 sscanf(tmp, "%u", &te->catalogId.oid);
1906 te->tag = ReadStr(AH);
1907 te->desc = ReadStr(AH);
1908 te->defn = ReadStr(AH);
1909 te->dropStmt = ReadStr(AH);
1911 if (AH->version >= K_VERS_1_3)
1912 te->copyStmt = ReadStr(AH);
1914 if (AH->version >= K_VERS_1_6)
1915 te->namespace = ReadStr(AH);
1917 if (AH->version >= K_VERS_1_10)
1918 te->tablespace = ReadStr(AH);
1920 te->owner = ReadStr(AH);
1921 if (AH->version >= K_VERS_1_9)
1923 if (strcmp(ReadStr(AH), "true") == 0)
1924 te->withOids = true;
1926 te->withOids = false;
1929 te->withOids = true;
1931 /* Read TOC entry dependencies */
1932 if (AH->version >= K_VERS_1_5)
1935 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1941 break; /* end of list */
1942 if (depIdx >= depSize)
1945 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1947 sscanf(tmp, "%d", &deps[depIdx]);
1952 if (depIdx > 0) /* We have a non-null entry */
1954 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1955 te->dependencies = deps;
1961 te->dependencies = NULL;
1967 te->dependencies = NULL;
1971 if (AH->ReadExtraTocPtr)
1972 (*AH->ReadExtraTocPtr) (AH, te);
1974 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1975 i, te->dumpId, te->desc, te->tag);
1977 te->prev = AH->toc->prev;
1978 AH->toc->prev->next = te;
1985 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
1987 teReqs res = REQ_ALL;
1989 /* ENCODING objects are dumped specially, so always reject here */
1990 if (strcmp(te->desc, "ENCODING") == 0)
1993 /* If it's an ACL, maybe ignore it */
1994 if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1997 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
2000 /* Check if tablename only is wanted */
2003 if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
2005 if (!ropt->selTable)
2007 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2010 else if (strcmp(te->desc, "INDEX") == 0)
2012 if (!ropt->selIndex)
2014 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2017 else if (strcmp(te->desc, "FUNCTION") == 0)
2019 if (!ropt->selFunction)
2021 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2024 else if (strcmp(te->desc, "TRIGGER") == 0)
2026 if (!ropt->selTrigger)
2028 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2036 * Check if we had a dataDumper. Indicates if the entry is schema or
2042 * Special Case: If 'SEQUENCE SET' then it is considered a data
2045 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2046 res = res & REQ_DATA;
2048 res = res & ~REQ_DATA;
2052 * Special case: <Init> type with <Max OID> tag; this is part of a
2053 * DATA restore even though it has SQL.
2055 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2058 /* Mask it if we only want schema */
2059 if (ropt->schemaOnly)
2060 res = res & REQ_SCHEMA;
2062 /* Mask it we only want data */
2064 res = res & REQ_DATA;
2066 /* Mask it if we don't have a schema contribution */
2067 if (!te->defn || strlen(te->defn) == 0)
2068 res = res & ~REQ_SCHEMA;
2070 /* Finally, if we used a list, limit based on that as well */
2071 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2078 * Issue SET commands for parameters that we want to have set the same way
2079 * at all times during execution of a restore script.
2082 _doSetFixedOutputState(ArchiveHandle *AH)
2086 /* If we have an encoding setting, emit that */
2088 while (te != AH->toc)
2090 if (strcmp(te->desc, "ENCODING") == 0)
2092 ahprintf(AH, "%s", te->defn);
2098 /* Make sure function checking is disabled */
2099 ahprintf(AH, "SET check_function_bodies = false;\n");
2101 /* Avoid annoying notices etc */
2102 ahprintf(AH, "SET client_min_messages = warning;\n");
2108 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2109 * for updating state if appropriate. If user is NULL or an empty string,
2110 * the specification DEFAULT will be used.
2113 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2115 PQExpBuffer cmd = createPQExpBuffer();
2117 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2120 * SQL requires a string literal here. Might as well be correct.
2123 appendStringLiteral(cmd, user, false);
2125 appendPQExpBuffer(cmd, "DEFAULT");
2126 appendPQExpBuffer(cmd, ";");
2128 if (RestoringToDB(AH))
2132 res = PQexec(AH->connection, cmd->data);
2134 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2135 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2136 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2137 user, PQerrorMessage(AH->connection));
2142 ahprintf(AH, "%s\n\n", cmd->data);
2144 destroyPQExpBuffer(cmd);
2149 * Issue a SET default_with_oids command. Caller is responsible
2150 * for updating state if appropriate.
2153 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2155 PQExpBuffer cmd = createPQExpBuffer();
2157 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2160 if (RestoringToDB(AH))
2164 res = PQexec(AH->connection, cmd->data);
2166 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2167 warn_or_die_horribly(AH, modulename,
2168 "could not set default_with_oids: %s",
2169 PQerrorMessage(AH->connection));
2174 ahprintf(AH, "%s\n\n", cmd->data);
2176 destroyPQExpBuffer(cmd);
2181 * Issue the commands to connect to the specified database.
2183 * If we're currently restoring right into a database, this will
2184 * actually establish a connection. Otherwise it puts a \connect into
2185 * the script output.
2187 * NULL dbname implies reconnecting to the current DB (pretty useless).
2190 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2192 if (RestoringToDB(AH))
2193 ReconnectToServer(AH, dbname, NULL);
2196 PQExpBuffer qry = createPQExpBuffer();
2198 appendPQExpBuffer(qry, "\\connect %s\n\n",
2199 dbname ? fmtId(dbname) : "-");
2201 ahprintf(AH, qry->data);
2203 destroyPQExpBuffer(qry);
2207 * NOTE: currUser keeps track of what the imaginary session user in
2208 * our script is. It's now effectively reset to the original userID.
2213 AH->currUser = strdup("");
2215 /* don't assume we still know the output schema */
2217 free(AH->currSchema);
2218 AH->currSchema = strdup("");
2219 AH->currWithOids = -1;
2221 /* re-establish fixed state */
2222 _doSetFixedOutputState(AH);
2226 * Become the specified user, and update state to avoid redundant commands
2228 * NULL or empty argument is taken to mean restoring the session default
2231 _becomeUser(ArchiveHandle *AH, const char *user)
2234 user = ""; /* avoid null pointers */
2236 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2237 return; /* no need to do anything */
2239 _doSetSessionAuth(AH, user);
2242 * NOTE: currUser keeps track of what the imaginary session user in
2248 AH->currUser = strdup(user);
2252 * Become the owner of the the given TOC entry object. If
2253 * changes in ownership are not allowed, this doesn't do anything.
2256 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2258 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2261 _becomeUser(AH, te->owner);
2266 * Set the proper default_with_oids value for the table.
2269 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2271 if (AH->currWithOids != te->withOids)
2273 _doSetWithOids(AH, te->withOids);
2274 AH->currWithOids = te->withOids;
2280 * Issue the commands to select the specified schema as the current schema
2281 * in the target database.
2284 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2288 if (!schemaName || *schemaName == '\0' ||
2289 strcmp(AH->currSchema, schemaName) == 0)
2290 return; /* no need to do anything */
2292 qry = createPQExpBuffer();
2294 appendPQExpBuffer(qry, "SET search_path = %s",
2296 if (strcmp(schemaName, "pg_catalog") != 0)
2297 appendPQExpBuffer(qry, ", pg_catalog");
2299 if (RestoringToDB(AH))
2303 res = PQexec(AH->connection, qry->data);
2305 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2306 warn_or_die_horribly(AH, modulename,
2307 "could not set search_path to \"%s\": %s",
2308 schemaName, PQerrorMessage(AH->connection));
2313 ahprintf(AH, "%s;\n\n", qry->data);
2316 free(AH->currSchema);
2317 AH->currSchema = strdup(schemaName);
2319 destroyPQExpBuffer(qry);
2323 * Issue the commands to select the specified tablespace as the current one
2324 * in the target database.
2327 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2330 const char *want, *have;
2332 have = AH->currTablespace;
2335 /* no need to do anything for non-tablespace object */
2339 if (have && strcmp(want, have) == 0)
2340 return; /* no need to do anything */
2342 qry = createPQExpBuffer();
2344 if (strcmp(want, "") == 0)
2346 /* We want the tablespace to be the database's default */
2347 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2351 /* We want an explicit tablespace */
2352 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2355 if (RestoringToDB(AH))
2359 res = PQexec(AH->connection, qry->data);
2361 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2362 warn_or_die_horribly(AH, modulename,
2363 "could not set default_tablespace to %s: %s",
2364 fmtId(want), PQerrorMessage(AH->connection));
2369 ahprintf(AH, "%s;\n\n", qry->data);
2371 if (AH->currTablespace)
2372 free(AH->currTablespace);
2373 AH->currTablespace = strdup(want);
2375 destroyPQExpBuffer(qry);
2379 * Extract an object description for a TOC entry, and append it to buf.
2381 * This is not quite as general as it may seem, since it really only
2382 * handles constructing the right thing to put into ALTER ... OWNER TO.
2384 * The whole thing is pretty grotty, but we are kind of stuck since the
2385 * information used is all that's available in older dump files.
2388 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2390 const char *type = te->desc;
2392 /* Use ALTER TABLE for views and sequences */
2393 if (strcmp(type, "VIEW") == 0 ||
2394 strcmp(type, "SEQUENCE") == 0)
2397 /* We assume CONSTRAINTs are always pkey/unique indexes */
2398 if (strcmp(type, "CONSTRAINT") == 0)
2401 /* objects named by a schema and name */
2402 if (strcmp(type, "CONVERSION") == 0 ||
2403 strcmp(type, "DOMAIN") == 0 ||
2404 strcmp(type, "INDEX") == 0 ||
2405 strcmp(type, "TABLE") == 0 ||
2406 strcmp(type, "TYPE") == 0)
2408 appendPQExpBuffer(buf, "%s ", type);
2409 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2410 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2412 * Pre-7.3 pg_dump would sometimes (not always) put
2413 * a fmtId'd name into te->tag for an index.
2414 * This check is heuristic, so make its scope as
2415 * narrow as possible.
2417 if (AH->version < K_VERS_1_7 &&
2418 te->tag[0] == '"' &&
2419 te->tag[strlen(te->tag)-1] == '"' &&
2420 strcmp(type, "INDEX") == 0)
2421 appendPQExpBuffer(buf, "%s", te->tag);
2423 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2427 /* objects named by just a name */
2428 if (strcmp(type, "DATABASE") == 0 ||
2429 strcmp(type, "SCHEMA") == 0)
2431 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2436 * These object types require additional decoration. Fortunately,
2437 * the information needed is exactly what's in the DROP command.
2439 if (strcmp(type, "AGGREGATE") == 0 ||
2440 strcmp(type, "FUNCTION") == 0 ||
2441 strcmp(type, "OPERATOR") == 0 ||
2442 strcmp(type, "OPERATOR CLASS") == 0)
2444 /* Chop "DROP " off the front and make a modifiable copy */
2445 char *first = strdup(te->dropStmt + 5);
2448 /* point to last character in string */
2449 last = first + strlen(first) - 1;
2451 /* Strip off any ';' or '\n' at the end */
2452 while (last >= first && (*last == '\n' || *last == ';'))
2456 appendPQExpBufferStr(buf, first);
2462 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2467 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2469 /* ACLs are dumped only during acl pass */
2472 if (strcmp(te->desc, "ACL") != 0)
2477 if (strcmp(te->desc, "ACL") == 0)
2482 * Avoid dumping the public schema, as it will already be created ...
2483 * unless we are using --clean mode, in which case it's been deleted
2484 * and we'd better recreate it.
2486 if (!ropt->dropSchema &&
2487 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2490 /* Select owner, schema, and tablespace as necessary */
2491 _becomeOwner(AH, te);
2492 _selectOutputSchema(AH, te->namespace);
2493 _selectTablespace(AH, te->tablespace);
2495 /* Set up OID mode too */
2496 if (strcmp(te->desc, "TABLE") == 0)
2497 _setWithOids(AH, te);
2499 /* Emit header comment for item */
2500 if (!AH->noTocComments)
2509 ahprintf(AH, "--\n");
2510 if (AH->public.verbose)
2512 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2513 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2518 ahprintf(AH, "-- Dependencies:");
2519 for (i = 0; i < te->nDeps; i++)
2520 ahprintf(AH, " %d", te->dependencies[i]);
2524 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2525 pfx, te->tag, te->desc,
2526 te->namespace ? te->namespace : "-",
2529 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2532 if (AH->PrintExtraTocPtr != NULL)
2533 (*AH->PrintExtraTocPtr) (AH, te);
2534 ahprintf(AH, "--\n\n");
2538 * Actually print the definition.
2540 * Really crude hack for suppressing AUTHORIZATION clause that old
2541 * pg_dump versions put into CREATE SCHEMA. We have to do this when
2542 * --no-owner mode is selected. This is ugly, but I see
2543 * no other good way ...
2545 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2547 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2551 if (strlen(te->defn) > 0)
2552 ahprintf(AH, "%s\n\n", te->defn);
2556 * If we aren't using SET SESSION AUTH to determine ownership, we must
2557 * instead issue an ALTER OWNER command. We assume that anything without
2558 * a DROP command is not a separately ownable object. All the categories
2559 * with DROP commands must appear in one list or the other.
2561 if (!ropt->noOwner && !ropt->use_setsessauth &&
2562 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2564 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2565 strcmp(te->desc, "CONSTRAINT") == 0 ||
2566 strcmp(te->desc, "CONVERSION") == 0 ||
2567 strcmp(te->desc, "DATABASE") == 0 ||
2568 strcmp(te->desc, "DOMAIN") == 0 ||
2569 strcmp(te->desc, "FUNCTION") == 0 ||
2570 strcmp(te->desc, "INDEX") == 0 ||
2571 strcmp(te->desc, "OPERATOR") == 0 ||
2572 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2573 strcmp(te->desc, "SCHEMA") == 0 ||
2574 strcmp(te->desc, "TABLE") == 0 ||
2575 strcmp(te->desc, "TYPE") == 0 ||
2576 strcmp(te->desc, "VIEW") == 0 ||
2577 strcmp(te->desc, "SEQUENCE") == 0)
2579 PQExpBuffer temp = createPQExpBuffer();
2581 appendPQExpBuffer(temp, "ALTER ");
2582 _getObjectDescription(temp, te, AH);
2583 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2584 ahprintf(AH, "%s\n\n", temp->data);
2585 destroyPQExpBuffer(temp);
2587 else if (strcmp(te->desc, "CAST") == 0 ||
2588 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2589 strcmp(te->desc, "DEFAULT") == 0 ||
2590 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2591 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2592 strcmp(te->desc, "RULE") == 0 ||
2593 strcmp(te->desc, "TRIGGER") == 0)
2595 /* these object types don't have separate owners */
2599 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2605 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2606 * commands, so we can no longer assume we know the current auth
2609 if (strncmp(te->desc, "ACL", 3) == 0)
2613 AH->currUser = NULL;
2618 WriteHead(ArchiveHandle *AH)
2622 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2623 (*AH->WriteBytePtr) (AH, AH->vmaj);
2624 (*AH->WriteBytePtr) (AH, AH->vmin);
2625 (*AH->WriteBytePtr) (AH, AH->vrev);
2626 (*AH->WriteBytePtr) (AH, AH->intSize);
2627 (*AH->WriteBytePtr) (AH, AH->offSize);
2628 (*AH->WriteBytePtr) (AH, AH->format);
2631 if (AH->compression != 0)
2632 write_msg(modulename, "WARNING: requested compression not available in this "
2633 "installation -- archive will be uncompressed\n");
2635 AH->compression = 0;
2638 WriteInt(AH, AH->compression);
2640 crtm = *localtime(&AH->createDate);
2641 WriteInt(AH, crtm.tm_sec);
2642 WriteInt(AH, crtm.tm_min);
2643 WriteInt(AH, crtm.tm_hour);
2644 WriteInt(AH, crtm.tm_mday);
2645 WriteInt(AH, crtm.tm_mon);
2646 WriteInt(AH, crtm.tm_year);
2647 WriteInt(AH, crtm.tm_isdst);
2648 WriteStr(AH, PQdb(AH->connection));
2649 WriteStr(AH, AH->public.remoteVersionStr);
2650 WriteStr(AH, PG_VERSION);
2654 ReadHead(ArchiveHandle *AH)
2660 /* If we haven't already read the header... */
2661 if (!AH->readHeader)
2664 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2666 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2667 die_horribly(AH, modulename, "did not find magic string in file header\n");
2669 AH->vmaj = (*AH->ReadBytePtr) (AH);
2670 AH->vmin = (*AH->ReadBytePtr) (AH);
2672 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2673 AH->vrev = (*AH->ReadBytePtr) (AH);
2677 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2680 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2681 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2682 AH->vmaj, AH->vmin);
2684 AH->intSize = (*AH->ReadBytePtr) (AH);
2685 if (AH->intSize > 32)
2686 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2687 (unsigned long) AH->intSize);
2689 if (AH->intSize > sizeof(int))
2690 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2692 if (AH->version >= K_VERS_1_7)
2693 AH->offSize = (*AH->ReadBytePtr) (AH);
2695 AH->offSize = AH->intSize;
2697 fmt = (*AH->ReadBytePtr) (AH);
2699 if (AH->format != fmt)
2700 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2704 if (AH->version >= K_VERS_1_2)
2706 if (AH->version < K_VERS_1_4)
2707 AH->compression = (*AH->ReadBytePtr) (AH);
2709 AH->compression = ReadInt(AH);
2712 AH->compression = Z_DEFAULT_COMPRESSION;
2715 if (AH->compression != 0)
2716 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2719 if (AH->version >= K_VERS_1_4)
2721 crtm.tm_sec = ReadInt(AH);
2722 crtm.tm_min = ReadInt(AH);
2723 crtm.tm_hour = ReadInt(AH);
2724 crtm.tm_mday = ReadInt(AH);
2725 crtm.tm_mon = ReadInt(AH);
2726 crtm.tm_year = ReadInt(AH);
2727 crtm.tm_isdst = ReadInt(AH);
2729 AH->archdbname = ReadStr(AH);
2731 AH->createDate = mktime(&crtm);
2733 if (AH->createDate == (time_t) -1)
2734 write_msg(modulename, "WARNING: invalid creation date in header\n");
2737 if (AH->version >= K_VERS_1_10)
2739 AH->archiveRemoteVersion = ReadStr(AH);
2740 AH->archiveDumpVersion = ReadStr(AH);
2748 * check to see if fseek can be performed.
2755 if (fseeko(fp, 0, SEEK_CUR) != 0)
2757 else if (sizeof(off_t) > sizeof(long))
2760 * At this point, off_t is too large for long, so we return based
2761 * on whether an off_t version of fseek is available.
2777 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
2781 if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&tim)) != 0)
2782 ahprintf(AH, "-- %s %s\n\n", msg, buf);