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.179 2010/02/18 01:29:10 tgl 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: create+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->create && ropt->dropSchema)
220 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
223 * -1 is not compatible with -C, because we can't create a database inside
224 * a transaction block.
226 if (ropt->create && 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)
306 dumpTimestamp(AH, "Started on", AH->createDate);
308 if (ropt->single_txn)
311 StartTransaction(AH);
313 ahprintf(AH, "BEGIN;\n\n");
317 * Establish important parameter values right away.
319 _doSetFixedOutputState(AH);
321 AH->stage = STAGE_PROCESSING;
324 * Drop the items at the start, in reverse order
326 if (ropt->dropSchema)
328 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
332 reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
333 /* We want anything that's selected and has a dropStmt */
334 if (((reqs & (REQ_SCHEMA|REQ_DATA)) != 0) && te->dropStmt)
336 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
337 /* Select owner and schema as necessary */
338 _becomeOwner(AH, te);
339 _selectOutputSchema(AH, te->namespace);
341 ahprintf(AH, "%s", te->dropStmt);
346 * _selectOutputSchema may have set currSchema to reflect the effect
347 * of a "SET search_path" command it emitted. However, by now we may
348 * have dropped that schema; or it might not have existed in the first
349 * place. In either case the effective value of search_path will not
350 * be what we think. Forcibly reset currSchema so that we will
351 * re-establish the search_path setting when needed (after creating
354 * If we treated users as pg_dump'able objects then we'd need to reset
358 free(AH->currSchema);
359 AH->currSchema = NULL;
363 * In serial mode, we now process each non-ACL TOC entry.
365 * In parallel mode, turn control over to the parallel-restore logic.
367 if (ropt->number_of_jobs > 1 && ropt->useDB)
368 restore_toc_entries_parallel(AH);
371 for (te = AH->toc->next; te != AH->toc; te = te->next)
372 (void) restore_toc_entry(AH, te, ropt, false);
376 * Scan TOC again to output ownership commands and ACLs
378 for (te = AH->toc->next; te != AH->toc; te = te->next)
382 /* Work out what, if anything, we want from this entry */
383 reqs = _tocEntryRequired(te, ropt, true);
385 /* Both schema and data objects might now have ownership/ACLs */
386 if ((reqs & (REQ_SCHEMA|REQ_DATA)) != 0)
388 ahlog(AH, 1, "setting owner and privileges for %s %s\n",
390 _printTocEntry(AH, te, ropt, false, true);
394 if (ropt->single_txn)
397 CommitTransaction(AH);
399 ahprintf(AH, "COMMIT;\n\n");
402 if (AH->public.verbose)
403 dumpTimestamp(AH, "Completed on", time(NULL));
405 ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
408 * Clean up & we're done.
410 AH->stage = STAGE_FINALIZING;
412 if (ropt->filename || ropt->compression)
413 ResetOutput(AH, sav);
417 PQfinish(AH->connection);
418 AH->connection = NULL;
423 * Restore a single TOC item. Used in both parallel and non-parallel restore;
424 * is_parallel is true if we are in a worker child process.
426 * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
427 * the parallel parent has to make the corresponding status update.
430 restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
431 RestoreOptions *ropt, bool is_parallel)
439 /* Work out what, if anything, we want from this entry */
440 reqs = _tocEntryRequired(te, ropt, false);
442 /* Dump any relevant dump warnings to stderr */
443 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
445 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
446 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
447 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
448 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
453 if ((reqs & REQ_SCHEMA) != 0) /* We want the schema */
455 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
457 _printTocEntry(AH, te, ropt, false, false);
460 if (strcmp(te->desc, "TABLE") == 0)
462 if (AH->lastErrorTE == te)
465 * We failed to create the table. If
466 * --no-data-for-failed-tables was given, mark the
467 * corresponding TABLE DATA to be ignored.
469 * In the parallel case this must be done in the parent, so we
470 * just set the return value.
472 if (ropt->noDataForFailedTables)
475 retval = WORKER_INHIBIT_DATA;
477 inhibit_data_for_failed_table(AH, te);
483 * We created the table successfully. Mark the corresponding
484 * TABLE DATA for possible truncation.
486 * In the parallel case this must be done in the parent, so we
487 * just set the return value.
490 retval = WORKER_CREATE_DONE;
492 mark_create_done(AH, te);
496 /* If we created a DB, connect to it... */
497 if (strcmp(te->desc, "DATABASE") == 0)
499 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
500 _reconnectToDB(AH, te->tag);
501 ropt->dbname = strdup(te->tag);
506 * If we have a data component, then process it
508 if ((reqs & REQ_DATA) != 0)
511 * hadDumper will be set if there is genuine data component for this
512 * node. Otherwise, we need to check the defn field for statements
513 * that need to be executed in data-only restores.
518 * If we can output the data, then restore it.
520 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
522 _printTocEntry(AH, te, ropt, true, false);
524 if (strcmp(te->desc, "BLOBS") == 0 ||
525 strcmp(te->desc, "BLOB COMMENTS") == 0)
527 ahlog(AH, 1, "restoring %s\n", te->desc);
529 _selectOutputSchema(AH, "pg_catalog");
531 (*AH->PrintTocDataPtr) (AH, te, ropt);
535 _disableTriggersIfNecessary(AH, te, ropt);
537 /* Select owner and schema as necessary */
538 _becomeOwner(AH, te);
539 _selectOutputSchema(AH, te->namespace);
541 ahlog(AH, 1, "restoring data for table \"%s\"\n",
545 * In parallel restore, if we created the table earlier in
546 * the run then we wrap the COPY in a transaction and
547 * precede it with a TRUNCATE. If archiving is not on
548 * this prevents WAL-logging the COPY. This obtains a
549 * speedup similar to that from using single_txn mode in
550 * non-parallel restores.
552 if (is_parallel && te->created)
555 * Parallel restore is always talking directly to a
556 * server, so no need to see if we should issue BEGIN.
558 StartTransaction(AH);
561 * If the server version is >= 8.4, make sure we issue
562 * TRUNCATE with ONLY so that child tables are not
565 ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
566 (PQserverVersion(AH->connection) >= 80400 ?
572 * If we have a copy statement, use it. As of V1.3, these
573 * are separate to allow easy import from withing a
574 * database connection. Pre 1.3 archives can not use DB
575 * connections and are sent to output only.
577 * For V1.3+, the table data MUST have a copy statement so
578 * that we can go into appropriate mode with libpq.
580 if (te->copyStmt && strlen(te->copyStmt) > 0)
582 ahprintf(AH, "%s", te->copyStmt);
583 AH->writingCopyData = true;
586 (*AH->PrintTocDataPtr) (AH, te, ropt);
588 AH->writingCopyData = false;
590 /* close out the transaction started above */
591 if (is_parallel && te->created)
592 CommitTransaction(AH);
594 _enableTriggersIfNecessary(AH, te, ropt);
598 else if (!defnDumped)
600 /* If we haven't already dumped the defn part, do so now */
601 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
602 _printTocEntry(AH, te, ropt, false, false);
610 * Allocate a new RestoreOptions block.
611 * This is mainly so we can initialize it, but also for future expansion,
614 NewRestoreOptions(void)
616 RestoreOptions *opts;
618 opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
620 /* set any fields that shouldn't default to zeroes */
621 opts->format = archUnknown;
622 opts->promptPassword = TRI_DEFAULT;
628 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
630 /* This hack is only needed in a data-only restore */
631 if (!ropt->dataOnly || !ropt->disable_triggers)
634 ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
637 * Become superuser if possible, since they are the only ones who can
638 * disable constraint triggers. If -S was not given, assume the initial
639 * user identity is a superuser. (XXX would it be better to become the
642 _becomeUser(AH, ropt->superuser);
647 _selectOutputSchema(AH, te->namespace);
649 ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
654 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
656 /* This hack is only needed in a data-only restore */
657 if (!ropt->dataOnly || !ropt->disable_triggers)
660 ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
663 * Become superuser if possible, since they are the only ones who can
664 * disable constraint triggers. If -S was not given, assume the initial
665 * user identity is a superuser. (XXX would it be better to become the
668 _becomeUser(AH, ropt->superuser);
673 _selectOutputSchema(AH, te->namespace);
675 ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
680 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
685 WriteData(Archive *AHX, const void *data, size_t dLen)
687 ArchiveHandle *AH = (ArchiveHandle *) AHX;
690 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
692 return (*AH->WriteDataPtr) (AH, data, dLen);
696 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
697 * repository for all metadata. But the name has stuck.
702 ArchiveEntry(Archive *AHX,
703 CatalogId catalogId, DumpId dumpId,
705 const char *namespace,
706 const char *tablespace,
707 const char *owner, bool withOids,
708 const char *desc, teSection section,
710 const char *dropStmt, const char *copyStmt,
711 const DumpId *deps, int nDeps,
712 DataDumperPtr dumpFn, void *dumpArg)
714 ArchiveHandle *AH = (ArchiveHandle *) AHX;
717 newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
719 die_horribly(AH, modulename, "out of memory\n");
722 if (dumpId > AH->maxDumpId)
723 AH->maxDumpId = dumpId;
725 newToc->prev = AH->toc->prev;
726 newToc->next = AH->toc;
727 AH->toc->prev->next = newToc;
728 AH->toc->prev = newToc;
730 newToc->catalogId = catalogId;
731 newToc->dumpId = dumpId;
732 newToc->section = section;
734 newToc->tag = strdup(tag);
735 newToc->namespace = namespace ? strdup(namespace) : NULL;
736 newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
737 newToc->owner = strdup(owner);
738 newToc->withOids = withOids;
739 newToc->desc = strdup(desc);
740 newToc->defn = strdup(defn);
741 newToc->dropStmt = strdup(dropStmt);
742 newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
746 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
747 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
748 newToc->nDeps = nDeps;
752 newToc->dependencies = NULL;
756 newToc->dataDumper = dumpFn;
757 newToc->dataDumperArg = dumpArg;
758 newToc->hadDumper = dumpFn ? true : false;
760 newToc->formatData = NULL;
762 if (AH->ArchiveEntryPtr !=NULL)
763 (*AH->ArchiveEntryPtr) (AH, newToc);
768 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
770 ArchiveHandle *AH = (ArchiveHandle *) AHX;
776 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
778 ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
779 ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n",
780 AH->archdbname, AH->tocCount, AH->compression);
797 ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
798 ahprintf(AH, "; Format: %s\n", fmtName);
799 ahprintf(AH, "; Integer: %d bytes\n", (int) AH->intSize);
800 ahprintf(AH, "; Offset: %d bytes\n", (int) AH->offSize);
801 if (AH->archiveRemoteVersion)
802 ahprintf(AH, "; Dumped from database version: %s\n",
803 AH->archiveRemoteVersion);
804 if (AH->archiveDumpVersion)
805 ahprintf(AH, "; Dumped by pg_dump version: %s\n",
806 AH->archiveDumpVersion);
808 ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
810 for (te = AH->toc->next; te != AH->toc; te = te->next)
812 if (ropt->verbose || _tocEntryRequired(te, ropt, true) != 0)
813 ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
814 te->catalogId.tableoid, te->catalogId.oid,
815 te->desc, te->namespace ? te->namespace : "-",
817 if (ropt->verbose && te->nDeps > 0)
821 ahprintf(AH, ";\tdepends on:");
822 for (i = 0; i < te->nDeps; i++)
823 ahprintf(AH, " %d", te->dependencies[i]);
829 ResetOutput(AH, sav);
836 /* Called by a dumper to signal start of a BLOB */
838 StartBlob(Archive *AHX, Oid oid)
840 ArchiveHandle *AH = (ArchiveHandle *) AHX;
842 if (!AH->StartBlobPtr)
843 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
845 (*AH->StartBlobPtr) (AH, AH->currToc, oid);
850 /* Called by a dumper to signal end of a BLOB */
852 EndBlob(Archive *AHX, Oid oid)
854 ArchiveHandle *AH = (ArchiveHandle *) AHX;
857 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
867 * Called by a format handler before any blobs are restored
870 StartRestoreBlobs(ArchiveHandle *AH)
872 if (!AH->ropt->single_txn)
875 StartTransaction(AH);
877 ahprintf(AH, "BEGIN;\n\n");
884 * Called by a format handler after all blobs are restored
887 EndRestoreBlobs(ArchiveHandle *AH)
889 if (!AH->ropt->single_txn)
892 CommitTransaction(AH);
894 ahprintf(AH, "COMMIT;\n\n");
897 ahlog(AH, 1, ngettext("restored %d large object\n",
898 "restored %d large objects\n",
905 * Called by a format handler to initiate restoration of a blob
908 StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
910 bool old_blob_style = (AH->version < K_VERS_1_12);
915 /* Initialize the LO Buffer */
918 ahlog(AH, 2, "restoring large object with OID %u\n", oid);
920 /* With an old archive we must do drop and create logic here */
921 if (old_blob_style && drop)
922 DropBlobIfExists(AH, oid);
928 loOid = lo_create(AH->connection, oid);
929 if (loOid == 0 || loOid != oid)
930 die_horribly(AH, modulename, "could not create large object %u\n",
933 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
935 die_horribly(AH, modulename, "could not open large object %u\n",
941 ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
944 ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
952 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
954 if (AH->lo_buf_used > 0)
956 /* Write remaining bytes from the LO buffer */
964 lo_close(AH->connection, AH->loFd);
969 ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
974 * Sorting and Reordering
978 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
980 ArchiveHandle *AH = (ArchiveHandle *) AHX;
989 /* Allocate space for the 'wanted' array, and init it */
990 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
991 memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
993 /* Set prev entry as head of list */
997 fh = fopen(ropt->tocFile, PG_BINARY_R);
999 die_horribly(AH, modulename, "could not open TOC file \"%s\": %s\n",
1000 ropt->tocFile, strerror(errno));
1002 while (fgets(buf, sizeof(buf), fh) != NULL)
1004 /* Truncate line at comment, if any */
1005 cmnt = strchr(buf, ';');
1009 /* Ignore if all blank */
1010 if (strspn(buf, " \t\r") == strlen(buf))
1013 /* Get an ID, check it's valid and not already seen */
1014 id = strtol(buf, &endptr, 10);
1015 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
1016 ropt->idWanted[id - 1])
1018 write_msg(modulename, "WARNING: line ignored: %s\n", buf);
1022 /* Find TOC entry */
1023 te = getTocEntryByDumpId(AH, id);
1025 die_horribly(AH, modulename, "could not find entry for ID %d\n",
1028 ropt->idWanted[id - 1] = true;
1030 _moveAfter(AH, tePrev, te);
1034 if (fclose(fh) != 0)
1035 die_horribly(AH, modulename, "could not close TOC file: %s\n",
1040 * Set up a dummy ID filter that selects all dump IDs
1043 InitDummyWantedList(Archive *AHX, RestoreOptions *ropt)
1045 ArchiveHandle *AH = (ArchiveHandle *) AHX;
1047 /* Allocate space for the 'wanted' array, and init it to 1's */
1048 ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
1049 memset(ropt->idWanted, 1, sizeof(bool) * AH->maxDumpId);
1052 /**********************
1053 * 'Convenience functions that look like standard IO functions
1054 * for writing data when in dump mode.
1055 **********************/
1059 archputs(const char *s, Archive *AH)
1061 return WriteData(AH, s, strlen(s));
1066 archprintf(Archive *AH, const char *fmt,...)
1070 int bSize = strlen(fmt) + 256;
1074 * This is paranoid: deal with the possibility that vsnprintf is willing
1075 * to ignore trailing null or returns > 0 even if string does not fit. It
1076 * may be the case that it returns cnt = bufsize
1078 while (cnt < 0 || cnt >= (bSize - 1))
1083 p = (char *) malloc(bSize);
1085 exit_horribly(AH, modulename, "out of memory\n");
1087 cnt = vsnprintf(p, bSize, fmt, ap);
1090 WriteData(AH, p, cnt);
1096 /*******************************
1097 * Stuff below here should be 'private' to the archiver routines
1098 *******************************/
1100 static OutputContext
1101 SetOutput(ArchiveHandle *AH, char *filename, int compression)
1106 /* Replace the AH output file handle */
1108 sav.gzOut = AH->gzOut;
1113 fn = fileno(AH->FH);
1117 filename = AH->fSpec;
1120 fn = fileno(stdout);
1122 /* If compression explicitly requested, use gzopen */
1124 if (compression != 0)
1128 /* Don't use PG_BINARY_x since this is zlib */
1129 sprintf(fmode, "wb%d", compression);
1131 AH->OF = gzdopen(dup(fn), fmode);
1133 AH->OF = gzopen(filename, fmode);
1139 if (AH->mode == archModeAppend)
1142 AH->OF = fdopen(dup(fn), PG_BINARY_A);
1144 AH->OF = fopen(filename, PG_BINARY_A);
1149 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1151 AH->OF = fopen(filename, PG_BINARY_W);
1159 die_horribly(AH, modulename, "could not open output file \"%s\": %s\n",
1160 filename, strerror(errno));
1162 die_horribly(AH, modulename, "could not open output file: %s\n",
1170 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1175 res = GZCLOSE(AH->OF);
1177 res = fclose(AH->OF);
1180 die_horribly(AH, modulename, "could not close output file: %s\n",
1183 AH->gzOut = sav.gzOut;
1190 * Print formatted text to the output file (usually stdout).
1193 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1197 int bSize = strlen(fmt) + 256; /* Should be enough */
1201 * This is paranoid: deal with the possibility that vsnprintf is willing
1202 * to ignore trailing null
1206 * or returns > 0 even if string does not fit. It may be the case that it
1207 * returns cnt = bufsize
1209 while (cnt < 0 || cnt >= (bSize - 1))
1214 p = (char *) malloc(bSize);
1216 die_horribly(AH, modulename, "out of memory\n");
1218 cnt = vsnprintf(p, bSize, fmt, ap);
1221 ahwrite(p, 1, cnt, AH);
1227 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1231 if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1235 _write_msg(NULL, fmt, ap);
1240 * Single place for logic which says 'We are restoring to a direct DB connection'.
1243 RestoringToDB(ArchiveHandle *AH)
1245 return (AH->ropt && AH->ropt->useDB && AH->connection);
1249 * Dump the current contents of the LO data buffer while writing a BLOB
1252 dump_lo_buf(ArchiveHandle *AH)
1258 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1259 ahlog(AH, 5, ngettext("wrote %lu byte of large object data (result = %lu)\n",
1260 "wrote %lu bytes of large object data (result = %lu)\n",
1262 (unsigned long) AH->lo_buf_used, (unsigned long) res);
1263 if (res != AH->lo_buf_used)
1264 die_horribly(AH, modulename,
1265 "could not write to large object (result: %lu, expected: %lu)\n",
1266 (unsigned long) res, (unsigned long) AH->lo_buf_used);
1270 PQExpBuffer buf = createPQExpBuffer();
1272 appendByteaLiteralAHX(buf,
1273 (const unsigned char *) AH->lo_buf,
1277 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1278 AH->writingBlob = 0;
1279 ahprintf(AH, "SELECT pg_catalog.lowrite(0, %s);\n", buf->data);
1280 AH->writingBlob = 1;
1282 destroyPQExpBuffer(buf);
1284 AH->lo_buf_used = 0;
1289 * Write buffer to the output file (usually stdout). This is user for
1290 * outputting 'restore' scripts etc. It is even possible for an archive
1291 * format to create a custom output routine to 'fake' a restore if it
1292 * wants to generate a script (see TAR output).
1295 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1299 if (AH->writingBlob)
1301 size_t remaining = size * nmemb;
1303 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1305 size_t avail = AH->lo_buf_size - AH->lo_buf_used;
1307 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1308 ptr = (const void *) ((const char *) ptr + avail);
1310 AH->lo_buf_used += avail;
1314 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1315 AH->lo_buf_used += remaining;
1317 return size * nmemb;
1321 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1322 if (res != (nmemb * size))
1323 die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1326 else if (AH->CustomOutPtr)
1328 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1330 if (res != (nmemb * size))
1331 die_horribly(AH, modulename, "could not write to custom output routine\n");
1337 * If we're doing a restore, and it's direct to DB, and we're
1338 * connected then send it to the DB.
1340 if (RestoringToDB(AH))
1341 return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */
1344 res = fwrite((void *) ptr, size, nmemb, AH->OF);
1346 die_horribly(AH, modulename, "could not write to output file: %s\n",
1353 /* Common exit code */
1355 _write_msg(const char *modulename, const char *fmt, va_list ap)
1358 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1360 fprintf(stderr, "%s: ", progname);
1361 vfprintf(stderr, _(fmt), ap);
1365 write_msg(const char *modulename, const char *fmt,...)
1370 _write_msg(modulename, fmt, ap);
1376 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1378 _write_msg(modulename, fmt, ap);
1382 if (AH->public.verbose)
1383 write_msg(NULL, "*** aborted because of error\n");
1385 PQfinish(AH->connection);
1393 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1398 _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1402 /* Archiver use (just different arg declaration) */
1404 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1409 _die_horribly(AH, modulename, fmt, ap);
1413 /* on some error, we may decide to go on... */
1415 warn_or_die_horribly(ArchiveHandle *AH,
1416 const char *modulename, const char *fmt,...)
1424 /* Do nothing special */
1427 case STAGE_INITIALIZING:
1428 if (AH->stage != AH->lastErrorStage)
1429 write_msg(modulename, "Error while INITIALIZING:\n");
1432 case STAGE_PROCESSING:
1433 if (AH->stage != AH->lastErrorStage)
1434 write_msg(modulename, "Error while PROCESSING TOC:\n");
1437 case STAGE_FINALIZING:
1438 if (AH->stage != AH->lastErrorStage)
1439 write_msg(modulename, "Error while FINALIZING:\n");
1442 if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1444 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1445 AH->currentTE->dumpId,
1446 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1447 AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1449 AH->lastErrorStage = AH->stage;
1450 AH->lastErrorTE = AH->currentTE;
1453 if (AH->public.exit_on_error)
1454 _die_horribly(AH, modulename, fmt, ap);
1457 _write_msg(modulename, fmt, ap);
1458 AH->public.n_errors++;
1464 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1466 te->prev->next = te->next;
1467 te->next->prev = te->prev;
1470 te->next = pos->next;
1472 pos->next->prev = te;
1479 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1481 te->prev->next = te->next;
1482 te->next->prev = te->prev;
1484 te->prev = pos->prev;
1486 pos->prev->next = te;
1492 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1496 for (te = AH->toc->next; te != AH->toc; te = te->next)
1498 if (te->dumpId == id)
1505 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1507 TocEntry *te = getTocEntryByDumpId(AH, id);
1512 return _tocEntryRequired(te, ropt, true);
1516 WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1521 (*AH->WriteBytePtr) (AH, wasSet);
1523 /* Write out pgoff_t smallest byte first, prevents endian mismatch */
1524 for (off = 0; off < sizeof(pgoff_t); off++)
1526 (*AH->WriteBytePtr) (AH, o & 0xFF);
1529 return sizeof(pgoff_t) + 1;
1533 ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1539 /* Initialize to zero */
1542 /* Check for old version */
1543 if (AH->version < K_VERS_1_7)
1545 /* Prior versions wrote offsets using WriteInt */
1547 /* -1 means not set */
1549 return K_OFFSET_POS_NOT_SET;
1551 return K_OFFSET_NO_DATA;
1553 /* Cast to pgoff_t because it was written as an int. */
1555 return K_OFFSET_POS_SET;
1559 * Read the flag indicating the state of the data pointer. Check if valid
1562 * This used to be handled by a negative or zero pointer, now we use an
1563 * extra byte specifically for the state.
1565 offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1569 case K_OFFSET_POS_NOT_SET:
1570 case K_OFFSET_NO_DATA:
1571 case K_OFFSET_POS_SET:
1576 die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1582 for (off = 0; off < AH->offSize; off++)
1584 if (off < sizeof(pgoff_t))
1585 *o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1588 if ((*AH->ReadBytePtr) (AH) != 0)
1589 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1597 WriteInt(ArchiveHandle *AH, int i)
1602 * This is a bit yucky, but I don't want to make the binary format very
1603 * dependent on representation, and not knowing much about it, I write out
1604 * a sign byte. If you change this, don't forget to change the file
1605 * version #, and modify readInt to read the new format AS WELL AS the old
1612 (*AH->WriteBytePtr) (AH, 1);
1616 (*AH->WriteBytePtr) (AH, 0);
1618 for (b = 0; b < AH->intSize; b++)
1620 (*AH->WriteBytePtr) (AH, i & 0xFF);
1624 return AH->intSize + 1;
1628 ReadInt(ArchiveHandle *AH)
1633 int sign = 0; /* Default positive */
1636 if (AH->version > K_VERS_1_0)
1637 /* Read a sign byte */
1638 sign = (*AH->ReadBytePtr) (AH);
1640 for (b = 0; b < AH->intSize; b++)
1642 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1644 res = res + (bv << bitShift);
1655 WriteStr(ArchiveHandle *AH, const char *c)
1661 res = WriteInt(AH, strlen(c));
1662 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1665 res = WriteInt(AH, -1);
1671 ReadStr(ArchiveHandle *AH)
1681 buf = (char *) malloc(l + 1);
1683 die_horribly(AH, modulename, "out of memory\n");
1685 if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1686 die_horribly(AH, modulename, "unexpected end of file\n");
1695 _discoverArchiveFormat(ArchiveHandle *AH)
1698 char sig[6]; /* More than enough */
1703 write_msg(modulename, "attempting to ascertain archive format\n");
1707 free(AH->lookahead);
1709 AH->lookaheadSize = 512;
1710 AH->lookahead = calloc(1, 512);
1711 AH->lookaheadLen = 0;
1712 AH->lookaheadPos = 0;
1717 fh = fopen(AH->fSpec, PG_BINARY_R);
1719 die_horribly(AH, modulename, "could not open input file \"%s\": %s\n",
1720 AH->fSpec, strerror(errno));
1726 die_horribly(AH, modulename, "could not open input file: %s\n",
1730 cnt = fread(sig, 1, 5, fh);
1735 die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1737 die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1738 (unsigned long) cnt);
1741 /* Save it, just in case we need it later */
1742 strncpy(&AH->lookahead[0], sig, 5);
1743 AH->lookaheadLen = 5;
1745 if (strncmp(sig, "PGDMP", 5) == 0)
1747 AH->vmaj = fgetc(fh);
1748 AH->vmin = fgetc(fh);
1750 /* Save these too... */
1751 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1752 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1754 /* Check header version; varies from V1.0 */
1755 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
1757 AH->vrev = fgetc(fh);
1758 AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1763 /* Make a convenient integer <maj><min><rev>00 */
1764 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1766 AH->intSize = fgetc(fh);
1767 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1769 if (AH->version >= K_VERS_1_7)
1771 AH->offSize = fgetc(fh);
1772 AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1775 AH->offSize = AH->intSize;
1777 AH->format = fgetc(fh);
1778 AH->lookahead[AH->lookaheadLen++] = AH->format;
1783 * *Maybe* we have a tar archive format file... So, read first 512
1786 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1787 AH->lookaheadLen += cnt;
1789 if (AH->lookaheadLen != 512)
1790 die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1792 if (!isValidTarHeader(AH->lookahead))
1793 die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1795 AH->format = archTar;
1798 /* If we can't seek, then mark the header as read */
1799 if (fseeko(fh, 0, SEEK_SET) != 0)
1802 * NOTE: Formats that use the lookahead buffer can unset this in their
1808 AH->lookaheadLen = 0; /* Don't bother since we've reset the file */
1810 /* Close the file */
1812 if (fclose(fh) != 0)
1813 die_horribly(AH, modulename, "could not close input file: %s\n",
1821 * Allocate an archive handle
1823 static ArchiveHandle *
1824 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1825 const int compression, ArchiveMode mode)
1830 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1833 AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1835 die_horribly(AH, modulename, "out of memory\n");
1837 /* AH->debugLevel = 100; */
1839 AH->vmaj = K_VERS_MAJOR;
1840 AH->vmin = K_VERS_MINOR;
1841 AH->vrev = K_VERS_REV;
1843 /* Make a convenient integer <maj><min><rev>00 */
1844 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1846 /* initialize for backwards compatible string processing */
1847 AH->public.encoding = 0; /* PG_SQL_ASCII */
1848 AH->public.std_strings = false;
1850 /* sql error handling */
1851 AH->public.exit_on_error = true;
1852 AH->public.n_errors = 0;
1854 AH->createDate = time(NULL);
1856 AH->intSize = sizeof(int);
1857 AH->offSize = sizeof(pgoff_t);
1860 AH->fSpec = strdup(FileSpec);
1863 * Not used; maybe later....
1865 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1866 * i--) if (AH->workDir[i-1] == '/')
1872 AH->currUser = NULL; /* unknown */
1873 AH->currSchema = NULL; /* ditto */
1874 AH->currTablespace = NULL; /* ditto */
1875 AH->currWithOids = -1; /* force SET */
1877 AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1879 die_horribly(AH, modulename, "out of memory\n");
1881 AH->toc->next = AH->toc;
1882 AH->toc->prev = AH->toc;
1885 AH->compression = compression;
1887 AH->pgCopyBuf = createPQExpBuffer();
1888 AH->sqlBuf = createPQExpBuffer();
1890 /* Open stdout with no compression for AH output handle */
1895 * On Windows, we need to use binary mode to read/write non-text archive
1896 * formats. Force stdin/stdout into binary mode if that is what we are
1900 if (fmt != archNull &&
1901 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1903 if (mode == archModeWrite)
1904 setmode(fileno(stdout), O_BINARY);
1906 setmode(fileno(stdin), O_BINARY);
1910 if (fmt == archUnknown)
1911 AH->format = _discoverArchiveFormat(AH);
1915 AH->promptPassword = TRI_DEFAULT;
1920 InitArchiveFmt_Custom(AH);
1924 InitArchiveFmt_Files(AH);
1928 InitArchiveFmt_Null(AH);
1932 InitArchiveFmt_Tar(AH);
1936 die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1944 WriteDataChunks(ArchiveHandle *AH)
1947 StartDataPtr startPtr;
1950 for (te = AH->toc->next; te != AH->toc; te = te->next)
1952 if (te->dataDumper != NULL)
1955 /* printf("Writing data for %d (%x)\n", te->id, te); */
1957 if (strcmp(te->desc, "BLOBS") == 0)
1959 startPtr = AH->StartBlobsPtr;
1960 endPtr = AH->EndBlobsPtr;
1964 startPtr = AH->StartDataPtr;
1965 endPtr = AH->EndDataPtr;
1968 if (startPtr != NULL)
1969 (*startPtr) (AH, te);
1972 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1976 * The user-provided DataDumper routine needs to call
1979 (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1989 WriteToc(ArchiveHandle *AH)
1995 /* printf("%d TOC Entries to save\n", AH->tocCount); */
1997 WriteInt(AH, AH->tocCount);
1999 for (te = AH->toc->next; te != AH->toc; te = te->next)
2001 WriteInt(AH, te->dumpId);
2002 WriteInt(AH, te->dataDumper ? 1 : 0);
2004 /* OID is recorded as a string for historical reasons */
2005 sprintf(workbuf, "%u", te->catalogId.tableoid);
2006 WriteStr(AH, workbuf);
2007 sprintf(workbuf, "%u", te->catalogId.oid);
2008 WriteStr(AH, workbuf);
2010 WriteStr(AH, te->tag);
2011 WriteStr(AH, te->desc);
2012 WriteInt(AH, te->section);
2013 WriteStr(AH, te->defn);
2014 WriteStr(AH, te->dropStmt);
2015 WriteStr(AH, te->copyStmt);
2016 WriteStr(AH, te->namespace);
2017 WriteStr(AH, te->tablespace);
2018 WriteStr(AH, te->owner);
2019 WriteStr(AH, te->withOids ? "true" : "false");
2021 /* Dump list of dependencies */
2022 for (i = 0; i < te->nDeps; i++)
2024 sprintf(workbuf, "%d", te->dependencies[i]);
2025 WriteStr(AH, workbuf);
2027 WriteStr(AH, NULL); /* Terminate List */
2029 if (AH->WriteExtraTocPtr)
2030 (*AH->WriteExtraTocPtr) (AH, te);
2035 ReadToc(ArchiveHandle *AH)
2044 AH->tocCount = ReadInt(AH);
2047 for (i = 0; i < AH->tocCount; i++)
2049 te = (TocEntry *) calloc(1, sizeof(TocEntry));
2050 te->dumpId = ReadInt(AH);
2052 if (te->dumpId > AH->maxDumpId)
2053 AH->maxDumpId = te->dumpId;
2056 if (te->dumpId <= 0)
2057 die_horribly(AH, modulename,
2058 "entry ID %d out of range -- perhaps a corrupt TOC\n",
2061 te->hadDumper = ReadInt(AH);
2063 if (AH->version >= K_VERS_1_8)
2066 sscanf(tmp, "%u", &te->catalogId.tableoid);
2070 te->catalogId.tableoid = InvalidOid;
2072 sscanf(tmp, "%u", &te->catalogId.oid);
2075 te->tag = ReadStr(AH);
2076 te->desc = ReadStr(AH);
2078 if (AH->version >= K_VERS_1_11)
2080 te->section = ReadInt(AH);
2085 * Rules for pre-8.4 archives wherein pg_dump hasn't classified
2086 * the entries into sections. This list need not cover entry
2087 * types added later than 8.4.
2089 if (strcmp(te->desc, "COMMENT") == 0 ||
2090 strcmp(te->desc, "ACL") == 0 ||
2091 strcmp(te->desc, "ACL LANGUAGE") == 0)
2092 te->section = SECTION_NONE;
2093 else if (strcmp(te->desc, "TABLE DATA") == 0 ||
2094 strcmp(te->desc, "BLOBS") == 0 ||
2095 strcmp(te->desc, "BLOB COMMENTS") == 0)
2096 te->section = SECTION_DATA;
2097 else if (strcmp(te->desc, "CONSTRAINT") == 0 ||
2098 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2099 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2100 strcmp(te->desc, "INDEX") == 0 ||
2101 strcmp(te->desc, "RULE") == 0 ||
2102 strcmp(te->desc, "TRIGGER") == 0)
2103 te->section = SECTION_POST_DATA;
2105 te->section = SECTION_PRE_DATA;
2108 te->defn = ReadStr(AH);
2109 te->dropStmt = ReadStr(AH);
2111 if (AH->version >= K_VERS_1_3)
2112 te->copyStmt = ReadStr(AH);
2114 if (AH->version >= K_VERS_1_6)
2115 te->namespace = ReadStr(AH);
2117 if (AH->version >= K_VERS_1_10)
2118 te->tablespace = ReadStr(AH);
2120 te->owner = ReadStr(AH);
2121 if (AH->version >= K_VERS_1_9)
2123 if (strcmp(ReadStr(AH), "true") == 0)
2124 te->withOids = true;
2126 te->withOids = false;
2129 te->withOids = true;
2131 /* Read TOC entry dependencies */
2132 if (AH->version >= K_VERS_1_5)
2135 deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
2141 break; /* end of list */
2142 if (depIdx >= depSize)
2145 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
2147 sscanf(tmp, "%d", &deps[depIdx]);
2152 if (depIdx > 0) /* We have a non-null entry */
2154 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
2155 te->dependencies = deps;
2161 te->dependencies = NULL;
2167 te->dependencies = NULL;
2171 if (AH->ReadExtraTocPtr)
2172 (*AH->ReadExtraTocPtr) (AH, te);
2174 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
2175 i, te->dumpId, te->desc, te->tag);
2177 /* link completed entry into TOC circular list */
2178 te->prev = AH->toc->prev;
2179 AH->toc->prev->next = te;
2183 /* special processing immediately upon read for some items */
2184 if (strcmp(te->desc, "ENCODING") == 0)
2185 processEncodingEntry(AH, te);
2186 else if (strcmp(te->desc, "STDSTRINGS") == 0)
2187 processStdStringsEntry(AH, te);
2192 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
2194 /* te->defn should have the form SET client_encoding = 'foo'; */
2195 char *defn = strdup(te->defn);
2200 ptr1 = strchr(defn, '\'');
2202 ptr2 = strchr(++ptr1, '\'');
2206 encoding = pg_char_to_encoding(ptr1);
2208 die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
2210 AH->public.encoding = encoding;
2213 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
2220 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
2222 /* te->defn should have the form SET standard_conforming_strings = 'x'; */
2225 ptr1 = strchr(te->defn, '\'');
2226 if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
2227 AH->public.std_strings = true;
2228 else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
2229 AH->public.std_strings = false;
2231 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
2236 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
2238 teReqs res = REQ_ALL;
2240 /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
2241 if (strcmp(te->desc, "ENCODING") == 0 ||
2242 strcmp(te->desc, "STDSTRINGS") == 0)
2245 /* If it's an ACL, maybe ignore it */
2246 if ((!include_acls || ropt->aclsSkip) && _tocEntryIsACL(te))
2249 /* Ignore DATABASE entry unless we should create it */
2250 if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
2253 /* Check options for selective dump/restore */
2254 if (ropt->schemaNames)
2256 /* If no namespace is specified, it means all. */
2259 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2265 if (strcmp(te->desc, "TABLE") == 0 ||
2266 strcmp(te->desc, "TABLE DATA") == 0)
2268 if (!ropt->selTable)
2270 if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2273 else if (strcmp(te->desc, "INDEX") == 0)
2275 if (!ropt->selIndex)
2277 if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2280 else if (strcmp(te->desc, "FUNCTION") == 0)
2282 if (!ropt->selFunction)
2284 if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2287 else if (strcmp(te->desc, "TRIGGER") == 0)
2289 if (!ropt->selTrigger)
2291 if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2299 * Check if we had a dataDumper. Indicates if the entry is schema or data
2304 * Special Case: If 'SEQUENCE SET' or anything to do with BLOBs,
2305 * then it is considered a data entry. We don't need to check for
2306 * the BLOBS entry or old-style BLOB COMMENTS, because they will
2307 * have hadDumper = true ... but we do need to check new-style
2310 if (strcmp(te->desc, "SEQUENCE SET") == 0 ||
2311 strcmp(te->desc, "BLOB") == 0 ||
2312 (strcmp(te->desc, "ACL") == 0 &&
2313 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
2314 (strcmp(te->desc, "COMMENT") == 0 &&
2315 strncmp(te->tag, "LARGE OBJECT ", 13) == 0))
2316 res = res & REQ_DATA;
2318 res = res & ~REQ_DATA;
2322 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2325 if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2328 /* Mask it if we only want schema */
2329 if (ropt->schemaOnly)
2330 res = res & REQ_SCHEMA;
2332 /* Mask it we only want data */
2334 res = res & REQ_DATA;
2336 /* Mask it if we don't have a schema contribution */
2337 if (!te->defn || strlen(te->defn) == 0)
2338 res = res & ~REQ_SCHEMA;
2340 /* Finally, if there's a per-ID filter, limit based on that as well */
2341 if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2348 * Identify TOC entries that are ACLs.
2351 _tocEntryIsACL(TocEntry *te)
2353 /* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
2354 if (strcmp(te->desc, "ACL") == 0 ||
2355 strcmp(te->desc, "ACL LANGUAGE") == 0 ||
2356 strcmp(te->desc, "DEFAULT ACL") == 0)
2362 * Issue SET commands for parameters that we want to have set the same way
2363 * at all times during execution of a restore script.
2366 _doSetFixedOutputState(ArchiveHandle *AH)
2368 /* Disable statement_timeout in archive for pg_restore/psql */
2369 ahprintf(AH, "SET statement_timeout = 0;\n");
2371 /* Select the correct character set encoding */
2372 ahprintf(AH, "SET client_encoding = '%s';\n",
2373 pg_encoding_to_char(AH->public.encoding));
2375 /* Select the correct string literal syntax */
2376 ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2377 AH->public.std_strings ? "on" : "off");
2379 /* Select the role to be used during restore */
2380 if (AH->ropt && AH->ropt->use_role)
2381 ahprintf(AH, "SET ROLE %s;\n", fmtId(AH->ropt->use_role));
2383 /* Make sure function checking is disabled */
2384 ahprintf(AH, "SET check_function_bodies = false;\n");
2386 /* Avoid annoying notices etc */
2387 ahprintf(AH, "SET client_min_messages = warning;\n");
2388 if (!AH->public.std_strings)
2389 ahprintf(AH, "SET escape_string_warning = off;\n");
2395 * Issue a SET SESSION AUTHORIZATION command. Caller is responsible
2396 * for updating state if appropriate. If user is NULL or an empty string,
2397 * the specification DEFAULT will be used.
2400 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2402 PQExpBuffer cmd = createPQExpBuffer();
2404 appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2407 * SQL requires a string literal here. Might as well be correct.
2410 appendStringLiteralAHX(cmd, user, AH);
2412 appendPQExpBuffer(cmd, "DEFAULT");
2413 appendPQExpBuffer(cmd, ";");
2415 if (RestoringToDB(AH))
2419 res = PQexec(AH->connection, cmd->data);
2421 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2422 /* NOT warn_or_die_horribly... use -O instead to skip this. */
2423 die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2424 user, PQerrorMessage(AH->connection));
2429 ahprintf(AH, "%s\n\n", cmd->data);
2431 destroyPQExpBuffer(cmd);
2436 * Issue a SET default_with_oids command. Caller is responsible
2437 * for updating state if appropriate.
2440 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2442 PQExpBuffer cmd = createPQExpBuffer();
2444 appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2447 if (RestoringToDB(AH))
2451 res = PQexec(AH->connection, cmd->data);
2453 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2454 warn_or_die_horribly(AH, modulename,
2455 "could not set default_with_oids: %s",
2456 PQerrorMessage(AH->connection));
2461 ahprintf(AH, "%s\n\n", cmd->data);
2463 destroyPQExpBuffer(cmd);
2468 * Issue the commands to connect to the specified database.
2470 * If we're currently restoring right into a database, this will
2471 * actually establish a connection. Otherwise it puts a \connect into
2472 * the script output.
2474 * NULL dbname implies reconnecting to the current DB (pretty useless).
2477 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2479 if (RestoringToDB(AH))
2480 ReconnectToServer(AH, dbname, NULL);
2483 PQExpBuffer qry = createPQExpBuffer();
2485 appendPQExpBuffer(qry, "\\connect %s\n\n",
2486 dbname ? fmtId(dbname) : "-");
2487 ahprintf(AH, "%s", qry->data);
2488 destroyPQExpBuffer(qry);
2492 * NOTE: currUser keeps track of what the imaginary session user in our
2493 * script is. It's now effectively reset to the original userID.
2497 AH->currUser = NULL;
2499 /* don't assume we still know the output schema, tablespace, etc either */
2501 free(AH->currSchema);
2502 AH->currSchema = NULL;
2503 if (AH->currTablespace)
2504 free(AH->currTablespace);
2505 AH->currTablespace = NULL;
2506 AH->currWithOids = -1;
2508 /* re-establish fixed state */
2509 _doSetFixedOutputState(AH);
2513 * Become the specified user, and update state to avoid redundant commands
2515 * NULL or empty argument is taken to mean restoring the session default
2518 _becomeUser(ArchiveHandle *AH, const char *user)
2521 user = ""; /* avoid null pointers */
2523 if (AH->currUser && strcmp(AH->currUser, user) == 0)
2524 return; /* no need to do anything */
2526 _doSetSessionAuth(AH, user);
2529 * NOTE: currUser keeps track of what the imaginary session user in our
2534 AH->currUser = strdup(user);
2538 * Become the owner of the the given TOC entry object. If
2539 * changes in ownership are not allowed, this doesn't do anything.
2542 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2544 if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2547 _becomeUser(AH, te->owner);
2552 * Set the proper default_with_oids value for the table.
2555 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2557 if (AH->currWithOids != te->withOids)
2559 _doSetWithOids(AH, te->withOids);
2560 AH->currWithOids = te->withOids;
2566 * Issue the commands to select the specified schema as the current schema
2567 * in the target database.
2570 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2574 if (!schemaName || *schemaName == '\0' ||
2575 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2576 return; /* no need to do anything */
2578 qry = createPQExpBuffer();
2580 appendPQExpBuffer(qry, "SET search_path = %s",
2582 if (strcmp(schemaName, "pg_catalog") != 0)
2583 appendPQExpBuffer(qry, ", pg_catalog");
2585 if (RestoringToDB(AH))
2589 res = PQexec(AH->connection, qry->data);
2591 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2592 warn_or_die_horribly(AH, modulename,
2593 "could not set search_path to \"%s\": %s",
2594 schemaName, PQerrorMessage(AH->connection));
2599 ahprintf(AH, "%s;\n\n", qry->data);
2602 free(AH->currSchema);
2603 AH->currSchema = strdup(schemaName);
2605 destroyPQExpBuffer(qry);
2609 * Issue the commands to select the specified tablespace as the current one
2610 * in the target database.
2613 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2619 /* do nothing in --no-tablespaces mode */
2620 if (AH->ropt->noTablespace)
2623 have = AH->currTablespace;
2626 /* no need to do anything for non-tablespace object */
2630 if (have && strcmp(want, have) == 0)
2631 return; /* no need to do anything */
2633 qry = createPQExpBuffer();
2635 if (strcmp(want, "") == 0)
2637 /* We want the tablespace to be the database's default */
2638 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2642 /* We want an explicit tablespace */
2643 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2646 if (RestoringToDB(AH))
2650 res = PQexec(AH->connection, qry->data);
2652 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2653 warn_or_die_horribly(AH, modulename,
2654 "could not set default_tablespace to %s: %s",
2655 fmtId(want), PQerrorMessage(AH->connection));
2660 ahprintf(AH, "%s;\n\n", qry->data);
2662 if (AH->currTablespace)
2663 free(AH->currTablespace);
2664 AH->currTablespace = strdup(want);
2666 destroyPQExpBuffer(qry);
2670 * Extract an object description for a TOC entry, and append it to buf.
2672 * This is not quite as general as it may seem, since it really only
2673 * handles constructing the right thing to put into ALTER ... OWNER TO.
2675 * The whole thing is pretty grotty, but we are kind of stuck since the
2676 * information used is all that's available in older dump files.
2679 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2681 const char *type = te->desc;
2683 /* Use ALTER TABLE for views and sequences */
2684 if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2687 /* objects named by a schema and name */
2688 if (strcmp(type, "CONVERSION") == 0 ||
2689 strcmp(type, "DOMAIN") == 0 ||
2690 strcmp(type, "TABLE") == 0 ||
2691 strcmp(type, "TYPE") == 0 ||
2692 strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
2693 strcmp(type, "TEXT SEARCH CONFIGURATION") == 0)
2695 appendPQExpBuffer(buf, "%s ", type);
2696 if (te->namespace && te->namespace[0]) /* is null pre-7.3 */
2697 appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2700 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2701 * into te->tag for an index. This check is heuristic, so make its
2702 * scope as narrow as possible.
2704 if (AH->version < K_VERS_1_7 &&
2705 te->tag[0] == '"' &&
2706 te->tag[strlen(te->tag) - 1] == '"' &&
2707 strcmp(type, "INDEX") == 0)
2708 appendPQExpBuffer(buf, "%s", te->tag);
2710 appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2714 /* objects named by just a name */
2715 if (strcmp(type, "DATABASE") == 0 ||
2716 strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
2717 strcmp(type, "SCHEMA") == 0 ||
2718 strcmp(type, "FOREIGN DATA WRAPPER") == 0 ||
2719 strcmp(type, "SERVER") == 0 ||
2720 strcmp(type, "USER MAPPING") == 0)
2722 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2726 /* BLOBs just have a name, but it's numeric so must not use fmtId */
2727 if (strcmp(type, "BLOB") == 0)
2729 appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
2734 * These object types require additional decoration. Fortunately, the
2735 * information needed is exactly what's in the DROP command.
2737 if (strcmp(type, "AGGREGATE") == 0 ||
2738 strcmp(type, "FUNCTION") == 0 ||
2739 strcmp(type, "OPERATOR") == 0 ||
2740 strcmp(type, "OPERATOR CLASS") == 0 ||
2741 strcmp(type, "OPERATOR FAMILY") == 0)
2743 /* Chop "DROP " off the front and make a modifiable copy */
2744 char *first = strdup(te->dropStmt + 5);
2747 /* point to last character in string */
2748 last = first + strlen(first) - 1;
2750 /* Strip off any ';' or '\n' at the end */
2751 while (last >= first && (*last == '\n' || *last == ';'))
2755 appendPQExpBufferStr(buf, first);
2761 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2766 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2768 /* ACLs are dumped only during acl pass */
2771 if (!_tocEntryIsACL(te))
2776 if (_tocEntryIsACL(te))
2781 * Avoid dumping the public schema, as it will already be created ...
2782 * unless we are using --clean mode, in which case it's been deleted and
2783 * we'd better recreate it. Likewise for its comment, if any.
2785 if (!ropt->dropSchema)
2787 if (strcmp(te->desc, "SCHEMA") == 0 &&
2788 strcmp(te->tag, "public") == 0)
2790 /* The comment restore would require super-user privs, so avoid it. */
2791 if (strcmp(te->desc, "COMMENT") == 0 &&
2792 strcmp(te->tag, "SCHEMA public") == 0)
2796 /* Select owner, schema, and tablespace as necessary */
2797 _becomeOwner(AH, te);
2798 _selectOutputSchema(AH, te->namespace);
2799 _selectTablespace(AH, te->tablespace);
2801 /* Set up OID mode too */
2802 if (strcmp(te->desc, "TABLE") == 0)
2803 _setWithOids(AH, te);
2805 /* Emit header comment for item */
2806 if (!AH->noTocComments)
2815 ahprintf(AH, "--\n");
2816 if (AH->public.verbose)
2818 ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2819 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2824 ahprintf(AH, "-- Dependencies:");
2825 for (i = 0; i < te->nDeps; i++)
2826 ahprintf(AH, " %d", te->dependencies[i]);
2830 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2831 pfx, te->tag, te->desc,
2832 te->namespace ? te->namespace : "-",
2833 ropt->noOwner ? "-" : te->owner);
2834 if (te->tablespace && !ropt->noTablespace)
2835 ahprintf(AH, "; Tablespace: %s", te->tablespace);
2838 if (AH->PrintExtraTocPtr !=NULL)
2839 (*AH->PrintExtraTocPtr) (AH, te);
2840 ahprintf(AH, "--\n\n");
2844 * Actually print the definition.
2846 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2847 * versions put into CREATE SCHEMA. We have to do this when --no-owner
2848 * mode is selected. This is ugly, but I see no other good way ...
2850 if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2852 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2856 if (strlen(te->defn) > 0)
2857 ahprintf(AH, "%s\n\n", te->defn);
2861 * If we aren't using SET SESSION AUTH to determine ownership, we must
2862 * instead issue an ALTER OWNER command. We assume that anything without
2863 * a DROP command is not a separately ownable object. All the categories
2864 * with DROP commands must appear in one list or the other.
2866 if (!ropt->noOwner && !ropt->use_setsessauth &&
2867 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2869 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2870 strcmp(te->desc, "BLOB") == 0 ||
2871 strcmp(te->desc, "CONVERSION") == 0 ||
2872 strcmp(te->desc, "DATABASE") == 0 ||
2873 strcmp(te->desc, "DOMAIN") == 0 ||
2874 strcmp(te->desc, "FUNCTION") == 0 ||
2875 strcmp(te->desc, "OPERATOR") == 0 ||
2876 strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2877 strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
2878 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2879 strcmp(te->desc, "SCHEMA") == 0 ||
2880 strcmp(te->desc, "TABLE") == 0 ||
2881 strcmp(te->desc, "TYPE") == 0 ||
2882 strcmp(te->desc, "VIEW") == 0 ||
2883 strcmp(te->desc, "SEQUENCE") == 0 ||
2884 strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
2885 strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0 ||
2886 strcmp(te->desc, "FOREIGN DATA WRAPPER") == 0 ||
2887 strcmp(te->desc, "SERVER") == 0)
2889 PQExpBuffer temp = createPQExpBuffer();
2891 appendPQExpBuffer(temp, "ALTER ");
2892 _getObjectDescription(temp, te, AH);
2893 appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2894 ahprintf(AH, "%s\n\n", temp->data);
2895 destroyPQExpBuffer(temp);
2897 else if (strcmp(te->desc, "CAST") == 0 ||
2898 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2899 strcmp(te->desc, "CONSTRAINT") == 0 ||
2900 strcmp(te->desc, "DEFAULT") == 0 ||
2901 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2902 strcmp(te->desc, "INDEX") == 0 ||
2903 strcmp(te->desc, "RULE") == 0 ||
2904 strcmp(te->desc, "TRIGGER") == 0 ||
2905 strcmp(te->desc, "USER MAPPING") == 0)
2907 /* these object types don't have separate owners */
2911 write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2917 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2918 * commands, so we can no longer assume we know the current auth setting.
2924 AH->currUser = NULL;
2929 WriteHead(ArchiveHandle *AH)
2933 (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */
2934 (*AH->WriteBytePtr) (AH, AH->vmaj);
2935 (*AH->WriteBytePtr) (AH, AH->vmin);
2936 (*AH->WriteBytePtr) (AH, AH->vrev);
2937 (*AH->WriteBytePtr) (AH, AH->intSize);
2938 (*AH->WriteBytePtr) (AH, AH->offSize);
2939 (*AH->WriteBytePtr) (AH, AH->format);
2942 if (AH->compression != 0)
2943 write_msg(modulename, "WARNING: requested compression not available in this "
2944 "installation -- archive will be uncompressed\n");
2946 AH->compression = 0;
2949 WriteInt(AH, AH->compression);
2951 crtm = *localtime(&AH->createDate);
2952 WriteInt(AH, crtm.tm_sec);
2953 WriteInt(AH, crtm.tm_min);
2954 WriteInt(AH, crtm.tm_hour);
2955 WriteInt(AH, crtm.tm_mday);
2956 WriteInt(AH, crtm.tm_mon);
2957 WriteInt(AH, crtm.tm_year);
2958 WriteInt(AH, crtm.tm_isdst);
2959 WriteStr(AH, PQdb(AH->connection));
2960 WriteStr(AH, AH->public.remoteVersionStr);
2961 WriteStr(AH, PG_VERSION);
2965 ReadHead(ArchiveHandle *AH)
2971 /* If we haven't already read the header... */
2972 if (!AH->readHeader)
2974 if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
2975 die_horribly(AH, modulename, "unexpected end of file\n");
2977 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2978 die_horribly(AH, modulename, "did not find magic string in file header\n");
2980 AH->vmaj = (*AH->ReadBytePtr) (AH);
2981 AH->vmin = (*AH->ReadBytePtr) (AH);
2983 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */
2984 AH->vrev = (*AH->ReadBytePtr) (AH);
2988 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2991 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2992 die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2993 AH->vmaj, AH->vmin);
2995 AH->intSize = (*AH->ReadBytePtr) (AH);
2996 if (AH->intSize > 32)
2997 die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2998 (unsigned long) AH->intSize);
3000 if (AH->intSize > sizeof(int))
3001 write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations might fail\n");
3003 if (AH->version >= K_VERS_1_7)
3004 AH->offSize = (*AH->ReadBytePtr) (AH);
3006 AH->offSize = AH->intSize;
3008 fmt = (*AH->ReadBytePtr) (AH);
3010 if (AH->format != fmt)
3011 die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
3015 if (AH->version >= K_VERS_1_2)
3017 if (AH->version < K_VERS_1_4)
3018 AH->compression = (*AH->ReadBytePtr) (AH);
3020 AH->compression = ReadInt(AH);
3023 AH->compression = Z_DEFAULT_COMPRESSION;
3026 if (AH->compression != 0)
3027 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
3030 if (AH->version >= K_VERS_1_4)
3032 crtm.tm_sec = ReadInt(AH);
3033 crtm.tm_min = ReadInt(AH);
3034 crtm.tm_hour = ReadInt(AH);
3035 crtm.tm_mday = ReadInt(AH);
3036 crtm.tm_mon = ReadInt(AH);
3037 crtm.tm_year = ReadInt(AH);
3038 crtm.tm_isdst = ReadInt(AH);
3040 AH->archdbname = ReadStr(AH);
3042 AH->createDate = mktime(&crtm);
3044 if (AH->createDate == (time_t) -1)
3045 write_msg(modulename, "WARNING: invalid creation date in header\n");
3048 if (AH->version >= K_VERS_1_10)
3050 AH->archiveRemoteVersion = ReadStr(AH);
3051 AH->archiveDumpVersion = ReadStr(AH);
3059 * check to see if fseek can be performed.
3064 if (fseeko(fp, 0, SEEK_CUR) != 0)
3066 else if (sizeof(pgoff_t) > sizeof(long))
3069 * At this point, pgoff_t is too large for long, so we return based on
3070 * whether an pgoff_t version of fseek is available.
3087 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
3092 * We don't print the timezone on Win32, because the names are long and
3093 * localized, which means they may contain characters in various random
3094 * encodings; this has been seen to cause encoding errors when reading the
3097 if (strftime(buf, sizeof(buf),
3099 "%Y-%m-%d %H:%M:%S %Z",
3101 "%Y-%m-%d %H:%M:%S",
3103 localtime(&tim)) != 0)
3104 ahprintf(AH, "-- %s %s\n\n", msg, buf);
3109 * Main engine for parallel restore.
3111 * Work is done in three phases.
3112 * First we process tocEntries until we come to one that is marked
3113 * SECTION_DATA or SECTION_POST_DATA, in a single connection, just as for a
3114 * standard restore. Second we process the remaining non-ACL steps in
3115 * parallel worker children (threads on Windows, processes on Unix), each of
3116 * which connects separately to the database. Finally we process all the ACL
3117 * entries in a single connection (that happens back in RestoreArchive).
3120 restore_toc_entries_parallel(ArchiveHandle *AH)
3122 RestoreOptions *ropt = AH->ropt;
3123 int n_slots = ropt->number_of_jobs;
3124 ParallelSlot *slots;
3127 TocEntry pending_list;
3128 TocEntry ready_list;
3129 TocEntry *next_work_item;
3133 ahlog(AH, 2, "entering restore_toc_entries_parallel\n");
3135 /* we haven't got round to making this work for all archive formats */
3136 if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
3137 die_horribly(AH, modulename, "parallel restore is not supported with this archive file format\n");
3139 /* doesn't work if the archive represents dependencies as OIDs, either */
3140 if (AH->version < K_VERS_1_8)
3141 die_horribly(AH, modulename, "parallel restore is not supported with archives made by pre-8.0 pg_dump\n");
3143 slots = (ParallelSlot *) calloc(sizeof(ParallelSlot), n_slots);
3145 /* Adjust dependency information */
3146 fix_dependencies(AH);
3149 * Do all the early stuff in a single connection in the parent. There's no
3150 * great point in running it in parallel, in fact it will actually run
3151 * faster in a single connection because we avoid all the connection and
3154 for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3156 if (next_work_item->section == SECTION_DATA ||
3157 next_work_item->section == SECTION_POST_DATA)
3160 ahlog(AH, 1, "processing item %d %s %s\n",
3161 next_work_item->dumpId,
3162 next_work_item->desc, next_work_item->tag);
3164 (void) restore_toc_entry(AH, next_work_item, ropt, false);
3166 /* there should be no touch of ready_list here, so pass NULL */
3167 reduce_dependencies(AH, next_work_item, NULL);
3171 * Now close parent connection in prep for parallel steps. We do this
3172 * mainly to ensure that we don't exceed the specified number of parallel
3175 PQfinish(AH->connection);
3176 AH->connection = NULL;
3178 /* blow away any transient state from the old connection */
3181 AH->currUser = NULL;
3183 free(AH->currSchema);
3184 AH->currSchema = NULL;
3185 if (AH->currTablespace)
3186 free(AH->currTablespace);
3187 AH->currTablespace = NULL;
3188 AH->currWithOids = -1;
3191 * Initialize the lists of pending and ready items. After this setup,
3192 * the pending list is everything that needs to be done but is blocked
3193 * by one or more dependencies, while the ready list contains items that
3194 * have no remaining dependencies. Note: we don't yet filter out entries
3195 * that aren't going to be restored. They might participate in
3196 * dependency chains connecting entries that should be restored, so we
3197 * treat them as live until we actually process them.
3199 par_list_header_init(&pending_list);
3200 par_list_header_init(&ready_list);
3201 for (; next_work_item != AH->toc; next_work_item = next_work_item->next)
3203 if (next_work_item->depCount > 0)
3204 par_list_append(&pending_list, next_work_item);
3206 par_list_append(&ready_list, next_work_item);
3212 * Keep going until there is no worker still running AND there is no work
3216 ahlog(AH, 1, "entering main parallel loop\n");
3218 while ((next_work_item = get_next_work_item(AH, &ready_list,
3219 slots, n_slots)) != NULL ||
3220 work_in_progress(slots, n_slots))
3222 if (next_work_item != NULL)
3226 /* If not to be dumped, don't waste time launching a worker */
3227 reqs = _tocEntryRequired(next_work_item, AH->ropt, false);
3228 if ((reqs & (REQ_SCHEMA | REQ_DATA)) == 0)
3230 ahlog(AH, 1, "skipping item %d %s %s\n",
3231 next_work_item->dumpId,
3232 next_work_item->desc, next_work_item->tag);
3234 par_list_remove(next_work_item);
3235 reduce_dependencies(AH, next_work_item, &ready_list);
3240 if ((next_slot = get_next_slot(slots, n_slots)) != NO_SLOT)
3242 /* There is work still to do and a worker slot available */
3246 ahlog(AH, 1, "launching item %d %s %s\n",
3247 next_work_item->dumpId,
3248 next_work_item->desc, next_work_item->tag);
3250 par_list_remove(next_work_item);
3252 /* this memory is dealloced in mark_work_done() */
3253 args = malloc(sizeof(RestoreArgs));
3254 args->AH = CloneArchive(AH);
3255 args->te = next_work_item;
3257 /* run the step in a worker child */
3258 child = spawn_restore(args);
3260 slots[next_slot].child_id = child;
3261 slots[next_slot].args = args;
3268 * If we get here there must be work being done. Either there is no
3269 * work available to schedule (and work_in_progress returned true) or
3270 * there are no slots available. So we wait for a worker to finish,
3271 * and process the result.
3273 ret_child = reap_child(slots, n_slots, &work_status);
3275 if (WIFEXITED(work_status))
3277 mark_work_done(AH, &ready_list,
3278 ret_child, WEXITSTATUS(work_status),
3283 die_horribly(AH, modulename, "worker process crashed: status %d\n",
3288 ahlog(AH, 1, "finished main parallel loop\n");
3291 * Now reconnect the single parent connection.
3293 ConnectDatabase((Archive *) AH, ropt->dbname,
3294 ropt->pghost, ropt->pgport, ropt->username,
3295 ropt->promptPassword);
3297 _doSetFixedOutputState(AH);
3300 * Make sure there is no non-ACL work left due to, say, circular
3301 * dependencies, or some other pathological condition. If so, do it in the
3302 * single parent connection.
3304 for (te = pending_list.par_next; te != &pending_list; te = te->par_next)
3306 ahlog(AH, 1, "processing missed item %d %s %s\n",
3307 te->dumpId, te->desc, te->tag);
3308 (void) restore_toc_entry(AH, te, ropt, false);
3311 /* The ACLs will be handled back in RestoreArchive. */
3315 * create a worker child to perform a restore step in parallel
3318 spawn_restore(RestoreArgs *args)
3322 /* Ensure stdio state is quiesced before forking */
3329 /* in child process */
3330 parallel_restore(args);
3331 die_horribly(args->AH, modulename,
3332 "parallel_restore should not return\n");
3337 die_horribly(args->AH, modulename,
3338 "could not create worker process: %s\n",
3342 child = (HANDLE) _beginthreadex(NULL, 0, (void *) parallel_restore,
3345 die_horribly(args->AH, modulename,
3346 "could not create worker thread: %s\n",
3354 * collect status from a completed worker child
3357 reap_child(ParallelSlot *slots, int n_slots, int *work_status)
3360 /* Unix is so much easier ... */
3361 return wait(work_status);
3363 static HANDLE *handles = NULL;
3370 /* first time around only, make space for handles to listen on */
3371 if (handles == NULL)
3372 handles = (HANDLE *) calloc(sizeof(HANDLE), n_slots);
3374 /* set up list of handles to listen to */
3375 for (snum = 0, tnum = 0; snum < n_slots; snum++)
3376 if (slots[snum].child_id != 0)
3377 handles[tnum++] = slots[snum].child_id;
3379 /* wait for one to finish */
3380 hindex = WaitForMultipleObjects(tnum, handles, false, INFINITE);
3382 /* get handle of finished thread */
3383 ret_child = handles[hindex - WAIT_OBJECT_0];
3385 /* get the result */
3386 GetExitCodeThread(ret_child, &res);
3389 /* dispose of handle to stop leaks */
3390 CloseHandle(ret_child);
3397 * are we doing anything now?
3400 work_in_progress(ParallelSlot *slots, int n_slots)
3404 for (i = 0; i < n_slots; i++)
3406 if (slots[i].child_id != 0)
3413 * find the first free parallel slot (if any).
3416 get_next_slot(ParallelSlot *slots, int n_slots)
3420 for (i = 0; i < n_slots; i++)
3422 if (slots[i].child_id == 0)
3430 * Check if te1 has an exclusive lock requirement for an item that te2 also
3431 * requires, whether or not te2's requirement is for an exclusive lock.
3434 has_lock_conflicts(TocEntry *te1, TocEntry *te2)
3439 for (j = 0; j < te1->nLockDeps; j++)
3441 for (k = 0; k < te2->nDeps; k++)
3443 if (te1->lockDeps[j] == te2->dependencies[k])
3452 * Initialize the header of a parallel-processing list.
3454 * These are circular lists with a dummy TocEntry as header, just like the
3455 * main TOC list; but we use separate list links so that an entry can be in
3456 * the main TOC list as well as in a parallel-processing list.
3459 par_list_header_init(TocEntry *l)
3461 l->par_prev = l->par_next = l;
3464 /* Append te to the end of the parallel-processing list headed by l */
3466 par_list_append(TocEntry *l, TocEntry *te)
3468 te->par_prev = l->par_prev;
3469 l->par_prev->par_next = te;
3474 /* Remove te from whatever parallel-processing list it's in */
3476 par_list_remove(TocEntry *te)
3478 te->par_prev->par_next = te->par_next;
3479 te->par_next->par_prev = te->par_prev;
3480 te->par_prev = NULL;
3481 te->par_next = NULL;
3486 * Find the next work item (if any) that is capable of being run now.
3488 * To qualify, the item must have no remaining dependencies
3489 * and no requirements for locks that are incompatible with
3490 * items currently running. Items in the ready_list are known to have
3491 * no remaining dependencies, but we have to check for lock conflicts.
3493 * Note that the returned item has *not* been removed from ready_list.
3494 * The caller must do that after successfully dispatching the item.
3496 * pref_non_data is for an alternative selection algorithm that gives
3497 * preference to non-data items if there is already a data load running.
3498 * It is currently disabled.
3501 get_next_work_item(ArchiveHandle *AH, TocEntry *ready_list,
3502 ParallelSlot *slots, int n_slots)
3504 bool pref_non_data = false; /* or get from AH->ropt */
3505 TocEntry *data_te = NULL;
3511 * Bogus heuristics for pref_non_data
3517 for (k = 0; k < n_slots; k++)
3518 if (slots[k].args->te != NULL &&
3519 slots[k].args->te->section == SECTION_DATA)
3521 if (n_slots == 0 || count * 4 < n_slots)
3522 pref_non_data = false;
3526 * Search the ready_list until we find a suitable item.
3528 for (te = ready_list->par_next; te != ready_list; te = te->par_next)
3530 bool conflicts = false;
3533 * Check to see if the item would need exclusive lock on something
3534 * that a currently running item also needs lock on, or vice versa. If
3535 * so, we don't want to schedule them together.
3537 for (i = 0; i < n_slots && !conflicts; i++)
3539 TocEntry *running_te;
3541 if (slots[i].args == NULL)
3543 running_te = slots[i].args->te;
3545 if (has_lock_conflicts(te, running_te) ||
3546 has_lock_conflicts(running_te, te))
3556 if (pref_non_data && te->section == SECTION_DATA)
3558 if (data_te == NULL)
3563 /* passed all tests, so this item can run */
3567 if (data_te != NULL)
3570 ahlog(AH, 2, "no item ready\n");
3576 * Restore a single TOC item in parallel with others
3578 * this is the procedure run as a thread (Windows) or a
3579 * separate process (everything else).
3581 static parallel_restore_result
3582 parallel_restore(RestoreArgs *args)
3584 ArchiveHandle *AH = args->AH;
3585 TocEntry *te = args->te;
3586 RestoreOptions *ropt = AH->ropt;
3590 * Close and reopen the input file so we have a private file pointer that
3591 * doesn't stomp on anyone else's file pointer, if we're actually going to
3592 * need to read from the file. Otherwise, just close it except on Windows,
3593 * where it will possibly be needed by other threads.
3595 * Note: on Windows, since we are using threads not processes, the reopen
3596 * call *doesn't* close the original file pointer but just open a new one.
3598 if (te->section == SECTION_DATA)
3599 (AH->ReopenPtr) (AH);
3602 (AH->ClosePtr) (AH);
3606 * We need our own database connection, too
3608 ConnectDatabase((Archive *) AH, ropt->dbname,
3609 ropt->pghost, ropt->pgport, ropt->username,
3610 ropt->promptPassword);
3612 _doSetFixedOutputState(AH);
3614 /* Restore the TOC item */
3615 retval = restore_toc_entry(AH, te, ropt, true);
3618 PQfinish(AH->connection);
3619 AH->connection = NULL;
3621 /* If we reopened the file, we are done with it, so close it now */
3622 if (te->section == SECTION_DATA)
3623 (AH->ClosePtr) (AH);
3625 if (retval == 0 && AH->public.n_errors)
3626 retval = WORKER_IGNORED_ERRORS;
3637 * Housekeeping to be done after a step has been parallel restored.
3639 * Clear the appropriate slot, free all the extra memory we allocated,
3640 * update status, and reduce the dependency count of any dependent items.
3643 mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
3644 thandle worker, int status,
3645 ParallelSlot *slots, int n_slots)
3647 TocEntry *te = NULL;
3650 for (i = 0; i < n_slots; i++)
3652 if (slots[i].child_id == worker)
3654 slots[i].child_id = 0;
3655 te = slots[i].args->te;
3656 DeCloneArchive(slots[i].args->AH);
3657 free(slots[i].args);
3658 slots[i].args = NULL;
3665 die_horribly(AH, modulename, "could not find slot of finished worker\n");
3667 ahlog(AH, 1, "finished item %d %s %s\n",
3668 te->dumpId, te->desc, te->tag);
3670 if (status == WORKER_CREATE_DONE)
3671 mark_create_done(AH, te);
3672 else if (status == WORKER_INHIBIT_DATA)
3674 inhibit_data_for_failed_table(AH, te);
3675 AH->public.n_errors++;
3677 else if (status == WORKER_IGNORED_ERRORS)
3678 AH->public.n_errors++;
3679 else if (status != 0)
3680 die_horribly(AH, modulename, "worker process failed: exit code %d\n",
3683 reduce_dependencies(AH, te, ready_list);
3688 * Process the dependency information into a form useful for parallel restore.
3690 * We set up depCount fields that are the number of as-yet-unprocessed
3691 * dependencies for each TOC entry.
3693 * We also identify locking dependencies so that we can avoid trying to
3694 * schedule conflicting items at the same time.
3697 fix_dependencies(ArchiveHandle *AH)
3699 TocEntry **tocsByDumpId;
3705 * For some of the steps here, it is convenient to have an array that
3706 * indexes the TOC entries by dump ID, rather than searching the TOC list
3707 * repeatedly. Entries for dump IDs not present in the TOC will be NULL.
3709 * NOTE: because maxDumpId is just the highest dump ID defined in the
3710 * archive, there might be dependencies for IDs > maxDumpId. All uses
3711 * of this array must guard against out-of-range dependency numbers.
3713 * Also, initialize the depCount fields, and make sure all the TOC items
3714 * are marked as not being in any parallel-processing list.
3716 maxDumpId = AH->maxDumpId;
3717 tocsByDumpId = (TocEntry **) calloc(maxDumpId, sizeof(TocEntry *));
3718 for (te = AH->toc->next; te != AH->toc; te = te->next)
3720 tocsByDumpId[te->dumpId - 1] = te;
3721 te->depCount = te->nDeps;
3722 te->par_prev = NULL;
3723 te->par_next = NULL;
3727 * POST_DATA items that are shown as depending on a table need to be
3728 * re-pointed to depend on that table's data, instead. This ensures they
3729 * won't get scheduled until the data has been loaded. We handle this by
3730 * first finding TABLE/TABLE DATA pairs and then scanning all the
3733 * Note: currently, a TABLE DATA should always have exactly one
3734 * dependency, on its TABLE item. So we don't bother to search, but look
3735 * just at the first dependency. We do trouble to make sure that it's a
3736 * TABLE, if possible. However, if the dependency isn't in the archive
3737 * then just assume it was a TABLE; this is to cover cases where the table
3738 * was suppressed but we have the data and some dependent post-data items.
3740 for (te = AH->toc->next; te != AH->toc; te = te->next)
3742 if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
3744 DumpId tableId = te->dependencies[0];
3746 if (tableId > maxDumpId ||
3747 tocsByDumpId[tableId - 1] == NULL ||
3748 strcmp(tocsByDumpId[tableId - 1]->desc, "TABLE") == 0)
3750 repoint_table_dependencies(AH, tableId, te->dumpId);
3756 * Pre-8.4 versions of pg_dump neglected to set up a dependency from BLOB
3757 * COMMENTS to BLOBS. Cope. (We assume there's only one BLOBS and only
3758 * one BLOB COMMENTS in such files.)
3760 if (AH->version < K_VERS_1_11)
3762 for (te = AH->toc->next; te != AH->toc; te = te->next)
3764 if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
3768 for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
3770 if (strcmp(te2->desc, "BLOBS") == 0)
3772 te->dependencies = (DumpId *) malloc(sizeof(DumpId));
3773 te->dependencies[0] = te2->dumpId;
3785 * It is possible that the dependencies list items that are not in the
3786 * archive at all. Subtract such items from the depCounts.
3788 for (te = AH->toc->next; te != AH->toc; te = te->next)
3790 for (i = 0; i < te->nDeps; i++)
3792 DumpId depid = te->dependencies[i];
3794 if (depid > maxDumpId || tocsByDumpId[depid - 1] == NULL)
3800 * Lastly, work out the locking dependencies.
3802 for (te = AH->toc->next; te != AH->toc; te = te->next)
3804 te->lockDeps = NULL;
3806 identify_locking_dependencies(te, tocsByDumpId, maxDumpId);
3813 * Change dependencies on tableId to depend on tableDataId instead,
3814 * but only in POST_DATA items.
3817 repoint_table_dependencies(ArchiveHandle *AH,
3818 DumpId tableId, DumpId tableDataId)
3823 for (te = AH->toc->next; te != AH->toc; te = te->next)
3825 if (te->section != SECTION_POST_DATA)
3827 for (i = 0; i < te->nDeps; i++)
3829 if (te->dependencies[i] == tableId)
3831 te->dependencies[i] = tableDataId;
3832 ahlog(AH, 2, "transferring dependency %d -> %d to %d\n",
3833 te->dumpId, tableId, tableDataId);
3840 * Identify which objects we'll need exclusive lock on in order to restore
3841 * the given TOC entry (*other* than the one identified by the TOC entry
3842 * itself). Record their dump IDs in the entry's lockDeps[] array.
3843 * tocsByDumpId[] is a convenience array (of size maxDumpId) to avoid
3844 * searching the TOC for each dependency.
3847 identify_locking_dependencies(TocEntry *te,
3848 TocEntry **tocsByDumpId,
3855 /* Quick exit if no dependencies at all */
3859 /* Exit if this entry doesn't need exclusive lock on other objects */
3860 if (!(strcmp(te->desc, "CONSTRAINT") == 0 ||
3861 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
3862 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
3863 strcmp(te->desc, "RULE") == 0 ||
3864 strcmp(te->desc, "TRIGGER") == 0))
3868 * We assume the item requires exclusive lock on each TABLE DATA item
3869 * listed among its dependencies. (This was originally a dependency on
3870 * the TABLE, but fix_dependencies repointed it to the data item. Note
3871 * that all the entry types we are interested in here are POST_DATA, so
3872 * they will all have been changed this way.)
3874 lockids = (DumpId *) malloc(te->nDeps * sizeof(DumpId));
3876 for (i = 0; i < te->nDeps; i++)
3878 DumpId depid = te->dependencies[i];
3880 if (depid <= maxDumpId && tocsByDumpId[depid - 1] &&
3881 strcmp(tocsByDumpId[depid - 1]->desc, "TABLE DATA") == 0)
3882 lockids[nlockids++] = depid;
3891 te->lockDeps = realloc(lockids, nlockids * sizeof(DumpId));
3892 te->nLockDeps = nlockids;
3896 * Remove the specified TOC entry from the depCounts of items that depend on
3897 * it, thereby possibly making them ready-to-run. Any pending item that
3898 * becomes ready should be moved to the ready list.
3901 reduce_dependencies(ArchiveHandle *AH, TocEntry *te, TocEntry *ready_list)
3903 DumpId target = te->dumpId;
3906 ahlog(AH, 2, "reducing dependencies for %d\n", target);
3909 * We must examine all entries, not only the ones after the target item,
3910 * because if the user used a -L switch then the original dependency-
3911 * respecting order has been destroyed by SortTocFromFile.
3913 for (te = AH->toc->next; te != AH->toc; te = te->next)
3915 for (i = 0; i < te->nDeps; i++)
3917 if (te->dependencies[i] == target)
3920 if (te->depCount == 0 && te->par_prev != NULL)
3922 /* It must be in the pending list, so remove it ... */
3923 par_list_remove(te);
3924 /* ... and add to ready_list */
3925 par_list_append(ready_list, te);
3933 * Set the created flag on the DATA member corresponding to the given
3937 mark_create_done(ArchiveHandle *AH, TocEntry *te)
3941 for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
3943 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
3944 strcmp(tes->tag, te->tag) == 0 &&
3945 strcmp(tes->namespace ? tes->namespace : "",
3946 te->namespace ? te->namespace : "") == 0)
3948 tes->created = true;
3955 * Mark the DATA member corresponding to the given TABLE member
3959 inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
3961 RestoreOptions *ropt = AH->ropt;
3964 ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
3967 for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
3969 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
3970 strcmp(tes->tag, te->tag) == 0 &&
3971 strcmp(tes->namespace ? tes->namespace : "",
3972 te->namespace ? te->namespace : "") == 0)
3974 /* mark it unwanted; we assume idWanted array already exists */
3975 ropt->idWanted[tes->dumpId - 1] = false;
3983 * Clone and de-clone routines used in parallel restoration.
3985 * Enough of the structure is cloned to ensure that there is no
3986 * conflict between different threads each with their own clone.
3988 * These could be public, but no need at present.
3990 static ArchiveHandle *
3991 CloneArchive(ArchiveHandle *AH)
3993 ArchiveHandle *clone;
3995 /* Make a "flat" copy */
3996 clone = (ArchiveHandle *) malloc(sizeof(ArchiveHandle));
3998 die_horribly(AH, modulename, "out of memory\n");
3999 memcpy(clone, AH, sizeof(ArchiveHandle));
4001 /* Handle format-independent fields */
4002 clone->pgCopyBuf = createPQExpBuffer();
4003 clone->sqlBuf = createPQExpBuffer();
4004 clone->sqlparse.tagBuf = NULL;
4006 /* The clone will have its own connection, so disregard connection state */
4007 clone->connection = NULL;
4008 clone->currUser = NULL;
4009 clone->currSchema = NULL;
4010 clone->currTablespace = NULL;
4011 clone->currWithOids = -1;
4013 /* savedPassword must be local in case we change it while connecting */
4014 if (clone->savedPassword)
4015 clone->savedPassword = strdup(clone->savedPassword);
4017 /* clone has its own error count, too */
4018 clone->public.n_errors = 0;
4020 /* Let the format-specific code have a chance too */
4021 (clone->ClonePtr) (clone);
4027 * Release clone-local storage.
4029 * Note: we assume any clone-local connection was already closed.
4032 DeCloneArchive(ArchiveHandle *AH)
4034 /* Clear format-specific state */
4035 (AH->DeClonePtr) (AH);
4037 /* Clear state allocated by CloneArchive */
4038 destroyPQExpBuffer(AH->pgCopyBuf);
4039 destroyPQExpBuffer(AH->sqlBuf);
4040 if (AH->sqlparse.tagBuf)
4041 destroyPQExpBuffer(AH->sqlparse.tagBuf);
4043 /* Clear any connection-local state */
4047 free(AH->currSchema);
4048 if (AH->currTablespace)
4049 free(AH->currTablespace);
4050 if (AH->savedPassword)
4051 free(AH->savedPassword);