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.149 2007/11/15 21:14:41 momjian Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup_db.h"
24 #include "dumputils.h"
34 #include "libpq/libpq-fs.h"
39 static const char *modulename = gettext_noop("archiver");
42 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
43 const int compression, ArchiveMode mode);
44 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
46 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
49 static void _doSetFixedOutputState(ArchiveHandle *AH);
50 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
51 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
52 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
53 static void _becomeUser(ArchiveHandle *AH, const char *user);
54 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
55 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
56 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
57 static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
58 static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
59 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
60 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
61 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
62 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
63 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
64 static int _discoverArchiveFormat(ArchiveHandle *AH);
66 static void dump_lo_buf(ArchiveHandle *AH);
67 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
68 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
70 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
71 static OutputContext SetOutput(ArchiveHandle *AH, char *filename, int compression);
72 static void ResetOutput(ArchiveHandle *AH, OutputContext savedContext);
78 * The objective it to make writing new formats and dumpers as simple
79 * as possible, if necessary at the expense of extra function calls etc.
84 /* Create a new archive */
87 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
88 const int compression, ArchiveMode mode)
91 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode);
93 return (Archive *) AH;
96 /* Open an existing archive */
99 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
101 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
103 return (Archive *) AH;
108 CloseArchive(Archive *AHX)
111 ArchiveHandle *AH = (ArchiveHandle *) AHX;
113 (*AH->ClosePtr) (AH);
115 /* Close the output */
117 res = GZCLOSE(AH->OF);
118 else if (AH->OF != stdout)
119 res = fclose(AH->OF);
122 die_horribly(AH, modulename, "could not close output file: %s\n",
128 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
130 ArchiveHandle *AH = (ArchiveHandle *) AHX;
137 AH->stage = STAGE_INITIALIZING;
140 * Check for nonsensical option combinations.
142 * NB: create+dropSchema is useless because if you're creating the DB,
143 * there's no need to drop individual items in it. Moreover, if we tried
144 * to do that then we'd issue the drops in the database initially
145 * connected to, not the one we will create, which is very bad...
147 if (ropt->create && ropt->dropSchema)
148 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
151 * If we're using a DB connection, then connect it.
155 ahlog(AH, 1, "connecting to database for restore\n");
156 if (AH->version < K_VERS_1_3)
157 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
159 /* XXX Should get this from the archive */
160 AHX->minRemoteVersion = 070100;
161 AHX->maxRemoteVersion = 999999;
163 ConnectDatabase(AHX, ropt->dbname,
164 ropt->pghost, ropt->pgport, ropt->username,
165 ropt->requirePassword, ropt->ignoreVersion);
168 * If we're talking to the DB directly, don't send comments since they
169 * obscure SQL when displaying errors
171 AH->noTocComments = 1;
175 * Work out if we have an implied data-only restore. This can happen if
176 * the dump was data only or if the user has used a toc list to exclude
177 * all of the schema data. All we do is look for schema entries - if none
178 * are found then we set the dataOnly flag.
180 * We could scan for wanted TABLE entries, but that is not the same as
181 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
185 int impliedDataOnly = 1;
187 for (te = AH->toc->next; te != AH->toc; te = te->next)
189 reqs = _tocEntryRequired(te, ropt, true);
190 if ((reqs & REQ_SCHEMA) != 0)
191 { /* It's schema, and it's wanted */
198 ropt->dataOnly = impliedDataOnly;
199 ahlog(AH, 1, "implied data-only restore\n");
204 * Setup the output file if necessary.
206 if (ropt->filename || ropt->compression)
207 sav = SetOutput(AH, ropt->filename, ropt->compression);
209 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
211 if (AH->public.verbose)
212 dumpTimestamp(AH, "Started on", AH->createDate);
214 if (ropt->single_txn)
217 StartTransaction(AH);
219 ahprintf(AH, "BEGIN;\n\n");
223 * Establish important parameter values right away.
225 _doSetFixedOutputState(AH);
227 AH->stage = STAGE_PROCESSING;
230 * Drop the items at the start, in reverse order
232 if (ropt->dropSchema)
234 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
238 reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
239 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
241 /* We want the schema */
242 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
243 /* Select owner and schema as necessary */
244 _becomeOwner(AH, te);
245 _selectOutputSchema(AH, te->namespace);
247 ahprintf(AH, "%s", te->dropStmt);
253 * Now process each non-ACL TOC entry
255 for (te = AH->toc->next; te != AH->toc; te = te->next)
259 /* Work out what, if anything, we want from this entry */
260 reqs = _tocEntryRequired(te, ropt, false);
262 /* Dump any relevant dump warnings to stderr */
263 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
265 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
266 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
267 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
268 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
273 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
275 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
277 _printTocEntry(AH, te, ropt, false, false);
281 * If we could not create a table and --no-data-for-failed-tables
282 * was given, ignore the corresponding TABLE DATA
284 if (ropt->noDataForFailedTables &&
285 AH->lastErrorTE == te &&
286 strcmp(te->desc, "TABLE") == 0)
290 ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
293 for (tes = te->next; tes != AH->toc; tes = tes->next)
295 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
296 strcmp(tes->tag, te->tag) == 0 &&
297 strcmp(tes->namespace ? tes->namespace : "",
298 te->namespace ? te->namespace : "") == 0)
300 /* mark it unwanted */
301 ropt->idWanted[tes->dumpId - 1] = false;
307 /* If we created a DB, connect to it... */
308 if (strcmp(te->desc, "DATABASE") == 0)
310 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
311 _reconnectToDB(AH, te->tag);
316 * If we have a data component, then process it
318 if ((reqs & REQ_DATA) != 0)
321 * hadDumper will be set if there is genuine data component for
322 * this node. Otherwise, we need to check the defn field for
323 * statements that need to be executed in data-only restores.
328 * If we can output the data, then restore it.
330 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
333 if (AH->compression != 0)
334 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
337 _printTocEntry(AH, te, ropt, true, false);
339 if (strcmp(te->desc, "BLOBS") == 0 ||
340 strcmp(te->desc, "BLOB COMMENTS") == 0)
342 ahlog(AH, 1, "restoring %s\n", te->desc);
344 _selectOutputSchema(AH, "pg_catalog");
346 (*AH->PrintTocDataPtr) (AH, te, ropt);
350 _disableTriggersIfNecessary(AH, te, ropt);
352 /* Select owner and schema as necessary */
353 _becomeOwner(AH, te);
354 _selectOutputSchema(AH, te->namespace);
356 ahlog(AH, 1, "restoring data for table \"%s\"\n",
360 * If we have a copy statement, use it. As of V1.3,
361 * these are separate to allow easy import from
362 * withing a database connection. Pre 1.3 archives can
363 * not use DB connections and are sent to output only.
365 * For V1.3+, the table data MUST have a copy
366 * statement so that we can go into appropriate mode
369 if (te->copyStmt && strlen(te->copyStmt) > 0)
371 ahprintf(AH, "%s", te->copyStmt);
372 AH->writingCopyData = true;
375 (*AH->PrintTocDataPtr) (AH, te, ropt);
377 AH->writingCopyData = false;
379 _enableTriggersIfNecessary(AH, te, ropt);
383 else if (!defnDumped)
385 /* If we haven't already dumped the defn part, do so now */
386 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
387 _printTocEntry(AH, te, ropt, false, false);
390 } /* end loop over TOC entries */
393 * Scan TOC again to output ownership commands and ACLs
395 for (te = AH->toc->next; te != AH->toc; te = te->next)
399 /* Work out what, if anything, we want from this entry */
400 reqs = _tocEntryRequired(te, ropt, true);
402 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
404 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
406 _printTocEntry(AH, te, ropt, false, true);
410 if (ropt->single_txn)
413 CommitTransaction(AH);
415 ahprintf(AH, "COMMIT;\n\n");
418 if (AH->public.verbose)
419 dumpTimestamp(AH, "Completed on", time(NULL));
421 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
424 * Clean up & we're done.
426 AH->stage = STAGE_FINALIZING;
428 if (ropt->filename || ropt->compression)
429 ResetOutput(AH, sav);
433 PQfinish(AH->connection);
434 AH->connection = NULL;
439 * Allocate a new RestoreOptions block.
440 * This is mainly so we can initialize it, but also for future expansion,
443 NewRestoreOptions(void)
445 RestoreOptions *opts;
447 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
449 opts->format = archUnknown;
450 opts->suppressDumpWarnings = false;
451 opts->exit_on_error = false;
457 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
459 /* This hack is only needed in a data-only restore */
460 if (!ropt->dataOnly || !ropt->disable_triggers)
463 ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
466 * Become superuser if possible, since they are the only ones who can
467 * disable constraint triggers. If -S was not given, assume the initial
468 * user identity is a superuser. (XXX would it be better to become the
471 _becomeUser(AH, ropt->superuser);
476 _selectOutputSchema(AH, te->namespace);
478 ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
483 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
485 /* This hack is only needed in a data-only restore */
486 if (!ropt->dataOnly || !ropt->disable_triggers)
489 ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
492 * Become superuser if possible, since they are the only ones who can
493 * disable constraint triggers. If -S was not given, assume the initial
494 * user identity is a superuser. (XXX would it be better to become the
497 _becomeUser(AH, ropt->superuser);
502 _selectOutputSchema(AH, te->namespace);
504 ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
509 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
514 WriteData(Archive *AHX, const void *data, size_t dLen)
516 ArchiveHandle *AH = (ArchiveHandle *) AHX;
519 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
521 return (*AH->WriteDataPtr) (AH, data, dLen);
525 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
526 * repository for all metadata. But the name has stuck.
531 ArchiveEntry(Archive *AHX,
532 CatalogId catalogId, DumpId dumpId,
534 const char *namespace,
535 const char *tablespace,
536 const char *owner, bool withOids,
537 const char *desc, const char *defn,
538 const char *dropStmt, const char *copyStmt,
539 const DumpId *deps, int nDeps,
540 DataDumperPtr dumpFn, void *dumpArg)
542 ArchiveHandle *AH = (ArchiveHandle *) AHX;
545 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
547 die_horribly(AH, modulename, "out of memory\n");
550 if (dumpId > AH->maxDumpId)
551 AH->maxDumpId = dumpId;
553 newToc->prev = AH->toc->prev;
554 newToc->next = AH->toc;
555 AH->toc->prev->next = newToc;
556 AH->toc->prev = newToc;
558 newToc->catalogId = catalogId;
559 newToc->dumpId = dumpId;
561 newToc->tag = strdup(tag);
562 newToc->namespace = namespace ? strdup(namespace) : NULL;
563 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
564 newToc->owner = strdup(owner);
565 newToc->withOids = withOids;
566 newToc->desc = strdup(desc);
567 newToc->defn = strdup(defn);
568 newToc->dropStmt = strdup(dropStmt);
569 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
573 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
574 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
575 newToc->nDeps = nDeps;
579 newToc->dependencies = NULL;
583 newToc->dataDumper = dumpFn;
584 newToc->dataDumperArg = dumpArg;
585 newToc->hadDumper = dumpFn ? true : false;
587 newToc->formatData = NULL;
589 if (AH->ArchiveEntryPtr !=NULL)
590 (*AH->ArchiveEntryPtr) (AH, newToc);
595 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
597 ArchiveHandle *AH = (ArchiveHandle *) AHX;
598 TocEntry *te = AH->toc->next;
603 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
605 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
606 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
607 AH->archdbname, AH->tocCount, AH->compression);
624 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
625 ahprintf(AH, "; Format: %s\n", fmtName);
626 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
627 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
628 if (AH->archiveRemoteVersion)
629 ahprintf(AH, "; Dumped from database version: %s\n",
630 AH->archiveRemoteVersion);
631 if (AH->archiveDumpVersion)
632 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
633 AH->archiveDumpVersion);
635 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
637 while (te != AH->toc)
639 if (_tocEntryRequired(te, ropt, true) != 0)
640 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
641 te->catalogId.tableoid, te->catalogId.oid,
642 te->desc, te->namespace ? te->namespace : "-",
648 ResetOutput(AH, sav);
655 /* Called by a dumper to signal start of a BLOB */
657 StartBlob(Archive *AHX, Oid oid)
659 ArchiveHandle *AH = (ArchiveHandle *) AHX;
661 if (!AH->StartBlobPtr)
662 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
664 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
669 /* Called by a dumper to signal end of a BLOB */
671 EndBlob(Archive *AHX, Oid oid)
673 ArchiveHandle *AH = (ArchiveHandle *) AHX;
676 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
686 * Called by a format handler before any blobs are restored
689 StartRestoreBlobs(ArchiveHandle *AH)
691 if (!AH->ropt->single_txn)
694 StartTransaction(AH);
696 ahprintf(AH, "BEGIN;\n\n");
703 * Called by a format handler after all blobs are restored
706 EndRestoreBlobs(ArchiveHandle *AH)
708 if (!AH->ropt->single_txn)
711 CommitTransaction(AH);
713 ahprintf(AH, "COMMIT;\n\n");
716 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
721 * Called by a format handler to initiate restoration of a blob
724 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
730 /* Initialize the LO Buffer */
733 ahlog(AH, 2, "restoring large object with OID %u\n", oid);
737 loOid = lo_create(AH->connection, oid);
738 if (loOid == 0 || loOid != oid)
739 die_horribly(AH, modulename, "could not create large object %u\n",
742 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
744 die_horribly(AH, modulename, "could not open large object\n");
748 ahprintf(AH, "SELECT lo_open(lo_create(%u), %d);\n", oid, INV_WRITE);
755 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
757 if (AH->lo_buf_used > 0)
759 /* Write remaining bytes from the LO buffer */
767 lo_close(AH->connection, AH->loFd);
772 ahprintf(AH, "SELECT lo_close(0);\n\n");
777 * Sorting and Reordering
781 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
783 ArchiveHandle *AH = (ArchiveHandle *) AHX;
792 /* Allocate space for the 'wanted' array, and init it */
793 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
794 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
796 /* Set prev entry as head of list */
800 fh = fopen(ropt->tocFile, PG_BINARY_R);
802 die_horribly(AH, modulename, "could not open TOC file \"%s\": %s\n",
803 ropt->tocFile, strerror(errno));
805 while (fgets(buf, sizeof(buf), fh) != NULL)
807 /* Truncate line at comment, if any */
808 cmnt = strchr(buf, ';');
812 /* Ignore if all blank */
813 if (strspn(buf, " \t\r") == strlen(buf))
816 /* Get an ID, check it's valid and not already seen */
817 id = strtol(buf, &endptr, 10);
818 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
819 ropt->idWanted[id - 1])
821 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
826 te = getTocEntryByDumpId(AH, id);
828 die_horribly(AH, modulename, "could not find entry for ID %d\n",
831 ropt->idWanted[id - 1] = true;
833 _moveAfter(AH, tePrev, te);
838 die_horribly(AH, modulename, "could not close TOC file: %s\n",
843 * Set up a dummy ID filter that selects all dump IDs
846 InitDummyWantedList(Archive *AHX, RestoreOptions *ropt)
848 ArchiveHandle *AH = (ArchiveHandle *) AHX;
850 /* Allocate space for the 'wanted' array, and init it to 1's */
851 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
852 memset(ropt->idWanted, 1, sizeof(bool) * AH->maxDumpId);
855 /**********************
856 * 'Convenience functions that look like standard IO functions
857 * for writing data when in dump mode.
858 **********************/
862 archputs(const char *s, Archive *AH)
864 return WriteData(AH, s, strlen(s));
869 archprintf(Archive *AH, const char *fmt,...)
873 int bSize = strlen(fmt) + 256;
877 * This is paranoid: deal with the possibility that vsnprintf is willing
878 * to ignore trailing null or returns > 0 even if string does not fit. It
879 * may be the case that it returns cnt = bufsize
881 while (cnt < 0 || cnt >= (bSize - 1))
886 p = (char *) malloc(bSize);
888 exit_horribly(AH, modulename, "out of memory\n");
890 cnt = vsnprintf(p, bSize, fmt, ap);
893 WriteData(AH, p, cnt);
899 /*******************************
900 * Stuff below here should be 'private' to the archiver routines
901 *******************************/
904 SetOutput(ArchiveHandle *AH, char *filename, int compression)
909 /* Replace the AH output file handle */
911 sav.gzOut = AH->gzOut;
920 filename = AH->fSpec;
925 /* If compression explicitly requested, use gzopen */
927 if (compression != 0)
931 /* Don't use PG_BINARY_x since this is zlib */
932 sprintf(fmode, "wb%d", compression);
934 AH->OF = gzdopen(dup(fn), fmode);
936 AH->OF = gzopen(filename, fmode);
942 if (AH->mode == archModeAppend)
945 AH->OF = fdopen(dup(fn), PG_BINARY_A);
947 AH->OF = fopen(filename, PG_BINARY_A);
952 AH->OF = fdopen(dup(fn), PG_BINARY_W);
954 AH->OF = fopen(filename, PG_BINARY_W);
962 die_horribly(AH, modulename, "could not open output file \"%s\": %s\n",
963 filename, strerror(errno));
965 die_horribly(AH, modulename, "could not open output file: %s\n",
973 ResetOutput(ArchiveHandle *AH, OutputContext sav)
978 res = GZCLOSE(AH->OF);
980 res = fclose(AH->OF);
983 die_horribly(AH, modulename, "could not close output file: %s\n",
986 AH->gzOut = sav.gzOut;
993 * Print formatted text to the output file (usually stdout).
996 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1000 int bSize = strlen(fmt) + 256; /* Should be enough */
1004 * This is paranoid: deal with the possibility that vsnprintf is willing
1005 * to ignore trailing null
1009 * or returns > 0 even if string does not fit. It may be the case that it
1010 * returns cnt = bufsize
1012 while (cnt < 0 || cnt >= (bSize - 1))
1017 p = (char *) malloc(bSize);
1019 die_horribly(AH, modulename, "out of memory\n");
1021 cnt = vsnprintf(p, bSize, fmt, ap);
1024 ahwrite(p, 1, cnt, AH);
1030 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1034 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1038 _write_msg(NULL, fmt, ap);
1043 * Single place for logic which says 'We are restoring to a direct DB connection'.
1046 RestoringToDB(ArchiveHandle *AH)
1048 return (AH->ropt && AH->ropt->useDB && AH->connection);
1052 * Dump the current contents of the LO data buffer while writing a BLOB
1055 dump_lo_buf(ArchiveHandle *AH)
1061 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1062 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1063 (unsigned long) AH->lo_buf_used, (unsigned long) res);
1064 if (res != AH->lo_buf_used)
1065 die_horribly(AH, modulename,
1066 "could not write to large object (result: %lu, expected: %lu)\n",
1067 (unsigned long) res, (unsigned long) AH->lo_buf_used);
1074 str = PQescapeBytea((const unsigned char *) AH->lo_buf,
1075 AH->lo_buf_used, &len);
1077 die_horribly(AH, modulename, "out of memory\n");
1079 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1080 AH->writingBlob = 0;
1081 ahprintf(AH, "SELECT lowrite(0, '%s');\n", str);
1082 AH->writingBlob = 1;
1086 AH->lo_buf_used = 0;
1091 * Write buffer to the output file (usually stdout). This is user for
1092 * outputting 'restore' scripts etc. It is even possible for an archive
1093 * format to create a custom output routine to 'fake' a restore if it
1094 * wants to generate a script (see TAR output).
1097 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1101 if (AH->writingBlob)
1103 size_t remaining = size * nmemb;
1105 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1107 size_t avail = AH->lo_buf_size - AH->lo_buf_used;
1109 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1110 ptr = (const void *) ((const char *) ptr + avail);
1112 AH->lo_buf_used += avail;
1116 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1117 AH->lo_buf_used += remaining;
1119 return size * nmemb;
1123 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1124 if (res != (nmemb * size))
1125 die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1128 else if (AH->CustomOutPtr)
1130 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1132 if (res != (nmemb * size))
1133 die_horribly(AH, modulename, "could not write to custom output routine\n");
1139 * If we're doing a restore, and it's direct to DB, and we're
1140 * connected then send it to the DB.
1142 if (RestoringToDB(AH))
1143 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1146 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1148 die_horribly(AH, modulename, "could not write to output file: %s\n",
1155 /* Common exit code */
1157 _write_msg(const char *modulename, const char *fmt, va_list ap)
1160 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1162 fprintf(stderr, "%s: ", progname);
1163 vfprintf(stderr, _(fmt), ap);
1167 write_msg(const char *modulename, const char *fmt,...)
1172 _write_msg(modulename, fmt, ap);
1178 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1180 _write_msg(modulename, fmt, ap);
1184 if (AH->public.verbose)
1185 write_msg(NULL, "*** aborted because of error\n");
1187 PQfinish(AH->connection);
1195 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1200 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1204 /* Archiver use (just different arg declaration) */
1206 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1211 _die_horribly(AH, modulename, fmt, ap);
1215 /* on some error, we may decide to go on... */
1217 warn_or_die_horribly(ArchiveHandle *AH,
1218 const char *modulename, const char *fmt,...)
1226 /* Do nothing special */
1229 case STAGE_INITIALIZING:
1230 if (AH->stage != AH->lastErrorStage)
1231 write_msg(modulename, "Error while INITIALIZING:\n");
1234 case STAGE_PROCESSING:
1235 if (AH->stage != AH->lastErrorStage)
1236 write_msg(modulename, "Error while PROCESSING TOC:\n");
1239 case STAGE_FINALIZING:
1240 if (AH->stage != AH->lastErrorStage)
1241 write_msg(modulename, "Error while FINALIZING:\n");
1244 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1246 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1247 AH->currentTE->dumpId,
1248 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1249 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1251 AH->lastErrorStage = AH->stage;
1252 AH->lastErrorTE = AH->currentTE;
1255 if (AH->public.exit_on_error)
1256 _die_horribly(AH, modulename, fmt, ap);
1259 _write_msg(modulename, fmt, ap);
1260 AH->public.n_errors++;
1266 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1268 te->prev->next = te->next;
1269 te->next->prev = te->prev;
1272 te->next = pos->next;
1274 pos->next->prev = te;
1281 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1283 te->prev->next = te->next;
1284 te->next->prev = te->prev;
1286 te->prev = pos->prev;
1288 pos->prev->next = te;
1294 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1299 while (te != AH->toc)
1301 if (te->dumpId == id)
1309 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1311 TocEntry *te = getTocEntryByDumpId(AH, id);
1316 return _tocEntryRequired(te, ropt, true);
1320 WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1325 (*AH->WriteBytePtr) (AH, wasSet);
1327 /* Write out pgoff_t smallest byte first, prevents endian mismatch */
1328 for (off = 0; off < sizeof(pgoff_t); off++)
1330 (*AH->WriteBytePtr) (AH, o & 0xFF);
1333 return sizeof(pgoff_t) + 1;
1337 ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1343 /* Initialize to zero */
1346 /* Check for old version */
1347 if (AH->version < K_VERS_1_7)
1349 /* Prior versions wrote offsets using WriteInt */
1351 /* -1 means not set */
1353 return K_OFFSET_POS_NOT_SET;
1355 return K_OFFSET_NO_DATA;
1357 /* Cast to pgoff_t because it was written as an int. */
1359 return K_OFFSET_POS_SET;
1363 * Read the flag indicating the state of the data pointer. Check if valid
1366 * This used to be handled by a negative or zero pointer, now we use an
1367 * extra byte specifically for the state.
1369 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1373 case K_OFFSET_POS_NOT_SET:
1374 case K_OFFSET_NO_DATA:
1375 case K_OFFSET_POS_SET:
1380 die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1386 for (off = 0; off < AH->offSize; off++)
1388 if (off < sizeof(pgoff_t))
1389 *o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1392 if ((*AH->ReadBytePtr) (AH) != 0)
1393 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1401 WriteInt(ArchiveHandle *AH, int i)
1406 * This is a bit yucky, but I don't want to make the binary format very
1407 * dependent on representation, and not knowing much about it, I write out
1408 * a sign byte. If you change this, don't forget to change the file
1409 * version #, and modify readInt to read the new format AS WELL AS the old
1416 (*AH->WriteBytePtr) (AH, 1);
1420 (*AH->WriteBytePtr) (AH, 0);
1422 for (b = 0; b < AH->intSize; b++)
1424 (*AH->WriteBytePtr) (AH, i & 0xFF);
1428 return AH->intSize + 1;
1432 ReadInt(ArchiveHandle *AH)
1437 int sign = 0; /* Default positive */
1440 if (AH->version > K_VERS_1_0)
1441 /* Read a sign byte */
1442 sign = (*AH->ReadBytePtr) (AH);
1444 for (b = 0; b < AH->intSize; b++)
1446 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1448 res = res + (bv << bitShift);
1459 WriteStr(ArchiveHandle *AH, const char *c)
1465 res = WriteInt(AH, strlen(c));
1466 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1469 res = WriteInt(AH, -1);
1475 ReadStr(ArchiveHandle *AH)
1485 buf = (char *) malloc(l + 1);
1487 die_horribly(AH, modulename, "out of memory\n");
1489 if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1490 die_horribly(AH, modulename, "unexpected end of file\n");
1499 _discoverArchiveFormat(ArchiveHandle *AH)
1502 char sig[6]; /* More than enough */
1507 write_msg(modulename, "attempting to ascertain archive format\n");
1511 free(AH->lookahead);
1513 AH->lookaheadSize = 512;
1514 AH->lookahead = calloc(1, 512);
1515 AH->lookaheadLen = 0;
1516 AH->lookaheadPos = 0;
1521 fh = fopen(AH->fSpec, PG_BINARY_R);
1523 die_horribly(AH, modulename, "could not open input file \"%s\": %s\n",
1524 AH->fSpec, strerror(errno));
1530 die_horribly(AH, modulename, "could not open input file: %s\n",
1534 cnt = fread(sig, 1, 5, fh);
1539 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1541 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1542 (unsigned long) cnt);
1545 /* Save it, just in case we need it later */
1546 strncpy(&AH->lookahead[0], sig, 5);
1547 AH->lookaheadLen = 5;
1549 if (strncmp(sig, "PGDMP", 5) == 0)
1551 AH->vmaj = fgetc(fh);
1552 AH->vmin = fgetc(fh);
1554 /* Save these too... */
1555 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1556 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1558 /* Check header version; varies from V1.0 */
1559 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1561 AH->vrev = fgetc(fh);
1562 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1567 /* Make a convenient integer <maj><min><rev>00 */
1568 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1570 AH->intSize = fgetc(fh);
1571 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1573 if (AH->version >= K_VERS_1_7)
1575 AH->offSize = fgetc(fh);
1576 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1579 AH->offSize = AH->intSize;
1581 AH->format = fgetc(fh);
1582 AH->lookahead[AH->lookaheadLen++] = AH->format;
1587 * *Maybe* we have a tar archive format file... So, read first 512
1590 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1591 AH->lookaheadLen += cnt;
1593 if (AH->lookaheadLen != 512)
1594 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1596 if (!isValidTarHeader(AH->lookahead))
1597 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1599 AH->format = archTar;
1602 /* If we can't seek, then mark the header as read */
1603 if (fseeko(fh, 0, SEEK_SET) != 0)
1606 * NOTE: Formats that use the lookahead buffer can unset this in their
1612 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1615 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1616 (unsigned long) AH->lookaheadLen);
1619 /* Close the file */
1621 if (fclose(fh) != 0)
1622 die_horribly(AH, modulename, "could not close input file: %s\n",
1630 * Allocate an archive handle
1632 static ArchiveHandle *
1633 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1634 const int compression, ArchiveMode mode)
1639 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1642 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1644 die_horribly(AH, modulename, "out of memory\n");
1646 /* AH->debugLevel = 100; */
1648 AH->vmaj = K_VERS_MAJOR;
1649 AH->vmin = K_VERS_MINOR;
1650 AH->vrev = K_VERS_REV;
1652 /* initialize for backwards compatible string processing */
1653 AH->public.encoding = 0; /* PG_SQL_ASCII */
1654 AH->public.std_strings = false;
1656 /* sql error handling */
1657 AH->public.exit_on_error = true;
1658 AH->public.n_errors = 0;
1660 AH->createDate = time(NULL);
1662 AH->intSize = sizeof(int);
1663 AH->offSize = sizeof(pgoff_t);
1666 AH->fSpec = strdup(FileSpec);
1669 * Not used; maybe later....
1671 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1672 * i--) if (AH->workDir[i-1] == '/')
1678 AH->currUser = strdup(""); /* So it's valid, but we can free() it later
1680 AH->currSchema = strdup(""); /* ditto */
1681 AH->currWithOids = -1; /* force SET */
1683 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1685 die_horribly(AH, modulename, "out of memory\n");
1687 AH->toc->next = AH->toc;
1688 AH->toc->prev = AH->toc;
1691 AH->compression = compression;
1693 AH->pgCopyBuf = createPQExpBuffer();
1694 AH->sqlBuf = createPQExpBuffer();
1696 /* Open stdout with no compression for AH output handle */
1701 * On Windows, we need to use binary mode to read/write non-text archive
1702 * formats. Force stdin/stdout into binary mode if that is what we are
1706 if (fmt != archNull &&
1707 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1709 if (mode == archModeWrite)
1710 setmode(fileno(stdout), O_BINARY);
1712 setmode(fileno(stdin), O_BINARY);
1717 write_msg(modulename, "archive format is %d\n", fmt);
1720 if (fmt == archUnknown)
1721 AH->format = _discoverArchiveFormat(AH);
1728 InitArchiveFmt_Custom(AH);
1732 InitArchiveFmt_Files(AH);
1736 InitArchiveFmt_Null(AH);
1740 InitArchiveFmt_Tar(AH);
1744 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1752 WriteDataChunks(ArchiveHandle *AH)
1754 TocEntry *te = AH->toc->next;
1755 StartDataPtr startPtr;
1758 while (te != AH->toc)
1760 if (te->dataDumper != NULL)
1763 /* printf("Writing data for %d (%x)\n", te->id, te); */
1765 if (strcmp(te->desc, "BLOBS") == 0)
1767 startPtr = AH->StartBlobsPtr;
1768 endPtr = AH->EndBlobsPtr;
1772 startPtr = AH->StartDataPtr;
1773 endPtr = AH->EndDataPtr;
1776 if (startPtr != NULL)
1777 (*startPtr) (AH, te);
1780 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1784 * The user-provided DataDumper routine needs to call
1787 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1798 WriteToc(ArchiveHandle *AH)
1804 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1806 WriteInt(AH, AH->tocCount);
1808 for (te = AH->toc->next; te != AH->toc; te = te->next)
1810 WriteInt(AH, te->dumpId);
1811 WriteInt(AH, te->dataDumper ? 1 : 0);
1813 /* OID is recorded as a string for historical reasons */
1814 sprintf(workbuf, "%u", te->catalogId.tableoid);
1815 WriteStr(AH, workbuf);
1816 sprintf(workbuf, "%u", te->catalogId.oid);
1817 WriteStr(AH, workbuf);
1819 WriteStr(AH, te->tag);
1820 WriteStr(AH, te->desc);
1821 WriteStr(AH, te->defn);
1822 WriteStr(AH, te->dropStmt);
1823 WriteStr(AH, te->copyStmt);
1824 WriteStr(AH, te->namespace);
1825 WriteStr(AH, te->tablespace);
1826 WriteStr(AH, te->owner);
1827 WriteStr(AH, te->withOids ? "true" : "false");
1829 /* Dump list of dependencies */
1830 for (i = 0; i < te->nDeps; i++)
1832 sprintf(workbuf, "%d", te->dependencies[i]);
1833 WriteStr(AH, workbuf);
1835 WriteStr(AH, NULL); /* Terminate List */
1837 if (AH->WriteExtraTocPtr)
1838 (*AH->WriteExtraTocPtr) (AH, te);
1843 ReadToc(ArchiveHandle *AH)
1851 TocEntry *te = AH->toc->next;
1853 AH->tocCount = ReadInt(AH);
1856 for (i = 0; i < AH->tocCount; i++)
1858 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1859 te->dumpId = ReadInt(AH);
1861 if (te->dumpId > AH->maxDumpId)
1862 AH->maxDumpId = te->dumpId;
1865 if (te->dumpId <= 0)
1866 die_horribly(AH, modulename,
1867 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1870 te->hadDumper = ReadInt(AH);
1872 if (AH->version >= K_VERS_1_8)
1875 sscanf(tmp, "%u", &te->catalogId.tableoid);
1879 te->catalogId.tableoid = InvalidOid;
1881 sscanf(tmp, "%u", &te->catalogId.oid);
1884 te->tag = ReadStr(AH);
1885 te->desc = ReadStr(AH);
1886 te->defn = ReadStr(AH);
1887 te->dropStmt = ReadStr(AH);
1889 if (AH->version >= K_VERS_1_3)
1890 te->copyStmt = ReadStr(AH);
1892 if (AH->version >= K_VERS_1_6)
1893 te->namespace = ReadStr(AH);
1895 if (AH->version >= K_VERS_1_10)
1896 te->tablespace = ReadStr(AH);
1898 te->owner = ReadStr(AH);
1899 if (AH->version >= K_VERS_1_9)
1901 if (strcmp(ReadStr(AH), "true") == 0)
1902 te->withOids = true;
1904 te->withOids = false;
1907 te->withOids = true;
1909 /* Read TOC entry dependencies */
1910 if (AH->version >= K_VERS_1_5)
1913 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1919 break; /* end of list */
1920 if (depIdx >= depSize)
1923 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1925 sscanf(tmp, "%d", &deps[depIdx]);
1930 if (depIdx > 0) /* We have a non-null entry */
1932 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1933 te->dependencies = deps;
1939 te->dependencies = NULL;
1945 te->dependencies = NULL;
1949 if (AH->ReadExtraTocPtr)
1950 (*AH->ReadExtraTocPtr) (AH, te);
1952 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1953 i, te->dumpId, te->desc, te->tag);
1955 /* link completed entry into TOC circular list */
1956 te->prev = AH->toc->prev;
1957 AH->toc->prev->next = te;
1961 /* special processing immediately upon read for some items */
1962 if (strcmp(te->desc, "ENCODING") == 0)
1963 processEncodingEntry(AH, te);
1964 else if (strcmp(te->desc, "STDSTRINGS") == 0)
1965 processStdStringsEntry(AH, te);
1970 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
1972 /* te->defn should have the form SET client_encoding = 'foo'; */
1973 char *defn = strdup(te->defn);
1978 ptr1 = strchr(defn, '\'');
1980 ptr2 = strchr(++ptr1, '\'');
1984 encoding = pg_char_to_encoding(ptr1);
1986 die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
1988 AH->public.encoding = encoding;
1991 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
1998 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
2000 /* te->defn should have the form SET standard_conforming_strings = 'x'; */
2003 ptr1 = strchr(te->defn, '\'');
2004 if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
2005 AH->public.std_strings = true;
2006 else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
2007 AH->public.std_strings = false;
2009 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
2014 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
2016 teReqs res = REQ_ALL;
2018 /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
2019 if (strcmp(te->desc, "ENCODING") == 0 ||
2020 strcmp(te->desc, "STDSTRINGS") == 0)
2023 /* If it's an ACL, maybe ignore it */
2024 if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
2027 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
2030 /* Check options for selective dump/restore */
2031 if (ropt->schemaNames)
2033 /* If no namespace is specified, it means all. */
2036 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2042 if (strcmp(te->desc, "TABLE") == 0 ||
2043 strcmp(te->desc, "TABLE DATA") == 0)
2045 if (!ropt->selTable)
2047 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2050 else if (strcmp(te->desc, "INDEX") == 0)
2052 if (!ropt->selIndex)
2054 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2057 else if (strcmp(te->desc, "FUNCTION") == 0)
2059 if (!ropt->selFunction)
2061 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2064 else if (strcmp(te->desc, "TRIGGER") == 0)
2066 if (!ropt->selTrigger)
2068 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2076 * Check if we had a dataDumper. Indicates if the entry is schema or data
2081 * Special Case: If 'SEQUENCE SET' then it is considered a data entry
2083 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2084 res = res & REQ_DATA;
2086 res = res & ~REQ_DATA;
2090 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2093 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2096 /* Mask it if we only want schema */
2097 if (ropt->schemaOnly)
2098 res = res & REQ_SCHEMA;
2100 /* Mask it we only want data */
2102 res = res & REQ_DATA;
2104 /* Mask it if we don't have a schema contribution */
2105 if (!te->defn || strlen(te->defn) == 0)
2106 res = res & ~REQ_SCHEMA;
2108 /* Finally, if there's a per-ID filter, limit based on that as well */
2109 if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2116 * Issue SET commands for parameters that we want to have set the same way
2117 * at all times during execution of a restore script.
2120 _doSetFixedOutputState(ArchiveHandle *AH)
2122 /* Select the correct character set encoding */
2123 ahprintf(AH, "SET client_encoding = '%s';\n",
2124 pg_encoding_to_char(AH->public.encoding));
2126 /* Select the correct string literal syntax */
2127 ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2128 AH->public.std_strings ? "on" : "off");
2130 /* Make sure function checking is disabled */
2131 ahprintf(AH, "SET check_function_bodies = false;\n");
2133 /* Avoid annoying notices etc */
2134 ahprintf(AH, "SET client_min_messages = warning;\n");
2135 if (!AH->public.std_strings)
2136 ahprintf(AH, "SET escape_string_warning = off;\n");
2142 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2143 * for updating state if appropriate. If user is NULL or an empty string,
2144 * the specification DEFAULT will be used.
2147 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2149 PQExpBuffer cmd = createPQExpBuffer();
2151 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2154 * SQL requires a string literal here. Might as well be correct.
2157 appendStringLiteralAHX(cmd, user, AH);
2159 appendPQExpBuffer(cmd, "DEFAULT");
2160 appendPQExpBuffer(cmd, ";");
2162 if (RestoringToDB(AH))
2166 res = PQexec(AH->connection, cmd->data);
2168 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2169 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2170 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2171 user, PQerrorMessage(AH->connection));
2176 ahprintf(AH, "%s\n\n", cmd->data);
2178 destroyPQExpBuffer(cmd);
2183 * Issue a SET default_with_oids command. Caller is responsible
2184 * for updating state if appropriate.
2187 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2189 PQExpBuffer cmd = createPQExpBuffer();
2191 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2194 if (RestoringToDB(AH))
2198 res = PQexec(AH->connection, cmd->data);
2200 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2201 warn_or_die_horribly(AH, modulename,
2202 "could not set default_with_oids: %s",
2203 PQerrorMessage(AH->connection));
2208 ahprintf(AH, "%s\n\n", cmd->data);
2210 destroyPQExpBuffer(cmd);
2215 * Issue the commands to connect to the specified database.
2217 * If we're currently restoring right into a database, this will
2218 * actually establish a connection. Otherwise it puts a \connect into
2219 * the script output.
2221 * NULL dbname implies reconnecting to the current DB (pretty useless).
2224 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2226 if (RestoringToDB(AH))
2227 ReconnectToServer(AH, dbname, NULL);
2230 PQExpBuffer qry = createPQExpBuffer();
2232 appendPQExpBuffer(qry, "\\connect %s\n\n",
2233 dbname ? fmtId(dbname) : "-");
2234 ahprintf(AH, "%s", qry->data);
2235 destroyPQExpBuffer(qry);
2239 * NOTE: currUser keeps track of what the imaginary session user in our
2240 * script is. It's now effectively reset to the original userID.
2245 AH->currUser = strdup("");
2247 /* don't assume we still know the output schema */
2249 free(AH->currSchema);
2250 AH->currSchema = strdup("");
2251 AH->currWithOids = -1;
2253 /* re-establish fixed state */
2254 _doSetFixedOutputState(AH);
2258 * Become the specified user, and update state to avoid redundant commands
2260 * NULL or empty argument is taken to mean restoring the session default
2263 _becomeUser(ArchiveHandle *AH, const char *user)
2266 user = ""; /* avoid null pointers */
2268 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2269 return; /* no need to do anything */
2271 _doSetSessionAuth(AH, user);
2274 * NOTE: currUser keeps track of what the imaginary session user in our
2280 AH->currUser = strdup(user);
2284 * Become the owner of the the given TOC entry object. If
2285 * changes in ownership are not allowed, this doesn't do anything.
2288 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2290 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2293 _becomeUser(AH, te->owner);
2298 * Set the proper default_with_oids value for the table.
2301 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2303 if (AH->currWithOids != te->withOids)
2305 _doSetWithOids(AH, te->withOids);
2306 AH->currWithOids = te->withOids;
2312 * Issue the commands to select the specified schema as the current schema
2313 * in the target database.
2316 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2320 if (!schemaName || *schemaName == '\0' ||
2321 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2322 return; /* no need to do anything */
2324 qry = createPQExpBuffer();
2326 appendPQExpBuffer(qry, "SET search_path = %s",
2328 if (strcmp(schemaName, "pg_catalog") != 0)
2329 appendPQExpBuffer(qry, ", pg_catalog");
2331 if (RestoringToDB(AH))
2335 res = PQexec(AH->connection, qry->data);
2337 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2338 warn_or_die_horribly(AH, modulename,
2339 "could not set search_path to \"%s\": %s",
2340 schemaName, PQerrorMessage(AH->connection));
2345 ahprintf(AH, "%s;\n\n", qry->data);
2348 free(AH->currSchema);
2349 AH->currSchema = strdup(schemaName);
2351 destroyPQExpBuffer(qry);
2355 * Issue the commands to select the specified tablespace as the current one
2356 * in the target database.
2359 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2365 have = AH->currTablespace;
2368 /* no need to do anything for non-tablespace object */
2372 if (have && strcmp(want, have) == 0)
2373 return; /* no need to do anything */
2375 qry = createPQExpBuffer();
2377 if (strcmp(want, "") == 0)
2379 /* We want the tablespace to be the database's default */
2380 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2384 /* We want an explicit tablespace */
2385 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2388 if (RestoringToDB(AH))
2392 res = PQexec(AH->connection, qry->data);
2394 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2395 warn_or_die_horribly(AH, modulename,
2396 "could not set default_tablespace to %s: %s",
2397 fmtId(want), PQerrorMessage(AH->connection));
2402 ahprintf(AH, "%s;\n\n", qry->data);
2404 if (AH->currTablespace)
2405 free(AH->currTablespace);
2406 AH->currTablespace = strdup(want);
2408 destroyPQExpBuffer(qry);
2412 * Extract an object description for a TOC entry, and append it to buf.
2414 * This is not quite as general as it may seem, since it really only
2415 * handles constructing the right thing to put into ALTER ... OWNER TO.
2417 * The whole thing is pretty grotty, but we are kind of stuck since the
2418 * information used is all that's available in older dump files.
2421 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2423 const char *type = te->desc;
2425 /* Use ALTER TABLE for views and sequences */
2426 if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2429 /* objects named by a schema and name */
2430 if (strcmp(type, "CONVERSION") == 0 ||
2431 strcmp(type, "DOMAIN") == 0 ||
2432 strcmp(type, "TABLE") == 0 ||
2433 strcmp(type, "TYPE") == 0 ||
2434 strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
2435 strcmp(type, "TEXT SEARCH CONFIGURATION") == 0)
2437 appendPQExpBuffer(buf, "%s ", type);
2438 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2439 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2442 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2443 * into te->tag for an index. This check is heuristic, so make its
2444 * scope as narrow as possible.
2446 if (AH->version < K_VERS_1_7 &&
2447 te->tag[0] == '"' &&
2448 te->tag[strlen(te->tag) - 1] == '"' &&
2449 strcmp(type, "INDEX") == 0)
2450 appendPQExpBuffer(buf, "%s", te->tag);
2452 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2456 /* objects named by just a name */
2457 if (strcmp(type, "DATABASE") == 0 ||
2458 strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
2459 strcmp(type, "SCHEMA") == 0)
2461 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2466 * These object types require additional decoration. Fortunately, the
2467 * information needed is exactly what's in the DROP command.
2469 if (strcmp(type, "AGGREGATE") == 0 ||
2470 strcmp(type, "FUNCTION") == 0 ||
2471 strcmp(type, "OPERATOR") == 0 ||
2472 strcmp(type, "OPERATOR CLASS") == 0 ||
2473 strcmp(type, "OPERATOR FAMILY") == 0)
2475 /* Chop "DROP " off the front and make a modifiable copy */
2476 char *first = strdup(te->dropStmt + 5);
2479 /* point to last character in string */
2480 last = first + strlen(first) - 1;
2482 /* Strip off any ';' or '\n' at the end */
2483 while (last >= first && (*last == '\n' || *last == ';'))
2487 appendPQExpBufferStr(buf, first);
2493 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2498 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2500 /* ACLs are dumped only during acl pass */
2503 if (strcmp(te->desc, "ACL") != 0)
2508 if (strcmp(te->desc, "ACL") == 0)
2513 * Avoid dumping the public schema, as it will already be created ...
2514 * unless we are using --clean mode, in which case it's been deleted and
2515 * we'd better recreate it.
2517 if (!ropt->dropSchema &&
2518 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2521 /* Select owner, schema, and tablespace as necessary */
2522 _becomeOwner(AH, te);
2523 _selectOutputSchema(AH, te->namespace);
2524 _selectTablespace(AH, te->tablespace);
2526 /* Set up OID mode too */
2527 if (strcmp(te->desc, "TABLE") == 0)
2528 _setWithOids(AH, te);
2530 /* Emit header comment for item */
2531 if (!AH->noTocComments)
2540 ahprintf(AH, "--\n");
2541 if (AH->public.verbose)
2543 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2544 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2549 ahprintf(AH, "-- Dependencies:");
2550 for (i = 0; i < te->nDeps; i++)
2551 ahprintf(AH, " %d", te->dependencies[i]);
2555 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2556 pfx, te->tag, te->desc,
2557 te->namespace ? te->namespace : "-",
2558 ropt->noOwner ? "-" : te->owner);
2560 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2563 if (AH->PrintExtraTocPtr !=NULL)
2564 (*AH->PrintExtraTocPtr) (AH, te);
2565 ahprintf(AH, "--\n\n");
2569 * Actually print the definition.
2571 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2572 * versions put into CREATE SCHEMA. We have to do this when --no-owner
2573 * mode is selected. This is ugly, but I see no other good way ...
2575 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2577 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2581 if (strlen(te->defn) > 0)
2582 ahprintf(AH, "%s\n\n", te->defn);
2586 * If we aren't using SET SESSION AUTH to determine ownership, we must
2587 * instead issue an ALTER OWNER command. We assume that anything without
2588 * a DROP command is not a separately ownable object. All the categories
2589 * with DROP commands must appear in one list or the other.
2591 if (!ropt->noOwner && !ropt->use_setsessauth &&
2592 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2594 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2595 strcmp(te->desc, "CONVERSION") == 0 ||
2596 strcmp(te->desc, "DATABASE") == 0 ||
2597 strcmp(te->desc, "DOMAIN") == 0 ||
2598 strcmp(te->desc, "FUNCTION") == 0 ||
2599 strcmp(te->desc, "OPERATOR") == 0 ||
2600 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2601 strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
2602 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2603 strcmp(te->desc, "SCHEMA") == 0 ||
2604 strcmp(te->desc, "TABLE") == 0 ||
2605 strcmp(te->desc, "TYPE") == 0 ||
2606 strcmp(te->desc, "VIEW") == 0 ||
2607 strcmp(te->desc, "SEQUENCE") == 0 ||
2608 strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
2609 strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0)
2611 PQExpBuffer temp = createPQExpBuffer();
2613 appendPQExpBuffer(temp, "ALTER ");
2614 _getObjectDescription(temp, te, AH);
2615 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2616 ahprintf(AH, "%s\n\n", temp->data);
2617 destroyPQExpBuffer(temp);
2619 else if (strcmp(te->desc, "CAST") == 0 ||
2620 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2621 strcmp(te->desc, "CONSTRAINT") == 0 ||
2622 strcmp(te->desc, "DEFAULT") == 0 ||
2623 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2624 strcmp(te->desc, "INDEX") == 0 ||
2625 strcmp(te->desc, "RULE") == 0 ||
2626 strcmp(te->desc, "TRIGGER") == 0)
2628 /* these object types don't have separate owners */
2632 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2638 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2639 * commands, so we can no longer assume we know the current auth setting.
2641 if (strncmp(te->desc, "ACL", 3) == 0)
2645 AH->currUser = NULL;
2650 WriteHead(ArchiveHandle *AH)
2654 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2655 (*AH->WriteBytePtr) (AH, AH->vmaj);
2656 (*AH->WriteBytePtr) (AH, AH->vmin);
2657 (*AH->WriteBytePtr) (AH, AH->vrev);
2658 (*AH->WriteBytePtr) (AH, AH->intSize);
2659 (*AH->WriteBytePtr) (AH, AH->offSize);
2660 (*AH->WriteBytePtr) (AH, AH->format);
2663 if (AH->compression != 0)
2664 write_msg(modulename, "WARNING: requested compression not available in this "
2665 "installation -- archive will be uncompressed\n");
2667 AH->compression = 0;
2670 WriteInt(AH, AH->compression);
2672 crtm = *localtime(&AH->createDate);
2673 WriteInt(AH, crtm.tm_sec);
2674 WriteInt(AH, crtm.tm_min);
2675 WriteInt(AH, crtm.tm_hour);
2676 WriteInt(AH, crtm.tm_mday);
2677 WriteInt(AH, crtm.tm_mon);
2678 WriteInt(AH, crtm.tm_year);
2679 WriteInt(AH, crtm.tm_isdst);
2680 WriteStr(AH, PQdb(AH->connection));
2681 WriteStr(AH, AH->public.remoteVersionStr);
2682 WriteStr(AH, PG_VERSION);
2686 ReadHead(ArchiveHandle *AH)
2692 /* If we haven't already read the header... */
2693 if (!AH->readHeader)
2695 if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
2696 die_horribly(AH, modulename, "unexpected end of file\n");
2698 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2699 die_horribly(AH, modulename, "did not find magic string in file header\n");
2701 AH->vmaj = (*AH->ReadBytePtr) (AH);
2702 AH->vmin = (*AH->ReadBytePtr) (AH);
2704 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2705 AH->vrev = (*AH->ReadBytePtr) (AH);
2709 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2712 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2713 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2714 AH->vmaj, AH->vmin);
2716 AH->intSize = (*AH->ReadBytePtr) (AH);
2717 if (AH->intSize > 32)
2718 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2719 (unsigned long) AH->intSize);
2721 if (AH->intSize > sizeof(int))
2722 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations might fail\n");
2724 if (AH->version >= K_VERS_1_7)
2725 AH->offSize = (*AH->ReadBytePtr) (AH);
2727 AH->offSize = AH->intSize;
2729 fmt = (*AH->ReadBytePtr) (AH);
2731 if (AH->format != fmt)
2732 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2736 if (AH->version >= K_VERS_1_2)
2738 if (AH->version < K_VERS_1_4)
2739 AH->compression = (*AH->ReadBytePtr) (AH);
2741 AH->compression = ReadInt(AH);
2744 AH->compression = Z_DEFAULT_COMPRESSION;
2747 if (AH->compression != 0)
2748 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2751 if (AH->version >= K_VERS_1_4)
2753 crtm.tm_sec = ReadInt(AH);
2754 crtm.tm_min = ReadInt(AH);
2755 crtm.tm_hour = ReadInt(AH);
2756 crtm.tm_mday = ReadInt(AH);
2757 crtm.tm_mon = ReadInt(AH);
2758 crtm.tm_year = ReadInt(AH);
2759 crtm.tm_isdst = ReadInt(AH);
2761 AH->archdbname = ReadStr(AH);
2763 AH->createDate = mktime(&crtm);
2765 if (AH->createDate == (time_t) -1)
2766 write_msg(modulename, "WARNING: invalid creation date in header\n");
2769 if (AH->version >= K_VERS_1_10)
2771 AH->archiveRemoteVersion = ReadStr(AH);
2772 AH->archiveDumpVersion = ReadStr(AH);
2780 * check to see if fseek can be performed.
2787 if (fseeko(fp, 0, SEEK_CUR) != 0)
2789 else if (sizeof(pgoff_t) > sizeof(long))
2792 * At this point, pgoff_t is too large for long, so we return based on
2793 * whether an pgoff_t version of fseek is available.
2809 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
2814 * We don't print the timezone on Win32, because the names are long and
2815 * localized, which means they may contain characters in various random
2816 * encodings; this has been seen to cause encoding errors when reading the
2819 if (strftime(buf, sizeof(buf),
2821 "%Y-%m-%d %H:%M:%S %Z",
2823 "%Y-%m-%d %H:%M:%S",
2825 localtime(&tim)) != 0)
2826 ahprintf(AH, "-- %s %s\n\n", msg, buf);