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.135 2006/08/01 18:21:44 momjian Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup_db.h"
24 #include "dumputils.h"
34 #include "libpq/libpq-fs.h"
35 #include "mb/pg_wchar.h"
40 static char *modulename = gettext_noop("archiver");
43 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
44 const int compression, ArchiveMode mode);
45 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
47 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
50 static void _doSetFixedOutputState(ArchiveHandle *AH);
51 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
52 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
53 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
54 static void _becomeUser(ArchiveHandle *AH, const char *user);
55 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
56 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
57 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
58 static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
59 static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
60 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
61 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
62 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
63 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
64 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
65 static int _discoverArchiveFormat(ArchiveHandle *AH);
67 static void dump_lo_buf(ArchiveHandle *AH);
68 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
69 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
71 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
72 static OutputContext SetOutput(ArchiveHandle *AH, char *filename, int compression);
73 static void ResetOutput(ArchiveHandle *AH, OutputContext savedContext);
79 * The objective it to make writing new formats and dumpers as simple
80 * as possible, if necessary at the expense of extra function calls etc.
85 /* Create a new archive */
88 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
89 const int compression)
92 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
94 return (Archive *) AH;
97 /* Open an existing archive */
100 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
102 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
104 return (Archive *) AH;
109 CloseArchive(Archive *AHX)
112 ArchiveHandle *AH = (ArchiveHandle *) AHX;
114 (*AH->ClosePtr) (AH);
116 /* Close the output */
118 res = GZCLOSE(AH->OF);
119 else if (AH->OF != stdout)
120 res = fclose(AH->OF);
123 die_horribly(AH, modulename, "could not close output file: %s\n",
129 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
131 ArchiveHandle *AH = (ArchiveHandle *) AHX;
138 AH->stage = STAGE_INITIALIZING;
141 * Check for nonsensical option combinations.
143 * NB: create+dropSchema is useless because if you're creating the DB,
144 * there's no need to drop individual items in it. Moreover, if we tried
145 * to do that then we'd issue the drops in the database initially
146 * connected to, not the one we will create, which is very bad...
148 if (ropt->create && ropt->dropSchema)
149 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
152 * If we're using a DB connection, then connect it.
156 ahlog(AH, 1, "connecting to database for restore\n");
157 if (AH->version < K_VERS_1_3)
158 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
160 /* XXX Should get this from the archive */
161 AHX->minRemoteVersion = 070100;
162 AHX->maxRemoteVersion = 999999;
164 ConnectDatabase(AHX, ropt->dbname,
165 ropt->pghost, ropt->pgport, ropt->username,
166 ropt->requirePassword, ropt->ignoreVersion);
169 * If we're talking to the DB directly, don't send comments since they
170 * obscure SQL when displaying errors
172 AH->noTocComments = 1;
176 * Work out if we have an implied data-only restore. This can happen if
177 * the dump was data only or if the user has used a toc list to exclude
178 * all of the schema data. All we do is look for schema entries - if none
179 * are found then we set the dataOnly flag.
181 * We could scan for wanted TABLE entries, but that is not the same as
182 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
186 int impliedDataOnly = 1;
188 for (te = AH->toc->next; te != AH->toc; te = te->next)
190 reqs = _tocEntryRequired(te, ropt, true);
191 if ((reqs & REQ_SCHEMA) != 0)
192 { /* It's schema, and it's wanted */
199 ropt->dataOnly = impliedDataOnly;
200 ahlog(AH, 1, "implied data-only restore\n");
205 * Setup the output file if necessary.
207 if (ropt->filename || ropt->compression)
208 sav = SetOutput(AH, ropt->filename, ropt->compression);
210 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
212 if (AH->public.verbose)
213 dumpTimestamp(AH, "Started on", AH->createDate);
215 if (ropt->single_txn)
218 StartTransaction(AH);
220 ahprintf(AH, "BEGIN;\n\n");
224 * Establish important parameter values right away.
226 _doSetFixedOutputState(AH);
228 AH->stage = STAGE_PROCESSING;
231 * Drop the items at the start, in reverse order
233 if (ropt->dropSchema)
235 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
239 reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
240 if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
242 /* We want the schema */
243 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
244 /* Select owner and schema as necessary */
245 _becomeOwner(AH, te);
246 _selectOutputSchema(AH, te->namespace);
248 ahprintf(AH, "%s", te->dropStmt);
254 * Now process each non-ACL TOC entry
256 for (te = AH->toc->next; te != AH->toc; te = te->next)
260 /* Work out what, if anything, we want from this entry */
261 reqs = _tocEntryRequired(te, ropt, false);
263 /* Dump any relevant dump warnings to stderr */
264 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
266 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
267 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
268 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
269 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
274 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
276 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
278 _printTocEntry(AH, te, ropt, false, false);
281 /* If we could not create a table, ignore the respective TABLE DATA if
282 * -X no-data-for-failed-tables is given */
283 if (ropt->noDataForFailedTables && AH->lastErrorTE == te && strcmp (te->desc, "TABLE") == 0) {
284 TocEntry *tes, *last;
286 ahlog (AH, 1, "table %s could not be created, will not restore its data\n", te->tag);
288 for (last = te, tes = te->next; tes != AH->toc; last = tes, tes = tes->next) {
289 if (strcmp (tes->desc, "TABLE DATA") == 0 && strcmp (tes->tag, te->tag) == 0 &&
290 strcmp (tes->namespace ? tes->namespace : "", te->namespace ? te->namespace : "") == 0) {
291 /* remove this node */
292 last->next = tes->next;
298 /* If we created a DB, connect to it... */
299 if (strcmp(te->desc, "DATABASE") == 0)
301 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
302 _reconnectToDB(AH, te->tag);
307 * If we have a data component, then process it
309 if ((reqs & REQ_DATA) != 0)
312 * hadDumper will be set if there is genuine data component for
313 * this node. Otherwise, we need to check the defn field for
314 * statements that need to be executed in data-only restores.
319 * If we can output the data, then restore it.
321 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
324 if (AH->compression != 0)
325 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
328 _printTocEntry(AH, te, ropt, true, false);
330 if (strcmp(te->desc, "BLOBS") == 0 ||
331 strcmp(te->desc, "BLOB COMMENTS") == 0)
333 ahlog(AH, 1, "restoring %s\n", te->desc);
335 _selectOutputSchema(AH, "pg_catalog");
337 (*AH->PrintTocDataPtr) (AH, te, ropt);
341 _disableTriggersIfNecessary(AH, te, ropt);
343 /* Select owner and schema as necessary */
344 _becomeOwner(AH, te);
345 _selectOutputSchema(AH, te->namespace);
347 ahlog(AH, 1, "restoring data for table \"%s\"\n",
351 * If we have a copy statement, use it. As of V1.3,
352 * these are separate to allow easy import from
353 * withing a database connection. Pre 1.3 archives can
354 * not use DB connections and are sent to output only.
356 * For V1.3+, the table data MUST have a copy
357 * statement so that we can go into appropriate mode
360 if (te->copyStmt && strlen(te->copyStmt) > 0)
362 ahprintf(AH, "%s", te->copyStmt);
363 AH->writingCopyData = true;
366 (*AH->PrintTocDataPtr) (AH, te, ropt);
368 AH->writingCopyData = false;
370 _enableTriggersIfNecessary(AH, te, ropt);
374 else if (!defnDumped)
376 /* If we haven't already dumped the defn part, do so now */
377 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
378 _printTocEntry(AH, te, ropt, false, false);
381 } /* end loop over TOC entries */
384 * Scan TOC again to output ownership commands and ACLs
386 for (te = AH->toc->next; te != AH->toc; te = te->next)
390 /* Work out what, if anything, we want from this entry */
391 reqs = _tocEntryRequired(te, ropt, true);
393 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
395 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
397 _printTocEntry(AH, te, ropt, false, true);
401 if (ropt->single_txn)
404 CommitTransaction(AH);
406 ahprintf(AH, "COMMIT;\n\n");
409 if (AH->public.verbose)
410 dumpTimestamp(AH, "Completed on", time(NULL));
412 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
415 * Clean up & we're done.
417 AH->stage = STAGE_FINALIZING;
419 if (ropt->filename || ropt->compression)
420 ResetOutput(AH, sav);
424 PQfinish(AH->connection);
425 AH->connection = NULL;
430 * Allocate a new RestoreOptions block.
431 * This is mainly so we can initialize it, but also for future expansion,
434 NewRestoreOptions(void)
436 RestoreOptions *opts;
438 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
440 opts->format = archUnknown;
441 opts->suppressDumpWarnings = false;
442 opts->exit_on_error = false;
448 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
450 /* This hack is only needed in a data-only restore */
451 if (!ropt->dataOnly || !ropt->disable_triggers)
454 ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
457 * Become superuser if possible, since they are the only ones who can
458 * disable constraint triggers. If -S was not given, assume the initial
459 * user identity is a superuser. (XXX would it be better to become the
462 _becomeUser(AH, ropt->superuser);
467 _selectOutputSchema(AH, te->namespace);
469 ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
474 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
476 /* This hack is only needed in a data-only restore */
477 if (!ropt->dataOnly || !ropt->disable_triggers)
480 ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
483 * Become superuser if possible, since they are the only ones who can
484 * disable constraint triggers. If -S was not given, assume the initial
485 * user identity is a superuser. (XXX would it be better to become the
488 _becomeUser(AH, ropt->superuser);
493 _selectOutputSchema(AH, te->namespace);
495 ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
500 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
505 WriteData(Archive *AHX, const void *data, size_t dLen)
507 ArchiveHandle *AH = (ArchiveHandle *) AHX;
510 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
512 return (*AH->WriteDataPtr) (AH, data, dLen);
516 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
517 * repository for all metadata. But the name has stuck.
522 ArchiveEntry(Archive *AHX,
523 CatalogId catalogId, DumpId dumpId,
525 const char *namespace,
526 const char *tablespace,
527 const char *owner, bool withOids,
528 const char *desc, const char *defn,
529 const char *dropStmt, const char *copyStmt,
530 const DumpId *deps, int nDeps,
531 DataDumperPtr dumpFn, void *dumpArg)
533 ArchiveHandle *AH = (ArchiveHandle *) AHX;
536 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
538 die_horribly(AH, modulename, "out of memory\n");
541 if (dumpId > AH->maxDumpId)
542 AH->maxDumpId = dumpId;
544 newToc->prev = AH->toc->prev;
545 newToc->next = AH->toc;
546 AH->toc->prev->next = newToc;
547 AH->toc->prev = newToc;
549 newToc->catalogId = catalogId;
550 newToc->dumpId = dumpId;
552 newToc->tag = strdup(tag);
553 newToc->namespace = namespace ? strdup(namespace) : NULL;
554 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
555 newToc->owner = strdup(owner);
556 newToc->withOids = withOids;
557 newToc->desc = strdup(desc);
558 newToc->defn = strdup(defn);
559 newToc->dropStmt = strdup(dropStmt);
560 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
564 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
565 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
566 newToc->nDeps = nDeps;
570 newToc->dependencies = NULL;
574 newToc->dataDumper = dumpFn;
575 newToc->dataDumperArg = dumpArg;
576 newToc->hadDumper = dumpFn ? true : false;
578 newToc->formatData = NULL;
580 if (AH->ArchiveEntryPtr !=NULL)
581 (*AH->ArchiveEntryPtr) (AH, newToc);
586 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
588 ArchiveHandle *AH = (ArchiveHandle *) AHX;
589 TocEntry *te = AH->toc->next;
594 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
596 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
597 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
598 AH->archdbname, AH->tocCount, AH->compression);
615 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
616 ahprintf(AH, "; Format: %s\n", fmtName);
617 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
618 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
619 if (AH->archiveRemoteVersion)
620 ahprintf(AH, "; Dumped from database version: %s\n",
621 AH->archiveRemoteVersion);
622 if (AH->archiveDumpVersion)
623 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
624 AH->archiveDumpVersion);
626 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
628 while (te != AH->toc)
630 if (_tocEntryRequired(te, ropt, true) != 0)
631 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
632 te->catalogId.tableoid, te->catalogId.oid,
633 te->desc, te->namespace ? te->namespace : "-",
639 ResetOutput(AH, sav);
646 /* Called by a dumper to signal start of a BLOB */
648 StartBlob(Archive *AHX, Oid oid)
650 ArchiveHandle *AH = (ArchiveHandle *) AHX;
652 if (!AH->StartBlobPtr)
653 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
655 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
660 /* Called by a dumper to signal end of a BLOB */
662 EndBlob(Archive *AHX, Oid oid)
664 ArchiveHandle *AH = (ArchiveHandle *) AHX;
667 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
677 * Called by a format handler before any blobs are restored
680 StartRestoreBlobs(ArchiveHandle *AH)
682 if (!AH->ropt->single_txn)
685 StartTransaction(AH);
687 ahprintf(AH, "BEGIN;\n\n");
694 * Called by a format handler after all blobs are restored
697 EndRestoreBlobs(ArchiveHandle *AH)
699 if (!AH->ropt->single_txn)
702 CommitTransaction(AH);
704 ahprintf(AH, "COMMIT;\n\n");
707 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
712 * Called by a format handler to initiate restoration of a blob
715 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
721 /* Initialize the LO Buffer */
724 ahlog(AH, 2, "restoring large object with OID %u\n", oid);
728 loOid = lo_create(AH->connection, oid);
729 if (loOid == 0 || loOid != oid)
730 die_horribly(AH, modulename, "could not create large object %u\n",
733 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
735 die_horribly(AH, modulename, "could not open large object\n");
739 ahprintf(AH, "SELECT lo_open(lo_create(%u), %d);\n", oid, INV_WRITE);
746 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
748 if (AH->lo_buf_used > 0)
750 /* Write remaining bytes from the LO buffer */
758 lo_close(AH->connection, AH->loFd);
763 ahprintf(AH, "SELECT lo_close(0);\n\n");
768 * Sorting and Reordering
772 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
774 ArchiveHandle *AH = (ArchiveHandle *) AHX;
783 /* Allocate space for the 'wanted' array, and init it */
784 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
785 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
786 ropt->limitToList = true;
788 /* Set prev entry as head of list */
792 fh = fopen(ropt->tocFile, PG_BINARY_R);
794 die_horribly(AH, modulename, "could not open TOC file: %s\n",
797 while (fgets(buf, sizeof(buf), fh) != NULL)
799 /* Truncate line at comment, if any */
800 cmnt = strchr(buf, ';');
804 /* Ignore if all blank */
805 if (strspn(buf, " \t\r") == strlen(buf))
808 /* Get an ID, check it's valid and not already seen */
809 id = strtol(buf, &endptr, 10);
810 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
811 ropt->idWanted[id - 1])
813 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
818 te = getTocEntryByDumpId(AH, id);
820 die_horribly(AH, modulename, "could not find entry for ID %d\n",
823 ropt->idWanted[id - 1] = true;
825 _moveAfter(AH, tePrev, te);
830 die_horribly(AH, modulename, "could not close TOC file: %s\n",
834 /**********************
835 * 'Convenience functions that look like standard IO functions
836 * for writing data when in dump mode.
837 **********************/
841 archputs(const char *s, Archive *AH)
843 return WriteData(AH, s, strlen(s));
848 archprintf(Archive *AH, const char *fmt,...)
852 int bSize = strlen(fmt) + 256;
856 * This is paranoid: deal with the possibility that vsnprintf is willing
857 * to ignore trailing null or returns > 0 even if string does not fit. It
858 * may be the case that it returns cnt = bufsize
860 while (cnt < 0 || cnt >= (bSize - 1))
865 p = (char *) malloc(bSize);
867 exit_horribly(AH, modulename, "out of memory\n");
869 cnt = vsnprintf(p, bSize, fmt, ap);
872 WriteData(AH, p, cnt);
878 /*******************************
879 * Stuff below here should be 'private' to the archiver routines
880 *******************************/
883 SetOutput(ArchiveHandle *AH, char *filename, int compression)
888 /* Replace the AH output file handle */
890 sav.gzOut = AH->gzOut;
899 filename = AH->fSpec;
904 /* If compression explicitly requested, use gzopen */
906 if (compression != 0)
910 /* Don't use PG_BINARY_x since this is zlib */
911 sprintf(fmode, "wb%d", compression);
913 AH->OF = gzdopen(dup(fn), fmode);
915 AH->OF = gzopen(filename, fmode);
922 AH->OF = fdopen(dup(fn), PG_BINARY_W);
924 AH->OF = fopen(filename, PG_BINARY_W);
929 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
935 ResetOutput(ArchiveHandle *AH, OutputContext sav)
940 res = GZCLOSE(AH->OF);
942 res = fclose(AH->OF);
945 die_horribly(AH, modulename, "could not close output file: %s\n",
948 AH->gzOut = sav.gzOut;
955 * Print formatted text to the output file (usually stdout).
958 ahprintf(ArchiveHandle *AH, const char *fmt,...)
962 int bSize = strlen(fmt) + 256; /* Should be enough */
966 * This is paranoid: deal with the possibility that vsnprintf is willing
967 * to ignore trailing null
971 * or returns > 0 even if string does not fit. It may be the case that it
972 * returns cnt = bufsize
974 while (cnt < 0 || cnt >= (bSize - 1))
979 p = (char *) malloc(bSize);
981 die_horribly(AH, modulename, "out of memory\n");
983 cnt = vsnprintf(p, bSize, fmt, ap);
986 ahwrite(p, 1, cnt, AH);
992 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
996 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1000 _write_msg(NULL, fmt, ap);
1005 * Single place for logic which says 'We are restoring to a direct DB connection'.
1008 RestoringToDB(ArchiveHandle *AH)
1010 return (AH->ropt && AH->ropt->useDB && AH->connection);
1014 * Dump the current contents of the LO data buffer while writing a BLOB
1017 dump_lo_buf(ArchiveHandle *AH)
1023 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1024 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1025 (unsigned long) AH->lo_buf_used, (unsigned long) res);
1026 if (res != AH->lo_buf_used)
1027 die_horribly(AH, modulename,
1028 "could not write to large object (result: %lu, expected: %lu)\n",
1029 (unsigned long) res, (unsigned long) AH->lo_buf_used);
1036 str = PQescapeBytea((const unsigned char *) AH->lo_buf,
1037 AH->lo_buf_used, &len);
1039 die_horribly(AH, modulename, "out of memory\n");
1041 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1042 AH->writingBlob = 0;
1043 ahprintf(AH, "SELECT lowrite(0, '%s');\n", str);
1044 AH->writingBlob = 1;
1048 AH->lo_buf_used = 0;
1053 * Write buffer to the output file (usually stdout). This is user for
1054 * outputting 'restore' scripts etc. It is even possible for an archive
1055 * format to create a custom output routine to 'fake' a restore if it
1056 * wants to generate a script (see TAR output).
1059 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1063 if (AH->writingBlob)
1065 size_t remaining = size * nmemb;
1067 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1069 size_t avail = AH->lo_buf_size - AH->lo_buf_used;
1071 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1072 ptr = (const void *) ((const char *) ptr + avail);
1074 AH->lo_buf_used += avail;
1078 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1079 AH->lo_buf_used += remaining;
1081 return size * nmemb;
1085 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1086 if (res != (nmemb * size))
1087 die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1090 else if (AH->CustomOutPtr)
1092 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1094 if (res != (nmemb * size))
1095 die_horribly(AH, modulename, "could not write to custom output routine\n");
1101 * If we're doing a restore, and it's direct to DB, and we're
1102 * connected then send it to the DB.
1104 if (RestoringToDB(AH))
1105 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1108 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1110 die_horribly(AH, modulename, "could not write to output file: %s\n",
1117 /* Common exit code */
1119 _write_msg(const char *modulename, const char *fmt, va_list ap)
1122 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1124 fprintf(stderr, "%s: ", progname);
1125 vfprintf(stderr, _(fmt), ap);
1129 write_msg(const char *modulename, const char *fmt,...)
1134 _write_msg(modulename, fmt, ap);
1140 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1142 _write_msg(modulename, fmt, ap);
1146 if (AH->public.verbose)
1147 write_msg(NULL, "*** aborted because of error\n");
1149 PQfinish(AH->connection);
1157 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1162 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1166 /* Archiver use (just different arg declaration) */
1168 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1173 _die_horribly(AH, modulename, fmt, ap);
1177 /* on some error, we may decide to go on... */
1179 warn_or_die_horribly(ArchiveHandle *AH,
1180 const char *modulename, const char *fmt,...)
1188 /* Do nothing special */
1191 case STAGE_INITIALIZING:
1192 if (AH->stage != AH->lastErrorStage)
1193 write_msg(modulename, "Error while INITIALIZING:\n");
1196 case STAGE_PROCESSING:
1197 if (AH->stage != AH->lastErrorStage)
1198 write_msg(modulename, "Error while PROCESSING TOC:\n");
1201 case STAGE_FINALIZING:
1202 if (AH->stage != AH->lastErrorStage)
1203 write_msg(modulename, "Error while FINALIZING:\n");
1206 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1208 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1209 AH->currentTE->dumpId,
1210 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1211 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1213 AH->lastErrorStage = AH->stage;
1214 AH->lastErrorTE = AH->currentTE;
1217 if (AH->public.exit_on_error)
1218 _die_horribly(AH, modulename, fmt, ap);
1221 _write_msg(modulename, fmt, ap);
1222 AH->public.n_errors++;
1228 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1230 te->prev->next = te->next;
1231 te->next->prev = te->prev;
1234 te->next = pos->next;
1236 pos->next->prev = te;
1243 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1245 te->prev->next = te->next;
1246 te->next->prev = te->prev;
1248 te->prev = pos->prev;
1250 pos->prev->next = te;
1256 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1261 while (te != AH->toc)
1263 if (te->dumpId == id)
1271 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1273 TocEntry *te = getTocEntryByDumpId(AH, id);
1278 return _tocEntryRequired(te, ropt, true);
1282 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1287 (*AH->WriteBytePtr) (AH, wasSet);
1289 /* Write out off_t smallest byte first, prevents endian mismatch */
1290 for (off = 0; off < sizeof(off_t); off++)
1292 (*AH->WriteBytePtr) (AH, o & 0xFF);
1295 return sizeof(off_t) + 1;
1299 ReadOffset(ArchiveHandle *AH, off_t *o)
1305 /* Initialize to zero */
1308 /* Check for old version */
1309 if (AH->version < K_VERS_1_7)
1311 /* Prior versions wrote offsets using WriteInt */
1313 /* -1 means not set */
1315 return K_OFFSET_POS_NOT_SET;
1317 return K_OFFSET_NO_DATA;
1319 /* Cast to off_t because it was written as an int. */
1321 return K_OFFSET_POS_SET;
1325 * Read the flag indicating the state of the data pointer. Check if valid
1328 * This used to be handled by a negative or zero pointer, now we use an
1329 * extra byte specifically for the state.
1331 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1335 case K_OFFSET_POS_NOT_SET:
1336 case K_OFFSET_NO_DATA:
1337 case K_OFFSET_POS_SET:
1342 die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1348 for (off = 0; off < AH->offSize; off++)
1350 if (off < sizeof(off_t))
1351 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1354 if ((*AH->ReadBytePtr) (AH) != 0)
1355 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1363 WriteInt(ArchiveHandle *AH, int i)
1368 * This is a bit yucky, but I don't want to make the binary format very
1369 * dependent on representation, and not knowing much about it, I write out
1370 * a sign byte. If you change this, don't forget to change the file
1371 * version #, and modify readInt to read the new format AS WELL AS the old
1378 (*AH->WriteBytePtr) (AH, 1);
1382 (*AH->WriteBytePtr) (AH, 0);
1384 for (b = 0; b < AH->intSize; b++)
1386 (*AH->WriteBytePtr) (AH, i & 0xFF);
1390 return AH->intSize + 1;
1394 ReadInt(ArchiveHandle *AH)
1399 int sign = 0; /* Default positive */
1402 if (AH->version > K_VERS_1_0)
1403 /* Read a sign byte */
1404 sign = (*AH->ReadBytePtr) (AH);
1406 for (b = 0; b < AH->intSize; b++)
1408 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1410 res = res + (bv << bitShift);
1421 WriteStr(ArchiveHandle *AH, const char *c)
1427 res = WriteInt(AH, strlen(c));
1428 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1431 res = WriteInt(AH, -1);
1437 ReadStr(ArchiveHandle *AH)
1447 buf = (char *) malloc(l + 1);
1449 die_horribly(AH, modulename, "out of memory\n");
1451 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1459 _discoverArchiveFormat(ArchiveHandle *AH)
1462 char sig[6]; /* More than enough */
1467 write_msg(modulename, "attempting to ascertain archive format\n");
1471 free(AH->lookahead);
1473 AH->lookaheadSize = 512;
1474 AH->lookahead = calloc(1, 512);
1475 AH->lookaheadLen = 0;
1476 AH->lookaheadPos = 0;
1481 fh = fopen(AH->fSpec, PG_BINARY_R);
1487 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1489 cnt = fread(sig, 1, 5, fh);
1494 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1496 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1497 (unsigned long) cnt);
1500 /* Save it, just in case we need it later */
1501 strncpy(&AH->lookahead[0], sig, 5);
1502 AH->lookaheadLen = 5;
1504 if (strncmp(sig, "PGDMP", 5) == 0)
1506 AH->vmaj = fgetc(fh);
1507 AH->vmin = fgetc(fh);
1509 /* Save these too... */
1510 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1511 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1513 /* Check header version; varies from V1.0 */
1514 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1516 AH->vrev = fgetc(fh);
1517 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1522 /* Make a convenient integer <maj><min><rev>00 */
1523 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1525 AH->intSize = fgetc(fh);
1526 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1528 if (AH->version >= K_VERS_1_7)
1530 AH->offSize = fgetc(fh);
1531 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1534 AH->offSize = AH->intSize;
1536 AH->format = fgetc(fh);
1537 AH->lookahead[AH->lookaheadLen++] = AH->format;
1542 * *Maybe* we have a tar archive format file... So, read first 512
1545 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1546 AH->lookaheadLen += cnt;
1548 if (AH->lookaheadLen != 512)
1549 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1551 if (!isValidTarHeader(AH->lookahead))
1552 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1554 AH->format = archTar;
1557 /* If we can't seek, then mark the header as read */
1558 if (fseeko(fh, 0, SEEK_SET) != 0)
1561 * NOTE: Formats that use the lookahead buffer can unset this in their
1567 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1570 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1571 (unsigned long) AH->lookaheadLen);
1574 /* Close the file */
1576 if (fclose(fh) != 0)
1577 die_horribly(AH, modulename, "could not close input file: %s\n",
1585 * Allocate an archive handle
1587 static ArchiveHandle *
1588 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1589 const int compression, ArchiveMode mode)
1594 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1597 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1599 die_horribly(AH, modulename, "out of memory\n");
1601 /* AH->debugLevel = 100; */
1603 AH->vmaj = K_VERS_MAJOR;
1604 AH->vmin = K_VERS_MINOR;
1605 AH->vrev = K_VERS_REV;
1607 /* initialize for backwards compatible string processing */
1608 AH->public.encoding = PG_SQL_ASCII;
1609 AH->public.std_strings = false;
1611 /* sql error handling */
1612 AH->public.exit_on_error = true;
1613 AH->public.n_errors = 0;
1615 AH->createDate = time(NULL);
1617 AH->intSize = sizeof(int);
1618 AH->offSize = sizeof(off_t);
1621 AH->fSpec = strdup(FileSpec);
1624 * Not used; maybe later....
1626 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1627 * i--) if (AH->workDir[i-1] == '/')
1633 AH->currUser = strdup(""); /* So it's valid, but we can free() it later
1635 AH->currSchema = strdup(""); /* ditto */
1636 AH->currWithOids = -1; /* force SET */
1638 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1640 die_horribly(AH, modulename, "out of memory\n");
1642 AH->toc->next = AH->toc;
1643 AH->toc->prev = AH->toc;
1646 AH->compression = compression;
1648 AH->pgCopyBuf = createPQExpBuffer();
1649 AH->sqlBuf = createPQExpBuffer();
1651 /* Open stdout with no compression for AH output handle */
1656 * On Windows, we need to use binary mode to read/write non-text archive
1657 * formats. Force stdin/stdout into binary mode if that is what we are
1661 if (fmt != archNull &&
1662 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1664 if (mode == archModeWrite)
1665 setmode(fileno(stdout), O_BINARY);
1667 setmode(fileno(stdin), O_BINARY);
1672 write_msg(modulename, "archive format is %d\n", fmt);
1675 if (fmt == archUnknown)
1676 AH->format = _discoverArchiveFormat(AH);
1683 InitArchiveFmt_Custom(AH);
1687 InitArchiveFmt_Files(AH);
1691 InitArchiveFmt_Null(AH);
1695 InitArchiveFmt_Tar(AH);
1699 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1707 WriteDataChunks(ArchiveHandle *AH)
1709 TocEntry *te = AH->toc->next;
1710 StartDataPtr startPtr;
1713 while (te != AH->toc)
1715 if (te->dataDumper != NULL)
1718 /* printf("Writing data for %d (%x)\n", te->id, te); */
1720 if (strcmp(te->desc, "BLOBS") == 0)
1722 startPtr = AH->StartBlobsPtr;
1723 endPtr = AH->EndBlobsPtr;
1727 startPtr = AH->StartDataPtr;
1728 endPtr = AH->EndDataPtr;
1731 if (startPtr != NULL)
1732 (*startPtr) (AH, te);
1735 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1739 * The user-provided DataDumper routine needs to call
1742 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1753 WriteToc(ArchiveHandle *AH)
1759 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1761 WriteInt(AH, AH->tocCount);
1763 for (te = AH->toc->next; te != AH->toc; te = te->next)
1765 WriteInt(AH, te->dumpId);
1766 WriteInt(AH, te->dataDumper ? 1 : 0);
1768 /* OID is recorded as a string for historical reasons */
1769 sprintf(workbuf, "%u", te->catalogId.tableoid);
1770 WriteStr(AH, workbuf);
1771 sprintf(workbuf, "%u", te->catalogId.oid);
1772 WriteStr(AH, workbuf);
1774 WriteStr(AH, te->tag);
1775 WriteStr(AH, te->desc);
1776 WriteStr(AH, te->defn);
1777 WriteStr(AH, te->dropStmt);
1778 WriteStr(AH, te->copyStmt);
1779 WriteStr(AH, te->namespace);
1780 WriteStr(AH, te->tablespace);
1781 WriteStr(AH, te->owner);
1782 WriteStr(AH, te->withOids ? "true" : "false");
1784 /* Dump list of dependencies */
1785 for (i = 0; i < te->nDeps; i++)
1787 sprintf(workbuf, "%d", te->dependencies[i]);
1788 WriteStr(AH, workbuf);
1790 WriteStr(AH, NULL); /* Terminate List */
1792 if (AH->WriteExtraTocPtr)
1793 (*AH->WriteExtraTocPtr) (AH, te);
1798 ReadToc(ArchiveHandle *AH)
1806 TocEntry *te = AH->toc->next;
1808 AH->tocCount = ReadInt(AH);
1811 for (i = 0; i < AH->tocCount; i++)
1813 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1814 te->dumpId = ReadInt(AH);
1816 if (te->dumpId > AH->maxDumpId)
1817 AH->maxDumpId = te->dumpId;
1820 if (te->dumpId <= 0)
1821 die_horribly(AH, modulename,
1822 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1825 te->hadDumper = ReadInt(AH);
1827 if (AH->version >= K_VERS_1_8)
1830 sscanf(tmp, "%u", &te->catalogId.tableoid);
1834 te->catalogId.tableoid = InvalidOid;
1836 sscanf(tmp, "%u", &te->catalogId.oid);
1839 te->tag = ReadStr(AH);
1840 te->desc = ReadStr(AH);
1841 te->defn = ReadStr(AH);
1842 te->dropStmt = ReadStr(AH);
1844 if (AH->version >= K_VERS_1_3)
1845 te->copyStmt = ReadStr(AH);
1847 if (AH->version >= K_VERS_1_6)
1848 te->namespace = ReadStr(AH);
1850 if (AH->version >= K_VERS_1_10)
1851 te->tablespace = ReadStr(AH);
1853 te->owner = ReadStr(AH);
1854 if (AH->version >= K_VERS_1_9)
1856 if (strcmp(ReadStr(AH), "true") == 0)
1857 te->withOids = true;
1859 te->withOids = false;
1862 te->withOids = true;
1864 /* Read TOC entry dependencies */
1865 if (AH->version >= K_VERS_1_5)
1868 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1874 break; /* end of list */
1875 if (depIdx >= depSize)
1878 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1880 sscanf(tmp, "%d", &deps[depIdx]);
1885 if (depIdx > 0) /* We have a non-null entry */
1887 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1888 te->dependencies = deps;
1894 te->dependencies = NULL;
1900 te->dependencies = NULL;
1904 if (AH->ReadExtraTocPtr)
1905 (*AH->ReadExtraTocPtr) (AH, te);
1907 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1908 i, te->dumpId, te->desc, te->tag);
1910 /* link completed entry into TOC circular list */
1911 te->prev = AH->toc->prev;
1912 AH->toc->prev->next = te;
1916 /* special processing immediately upon read for some items */
1917 if (strcmp(te->desc, "ENCODING") == 0)
1918 processEncodingEntry(AH, te);
1919 else if (strcmp(te->desc, "STDSTRINGS") == 0)
1920 processStdStringsEntry(AH, te);
1925 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
1927 /* te->defn should have the form SET client_encoding = 'foo'; */
1928 char *defn = strdup(te->defn);
1933 ptr1 = strchr(defn, '\'');
1935 ptr2 = strchr(++ptr1, '\'');
1939 encoding = pg_char_to_encoding(ptr1);
1941 die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
1943 AH->public.encoding = encoding;
1946 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
1953 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
1955 /* te->defn should have the form SET standard_conforming_strings = 'x'; */
1958 ptr1 = strchr(te->defn, '\'');
1959 if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
1960 AH->public.std_strings = true;
1961 else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
1962 AH->public.std_strings = false;
1964 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
1969 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
1971 teReqs res = REQ_ALL;
1973 /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
1974 if (strcmp(te->desc, "ENCODING") == 0 ||
1975 strcmp(te->desc, "STDSTRINGS") == 0)
1978 /* If it's an ACL, maybe ignore it */
1979 if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1982 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1985 /* Check options for selective dump/restore */
1986 if (ropt->schemaNames)
1988 /* If no namespace is specified, it means all. */
1991 if (strcmp(ropt->schemaNames, te->namespace) != 0)
1997 if (strcmp(te->desc, "TABLE") == 0 ||
1998 strcmp(te->desc, "TABLE DATA") == 0)
2000 if (!ropt->selTable)
2002 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2005 else if (strcmp(te->desc, "INDEX") == 0)
2007 if (!ropt->selIndex)
2009 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2012 else if (strcmp(te->desc, "FUNCTION") == 0)
2014 if (!ropt->selFunction)
2016 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2019 else if (strcmp(te->desc, "TRIGGER") == 0)
2021 if (!ropt->selTrigger)
2023 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2031 * Check if we had a dataDumper. Indicates if the entry is schema or data
2036 * Special Case: If 'SEQUENCE SET' then it is considered a data entry
2038 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2039 res = res & REQ_DATA;
2041 res = res & ~REQ_DATA;
2045 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2048 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2051 /* Mask it if we only want schema */
2052 if (ropt->schemaOnly)
2053 res = res & REQ_SCHEMA;
2055 /* Mask it we only want data */
2057 res = res & REQ_DATA;
2059 /* Mask it if we don't have a schema contribution */
2060 if (!te->defn || strlen(te->defn) == 0)
2061 res = res & ~REQ_SCHEMA;
2063 /* Finally, if we used a list, limit based on that as well */
2064 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2071 * Issue SET commands for parameters that we want to have set the same way
2072 * at all times during execution of a restore script.
2075 _doSetFixedOutputState(ArchiveHandle *AH)
2077 /* Select the correct character set encoding */
2078 ahprintf(AH, "SET client_encoding = '%s';\n",
2079 pg_encoding_to_char(AH->public.encoding));
2081 /* Select the correct string literal syntax */
2082 ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2083 AH->public.std_strings ? "on" : "off");
2085 /* Make sure function checking is disabled */
2086 ahprintf(AH, "SET check_function_bodies = false;\n");
2088 /* Avoid annoying notices etc */
2089 ahprintf(AH, "SET client_min_messages = warning;\n");
2090 if (!AH->public.std_strings)
2091 ahprintf(AH, "SET escape_string_warning = off;\n");
2097 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2098 * for updating state if appropriate. If user is NULL or an empty string,
2099 * the specification DEFAULT will be used.
2102 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2104 PQExpBuffer cmd = createPQExpBuffer();
2106 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2109 * SQL requires a string literal here. Might as well be correct.
2112 appendStringLiteralAHX(cmd, user, AH);
2114 appendPQExpBuffer(cmd, "DEFAULT");
2115 appendPQExpBuffer(cmd, ";");
2117 if (RestoringToDB(AH))
2121 res = PQexec(AH->connection, cmd->data);
2123 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2124 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2125 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2126 user, PQerrorMessage(AH->connection));
2131 ahprintf(AH, "%s\n\n", cmd->data);
2133 destroyPQExpBuffer(cmd);
2138 * Issue a SET default_with_oids command. Caller is responsible
2139 * for updating state if appropriate.
2142 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2144 PQExpBuffer cmd = createPQExpBuffer();
2146 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2149 if (RestoringToDB(AH))
2153 res = PQexec(AH->connection, cmd->data);
2155 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2156 warn_or_die_horribly(AH, modulename,
2157 "could not set default_with_oids: %s",
2158 PQerrorMessage(AH->connection));
2163 ahprintf(AH, "%s\n\n", cmd->data);
2165 destroyPQExpBuffer(cmd);
2170 * Issue the commands to connect to the specified database.
2172 * If we're currently restoring right into a database, this will
2173 * actually establish a connection. Otherwise it puts a \connect into
2174 * the script output.
2176 * NULL dbname implies reconnecting to the current DB (pretty useless).
2179 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2181 if (RestoringToDB(AH))
2182 ReconnectToServer(AH, dbname, NULL);
2185 PQExpBuffer qry = createPQExpBuffer();
2187 appendPQExpBuffer(qry, "\\connect %s\n\n",
2188 dbname ? fmtId(dbname) : "-");
2189 ahprintf(AH, "%s", qry->data);
2190 destroyPQExpBuffer(qry);
2194 * NOTE: currUser keeps track of what the imaginary session user in our
2195 * script is. It's now effectively reset to the original userID.
2200 AH->currUser = strdup("");
2202 /* don't assume we still know the output schema */
2204 free(AH->currSchema);
2205 AH->currSchema = strdup("");
2206 AH->currWithOids = -1;
2208 /* re-establish fixed state */
2209 _doSetFixedOutputState(AH);
2213 * Become the specified user, and update state to avoid redundant commands
2215 * NULL or empty argument is taken to mean restoring the session default
2218 _becomeUser(ArchiveHandle *AH, const char *user)
2221 user = ""; /* avoid null pointers */
2223 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2224 return; /* no need to do anything */
2226 _doSetSessionAuth(AH, user);
2229 * NOTE: currUser keeps track of what the imaginary session user in our
2235 AH->currUser = strdup(user);
2239 * Become the owner of the the given TOC entry object. If
2240 * changes in ownership are not allowed, this doesn't do anything.
2243 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2245 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2248 _becomeUser(AH, te->owner);
2253 * Set the proper default_with_oids value for the table.
2256 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2258 if (AH->currWithOids != te->withOids)
2260 _doSetWithOids(AH, te->withOids);
2261 AH->currWithOids = te->withOids;
2267 * Issue the commands to select the specified schema as the current schema
2268 * in the target database.
2271 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2275 if (!schemaName || *schemaName == '\0' ||
2276 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2277 return; /* no need to do anything */
2279 qry = createPQExpBuffer();
2281 appendPQExpBuffer(qry, "SET search_path = %s",
2283 if (strcmp(schemaName, "pg_catalog") != 0)
2284 appendPQExpBuffer(qry, ", pg_catalog");
2286 if (RestoringToDB(AH))
2290 res = PQexec(AH->connection, qry->data);
2292 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2293 warn_or_die_horribly(AH, modulename,
2294 "could not set search_path to \"%s\": %s",
2295 schemaName, PQerrorMessage(AH->connection));
2300 ahprintf(AH, "%s;\n\n", qry->data);
2303 free(AH->currSchema);
2304 AH->currSchema = strdup(schemaName);
2306 destroyPQExpBuffer(qry);
2310 * Issue the commands to select the specified tablespace as the current one
2311 * in the target database.
2314 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
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, ArchiveHandle *AH)
2378 const char *type = te->desc;
2380 /* Use ALTER TABLE for views and sequences */
2381 if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2384 /* objects named by a schema and name */
2385 if (strcmp(type, "CONVERSION") == 0 ||
2386 strcmp(type, "DOMAIN") == 0 ||
2387 strcmp(type, "TABLE") == 0 ||
2388 strcmp(type, "TYPE") == 0)
2390 appendPQExpBuffer(buf, "%s ", type);
2391 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2392 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2395 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2396 * into te->tag for an index. This check is heuristic, so make its
2397 * scope as narrow as possible.
2399 if (AH->version < K_VERS_1_7 &&
2400 te->tag[0] == '"' &&
2401 te->tag[strlen(te->tag) - 1] == '"' &&
2402 strcmp(type, "INDEX") == 0)
2403 appendPQExpBuffer(buf, "%s", te->tag);
2405 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2409 /* objects named by just a name */
2410 if (strcmp(type, "DATABASE") == 0 ||
2411 strcmp(type, "SCHEMA") == 0)
2413 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2418 * These object types require additional decoration. Fortunately, the
2419 * information needed is exactly what's in the DROP command.
2421 if (strcmp(type, "AGGREGATE") == 0 ||
2422 strcmp(type, "FUNCTION") == 0 ||
2423 strcmp(type, "OPERATOR") == 0 ||
2424 strcmp(type, "OPERATOR CLASS") == 0)
2426 /* Chop "DROP " off the front and make a modifiable copy */
2427 char *first = strdup(te->dropStmt + 5);
2430 /* point to last character in string */
2431 last = first + strlen(first) - 1;
2433 /* Strip off any ';' or '\n' at the end */
2434 while (last >= first && (*last == '\n' || *last == ';'))
2438 appendPQExpBufferStr(buf, first);
2444 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2449 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2451 /* ACLs are dumped only during acl pass */
2454 if (strcmp(te->desc, "ACL") != 0)
2459 if (strcmp(te->desc, "ACL") == 0)
2464 * Avoid dumping the public schema, as it will already be created ...
2465 * unless we are using --clean mode, in which case it's been deleted and
2466 * we'd better recreate it.
2468 if (!ropt->dropSchema &&
2469 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2472 /* Select owner, schema, and tablespace as necessary */
2473 _becomeOwner(AH, te);
2474 _selectOutputSchema(AH, te->namespace);
2475 _selectTablespace(AH, te->tablespace);
2477 /* Set up OID mode too */
2478 if (strcmp(te->desc, "TABLE") == 0)
2479 _setWithOids(AH, te);
2481 /* Emit header comment for item */
2482 if (!AH->noTocComments)
2491 ahprintf(AH, "--\n");
2492 if (AH->public.verbose)
2494 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2495 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2500 ahprintf(AH, "-- Dependencies:");
2501 for (i = 0; i < te->nDeps; i++)
2502 ahprintf(AH, " %d", te->dependencies[i]);
2506 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2507 pfx, te->tag, te->desc,
2508 te->namespace ? te->namespace : "-",
2509 ropt->noOwner ? "-" : te->owner);
2511 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2514 if (AH->PrintExtraTocPtr !=NULL)
2515 (*AH->PrintExtraTocPtr) (AH, te);
2516 ahprintf(AH, "--\n\n");
2520 * Actually print the definition.
2522 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2523 * versions put into CREATE SCHEMA. We have to do this when --no-owner
2524 * mode is selected. This is ugly, but I see no other good way ...
2526 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2528 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2532 if (strlen(te->defn) > 0)
2533 ahprintf(AH, "%s\n\n", te->defn);
2537 * If we aren't using SET SESSION AUTH to determine ownership, we must
2538 * instead issue an ALTER OWNER command. We assume that anything without
2539 * a DROP command is not a separately ownable object. All the categories
2540 * with DROP commands must appear in one list or the other.
2542 if (!ropt->noOwner && !ropt->use_setsessauth &&
2543 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2545 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2546 strcmp(te->desc, "CONVERSION") == 0 ||
2547 strcmp(te->desc, "DATABASE") == 0 ||
2548 strcmp(te->desc, "DOMAIN") == 0 ||
2549 strcmp(te->desc, "FUNCTION") == 0 ||
2550 strcmp(te->desc, "OPERATOR") == 0 ||
2551 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2552 strcmp(te->desc, "SCHEMA") == 0 ||
2553 strcmp(te->desc, "TABLE") == 0 ||
2554 strcmp(te->desc, "TYPE") == 0 ||
2555 strcmp(te->desc, "VIEW") == 0 ||
2556 strcmp(te->desc, "SEQUENCE") == 0)
2558 PQExpBuffer temp = createPQExpBuffer();
2560 appendPQExpBuffer(temp, "ALTER ");
2561 _getObjectDescription(temp, te, AH);
2562 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2563 ahprintf(AH, "%s\n\n", temp->data);
2564 destroyPQExpBuffer(temp);
2566 else if (strcmp(te->desc, "CAST") == 0 ||
2567 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2568 strcmp(te->desc, "CONSTRAINT") == 0 ||
2569 strcmp(te->desc, "DEFAULT") == 0 ||
2570 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2571 strcmp(te->desc, "INDEX") == 0 ||
2572 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2573 strcmp(te->desc, "RULE") == 0 ||
2574 strcmp(te->desc, "TRIGGER") == 0)
2576 /* these object types don't have separate owners */
2580 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2586 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2587 * commands, so we can no longer assume we know the current auth setting.
2589 if (strncmp(te->desc, "ACL", 3) == 0)
2593 AH->currUser = NULL;
2598 WriteHead(ArchiveHandle *AH)
2602 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2603 (*AH->WriteBytePtr) (AH, AH->vmaj);
2604 (*AH->WriteBytePtr) (AH, AH->vmin);
2605 (*AH->WriteBytePtr) (AH, AH->vrev);
2606 (*AH->WriteBytePtr) (AH, AH->intSize);
2607 (*AH->WriteBytePtr) (AH, AH->offSize);
2608 (*AH->WriteBytePtr) (AH, AH->format);
2611 if (AH->compression != 0)
2612 write_msg(modulename, "WARNING: requested compression not available in this "
2613 "installation -- archive will be uncompressed\n");
2615 AH->compression = 0;
2618 WriteInt(AH, AH->compression);
2620 crtm = *localtime(&AH->createDate);
2621 WriteInt(AH, crtm.tm_sec);
2622 WriteInt(AH, crtm.tm_min);
2623 WriteInt(AH, crtm.tm_hour);
2624 WriteInt(AH, crtm.tm_mday);
2625 WriteInt(AH, crtm.tm_mon);
2626 WriteInt(AH, crtm.tm_year);
2627 WriteInt(AH, crtm.tm_isdst);
2628 WriteStr(AH, PQdb(AH->connection));
2629 WriteStr(AH, AH->public.remoteVersionStr);
2630 WriteStr(AH, PG_VERSION);
2634 ReadHead(ArchiveHandle *AH)
2640 /* If we haven't already read the header... */
2641 if (!AH->readHeader)
2644 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2646 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2647 die_horribly(AH, modulename, "did not find magic string in file header\n");
2649 AH->vmaj = (*AH->ReadBytePtr) (AH);
2650 AH->vmin = (*AH->ReadBytePtr) (AH);
2652 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2653 AH->vrev = (*AH->ReadBytePtr) (AH);
2657 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2660 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2661 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2662 AH->vmaj, AH->vmin);
2664 AH->intSize = (*AH->ReadBytePtr) (AH);
2665 if (AH->intSize > 32)
2666 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2667 (unsigned long) AH->intSize);
2669 if (AH->intSize > sizeof(int))
2670 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2672 if (AH->version >= K_VERS_1_7)
2673 AH->offSize = (*AH->ReadBytePtr) (AH);
2675 AH->offSize = AH->intSize;
2677 fmt = (*AH->ReadBytePtr) (AH);
2679 if (AH->format != fmt)
2680 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2684 if (AH->version >= K_VERS_1_2)
2686 if (AH->version < K_VERS_1_4)
2687 AH->compression = (*AH->ReadBytePtr) (AH);
2689 AH->compression = ReadInt(AH);
2692 AH->compression = Z_DEFAULT_COMPRESSION;
2695 if (AH->compression != 0)
2696 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2699 if (AH->version >= K_VERS_1_4)
2701 crtm.tm_sec = ReadInt(AH);
2702 crtm.tm_min = ReadInt(AH);
2703 crtm.tm_hour = ReadInt(AH);
2704 crtm.tm_mday = ReadInt(AH);
2705 crtm.tm_mon = ReadInt(AH);
2706 crtm.tm_year = ReadInt(AH);
2707 crtm.tm_isdst = ReadInt(AH);
2709 AH->archdbname = ReadStr(AH);
2711 AH->createDate = mktime(&crtm);
2713 if (AH->createDate == (time_t) -1)
2714 write_msg(modulename, "WARNING: invalid creation date in header\n");
2717 if (AH->version >= K_VERS_1_10)
2719 AH->archiveRemoteVersion = ReadStr(AH);
2720 AH->archiveDumpVersion = ReadStr(AH);
2728 * check to see if fseek can be performed.
2735 if (fseeko(fp, 0, SEEK_CUR) != 0)
2737 else if (sizeof(off_t) > sizeof(long))
2740 * At this point, off_t is too large for long, so we return based on
2741 * whether an off_t version of fseek is available.
2757 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
2761 if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&tim)) != 0)
2762 ahprintf(AH, "-- %s %s\n\n", msg, buf);