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.187 2010/07/06 19:18:59 momjian Exp $
20 *-------------------------------------------------------------------------
23 #include "pg_backup_db.h"
24 #include "dumputils.h"
28 #include <sys/types.h>
35 #include "libpq/libpq-fs.h"
38 * Special exit values from worker children. We reserve 0 for normal
39 * success; 1 and other small values should be interpreted as crashes.
41 #define WORKER_CREATE_DONE 10
42 #define WORKER_INHIBIT_DATA 11
43 #define WORKER_IGNORED_ERRORS 12
46 * Unix uses exit to return result from worker child, so function is void.
47 * Windows thread result comes via function return.
50 #define parallel_restore_result void
52 #define parallel_restore_result DWORD
55 /* IDs for worker children are either PIDs or thread handles */
59 #define thandle HANDLE
62 /* Arguments needed for a worker child */
63 typedef struct _restore_args
69 /* State for each parallel activity slot */
70 typedef struct _parallel_slot
80 static const char *modulename = gettext_noop("archiver");
83 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
84 const int compression, ArchiveMode mode);
85 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
87 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
90 static void _doSetFixedOutputState(ArchiveHandle *AH);
91 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
92 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
93 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
94 static void _becomeUser(ArchiveHandle *AH, const char *user);
95 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
96 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
97 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
98 static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
99 static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
100 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
101 static bool _tocEntryIsACL(TocEntry *te);
102 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
103 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
104 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
105 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
106 static int _discoverArchiveFormat(ArchiveHandle *AH);
108 static void dump_lo_buf(ArchiveHandle *AH);
109 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
110 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
112 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
113 static OutputContext SetOutput(ArchiveHandle *AH, char *filename, int compression);
114 static void ResetOutput(ArchiveHandle *AH, OutputContext savedContext);
116 static int restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
117 RestoreOptions *ropt, bool is_parallel);
118 static void restore_toc_entries_parallel(ArchiveHandle *AH);
119 static thandle spawn_restore(RestoreArgs *args);
120 static thandle reap_child(ParallelSlot *slots, int n_slots, int *work_status);
121 static bool work_in_progress(ParallelSlot *slots, int n_slots);
122 static int get_next_slot(ParallelSlot *slots, int n_slots);
123 static void par_list_header_init(TocEntry *l);
124 static void par_list_append(TocEntry *l, TocEntry *te);
125 static void par_list_remove(TocEntry *te);
126 static TocEntry *get_next_work_item(ArchiveHandle *AH,
127 TocEntry *ready_list,
128 ParallelSlot *slots, int n_slots);
129 static parallel_restore_result parallel_restore(RestoreArgs *args);
130 static void mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
131 thandle worker, int status,
132 ParallelSlot *slots, int n_slots);
133 static void fix_dependencies(ArchiveHandle *AH);
134 static bool has_lock_conflicts(TocEntry *te1, TocEntry *te2);
135 static void repoint_table_dependencies(ArchiveHandle *AH,
136 DumpId tableId, DumpId tableDataId);
137 static void identify_locking_dependencies(TocEntry *te,
138 TocEntry **tocsByDumpId,
140 static void reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
141 TocEntry *ready_list);
142 static void mark_create_done(ArchiveHandle *AH, TocEntry *te);
143 static void inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te);
144 static ArchiveHandle *CloneArchive(ArchiveHandle *AH);
145 static void DeCloneArchive(ArchiveHandle *AH);
151 * The objective it to make writing new formats and dumpers as simple
152 * as possible, if necessary at the expense of extra function calls etc.
157 /* Create a new archive */
160 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
161 const int compression, ArchiveMode mode)
164 ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode);
166 return (Archive *) AH;
169 /* Open an existing archive */
172 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
174 ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
176 return (Archive *) AH;
181 CloseArchive(Archive *AHX)
184 ArchiveHandle *AH = (ArchiveHandle *) AHX;
186 (*AH->ClosePtr) (AH);
188 /* Close the output */
190 res = GZCLOSE(AH->OF);
191 else if (AH->OF != stdout)
192 res = fclose(AH->OF);
195 die_horribly(AH, modulename, "could not close output file: %s\n",
201 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
203 ArchiveHandle *AH = (ArchiveHandle *) AHX;
209 AH->stage = STAGE_INITIALIZING;
212 * Check for nonsensical option combinations.
214 * NB: createDB+dropSchema is useless because if you're creating the DB,
215 * there's no need to drop individual items in it. Moreover, if we tried
216 * to do that then we'd issue the drops in the database initially
217 * connected to, not the one we will create, which is very bad...
219 if (ropt->createDB && ropt->dropSchema)
220 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
223 * -C is not compatible with -1, because we can't create a database inside
224 * a transaction block.
226 if (ropt->createDB && ropt->single_txn)
227 die_horribly(AH, modulename, "-C and -1 are incompatible options\n");
230 * Make sure we won't need (de)compression we haven't got
233 if (AH->compression != 0 && AH->PrintTocDataPtr !=NULL)
235 for (te = AH->toc->next; te != AH->toc; te = te->next)
237 reqs = _tocEntryRequired(te, ropt, false);
238 if (te->hadDumper && (reqs & REQ_DATA) != 0)
239 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
245 * If we're using a DB connection, then connect it.
249 ahlog(AH, 1, "connecting to database for restore\n");
250 if (AH->version < K_VERS_1_3)
251 die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
253 /* XXX Should get this from the archive */
254 AHX->minRemoteVersion = 070100;
255 AHX->maxRemoteVersion = 999999;
257 ConnectDatabase(AHX, ropt->dbname,
258 ropt->pghost, ropt->pgport, ropt->username,
259 ropt->promptPassword);
262 * If we're talking to the DB directly, don't send comments since they
263 * obscure SQL when displaying errors
265 AH->noTocComments = 1;
269 * Work out if we have an implied data-only restore. This can happen if
270 * the dump was data only or if the user has used a toc list to exclude
271 * all of the schema data. All we do is look for schema entries - if none
272 * are found then we set the dataOnly flag.
274 * We could scan for wanted TABLE entries, but that is not the same as
275 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
279 int impliedDataOnly = 1;
281 for (te = AH->toc->next; te != AH->toc; te = te->next)
283 reqs = _tocEntryRequired(te, ropt, true);
284 if ((reqs & REQ_SCHEMA) != 0)
285 { /* It's schema, and it's wanted */
292 ropt->dataOnly = impliedDataOnly;
293 ahlog(AH, 1, "implied data-only restore\n");
298 * Setup the output file if necessary.
300 if (ropt->filename || ropt->compression)
301 sav = SetOutput(AH, ropt->filename, ropt->compression);
303 ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
305 if (AH->public.verbose)
307 if (AH->archiveRemoteVersion)
308 ahprintf(AH, "-- Dumped from database version %s\n",
309 AH->archiveRemoteVersion);
310 if (AH->archiveDumpVersion)
311 ahprintf(AH, "-- Dumped by pg_dump version %s\n",
312 AH->archiveDumpVersion);
313 dumpTimestamp(AH, "Started on", AH->createDate);
316 if (ropt->single_txn)
319 StartTransaction(AH);
321 ahprintf(AH, "BEGIN;\n\n");
325 * Establish important parameter values right away.
327 _doSetFixedOutputState(AH);
329 AH->stage = STAGE_PROCESSING;
332 * Drop the items at the start, in reverse order
334 if (ropt->dropSchema)
336 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
340 reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
341 /* We want anything that's selected and has a dropStmt */
342 if (((reqs & (REQ_SCHEMA | REQ_DATA)) != 0) && te->dropStmt)
344 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
345 /* Select owner and schema as necessary */
346 _becomeOwner(AH, te);
347 _selectOutputSchema(AH, te->namespace);
349 ahprintf(AH, "%s", te->dropStmt);
354 * _selectOutputSchema may have set currSchema to reflect the effect
355 * of a "SET search_path" command it emitted. However, by now we may
356 * have dropped that schema; or it might not have existed in the first
357 * place. In either case the effective value of search_path will not
358 * be what we think. Forcibly reset currSchema so that we will
359 * re-establish the search_path setting when needed (after creating
362 * If we treated users as pg_dump'able objects then we'd need to reset
366 free(AH->currSchema);
367 AH->currSchema = NULL;
371 * In serial mode, we now process each non-ACL TOC entry.
373 * In parallel mode, turn control over to the parallel-restore logic.
375 if (ropt->number_of_jobs > 1 && ropt->useDB)
376 restore_toc_entries_parallel(AH);
379 for (te = AH->toc->next; te != AH->toc; te = te->next)
380 (void) restore_toc_entry(AH, te, ropt, false);
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 /* Both schema and data objects might now have ownership/ACLs */
394 if ((reqs & (REQ_SCHEMA | REQ_DATA)) != 0)
396 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
398 _printTocEntry(AH, te, ropt, false, true);
402 if (ropt->single_txn)
405 CommitTransaction(AH);
407 ahprintf(AH, "COMMIT;\n\n");
410 if (AH->public.verbose)
411 dumpTimestamp(AH, "Completed on", time(NULL));
413 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
416 * Clean up & we're done.
418 AH->stage = STAGE_FINALIZING;
420 if (ropt->filename || ropt->compression)
421 ResetOutput(AH, sav);
425 PQfinish(AH->connection);
426 AH->connection = NULL;
431 * Restore a single TOC item. Used in both parallel and non-parallel restore;
432 * is_parallel is true if we are in a worker child process.
434 * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
435 * the parallel parent has to make the corresponding status update.
438 restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
439 RestoreOptions *ropt, bool is_parallel)
447 /* Work out what, if anything, we want from this entry */
448 reqs = _tocEntryRequired(te, ropt, false);
450 /* Dump any relevant dump warnings to stderr */
451 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
453 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
454 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
455 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
456 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
461 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
463 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
465 _printTocEntry(AH, te, ropt, false, false);
468 if (strcmp(te->desc, "TABLE") == 0)
470 if (AH->lastErrorTE == te)
473 * We failed to create the table. If
474 * --no-data-for-failed-tables was given, mark the
475 * corresponding TABLE DATA to be ignored.
477 * In the parallel case this must be done in the parent, so we
478 * just set the return value.
480 if (ropt->noDataForFailedTables)
483 retval = WORKER_INHIBIT_DATA;
485 inhibit_data_for_failed_table(AH, te);
491 * We created the table successfully. Mark the corresponding
492 * TABLE DATA for possible truncation.
494 * In the parallel case this must be done in the parent, so we
495 * just set the return value.
498 retval = WORKER_CREATE_DONE;
500 mark_create_done(AH, te);
504 /* If we created a DB, connect to it... */
505 if (strcmp(te->desc, "DATABASE") == 0)
507 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
508 _reconnectToDB(AH, te->tag);
509 ropt->dbname = strdup(te->tag);
514 * If we have a data component, then process it
516 if ((reqs & REQ_DATA) != 0)
519 * hadDumper will be set if there is genuine data component for this
520 * node. Otherwise, we need to check the defn field for statements
521 * that need to be executed in data-only restores.
526 * If we can output the data, then restore it.
528 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
530 _printTocEntry(AH, te, ropt, true, false);
532 if (strcmp(te->desc, "BLOBS") == 0 ||
533 strcmp(te->desc, "BLOB COMMENTS") == 0)
535 ahlog(AH, 1, "restoring %s\n", te->desc);
537 _selectOutputSchema(AH, "pg_catalog");
539 (*AH->PrintTocDataPtr) (AH, te, ropt);
543 _disableTriggersIfNecessary(AH, te, ropt);
545 /* Select owner and schema as necessary */
546 _becomeOwner(AH, te);
547 _selectOutputSchema(AH, te->namespace);
549 ahlog(AH, 1, "restoring data for table \"%s\"\n",
553 * In parallel restore, if we created the table earlier in
554 * the run then we wrap the COPY in a transaction and
555 * precede it with a TRUNCATE. If archiving is not on
556 * this prevents WAL-logging the COPY. This obtains a
557 * speedup similar to that from using single_txn mode in
558 * non-parallel restores.
560 if (is_parallel && te->created)
563 * Parallel restore is always talking directly to a
564 * server, so no need to see if we should issue BEGIN.
566 StartTransaction(AH);
569 * If the server version is >= 8.4, make sure we issue
570 * TRUNCATE with ONLY so that child tables are not
573 ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
574 (PQserverVersion(AH->connection) >= 80400 ?
580 * If we have a copy statement, use it. As of V1.3, these
581 * are separate to allow easy import from withing a
582 * database connection. Pre 1.3 archives can not use DB
583 * connections and are sent to output only.
585 * For V1.3+, the table data MUST have a copy statement so
586 * that we can go into appropriate mode with libpq.
588 if (te->copyStmt && strlen(te->copyStmt) > 0)
590 ahprintf(AH, "%s", te->copyStmt);
591 AH->writingCopyData = true;
594 (*AH->PrintTocDataPtr) (AH, te, ropt);
596 AH->writingCopyData = false;
598 /* close out the transaction started above */
599 if (is_parallel && te->created)
600 CommitTransaction(AH);
602 _enableTriggersIfNecessary(AH, te, ropt);
606 else if (!defnDumped)
608 /* If we haven't already dumped the defn part, do so now */
609 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
610 _printTocEntry(AH, te, ropt, false, false);
618 * Allocate a new RestoreOptions block.
619 * This is mainly so we can initialize it, but also for future expansion,
622 NewRestoreOptions(void)
624 RestoreOptions *opts;
626 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
628 /* set any fields that shouldn't default to zeroes */
629 opts->format = archUnknown;
630 opts->promptPassword = TRI_DEFAULT;
636 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
638 /* This hack is only needed in a data-only restore */
639 if (!ropt->dataOnly || !ropt->disable_triggers)
642 ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
645 * Become superuser if possible, since they are the only ones who can
646 * disable constraint triggers. If -S was not given, assume the initial
647 * user identity is a superuser. (XXX would it be better to become the
650 _becomeUser(AH, ropt->superuser);
655 _selectOutputSchema(AH, te->namespace);
657 ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
662 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
664 /* This hack is only needed in a data-only restore */
665 if (!ropt->dataOnly || !ropt->disable_triggers)
668 ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
671 * Become superuser if possible, since they are the only ones who can
672 * disable constraint triggers. If -S was not given, assume the initial
673 * user identity is a superuser. (XXX would it be better to become the
676 _becomeUser(AH, ropt->superuser);
681 _selectOutputSchema(AH, te->namespace);
683 ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
688 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
693 WriteData(Archive *AHX, const void *data, size_t dLen)
695 ArchiveHandle *AH = (ArchiveHandle *) AHX;
698 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
700 return (*AH->WriteDataPtr) (AH, data, dLen);
704 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
705 * repository for all metadata. But the name has stuck.
710 ArchiveEntry(Archive *AHX,
711 CatalogId catalogId, DumpId dumpId,
713 const char *namespace,
714 const char *tablespace,
715 const char *owner, bool withOids,
716 const char *desc, teSection section,
718 const char *dropStmt, const char *copyStmt,
719 const DumpId *deps, int nDeps,
720 DataDumperPtr dumpFn, void *dumpArg)
722 ArchiveHandle *AH = (ArchiveHandle *) AHX;
725 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
727 die_horribly(AH, modulename, "out of memory\n");
730 if (dumpId > AH->maxDumpId)
731 AH->maxDumpId = dumpId;
733 newToc->prev = AH->toc->prev;
734 newToc->next = AH->toc;
735 AH->toc->prev->next = newToc;
736 AH->toc->prev = newToc;
738 newToc->catalogId = catalogId;
739 newToc->dumpId = dumpId;
740 newToc->section = section;
742 newToc->tag = strdup(tag);
743 newToc->namespace = namespace ? strdup(namespace) : NULL;
744 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
745 newToc->owner = strdup(owner);
746 newToc->withOids = withOids;
747 newToc->desc = strdup(desc);
748 newToc->defn = strdup(defn);
749 newToc->dropStmt = strdup(dropStmt);
750 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
754 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
755 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
756 newToc->nDeps = nDeps;
760 newToc->dependencies = NULL;
764 newToc->dataDumper = dumpFn;
765 newToc->dataDumperArg = dumpArg;
766 newToc->hadDumper = dumpFn ? true : false;
768 newToc->formatData = NULL;
770 if (AH->ArchiveEntryPtr !=NULL)
771 (*AH->ArchiveEntryPtr) (AH, newToc);
776 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
778 ArchiveHandle *AH = (ArchiveHandle *) AHX;
784 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
786 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
787 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
788 AH->archdbname, AH->tocCount, AH->compression);
805 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
806 ahprintf(AH, "; Format: %s\n", fmtName);
807 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
808 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
809 if (AH->archiveRemoteVersion)
810 ahprintf(AH, "; Dumped from database version: %s\n",
811 AH->archiveRemoteVersion);
812 if (AH->archiveDumpVersion)
813 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
814 AH->archiveDumpVersion);
816 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
818 /* We should print DATABASE entries whether or not -C was specified */
821 for (te = AH->toc->next; te != AH->toc; te = te->next)
823 if (ropt->verbose || _tocEntryRequired(te, ropt, true) != 0)
824 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
825 te->catalogId.tableoid, te->catalogId.oid,
826 te->desc, te->namespace ? te->namespace : "-",
828 if (ropt->verbose && te->nDeps > 0)
832 ahprintf(AH, ";\tdepends on:");
833 for (i = 0; i < te->nDeps; i++)
834 ahprintf(AH, " %d", te->dependencies[i]);
840 ResetOutput(AH, sav);
847 /* Called by a dumper to signal start of a BLOB */
849 StartBlob(Archive *AHX, Oid oid)
851 ArchiveHandle *AH = (ArchiveHandle *) AHX;
853 if (!AH->StartBlobPtr)
854 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
856 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
861 /* Called by a dumper to signal end of a BLOB */
863 EndBlob(Archive *AHX, Oid oid)
865 ArchiveHandle *AH = (ArchiveHandle *) AHX;
868 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
878 * Called by a format handler before any blobs are restored
881 StartRestoreBlobs(ArchiveHandle *AH)
883 if (!AH->ropt->single_txn)
886 StartTransaction(AH);
888 ahprintf(AH, "BEGIN;\n\n");
895 * Called by a format handler after all blobs are restored
898 EndRestoreBlobs(ArchiveHandle *AH)
900 if (!AH->ropt->single_txn)
903 CommitTransaction(AH);
905 ahprintf(AH, "COMMIT;\n\n");
908 ahlog(AH, 1, ngettext("restored %d large object\n",
909 "restored %d large objects\n",
916 * Called by a format handler to initiate restoration of a blob
919 StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
921 bool old_blob_style = (AH->version < K_VERS_1_12);
926 /* Initialize the LO Buffer */
929 ahlog(AH, 2, "restoring large object with OID %u\n", oid);
931 /* With an old archive we must do drop and create logic here */
932 if (old_blob_style && drop)
933 DropBlobIfExists(AH, oid);
939 loOid = lo_create(AH->connection, oid);
940 if (loOid == 0 || loOid != oid)
941 die_horribly(AH, modulename, "could not create large object %u: %s",
942 oid, PQerrorMessage(AH->connection));
944 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
946 die_horribly(AH, modulename, "could not open large object %u: %s",
947 oid, PQerrorMessage(AH->connection));
952 ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
955 ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
963 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
965 if (AH->lo_buf_used > 0)
967 /* Write remaining bytes from the LO buffer */
975 lo_close(AH->connection, AH->loFd);
980 ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
985 * Sorting and Reordering
989 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
991 ArchiveHandle *AH = (ArchiveHandle *) AHX;
1000 /* Allocate space for the 'wanted' array, and init it */
1001 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
1002 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
1004 /* Set prev entry as head of list */
1007 /* Setup the file */
1008 fh = fopen(ropt->tocFile, PG_BINARY_R);
1010 die_horribly(AH, modulename, "could not open TOC file \"%s\": %s\n",
1011 ropt->tocFile, strerror(errno));
1013 while (fgets(buf, sizeof(buf), fh) != NULL)
1015 /* Truncate line at comment, if any */
1016 cmnt = strchr(buf, ';');
1020 /* Ignore if all blank */
1021 if (strspn(buf, " \t\r") == strlen(buf))
1024 /* Get an ID, check it's valid and not already seen */
1025 id = strtol(buf, &endptr, 10);
1026 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
1027 ropt->idWanted[id - 1])
1029 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
1033 /* Find TOC entry */
1034 te = getTocEntryByDumpId(AH, id);
1036 die_horribly(AH, modulename, "could not find entry for ID %d\n",
1039 ropt->idWanted[id - 1] = true;
1041 _moveAfter(AH, tePrev, te);
1045 if (fclose(fh) != 0)
1046 die_horribly(AH, modulename, "could not close TOC file: %s\n",
1051 * Set up a dummy ID filter that selects all dump IDs
1054 InitDummyWantedList(Archive *AHX, RestoreOptions *ropt)
1056 ArchiveHandle *AH = (ArchiveHandle *) AHX;
1058 /* Allocate space for the 'wanted' array, and init it to 1's */
1059 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
1060 memset(ropt->idWanted, 1, sizeof(bool) * AH->maxDumpId);
1063 /**********************
1064 * 'Convenience functions that look like standard IO functions
1065 * for writing data when in dump mode.
1066 **********************/
1070 archputs(const char *s, Archive *AH)
1072 return WriteData(AH, s, strlen(s));
1077 archprintf(Archive *AH, const char *fmt,...)
1081 int bSize = strlen(fmt) + 256;
1085 * This is paranoid: deal with the possibility that vsnprintf is willing
1086 * to ignore trailing null or returns > 0 even if string does not fit. It
1087 * may be the case that it returns cnt = bufsize
1089 while (cnt < 0 || cnt >= (bSize - 1))
1094 p = (char *) malloc(bSize);
1096 exit_horribly(AH, modulename, "out of memory\n");
1098 cnt = vsnprintf(p, bSize, fmt, ap);
1101 WriteData(AH, p, cnt);
1107 /*******************************
1108 * Stuff below here should be 'private' to the archiver routines
1109 *******************************/
1111 static OutputContext
1112 SetOutput(ArchiveHandle *AH, char *filename, int compression)
1117 /* Replace the AH output file handle */
1119 sav.gzOut = AH->gzOut;
1124 fn = fileno(AH->FH);
1128 filename = AH->fSpec;
1131 fn = fileno(stdout);
1133 /* If compression explicitly requested, use gzopen */
1135 if (compression != 0)
1139 /* Don't use PG_BINARY_x since this is zlib */
1140 sprintf(fmode, "wb%d", compression);
1142 AH->OF = gzdopen(dup(fn), fmode);
1144 AH->OF = gzopen(filename, fmode);
1150 if (AH->mode == archModeAppend)
1153 AH->OF = fdopen(dup(fn), PG_BINARY_A);
1155 AH->OF = fopen(filename, PG_BINARY_A);
1160 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1162 AH->OF = fopen(filename, PG_BINARY_W);
1170 die_horribly(AH, modulename, "could not open output file \"%s\": %s\n",
1171 filename, strerror(errno));
1173 die_horribly(AH, modulename, "could not open output file: %s\n",
1181 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1186 res = GZCLOSE(AH->OF);
1188 res = fclose(AH->OF);
1191 die_horribly(AH, modulename, "could not close output file: %s\n",
1194 AH->gzOut = sav.gzOut;
1201 * Print formatted text to the output file (usually stdout).
1204 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1208 int bSize = strlen(fmt) + 256; /* Should be enough */
1212 * This is paranoid: deal with the possibility that vsnprintf is willing
1213 * to ignore trailing null
1217 * or returns > 0 even if string does not fit. It may be the case that it
1218 * returns cnt = bufsize
1220 while (cnt < 0 || cnt >= (bSize - 1))
1225 p = (char *) malloc(bSize);
1227 die_horribly(AH, modulename, "out of memory\n");
1229 cnt = vsnprintf(p, bSize, fmt, ap);
1232 ahwrite(p, 1, cnt, AH);
1238 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1242 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1246 _write_msg(NULL, fmt, ap);
1251 * Single place for logic which says 'We are restoring to a direct DB connection'.
1254 RestoringToDB(ArchiveHandle *AH)
1256 return (AH->ropt && AH->ropt->useDB && AH->connection);
1260 * Dump the current contents of the LO data buffer while writing a BLOB
1263 dump_lo_buf(ArchiveHandle *AH)
1269 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1270 ahlog(AH, 5, ngettext("wrote %lu byte of large object data (result = %lu)\n",
1271 "wrote %lu bytes of large object data (result = %lu)\n",
1273 (unsigned long) AH->lo_buf_used, (unsigned long) res);
1274 if (res != AH->lo_buf_used)
1275 die_horribly(AH, modulename,
1276 "could not write to large object (result: %lu, expected: %lu)\n",
1277 (unsigned long) res, (unsigned long) AH->lo_buf_used);
1281 PQExpBuffer buf = createPQExpBuffer();
1283 appendByteaLiteralAHX(buf,
1284 (const unsigned char *) AH->lo_buf,
1288 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1289 AH->writingBlob = 0;
1290 ahprintf(AH, "SELECT pg_catalog.lowrite(0, %s);\n", buf->data);
1291 AH->writingBlob = 1;
1293 destroyPQExpBuffer(buf);
1295 AH->lo_buf_used = 0;
1300 * Write buffer to the output file (usually stdout). This is user for
1301 * outputting 'restore' scripts etc. It is even possible for an archive
1302 * format to create a custom output routine to 'fake' a restore if it
1303 * wants to generate a script (see TAR output).
1306 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1310 if (AH->writingBlob)
1312 size_t remaining = size * nmemb;
1314 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1316 size_t avail = AH->lo_buf_size - AH->lo_buf_used;
1318 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1319 ptr = (const void *) ((const char *) ptr + avail);
1321 AH->lo_buf_used += avail;
1325 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1326 AH->lo_buf_used += remaining;
1328 return size * nmemb;
1332 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1333 if (res != (nmemb * size))
1334 die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1337 else if (AH->CustomOutPtr)
1339 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1341 if (res != (nmemb * size))
1342 die_horribly(AH, modulename, "could not write to custom output routine\n");
1348 * If we're doing a restore, and it's direct to DB, and we're
1349 * connected then send it to the DB.
1351 if (RestoringToDB(AH))
1352 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1355 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1357 die_horribly(AH, modulename, "could not write to output file: %s\n",
1364 /* Common exit code */
1366 _write_msg(const char *modulename, const char *fmt, va_list ap)
1369 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1371 fprintf(stderr, "%s: ", progname);
1372 vfprintf(stderr, _(fmt), ap);
1376 write_msg(const char *modulename, const char *fmt,...)
1381 _write_msg(modulename, fmt, ap);
1387 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1389 _write_msg(modulename, fmt, ap);
1393 if (AH->public.verbose)
1394 write_msg(NULL, "*** aborted because of error\n");
1396 PQfinish(AH->connection);
1404 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1409 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1413 /* Archiver use (just different arg declaration) */
1415 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1420 _die_horribly(AH, modulename, fmt, ap);
1424 /* on some error, we may decide to go on... */
1426 warn_or_die_horribly(ArchiveHandle *AH,
1427 const char *modulename, const char *fmt,...)
1435 /* Do nothing special */
1438 case STAGE_INITIALIZING:
1439 if (AH->stage != AH->lastErrorStage)
1440 write_msg(modulename, "Error while INITIALIZING:\n");
1443 case STAGE_PROCESSING:
1444 if (AH->stage != AH->lastErrorStage)
1445 write_msg(modulename, "Error while PROCESSING TOC:\n");
1448 case STAGE_FINALIZING:
1449 if (AH->stage != AH->lastErrorStage)
1450 write_msg(modulename, "Error while FINALIZING:\n");
1453 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1455 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1456 AH->currentTE->dumpId,
1457 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1458 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1460 AH->lastErrorStage = AH->stage;
1461 AH->lastErrorTE = AH->currentTE;
1464 if (AH->public.exit_on_error)
1465 _die_horribly(AH, modulename, fmt, ap);
1468 _write_msg(modulename, fmt, ap);
1469 AH->public.n_errors++;
1475 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1477 te->prev->next = te->next;
1478 te->next->prev = te->prev;
1481 te->next = pos->next;
1483 pos->next->prev = te;
1490 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1492 te->prev->next = te->next;
1493 te->next->prev = te->prev;
1495 te->prev = pos->prev;
1497 pos->prev->next = te;
1503 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1507 for (te = AH->toc->next; te != AH->toc; te = te->next)
1509 if (te->dumpId == id)
1516 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1518 TocEntry *te = getTocEntryByDumpId(AH, id);
1523 return _tocEntryRequired(te, ropt, true);
1527 WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1532 (*AH->WriteBytePtr) (AH, wasSet);
1534 /* Write out pgoff_t smallest byte first, prevents endian mismatch */
1535 for (off = 0; off < sizeof(pgoff_t); off++)
1537 (*AH->WriteBytePtr) (AH, o & 0xFF);
1540 return sizeof(pgoff_t) + 1;
1544 ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1550 /* Initialize to zero */
1553 /* Check for old version */
1554 if (AH->version < K_VERS_1_7)
1556 /* Prior versions wrote offsets using WriteInt */
1558 /* -1 means not set */
1560 return K_OFFSET_POS_NOT_SET;
1562 return K_OFFSET_NO_DATA;
1564 /* Cast to pgoff_t because it was written as an int. */
1566 return K_OFFSET_POS_SET;
1570 * Read the flag indicating the state of the data pointer. Check if valid
1573 * This used to be handled by a negative or zero pointer, now we use an
1574 * extra byte specifically for the state.
1576 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1580 case K_OFFSET_POS_NOT_SET:
1581 case K_OFFSET_NO_DATA:
1582 case K_OFFSET_POS_SET:
1587 die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1593 for (off = 0; off < AH->offSize; off++)
1595 if (off < sizeof(pgoff_t))
1596 *o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1599 if ((*AH->ReadBytePtr) (AH) != 0)
1600 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1608 WriteInt(ArchiveHandle *AH, int i)
1613 * This is a bit yucky, but I don't want to make the binary format very
1614 * dependent on representation, and not knowing much about it, I write out
1615 * a sign byte. If you change this, don't forget to change the file
1616 * version #, and modify readInt to read the new format AS WELL AS the old
1623 (*AH->WriteBytePtr) (AH, 1);
1627 (*AH->WriteBytePtr) (AH, 0);
1629 for (b = 0; b < AH->intSize; b++)
1631 (*AH->WriteBytePtr) (AH, i & 0xFF);
1635 return AH->intSize + 1;
1639 ReadInt(ArchiveHandle *AH)
1644 int sign = 0; /* Default positive */
1647 if (AH->version > K_VERS_1_0)
1648 /* Read a sign byte */
1649 sign = (*AH->ReadBytePtr) (AH);
1651 for (b = 0; b < AH->intSize; b++)
1653 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1655 res = res + (bv << bitShift);
1666 WriteStr(ArchiveHandle *AH, const char *c)
1672 res = WriteInt(AH, strlen(c));
1673 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1676 res = WriteInt(AH, -1);
1682 ReadStr(ArchiveHandle *AH)
1692 buf = (char *) malloc(l + 1);
1694 die_horribly(AH, modulename, "out of memory\n");
1696 if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1697 die_horribly(AH, modulename, "unexpected end of file\n");
1706 _discoverArchiveFormat(ArchiveHandle *AH)
1709 char sig[6]; /* More than enough */
1714 write_msg(modulename, "attempting to ascertain archive format\n");
1718 free(AH->lookahead);
1720 AH->lookaheadSize = 512;
1721 AH->lookahead = calloc(1, 512);
1722 AH->lookaheadLen = 0;
1723 AH->lookaheadPos = 0;
1728 fh = fopen(AH->fSpec, PG_BINARY_R);
1730 die_horribly(AH, modulename, "could not open input file \"%s\": %s\n",
1731 AH->fSpec, strerror(errno));
1737 die_horribly(AH, modulename, "could not open input file: %s\n",
1741 cnt = fread(sig, 1, 5, fh);
1746 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1748 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1749 (unsigned long) cnt);
1752 /* Save it, just in case we need it later */
1753 strncpy(&AH->lookahead[0], sig, 5);
1754 AH->lookaheadLen = 5;
1756 if (strncmp(sig, "PGDMP", 5) == 0)
1759 * Finish reading (most of) a custom-format header.
1761 * NB: this code must agree with ReadHead().
1763 AH->vmaj = fgetc(fh);
1764 AH->vmin = fgetc(fh);
1766 /* Save these too... */
1767 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1768 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1770 /* Check header version; varies from V1.0 */
1771 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1773 AH->vrev = fgetc(fh);
1774 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1779 /* Make a convenient integer <maj><min><rev>00 */
1780 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1782 AH->intSize = fgetc(fh);
1783 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1785 if (AH->version >= K_VERS_1_7)
1787 AH->offSize = fgetc(fh);
1788 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1791 AH->offSize = AH->intSize;
1793 AH->format = fgetc(fh);
1794 AH->lookahead[AH->lookaheadLen++] = AH->format;
1799 * *Maybe* we have a tar archive format file... So, read first 512
1802 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1803 AH->lookaheadLen += cnt;
1805 if (AH->lookaheadLen != 512)
1806 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1808 if (!isValidTarHeader(AH->lookahead))
1809 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1811 AH->format = archTar;
1814 /* If we can't seek, then mark the header as read */
1815 if (fseeko(fh, 0, SEEK_SET) != 0)
1818 * NOTE: Formats that use the lookahead buffer can unset this in their
1824 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1826 /* Close the file */
1828 if (fclose(fh) != 0)
1829 die_horribly(AH, modulename, "could not close input file: %s\n",
1837 * Allocate an archive handle
1839 static ArchiveHandle *
1840 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1841 const int compression, ArchiveMode mode)
1846 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1849 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1851 die_horribly(AH, modulename, "out of memory\n");
1853 /* AH->debugLevel = 100; */
1855 AH->vmaj = K_VERS_MAJOR;
1856 AH->vmin = K_VERS_MINOR;
1857 AH->vrev = K_VERS_REV;
1859 /* Make a convenient integer <maj><min><rev>00 */
1860 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1862 /* initialize for backwards compatible string processing */
1863 AH->public.encoding = 0; /* PG_SQL_ASCII */
1864 AH->public.std_strings = false;
1866 /* sql error handling */
1867 AH->public.exit_on_error = true;
1868 AH->public.n_errors = 0;
1870 AH->archiveDumpVersion = PG_VERSION;
1872 AH->createDate = time(NULL);
1874 AH->intSize = sizeof(int);
1875 AH->offSize = sizeof(pgoff_t);
1878 AH->fSpec = strdup(FileSpec);
1881 * Not used; maybe later....
1883 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1884 * i--) if (AH->workDir[i-1] == '/')
1890 AH->currUser = NULL; /* unknown */
1891 AH->currSchema = NULL; /* ditto */
1892 AH->currTablespace = NULL; /* ditto */
1893 AH->currWithOids = -1; /* force SET */
1895 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1897 die_horribly(AH, modulename, "out of memory\n");
1899 AH->toc->next = AH->toc;
1900 AH->toc->prev = AH->toc;
1903 AH->compression = compression;
1905 AH->pgCopyBuf = createPQExpBuffer();
1906 AH->sqlBuf = createPQExpBuffer();
1908 /* Open stdout with no compression for AH output handle */
1913 * On Windows, we need to use binary mode to read/write non-text archive
1914 * formats. Force stdin/stdout into binary mode if that is what we are
1918 if (fmt != archNull &&
1919 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1921 if (mode == archModeWrite)
1922 setmode(fileno(stdout), O_BINARY);
1924 setmode(fileno(stdin), O_BINARY);
1928 if (fmt == archUnknown)
1929 AH->format = _discoverArchiveFormat(AH);
1933 AH->promptPassword = TRI_DEFAULT;
1938 InitArchiveFmt_Custom(AH);
1942 InitArchiveFmt_Files(AH);
1946 InitArchiveFmt_Null(AH);
1950 InitArchiveFmt_Tar(AH);
1954 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1962 WriteDataChunks(ArchiveHandle *AH)
1965 StartDataPtr startPtr;
1968 for (te = AH->toc->next; te != AH->toc; te = te->next)
1970 if (te->dataDumper != NULL)
1973 /* printf("Writing data for %d (%x)\n", te->id, te); */
1975 if (strcmp(te->desc, "BLOBS") == 0)
1977 startPtr = AH->StartBlobsPtr;
1978 endPtr = AH->EndBlobsPtr;
1982 startPtr = AH->StartDataPtr;
1983 endPtr = AH->EndDataPtr;
1986 if (startPtr != NULL)
1987 (*startPtr) (AH, te);
1990 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1994 * The user-provided DataDumper routine needs to call
1997 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
2007 WriteToc(ArchiveHandle *AH)
2013 /* printf("%d TOC Entries to save\n", AH->tocCount); */
2015 WriteInt(AH, AH->tocCount);
2017 for (te = AH->toc->next; te != AH->toc; te = te->next)
2019 WriteInt(AH, te->dumpId);
2020 WriteInt(AH, te->dataDumper ? 1 : 0);
2022 /* OID is recorded as a string for historical reasons */
2023 sprintf(workbuf, "%u", te->catalogId.tableoid);
2024 WriteStr(AH, workbuf);
2025 sprintf(workbuf, "%u", te->catalogId.oid);
2026 WriteStr(AH, workbuf);
2028 WriteStr(AH, te->tag);
2029 WriteStr(AH, te->desc);
2030 WriteInt(AH, te->section);
2031 WriteStr(AH, te->defn);
2032 WriteStr(AH, te->dropStmt);
2033 WriteStr(AH, te->copyStmt);
2034 WriteStr(AH, te->namespace);
2035 WriteStr(AH, te->tablespace);
2036 WriteStr(AH, te->owner);
2037 WriteStr(AH, te->withOids ? "true" : "false");
2039 /* Dump list of dependencies */
2040 for (i = 0; i < te->nDeps; i++)
2042 sprintf(workbuf, "%d", te->dependencies[i]);
2043 WriteStr(AH, workbuf);
2045 WriteStr(AH, NULL); /* Terminate List */
2047 if (AH->WriteExtraTocPtr)
2048 (*AH->WriteExtraTocPtr) (AH, te);
2053 ReadToc(ArchiveHandle *AH)
2062 AH->tocCount = ReadInt(AH);
2065 for (i = 0; i < AH->tocCount; i++)
2067 te = (TocEntry *) calloc(1, sizeof(TocEntry));
2068 te->dumpId = ReadInt(AH);
2070 if (te->dumpId > AH->maxDumpId)
2071 AH->maxDumpId = te->dumpId;
2074 if (te->dumpId <= 0)
2075 die_horribly(AH, modulename,
2076 "entry ID %d out of range -- perhaps a corrupt TOC\n",
2079 te->hadDumper = ReadInt(AH);
2081 if (AH->version >= K_VERS_1_8)
2084 sscanf(tmp, "%u", &te->catalogId.tableoid);
2088 te->catalogId.tableoid = InvalidOid;
2090 sscanf(tmp, "%u", &te->catalogId.oid);
2093 te->tag = ReadStr(AH);
2094 te->desc = ReadStr(AH);
2096 if (AH->version >= K_VERS_1_11)
2098 te->section = ReadInt(AH);
2103 * Rules for pre-8.4 archives wherein pg_dump hasn't classified
2104 * the entries into sections. This list need not cover entry
2105 * types added later than 8.4.
2107 if (strcmp(te->desc, "COMMENT") == 0 ||
2108 strcmp(te->desc, "ACL") == 0 ||
2109 strcmp(te->desc, "ACL LANGUAGE") == 0)
2110 te->section = SECTION_NONE;
2111 else if (strcmp(te->desc, "TABLE DATA") == 0 ||
2112 strcmp(te->desc, "BLOBS") == 0 ||
2113 strcmp(te->desc, "BLOB COMMENTS") == 0)
2114 te->section = SECTION_DATA;
2115 else if (strcmp(te->desc, "CONSTRAINT") == 0 ||
2116 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2117 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2118 strcmp(te->desc, "INDEX") == 0 ||
2119 strcmp(te->desc, "RULE") == 0 ||
2120 strcmp(te->desc, "TRIGGER") == 0)
2121 te->section = SECTION_POST_DATA;
2123 te->section = SECTION_PRE_DATA;
2126 te->defn = ReadStr(AH);
2127 te->dropStmt = ReadStr(AH);
2129 if (AH->version >= K_VERS_1_3)
2130 te->copyStmt = ReadStr(AH);
2132 if (AH->version >= K_VERS_1_6)
2133 te->namespace = ReadStr(AH);
2135 if (AH->version >= K_VERS_1_10)
2136 te->tablespace = ReadStr(AH);
2138 te->owner = ReadStr(AH);
2139 if (AH->version >= K_VERS_1_9)
2141 if (strcmp(ReadStr(AH), "true") == 0)
2142 te->withOids = true;
2144 te->withOids = false;
2147 te->withOids = true;
2149 /* Read TOC entry dependencies */
2150 if (AH->version >= K_VERS_1_5)
2153 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
2159 break; /* end of list */
2160 if (depIdx >= depSize)
2163 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
2165 sscanf(tmp, "%d", &deps[depIdx]);
2170 if (depIdx > 0) /* We have a non-null entry */
2172 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
2173 te->dependencies = deps;
2179 te->dependencies = NULL;
2185 te->dependencies = NULL;
2189 if (AH->ReadExtraTocPtr)
2190 (*AH->ReadExtraTocPtr) (AH, te);
2192 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
2193 i, te->dumpId, te->desc, te->tag);
2195 /* link completed entry into TOC circular list */
2196 te->prev = AH->toc->prev;
2197 AH->toc->prev->next = te;
2201 /* special processing immediately upon read for some items */
2202 if (strcmp(te->desc, "ENCODING") == 0)
2203 processEncodingEntry(AH, te);
2204 else if (strcmp(te->desc, "STDSTRINGS") == 0)
2205 processStdStringsEntry(AH, te);
2210 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
2212 /* te->defn should have the form SET client_encoding = 'foo'; */
2213 char *defn = strdup(te->defn);
2218 ptr1 = strchr(defn, '\'');
2220 ptr2 = strchr(++ptr1, '\'');
2224 encoding = pg_char_to_encoding(ptr1);
2226 die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
2228 AH->public.encoding = encoding;
2231 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
2238 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
2240 /* te->defn should have the form SET standard_conforming_strings = 'x'; */
2243 ptr1 = strchr(te->defn, '\'');
2244 if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
2245 AH->public.std_strings = true;
2246 else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
2247 AH->public.std_strings = false;
2249 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
2254 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
2256 teReqs res = REQ_ALL;
2258 /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
2259 if (strcmp(te->desc, "ENCODING") == 0 ||
2260 strcmp(te->desc, "STDSTRINGS") == 0)
2263 /* If it's an ACL, maybe ignore it */
2264 if ((!include_acls || ropt->aclsSkip) && _tocEntryIsACL(te))
2267 /* Ignore DATABASE entry unless we should create it */
2268 if (!ropt->createDB && strcmp(te->desc, "DATABASE") == 0)
2271 /* Check options for selective dump/restore */
2272 if (ropt->schemaNames)
2274 /* If no namespace is specified, it means all. */
2277 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2283 if (strcmp(te->desc, "TABLE") == 0 ||
2284 strcmp(te->desc, "TABLE DATA") == 0)
2286 if (!ropt->selTable)
2288 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2291 else if (strcmp(te->desc, "INDEX") == 0)
2293 if (!ropt->selIndex)
2295 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2298 else if (strcmp(te->desc, "FUNCTION") == 0)
2300 if (!ropt->selFunction)
2302 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2305 else if (strcmp(te->desc, "TRIGGER") == 0)
2307 if (!ropt->selTrigger)
2309 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2317 * Check if we had a dataDumper. Indicates if the entry is schema or data
2322 * Special Case: If 'SEQUENCE SET' or anything to do with BLOBs, then
2323 * it is considered a data entry. We don't need to check for the
2324 * BLOBS entry or old-style BLOB COMMENTS, because they will have
2325 * hadDumper = true ... but we do need to check new-style BLOB
2328 if (strcmp(te->desc, "SEQUENCE SET") == 0 ||
2329 strcmp(te->desc, "BLOB") == 0 ||
2330 (strcmp(te->desc, "ACL") == 0 &&
2331 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
2332 (strcmp(te->desc, "COMMENT") == 0 &&
2333 strncmp(te->tag, "LARGE OBJECT ", 13) == 0))
2334 res = res & REQ_DATA;
2336 res = res & ~REQ_DATA;
2340 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2343 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2346 /* Mask it if we only want schema */
2347 if (ropt->schemaOnly)
2348 res = res & REQ_SCHEMA;
2350 /* Mask it we only want data */
2352 res = res & REQ_DATA;
2354 /* Mask it if we don't have a schema contribution */
2355 if (!te->defn || strlen(te->defn) == 0)
2356 res = res & ~REQ_SCHEMA;
2358 /* Finally, if there's a per-ID filter, limit based on that as well */
2359 if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2366 * Identify TOC entries that are ACLs.
2369 _tocEntryIsACL(TocEntry *te)
2371 /* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
2372 if (strcmp(te->desc, "ACL") == 0 ||
2373 strcmp(te->desc, "ACL LANGUAGE") == 0 ||
2374 strcmp(te->desc, "DEFAULT ACL") == 0)
2380 * Issue SET commands for parameters that we want to have set the same way
2381 * at all times during execution of a restore script.
2384 _doSetFixedOutputState(ArchiveHandle *AH)
2386 /* Disable statement_timeout in archive for pg_restore/psql */
2387 ahprintf(AH, "SET statement_timeout = 0;\n");
2389 /* Select the correct character set encoding */
2390 ahprintf(AH, "SET client_encoding = '%s';\n",
2391 pg_encoding_to_char(AH->public.encoding));
2393 /* Select the correct string literal syntax */
2394 ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2395 AH->public.std_strings ? "on" : "off");
2397 /* Select the role to be used during restore */
2398 if (AH->ropt && AH->ropt->use_role)
2399 ahprintf(AH, "SET ROLE %s;\n", fmtId(AH->ropt->use_role));
2401 /* Make sure function checking is disabled */
2402 ahprintf(AH, "SET check_function_bodies = false;\n");
2404 /* Avoid annoying notices etc */
2405 ahprintf(AH, "SET client_min_messages = warning;\n");
2406 if (!AH->public.std_strings)
2407 ahprintf(AH, "SET escape_string_warning = off;\n");
2413 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2414 * for updating state if appropriate. If user is NULL or an empty string,
2415 * the specification DEFAULT will be used.
2418 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2420 PQExpBuffer cmd = createPQExpBuffer();
2422 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2425 * SQL requires a string literal here. Might as well be correct.
2428 appendStringLiteralAHX(cmd, user, AH);
2430 appendPQExpBuffer(cmd, "DEFAULT");
2431 appendPQExpBuffer(cmd, ";");
2433 if (RestoringToDB(AH))
2437 res = PQexec(AH->connection, cmd->data);
2439 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2440 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2441 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2442 user, PQerrorMessage(AH->connection));
2447 ahprintf(AH, "%s\n\n", cmd->data);
2449 destroyPQExpBuffer(cmd);
2454 * Issue a SET default_with_oids command. Caller is responsible
2455 * for updating state if appropriate.
2458 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2460 PQExpBuffer cmd = createPQExpBuffer();
2462 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2465 if (RestoringToDB(AH))
2469 res = PQexec(AH->connection, cmd->data);
2471 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2472 warn_or_die_horribly(AH, modulename,
2473 "could not set default_with_oids: %s",
2474 PQerrorMessage(AH->connection));
2479 ahprintf(AH, "%s\n\n", cmd->data);
2481 destroyPQExpBuffer(cmd);
2486 * Issue the commands to connect to the specified database.
2488 * If we're currently restoring right into a database, this will
2489 * actually establish a connection. Otherwise it puts a \connect into
2490 * the script output.
2492 * NULL dbname implies reconnecting to the current DB (pretty useless).
2495 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2497 if (RestoringToDB(AH))
2498 ReconnectToServer(AH, dbname, NULL);
2501 PQExpBuffer qry = createPQExpBuffer();
2503 appendPQExpBuffer(qry, "\\connect %s\n\n",
2504 dbname ? fmtId(dbname) : "-");
2505 ahprintf(AH, "%s", qry->data);
2506 destroyPQExpBuffer(qry);
2510 * NOTE: currUser keeps track of what the imaginary session user in our
2511 * script is. It's now effectively reset to the original userID.
2515 AH->currUser = NULL;
2517 /* don't assume we still know the output schema, tablespace, etc either */
2519 free(AH->currSchema);
2520 AH->currSchema = NULL;
2521 if (AH->currTablespace)
2522 free(AH->currTablespace);
2523 AH->currTablespace = NULL;
2524 AH->currWithOids = -1;
2526 /* re-establish fixed state */
2527 _doSetFixedOutputState(AH);
2531 * Become the specified user, and update state to avoid redundant commands
2533 * NULL or empty argument is taken to mean restoring the session default
2536 _becomeUser(ArchiveHandle *AH, const char *user)
2539 user = ""; /* avoid null pointers */
2541 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2542 return; /* no need to do anything */
2544 _doSetSessionAuth(AH, user);
2547 * NOTE: currUser keeps track of what the imaginary session user in our
2552 AH->currUser = strdup(user);
2556 * Become the owner of the given TOC entry object. If
2557 * changes in ownership are not allowed, this doesn't do anything.
2560 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2562 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2565 _becomeUser(AH, te->owner);
2570 * Set the proper default_with_oids value for the table.
2573 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2575 if (AH->currWithOids != te->withOids)
2577 _doSetWithOids(AH, te->withOids);
2578 AH->currWithOids = te->withOids;
2584 * Issue the commands to select the specified schema as the current schema
2585 * in the target database.
2588 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2592 if (!schemaName || *schemaName == '\0' ||
2593 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2594 return; /* no need to do anything */
2596 qry = createPQExpBuffer();
2598 appendPQExpBuffer(qry, "SET search_path = %s",
2600 if (strcmp(schemaName, "pg_catalog") != 0)
2601 appendPQExpBuffer(qry, ", pg_catalog");
2603 if (RestoringToDB(AH))
2607 res = PQexec(AH->connection, qry->data);
2609 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2610 warn_or_die_horribly(AH, modulename,
2611 "could not set search_path to \"%s\": %s",
2612 schemaName, PQerrorMessage(AH->connection));
2617 ahprintf(AH, "%s;\n\n", qry->data);
2620 free(AH->currSchema);
2621 AH->currSchema = strdup(schemaName);
2623 destroyPQExpBuffer(qry);
2627 * Issue the commands to select the specified tablespace as the current one
2628 * in the target database.
2631 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2637 /* do nothing in --no-tablespaces mode */
2638 if (AH->ropt->noTablespace)
2641 have = AH->currTablespace;
2644 /* no need to do anything for non-tablespace object */
2648 if (have && strcmp(want, have) == 0)
2649 return; /* no need to do anything */
2651 qry = createPQExpBuffer();
2653 if (strcmp(want, "") == 0)
2655 /* We want the tablespace to be the database's default */
2656 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2660 /* We want an explicit tablespace */
2661 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2664 if (RestoringToDB(AH))
2668 res = PQexec(AH->connection, qry->data);
2670 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2671 warn_or_die_horribly(AH, modulename,
2672 "could not set default_tablespace to %s: %s",
2673 fmtId(want), PQerrorMessage(AH->connection));
2678 ahprintf(AH, "%s;\n\n", qry->data);
2680 if (AH->currTablespace)
2681 free(AH->currTablespace);
2682 AH->currTablespace = strdup(want);
2684 destroyPQExpBuffer(qry);
2688 * Extract an object description for a TOC entry, and append it to buf.
2690 * This is not quite as general as it may seem, since it really only
2691 * handles constructing the right thing to put into ALTER ... OWNER TO.
2693 * The whole thing is pretty grotty, but we are kind of stuck since the
2694 * information used is all that's available in older dump files.
2697 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2699 const char *type = te->desc;
2701 /* Use ALTER TABLE for views and sequences */
2702 if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2705 /* objects named by a schema and name */
2706 if (strcmp(type, "CONVERSION") == 0 ||
2707 strcmp(type, "DOMAIN") == 0 ||
2708 strcmp(type, "TABLE") == 0 ||
2709 strcmp(type, "TYPE") == 0 ||
2710 strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
2711 strcmp(type, "TEXT SEARCH CONFIGURATION") == 0)
2713 appendPQExpBuffer(buf, "%s ", type);
2714 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2715 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2718 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2719 * into te->tag for an index. This check is heuristic, so make its
2720 * scope as narrow as possible.
2722 if (AH->version < K_VERS_1_7 &&
2723 te->tag[0] == '"' &&
2724 te->tag[strlen(te->tag) - 1] == '"' &&
2725 strcmp(type, "INDEX") == 0)
2726 appendPQExpBuffer(buf, "%s", te->tag);
2728 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2732 /* objects named by just a name */
2733 if (strcmp(type, "DATABASE") == 0 ||
2734 strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
2735 strcmp(type, "SCHEMA") == 0 ||
2736 strcmp(type, "FOREIGN DATA WRAPPER") == 0 ||
2737 strcmp(type, "SERVER") == 0 ||
2738 strcmp(type, "USER MAPPING") == 0)
2740 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2744 /* BLOBs just have a name, but it's numeric so must not use fmtId */
2745 if (strcmp(type, "BLOB") == 0)
2747 appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
2752 * These object types require additional decoration. Fortunately, the
2753 * information needed is exactly what's in the DROP command.
2755 if (strcmp(type, "AGGREGATE") == 0 ||
2756 strcmp(type, "FUNCTION") == 0 ||
2757 strcmp(type, "OPERATOR") == 0 ||
2758 strcmp(type, "OPERATOR CLASS") == 0 ||
2759 strcmp(type, "OPERATOR FAMILY") == 0)
2761 /* Chop "DROP " off the front and make a modifiable copy */
2762 char *first = strdup(te->dropStmt + 5);
2765 /* point to last character in string */
2766 last = first + strlen(first) - 1;
2768 /* Strip off any ';' or '\n' at the end */
2769 while (last >= first && (*last == '\n' || *last == ';'))
2773 appendPQExpBufferStr(buf, first);
2779 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2784 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2786 /* ACLs are dumped only during acl pass */
2789 if (!_tocEntryIsACL(te))
2794 if (_tocEntryIsACL(te))
2799 * Avoid dumping the public schema, as it will already be created ...
2800 * unless we are using --clean mode, in which case it's been deleted and
2801 * we'd better recreate it. Likewise for its comment, if any.
2803 if (!ropt->dropSchema)
2805 if (strcmp(te->desc, "SCHEMA") == 0 &&
2806 strcmp(te->tag, "public") == 0)
2808 /* The comment restore would require super-user privs, so avoid it. */
2809 if (strcmp(te->desc, "COMMENT") == 0 &&
2810 strcmp(te->tag, "SCHEMA public") == 0)
2814 /* Select owner, schema, and tablespace as necessary */
2815 _becomeOwner(AH, te);
2816 _selectOutputSchema(AH, te->namespace);
2817 _selectTablespace(AH, te->tablespace);
2819 /* Set up OID mode too */
2820 if (strcmp(te->desc, "TABLE") == 0)
2821 _setWithOids(AH, te);
2823 /* Emit header comment for item */
2824 if (!AH->noTocComments)
2833 ahprintf(AH, "--\n");
2834 if (AH->public.verbose)
2836 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2837 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2842 ahprintf(AH, "-- Dependencies:");
2843 for (i = 0; i < te->nDeps; i++)
2844 ahprintf(AH, " %d", te->dependencies[i]);
2848 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2849 pfx, te->tag, te->desc,
2850 te->namespace ? te->namespace : "-",
2851 ropt->noOwner ? "-" : te->owner);
2852 if (te->tablespace && !ropt->noTablespace)
2853 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2856 if (AH->PrintExtraTocPtr !=NULL)
2857 (*AH->PrintExtraTocPtr) (AH, te);
2858 ahprintf(AH, "--\n\n");
2862 * Actually print the definition.
2864 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2865 * versions put into CREATE SCHEMA. We have to do this when --no-owner
2866 * mode is selected. This is ugly, but I see no other good way ...
2868 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2870 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2874 if (strlen(te->defn) > 0)
2875 ahprintf(AH, "%s\n\n", te->defn);
2879 * If we aren't using SET SESSION AUTH to determine ownership, we must
2880 * instead issue an ALTER OWNER command. We assume that anything without
2881 * a DROP command is not a separately ownable object. All the categories
2882 * with DROP commands must appear in one list or the other.
2884 if (!ropt->noOwner && !ropt->use_setsessauth &&
2885 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2887 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2888 strcmp(te->desc, "BLOB") == 0 ||
2889 strcmp(te->desc, "CONVERSION") == 0 ||
2890 strcmp(te->desc, "DATABASE") == 0 ||
2891 strcmp(te->desc, "DOMAIN") == 0 ||
2892 strcmp(te->desc, "FUNCTION") == 0 ||
2893 strcmp(te->desc, "OPERATOR") == 0 ||
2894 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2895 strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
2896 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2897 strcmp(te->desc, "SCHEMA") == 0 ||
2898 strcmp(te->desc, "TABLE") == 0 ||
2899 strcmp(te->desc, "TYPE") == 0 ||
2900 strcmp(te->desc, "VIEW") == 0 ||
2901 strcmp(te->desc, "SEQUENCE") == 0 ||
2902 strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
2903 strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0 ||
2904 strcmp(te->desc, "FOREIGN DATA WRAPPER") == 0 ||
2905 strcmp(te->desc, "SERVER") == 0)
2907 PQExpBuffer temp = createPQExpBuffer();
2909 appendPQExpBuffer(temp, "ALTER ");
2910 _getObjectDescription(temp, te, AH);
2911 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2912 ahprintf(AH, "%s\n\n", temp->data);
2913 destroyPQExpBuffer(temp);
2915 else if (strcmp(te->desc, "CAST") == 0 ||
2916 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2917 strcmp(te->desc, "CONSTRAINT") == 0 ||
2918 strcmp(te->desc, "DEFAULT") == 0 ||
2919 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2920 strcmp(te->desc, "INDEX") == 0 ||
2921 strcmp(te->desc, "RULE") == 0 ||
2922 strcmp(te->desc, "TRIGGER") == 0 ||
2923 strcmp(te->desc, "USER MAPPING") == 0)
2925 /* these object types don't have separate owners */
2929 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2935 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2936 * commands, so we can no longer assume we know the current auth setting.
2942 AH->currUser = NULL;
2947 WriteHead(ArchiveHandle *AH)
2951 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2952 (*AH->WriteBytePtr) (AH, AH->vmaj);
2953 (*AH->WriteBytePtr) (AH, AH->vmin);
2954 (*AH->WriteBytePtr) (AH, AH->vrev);
2955 (*AH->WriteBytePtr) (AH, AH->intSize);
2956 (*AH->WriteBytePtr) (AH, AH->offSize);
2957 (*AH->WriteBytePtr) (AH, AH->format);
2960 if (AH->compression != 0)
2961 write_msg(modulename, "WARNING: requested compression not available in this "
2962 "installation -- archive will be uncompressed\n");
2964 AH->compression = 0;
2967 WriteInt(AH, AH->compression);
2969 crtm = *localtime(&AH->createDate);
2970 WriteInt(AH, crtm.tm_sec);
2971 WriteInt(AH, crtm.tm_min);
2972 WriteInt(AH, crtm.tm_hour);
2973 WriteInt(AH, crtm.tm_mday);
2974 WriteInt(AH, crtm.tm_mon);
2975 WriteInt(AH, crtm.tm_year);
2976 WriteInt(AH, crtm.tm_isdst);
2977 WriteStr(AH, PQdb(AH->connection));
2978 WriteStr(AH, AH->public.remoteVersionStr);
2979 WriteStr(AH, PG_VERSION);
2983 ReadHead(ArchiveHandle *AH)
2990 * If we haven't already read the header, do so.
2992 * NB: this code must agree with _discoverArchiveFormat(). Maybe find a
2993 * way to unify the cases?
2995 if (!AH->readHeader)
2997 if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
2998 die_horribly(AH, modulename, "unexpected end of file\n");
3000 if (strncmp(tmpMag, "PGDMP", 5) != 0)
3001 die_horribly(AH, modulename, "did not find magic string in file header\n");
3003 AH->vmaj = (*AH->ReadBytePtr) (AH);
3004 AH->vmin = (*AH->ReadBytePtr) (AH);
3006 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
3007 AH->vrev = (*AH->ReadBytePtr) (AH);
3011 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
3013 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
3014 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
3015 AH->vmaj, AH->vmin);
3017 AH->intSize = (*AH->ReadBytePtr) (AH);
3018 if (AH->intSize > 32)
3019 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
3020 (unsigned long) AH->intSize);
3022 if (AH->intSize > sizeof(int))
3023 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations might fail\n");
3025 if (AH->version >= K_VERS_1_7)
3026 AH->offSize = (*AH->ReadBytePtr) (AH);
3028 AH->offSize = AH->intSize;
3030 fmt = (*AH->ReadBytePtr) (AH);
3032 if (AH->format != fmt)
3033 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
3037 if (AH->version >= K_VERS_1_2)
3039 if (AH->version < K_VERS_1_4)
3040 AH->compression = (*AH->ReadBytePtr) (AH);
3042 AH->compression = ReadInt(AH);
3045 AH->compression = Z_DEFAULT_COMPRESSION;
3048 if (AH->compression != 0)
3049 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
3052 if (AH->version >= K_VERS_1_4)
3054 crtm.tm_sec = ReadInt(AH);
3055 crtm.tm_min = ReadInt(AH);
3056 crtm.tm_hour = ReadInt(AH);
3057 crtm.tm_mday = ReadInt(AH);
3058 crtm.tm_mon = ReadInt(AH);
3059 crtm.tm_year = ReadInt(AH);
3060 crtm.tm_isdst = ReadInt(AH);
3062 AH->archdbname = ReadStr(AH);
3064 AH->createDate = mktime(&crtm);
3066 if (AH->createDate == (time_t) -1)
3067 write_msg(modulename, "WARNING: invalid creation date in header\n");
3070 if (AH->version >= K_VERS_1_10)
3072 AH->archiveRemoteVersion = ReadStr(AH);
3073 AH->archiveDumpVersion = ReadStr(AH);
3080 * check to see if ftell/fseek can be performed.
3088 * If pgoff_t is wider than long, we must have "real" fseeko and not an
3089 * emulation using fseek. Otherwise report no seek capability.
3092 if (sizeof(pgoff_t) > sizeof(long))
3096 /* Check that ftello works on this file */
3103 * Check that fseeko(SEEK_SET) works, too. NB: we used to try to test
3104 * this with fseeko(fp, 0, SEEK_CUR). But some platforms treat that as a
3105 * successful no-op even on files that are otherwise unseekable.
3107 if (fseeko(fp, tpos, SEEK_SET) != 0)
3118 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
3123 * We don't print the timezone on Win32, because the names are long and
3124 * localized, which means they may contain characters in various random
3125 * encodings; this has been seen to cause encoding errors when reading the
3128 if (strftime(buf, sizeof(buf),
3130 "%Y-%m-%d %H:%M:%S %Z",
3132 "%Y-%m-%d %H:%M:%S",
3134 localtime(&tim)) != 0)
3135 ahprintf(AH, "-- %s %s\n\n", msg, buf);
3140 * Main engine for parallel restore.
3142 * Work is done in three phases.
3143 * First we process tocEntries until we come to one that is marked
3144 * SECTION_DATA or SECTION_POST_DATA, in a single connection, just as for a
3145 * standard restore. Second we process the remaining non-ACL steps in
3146 * parallel worker children (threads on Windows, processes on Unix), each of
3147 * which connects separately to the database. Finally we process all the ACL
3148 * entries in a single connection (that happens back in RestoreArchive).
3151 restore_toc_entries_parallel(ArchiveHandle *AH)
3153 RestoreOptions *ropt = AH->ropt;
3154 int n_slots = ropt->number_of_jobs;
3155 ParallelSlot *slots;
3158 TocEntry pending_list;
3159 TocEntry ready_list;
3160 TocEntry *next_work_item;
3164 ahlog(AH, 2, "entering restore_toc_entries_parallel\n");
3166 /* we haven't got round to making this work for all archive formats */
3167 if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
3168 die_horribly(AH, modulename, "parallel restore is not supported with this archive file format\n");
3170 /* doesn't work if the archive represents dependencies as OIDs, either */
3171 if (AH->version < K_VERS_1_8)
3172 die_horribly(AH, modulename, "parallel restore is not supported with archives made by pre-8.0 pg_dump\n");
3174 slots = (ParallelSlot *) calloc(sizeof(ParallelSlot), n_slots);
3176 /* Adjust dependency information */
3177 fix_dependencies(AH);
3180 * Do all the early stuff in a single connection in the parent. There's no
3181 * great point in running it in parallel, in fact it will actually run
3182 * faster in a single connection because we avoid all the connection and
3185 for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3187 if (next_work_item->section == SECTION_DATA ||
3188 next_work_item->section == SECTION_POST_DATA)
3191 ahlog(AH, 1, "processing item %d %s %s\n",
3192 next_work_item->dumpId,
3193 next_work_item->desc, next_work_item->tag);
3195 (void) restore_toc_entry(AH, next_work_item, ropt, false);
3197 /* there should be no touch of ready_list here, so pass NULL */
3198 reduce_dependencies(AH, next_work_item, NULL);
3202 * Now close parent connection in prep for parallel steps. We do this
3203 * mainly to ensure that we don't exceed the specified number of parallel
3206 PQfinish(AH->connection);
3207 AH->connection = NULL;
3209 /* blow away any transient state from the old connection */
3212 AH->currUser = NULL;
3214 free(AH->currSchema);
3215 AH->currSchema = NULL;
3216 if (AH->currTablespace)
3217 free(AH->currTablespace);
3218 AH->currTablespace = NULL;
3219 AH->currWithOids = -1;
3222 * Initialize the lists of pending and ready items. After this setup, the
3223 * pending list is everything that needs to be done but is blocked by one
3224 * or more dependencies, while the ready list contains items that have no
3225 * remaining dependencies. Note: we don't yet filter out entries that
3226 * aren't going to be restored. They might participate in dependency
3227 * chains connecting entries that should be restored, so we treat them as
3228 * live until we actually process them.
3230 par_list_header_init(&pending_list);
3231 par_list_header_init(&ready_list);
3232 for (; next_work_item != AH->toc; next_work_item = next_work_item->next)
3234 if (next_work_item->depCount > 0)
3235 par_list_append(&pending_list, next_work_item);
3237 par_list_append(&ready_list, next_work_item);
3243 * Keep going until there is no worker still running AND there is no work
3247 ahlog(AH, 1, "entering main parallel loop\n");
3249 while ((next_work_item = get_next_work_item(AH, &ready_list,
3250 slots, n_slots)) != NULL ||
3251 work_in_progress(slots, n_slots))
3253 if (next_work_item != NULL)
3257 /* If not to be dumped, don't waste time launching a worker */
3258 reqs = _tocEntryRequired(next_work_item, AH->ropt, false);
3259 if ((reqs & (REQ_SCHEMA | REQ_DATA)) == 0)
3261 ahlog(AH, 1, "skipping item %d %s %s\n",
3262 next_work_item->dumpId,
3263 next_work_item->desc, next_work_item->tag);
3265 par_list_remove(next_work_item);
3266 reduce_dependencies(AH, next_work_item, &ready_list);
3271 if ((next_slot = get_next_slot(slots, n_slots)) != NO_SLOT)
3273 /* There is work still to do and a worker slot available */
3277 ahlog(AH, 1, "launching item %d %s %s\n",
3278 next_work_item->dumpId,
3279 next_work_item->desc, next_work_item->tag);
3281 par_list_remove(next_work_item);
3283 /* this memory is dealloced in mark_work_done() */
3284 args = malloc(sizeof(RestoreArgs));
3285 args->AH = CloneArchive(AH);
3286 args->te = next_work_item;
3288 /* run the step in a worker child */
3289 child = spawn_restore(args);
3291 slots[next_slot].child_id = child;
3292 slots[next_slot].args = args;
3299 * If we get here there must be work being done. Either there is no
3300 * work available to schedule (and work_in_progress returned true) or
3301 * there are no slots available. So we wait for a worker to finish,
3302 * and process the result.
3304 ret_child = reap_child(slots, n_slots, &work_status);
3306 if (WIFEXITED(work_status))
3308 mark_work_done(AH, &ready_list,
3309 ret_child, WEXITSTATUS(work_status),
3314 die_horribly(AH, modulename, "worker process crashed: status %d\n",
3319 ahlog(AH, 1, "finished main parallel loop\n");
3322 * Now reconnect the single parent connection.
3324 ConnectDatabase((Archive *) AH, ropt->dbname,
3325 ropt->pghost, ropt->pgport, ropt->username,
3326 ropt->promptPassword);
3328 _doSetFixedOutputState(AH);
3331 * Make sure there is no non-ACL work left due to, say, circular
3332 * dependencies, or some other pathological condition. If so, do it in the
3333 * single parent connection.
3335 for (te = pending_list.par_next; te != &pending_list; te = te->par_next)
3337 ahlog(AH, 1, "processing missed item %d %s %s\n",
3338 te->dumpId, te->desc, te->tag);
3339 (void) restore_toc_entry(AH, te, ropt, false);
3342 /* The ACLs will be handled back in RestoreArchive. */
3346 * create a worker child to perform a restore step in parallel
3349 spawn_restore(RestoreArgs *args)
3353 /* Ensure stdio state is quiesced before forking */
3360 /* in child process */
3361 parallel_restore(args);
3362 die_horribly(args->AH, modulename,
3363 "parallel_restore should not return\n");
3368 die_horribly(args->AH, modulename,
3369 "could not create worker process: %s\n",
3373 child = (HANDLE) _beginthreadex(NULL, 0, (void *) parallel_restore,
3376 die_horribly(args->AH, modulename,
3377 "could not create worker thread: %s\n",
3385 * collect status from a completed worker child
3388 reap_child(ParallelSlot *slots, int n_slots, int *work_status)
3391 /* Unix is so much easier ... */
3392 return wait(work_status);
3394 static HANDLE *handles = NULL;
3401 /* first time around only, make space for handles to listen on */
3402 if (handles == NULL)
3403 handles = (HANDLE *) calloc(sizeof(HANDLE), n_slots);
3405 /* set up list of handles to listen to */
3406 for (snum = 0, tnum = 0; snum < n_slots; snum++)
3407 if (slots[snum].child_id != 0)
3408 handles[tnum++] = slots[snum].child_id;
3410 /* wait for one to finish */
3411 hindex = WaitForMultipleObjects(tnum, handles, false, INFINITE);
3413 /* get handle of finished thread */
3414 ret_child = handles[hindex - WAIT_OBJECT_0];
3416 /* get the result */
3417 GetExitCodeThread(ret_child, &res);
3420 /* dispose of handle to stop leaks */
3421 CloseHandle(ret_child);
3428 * are we doing anything now?
3431 work_in_progress(ParallelSlot *slots, int n_slots)
3435 for (i = 0; i < n_slots; i++)
3437 if (slots[i].child_id != 0)
3444 * find the first free parallel slot (if any).
3447 get_next_slot(ParallelSlot *slots, int n_slots)
3451 for (i = 0; i < n_slots; i++)
3453 if (slots[i].child_id == 0)
3461 * Check if te1 has an exclusive lock requirement for an item that te2 also
3462 * requires, whether or not te2's requirement is for an exclusive lock.
3465 has_lock_conflicts(TocEntry *te1, TocEntry *te2)
3470 for (j = 0; j < te1->nLockDeps; j++)
3472 for (k = 0; k < te2->nDeps; k++)
3474 if (te1->lockDeps[j] == te2->dependencies[k])
3483 * Initialize the header of a parallel-processing list.
3485 * These are circular lists with a dummy TocEntry as header, just like the
3486 * main TOC list; but we use separate list links so that an entry can be in
3487 * the main TOC list as well as in a parallel-processing list.
3490 par_list_header_init(TocEntry *l)
3492 l->par_prev = l->par_next = l;
3495 /* Append te to the end of the parallel-processing list headed by l */
3497 par_list_append(TocEntry *l, TocEntry *te)
3499 te->par_prev = l->par_prev;
3500 l->par_prev->par_next = te;
3505 /* Remove te from whatever parallel-processing list it's in */
3507 par_list_remove(TocEntry *te)
3509 te->par_prev->par_next = te->par_next;
3510 te->par_next->par_prev = te->par_prev;
3511 te->par_prev = NULL;
3512 te->par_next = NULL;
3517 * Find the next work item (if any) that is capable of being run now.
3519 * To qualify, the item must have no remaining dependencies
3520 * and no requirements for locks that are incompatible with
3521 * items currently running. Items in the ready_list are known to have
3522 * no remaining dependencies, but we have to check for lock conflicts.
3524 * Note that the returned item has *not* been removed from ready_list.
3525 * The caller must do that after successfully dispatching the item.
3527 * pref_non_data is for an alternative selection algorithm that gives
3528 * preference to non-data items if there is already a data load running.
3529 * It is currently disabled.
3532 get_next_work_item(ArchiveHandle *AH, TocEntry *ready_list,
3533 ParallelSlot *slots, int n_slots)
3535 bool pref_non_data = false; /* or get from AH->ropt */
3536 TocEntry *data_te = NULL;
3542 * Bogus heuristics for pref_non_data
3548 for (k = 0; k < n_slots; k++)
3549 if (slots[k].args->te != NULL &&
3550 slots[k].args->te->section == SECTION_DATA)
3552 if (n_slots == 0 || count * 4 < n_slots)
3553 pref_non_data = false;
3557 * Search the ready_list until we find a suitable item.
3559 for (te = ready_list->par_next; te != ready_list; te = te->par_next)
3561 bool conflicts = false;
3564 * Check to see if the item would need exclusive lock on something
3565 * that a currently running item also needs lock on, or vice versa. If
3566 * so, we don't want to schedule them together.
3568 for (i = 0; i < n_slots && !conflicts; i++)
3570 TocEntry *running_te;
3572 if (slots[i].args == NULL)
3574 running_te = slots[i].args->te;
3576 if (has_lock_conflicts(te, running_te) ||
3577 has_lock_conflicts(running_te, te))
3587 if (pref_non_data && te->section == SECTION_DATA)
3589 if (data_te == NULL)
3594 /* passed all tests, so this item can run */
3598 if (data_te != NULL)
3601 ahlog(AH, 2, "no item ready\n");
3607 * Restore a single TOC item in parallel with others
3609 * this is the procedure run as a thread (Windows) or a
3610 * separate process (everything else).
3612 static parallel_restore_result
3613 parallel_restore(RestoreArgs *args)
3615 ArchiveHandle *AH = args->AH;
3616 TocEntry *te = args->te;
3617 RestoreOptions *ropt = AH->ropt;
3621 * Close and reopen the input file so we have a private file pointer that
3622 * doesn't stomp on anyone else's file pointer, if we're actually going to
3623 * need to read from the file. Otherwise, just close it except on Windows,
3624 * where it will possibly be needed by other threads.
3626 * Note: on Windows, since we are using threads not processes, the reopen
3627 * call *doesn't* close the original file pointer but just open a new one.
3629 if (te->section == SECTION_DATA)
3630 (AH->ReopenPtr) (AH);
3633 (AH->ClosePtr) (AH);
3637 * We need our own database connection, too
3639 ConnectDatabase((Archive *) AH, ropt->dbname,
3640 ropt->pghost, ropt->pgport, ropt->username,
3641 ropt->promptPassword);
3643 _doSetFixedOutputState(AH);
3645 /* Restore the TOC item */
3646 retval = restore_toc_entry(AH, te, ropt, true);
3649 PQfinish(AH->connection);
3650 AH->connection = NULL;
3652 /* If we reopened the file, we are done with it, so close it now */
3653 if (te->section == SECTION_DATA)
3654 (AH->ClosePtr) (AH);
3656 if (retval == 0 && AH->public.n_errors)
3657 retval = WORKER_IGNORED_ERRORS;
3668 * Housekeeping to be done after a step has been parallel restored.
3670 * Clear the appropriate slot, free all the extra memory we allocated,
3671 * update status, and reduce the dependency count of any dependent items.
3674 mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
3675 thandle worker, int status,
3676 ParallelSlot *slots, int n_slots)
3678 TocEntry *te = NULL;
3681 for (i = 0; i < n_slots; i++)
3683 if (slots[i].child_id == worker)
3685 slots[i].child_id = 0;
3686 te = slots[i].args->te;
3687 DeCloneArchive(slots[i].args->AH);
3688 free(slots[i].args);
3689 slots[i].args = NULL;
3696 die_horribly(AH, modulename, "could not find slot of finished worker\n");
3698 ahlog(AH, 1, "finished item %d %s %s\n",
3699 te->dumpId, te->desc, te->tag);
3701 if (status == WORKER_CREATE_DONE)
3702 mark_create_done(AH, te);
3703 else if (status == WORKER_INHIBIT_DATA)
3705 inhibit_data_for_failed_table(AH, te);
3706 AH->public.n_errors++;
3708 else if (status == WORKER_IGNORED_ERRORS)
3709 AH->public.n_errors++;
3710 else if (status != 0)
3711 die_horribly(AH, modulename, "worker process failed: exit code %d\n",
3714 reduce_dependencies(AH, te, ready_list);
3719 * Process the dependency information into a form useful for parallel restore.
3721 * We set up depCount fields that are the number of as-yet-unprocessed
3722 * dependencies for each TOC entry.
3724 * We also identify locking dependencies so that we can avoid trying to
3725 * schedule conflicting items at the same time.
3728 fix_dependencies(ArchiveHandle *AH)
3730 TocEntry **tocsByDumpId;
3736 * For some of the steps here, it is convenient to have an array that
3737 * indexes the TOC entries by dump ID, rather than searching the TOC list
3738 * repeatedly. Entries for dump IDs not present in the TOC will be NULL.
3740 * NOTE: because maxDumpId is just the highest dump ID defined in the
3741 * archive, there might be dependencies for IDs > maxDumpId. All uses of
3742 * this array must guard against out-of-range dependency numbers.
3744 * Also, initialize the depCount fields, and make sure all the TOC items
3745 * are marked as not being in any parallel-processing list.
3747 maxDumpId = AH->maxDumpId;
3748 tocsByDumpId = (TocEntry **) calloc(maxDumpId, sizeof(TocEntry *));
3749 for (te = AH->toc->next; te != AH->toc; te = te->next)
3751 tocsByDumpId[te->dumpId - 1] = te;
3752 te->depCount = te->nDeps;
3753 te->par_prev = NULL;
3754 te->par_next = NULL;
3758 * POST_DATA items that are shown as depending on a table need to be
3759 * re-pointed to depend on that table's data, instead. This ensures they
3760 * won't get scheduled until the data has been loaded. We handle this by
3761 * first finding TABLE/TABLE DATA pairs and then scanning all the
3764 * Note: currently, a TABLE DATA should always have exactly one
3765 * dependency, on its TABLE item. So we don't bother to search, but look
3766 * just at the first dependency. We do trouble to make sure that it's a
3767 * TABLE, if possible. However, if the dependency isn't in the archive
3768 * then just assume it was a TABLE; this is to cover cases where the table
3769 * was suppressed but we have the data and some dependent post-data items.
3771 for (te = AH->toc->next; te != AH->toc; te = te->next)
3773 if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
3775 DumpId tableId = te->dependencies[0];
3777 if (tableId > maxDumpId ||
3778 tocsByDumpId[tableId - 1] == NULL ||
3779 strcmp(tocsByDumpId[tableId - 1]->desc, "TABLE") == 0)
3781 repoint_table_dependencies(AH, tableId, te->dumpId);
3787 * Pre-8.4 versions of pg_dump neglected to set up a dependency from BLOB
3788 * COMMENTS to BLOBS. Cope. (We assume there's only one BLOBS and only
3789 * one BLOB COMMENTS in such files.)
3791 if (AH->version < K_VERS_1_11)
3793 for (te = AH->toc->next; te != AH->toc; te = te->next)
3795 if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
3799 for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
3801 if (strcmp(te2->desc, "BLOBS") == 0)
3803 te->dependencies = (DumpId *) malloc(sizeof(DumpId));
3804 te->dependencies[0] = te2->dumpId;
3816 * It is possible that the dependencies list items that are not in the
3817 * archive at all. Subtract such items from the depCounts.
3819 for (te = AH->toc->next; te != AH->toc; te = te->next)
3821 for (i = 0; i < te->nDeps; i++)
3823 DumpId depid = te->dependencies[i];
3825 if (depid > maxDumpId || tocsByDumpId[depid - 1] == NULL)
3831 * Lastly, work out the locking dependencies.
3833 for (te = AH->toc->next; te != AH->toc; te = te->next)
3835 te->lockDeps = NULL;
3837 identify_locking_dependencies(te, tocsByDumpId, maxDumpId);
3844 * Change dependencies on tableId to depend on tableDataId instead,
3845 * but only in POST_DATA items.
3848 repoint_table_dependencies(ArchiveHandle *AH,
3849 DumpId tableId, DumpId tableDataId)
3854 for (te = AH->toc->next; te != AH->toc; te = te->next)
3856 if (te->section != SECTION_POST_DATA)
3858 for (i = 0; i < te->nDeps; i++)
3860 if (te->dependencies[i] == tableId)
3862 te->dependencies[i] = tableDataId;
3863 ahlog(AH, 2, "transferring dependency %d -> %d to %d\n",
3864 te->dumpId, tableId, tableDataId);
3871 * Identify which objects we'll need exclusive lock on in order to restore
3872 * the given TOC entry (*other* than the one identified by the TOC entry
3873 * itself). Record their dump IDs in the entry's lockDeps[] array.
3874 * tocsByDumpId[] is a convenience array (of size maxDumpId) to avoid
3875 * searching the TOC for each dependency.
3878 identify_locking_dependencies(TocEntry *te,
3879 TocEntry **tocsByDumpId,
3886 /* Quick exit if no dependencies at all */
3890 /* Exit if this entry doesn't need exclusive lock on other objects */
3891 if (!(strcmp(te->desc, "CONSTRAINT") == 0 ||
3892 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
3893 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
3894 strcmp(te->desc, "RULE") == 0 ||
3895 strcmp(te->desc, "TRIGGER") == 0))
3899 * We assume the item requires exclusive lock on each TABLE DATA item
3900 * listed among its dependencies. (This was originally a dependency on
3901 * the TABLE, but fix_dependencies repointed it to the data item. Note
3902 * that all the entry types we are interested in here are POST_DATA, so
3903 * they will all have been changed this way.)
3905 lockids = (DumpId *) malloc(te->nDeps * sizeof(DumpId));
3907 for (i = 0; i < te->nDeps; i++)
3909 DumpId depid = te->dependencies[i];
3911 if (depid <= maxDumpId && tocsByDumpId[depid - 1] &&
3912 strcmp(tocsByDumpId[depid - 1]->desc, "TABLE DATA") == 0)
3913 lockids[nlockids++] = depid;
3922 te->lockDeps = realloc(lockids, nlockids * sizeof(DumpId));
3923 te->nLockDeps = nlockids;
3927 * Remove the specified TOC entry from the depCounts of items that depend on
3928 * it, thereby possibly making them ready-to-run. Any pending item that
3929 * becomes ready should be moved to the ready list.
3932 reduce_dependencies(ArchiveHandle *AH, TocEntry *te, TocEntry *ready_list)
3934 DumpId target = te->dumpId;
3937 ahlog(AH, 2, "reducing dependencies for %d\n", target);
3940 * We must examine all entries, not only the ones after the target item,
3941 * because if the user used a -L switch then the original dependency-
3942 * respecting order has been destroyed by SortTocFromFile.
3944 for (te = AH->toc->next; te != AH->toc; te = te->next)
3946 for (i = 0; i < te->nDeps; i++)
3948 if (te->dependencies[i] == target)
3951 if (te->depCount == 0 && te->par_prev != NULL)
3953 /* It must be in the pending list, so remove it ... */
3954 par_list_remove(te);
3955 /* ... and add to ready_list */
3956 par_list_append(ready_list, te);
3964 * Set the created flag on the DATA member corresponding to the given
3968 mark_create_done(ArchiveHandle *AH, TocEntry *te)
3972 for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
3974 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
3975 strcmp(tes->tag, te->tag) == 0 &&
3976 strcmp(tes->namespace ? tes->namespace : "",
3977 te->namespace ? te->namespace : "") == 0)
3979 tes->created = true;
3986 * Mark the DATA member corresponding to the given TABLE member
3990 inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
3992 RestoreOptions *ropt = AH->ropt;
3995 ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
3998 for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
4000 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
4001 strcmp(tes->tag, te->tag) == 0 &&
4002 strcmp(tes->namespace ? tes->namespace : "",
4003 te->namespace ? te->namespace : "") == 0)
4005 /* mark it unwanted; we assume idWanted array already exists */
4006 ropt->idWanted[tes->dumpId - 1] = false;
4014 * Clone and de-clone routines used in parallel restoration.
4016 * Enough of the structure is cloned to ensure that there is no
4017 * conflict between different threads each with their own clone.
4019 * These could be public, but no need at present.
4021 static ArchiveHandle *
4022 CloneArchive(ArchiveHandle *AH)
4024 ArchiveHandle *clone;
4026 /* Make a "flat" copy */
4027 clone = (ArchiveHandle *) malloc(sizeof(ArchiveHandle));
4029 die_horribly(AH, modulename, "out of memory\n");
4030 memcpy(clone, AH, sizeof(ArchiveHandle));
4032 /* Handle format-independent fields */
4033 clone->pgCopyBuf = createPQExpBuffer();
4034 clone->sqlBuf = createPQExpBuffer();
4035 clone->sqlparse.tagBuf = NULL;
4037 /* The clone will have its own connection, so disregard connection state */
4038 clone->connection = NULL;
4039 clone->currUser = NULL;
4040 clone->currSchema = NULL;
4041 clone->currTablespace = NULL;
4042 clone->currWithOids = -1;
4044 /* savedPassword must be local in case we change it while connecting */
4045 if (clone->savedPassword)
4046 clone->savedPassword = strdup(clone->savedPassword);
4048 /* clone has its own error count, too */
4049 clone->public.n_errors = 0;
4051 /* Let the format-specific code have a chance too */
4052 (clone->ClonePtr) (clone);
4058 * Release clone-local storage.
4060 * Note: we assume any clone-local connection was already closed.
4063 DeCloneArchive(ArchiveHandle *AH)
4065 /* Clear format-specific state */
4066 (AH->DeClonePtr) (AH);
4068 /* Clear state allocated by CloneArchive */
4069 destroyPQExpBuffer(AH->pgCopyBuf);
4070 destroyPQExpBuffer(AH->sqlBuf);
4071 if (AH->sqlparse.tagBuf)
4072 destroyPQExpBuffer(AH->sqlparse.tagBuf);
4074 /* Clear any connection-local state */
4078 free(AH->currSchema);
4079 if (AH->currTablespace)
4080 free(AH->currTablespace);
4081 if (AH->savedPassword)
4082 free(AH->savedPassword);