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.136 2006/10/04 00:30:05 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);
282 * If we could not create a table, ignore the respective TABLE
283 * DATA if -X no-data-for-failed-tables is given
285 if (ropt->noDataForFailedTables && AH->lastErrorTE == te && strcmp(te->desc, "TABLE") == 0)
290 ahlog(AH, 1, "table %s could not be created, will not restore its data\n", te->tag);
292 for (last = te, tes = te->next; tes != AH->toc; last = tes, tes = tes->next)
294 if (strcmp(tes->desc, "TABLE DATA") == 0 && strcmp(tes->tag, te->tag) == 0 &&
295 strcmp(tes->namespace ? tes->namespace : "", te->namespace ? te->namespace : "") == 0)
297 /* remove this node */
298 last->next = tes->next;
304 /* If we created a DB, connect to it... */
305 if (strcmp(te->desc, "DATABASE") == 0)
307 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
308 _reconnectToDB(AH, te->tag);
313 * If we have a data component, then process it
315 if ((reqs & REQ_DATA) != 0)
318 * hadDumper will be set if there is genuine data component for
319 * this node. Otherwise, we need to check the defn field for
320 * statements that need to be executed in data-only restores.
325 * If we can output the data, then restore it.
327 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
330 if (AH->compression != 0)
331 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
334 _printTocEntry(AH, te, ropt, true, false);
336 if (strcmp(te->desc, "BLOBS") == 0 ||
337 strcmp(te->desc, "BLOB COMMENTS") == 0)
339 ahlog(AH, 1, "restoring %s\n", te->desc);
341 _selectOutputSchema(AH, "pg_catalog");
343 (*AH->PrintTocDataPtr) (AH, te, ropt);
347 _disableTriggersIfNecessary(AH, te, ropt);
349 /* Select owner and schema as necessary */
350 _becomeOwner(AH, te);
351 _selectOutputSchema(AH, te->namespace);
353 ahlog(AH, 1, "restoring data for table \"%s\"\n",
357 * If we have a copy statement, use it. As of V1.3,
358 * these are separate to allow easy import from
359 * withing a database connection. Pre 1.3 archives can
360 * not use DB connections and are sent to output only.
362 * For V1.3+, the table data MUST have a copy
363 * statement so that we can go into appropriate mode
366 if (te->copyStmt && strlen(te->copyStmt) > 0)
368 ahprintf(AH, "%s", te->copyStmt);
369 AH->writingCopyData = true;
372 (*AH->PrintTocDataPtr) (AH, te, ropt);
374 AH->writingCopyData = false;
376 _enableTriggersIfNecessary(AH, te, ropt);
380 else if (!defnDumped)
382 /* If we haven't already dumped the defn part, do so now */
383 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
384 _printTocEntry(AH, te, ropt, false, false);
387 } /* end loop over TOC entries */
390 * Scan TOC again to output ownership commands and ACLs
392 for (te = AH->toc->next; te != AH->toc; te = te->next)
396 /* Work out what, if anything, we want from this entry */
397 reqs = _tocEntryRequired(te, ropt, true);
399 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
401 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
403 _printTocEntry(AH, te, ropt, false, true);
407 if (ropt->single_txn)
410 CommitTransaction(AH);
412 ahprintf(AH, "COMMIT;\n\n");
415 if (AH->public.verbose)
416 dumpTimestamp(AH, "Completed on", time(NULL));
418 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
421 * Clean up & we're done.
423 AH->stage = STAGE_FINALIZING;
425 if (ropt->filename || ropt->compression)
426 ResetOutput(AH, sav);
430 PQfinish(AH->connection);
431 AH->connection = NULL;
436 * Allocate a new RestoreOptions block.
437 * This is mainly so we can initialize it, but also for future expansion,
440 NewRestoreOptions(void)
442 RestoreOptions *opts;
444 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
446 opts->format = archUnknown;
447 opts->suppressDumpWarnings = false;
448 opts->exit_on_error = false;
454 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
456 /* This hack is only needed in a data-only restore */
457 if (!ropt->dataOnly || !ropt->disable_triggers)
460 ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
463 * Become superuser if possible, since they are the only ones who can
464 * disable constraint triggers. If -S was not given, assume the initial
465 * user identity is a superuser. (XXX would it be better to become the
468 _becomeUser(AH, ropt->superuser);
473 _selectOutputSchema(AH, te->namespace);
475 ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
480 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
482 /* This hack is only needed in a data-only restore */
483 if (!ropt->dataOnly || !ropt->disable_triggers)
486 ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
489 * Become superuser if possible, since they are the only ones who can
490 * disable constraint triggers. If -S was not given, assume the initial
491 * user identity is a superuser. (XXX would it be better to become the
494 _becomeUser(AH, ropt->superuser);
499 _selectOutputSchema(AH, te->namespace);
501 ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
506 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
511 WriteData(Archive *AHX, const void *data, size_t dLen)
513 ArchiveHandle *AH = (ArchiveHandle *) AHX;
516 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
518 return (*AH->WriteDataPtr) (AH, data, dLen);
522 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
523 * repository for all metadata. But the name has stuck.
528 ArchiveEntry(Archive *AHX,
529 CatalogId catalogId, DumpId dumpId,
531 const char *namespace,
532 const char *tablespace,
533 const char *owner, bool withOids,
534 const char *desc, const char *defn,
535 const char *dropStmt, const char *copyStmt,
536 const DumpId *deps, int nDeps,
537 DataDumperPtr dumpFn, void *dumpArg)
539 ArchiveHandle *AH = (ArchiveHandle *) AHX;
542 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
544 die_horribly(AH, modulename, "out of memory\n");
547 if (dumpId > AH->maxDumpId)
548 AH->maxDumpId = dumpId;
550 newToc->prev = AH->toc->prev;
551 newToc->next = AH->toc;
552 AH->toc->prev->next = newToc;
553 AH->toc->prev = newToc;
555 newToc->catalogId = catalogId;
556 newToc->dumpId = dumpId;
558 newToc->tag = strdup(tag);
559 newToc->namespace = namespace ? strdup(namespace) : NULL;
560 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
561 newToc->owner = strdup(owner);
562 newToc->withOids = withOids;
563 newToc->desc = strdup(desc);
564 newToc->defn = strdup(defn);
565 newToc->dropStmt = strdup(dropStmt);
566 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
570 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
571 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
572 newToc->nDeps = nDeps;
576 newToc->dependencies = NULL;
580 newToc->dataDumper = dumpFn;
581 newToc->dataDumperArg = dumpArg;
582 newToc->hadDumper = dumpFn ? true : false;
584 newToc->formatData = NULL;
586 if (AH->ArchiveEntryPtr !=NULL)
587 (*AH->ArchiveEntryPtr) (AH, newToc);
592 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
594 ArchiveHandle *AH = (ArchiveHandle *) AHX;
595 TocEntry *te = AH->toc->next;
600 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
602 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
603 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
604 AH->archdbname, AH->tocCount, AH->compression);
621 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
622 ahprintf(AH, "; Format: %s\n", fmtName);
623 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
624 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
625 if (AH->archiveRemoteVersion)
626 ahprintf(AH, "; Dumped from database version: %s\n",
627 AH->archiveRemoteVersion);
628 if (AH->archiveDumpVersion)
629 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
630 AH->archiveDumpVersion);
632 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
634 while (te != AH->toc)
636 if (_tocEntryRequired(te, ropt, true) != 0)
637 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
638 te->catalogId.tableoid, te->catalogId.oid,
639 te->desc, te->namespace ? te->namespace : "-",
645 ResetOutput(AH, sav);
652 /* Called by a dumper to signal start of a BLOB */
654 StartBlob(Archive *AHX, Oid oid)
656 ArchiveHandle *AH = (ArchiveHandle *) AHX;
658 if (!AH->StartBlobPtr)
659 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
661 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
666 /* Called by a dumper to signal end of a BLOB */
668 EndBlob(Archive *AHX, Oid oid)
670 ArchiveHandle *AH = (ArchiveHandle *) AHX;
673 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
683 * Called by a format handler before any blobs are restored
686 StartRestoreBlobs(ArchiveHandle *AH)
688 if (!AH->ropt->single_txn)
691 StartTransaction(AH);
693 ahprintf(AH, "BEGIN;\n\n");
700 * Called by a format handler after all blobs are restored
703 EndRestoreBlobs(ArchiveHandle *AH)
705 if (!AH->ropt->single_txn)
708 CommitTransaction(AH);
710 ahprintf(AH, "COMMIT;\n\n");
713 ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
718 * Called by a format handler to initiate restoration of a blob
721 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
727 /* Initialize the LO Buffer */
730 ahlog(AH, 2, "restoring large object with OID %u\n", oid);
734 loOid = lo_create(AH->connection, oid);
735 if (loOid == 0 || loOid != oid)
736 die_horribly(AH, modulename, "could not create large object %u\n",
739 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
741 die_horribly(AH, modulename, "could not open large object\n");
745 ahprintf(AH, "SELECT lo_open(lo_create(%u), %d);\n", oid, INV_WRITE);
752 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
754 if (AH->lo_buf_used > 0)
756 /* Write remaining bytes from the LO buffer */
764 lo_close(AH->connection, AH->loFd);
769 ahprintf(AH, "SELECT lo_close(0);\n\n");
774 * Sorting and Reordering
778 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
780 ArchiveHandle *AH = (ArchiveHandle *) AHX;
789 /* Allocate space for the 'wanted' array, and init it */
790 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
791 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
792 ropt->limitToList = true;
794 /* Set prev entry as head of list */
798 fh = fopen(ropt->tocFile, PG_BINARY_R);
800 die_horribly(AH, modulename, "could not open TOC file: %s\n",
803 while (fgets(buf, sizeof(buf), fh) != NULL)
805 /* Truncate line at comment, if any */
806 cmnt = strchr(buf, ';');
810 /* Ignore if all blank */
811 if (strspn(buf, " \t\r") == strlen(buf))
814 /* Get an ID, check it's valid and not already seen */
815 id = strtol(buf, &endptr, 10);
816 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
817 ropt->idWanted[id - 1])
819 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
824 te = getTocEntryByDumpId(AH, id);
826 die_horribly(AH, modulename, "could not find entry for ID %d\n",
829 ropt->idWanted[id - 1] = true;
831 _moveAfter(AH, tePrev, te);
836 die_horribly(AH, modulename, "could not close TOC file: %s\n",
840 /**********************
841 * 'Convenience functions that look like standard IO functions
842 * for writing data when in dump mode.
843 **********************/
847 archputs(const char *s, Archive *AH)
849 return WriteData(AH, s, strlen(s));
854 archprintf(Archive *AH, const char *fmt,...)
858 int bSize = strlen(fmt) + 256;
862 * This is paranoid: deal with the possibility that vsnprintf is willing
863 * to ignore trailing null or returns > 0 even if string does not fit. It
864 * may be the case that it returns cnt = bufsize
866 while (cnt < 0 || cnt >= (bSize - 1))
871 p = (char *) malloc(bSize);
873 exit_horribly(AH, modulename, "out of memory\n");
875 cnt = vsnprintf(p, bSize, fmt, ap);
878 WriteData(AH, p, cnt);
884 /*******************************
885 * Stuff below here should be 'private' to the archiver routines
886 *******************************/
889 SetOutput(ArchiveHandle *AH, char *filename, int compression)
894 /* Replace the AH output file handle */
896 sav.gzOut = AH->gzOut;
905 filename = AH->fSpec;
910 /* If compression explicitly requested, use gzopen */
912 if (compression != 0)
916 /* Don't use PG_BINARY_x since this is zlib */
917 sprintf(fmode, "wb%d", compression);
919 AH->OF = gzdopen(dup(fn), fmode);
921 AH->OF = gzopen(filename, fmode);
928 AH->OF = fdopen(dup(fn), PG_BINARY_W);
930 AH->OF = fopen(filename, PG_BINARY_W);
935 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
941 ResetOutput(ArchiveHandle *AH, OutputContext sav)
946 res = GZCLOSE(AH->OF);
948 res = fclose(AH->OF);
951 die_horribly(AH, modulename, "could not close output file: %s\n",
954 AH->gzOut = sav.gzOut;
961 * Print formatted text to the output file (usually stdout).
964 ahprintf(ArchiveHandle *AH, const char *fmt,...)
968 int bSize = strlen(fmt) + 256; /* Should be enough */
972 * This is paranoid: deal with the possibility that vsnprintf is willing
973 * to ignore trailing null
977 * or returns > 0 even if string does not fit. It may be the case that it
978 * returns cnt = bufsize
980 while (cnt < 0 || cnt >= (bSize - 1))
985 p = (char *) malloc(bSize);
987 die_horribly(AH, modulename, "out of memory\n");
989 cnt = vsnprintf(p, bSize, fmt, ap);
992 ahwrite(p, 1, cnt, AH);
998 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1002 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1006 _write_msg(NULL, fmt, ap);
1011 * Single place for logic which says 'We are restoring to a direct DB connection'.
1014 RestoringToDB(ArchiveHandle *AH)
1016 return (AH->ropt && AH->ropt->useDB && AH->connection);
1020 * Dump the current contents of the LO data buffer while writing a BLOB
1023 dump_lo_buf(ArchiveHandle *AH)
1029 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1030 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1031 (unsigned long) AH->lo_buf_used, (unsigned long) res);
1032 if (res != AH->lo_buf_used)
1033 die_horribly(AH, modulename,
1034 "could not write to large object (result: %lu, expected: %lu)\n",
1035 (unsigned long) res, (unsigned long) AH->lo_buf_used);
1042 str = PQescapeBytea((const unsigned char *) AH->lo_buf,
1043 AH->lo_buf_used, &len);
1045 die_horribly(AH, modulename, "out of memory\n");
1047 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1048 AH->writingBlob = 0;
1049 ahprintf(AH, "SELECT lowrite(0, '%s');\n", str);
1050 AH->writingBlob = 1;
1054 AH->lo_buf_used = 0;
1059 * Write buffer to the output file (usually stdout). This is user for
1060 * outputting 'restore' scripts etc. It is even possible for an archive
1061 * format to create a custom output routine to 'fake' a restore if it
1062 * wants to generate a script (see TAR output).
1065 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1069 if (AH->writingBlob)
1071 size_t remaining = size * nmemb;
1073 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1075 size_t avail = AH->lo_buf_size - AH->lo_buf_used;
1077 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1078 ptr = (const void *) ((const char *) ptr + avail);
1080 AH->lo_buf_used += avail;
1084 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1085 AH->lo_buf_used += remaining;
1087 return size * nmemb;
1091 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1092 if (res != (nmemb * size))
1093 die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1096 else if (AH->CustomOutPtr)
1098 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1100 if (res != (nmemb * size))
1101 die_horribly(AH, modulename, "could not write to custom output routine\n");
1107 * If we're doing a restore, and it's direct to DB, and we're
1108 * connected then send it to the DB.
1110 if (RestoringToDB(AH))
1111 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1114 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1116 die_horribly(AH, modulename, "could not write to output file: %s\n",
1123 /* Common exit code */
1125 _write_msg(const char *modulename, const char *fmt, va_list ap)
1128 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1130 fprintf(stderr, "%s: ", progname);
1131 vfprintf(stderr, _(fmt), ap);
1135 write_msg(const char *modulename, const char *fmt,...)
1140 _write_msg(modulename, fmt, ap);
1146 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1148 _write_msg(modulename, fmt, ap);
1152 if (AH->public.verbose)
1153 write_msg(NULL, "*** aborted because of error\n");
1155 PQfinish(AH->connection);
1163 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1168 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1172 /* Archiver use (just different arg declaration) */
1174 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1179 _die_horribly(AH, modulename, fmt, ap);
1183 /* on some error, we may decide to go on... */
1185 warn_or_die_horribly(ArchiveHandle *AH,
1186 const char *modulename, const char *fmt,...)
1194 /* Do nothing special */
1197 case STAGE_INITIALIZING:
1198 if (AH->stage != AH->lastErrorStage)
1199 write_msg(modulename, "Error while INITIALIZING:\n");
1202 case STAGE_PROCESSING:
1203 if (AH->stage != AH->lastErrorStage)
1204 write_msg(modulename, "Error while PROCESSING TOC:\n");
1207 case STAGE_FINALIZING:
1208 if (AH->stage != AH->lastErrorStage)
1209 write_msg(modulename, "Error while FINALIZING:\n");
1212 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1214 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1215 AH->currentTE->dumpId,
1216 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1217 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1219 AH->lastErrorStage = AH->stage;
1220 AH->lastErrorTE = AH->currentTE;
1223 if (AH->public.exit_on_error)
1224 _die_horribly(AH, modulename, fmt, ap);
1227 _write_msg(modulename, fmt, ap);
1228 AH->public.n_errors++;
1234 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1236 te->prev->next = te->next;
1237 te->next->prev = te->prev;
1240 te->next = pos->next;
1242 pos->next->prev = te;
1249 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1251 te->prev->next = te->next;
1252 te->next->prev = te->prev;
1254 te->prev = pos->prev;
1256 pos->prev->next = te;
1262 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1267 while (te != AH->toc)
1269 if (te->dumpId == id)
1277 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1279 TocEntry *te = getTocEntryByDumpId(AH, id);
1284 return _tocEntryRequired(te, ropt, true);
1288 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1293 (*AH->WriteBytePtr) (AH, wasSet);
1295 /* Write out off_t smallest byte first, prevents endian mismatch */
1296 for (off = 0; off < sizeof(off_t); off++)
1298 (*AH->WriteBytePtr) (AH, o & 0xFF);
1301 return sizeof(off_t) + 1;
1305 ReadOffset(ArchiveHandle *AH, off_t *o)
1311 /* Initialize to zero */
1314 /* Check for old version */
1315 if (AH->version < K_VERS_1_7)
1317 /* Prior versions wrote offsets using WriteInt */
1319 /* -1 means not set */
1321 return K_OFFSET_POS_NOT_SET;
1323 return K_OFFSET_NO_DATA;
1325 /* Cast to off_t because it was written as an int. */
1327 return K_OFFSET_POS_SET;
1331 * Read the flag indicating the state of the data pointer. Check if valid
1334 * This used to be handled by a negative or zero pointer, now we use an
1335 * extra byte specifically for the state.
1337 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1341 case K_OFFSET_POS_NOT_SET:
1342 case K_OFFSET_NO_DATA:
1343 case K_OFFSET_POS_SET:
1348 die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1354 for (off = 0; off < AH->offSize; off++)
1356 if (off < sizeof(off_t))
1357 *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1360 if ((*AH->ReadBytePtr) (AH) != 0)
1361 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1369 WriteInt(ArchiveHandle *AH, int i)
1374 * This is a bit yucky, but I don't want to make the binary format very
1375 * dependent on representation, and not knowing much about it, I write out
1376 * a sign byte. If you change this, don't forget to change the file
1377 * version #, and modify readInt to read the new format AS WELL AS the old
1384 (*AH->WriteBytePtr) (AH, 1);
1388 (*AH->WriteBytePtr) (AH, 0);
1390 for (b = 0; b < AH->intSize; b++)
1392 (*AH->WriteBytePtr) (AH, i & 0xFF);
1396 return AH->intSize + 1;
1400 ReadInt(ArchiveHandle *AH)
1405 int sign = 0; /* Default positive */
1408 if (AH->version > K_VERS_1_0)
1409 /* Read a sign byte */
1410 sign = (*AH->ReadBytePtr) (AH);
1412 for (b = 0; b < AH->intSize; b++)
1414 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1416 res = res + (bv << bitShift);
1427 WriteStr(ArchiveHandle *AH, const char *c)
1433 res = WriteInt(AH, strlen(c));
1434 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1437 res = WriteInt(AH, -1);
1443 ReadStr(ArchiveHandle *AH)
1453 buf = (char *) malloc(l + 1);
1455 die_horribly(AH, modulename, "out of memory\n");
1457 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1465 _discoverArchiveFormat(ArchiveHandle *AH)
1468 char sig[6]; /* More than enough */
1473 write_msg(modulename, "attempting to ascertain archive format\n");
1477 free(AH->lookahead);
1479 AH->lookaheadSize = 512;
1480 AH->lookahead = calloc(1, 512);
1481 AH->lookaheadLen = 0;
1482 AH->lookaheadPos = 0;
1487 fh = fopen(AH->fSpec, PG_BINARY_R);
1493 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1495 cnt = fread(sig, 1, 5, fh);
1500 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1502 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1503 (unsigned long) cnt);
1506 /* Save it, just in case we need it later */
1507 strncpy(&AH->lookahead[0], sig, 5);
1508 AH->lookaheadLen = 5;
1510 if (strncmp(sig, "PGDMP", 5) == 0)
1512 AH->vmaj = fgetc(fh);
1513 AH->vmin = fgetc(fh);
1515 /* Save these too... */
1516 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1517 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1519 /* Check header version; varies from V1.0 */
1520 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1522 AH->vrev = fgetc(fh);
1523 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1528 /* Make a convenient integer <maj><min><rev>00 */
1529 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1531 AH->intSize = fgetc(fh);
1532 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1534 if (AH->version >= K_VERS_1_7)
1536 AH->offSize = fgetc(fh);
1537 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1540 AH->offSize = AH->intSize;
1542 AH->format = fgetc(fh);
1543 AH->lookahead[AH->lookaheadLen++] = AH->format;
1548 * *Maybe* we have a tar archive format file... So, read first 512
1551 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1552 AH->lookaheadLen += cnt;
1554 if (AH->lookaheadLen != 512)
1555 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1557 if (!isValidTarHeader(AH->lookahead))
1558 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1560 AH->format = archTar;
1563 /* If we can't seek, then mark the header as read */
1564 if (fseeko(fh, 0, SEEK_SET) != 0)
1567 * NOTE: Formats that use the lookahead buffer can unset this in their
1573 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1576 write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1577 (unsigned long) AH->lookaheadLen);
1580 /* Close the file */
1582 if (fclose(fh) != 0)
1583 die_horribly(AH, modulename, "could not close input file: %s\n",
1591 * Allocate an archive handle
1593 static ArchiveHandle *
1594 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1595 const int compression, ArchiveMode mode)
1600 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1603 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1605 die_horribly(AH, modulename, "out of memory\n");
1607 /* AH->debugLevel = 100; */
1609 AH->vmaj = K_VERS_MAJOR;
1610 AH->vmin = K_VERS_MINOR;
1611 AH->vrev = K_VERS_REV;
1613 /* initialize for backwards compatible string processing */
1614 AH->public.encoding = PG_SQL_ASCII;
1615 AH->public.std_strings = false;
1617 /* sql error handling */
1618 AH->public.exit_on_error = true;
1619 AH->public.n_errors = 0;
1621 AH->createDate = time(NULL);
1623 AH->intSize = sizeof(int);
1624 AH->offSize = sizeof(off_t);
1627 AH->fSpec = strdup(FileSpec);
1630 * Not used; maybe later....
1632 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1633 * i--) if (AH->workDir[i-1] == '/')
1639 AH->currUser = strdup(""); /* So it's valid, but we can free() it later
1641 AH->currSchema = strdup(""); /* ditto */
1642 AH->currWithOids = -1; /* force SET */
1644 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1646 die_horribly(AH, modulename, "out of memory\n");
1648 AH->toc->next = AH->toc;
1649 AH->toc->prev = AH->toc;
1652 AH->compression = compression;
1654 AH->pgCopyBuf = createPQExpBuffer();
1655 AH->sqlBuf = createPQExpBuffer();
1657 /* Open stdout with no compression for AH output handle */
1662 * On Windows, we need to use binary mode to read/write non-text archive
1663 * formats. Force stdin/stdout into binary mode if that is what we are
1667 if (fmt != archNull &&
1668 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1670 if (mode == archModeWrite)
1671 setmode(fileno(stdout), O_BINARY);
1673 setmode(fileno(stdin), O_BINARY);
1678 write_msg(modulename, "archive format is %d\n", fmt);
1681 if (fmt == archUnknown)
1682 AH->format = _discoverArchiveFormat(AH);
1689 InitArchiveFmt_Custom(AH);
1693 InitArchiveFmt_Files(AH);
1697 InitArchiveFmt_Null(AH);
1701 InitArchiveFmt_Tar(AH);
1705 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1713 WriteDataChunks(ArchiveHandle *AH)
1715 TocEntry *te = AH->toc->next;
1716 StartDataPtr startPtr;
1719 while (te != AH->toc)
1721 if (te->dataDumper != NULL)
1724 /* printf("Writing data for %d (%x)\n", te->id, te); */
1726 if (strcmp(te->desc, "BLOBS") == 0)
1728 startPtr = AH->StartBlobsPtr;
1729 endPtr = AH->EndBlobsPtr;
1733 startPtr = AH->StartDataPtr;
1734 endPtr = AH->EndDataPtr;
1737 if (startPtr != NULL)
1738 (*startPtr) (AH, te);
1741 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1745 * The user-provided DataDumper routine needs to call
1748 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1759 WriteToc(ArchiveHandle *AH)
1765 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1767 WriteInt(AH, AH->tocCount);
1769 for (te = AH->toc->next; te != AH->toc; te = te->next)
1771 WriteInt(AH, te->dumpId);
1772 WriteInt(AH, te->dataDumper ? 1 : 0);
1774 /* OID is recorded as a string for historical reasons */
1775 sprintf(workbuf, "%u", te->catalogId.tableoid);
1776 WriteStr(AH, workbuf);
1777 sprintf(workbuf, "%u", te->catalogId.oid);
1778 WriteStr(AH, workbuf);
1780 WriteStr(AH, te->tag);
1781 WriteStr(AH, te->desc);
1782 WriteStr(AH, te->defn);
1783 WriteStr(AH, te->dropStmt);
1784 WriteStr(AH, te->copyStmt);
1785 WriteStr(AH, te->namespace);
1786 WriteStr(AH, te->tablespace);
1787 WriteStr(AH, te->owner);
1788 WriteStr(AH, te->withOids ? "true" : "false");
1790 /* Dump list of dependencies */
1791 for (i = 0; i < te->nDeps; i++)
1793 sprintf(workbuf, "%d", te->dependencies[i]);
1794 WriteStr(AH, workbuf);
1796 WriteStr(AH, NULL); /* Terminate List */
1798 if (AH->WriteExtraTocPtr)
1799 (*AH->WriteExtraTocPtr) (AH, te);
1804 ReadToc(ArchiveHandle *AH)
1812 TocEntry *te = AH->toc->next;
1814 AH->tocCount = ReadInt(AH);
1817 for (i = 0; i < AH->tocCount; i++)
1819 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1820 te->dumpId = ReadInt(AH);
1822 if (te->dumpId > AH->maxDumpId)
1823 AH->maxDumpId = te->dumpId;
1826 if (te->dumpId <= 0)
1827 die_horribly(AH, modulename,
1828 "entry ID %d out of range -- perhaps a corrupt TOC\n",
1831 te->hadDumper = ReadInt(AH);
1833 if (AH->version >= K_VERS_1_8)
1836 sscanf(tmp, "%u", &te->catalogId.tableoid);
1840 te->catalogId.tableoid = InvalidOid;
1842 sscanf(tmp, "%u", &te->catalogId.oid);
1845 te->tag = ReadStr(AH);
1846 te->desc = ReadStr(AH);
1847 te->defn = ReadStr(AH);
1848 te->dropStmt = ReadStr(AH);
1850 if (AH->version >= K_VERS_1_3)
1851 te->copyStmt = ReadStr(AH);
1853 if (AH->version >= K_VERS_1_6)
1854 te->namespace = ReadStr(AH);
1856 if (AH->version >= K_VERS_1_10)
1857 te->tablespace = ReadStr(AH);
1859 te->owner = ReadStr(AH);
1860 if (AH->version >= K_VERS_1_9)
1862 if (strcmp(ReadStr(AH), "true") == 0)
1863 te->withOids = true;
1865 te->withOids = false;
1868 te->withOids = true;
1870 /* Read TOC entry dependencies */
1871 if (AH->version >= K_VERS_1_5)
1874 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1880 break; /* end of list */
1881 if (depIdx >= depSize)
1884 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1886 sscanf(tmp, "%d", &deps[depIdx]);
1891 if (depIdx > 0) /* We have a non-null entry */
1893 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1894 te->dependencies = deps;
1900 te->dependencies = NULL;
1906 te->dependencies = NULL;
1910 if (AH->ReadExtraTocPtr)
1911 (*AH->ReadExtraTocPtr) (AH, te);
1913 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1914 i, te->dumpId, te->desc, te->tag);
1916 /* link completed entry into TOC circular list */
1917 te->prev = AH->toc->prev;
1918 AH->toc->prev->next = te;
1922 /* special processing immediately upon read for some items */
1923 if (strcmp(te->desc, "ENCODING") == 0)
1924 processEncodingEntry(AH, te);
1925 else if (strcmp(te->desc, "STDSTRINGS") == 0)
1926 processStdStringsEntry(AH, te);
1931 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
1933 /* te->defn should have the form SET client_encoding = 'foo'; */
1934 char *defn = strdup(te->defn);
1939 ptr1 = strchr(defn, '\'');
1941 ptr2 = strchr(++ptr1, '\'');
1945 encoding = pg_char_to_encoding(ptr1);
1947 die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
1949 AH->public.encoding = encoding;
1952 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
1959 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
1961 /* te->defn should have the form SET standard_conforming_strings = 'x'; */
1964 ptr1 = strchr(te->defn, '\'');
1965 if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
1966 AH->public.std_strings = true;
1967 else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
1968 AH->public.std_strings = false;
1970 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
1975 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
1977 teReqs res = REQ_ALL;
1979 /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
1980 if (strcmp(te->desc, "ENCODING") == 0 ||
1981 strcmp(te->desc, "STDSTRINGS") == 0)
1984 /* If it's an ACL, maybe ignore it */
1985 if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1988 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1991 /* Check options for selective dump/restore */
1992 if (ropt->schemaNames)
1994 /* If no namespace is specified, it means all. */
1997 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2003 if (strcmp(te->desc, "TABLE") == 0 ||
2004 strcmp(te->desc, "TABLE DATA") == 0)
2006 if (!ropt->selTable)
2008 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2011 else if (strcmp(te->desc, "INDEX") == 0)
2013 if (!ropt->selIndex)
2015 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2018 else if (strcmp(te->desc, "FUNCTION") == 0)
2020 if (!ropt->selFunction)
2022 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2025 else if (strcmp(te->desc, "TRIGGER") == 0)
2027 if (!ropt->selTrigger)
2029 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2037 * Check if we had a dataDumper. Indicates if the entry is schema or data
2042 * Special Case: If 'SEQUENCE SET' then it is considered a data entry
2044 if (strcmp(te->desc, "SEQUENCE SET") == 0)
2045 res = res & REQ_DATA;
2047 res = res & ~REQ_DATA;
2051 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2054 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2057 /* Mask it if we only want schema */
2058 if (ropt->schemaOnly)
2059 res = res & REQ_SCHEMA;
2061 /* Mask it we only want data */
2063 res = res & REQ_DATA;
2065 /* Mask it if we don't have a schema contribution */
2066 if (!te->defn || strlen(te->defn) == 0)
2067 res = res & ~REQ_SCHEMA;
2069 /* Finally, if we used a list, limit based on that as well */
2070 if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
2077 * Issue SET commands for parameters that we want to have set the same way
2078 * at all times during execution of a restore script.
2081 _doSetFixedOutputState(ArchiveHandle *AH)
2083 /* Select the correct character set encoding */
2084 ahprintf(AH, "SET client_encoding = '%s';\n",
2085 pg_encoding_to_char(AH->public.encoding));
2087 /* Select the correct string literal syntax */
2088 ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2089 AH->public.std_strings ? "on" : "off");
2091 /* Make sure function checking is disabled */
2092 ahprintf(AH, "SET check_function_bodies = false;\n");
2094 /* Avoid annoying notices etc */
2095 ahprintf(AH, "SET client_min_messages = warning;\n");
2096 if (!AH->public.std_strings)
2097 ahprintf(AH, "SET escape_string_warning = off;\n");
2103 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2104 * for updating state if appropriate. If user is NULL or an empty string,
2105 * the specification DEFAULT will be used.
2108 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2110 PQExpBuffer cmd = createPQExpBuffer();
2112 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2115 * SQL requires a string literal here. Might as well be correct.
2118 appendStringLiteralAHX(cmd, user, AH);
2120 appendPQExpBuffer(cmd, "DEFAULT");
2121 appendPQExpBuffer(cmd, ";");
2123 if (RestoringToDB(AH))
2127 res = PQexec(AH->connection, cmd->data);
2129 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2130 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2131 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2132 user, PQerrorMessage(AH->connection));
2137 ahprintf(AH, "%s\n\n", cmd->data);
2139 destroyPQExpBuffer(cmd);
2144 * Issue a SET default_with_oids command. Caller is responsible
2145 * for updating state if appropriate.
2148 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2150 PQExpBuffer cmd = createPQExpBuffer();
2152 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2155 if (RestoringToDB(AH))
2159 res = PQexec(AH->connection, cmd->data);
2161 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2162 warn_or_die_horribly(AH, modulename,
2163 "could not set default_with_oids: %s",
2164 PQerrorMessage(AH->connection));
2169 ahprintf(AH, "%s\n\n", cmd->data);
2171 destroyPQExpBuffer(cmd);
2176 * Issue the commands to connect to the specified database.
2178 * If we're currently restoring right into a database, this will
2179 * actually establish a connection. Otherwise it puts a \connect into
2180 * the script output.
2182 * NULL dbname implies reconnecting to the current DB (pretty useless).
2185 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2187 if (RestoringToDB(AH))
2188 ReconnectToServer(AH, dbname, NULL);
2191 PQExpBuffer qry = createPQExpBuffer();
2193 appendPQExpBuffer(qry, "\\connect %s\n\n",
2194 dbname ? fmtId(dbname) : "-");
2195 ahprintf(AH, "%s", qry->data);
2196 destroyPQExpBuffer(qry);
2200 * NOTE: currUser keeps track of what the imaginary session user in our
2201 * script is. It's now effectively reset to the original userID.
2206 AH->currUser = strdup("");
2208 /* don't assume we still know the output schema */
2210 free(AH->currSchema);
2211 AH->currSchema = strdup("");
2212 AH->currWithOids = -1;
2214 /* re-establish fixed state */
2215 _doSetFixedOutputState(AH);
2219 * Become the specified user, and update state to avoid redundant commands
2221 * NULL or empty argument is taken to mean restoring the session default
2224 _becomeUser(ArchiveHandle *AH, const char *user)
2227 user = ""; /* avoid null pointers */
2229 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2230 return; /* no need to do anything */
2232 _doSetSessionAuth(AH, user);
2235 * NOTE: currUser keeps track of what the imaginary session user in our
2241 AH->currUser = strdup(user);
2245 * Become the owner of the the given TOC entry object. If
2246 * changes in ownership are not allowed, this doesn't do anything.
2249 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2251 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2254 _becomeUser(AH, te->owner);
2259 * Set the proper default_with_oids value for the table.
2262 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2264 if (AH->currWithOids != te->withOids)
2266 _doSetWithOids(AH, te->withOids);
2267 AH->currWithOids = te->withOids;
2273 * Issue the commands to select the specified schema as the current schema
2274 * in the target database.
2277 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2281 if (!schemaName || *schemaName == '\0' ||
2282 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2283 return; /* no need to do anything */
2285 qry = createPQExpBuffer();
2287 appendPQExpBuffer(qry, "SET search_path = %s",
2289 if (strcmp(schemaName, "pg_catalog") != 0)
2290 appendPQExpBuffer(qry, ", pg_catalog");
2292 if (RestoringToDB(AH))
2296 res = PQexec(AH->connection, qry->data);
2298 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2299 warn_or_die_horribly(AH, modulename,
2300 "could not set search_path to \"%s\": %s",
2301 schemaName, PQerrorMessage(AH->connection));
2306 ahprintf(AH, "%s;\n\n", qry->data);
2309 free(AH->currSchema);
2310 AH->currSchema = strdup(schemaName);
2312 destroyPQExpBuffer(qry);
2316 * Issue the commands to select the specified tablespace as the current one
2317 * in the target database.
2320 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2326 have = AH->currTablespace;
2329 /* no need to do anything for non-tablespace object */
2333 if (have && strcmp(want, have) == 0)
2334 return; /* no need to do anything */
2336 qry = createPQExpBuffer();
2338 if (strcmp(want, "") == 0)
2340 /* We want the tablespace to be the database's default */
2341 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2345 /* We want an explicit tablespace */
2346 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2349 if (RestoringToDB(AH))
2353 res = PQexec(AH->connection, qry->data);
2355 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2356 warn_or_die_horribly(AH, modulename,
2357 "could not set default_tablespace to %s: %s",
2358 fmtId(want), PQerrorMessage(AH->connection));
2363 ahprintf(AH, "%s;\n\n", qry->data);
2365 if (AH->currTablespace)
2366 free(AH->currTablespace);
2367 AH->currTablespace = strdup(want);
2369 destroyPQExpBuffer(qry);
2373 * Extract an object description for a TOC entry, and append it to buf.
2375 * This is not quite as general as it may seem, since it really only
2376 * handles constructing the right thing to put into ALTER ... OWNER TO.
2378 * The whole thing is pretty grotty, but we are kind of stuck since the
2379 * information used is all that's available in older dump files.
2382 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2384 const char *type = te->desc;
2386 /* Use ALTER TABLE for views and sequences */
2387 if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2390 /* objects named by a schema and name */
2391 if (strcmp(type, "CONVERSION") == 0 ||
2392 strcmp(type, "DOMAIN") == 0 ||
2393 strcmp(type, "TABLE") == 0 ||
2394 strcmp(type, "TYPE") == 0)
2396 appendPQExpBuffer(buf, "%s ", type);
2397 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2398 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2401 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2402 * into te->tag for an index. This check is heuristic, so make its
2403 * scope as narrow as possible.
2405 if (AH->version < K_VERS_1_7 &&
2406 te->tag[0] == '"' &&
2407 te->tag[strlen(te->tag) - 1] == '"' &&
2408 strcmp(type, "INDEX") == 0)
2409 appendPQExpBuffer(buf, "%s", te->tag);
2411 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2415 /* objects named by just a name */
2416 if (strcmp(type, "DATABASE") == 0 ||
2417 strcmp(type, "SCHEMA") == 0)
2419 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2424 * These object types require additional decoration. Fortunately, the
2425 * information needed is exactly what's in the DROP command.
2427 if (strcmp(type, "AGGREGATE") == 0 ||
2428 strcmp(type, "FUNCTION") == 0 ||
2429 strcmp(type, "OPERATOR") == 0 ||
2430 strcmp(type, "OPERATOR CLASS") == 0)
2432 /* Chop "DROP " off the front and make a modifiable copy */
2433 char *first = strdup(te->dropStmt + 5);
2436 /* point to last character in string */
2437 last = first + strlen(first) - 1;
2439 /* Strip off any ';' or '\n' at the end */
2440 while (last >= first && (*last == '\n' || *last == ';'))
2444 appendPQExpBufferStr(buf, first);
2450 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2455 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2457 /* ACLs are dumped only during acl pass */
2460 if (strcmp(te->desc, "ACL") != 0)
2465 if (strcmp(te->desc, "ACL") == 0)
2470 * Avoid dumping the public schema, as it will already be created ...
2471 * unless we are using --clean mode, in which case it's been deleted and
2472 * we'd better recreate it.
2474 if (!ropt->dropSchema &&
2475 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2478 /* Select owner, schema, and tablespace as necessary */
2479 _becomeOwner(AH, te);
2480 _selectOutputSchema(AH, te->namespace);
2481 _selectTablespace(AH, te->tablespace);
2483 /* Set up OID mode too */
2484 if (strcmp(te->desc, "TABLE") == 0)
2485 _setWithOids(AH, te);
2487 /* Emit header comment for item */
2488 if (!AH->noTocComments)
2497 ahprintf(AH, "--\n");
2498 if (AH->public.verbose)
2500 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2501 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2506 ahprintf(AH, "-- Dependencies:");
2507 for (i = 0; i < te->nDeps; i++)
2508 ahprintf(AH, " %d", te->dependencies[i]);
2512 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2513 pfx, te->tag, te->desc,
2514 te->namespace ? te->namespace : "-",
2515 ropt->noOwner ? "-" : te->owner);
2517 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2520 if (AH->PrintExtraTocPtr !=NULL)
2521 (*AH->PrintExtraTocPtr) (AH, te);
2522 ahprintf(AH, "--\n\n");
2526 * Actually print the definition.
2528 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2529 * versions put into CREATE SCHEMA. We have to do this when --no-owner
2530 * mode is selected. This is ugly, but I see no other good way ...
2532 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2534 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2538 if (strlen(te->defn) > 0)
2539 ahprintf(AH, "%s\n\n", te->defn);
2543 * If we aren't using SET SESSION AUTH to determine ownership, we must
2544 * instead issue an ALTER OWNER command. We assume that anything without
2545 * a DROP command is not a separately ownable object. All the categories
2546 * with DROP commands must appear in one list or the other.
2548 if (!ropt->noOwner && !ropt->use_setsessauth &&
2549 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2551 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2552 strcmp(te->desc, "CONVERSION") == 0 ||
2553 strcmp(te->desc, "DATABASE") == 0 ||
2554 strcmp(te->desc, "DOMAIN") == 0 ||
2555 strcmp(te->desc, "FUNCTION") == 0 ||
2556 strcmp(te->desc, "OPERATOR") == 0 ||
2557 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2558 strcmp(te->desc, "SCHEMA") == 0 ||
2559 strcmp(te->desc, "TABLE") == 0 ||
2560 strcmp(te->desc, "TYPE") == 0 ||
2561 strcmp(te->desc, "VIEW") == 0 ||
2562 strcmp(te->desc, "SEQUENCE") == 0)
2564 PQExpBuffer temp = createPQExpBuffer();
2566 appendPQExpBuffer(temp, "ALTER ");
2567 _getObjectDescription(temp, te, AH);
2568 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2569 ahprintf(AH, "%s\n\n", temp->data);
2570 destroyPQExpBuffer(temp);
2572 else if (strcmp(te->desc, "CAST") == 0 ||
2573 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2574 strcmp(te->desc, "CONSTRAINT") == 0 ||
2575 strcmp(te->desc, "DEFAULT") == 0 ||
2576 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2577 strcmp(te->desc, "INDEX") == 0 ||
2578 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2579 strcmp(te->desc, "RULE") == 0 ||
2580 strcmp(te->desc, "TRIGGER") == 0)
2582 /* these object types don't have separate owners */
2586 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2592 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2593 * commands, so we can no longer assume we know the current auth setting.
2595 if (strncmp(te->desc, "ACL", 3) == 0)
2599 AH->currUser = NULL;
2604 WriteHead(ArchiveHandle *AH)
2608 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2609 (*AH->WriteBytePtr) (AH, AH->vmaj);
2610 (*AH->WriteBytePtr) (AH, AH->vmin);
2611 (*AH->WriteBytePtr) (AH, AH->vrev);
2612 (*AH->WriteBytePtr) (AH, AH->intSize);
2613 (*AH->WriteBytePtr) (AH, AH->offSize);
2614 (*AH->WriteBytePtr) (AH, AH->format);
2617 if (AH->compression != 0)
2618 write_msg(modulename, "WARNING: requested compression not available in this "
2619 "installation -- archive will be uncompressed\n");
2621 AH->compression = 0;
2624 WriteInt(AH, AH->compression);
2626 crtm = *localtime(&AH->createDate);
2627 WriteInt(AH, crtm.tm_sec);
2628 WriteInt(AH, crtm.tm_min);
2629 WriteInt(AH, crtm.tm_hour);
2630 WriteInt(AH, crtm.tm_mday);
2631 WriteInt(AH, crtm.tm_mon);
2632 WriteInt(AH, crtm.tm_year);
2633 WriteInt(AH, crtm.tm_isdst);
2634 WriteStr(AH, PQdb(AH->connection));
2635 WriteStr(AH, AH->public.remoteVersionStr);
2636 WriteStr(AH, PG_VERSION);
2640 ReadHead(ArchiveHandle *AH)
2646 /* If we haven't already read the header... */
2647 if (!AH->readHeader)
2650 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2652 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2653 die_horribly(AH, modulename, "did not find magic string in file header\n");
2655 AH->vmaj = (*AH->ReadBytePtr) (AH);
2656 AH->vmin = (*AH->ReadBytePtr) (AH);
2658 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2659 AH->vrev = (*AH->ReadBytePtr) (AH);
2663 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2666 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2667 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2668 AH->vmaj, AH->vmin);
2670 AH->intSize = (*AH->ReadBytePtr) (AH);
2671 if (AH->intSize > 32)
2672 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2673 (unsigned long) AH->intSize);
2675 if (AH->intSize > sizeof(int))
2676 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2678 if (AH->version >= K_VERS_1_7)
2679 AH->offSize = (*AH->ReadBytePtr) (AH);
2681 AH->offSize = AH->intSize;
2683 fmt = (*AH->ReadBytePtr) (AH);
2685 if (AH->format != fmt)
2686 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2690 if (AH->version >= K_VERS_1_2)
2692 if (AH->version < K_VERS_1_4)
2693 AH->compression = (*AH->ReadBytePtr) (AH);
2695 AH->compression = ReadInt(AH);
2698 AH->compression = Z_DEFAULT_COMPRESSION;
2701 if (AH->compression != 0)
2702 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2705 if (AH->version >= K_VERS_1_4)
2707 crtm.tm_sec = ReadInt(AH);
2708 crtm.tm_min = ReadInt(AH);
2709 crtm.tm_hour = ReadInt(AH);
2710 crtm.tm_mday = ReadInt(AH);
2711 crtm.tm_mon = ReadInt(AH);
2712 crtm.tm_year = ReadInt(AH);
2713 crtm.tm_isdst = ReadInt(AH);
2715 AH->archdbname = ReadStr(AH);
2717 AH->createDate = mktime(&crtm);
2719 if (AH->createDate == (time_t) -1)
2720 write_msg(modulename, "WARNING: invalid creation date in header\n");
2723 if (AH->version >= K_VERS_1_10)
2725 AH->archiveRemoteVersion = ReadStr(AH);
2726 AH->archiveDumpVersion = ReadStr(AH);
2734 * check to see if fseek can be performed.
2741 if (fseeko(fp, 0, SEEK_CUR) != 0)
2743 else if (sizeof(off_t) > sizeof(long))
2746 * At this point, off_t is too large for long, so we return based on
2747 * whether an off_t version of fseek is available.
2763 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
2767 if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&tim)) != 0)
2768 ahprintf(AH, "-- %s %s\n\n", msg, buf);