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.101 2005/01/11 05:14:10 tgl Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup.h"
25 #include "pg_backup_archiver.h"
26 #include "pg_backup_db.h"
27 #include "dumputils.h"
33 #include "pqexpbuffer.h"
34 #include "libpq/libpq-fs.h"
41 REQ_ALL = REQ_SCHEMA + REQ_DATA
45 static char *modulename = gettext_noop("archiver");
48 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
49 const int compression, ArchiveMode mode);
50 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te);
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);
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);
63 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
65 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool acl_pass);
66 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
67 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
68 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
69 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
70 static int _discoverArchiveFormat(ArchiveHandle *AH);
72 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
73 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
75 static int _canRestoreBlobs(ArchiveHandle *AH);
76 static int _restoringToDB(ArchiveHandle *AH);
82 * The objective it to make writing new formats and dumpers as simple
83 * as possible, if necessary at the expense of extra function calls etc.
88 /* Create a new archive */
91 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
92 const int compression)
95 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
97 return (Archive *) AH;
100 /* Open an existing archive */
103 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
105 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
107 return (Archive *) AH;
112 CloseArchive(Archive *AHX)
115 ArchiveHandle *AH = (ArchiveHandle *) AHX;
117 (*AH->ClosePtr) (AH);
119 /* Close the output */
121 res = GZCLOSE(AH->OF);
122 else if (AH->OF != stdout)
123 res = fclose(AH->OF);
126 die_horribly(AH, modulename, "could not close output archive file\n");
131 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
133 ArchiveHandle *AH = (ArchiveHandle *) AHX;
134 TocEntry *te = AH->toc->next;
141 AH->stage = STAGE_INITIALIZING;
144 * Check for nonsensical option combinations.
146 * NB: create+dropSchema is useless because if you're creating the DB,
147 * there's no need to drop individual items in it. Moreover, if we
148 * tried to do that then we'd issue the drops in the database
149 * initially connected to, not the one we will create, which is very
152 if (ropt->create && ropt->dropSchema)
153 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
156 * If we're using a DB connection, then connect it.
160 ahlog(AH, 1, "connecting to database for restore\n");
161 if (AH->version < K_VERS_1_3)
162 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
164 /* XXX Should get this from the archive */
165 AHX->minRemoteVersion = 070100;
166 AHX->maxRemoteVersion = 999999;
168 ConnectDatabase(AHX, ropt->dbname,
169 ropt->pghost, ropt->pgport, ropt->username,
170 ropt->requirePassword, ropt->ignoreVersion);
173 * If we're talking to the DB directly, don't send comments since
174 * they obscure SQL when displaying errors
176 AH->noTocComments = 1;
180 * Work out if we have an implied data-only restore. This can happen
181 * if the dump was data only or if the user has used a toc list to
182 * exclude all of the schema data. All we do is look for schema
183 * entries - if none are found then we set the dataOnly flag.
185 * We could scan for wanted TABLE entries, but that is not the same as
186 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
192 while (te != AH->toc)
194 reqs = _tocEntryRequired(te, ropt, false);
195 if ((reqs & REQ_SCHEMA) != 0)
196 { /* It's schema, and it's wanted */
204 ropt->dataOnly = impliedDataOnly;
205 ahlog(AH, 1, "implied data-only restore\n");
210 * Setup the output file if necessary.
212 if (ropt->filename || ropt->compression)
213 sav = SetOutput(AH, ropt->filename, ropt->compression);
215 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
218 * Establish important parameter values right away.
220 _doSetFixedOutputState(AH);
222 AH->stage = STAGE_PROCESSING;
225 * Drop the items at the start, in reverse order
227 if (ropt->dropSchema)
232 while (te != AH->toc)
234 reqs = _tocEntryRequired(te, ropt, false);
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);
250 * Now process each TOC entry
253 while (te != AH->toc)
257 /* Work out what, if anything, we want from this entry */
258 reqs = _tocEntryRequired(te, ropt, false);
260 /* Dump any relevant dump warnings to stderr */
261 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
263 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
264 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
265 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
266 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
271 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
273 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
275 _printTocEntry(AH, te, ropt, false, false);
278 /* If we created a DB, connect to it... */
279 if (strcmp(te->desc, "DATABASE") == 0)
281 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
282 _reconnectToDB(AH, te->tag);
287 * If we have a data component, then process it
289 if ((reqs & REQ_DATA) != 0)
292 * hadDumper will be set if there is genuine data component
293 * for this node. Otherwise, we need to check the defn field
294 * for statements that need to be executed in data-only
300 * If we can output the data, then restore it.
302 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
305 if (AH->compression != 0)
306 die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
309 _printTocEntry(AH, te, ropt, true, false);
312 * Maybe we can't do BLOBS, so check if this node is
315 if ((strcmp(te->desc, "BLOBS") == 0) &&
316 !_canRestoreBlobs(AH))
318 ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
321 * This is a bit nasty - we assume, for the
322 * moment, that if a custom output is used, then
323 * we don't want warnings.
325 if (!AH->CustomOutPtr)
326 write_msg(modulename, "WARNING: skipping large-object restoration\n");
330 _disableTriggersIfNecessary(AH, te, ropt);
332 /* Select owner and schema as necessary */
333 _becomeOwner(AH, te);
334 _selectOutputSchema(AH, te->namespace);
336 ahlog(AH, 1, "restoring data for table \"%s\"\n", te->tag);
339 * If we have a copy statement, use it. As of
340 * V1.3, these are separate to allow easy import
341 * from withing a database connection. Pre 1.3
342 * archives can not use DB connections and are
343 * sent to output only.
345 * For V1.3+, the table data MUST have a copy
346 * statement so that we can go into appropriate
349 if (te->copyStmt && strlen(te->copyStmt) > 0)
350 ahprintf(AH, te->copyStmt);
352 (*AH->PrintTocDataPtr) (AH, te, ropt);
355 * If we just restored blobs, fix references in
356 * previously-loaded tables; otherwise, if we
357 * previously restored blobs, fix references in
358 * this table. Note that in standard cases the
359 * BLOBS entry comes after all TABLE DATA entries,
360 * but we should cope with other orders in case
361 * the user demands reordering.
363 if (strcmp(te->desc, "BLOBS") == 0)
364 fixPriorBlobRefs(AH, te, ropt);
365 else if (AH->createdBlobXref &&
366 strcmp(te->desc, "TABLE DATA") == 0)
368 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
369 FixupBlobRefs(AH, te);
372 _enableTriggersIfNecessary(AH, te, ropt);
376 else if (!defnDumped)
378 /* If we haven't already dumped the defn part, do so now */
379 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
380 _printTocEntry(AH, te, ropt, false, false);
384 } /* end loop over TOC entries */
387 * Scan TOC again to output ownership commands and ACLs
390 while (te != AH->toc)
394 /* Work out what, if anything, we want from this entry */
395 reqs = _tocEntryRequired(te, ropt, true);
397 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
399 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
401 _printTocEntry(AH, te, ropt, false, true);
408 * Clean up & we're done.
410 AH->stage = STAGE_FINALIZING;
412 if (ropt->filename || ropt->compression)
413 ResetOutput(AH, sav);
417 PQfinish(AH->connection);
418 AH->connection = NULL;
420 if (AH->blobConnection)
422 PQfinish(AH->blobConnection);
423 AH->blobConnection = NULL;
427 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
431 * After restoring BLOBS, fix all blob references in previously-restored
432 * tables. (Normally, the BLOBS entry should appear after all TABLE DATA
433 * entries, so this will in fact handle all blob references.)
436 fixPriorBlobRefs(ArchiveHandle *AH, TocEntry *blobte, RestoreOptions *ropt)
441 if (AH->createdBlobXref)
443 /* NULL parameter means disable ALL user triggers */
444 _disableTriggersIfNecessary(AH, NULL, ropt);
446 for (te = AH->toc->next; te != blobte; te = te->next)
448 if (strcmp(te->desc, "TABLE DATA") == 0)
450 reqs = _tocEntryRequired(te, ropt, false);
452 if ((reqs & REQ_DATA) != 0) /* We loaded the data */
454 ahlog(AH, 1, "fixing up large-object cross-reference for \"%s\"\n", te->tag);
455 FixupBlobRefs(AH, te);
460 /* NULL parameter means enable ALL user triggers */
461 _enableTriggersIfNecessary(AH, NULL, ropt);
466 * Allocate a new RestoreOptions block.
467 * This is mainly so we can initialize it, but also for future expansion,
470 NewRestoreOptions(void)
472 RestoreOptions *opts;
474 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
476 opts->format = archUnknown;
477 opts->suppressDumpWarnings = false;
478 opts->exit_on_error = false;
484 * Returns true if we're restoring directly to the database (and
485 * aren't just making a psql script that can do the restoration).
488 _restoringToDB(ArchiveHandle *AH)
490 return (AH->ropt->useDB && AH->connection);
494 _canRestoreBlobs(ArchiveHandle *AH)
496 return _restoringToDB(AH);
500 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
502 /* This hack is only needed in a data-only restore */
503 if (!ropt->dataOnly || !ropt->disable_triggers)
506 /* Don't do it for the BLOBS TocEntry, either */
507 if (te && strcmp(te->desc, "BLOBS") == 0)
511 * Become superuser if possible, since they are the only ones who can
512 * update pg_class. If -S was not given, assume the initial user
513 * identity is a superuser.
515 _becomeUser(AH, ropt->superuser);
517 ahlog(AH, 1, "disabling triggers\n");
520 * Disable them. This is a hack. Needs to be done via an appropriate
521 * 'SET' command when one is available.
523 ahprintf(AH, "-- Disable triggers\n");
526 * Just update the AFFECTED table, if known. Otherwise update all
529 if (te && te->tag && strlen(te->tag) > 0)
530 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
531 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
534 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
535 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
539 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
541 /* This hack is only needed in a data-only restore */
542 if (!ropt->dataOnly || !ropt->disable_triggers)
545 /* Don't do it for the BLOBS TocEntry, either */
546 if (te && strcmp(te->desc, "BLOBS") == 0)
550 * Become superuser if possible, since they are the only ones who can
551 * update pg_class. If -S was not given, assume the initial user
552 * identity is a superuser.
554 _becomeUser(AH, ropt->superuser);
556 ahlog(AH, 1, "enabling triggers\n");
559 * Enable them. This is a hack. Needs to be done via an appropriate
560 * 'SET' command when one is available.
562 ahprintf(AH, "-- Enable triggers\n");
565 * Just update the AFFECTED table, if known. Otherwise update all
568 if (te && te->tag && strlen(te->tag) > 0)
569 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
570 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
571 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
574 ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
575 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
576 "FROM pg_catalog.pg_namespace "
577 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
581 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
586 WriteData(Archive *AHX, const void *data, size_t dLen)
588 ArchiveHandle *AH = (ArchiveHandle *) AHX;
591 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
593 return (*AH->WriteDataPtr) (AH, data, dLen);
597 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
598 * repository for all metadata. But the name has stuck.
603 ArchiveEntry(Archive *AHX,
604 CatalogId catalogId, DumpId dumpId,
606 const char *namespace,
607 const char *tablespace,
608 const char *owner, bool withOids,
609 const char *desc, const char *defn,
610 const char *dropStmt, const char *copyStmt,
611 const DumpId *deps, int nDeps,
612 DataDumperPtr dumpFn, void *dumpArg)
614 ArchiveHandle *AH = (ArchiveHandle *) AHX;
617 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
619 die_horribly(AH, modulename, "out of memory\n");
622 if (dumpId > AH->maxDumpId)
623 AH->maxDumpId = dumpId;
625 newToc->prev = AH->toc->prev;
626 newToc->next = AH->toc;
627 AH->toc->prev->next = newToc;
628 AH->toc->prev = newToc;
630 newToc->catalogId = catalogId;
631 newToc->dumpId = dumpId;
633 newToc->tag = strdup(tag);
634 newToc->namespace = namespace ? strdup(namespace) : NULL;
635 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
636 newToc->owner = strdup(owner);
637 newToc->withOids = withOids;
638 newToc->desc = strdup(desc);
639 newToc->defn = strdup(defn);
640 newToc->dropStmt = strdup(dropStmt);
641 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
645 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
646 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
647 newToc->nDeps = nDeps;
651 newToc->dependencies = NULL;
655 newToc->dataDumper = dumpFn;
656 newToc->dataDumperArg = dumpArg;
657 newToc->hadDumper = dumpFn ? true : false;
659 newToc->formatData = NULL;
661 if (AH->ArchiveEntryPtr !=NULL)
662 (*AH->ArchiveEntryPtr) (AH, newToc);
667 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
669 ArchiveHandle *AH = (ArchiveHandle *) AHX;
670 TocEntry *te = AH->toc->next;
675 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
677 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
678 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
679 AH->archdbname, AH->tocCount, AH->compression);
696 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
697 ahprintf(AH, "; Format: %s\n", fmtName);
698 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
699 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
700 if (AH->archiveRemoteVersion)
701 ahprintf(AH, "; Dumped from database version: %s\n",
702 AH->archiveRemoteVersion);
703 if (AH->archiveDumpVersion)
704 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
705 AH->archiveDumpVersion);
707 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
709 while (te != AH->toc)
711 if (_tocEntryRequired(te, ropt, false) != 0)
712 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
713 te->catalogId.tableoid, te->catalogId.oid,
714 te->desc, te->namespace ? te->namespace : "-",
720 ResetOutput(AH, sav);
727 /* Called by a dumper to signal start of a BLOB */
729 StartBlob(Archive *AHX, Oid oid)
731 ArchiveHandle *AH = (ArchiveHandle *) AHX;
733 if (!AH->StartBlobPtr)
734 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
736 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
741 /* Called by a dumper to signal end of a BLOB */
743 EndBlob(Archive *AHX, Oid oid)
745 ArchiveHandle *AH = (ArchiveHandle *) AHX;
748 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
758 * Called by a format handler before any blobs are restored
761 StartRestoreBlobs(ArchiveHandle *AH)
767 * Called by a format handler after all blobs are restored
770 EndRestoreBlobs(ArchiveHandle *AH)
774 ahlog(AH, 2, "committing large-object transactions\n");
775 CommitTransaction(AH);
778 if (AH->blobTxActive)
779 CommitTransactionXref(AH);
781 if (AH->createdBlobXref)
782 CreateBlobXrefIndex(AH);
784 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
789 * Called by a format handler to initiate restoration of a blob
792 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
798 if (!AH->createdBlobXref)
801 die_horribly(AH, modulename, "cannot restore large objects without a database connection\n");
803 CreateBlobXrefTable(AH);
804 AH->createdBlobXref = 1;
807 /* Initialize the LO Buffer */
811 * Start long-running TXs if necessary
815 ahlog(AH, 2, "starting large-object transactions\n");
816 StartTransaction(AH);
818 if (!AH->blobTxActive)
819 StartTransactionXref(AH);
821 loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
823 die_horribly(AH, modulename, "could not create large object\n");
825 ahlog(AH, 2, "restoring large object with OID %u as %u\n", oid, loOid);
827 InsertBlobXref(AH, oid, loOid);
829 AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
831 die_horribly(AH, modulename, "could not open large object\n");
837 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
839 if (AH->lo_buf_used > 0)
841 /* Write remaining bytes from the LO buffer */
844 res = lo_write(AH->connection, AH->loFd, (void *) AH->lo_buf, AH->lo_buf_used);
846 ahlog(AH, 5, "wrote remaining %lu bytes of large-object data (result = %lu)\n",
847 (unsigned long) AH->lo_buf_used, (unsigned long) res);
848 if (res != AH->lo_buf_used)
849 die_horribly(AH, modulename, "could not write to large object (result: %lu, expected: %lu)\n",
850 (unsigned long) res, (unsigned long) AH->lo_buf_used);
854 lo_close(AH->connection, AH->loFd);
858 * Commit every BLOB_BATCH_SIZE blobs...
860 if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
862 ahlog(AH, 2, "committing large-object transactions\n");
863 CommitTransaction(AH);
864 CommitTransactionXref(AH);
869 * Sorting and Reordering
873 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
875 ArchiveHandle *AH = (ArchiveHandle *) AHX;
884 /* Allocate space for the 'wanted' array, and init it */
885 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
886 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
887 ropt->limitToList = true;
889 /* Set prev entry as head of list */
893 fh = fopen(ropt->tocFile, PG_BINARY_R);
895 die_horribly(AH, modulename, "could not open TOC file\n");
897 while (fgets(buf, 1024, fh) != NULL)
900 cmnt = strchr(buf, ';');
904 /* End string at comment */
908 /* Skip if all spaces */
909 if (strspn(buf, " \t") == strlen(buf))
913 id = strtol(buf, &endptr, 10);
914 if (endptr == buf || id <= 0 || id > AH->maxDumpId)
916 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
921 te = getTocEntryByDumpId(AH, id);
923 die_horribly(AH, modulename, "could not find entry for ID %d\n",
926 ropt->idWanted[id - 1] = true;
928 _moveAfter(AH, tePrev, te);
933 die_horribly(AH, modulename, "could not close TOC file: %s\n",
937 /**********************
938 * 'Convenience functions that look like standard IO functions
939 * for writing data when in dump mode.
940 **********************/
944 archputs(const char *s, Archive *AH)
946 return WriteData(AH, s, strlen(s));
951 archprintf(Archive *AH, const char *fmt,...)
955 int bSize = strlen(fmt) + 256;
959 * This is paranoid: deal with the possibility that vsnprintf is
960 * willing to ignore trailing null or returns > 0 even if string does
961 * not fit. It may be the case that it returns cnt = bufsize
963 while (cnt < 0 || cnt >= (bSize - 1))
968 p = (char *) malloc(bSize);
970 exit_horribly(AH, modulename, "out of memory\n");
972 cnt = vsnprintf(p, bSize, fmt, ap);
975 WriteData(AH, p, cnt);
981 /*******************************
982 * Stuff below here should be 'private' to the archiver routines
983 *******************************/
986 SetOutput(ArchiveHandle *AH, char *filename, int compression)
991 /* Replace the AH output file handle */
993 sav.gzOut = AH->gzOut;
1002 filename = AH->fSpec;
1005 fn = fileno(stdout);
1007 /* If compression explicitly requested, use gzopen */
1009 if (compression != 0)
1013 /* Don't use PG_BINARY_x since this is zlib */
1014 sprintf(fmode, "wb%d", compression);
1016 AH->OF = gzdopen(dup(fn), fmode);
1018 AH->OF = gzopen(filename, fmode);
1025 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1027 AH->OF = fopen(filename, PG_BINARY_W);
1032 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
1038 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1043 res = GZCLOSE(AH->OF);
1045 res = fclose(AH->OF);
1048 die_horribly(AH, modulename, "could not close output file: %s\n",
1051 AH->gzOut = sav.gzOut;
1058 * Print formatted text to the output file (usually stdout).
1061 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1065 int bSize = strlen(fmt) + 256; /* Should be enough */
1069 * This is paranoid: deal with the possibility that vsnprintf is
1070 * willing to ignore trailing null
1074 * or returns > 0 even if string does not fit. It may be the case that
1075 * it returns cnt = bufsize
1077 while (cnt < 0 || cnt >= (bSize - 1))
1082 p = (char *) malloc(bSize);
1084 die_horribly(AH, modulename, "out of memory\n");
1086 cnt = vsnprintf(p, bSize, fmt, ap);
1089 ahwrite(p, 1, cnt, AH);
1095 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1099 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1103 _write_msg(NULL, fmt, ap);
1108 * Single place for logic which says 'We are restoring to a direct DB connection'.
1111 RestoringToDB(ArchiveHandle *AH)
1113 return (AH->ropt && AH->ropt->useDB && AH->connection);
1117 * Write buffer to the output file (usually stdout). This is user for
1118 * outputting 'restore' scripts etc. It is even possible for an archive
1119 * format to create a custom output routine to 'fake' a restore if it
1120 * wants to generate a script (see TAR output).
1123 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1127 if (AH->writingBlob)
1129 if (AH->lo_buf_used + size * nmemb > AH->lo_buf_size)
1131 /* Split LO buffer */
1132 size_t remaining = AH->lo_buf_size - AH->lo_buf_used;
1133 size_t slack = nmemb * size - remaining;
1135 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1136 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_size);
1137 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1138 (unsigned long) AH->lo_buf_size, (unsigned long) res);
1139 if (res != AH->lo_buf_size)
1140 die_horribly(AH, modulename,
1141 "could not write to large object (result: %lu, expected: %lu)\n",
1142 (unsigned long) res, (unsigned long) AH->lo_buf_size);
1143 memcpy(AH->lo_buf, (char *) ptr + remaining, slack);
1144 AH->lo_buf_used = slack;
1148 /* LO Buffer is still large enough, buffer it */
1149 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, size * nmemb);
1150 AH->lo_buf_used += size * nmemb;
1153 return size * nmemb;
1157 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1158 if (res != (nmemb * size))
1159 die_horribly(AH, modulename, "could not write to compressed archive\n");
1162 else if (AH->CustomOutPtr)
1164 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1166 if (res != (nmemb * size))
1167 die_horribly(AH, modulename, "could not write to custom output routine\n");
1173 * If we're doing a restore, and it's direct to DB, and we're
1174 * connected then send it to the DB.
1176 if (RestoringToDB(AH))
1177 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1180 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1182 die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
1183 (unsigned long) res, (unsigned long) nmemb);
1189 /* Common exit code */
1191 _write_msg(const char *modulename, const char *fmt, va_list ap)
1194 fprintf(stderr, "%s: [%s] ", progname, gettext(modulename));
1196 fprintf(stderr, "%s: ", progname);
1197 vfprintf(stderr, gettext(fmt), ap);
1201 write_msg(const char *modulename, const char *fmt,...)
1206 _write_msg(modulename, fmt, ap);
1212 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1214 _write_msg(modulename, fmt, ap);
1218 if (AH->public.verbose)
1219 write_msg(NULL, "*** aborted because of error\n");
1221 PQfinish(AH->connection);
1222 if (AH->blobConnection)
1223 PQfinish(AH->blobConnection);
1231 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1236 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1240 /* Archiver use (just different arg declaration) */
1242 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1247 _die_horribly(AH, modulename, fmt, ap);
1251 /* on some error, we may decide to go on... */
1253 warn_or_die_horribly(ArchiveHandle *AH,
1254 const char *modulename, const char *fmt,...)
1262 /* Do nothing special */
1265 case STAGE_INITIALIZING:
1266 if (AH->stage != AH->lastErrorStage)
1267 write_msg(modulename, "Error while INITIALIZING:\n");
1270 case STAGE_PROCESSING:
1271 if (AH->stage != AH->lastErrorStage)
1272 write_msg(modulename, "Error while PROCESSING TOC:\n");
1275 case STAGE_FINALIZING:
1276 if (AH->stage != AH->lastErrorStage)
1277 write_msg(modulename, "Error while FINALIZING:\n");
1280 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1282 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n", AH->currentTE->dumpId,
1283 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1284 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1286 AH->lastErrorStage = AH->stage;
1287 AH->lastErrorTE = AH->currentTE;
1290 if (AH->public.exit_on_error)
1291 _die_horribly(AH, modulename, fmt, ap);
1294 _write_msg(modulename, fmt, ap);
1295 AH->public.n_errors++;
1301 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1303 te->prev->next = te->next;
1304 te->next->prev = te->prev;
1307 te->next = pos->next;
1309 pos->next->prev = te;
1316 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1318 te->prev->next = te->next;
1319 te->next->prev = te->prev;
1321 te->prev = pos->prev;
1323 pos->prev->next = te;
1329 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1334 while (te != AH->toc)
1336 if (te->dumpId == id)
1344 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1346 TocEntry *te = getTocEntryByDumpId(AH, id);
1351 return _tocEntryRequired(te, ropt, false);
1355 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1360 (*AH->WriteBytePtr) (AH, wasSet);
1362 /* Write out off_t smallest byte first, prevents endian mismatch */
1363 for (off = 0; off < sizeof(off_t); off++)
1365 (*AH->WriteBytePtr) (AH, o & 0xFF);
1368 return sizeof(off_t) + 1;
1372 ReadOffset(ArchiveHandle *AH, off_t *o)
1378 /* Initialize to zero */
1381 /* Check for old version */
1382 if (AH->version < K_VERS_1_7)
1384 /* Prior versions wrote offsets using WriteInt */
1386 /* -1 means not set */
1388 return K_OFFSET_POS_NOT_SET;
1390 return K_OFFSET_NO_DATA;
1392 /* Cast to off_t because it was written as an int. */
1394 return K_OFFSET_POS_SET;
1398 * Read the flag indicating the state of the data pointer. Check if
1399 * valid and die if not.
1401 * This used to be handled by a negative or zero pointer, now we use an
1402 * extra byte specifically for the state.
1404 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1408 case K_OFFSET_POS_NOT_SET:
1409 case K_OFFSET_NO_DATA:
1410 case K_OFFSET_POS_SET:
1415 die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1421 for (off = 0; off < AH->offSize; off++)
1423 if (off < sizeof(off_t))
1424 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1427 if ((*AH->ReadBytePtr) (AH) != 0)
1428 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1436 WriteInt(ArchiveHandle *AH, int i)
1441 * This is a bit yucky, but I don't want to make the binary format
1442 * very dependent on representation, and not knowing much about it, I
1443 * write out a sign byte. If you change this, don't forget to change
1444 * the file version #, and modify readInt to read the new format AS
1445 * WELL AS the old formats.
1451 (*AH->WriteBytePtr) (AH, 1);
1455 (*AH->WriteBytePtr) (AH, 0);
1457 for (b = 0; b < AH->intSize; b++)
1459 (*AH->WriteBytePtr) (AH, i & 0xFF);
1463 return AH->intSize + 1;
1467 ReadInt(ArchiveHandle *AH)
1472 int sign = 0; /* Default positive */
1475 if (AH->version > K_VERS_1_0)
1476 /* Read a sign byte */
1477 sign = (*AH->ReadBytePtr) (AH);
1479 for (b = 0; b < AH->intSize; b++)
1481 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1483 res = res + (bv << bitShift);
1494 WriteStr(ArchiveHandle *AH, const char *c)
1500 res = WriteInt(AH, strlen(c));
1501 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1504 res = WriteInt(AH, -1);
1510 ReadStr(ArchiveHandle *AH)
1520 buf = (char *) malloc(l + 1);
1522 die_horribly(AH, modulename, "out of memory\n");
1524 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1532 _discoverArchiveFormat(ArchiveHandle *AH)
1535 char sig[6]; /* More than enough */
1540 write_msg(modulename, "attempting to ascertain archive format\n");
1544 free(AH->lookahead);
1546 AH->lookaheadSize = 512;
1547 AH->lookahead = calloc(1, 512);
1548 AH->lookaheadLen = 0;
1549 AH->lookaheadPos = 0;
1554 fh = fopen(AH->fSpec, PG_BINARY_R);
1560 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1562 cnt = fread(sig, 1, 5, fh);
1567 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1569 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1570 (unsigned long) cnt);
1573 /* Save it, just in case we need it later */
1574 strncpy(&AH->lookahead[0], sig, 5);
1575 AH->lookaheadLen = 5;
1577 if (strncmp(sig, "PGDMP", 5) == 0)
1579 AH->vmaj = fgetc(fh);
1580 AH->vmin = fgetc(fh);
1582 /* Save these too... */
1583 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1584 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1586 /* Check header version; varies from V1.0 */
1587 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1589 AH->vrev = fgetc(fh);
1590 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1595 /* Make a convenient integer <maj><min><rev>00 */
1596 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1598 AH->intSize = fgetc(fh);
1599 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1601 if (AH->version >= K_VERS_1_7)
1603 AH->offSize = fgetc(fh);
1604 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1607 AH->offSize = AH->intSize;
1609 AH->format = fgetc(fh);
1610 AH->lookahead[AH->lookaheadLen++] = AH->format;
1615 * *Maybe* we have a tar archive format file... So, read first 512
1618 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1619 AH->lookaheadLen += cnt;
1621 if (AH->lookaheadLen != 512)
1622 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1624 if (!isValidTarHeader(AH->lookahead))
1625 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1627 AH->format = archTar;
1630 /* If we can't seek, then mark the header as read */
1631 if (fseeko(fh, 0, SEEK_SET) != 0)
1634 * NOTE: Formats that use the lookahead buffer can unset this in
1635 * their Init routine.
1640 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1643 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1644 (unsigned long) AH->lookaheadLen);
1647 /* Close the file */
1649 if (fclose(fh) != 0)
1650 die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
1658 * Allocate an archive handle
1660 static ArchiveHandle *
1661 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1662 const int compression, ArchiveMode mode)
1667 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1670 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1672 die_horribly(AH, modulename, "out of memory\n");
1674 /* AH->debugLevel = 100; */
1676 AH->vmaj = K_VERS_MAJOR;
1677 AH->vmin = K_VERS_MINOR;
1678 AH->vrev = K_VERS_REV;
1680 AH->createDate = time(NULL);
1682 AH->intSize = sizeof(int);
1683 AH->offSize = sizeof(off_t);
1686 AH->fSpec = strdup(FileSpec);
1689 * Not used; maybe later....
1691 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1692 * i--) if (AH->workDir[i-1] == '/')
1698 AH->currUser = strdup(""); /* So it's valid, but we can free() it
1699 * later if necessary */
1700 AH->currSchema = strdup(""); /* ditto */
1701 AH->currWithOids = -1; /* force SET */
1703 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1705 die_horribly(AH, modulename, "out of memory\n");
1707 AH->toc->next = AH->toc;
1708 AH->toc->prev = AH->toc;
1711 AH->compression = compression;
1713 AH->pgCopyBuf = createPQExpBuffer();
1714 AH->sqlBuf = createPQExpBuffer();
1716 /* Open stdout with no compression for AH output handle */
1721 write_msg(modulename, "archive format is %d\n", fmt);
1724 if (fmt == archUnknown)
1725 AH->format = _discoverArchiveFormat(AH);
1733 InitArchiveFmt_Custom(AH);
1737 InitArchiveFmt_Files(AH);
1741 InitArchiveFmt_Null(AH);
1745 InitArchiveFmt_Tar(AH);
1749 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1752 /* sql error handling */
1753 AH->public.exit_on_error = true;
1754 AH->public.n_errors = 0;
1761 WriteDataChunks(ArchiveHandle *AH)
1763 TocEntry *te = AH->toc->next;
1764 StartDataPtr startPtr;
1767 while (te != AH->toc)
1769 if (te->dataDumper != NULL)
1772 /* printf("Writing data for %d (%x)\n", te->id, te); */
1774 if (strcmp(te->desc, "BLOBS") == 0)
1776 startPtr = AH->StartBlobsPtr;
1777 endPtr = AH->EndBlobsPtr;
1781 startPtr = AH->StartDataPtr;
1782 endPtr = AH->EndDataPtr;
1785 if (startPtr != NULL)
1786 (*startPtr) (AH, te);
1789 * printf("Dumper arg for %d is %x\n", te->id,
1790 * te->dataDumperArg);
1794 * The user-provided DataDumper routine needs to call
1797 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1808 WriteToc(ArchiveHandle *AH)
1814 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1816 WriteInt(AH, AH->tocCount);
1818 for (te = AH->toc->next; te != AH->toc; te = te->next)
1820 WriteInt(AH, te->dumpId);
1821 WriteInt(AH, te->dataDumper ? 1 : 0);
1823 /* OID is recorded as a string for historical reasons */
1824 sprintf(workbuf, "%u", te->catalogId.tableoid);
1825 WriteStr(AH, workbuf);
1826 sprintf(workbuf, "%u", te->catalogId.oid);
1827 WriteStr(AH, workbuf);
1829 WriteStr(AH, te->tag);
1830 WriteStr(AH, te->desc);
1831 WriteStr(AH, te->defn);
1832 WriteStr(AH, te->dropStmt);
1833 WriteStr(AH, te->copyStmt);
1834 WriteStr(AH, te->namespace);
1835 WriteStr(AH, te->tablespace);
1836 WriteStr(AH, te->owner);
1837 WriteStr(AH, te->withOids ? "true" : "false");
1839 /* Dump list of dependencies */
1840 for (i = 0; i < te->nDeps; i++)
1842 sprintf(workbuf, "%d", te->dependencies[i]);
1843 WriteStr(AH, workbuf);
1845 WriteStr(AH, NULL); /* Terminate List */
1847 if (AH->WriteExtraTocPtr)
1848 (*AH->WriteExtraTocPtr) (AH, te);
1853 ReadToc(ArchiveHandle *AH)
1861 TocEntry *te = AH->toc->next;
1863 AH->tocCount = ReadInt(AH);
1866 for (i = 0; i < AH->tocCount; i++)
1868 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1869 te->dumpId = ReadInt(AH);
1871 if (te->dumpId > AH->maxDumpId)
1872 AH->maxDumpId = te->dumpId;
1875 if (te->dumpId <= 0)
1876 die_horribly(AH, modulename,
1877 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1880 te->hadDumper = ReadInt(AH);
1882 if (AH->version >= K_VERS_1_8)
1885 sscanf(tmp, "%u", &te->catalogId.tableoid);
1889 te->catalogId.tableoid = InvalidOid;
1891 sscanf(tmp, "%u", &te->catalogId.oid);
1894 te->tag = ReadStr(AH);
1895 te->desc = ReadStr(AH);
1896 te->defn = ReadStr(AH);
1897 te->dropStmt = ReadStr(AH);
1899 if (AH->version >= K_VERS_1_3)
1900 te->copyStmt = ReadStr(AH);
1902 if (AH->version >= K_VERS_1_6)
1903 te->namespace = ReadStr(AH);
1905 if (AH->version >= K_VERS_1_10)
1906 te->tablespace = ReadStr(AH);
1908 te->owner = ReadStr(AH);
1909 if (AH->version >= K_VERS_1_9)
1911 if (strcmp(ReadStr(AH), "true") == 0)
1912 te->withOids = true;
1914 te->withOids = false;
1917 te->withOids = true;
1919 /* Read TOC entry dependencies */
1920 if (AH->version >= K_VERS_1_5)
1923 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1929 break; /* end of list */
1930 if (depIdx >= depSize)
1933 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1935 sscanf(tmp, "%d", &deps[depIdx]);
1940 if (depIdx > 0) /* We have a non-null entry */
1942 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1943 te->dependencies = deps;
1949 te->dependencies = NULL;
1955 te->dependencies = NULL;
1959 if (AH->ReadExtraTocPtr)
1960 (*AH->ReadExtraTocPtr) (AH, te);
1962 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1963 i, te->dumpId, te->desc, te->tag);
1965 te->prev = AH->toc->prev;
1966 AH->toc->prev->next = te;
1973 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool acl_pass)
1975 teReqs res = 3; /* Schema = 1, Data = 2, Both = 3 */
1977 /* ENCODING objects are dumped specially, so always reject here */
1978 if (strcmp(te->desc, "ENCODING") == 0)
1981 /* If it's an ACL, maybe ignore it */
1982 if ((!acl_pass || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1985 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1988 /* Check if tablename only is wanted */
1991 if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1993 if (!ropt->selTable)
1995 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1998 else if (strcmp(te->desc, "INDEX") == 0)
2000 if (!ropt->selIndex)
2002 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2005 else if (strcmp(te->desc, "FUNCTION") == 0)
2007 if (!ropt->selFunction)
2009 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2012 else if (strcmp(te->desc, "TRIGGER") == 0)
2014 if (!ropt->selTrigger)
2016 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2024 * Check if we had a dataDumper. Indicates if the entry is schema or
2030 * Special Case: If 'SEQUENCE SET' then it is considered a data
2033 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2034 res = res & REQ_DATA;
2036 res = res & ~REQ_DATA;
2040 * Special case: <Init> type with <Max OID> tag; this is part of a
2041 * DATA restore even though it has SQL.
2043 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2046 /* Mask it if we only want schema */
2047 if (ropt->schemaOnly)
2048 res = res & REQ_SCHEMA;
2050 /* Mask it we only want data */
2052 res = res & REQ_DATA;
2054 /* Mask it if we don't have a schema contribution */
2055 if (!te->defn || strlen(te->defn) == 0)
2056 res = res & ~REQ_SCHEMA;
2058 /* Finally, if we used a list, limit based on that as well */
2059 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2066 * Issue SET commands for parameters that we want to have set the same way
2067 * at all times during execution of a restore script.
2070 _doSetFixedOutputState(ArchiveHandle *AH)
2074 /* If we have an encoding setting, emit that */
2076 while (te != AH->toc)
2078 if (strcmp(te->desc, "ENCODING") == 0)
2080 ahprintf(AH, "%s", te->defn);
2086 /* Make sure function checking is disabled */
2087 ahprintf(AH, "SET check_function_bodies = false;\n");
2089 /* Avoid annoying notices etc */
2090 ahprintf(AH, "SET client_min_messages = warning;\n");
2096 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2097 * for updating state if appropriate. If user is NULL or an empty string,
2098 * the specification DEFAULT will be used.
2101 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2103 PQExpBuffer cmd = createPQExpBuffer();
2105 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2108 * SQL requires a string literal here. Might as well be correct.
2111 appendStringLiteral(cmd, user, false);
2113 appendPQExpBuffer(cmd, "DEFAULT");
2114 appendPQExpBuffer(cmd, ";");
2116 if (RestoringToDB(AH))
2120 res = PQexec(AH->connection, cmd->data);
2122 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2123 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2124 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2125 user, PQerrorMessage(AH->connection));
2130 ahprintf(AH, "%s\n\n", cmd->data);
2132 destroyPQExpBuffer(cmd);
2137 * Issue a SET default_with_oids command. Caller is responsible
2138 * for updating state if appropriate.
2141 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2143 PQExpBuffer cmd = createPQExpBuffer();
2145 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2148 if (RestoringToDB(AH))
2152 res = PQexec(AH->connection, cmd->data);
2154 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2155 warn_or_die_horribly(AH, modulename,
2156 "could not set default_with_oids: %s",
2157 PQerrorMessage(AH->connection));
2162 ahprintf(AH, "%s\n\n", cmd->data);
2164 destroyPQExpBuffer(cmd);
2169 * Issue the commands to connect to the specified database.
2171 * If we're currently restoring right into a database, this will
2172 * actually establish a connection. Otherwise it puts a \connect into
2173 * the script output.
2175 * NULL dbname implies reconnecting to the current DB (pretty useless).
2178 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2180 if (RestoringToDB(AH))
2181 ReconnectToServer(AH, dbname, NULL);
2184 PQExpBuffer qry = createPQExpBuffer();
2186 appendPQExpBuffer(qry, "\\connect %s\n\n",
2187 dbname ? fmtId(dbname) : "-");
2189 ahprintf(AH, qry->data);
2191 destroyPQExpBuffer(qry);
2195 * NOTE: currUser keeps track of what the imaginary session user in
2196 * our script is. It's now effectively reset to the original userID.
2201 AH->currUser = strdup("");
2203 /* don't assume we still know the output schema */
2205 free(AH->currSchema);
2206 AH->currSchema = strdup("");
2207 AH->currWithOids = -1;
2209 /* re-establish fixed state */
2210 _doSetFixedOutputState(AH);
2214 * Become the specified user, and update state to avoid redundant commands
2216 * NULL or empty argument is taken to mean restoring the session default
2219 _becomeUser(ArchiveHandle *AH, const char *user)
2222 user = ""; /* avoid null pointers */
2224 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2225 return; /* no need to do anything */
2227 _doSetSessionAuth(AH, user);
2230 * NOTE: currUser keeps track of what the imaginary session user in
2236 AH->currUser = strdup(user);
2240 * Become the owner of the the given TOC entry object. If
2241 * changes in ownership are not allowed, this doesn't do anything.
2244 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2246 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2249 _becomeUser(AH, te->owner);
2254 * Set the proper default_with_oids value for the table.
2257 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2259 if (AH->currWithOids != te->withOids)
2261 _doSetWithOids(AH, te->withOids);
2262 AH->currWithOids = te->withOids;
2268 * Issue the commands to select the specified schema as the current schema
2269 * in the target database.
2272 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2276 if (!schemaName || *schemaName == '\0' ||
2277 strcmp(AH->currSchema, schemaName) == 0)
2278 return; /* no need to do anything */
2280 qry = createPQExpBuffer();
2282 appendPQExpBuffer(qry, "SET search_path = %s",
2284 if (strcmp(schemaName, "pg_catalog") != 0)
2285 appendPQExpBuffer(qry, ", pg_catalog");
2287 if (RestoringToDB(AH))
2291 res = PQexec(AH->connection, qry->data);
2293 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2294 warn_or_die_horribly(AH, modulename,
2295 "could not set search_path to \"%s\": %s",
2296 schemaName, PQerrorMessage(AH->connection));
2301 ahprintf(AH, "%s;\n\n", qry->data);
2304 free(AH->currSchema);
2305 AH->currSchema = strdup(schemaName);
2307 destroyPQExpBuffer(qry);
2311 * Issue the commands to select the specified tablespace as the current one
2312 * in the target database.
2315 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2318 const char *want, *have;
2320 have = AH->currTablespace;
2323 /* no need to do anything for non-tablespace object */
2327 if (have && strcmp(want, have) == 0)
2328 return; /* no need to do anything */
2330 qry = createPQExpBuffer();
2332 if (strcmp(want, "") == 0)
2334 /* We want the tablespace to be the database's default */
2335 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2339 /* We want an explicit tablespace */
2340 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2343 if (RestoringToDB(AH))
2347 res = PQexec(AH->connection, qry->data);
2349 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2350 warn_or_die_horribly(AH, modulename,
2351 "could not set default_tablespace to %s: %s",
2352 fmtId(want), PQerrorMessage(AH->connection));
2357 ahprintf(AH, "%s;\n\n", qry->data);
2359 if (AH->currTablespace)
2360 free(AH->currTablespace);
2361 AH->currTablespace = strdup(want);
2363 destroyPQExpBuffer(qry);
2367 * Extract an object description for a TOC entry, and append it to buf.
2369 * This is not quite as general as it may seem, since it really only
2370 * handles constructing the right thing to put into ALTER ... OWNER TO.
2372 * The whole thing is pretty grotty, but we are kind of stuck since the
2373 * information used is all that's available in older dump files.
2376 _getObjectDescription(PQExpBuffer buf, TocEntry *te)
2378 const char *type = te->desc;
2380 /* Use ALTER TABLE for views and sequences */
2381 if (strcmp(type, "VIEW") == 0 ||
2382 strcmp(type, "SEQUENCE") == 0)
2385 /* We assume CONSTRAINTs are always pkey/unique indexes */
2386 if (strcmp(type, "CONSTRAINT") == 0)
2389 /* objects named by a schema and name */
2390 if (strcmp(type, "CONVERSION") == 0 ||
2391 strcmp(type, "DOMAIN") == 0 ||
2392 strcmp(type, "INDEX") == 0 ||
2393 strcmp(type, "TABLE") == 0 ||
2394 strcmp(type, "TYPE") == 0)
2396 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->namespace));
2397 appendPQExpBuffer(buf, ".%s", fmtId(te->tag));
2401 /* objects named by just a name */
2402 if (strcmp(type, "DATABASE") == 0 ||
2403 strcmp(type, "SCHEMA") == 0)
2405 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2410 * These object types require additional decoration. Fortunately,
2411 * the information needed is exactly what's in the DROP command.
2413 if (strcmp(type, "AGGREGATE") == 0 ||
2414 strcmp(type, "FUNCTION") == 0 ||
2415 strcmp(type, "OPERATOR") == 0 ||
2416 strcmp(type, "OPERATOR CLASS") == 0)
2418 /* Chop "DROP " off the front and make a modifiable copy */
2419 char *first = strdup(te->dropStmt + 5);
2422 /* point to last character in string */
2423 last = first + strlen(first) - 1;
2425 /* Strip off any ';' or '\n' at the end */
2426 while (last >= first && (*last == '\n' || *last == ';'))
2430 appendPQExpBufferStr(buf, first);
2436 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2441 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2443 /* ACLs are dumped only during acl pass */
2446 if (strcmp(te->desc, "ACL") != 0)
2451 if (strcmp(te->desc, "ACL") == 0)
2456 * Avoid dumping the public schema, as it will already be created ...
2457 * unless we are using --clean mode, in which case it's been deleted
2458 * and we'd better recreate it.
2460 if (!ropt->dropSchema &&
2461 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2464 /* Select owner, schema, and tablespace as necessary */
2465 _becomeOwner(AH, te);
2466 _selectOutputSchema(AH, te->namespace);
2467 _selectTablespace(AH, te->tablespace);
2469 /* Set up OID mode too */
2470 if (strcmp(te->desc, "TABLE") == 0)
2471 _setWithOids(AH, te);
2473 /* Emit header comment for item */
2474 if (!AH->noTocComments)
2483 ahprintf(AH, "--\n");
2484 if (AH->public.verbose)
2486 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2487 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2492 ahprintf(AH, "-- Dependencies:");
2493 for (i = 0; i < te->nDeps; i++)
2494 ahprintf(AH, " %d", te->dependencies[i]);
2498 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2499 pfx, te->tag, te->desc,
2500 te->namespace ? te->namespace : "-",
2503 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2506 if (AH->PrintExtraTocPtr != NULL)
2507 (*AH->PrintExtraTocPtr) (AH, te);
2508 ahprintf(AH, "--\n\n");
2512 * Actually print the definition.
2514 * Really crude hack for suppressing AUTHORIZATION clause that old
2515 * pg_dump versions put into CREATE SCHEMA. We have to do this when
2516 * --no-owner mode is selected. This is ugly, but I see
2517 * no other good way ...
2519 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2521 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2525 if (strlen(te->defn) > 0)
2526 ahprintf(AH, "%s\n\n", te->defn);
2530 * If we aren't using SET SESSION AUTH to determine ownership, we must
2531 * instead issue an ALTER OWNER command. We assume that anything without
2532 * a DROP command is not a separately ownable object. All the categories
2533 * with DROP commands must appear in one list or the other.
2535 if (!ropt->noOwner && !ropt->use_setsessauth &&
2536 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2538 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2539 strcmp(te->desc, "CONSTRAINT") == 0 ||
2540 strcmp(te->desc, "CONVERSION") == 0 ||
2541 strcmp(te->desc, "DATABASE") == 0 ||
2542 strcmp(te->desc, "DOMAIN") == 0 ||
2543 strcmp(te->desc, "FUNCTION") == 0 ||
2544 strcmp(te->desc, "INDEX") == 0 ||
2545 strcmp(te->desc, "OPERATOR") == 0 ||
2546 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2547 strcmp(te->desc, "SCHEMA") == 0 ||
2548 strcmp(te->desc, "TABLE") == 0 ||
2549 strcmp(te->desc, "TYPE") == 0 ||
2550 strcmp(te->desc, "VIEW") == 0 ||
2551 strcmp(te->desc, "SEQUENCE") == 0)
2553 PQExpBuffer temp = createPQExpBuffer();
2555 appendPQExpBuffer(temp, "ALTER ");
2556 _getObjectDescription(temp, te);
2557 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2558 ahprintf(AH, "%s\n\n", temp->data);
2559 destroyPQExpBuffer(temp);
2561 else if (strcmp(te->desc, "CAST") == 0 ||
2562 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2563 strcmp(te->desc, "DEFAULT") == 0 ||
2564 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2565 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2566 strcmp(te->desc, "RULE") == 0 ||
2567 strcmp(te->desc, "TRIGGER") == 0)
2569 /* these object types don't have separate owners */
2573 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2579 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2580 * commands, so we can no longer assume we know the current auth
2583 if (strncmp(te->desc, "ACL", 3) == 0)
2587 AH->currUser = NULL;
2592 WriteHead(ArchiveHandle *AH)
2596 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2597 (*AH->WriteBytePtr) (AH, AH->vmaj);
2598 (*AH->WriteBytePtr) (AH, AH->vmin);
2599 (*AH->WriteBytePtr) (AH, AH->vrev);
2600 (*AH->WriteBytePtr) (AH, AH->intSize);
2601 (*AH->WriteBytePtr) (AH, AH->offSize);
2602 (*AH->WriteBytePtr) (AH, AH->format);
2605 if (AH->compression != 0)
2606 write_msg(modulename, "WARNING: requested compression not available in this "
2607 "installation -- archive will be uncompressed\n");
2609 AH->compression = 0;
2612 WriteInt(AH, AH->compression);
2614 crtm = *localtime(&AH->createDate);
2615 WriteInt(AH, crtm.tm_sec);
2616 WriteInt(AH, crtm.tm_min);
2617 WriteInt(AH, crtm.tm_hour);
2618 WriteInt(AH, crtm.tm_mday);
2619 WriteInt(AH, crtm.tm_mon);
2620 WriteInt(AH, crtm.tm_year);
2621 WriteInt(AH, crtm.tm_isdst);
2622 WriteStr(AH, PQdb(AH->connection));
2623 WriteStr(AH, AH->public.remoteVersionStr);
2624 WriteStr(AH, PG_VERSION);
2628 ReadHead(ArchiveHandle *AH)
2634 /* If we haven't already read the header... */
2635 if (!AH->readHeader)
2638 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2640 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2641 die_horribly(AH, modulename, "did not find magic string in file header\n");
2643 AH->vmaj = (*AH->ReadBytePtr) (AH);
2644 AH->vmin = (*AH->ReadBytePtr) (AH);
2646 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2647 AH->vrev = (*AH->ReadBytePtr) (AH);
2651 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2654 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2655 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2656 AH->vmaj, AH->vmin);
2658 AH->intSize = (*AH->ReadBytePtr) (AH);
2659 if (AH->intSize > 32)
2660 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2661 (unsigned long) AH->intSize);
2663 if (AH->intSize > sizeof(int))
2664 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2666 if (AH->version >= K_VERS_1_7)
2667 AH->offSize = (*AH->ReadBytePtr) (AH);
2669 AH->offSize = AH->intSize;
2671 fmt = (*AH->ReadBytePtr) (AH);
2673 if (AH->format != fmt)
2674 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2678 if (AH->version >= K_VERS_1_2)
2680 if (AH->version < K_VERS_1_4)
2681 AH->compression = (*AH->ReadBytePtr) (AH);
2683 AH->compression = ReadInt(AH);
2686 AH->compression = Z_DEFAULT_COMPRESSION;
2689 if (AH->compression != 0)
2690 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2693 if (AH->version >= K_VERS_1_4)
2695 crtm.tm_sec = ReadInt(AH);
2696 crtm.tm_min = ReadInt(AH);
2697 crtm.tm_hour = ReadInt(AH);
2698 crtm.tm_mday = ReadInt(AH);
2699 crtm.tm_mon = ReadInt(AH);
2700 crtm.tm_year = ReadInt(AH);
2701 crtm.tm_isdst = ReadInt(AH);
2703 AH->archdbname = ReadStr(AH);
2705 AH->createDate = mktime(&crtm);
2707 if (AH->createDate == (time_t) -1)
2708 write_msg(modulename, "WARNING: invalid creation date in header\n");
2711 if (AH->version >= K_VERS_1_10)
2713 AH->archiveRemoteVersion = ReadStr(AH);
2714 AH->archiveDumpVersion = ReadStr(AH);
2722 * check to see if fseek can be performed.
2729 if (fseeko(fp, 0, SEEK_CUR) != 0)
2731 else if (sizeof(off_t) > sizeof(long))
2734 * At this point, off_t is too large for long, so we return based
2735 * on whether an off_t version of fseek is available.