]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_backup_archiver.c
Fix up pg_dump's treatment of large object ownership and ACLs. We now emit
[postgresql] / src / bin / pg_dump / pg_backup_archiver.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_backup_archiver.c
4  *
5  *      Private implementation of the archiver routines.
6  *
7  *      See the headers to pg_restore for more details.
8  *
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.
12  *
13  *      The author is not responsible for loss or damages that may
14  *      result from its use.
15  *
16  *
17  * IDENTIFICATION
18  *              $PostgreSQL: pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.179 2010/02/18 01:29:10 tgl Exp $
19  *
20  *-------------------------------------------------------------------------
21  */
22
23 #include "pg_backup_db.h"
24 #include "dumputils.h"
25
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30
31 #ifdef WIN32
32 #include <io.h>
33 #endif
34
35 #include "libpq/libpq-fs.h"
36
37 /*
38  * Special exit values from worker children.  We reserve 0 for normal
39  * success; 1 and other small values should be interpreted as crashes.
40  */
41 #define WORKER_CREATE_DONE              10
42 #define WORKER_INHIBIT_DATA             11
43 #define WORKER_IGNORED_ERRORS   12
44
45 /*
46  * Unix uses exit to return result from worker child, so function is void.
47  * Windows thread result comes via function return.
48  */
49 #ifndef WIN32
50 #define parallel_restore_result void
51 #else
52 #define parallel_restore_result DWORD
53 #endif
54
55 /* IDs for worker children are either PIDs or thread handles */
56 #ifndef WIN32
57 #define thandle pid_t
58 #else
59 #define thandle HANDLE
60 #endif
61
62 /* Arguments needed for a worker child */
63 typedef struct _restore_args
64 {
65         ArchiveHandle *AH;
66         TocEntry   *te;
67 } RestoreArgs;
68
69 /* State for each parallel activity slot */
70 typedef struct _parallel_slot
71 {
72         thandle         child_id;
73         RestoreArgs *args;
74 } ParallelSlot;
75
76 #define NO_SLOT (-1)
77
78 const char *progname;
79
80 static const char *modulename = gettext_noop("archiver");
81
82
83 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
84                  const int compression, ArchiveMode mode);
85 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
86                                           ArchiveHandle *AH);
87 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
88
89
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);
107
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);
111
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);
115
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,
139                                                           DumpId maxDumpId);
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);
146
147
148 /*
149  *      Wrapper functions.
150  *
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.
153  *
154  */
155
156
157 /* Create a new archive */
158 /* Public */
159 Archive *
160 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
161                           const int compression, ArchiveMode mode)
162
163 {
164         ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode);
165
166         return (Archive *) AH;
167 }
168
169 /* Open an existing archive */
170 /* Public */
171 Archive *
172 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
173 {
174         ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
175
176         return (Archive *) AH;
177 }
178
179 /* Public */
180 void
181 CloseArchive(Archive *AHX)
182 {
183         int                     res = 0;
184         ArchiveHandle *AH = (ArchiveHandle *) AHX;
185
186         (*AH->ClosePtr) (AH);
187
188         /* Close the output */
189         if (AH->gzOut)
190                 res = GZCLOSE(AH->OF);
191         else if (AH->OF != stdout)
192                 res = fclose(AH->OF);
193
194         if (res != 0)
195                 die_horribly(AH, modulename, "could not close output file: %s\n",
196                                          strerror(errno));
197 }
198
199 /* Public */
200 void
201 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
202 {
203         ArchiveHandle *AH = (ArchiveHandle *) AHX;
204         TocEntry   *te;
205         teReqs          reqs;
206         OutputContext sav;
207
208         AH->ropt = ropt;
209         AH->stage = STAGE_INITIALIZING;
210
211         /*
212          * Check for nonsensical option combinations.
213          *
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...
218          */
219         if (ropt->create && ropt->dropSchema)
220                 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
221
222         /*
223          * -1 is not compatible with -C, because we can't create a database inside
224          * a transaction block.
225          */
226         if (ropt->create && ropt->single_txn)
227                 die_horribly(AH, modulename, "-C and -1 are incompatible options\n");
228
229         /*
230          * Make sure we won't need (de)compression we haven't got
231          */
232 #ifndef HAVE_LIBZ
233         if (AH->compression != 0 && AH->PrintTocDataPtr !=NULL)
234         {
235                 for (te = AH->toc->next; te != AH->toc; te = te->next)
236                 {
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");
240                 }
241         }
242 #endif
243
244         /*
245          * If we're using a DB connection, then connect it.
246          */
247         if (ropt->useDB)
248         {
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");
252
253                 /* XXX Should get this from the archive */
254                 AHX->minRemoteVersion = 070100;
255                 AHX->maxRemoteVersion = 999999;
256
257                 ConnectDatabase(AHX, ropt->dbname,
258                                                 ropt->pghost, ropt->pgport, ropt->username,
259                                                 ropt->promptPassword);
260
261                 /*
262                  * If we're talking to the DB directly, don't send comments since they
263                  * obscure SQL when displaying errors
264                  */
265                 AH->noTocComments = 1;
266         }
267
268         /*
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.
273          *
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).
276          */
277         if (!ropt->dataOnly)
278         {
279                 int                     impliedDataOnly = 1;
280
281                 for (te = AH->toc->next; te != AH->toc; te = te->next)
282                 {
283                         reqs = _tocEntryRequired(te, ropt, true);
284                         if ((reqs & REQ_SCHEMA) != 0)
285                         {                                       /* It's schema, and it's wanted */
286                                 impliedDataOnly = 0;
287                                 break;
288                         }
289                 }
290                 if (impliedDataOnly)
291                 {
292                         ropt->dataOnly = impliedDataOnly;
293                         ahlog(AH, 1, "implied data-only restore\n");
294                 }
295         }
296
297         /*
298          * Setup the output file if necessary.
299          */
300         if (ropt->filename || ropt->compression)
301                 sav = SetOutput(AH, ropt->filename, ropt->compression);
302
303         ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
304
305         if (AH->public.verbose)
306                 dumpTimestamp(AH, "Started on", AH->createDate);
307
308         if (ropt->single_txn)
309         {
310                 if (AH->connection)
311                         StartTransaction(AH);
312                 else
313                         ahprintf(AH, "BEGIN;\n\n");
314         }
315
316         /*
317          * Establish important parameter values right away.
318          */
319         _doSetFixedOutputState(AH);
320
321         AH->stage = STAGE_PROCESSING;
322
323         /*
324          * Drop the items at the start, in reverse order
325          */
326         if (ropt->dropSchema)
327         {
328                 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
329                 {
330                         AH->currentTE = te;
331
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)
335                         {
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);
340                                 /* Drop it */
341                                 ahprintf(AH, "%s", te->dropStmt);
342                         }
343                 }
344
345                 /*
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
352                  * the schema).
353                  *
354                  * If we treated users as pg_dump'able objects then we'd need to reset
355                  * currUser here too.
356                  */
357                 if (AH->currSchema)
358                         free(AH->currSchema);
359                 AH->currSchema = NULL;
360         }
361
362         /*
363          * In serial mode, we now process each non-ACL TOC entry.
364          *
365          * In parallel mode, turn control over to the parallel-restore logic.
366          */
367         if (ropt->number_of_jobs > 1 && ropt->useDB)
368                 restore_toc_entries_parallel(AH);
369         else
370         {
371                 for (te = AH->toc->next; te != AH->toc; te = te->next)
372                         (void) restore_toc_entry(AH, te, ropt, false);
373         }
374
375         /*
376          * Scan TOC again to output ownership commands and ACLs
377          */
378         for (te = AH->toc->next; te != AH->toc; te = te->next)
379         {
380                 AH->currentTE = te;
381
382                 /* Work out what, if anything, we want from this entry */
383                 reqs = _tocEntryRequired(te, ropt, true);
384
385                 /* Both schema and data objects might now have ownership/ACLs */
386                 if ((reqs & (REQ_SCHEMA|REQ_DATA)) != 0)
387                 {
388                         ahlog(AH, 1, "setting owner and privileges for %s %s\n",
389                                   te->desc, te->tag);
390                         _printTocEntry(AH, te, ropt, false, true);
391                 }
392         }
393
394         if (ropt->single_txn)
395         {
396                 if (AH->connection)
397                         CommitTransaction(AH);
398                 else
399                         ahprintf(AH, "COMMIT;\n\n");
400         }
401
402         if (AH->public.verbose)
403                 dumpTimestamp(AH, "Completed on", time(NULL));
404
405         ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
406
407         /*
408          * Clean up & we're done.
409          */
410         AH->stage = STAGE_FINALIZING;
411
412         if (ropt->filename || ropt->compression)
413                 ResetOutput(AH, sav);
414
415         if (ropt->useDB)
416         {
417                 PQfinish(AH->connection);
418                 AH->connection = NULL;
419         }
420 }
421
422 /*
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.
425  *
426  * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
427  * the parallel parent has to make the corresponding status update.
428  */
429 static int
430 restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
431                                   RestoreOptions *ropt, bool is_parallel)
432 {
433         int                     retval = 0;
434         teReqs          reqs;
435         bool            defnDumped;
436
437         AH->currentTE = te;
438
439         /* Work out what, if anything, we want from this entry */
440         reqs = _tocEntryRequired(te, ropt, false);
441
442         /* Dump any relevant dump warnings to stderr */
443         if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
444         {
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);
449         }
450
451         defnDumped = false;
452
453         if ((reqs & REQ_SCHEMA) != 0)           /* We want the schema */
454         {
455                 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
456
457                 _printTocEntry(AH, te, ropt, false, false);
458                 defnDumped = true;
459
460                 if (strcmp(te->desc, "TABLE") == 0)
461                 {
462                         if (AH->lastErrorTE == te)
463                         {
464                                 /*
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.
468                                  *
469                                  * In the parallel case this must be done in the parent, so we
470                                  * just set the return value.
471                                  */
472                                 if (ropt->noDataForFailedTables)
473                                 {
474                                         if (is_parallel)
475                                                 retval = WORKER_INHIBIT_DATA;
476                                         else
477                                                 inhibit_data_for_failed_table(AH, te);
478                                 }
479                         }
480                         else
481                         {
482                                 /*
483                                  * We created the table successfully.  Mark the corresponding
484                                  * TABLE DATA for possible truncation.
485                                  *
486                                  * In the parallel case this must be done in the parent, so we
487                                  * just set the return value.
488                                  */
489                                 if (is_parallel)
490                                         retval = WORKER_CREATE_DONE;
491                                 else
492                                         mark_create_done(AH, te);
493                         }
494                 }
495
496                 /* If we created a DB, connect to it... */
497                 if (strcmp(te->desc, "DATABASE") == 0)
498                 {
499                         ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
500                         _reconnectToDB(AH, te->tag);
501                         ropt->dbname = strdup(te->tag);
502                 }
503         }
504
505         /*
506          * If we have a data component, then process it
507          */
508         if ((reqs & REQ_DATA) != 0)
509         {
510                 /*
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.
514                  */
515                 if (te->hadDumper)
516                 {
517                         /*
518                          * If we can output the data, then restore it.
519                          */
520                         if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
521                         {
522                                 _printTocEntry(AH, te, ropt, true, false);
523
524                                 if (strcmp(te->desc, "BLOBS") == 0 ||
525                                         strcmp(te->desc, "BLOB COMMENTS") == 0)
526                                 {
527                                         ahlog(AH, 1, "restoring %s\n", te->desc);
528
529                                         _selectOutputSchema(AH, "pg_catalog");
530
531                                         (*AH->PrintTocDataPtr) (AH, te, ropt);
532                                 }
533                                 else
534                                 {
535                                         _disableTriggersIfNecessary(AH, te, ropt);
536
537                                         /* Select owner and schema as necessary */
538                                         _becomeOwner(AH, te);
539                                         _selectOutputSchema(AH, te->namespace);
540
541                                         ahlog(AH, 1, "restoring data for table \"%s\"\n",
542                                                   te->tag);
543
544                                         /*
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.
551                                          */
552                                         if (is_parallel && te->created)
553                                         {
554                                                 /*
555                                                  * Parallel restore is always talking directly to a
556                                                  * server, so no need to see if we should issue BEGIN.
557                                                  */
558                                                 StartTransaction(AH);
559
560                                                 /*
561                                                  * If the server version is >= 8.4, make sure we issue
562                                                  * TRUNCATE with ONLY so that child tables are not
563                                                  * wiped.
564                                                  */
565                                                 ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
566                                                                  (PQserverVersion(AH->connection) >= 80400 ?
567                                                                   "ONLY " : ""),
568                                                                  fmtId(te->tag));
569                                         }
570
571                                         /*
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.
576                                          *
577                                          * For V1.3+, the table data MUST have a copy statement so
578                                          * that we can go into appropriate mode with libpq.
579                                          */
580                                         if (te->copyStmt && strlen(te->copyStmt) > 0)
581                                         {
582                                                 ahprintf(AH, "%s", te->copyStmt);
583                                                 AH->writingCopyData = true;
584                                         }
585
586                                         (*AH->PrintTocDataPtr) (AH, te, ropt);
587
588                                         AH->writingCopyData = false;
589
590                                         /* close out the transaction started above */
591                                         if (is_parallel && te->created)
592                                                 CommitTransaction(AH);
593
594                                         _enableTriggersIfNecessary(AH, te, ropt);
595                                 }
596                         }
597                 }
598                 else if (!defnDumped)
599                 {
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);
603                 }
604         }
605
606         return retval;
607 }
608
609 /*
610  * Allocate a new RestoreOptions block.
611  * This is mainly so we can initialize it, but also for future expansion,
612  */
613 RestoreOptions *
614 NewRestoreOptions(void)
615 {
616         RestoreOptions *opts;
617
618         opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
619
620         /* set any fields that shouldn't default to zeroes */
621         opts->format = archUnknown;
622         opts->promptPassword = TRI_DEFAULT;
623
624         return opts;
625 }
626
627 static void
628 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
629 {
630         /* This hack is only needed in a data-only restore */
631         if (!ropt->dataOnly || !ropt->disable_triggers)
632                 return;
633
634         ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
635
636         /*
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
640          * table owner?)
641          */
642         _becomeUser(AH, ropt->superuser);
643
644         /*
645          * Disable them.
646          */
647         _selectOutputSchema(AH, te->namespace);
648
649         ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
650                          fmtId(te->tag));
651 }
652
653 static void
654 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
655 {
656         /* This hack is only needed in a data-only restore */
657         if (!ropt->dataOnly || !ropt->disable_triggers)
658                 return;
659
660         ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
661
662         /*
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
666          * table owner?)
667          */
668         _becomeUser(AH, ropt->superuser);
669
670         /*
671          * Enable them.
672          */
673         _selectOutputSchema(AH, te->namespace);
674
675         ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
676                          fmtId(te->tag));
677 }
678
679 /*
680  * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
681  */
682
683 /* Public */
684 size_t
685 WriteData(Archive *AHX, const void *data, size_t dLen)
686 {
687         ArchiveHandle *AH = (ArchiveHandle *) AHX;
688
689         if (!AH->currToc)
690                 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
691
692         return (*AH->WriteDataPtr) (AH, data, dLen);
693 }
694
695 /*
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.
698  */
699
700 /* Public */
701 void
702 ArchiveEntry(Archive *AHX,
703                          CatalogId catalogId, DumpId dumpId,
704                          const char *tag,
705                          const char *namespace,
706                          const char *tablespace,
707                          const char *owner, bool withOids,
708                          const char *desc, teSection section,
709                          const char *defn,
710                          const char *dropStmt, const char *copyStmt,
711                          const DumpId *deps, int nDeps,
712                          DataDumperPtr dumpFn, void *dumpArg)
713 {
714         ArchiveHandle *AH = (ArchiveHandle *) AHX;
715         TocEntry   *newToc;
716
717         newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
718         if (!newToc)
719                 die_horribly(AH, modulename, "out of memory\n");
720
721         AH->tocCount++;
722         if (dumpId > AH->maxDumpId)
723                 AH->maxDumpId = dumpId;
724
725         newToc->prev = AH->toc->prev;
726         newToc->next = AH->toc;
727         AH->toc->prev->next = newToc;
728         AH->toc->prev = newToc;
729
730         newToc->catalogId = catalogId;
731         newToc->dumpId = dumpId;
732         newToc->section = section;
733
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;
743
744         if (nDeps > 0)
745         {
746                 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
747                 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
748                 newToc->nDeps = nDeps;
749         }
750         else
751         {
752                 newToc->dependencies = NULL;
753                 newToc->nDeps = 0;
754         }
755
756         newToc->dataDumper = dumpFn;
757         newToc->dataDumperArg = dumpArg;
758         newToc->hadDumper = dumpFn ? true : false;
759
760         newToc->formatData = NULL;
761
762         if (AH->ArchiveEntryPtr !=NULL)
763                 (*AH->ArchiveEntryPtr) (AH, newToc);
764 }
765
766 /* Public */
767 void
768 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
769 {
770         ArchiveHandle *AH = (ArchiveHandle *) AHX;
771         TocEntry   *te;
772         OutputContext sav;
773         char       *fmtName;
774
775         if (ropt->filename)
776                 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
777
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);
781
782         switch (AH->format)
783         {
784                 case archFiles:
785                         fmtName = "FILES";
786                         break;
787                 case archCustom:
788                         fmtName = "CUSTOM";
789                         break;
790                 case archTar:
791                         fmtName = "TAR";
792                         break;
793                 default:
794                         fmtName = "UNKNOWN";
795         }
796
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);
807
808         ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
809
810         for (te = AH->toc->next; te != AH->toc; te = te->next)
811         {
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 : "-",
816                                          te->tag, te->owner);
817                 if (ropt->verbose && te->nDeps > 0)
818                 {
819                         int                     i;
820
821                         ahprintf(AH, ";\tdepends on:");
822                         for (i = 0; i < te->nDeps; i++)
823                                 ahprintf(AH, " %d", te->dependencies[i]);
824                         ahprintf(AH, "\n");
825                 }
826         }
827
828         if (ropt->filename)
829                 ResetOutput(AH, sav);
830 }
831
832 /***********
833  * BLOB Archival
834  ***********/
835
836 /* Called by a dumper to signal start of a BLOB */
837 int
838 StartBlob(Archive *AHX, Oid oid)
839 {
840         ArchiveHandle *AH = (ArchiveHandle *) AHX;
841
842         if (!AH->StartBlobPtr)
843                 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
844
845         (*AH->StartBlobPtr) (AH, AH->currToc, oid);
846
847         return 1;
848 }
849
850 /* Called by a dumper to signal end of a BLOB */
851 int
852 EndBlob(Archive *AHX, Oid oid)
853 {
854         ArchiveHandle *AH = (ArchiveHandle *) AHX;
855
856         if (AH->EndBlobPtr)
857                 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
858
859         return 1;
860 }
861
862 /**********
863  * BLOB Restoration
864  **********/
865
866 /*
867  * Called by a format handler before any blobs are restored
868  */
869 void
870 StartRestoreBlobs(ArchiveHandle *AH)
871 {
872         if (!AH->ropt->single_txn)
873         {
874                 if (AH->connection)
875                         StartTransaction(AH);
876                 else
877                         ahprintf(AH, "BEGIN;\n\n");
878         }
879
880         AH->blobCount = 0;
881 }
882
883 /*
884  * Called by a format handler after all blobs are restored
885  */
886 void
887 EndRestoreBlobs(ArchiveHandle *AH)
888 {
889         if (!AH->ropt->single_txn)
890         {
891                 if (AH->connection)
892                         CommitTransaction(AH);
893                 else
894                         ahprintf(AH, "COMMIT;\n\n");
895         }
896
897         ahlog(AH, 1, ngettext("restored %d large object\n",
898                                                   "restored %d large objects\n",
899                                                   AH->blobCount),
900                   AH->blobCount);
901 }
902
903
904 /*
905  * Called by a format handler to initiate restoration of a blob
906  */
907 void
908 StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
909 {
910         bool            old_blob_style = (AH->version < K_VERS_1_12);
911         Oid                     loOid;
912
913         AH->blobCount++;
914
915         /* Initialize the LO Buffer */
916         AH->lo_buf_used = 0;
917
918         ahlog(AH, 2, "restoring large object with OID %u\n", oid);
919
920         /* With an old archive we must do drop and create logic here */
921         if (old_blob_style && drop)
922                 DropBlobIfExists(AH, oid);
923
924         if (AH->connection)
925         {
926                 if (old_blob_style)
927                 {
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",
931                                                          oid);
932                 }
933                 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
934                 if (AH->loFd == -1)
935                         die_horribly(AH, modulename, "could not open large object %u\n",
936                                                  oid);
937         }
938         else
939         {
940                 if (old_blob_style)
941                         ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
942                                          oid, INV_WRITE);
943                 else
944                         ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
945                                          oid, INV_WRITE);
946         }
947
948         AH->writingBlob = 1;
949 }
950
951 void
952 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
953 {
954         if (AH->lo_buf_used > 0)
955         {
956                 /* Write remaining bytes from the LO buffer */
957                 dump_lo_buf(AH);
958         }
959
960         AH->writingBlob = 0;
961
962         if (AH->connection)
963         {
964                 lo_close(AH->connection, AH->loFd);
965                 AH->loFd = -1;
966         }
967         else
968         {
969                 ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
970         }
971 }
972
973 /***********
974  * Sorting and Reordering
975  ***********/
976
977 void
978 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
979 {
980         ArchiveHandle *AH = (ArchiveHandle *) AHX;
981         FILE       *fh;
982         char            buf[1024];
983         char       *cmnt;
984         char       *endptr;
985         DumpId          id;
986         TocEntry   *te;
987         TocEntry   *tePrev;
988
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);
992
993         /* Set prev entry as head of list */
994         tePrev = AH->toc;
995
996         /* Setup the file */
997         fh = fopen(ropt->tocFile, PG_BINARY_R);
998         if (!fh)
999                 die_horribly(AH, modulename, "could not open TOC file \"%s\": %s\n",
1000                                          ropt->tocFile, strerror(errno));
1001
1002         while (fgets(buf, sizeof(buf), fh) != NULL)
1003         {
1004                 /* Truncate line at comment, if any */
1005                 cmnt = strchr(buf, ';');
1006                 if (cmnt != NULL)
1007                         cmnt[0] = '\0';
1008
1009                 /* Ignore if all blank */
1010                 if (strspn(buf, " \t\r") == strlen(buf))
1011                         continue;
1012
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])
1017                 {
1018                         write_msg(modulename, "WARNING: line ignored: %s\n", buf);
1019                         continue;
1020                 }
1021
1022                 /* Find TOC entry */
1023                 te = getTocEntryByDumpId(AH, id);
1024                 if (!te)
1025                         die_horribly(AH, modulename, "could not find entry for ID %d\n",
1026                                                  id);
1027
1028                 ropt->idWanted[id - 1] = true;
1029
1030                 _moveAfter(AH, tePrev, te);
1031                 tePrev = te;
1032         }
1033
1034         if (fclose(fh) != 0)
1035                 die_horribly(AH, modulename, "could not close TOC file: %s\n",
1036                                          strerror(errno));
1037 }
1038
1039 /*
1040  * Set up a dummy ID filter that selects all dump IDs
1041  */
1042 void
1043 InitDummyWantedList(Archive *AHX, RestoreOptions *ropt)
1044 {
1045         ArchiveHandle *AH = (ArchiveHandle *) AHX;
1046
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);
1050 }
1051
1052 /**********************
1053  * 'Convenience functions that look like standard IO functions
1054  * for writing data when in dump mode.
1055  **********************/
1056
1057 /* Public */
1058 int
1059 archputs(const char *s, Archive *AH)
1060 {
1061         return WriteData(AH, s, strlen(s));
1062 }
1063
1064 /* Public */
1065 int
1066 archprintf(Archive *AH, const char *fmt,...)
1067 {
1068         char       *p = NULL;
1069         va_list         ap;
1070         int                     bSize = strlen(fmt) + 256;
1071         int                     cnt = -1;
1072
1073         /*
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
1077          */
1078         while (cnt < 0 || cnt >= (bSize - 1))
1079         {
1080                 if (p != NULL)
1081                         free(p);
1082                 bSize *= 2;
1083                 p = (char *) malloc(bSize);
1084                 if (p == NULL)
1085                         exit_horribly(AH, modulename, "out of memory\n");
1086                 va_start(ap, fmt);
1087                 cnt = vsnprintf(p, bSize, fmt, ap);
1088                 va_end(ap);
1089         }
1090         WriteData(AH, p, cnt);
1091         free(p);
1092         return cnt;
1093 }
1094
1095
1096 /*******************************
1097  * Stuff below here should be 'private' to the archiver routines
1098  *******************************/
1099
1100 static OutputContext
1101 SetOutput(ArchiveHandle *AH, char *filename, int compression)
1102 {
1103         OutputContext sav;
1104         int                     fn;
1105
1106         /* Replace the AH output file handle */
1107         sav.OF = AH->OF;
1108         sav.gzOut = AH->gzOut;
1109
1110         if (filename)
1111                 fn = -1;
1112         else if (AH->FH)
1113                 fn = fileno(AH->FH);
1114         else if (AH->fSpec)
1115         {
1116                 fn = -1;
1117                 filename = AH->fSpec;
1118         }
1119         else
1120                 fn = fileno(stdout);
1121
1122         /* If compression explicitly requested, use gzopen */
1123 #ifdef HAVE_LIBZ
1124         if (compression != 0)
1125         {
1126                 char            fmode[10];
1127
1128                 /* Don't use PG_BINARY_x since this is zlib */
1129                 sprintf(fmode, "wb%d", compression);
1130                 if (fn >= 0)
1131                         AH->OF = gzdopen(dup(fn), fmode);
1132                 else
1133                         AH->OF = gzopen(filename, fmode);
1134                 AH->gzOut = 1;
1135         }
1136         else
1137 #endif
1138         {                                                       /* Use fopen */
1139                 if (AH->mode == archModeAppend)
1140                 {
1141                         if (fn >= 0)
1142                                 AH->OF = fdopen(dup(fn), PG_BINARY_A);
1143                         else
1144                                 AH->OF = fopen(filename, PG_BINARY_A);
1145                 }
1146                 else
1147                 {
1148                         if (fn >= 0)
1149                                 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1150                         else
1151                                 AH->OF = fopen(filename, PG_BINARY_W);
1152                 }
1153                 AH->gzOut = 0;
1154         }
1155
1156         if (!AH->OF)
1157         {
1158                 if (filename)
1159                         die_horribly(AH, modulename, "could not open output file \"%s\": %s\n",
1160                                                  filename, strerror(errno));
1161                 else
1162                         die_horribly(AH, modulename, "could not open output file: %s\n",
1163                                                  strerror(errno));
1164         }
1165
1166         return sav;
1167 }
1168
1169 static void
1170 ResetOutput(ArchiveHandle *AH, OutputContext sav)
1171 {
1172         int                     res;
1173
1174         if (AH->gzOut)
1175                 res = GZCLOSE(AH->OF);
1176         else
1177                 res = fclose(AH->OF);
1178
1179         if (res != 0)
1180                 die_horribly(AH, modulename, "could not close output file: %s\n",
1181                                          strerror(errno));
1182
1183         AH->gzOut = sav.gzOut;
1184         AH->OF = sav.OF;
1185 }
1186
1187
1188
1189 /*
1190  *      Print formatted text to the output file (usually stdout).
1191  */
1192 int
1193 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1194 {
1195         char       *p = NULL;
1196         va_list         ap;
1197         int                     bSize = strlen(fmt) + 256;              /* Should be enough */
1198         int                     cnt = -1;
1199
1200         /*
1201          * This is paranoid: deal with the possibility that vsnprintf is willing
1202          * to ignore trailing null
1203          */
1204
1205         /*
1206          * or returns > 0 even if string does not fit. It may be the case that it
1207          * returns cnt = bufsize
1208          */
1209         while (cnt < 0 || cnt >= (bSize - 1))
1210         {
1211                 if (p != NULL)
1212                         free(p);
1213                 bSize *= 2;
1214                 p = (char *) malloc(bSize);
1215                 if (p == NULL)
1216                         die_horribly(AH, modulename, "out of memory\n");
1217                 va_start(ap, fmt);
1218                 cnt = vsnprintf(p, bSize, fmt, ap);
1219                 va_end(ap);
1220         }
1221         ahwrite(p, 1, cnt, AH);
1222         free(p);
1223         return cnt;
1224 }
1225
1226 void
1227 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1228 {
1229         va_list         ap;
1230
1231         if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1232                 return;
1233
1234         va_start(ap, fmt);
1235         _write_msg(NULL, fmt, ap);
1236         va_end(ap);
1237 }
1238
1239 /*
1240  * Single place for logic which says 'We are restoring to a direct DB connection'.
1241  */
1242 static int
1243 RestoringToDB(ArchiveHandle *AH)
1244 {
1245         return (AH->ropt && AH->ropt->useDB && AH->connection);
1246 }
1247
1248 /*
1249  * Dump the current contents of the LO data buffer while writing a BLOB
1250  */
1251 static void
1252 dump_lo_buf(ArchiveHandle *AH)
1253 {
1254         if (AH->connection)
1255         {
1256                 size_t          res;
1257
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",
1261                                                           AH->lo_buf_used),
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);
1267         }
1268         else
1269         {
1270                 PQExpBuffer buf = createPQExpBuffer();
1271
1272                 appendByteaLiteralAHX(buf,
1273                                                           (const unsigned char *) AH->lo_buf,
1274                                                           AH->lo_buf_used,
1275                                                           AH);
1276
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;
1281
1282                 destroyPQExpBuffer(buf);
1283         }
1284         AH->lo_buf_used = 0;
1285 }
1286
1287
1288 /*
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).
1293  */
1294 int
1295 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1296 {
1297         size_t          res;
1298
1299         if (AH->writingBlob)
1300         {
1301                 size_t          remaining = size * nmemb;
1302
1303                 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1304                 {
1305                         size_t          avail = AH->lo_buf_size - AH->lo_buf_used;
1306
1307                         memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1308                         ptr = (const void *) ((const char *) ptr + avail);
1309                         remaining -= avail;
1310                         AH->lo_buf_used += avail;
1311                         dump_lo_buf(AH);
1312                 }
1313
1314                 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1315                 AH->lo_buf_used += remaining;
1316
1317                 return size * nmemb;
1318         }
1319         else if (AH->gzOut)
1320         {
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));
1324                 return res;
1325         }
1326         else if (AH->CustomOutPtr)
1327         {
1328                 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1329
1330                 if (res != (nmemb * size))
1331                         die_horribly(AH, modulename, "could not write to custom output routine\n");
1332                 return res;
1333         }
1334         else
1335         {
1336                 /*
1337                  * If we're doing a restore, and it's direct to DB, and we're
1338                  * connected then send it to the DB.
1339                  */
1340                 if (RestoringToDB(AH))
1341                         return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb);            /* Always 1, currently */
1342                 else
1343                 {
1344                         res = fwrite((void *) ptr, size, nmemb, AH->OF);
1345                         if (res != nmemb)
1346                                 die_horribly(AH, modulename, "could not write to output file: %s\n",
1347                                                          strerror(errno));
1348                         return res;
1349                 }
1350         }
1351 }
1352
1353 /* Common exit code */
1354 static void
1355 _write_msg(const char *modulename, const char *fmt, va_list ap)
1356 {
1357         if (modulename)
1358                 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1359         else
1360                 fprintf(stderr, "%s: ", progname);
1361         vfprintf(stderr, _(fmt), ap);
1362 }
1363
1364 void
1365 write_msg(const char *modulename, const char *fmt,...)
1366 {
1367         va_list         ap;
1368
1369         va_start(ap, fmt);
1370         _write_msg(modulename, fmt, ap);
1371         va_end(ap);
1372 }
1373
1374
1375 static void
1376 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1377 {
1378         _write_msg(modulename, fmt, ap);
1379
1380         if (AH)
1381         {
1382                 if (AH->public.verbose)
1383                         write_msg(NULL, "*** aborted because of error\n");
1384                 if (AH->connection)
1385                         PQfinish(AH->connection);
1386         }
1387
1388         exit(1);
1389 }
1390
1391 /* External use */
1392 void
1393 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1394 {
1395         va_list         ap;
1396
1397         va_start(ap, fmt);
1398         _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1399         va_end(ap);
1400 }
1401
1402 /* Archiver use (just different arg declaration) */
1403 void
1404 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1405 {
1406         va_list         ap;
1407
1408         va_start(ap, fmt);
1409         _die_horribly(AH, modulename, fmt, ap);
1410         va_end(ap);
1411 }
1412
1413 /* on some error, we may decide to go on... */
1414 void
1415 warn_or_die_horribly(ArchiveHandle *AH,
1416                                          const char *modulename, const char *fmt,...)
1417 {
1418         va_list         ap;
1419
1420         switch (AH->stage)
1421         {
1422
1423                 case STAGE_NONE:
1424                         /* Do nothing special */
1425                         break;
1426
1427                 case STAGE_INITIALIZING:
1428                         if (AH->stage != AH->lastErrorStage)
1429                                 write_msg(modulename, "Error while INITIALIZING:\n");
1430                         break;
1431
1432                 case STAGE_PROCESSING:
1433                         if (AH->stage != AH->lastErrorStage)
1434                                 write_msg(modulename, "Error while PROCESSING TOC:\n");
1435                         break;
1436
1437                 case STAGE_FINALIZING:
1438                         if (AH->stage != AH->lastErrorStage)
1439                                 write_msg(modulename, "Error while FINALIZING:\n");
1440                         break;
1441         }
1442         if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1443         {
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);
1448         }
1449         AH->lastErrorStage = AH->stage;
1450         AH->lastErrorTE = AH->currentTE;
1451
1452         va_start(ap, fmt);
1453         if (AH->public.exit_on_error)
1454                 _die_horribly(AH, modulename, fmt, ap);
1455         else
1456         {
1457                 _write_msg(modulename, fmt, ap);
1458                 AH->public.n_errors++;
1459         }
1460         va_end(ap);
1461 }
1462
1463 static void
1464 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1465 {
1466         te->prev->next = te->next;
1467         te->next->prev = te->prev;
1468
1469         te->prev = pos;
1470         te->next = pos->next;
1471
1472         pos->next->prev = te;
1473         pos->next = te;
1474 }
1475
1476 #ifdef NOT_USED
1477
1478 static void
1479 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1480 {
1481         te->prev->next = te->next;
1482         te->next->prev = te->prev;
1483
1484         te->prev = pos->prev;
1485         te->next = pos;
1486         pos->prev->next = te;
1487         pos->prev = te;
1488 }
1489 #endif
1490
1491 static TocEntry *
1492 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1493 {
1494         TocEntry   *te;
1495
1496         for (te = AH->toc->next; te != AH->toc; te = te->next)
1497         {
1498                 if (te->dumpId == id)
1499                         return te;
1500         }
1501         return NULL;
1502 }
1503
1504 teReqs
1505 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1506 {
1507         TocEntry   *te = getTocEntryByDumpId(AH, id);
1508
1509         if (!te)
1510                 return 0;
1511
1512         return _tocEntryRequired(te, ropt, true);
1513 }
1514
1515 size_t
1516 WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1517 {
1518         int                     off;
1519
1520         /* Save the flag */
1521         (*AH->WriteBytePtr) (AH, wasSet);
1522
1523         /* Write out pgoff_t smallest byte first, prevents endian mismatch */
1524         for (off = 0; off < sizeof(pgoff_t); off++)
1525         {
1526                 (*AH->WriteBytePtr) (AH, o & 0xFF);
1527                 o >>= 8;
1528         }
1529         return sizeof(pgoff_t) + 1;
1530 }
1531
1532 int
1533 ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1534 {
1535         int                     i;
1536         int                     off;
1537         int                     offsetFlg;
1538
1539         /* Initialize to zero */
1540         *o = 0;
1541
1542         /* Check for old version */
1543         if (AH->version < K_VERS_1_7)
1544         {
1545                 /* Prior versions wrote offsets using WriteInt */
1546                 i = ReadInt(AH);
1547                 /* -1 means not set */
1548                 if (i < 0)
1549                         return K_OFFSET_POS_NOT_SET;
1550                 else if (i == 0)
1551                         return K_OFFSET_NO_DATA;
1552
1553                 /* Cast to pgoff_t because it was written as an int. */
1554                 *o = (pgoff_t) i;
1555                 return K_OFFSET_POS_SET;
1556         }
1557
1558         /*
1559          * Read the flag indicating the state of the data pointer. Check if valid
1560          * and die if not.
1561          *
1562          * This used to be handled by a negative or zero pointer, now we use an
1563          * extra byte specifically for the state.
1564          */
1565         offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1566
1567         switch (offsetFlg)
1568         {
1569                 case K_OFFSET_POS_NOT_SET:
1570                 case K_OFFSET_NO_DATA:
1571                 case K_OFFSET_POS_SET:
1572
1573                         break;
1574
1575                 default:
1576                         die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1577         }
1578
1579         /*
1580          * Read the bytes
1581          */
1582         for (off = 0; off < AH->offSize; off++)
1583         {
1584                 if (off < sizeof(pgoff_t))
1585                         *o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1586                 else
1587                 {
1588                         if ((*AH->ReadBytePtr) (AH) != 0)
1589                                 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1590                 }
1591         }
1592
1593         return offsetFlg;
1594 }
1595
1596 size_t
1597 WriteInt(ArchiveHandle *AH, int i)
1598 {
1599         int                     b;
1600
1601         /*
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
1606          * formats.
1607          */
1608
1609         /* SIGN byte */
1610         if (i < 0)
1611         {
1612                 (*AH->WriteBytePtr) (AH, 1);
1613                 i = -i;
1614         }
1615         else
1616                 (*AH->WriteBytePtr) (AH, 0);
1617
1618         for (b = 0; b < AH->intSize; b++)
1619         {
1620                 (*AH->WriteBytePtr) (AH, i & 0xFF);
1621                 i >>= 8;
1622         }
1623
1624         return AH->intSize + 1;
1625 }
1626
1627 int
1628 ReadInt(ArchiveHandle *AH)
1629 {
1630         int                     res = 0;
1631         int                     bv,
1632                                 b;
1633         int                     sign = 0;               /* Default positive */
1634         int                     bitShift = 0;
1635
1636         if (AH->version > K_VERS_1_0)
1637                 /* Read a sign byte */
1638                 sign = (*AH->ReadBytePtr) (AH);
1639
1640         for (b = 0; b < AH->intSize; b++)
1641         {
1642                 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1643                 if (bv != 0)
1644                         res = res + (bv << bitShift);
1645                 bitShift += 8;
1646         }
1647
1648         if (sign)
1649                 res = -res;
1650
1651         return res;
1652 }
1653
1654 size_t
1655 WriteStr(ArchiveHandle *AH, const char *c)
1656 {
1657         size_t          res;
1658
1659         if (c)
1660         {
1661                 res = WriteInt(AH, strlen(c));
1662                 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1663         }
1664         else
1665                 res = WriteInt(AH, -1);
1666
1667         return res;
1668 }
1669
1670 char *
1671 ReadStr(ArchiveHandle *AH)
1672 {
1673         char       *buf;
1674         int                     l;
1675
1676         l = ReadInt(AH);
1677         if (l < 0)
1678                 buf = NULL;
1679         else
1680         {
1681                 buf = (char *) malloc(l + 1);
1682                 if (!buf)
1683                         die_horribly(AH, modulename, "out of memory\n");
1684
1685                 if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1686                         die_horribly(AH, modulename, "unexpected end of file\n");
1687
1688                 buf[l] = '\0';
1689         }
1690
1691         return buf;
1692 }
1693
1694 static int
1695 _discoverArchiveFormat(ArchiveHandle *AH)
1696 {
1697         FILE       *fh;
1698         char            sig[6];                 /* More than enough */
1699         size_t          cnt;
1700         int                     wantClose = 0;
1701
1702 #if 0
1703         write_msg(modulename, "attempting to ascertain archive format\n");
1704 #endif
1705
1706         if (AH->lookahead)
1707                 free(AH->lookahead);
1708
1709         AH->lookaheadSize = 512;
1710         AH->lookahead = calloc(1, 512);
1711         AH->lookaheadLen = 0;
1712         AH->lookaheadPos = 0;
1713
1714         if (AH->fSpec)
1715         {
1716                 wantClose = 1;
1717                 fh = fopen(AH->fSpec, PG_BINARY_R);
1718                 if (!fh)
1719                         die_horribly(AH, modulename, "could not open input file \"%s\": %s\n",
1720                                                  AH->fSpec, strerror(errno));
1721         }
1722         else
1723         {
1724                 fh = stdin;
1725                 if (!fh)
1726                         die_horribly(AH, modulename, "could not open input file: %s\n",
1727                                                  strerror(errno));
1728         }
1729
1730         cnt = fread(sig, 1, 5, fh);
1731
1732         if (cnt != 5)
1733         {
1734                 if (ferror(fh))
1735                         die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1736                 else
1737                         die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1738                                                  (unsigned long) cnt);
1739         }
1740
1741         /* Save it, just in case we need it later */
1742         strncpy(&AH->lookahead[0], sig, 5);
1743         AH->lookaheadLen = 5;
1744
1745         if (strncmp(sig, "PGDMP", 5) == 0)
1746         {
1747                 AH->vmaj = fgetc(fh);
1748                 AH->vmin = fgetc(fh);
1749
1750                 /* Save these too... */
1751                 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1752                 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1753
1754                 /* Check header version; varies from V1.0 */
1755                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
1756                 {
1757                         AH->vrev = fgetc(fh);
1758                         AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1759                 }
1760                 else
1761                         AH->vrev = 0;
1762
1763                 /* Make a convenient integer <maj><min><rev>00 */
1764                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1765
1766                 AH->intSize = fgetc(fh);
1767                 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1768
1769                 if (AH->version >= K_VERS_1_7)
1770                 {
1771                         AH->offSize = fgetc(fh);
1772                         AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1773                 }
1774                 else
1775                         AH->offSize = AH->intSize;
1776
1777                 AH->format = fgetc(fh);
1778                 AH->lookahead[AH->lookaheadLen++] = AH->format;
1779         }
1780         else
1781         {
1782                 /*
1783                  * *Maybe* we have a tar archive format file... So, read first 512
1784                  * byte header...
1785                  */
1786                 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1787                 AH->lookaheadLen += cnt;
1788
1789                 if (AH->lookaheadLen != 512)
1790                         die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1791
1792                 if (!isValidTarHeader(AH->lookahead))
1793                         die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1794
1795                 AH->format = archTar;
1796         }
1797
1798         /* If we can't seek, then mark the header as read */
1799         if (fseeko(fh, 0, SEEK_SET) != 0)
1800         {
1801                 /*
1802                  * NOTE: Formats that use the lookahead buffer can unset this in their
1803                  * Init routine.
1804                  */
1805                 AH->readHeader = 1;
1806         }
1807         else
1808                 AH->lookaheadLen = 0;   /* Don't bother since we've reset the file */
1809
1810         /* Close the file */
1811         if (wantClose)
1812                 if (fclose(fh) != 0)
1813                         die_horribly(AH, modulename, "could not close input file: %s\n",
1814                                                  strerror(errno));
1815
1816         return AH->format;
1817 }
1818
1819
1820 /*
1821  * Allocate an archive handle
1822  */
1823 static ArchiveHandle *
1824 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1825                  const int compression, ArchiveMode mode)
1826 {
1827         ArchiveHandle *AH;
1828
1829 #if 0
1830         write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1831 #endif
1832
1833         AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1834         if (!AH)
1835                 die_horribly(AH, modulename, "out of memory\n");
1836
1837         /* AH->debugLevel = 100; */
1838
1839         AH->vmaj = K_VERS_MAJOR;
1840         AH->vmin = K_VERS_MINOR;
1841         AH->vrev = K_VERS_REV;
1842
1843         /* Make a convenient integer <maj><min><rev>00 */
1844         AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1845
1846         /* initialize for backwards compatible string processing */
1847         AH->public.encoding = 0;        /* PG_SQL_ASCII */
1848         AH->public.std_strings = false;
1849
1850         /* sql error handling */
1851         AH->public.exit_on_error = true;
1852         AH->public.n_errors = 0;
1853
1854         AH->createDate = time(NULL);
1855
1856         AH->intSize = sizeof(int);
1857         AH->offSize = sizeof(pgoff_t);
1858         if (FileSpec)
1859         {
1860                 AH->fSpec = strdup(FileSpec);
1861
1862                 /*
1863                  * Not used; maybe later....
1864                  *
1865                  * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1866                  * i--) if (AH->workDir[i-1] == '/')
1867                  */
1868         }
1869         else
1870                 AH->fSpec = NULL;
1871
1872         AH->currUser = NULL;            /* unknown */
1873         AH->currSchema = NULL;          /* ditto */
1874         AH->currTablespace = NULL;      /* ditto */
1875         AH->currWithOids = -1;          /* force SET */
1876
1877         AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1878         if (!AH->toc)
1879                 die_horribly(AH, modulename, "out of memory\n");
1880
1881         AH->toc->next = AH->toc;
1882         AH->toc->prev = AH->toc;
1883
1884         AH->mode = mode;
1885         AH->compression = compression;
1886
1887         AH->pgCopyBuf = createPQExpBuffer();
1888         AH->sqlBuf = createPQExpBuffer();
1889
1890         /* Open stdout with no compression for AH output handle */
1891         AH->gzOut = 0;
1892         AH->OF = stdout;
1893
1894         /*
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
1897          * using.
1898          */
1899 #ifdef WIN32
1900         if (fmt != archNull &&
1901                 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1902         {
1903                 if (mode == archModeWrite)
1904                         setmode(fileno(stdout), O_BINARY);
1905                 else
1906                         setmode(fileno(stdin), O_BINARY);
1907         }
1908 #endif
1909
1910         if (fmt == archUnknown)
1911                 AH->format = _discoverArchiveFormat(AH);
1912         else
1913                 AH->format = fmt;
1914
1915         AH->promptPassword = TRI_DEFAULT;
1916
1917         switch (AH->format)
1918         {
1919                 case archCustom:
1920                         InitArchiveFmt_Custom(AH);
1921                         break;
1922
1923                 case archFiles:
1924                         InitArchiveFmt_Files(AH);
1925                         break;
1926
1927                 case archNull:
1928                         InitArchiveFmt_Null(AH);
1929                         break;
1930
1931                 case archTar:
1932                         InitArchiveFmt_Tar(AH);
1933                         break;
1934
1935                 default:
1936                         die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1937         }
1938
1939         return AH;
1940 }
1941
1942
1943 void
1944 WriteDataChunks(ArchiveHandle *AH)
1945 {
1946         TocEntry   *te;
1947         StartDataPtr startPtr;
1948         EndDataPtr      endPtr;
1949
1950         for (te = AH->toc->next; te != AH->toc; te = te->next)
1951         {
1952                 if (te->dataDumper != NULL)
1953                 {
1954                         AH->currToc = te;
1955                         /* printf("Writing data for %d (%x)\n", te->id, te); */
1956
1957                         if (strcmp(te->desc, "BLOBS") == 0)
1958                         {
1959                                 startPtr = AH->StartBlobsPtr;
1960                                 endPtr = AH->EndBlobsPtr;
1961                         }
1962                         else
1963                         {
1964                                 startPtr = AH->StartDataPtr;
1965                                 endPtr = AH->EndDataPtr;
1966                         }
1967
1968                         if (startPtr != NULL)
1969                                 (*startPtr) (AH, te);
1970
1971                         /*
1972                          * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1973                          */
1974
1975                         /*
1976                          * The user-provided DataDumper routine needs to call
1977                          * AH->WriteData
1978                          */
1979                         (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1980
1981                         if (endPtr != NULL)
1982                                 (*endPtr) (AH, te);
1983                         AH->currToc = NULL;
1984                 }
1985         }
1986 }
1987
1988 void
1989 WriteToc(ArchiveHandle *AH)
1990 {
1991         TocEntry   *te;
1992         char            workbuf[32];
1993         int                     i;
1994
1995         /* printf("%d TOC Entries to save\n", AH->tocCount); */
1996
1997         WriteInt(AH, AH->tocCount);
1998
1999         for (te = AH->toc->next; te != AH->toc; te = te->next)
2000         {
2001                 WriteInt(AH, te->dumpId);
2002                 WriteInt(AH, te->dataDumper ? 1 : 0);
2003
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);
2009
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");
2020
2021                 /* Dump list of dependencies */
2022                 for (i = 0; i < te->nDeps; i++)
2023                 {
2024                         sprintf(workbuf, "%d", te->dependencies[i]);
2025                         WriteStr(AH, workbuf);
2026                 }
2027                 WriteStr(AH, NULL);             /* Terminate List */
2028
2029                 if (AH->WriteExtraTocPtr)
2030                         (*AH->WriteExtraTocPtr) (AH, te);
2031         }
2032 }
2033
2034 void
2035 ReadToc(ArchiveHandle *AH)
2036 {
2037         int                     i;
2038         char       *tmp;
2039         DumpId     *deps;
2040         int                     depIdx;
2041         int                     depSize;
2042         TocEntry   *te;
2043
2044         AH->tocCount = ReadInt(AH);
2045         AH->maxDumpId = 0;
2046
2047         for (i = 0; i < AH->tocCount; i++)
2048         {
2049                 te = (TocEntry *) calloc(1, sizeof(TocEntry));
2050                 te->dumpId = ReadInt(AH);
2051
2052                 if (te->dumpId > AH->maxDumpId)
2053                         AH->maxDumpId = te->dumpId;
2054
2055                 /* Sanity check */
2056                 if (te->dumpId <= 0)
2057                         die_horribly(AH, modulename,
2058                                            "entry ID %d out of range -- perhaps a corrupt TOC\n",
2059                                                  te->dumpId);
2060
2061                 te->hadDumper = ReadInt(AH);
2062
2063                 if (AH->version >= K_VERS_1_8)
2064                 {
2065                         tmp = ReadStr(AH);
2066                         sscanf(tmp, "%u", &te->catalogId.tableoid);
2067                         free(tmp);
2068                 }
2069                 else
2070                         te->catalogId.tableoid = InvalidOid;
2071                 tmp = ReadStr(AH);
2072                 sscanf(tmp, "%u", &te->catalogId.oid);
2073                 free(tmp);
2074
2075                 te->tag = ReadStr(AH);
2076                 te->desc = ReadStr(AH);
2077
2078                 if (AH->version >= K_VERS_1_11)
2079                 {
2080                         te->section = ReadInt(AH);
2081                 }
2082                 else
2083                 {
2084                         /*
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.
2088                          */
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;
2104                         else
2105                                 te->section = SECTION_PRE_DATA;
2106                 }
2107
2108                 te->defn = ReadStr(AH);
2109                 te->dropStmt = ReadStr(AH);
2110
2111                 if (AH->version >= K_VERS_1_3)
2112                         te->copyStmt = ReadStr(AH);
2113
2114                 if (AH->version >= K_VERS_1_6)
2115                         te->namespace = ReadStr(AH);
2116
2117                 if (AH->version >= K_VERS_1_10)
2118                         te->tablespace = ReadStr(AH);
2119
2120                 te->owner = ReadStr(AH);
2121                 if (AH->version >= K_VERS_1_9)
2122                 {
2123                         if (strcmp(ReadStr(AH), "true") == 0)
2124                                 te->withOids = true;
2125                         else
2126                                 te->withOids = false;
2127                 }
2128                 else
2129                         te->withOids = true;
2130
2131                 /* Read TOC entry dependencies */
2132                 if (AH->version >= K_VERS_1_5)
2133                 {
2134                         depSize = 100;
2135                         deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
2136                         depIdx = 0;
2137                         for (;;)
2138                         {
2139                                 tmp = ReadStr(AH);
2140                                 if (!tmp)
2141                                         break;          /* end of list */
2142                                 if (depIdx >= depSize)
2143                                 {
2144                                         depSize *= 2;
2145                                         deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
2146                                 }
2147                                 sscanf(tmp, "%d", &deps[depIdx]);
2148                                 free(tmp);
2149                                 depIdx++;
2150                         }
2151
2152                         if (depIdx > 0)         /* We have a non-null entry */
2153                         {
2154                                 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
2155                                 te->dependencies = deps;
2156                                 te->nDeps = depIdx;
2157                         }
2158                         else
2159                         {
2160                                 free(deps);
2161                                 te->dependencies = NULL;
2162                                 te->nDeps = 0;
2163                         }
2164                 }
2165                 else
2166                 {
2167                         te->dependencies = NULL;
2168                         te->nDeps = 0;
2169                 }
2170
2171                 if (AH->ReadExtraTocPtr)
2172                         (*AH->ReadExtraTocPtr) (AH, te);
2173
2174                 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
2175                           i, te->dumpId, te->desc, te->tag);
2176
2177                 /* link completed entry into TOC circular list */
2178                 te->prev = AH->toc->prev;
2179                 AH->toc->prev->next = te;
2180                 AH->toc->prev = te;
2181                 te->next = AH->toc;
2182
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);
2188         }
2189 }
2190
2191 static void
2192 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
2193 {
2194         /* te->defn should have the form SET client_encoding = 'foo'; */
2195         char       *defn = strdup(te->defn);
2196         char       *ptr1;
2197         char       *ptr2 = NULL;
2198         int                     encoding;
2199
2200         ptr1 = strchr(defn, '\'');
2201         if (ptr1)
2202                 ptr2 = strchr(++ptr1, '\'');
2203         if (ptr2)
2204         {
2205                 *ptr2 = '\0';
2206                 encoding = pg_char_to_encoding(ptr1);
2207                 if (encoding < 0)
2208                         die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
2209                                                  ptr1);
2210                 AH->public.encoding = encoding;
2211         }
2212         else
2213                 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
2214                                          te->defn);
2215
2216         free(defn);
2217 }
2218
2219 static void
2220 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
2221 {
2222         /* te->defn should have the form SET standard_conforming_strings = 'x'; */
2223         char       *ptr1;
2224
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;
2230         else
2231                 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
2232                                          te->defn);
2233 }
2234
2235 static teReqs
2236 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
2237 {
2238         teReqs          res = REQ_ALL;
2239
2240         /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
2241         if (strcmp(te->desc, "ENCODING") == 0 ||
2242                 strcmp(te->desc, "STDSTRINGS") == 0)
2243                 return 0;
2244
2245         /* If it's an ACL, maybe ignore it */
2246         if ((!include_acls || ropt->aclsSkip) && _tocEntryIsACL(te))
2247                 return 0;
2248
2249         /* Ignore DATABASE entry unless we should create it */
2250         if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
2251                 return 0;
2252
2253         /* Check options for selective dump/restore */
2254         if (ropt->schemaNames)
2255         {
2256                 /* If no namespace is specified, it means all. */
2257                 if (!te->namespace)
2258                         return 0;
2259                 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2260                         return 0;
2261         }
2262
2263         if (ropt->selTypes)
2264         {
2265                 if (strcmp(te->desc, "TABLE") == 0 ||
2266                         strcmp(te->desc, "TABLE DATA") == 0)
2267                 {
2268                         if (!ropt->selTable)
2269                                 return 0;
2270                         if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2271                                 return 0;
2272                 }
2273                 else if (strcmp(te->desc, "INDEX") == 0)
2274                 {
2275                         if (!ropt->selIndex)
2276                                 return 0;
2277                         if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2278                                 return 0;
2279                 }
2280                 else if (strcmp(te->desc, "FUNCTION") == 0)
2281                 {
2282                         if (!ropt->selFunction)
2283                                 return 0;
2284                         if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2285                                 return 0;
2286                 }
2287                 else if (strcmp(te->desc, "TRIGGER") == 0)
2288                 {
2289                         if (!ropt->selTrigger)
2290                                 return 0;
2291                         if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2292                                 return 0;
2293                 }
2294                 else
2295                         return 0;
2296         }
2297
2298         /*
2299          * Check if we had a dataDumper. Indicates if the entry is schema or data
2300          */
2301         if (!te->hadDumper)
2302         {
2303                 /*
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
2308                  * BLOB comments.
2309                  */
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;
2317                 else
2318                         res = res & ~REQ_DATA;
2319         }
2320
2321         /*
2322          * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2323          * always ignore it.
2324          */
2325         if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2326                 return 0;
2327
2328         /* Mask it if we only want schema */
2329         if (ropt->schemaOnly)
2330                 res = res & REQ_SCHEMA;
2331
2332         /* Mask it we only want data */
2333         if (ropt->dataOnly)
2334                 res = res & REQ_DATA;
2335
2336         /* Mask it if we don't have a schema contribution */
2337         if (!te->defn || strlen(te->defn) == 0)
2338                 res = res & ~REQ_SCHEMA;
2339
2340         /* Finally, if there's a per-ID filter, limit based on that as well */
2341         if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2342                 return 0;
2343
2344         return res;
2345 }
2346
2347 /*
2348  * Identify TOC entries that are ACLs.
2349  */
2350 static bool
2351 _tocEntryIsACL(TocEntry *te)
2352 {
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)
2357                 return true;
2358         return false;
2359 }
2360
2361 /*
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.
2364  */
2365 static void
2366 _doSetFixedOutputState(ArchiveHandle *AH)
2367 {
2368         /* Disable statement_timeout in archive for pg_restore/psql  */
2369         ahprintf(AH, "SET statement_timeout = 0;\n");
2370
2371         /* Select the correct character set encoding */
2372         ahprintf(AH, "SET client_encoding = '%s';\n",
2373                          pg_encoding_to_char(AH->public.encoding));
2374
2375         /* Select the correct string literal syntax */
2376         ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2377                          AH->public.std_strings ? "on" : "off");
2378
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));
2382
2383         /* Make sure function checking is disabled */
2384         ahprintf(AH, "SET check_function_bodies = false;\n");
2385
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");
2390
2391         ahprintf(AH, "\n");
2392 }
2393
2394 /*
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.
2398  */
2399 static void
2400 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2401 {
2402         PQExpBuffer cmd = createPQExpBuffer();
2403
2404         appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2405
2406         /*
2407          * SQL requires a string literal here.  Might as well be correct.
2408          */
2409         if (user && *user)
2410                 appendStringLiteralAHX(cmd, user, AH);
2411         else
2412                 appendPQExpBuffer(cmd, "DEFAULT");
2413         appendPQExpBuffer(cmd, ";");
2414
2415         if (RestoringToDB(AH))
2416         {
2417                 PGresult   *res;
2418
2419                 res = PQexec(AH->connection, cmd->data);
2420
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));
2425
2426                 PQclear(res);
2427         }
2428         else
2429                 ahprintf(AH, "%s\n\n", cmd->data);
2430
2431         destroyPQExpBuffer(cmd);
2432 }
2433
2434
2435 /*
2436  * Issue a SET default_with_oids command.  Caller is responsible
2437  * for updating state if appropriate.
2438  */
2439 static void
2440 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2441 {
2442         PQExpBuffer cmd = createPQExpBuffer();
2443
2444         appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2445                                           "true" : "false");
2446
2447         if (RestoringToDB(AH))
2448         {
2449                 PGresult   *res;
2450
2451                 res = PQexec(AH->connection, cmd->data);
2452
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));
2457
2458                 PQclear(res);
2459         }
2460         else
2461                 ahprintf(AH, "%s\n\n", cmd->data);
2462
2463         destroyPQExpBuffer(cmd);
2464 }
2465
2466
2467 /*
2468  * Issue the commands to connect to the specified database.
2469  *
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.
2473  *
2474  * NULL dbname implies reconnecting to the current DB (pretty useless).
2475  */
2476 static void
2477 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2478 {
2479         if (RestoringToDB(AH))
2480                 ReconnectToServer(AH, dbname, NULL);
2481         else
2482         {
2483                 PQExpBuffer qry = createPQExpBuffer();
2484
2485                 appendPQExpBuffer(qry, "\\connect %s\n\n",
2486                                                   dbname ? fmtId(dbname) : "-");
2487                 ahprintf(AH, "%s", qry->data);
2488                 destroyPQExpBuffer(qry);
2489         }
2490
2491         /*
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.
2494          */
2495         if (AH->currUser)
2496                 free(AH->currUser);
2497         AH->currUser = NULL;
2498
2499         /* don't assume we still know the output schema, tablespace, etc either */
2500         if (AH->currSchema)
2501                 free(AH->currSchema);
2502         AH->currSchema = NULL;
2503         if (AH->currTablespace)
2504                 free(AH->currTablespace);
2505         AH->currTablespace = NULL;
2506         AH->currWithOids = -1;
2507
2508         /* re-establish fixed state */
2509         _doSetFixedOutputState(AH);
2510 }
2511
2512 /*
2513  * Become the specified user, and update state to avoid redundant commands
2514  *
2515  * NULL or empty argument is taken to mean restoring the session default
2516  */
2517 static void
2518 _becomeUser(ArchiveHandle *AH, const char *user)
2519 {
2520         if (!user)
2521                 user = "";                              /* avoid null pointers */
2522
2523         if (AH->currUser && strcmp(AH->currUser, user) == 0)
2524                 return;                                 /* no need to do anything */
2525
2526         _doSetSessionAuth(AH, user);
2527
2528         /*
2529          * NOTE: currUser keeps track of what the imaginary session user in our
2530          * script is
2531          */
2532         if (AH->currUser)
2533                 free(AH->currUser);
2534         AH->currUser = strdup(user);
2535 }
2536
2537 /*
2538  * Become the owner of the the given TOC entry object.  If
2539  * changes in ownership are not allowed, this doesn't do anything.
2540  */
2541 static void
2542 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2543 {
2544         if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2545                 return;
2546
2547         _becomeUser(AH, te->owner);
2548 }
2549
2550
2551 /*
2552  * Set the proper default_with_oids value for the table.
2553  */
2554 static void
2555 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2556 {
2557         if (AH->currWithOids != te->withOids)
2558         {
2559                 _doSetWithOids(AH, te->withOids);
2560                 AH->currWithOids = te->withOids;
2561         }
2562 }
2563
2564
2565 /*
2566  * Issue the commands to select the specified schema as the current schema
2567  * in the target database.
2568  */
2569 static void
2570 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2571 {
2572         PQExpBuffer qry;
2573
2574         if (!schemaName || *schemaName == '\0' ||
2575                 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2576                 return;                                 /* no need to do anything */
2577
2578         qry = createPQExpBuffer();
2579
2580         appendPQExpBuffer(qry, "SET search_path = %s",
2581                                           fmtId(schemaName));
2582         if (strcmp(schemaName, "pg_catalog") != 0)
2583                 appendPQExpBuffer(qry, ", pg_catalog");
2584
2585         if (RestoringToDB(AH))
2586         {
2587                 PGresult   *res;
2588
2589                 res = PQexec(AH->connection, qry->data);
2590
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));
2595
2596                 PQclear(res);
2597         }
2598         else
2599                 ahprintf(AH, "%s;\n\n", qry->data);
2600
2601         if (AH->currSchema)
2602                 free(AH->currSchema);
2603         AH->currSchema = strdup(schemaName);
2604
2605         destroyPQExpBuffer(qry);
2606 }
2607
2608 /*
2609  * Issue the commands to select the specified tablespace as the current one
2610  * in the target database.
2611  */
2612 static void
2613 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2614 {
2615         PQExpBuffer qry;
2616         const char *want,
2617                            *have;
2618
2619         /* do nothing in --no-tablespaces mode */
2620         if (AH->ropt->noTablespace)
2621                 return;
2622
2623         have = AH->currTablespace;
2624         want = tablespace;
2625
2626         /* no need to do anything for non-tablespace object */
2627         if (!want)
2628                 return;
2629
2630         if (have && strcmp(want, have) == 0)
2631                 return;                                 /* no need to do anything */
2632
2633         qry = createPQExpBuffer();
2634
2635         if (strcmp(want, "") == 0)
2636         {
2637                 /* We want the tablespace to be the database's default */
2638                 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2639         }
2640         else
2641         {
2642                 /* We want an explicit tablespace */
2643                 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2644         }
2645
2646         if (RestoringToDB(AH))
2647         {
2648                 PGresult   *res;
2649
2650                 res = PQexec(AH->connection, qry->data);
2651
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));
2656
2657                 PQclear(res);
2658         }
2659         else
2660                 ahprintf(AH, "%s;\n\n", qry->data);
2661
2662         if (AH->currTablespace)
2663                 free(AH->currTablespace);
2664         AH->currTablespace = strdup(want);
2665
2666         destroyPQExpBuffer(qry);
2667 }
2668
2669 /*
2670  * Extract an object description for a TOC entry, and append it to buf.
2671  *
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.
2674  *
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.
2677  */
2678 static void
2679 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2680 {
2681         const char *type = te->desc;
2682
2683         /* Use ALTER TABLE for views and sequences */
2684         if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2685                 type = "TABLE";
2686
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)
2694         {
2695                 appendPQExpBuffer(buf, "%s ", type);
2696                 if (te->namespace && te->namespace[0])  /* is null pre-7.3 */
2697                         appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2698
2699                 /*
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.
2703                  */
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);
2709                 else
2710                         appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2711                 return;
2712         }
2713
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)
2721         {
2722                 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2723                 return;
2724         }
2725
2726         /* BLOBs just have a name, but it's numeric so must not use fmtId */
2727         if (strcmp(type, "BLOB") == 0)
2728         {
2729                 appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
2730                 return;
2731         }
2732
2733         /*
2734          * These object types require additional decoration.  Fortunately, the
2735          * information needed is exactly what's in the DROP command.
2736          */
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)
2742         {
2743                 /* Chop "DROP " off the front and make a modifiable copy */
2744                 char       *first = strdup(te->dropStmt + 5);
2745                 char       *last;
2746
2747                 /* point to last character in string */
2748                 last = first + strlen(first) - 1;
2749
2750                 /* Strip off any ';' or '\n' at the end */
2751                 while (last >= first && (*last == '\n' || *last == ';'))
2752                         last--;
2753                 *(last + 1) = '\0';
2754
2755                 appendPQExpBufferStr(buf, first);
2756
2757                 free(first);
2758                 return;
2759         }
2760
2761         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2762                           type);
2763 }
2764
2765 static void
2766 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2767 {
2768         /* ACLs are dumped only during acl pass */
2769         if (acl_pass)
2770         {
2771                 if (!_tocEntryIsACL(te))
2772                         return;
2773         }
2774         else
2775         {
2776                 if (_tocEntryIsACL(te))
2777                         return;
2778         }
2779
2780         /*
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.
2784          */
2785         if (!ropt->dropSchema)
2786         {
2787                 if (strcmp(te->desc, "SCHEMA") == 0 &&
2788                         strcmp(te->tag, "public") == 0)
2789                         return;
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)
2793                         return;
2794         }
2795
2796         /* Select owner, schema, and tablespace as necessary */
2797         _becomeOwner(AH, te);
2798         _selectOutputSchema(AH, te->namespace);
2799         _selectTablespace(AH, te->tablespace);
2800
2801         /* Set up OID mode too */
2802         if (strcmp(te->desc, "TABLE") == 0)
2803                 _setWithOids(AH, te);
2804
2805         /* Emit header comment for item */
2806         if (!AH->noTocComments)
2807         {
2808                 const char *pfx;
2809
2810                 if (isData)
2811                         pfx = "Data for ";
2812                 else
2813                         pfx = "";
2814
2815                 ahprintf(AH, "--\n");
2816                 if (AH->public.verbose)
2817                 {
2818                         ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2819                                          te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2820                         if (te->nDeps > 0)
2821                         {
2822                                 int                     i;
2823
2824                                 ahprintf(AH, "-- Dependencies:");
2825                                 for (i = 0; i < te->nDeps; i++)
2826                                         ahprintf(AH, " %d", te->dependencies[i]);
2827                                 ahprintf(AH, "\n");
2828                         }
2829                 }
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);
2836                 ahprintf(AH, "\n");
2837
2838                 if (AH->PrintExtraTocPtr !=NULL)
2839                         (*AH->PrintExtraTocPtr) (AH, te);
2840                 ahprintf(AH, "--\n\n");
2841         }
2842
2843         /*
2844          * Actually print the definition.
2845          *
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 ...
2849          */
2850         if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2851         {
2852                 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2853         }
2854         else
2855         {
2856                 if (strlen(te->defn) > 0)
2857                         ahprintf(AH, "%s\n\n", te->defn);
2858         }
2859
2860         /*
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.
2865          */
2866         if (!ropt->noOwner && !ropt->use_setsessauth &&
2867                 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2868         {
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)
2888                 {
2889                         PQExpBuffer temp = createPQExpBuffer();
2890
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);
2896                 }
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)
2906                 {
2907                         /* these object types don't have separate owners */
2908                 }
2909                 else
2910                 {
2911                         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2912                                           te->desc);
2913                 }
2914         }
2915
2916         /*
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.
2919          */
2920         if (acl_pass)
2921         {
2922                 if (AH->currUser)
2923                         free(AH->currUser);
2924                 AH->currUser = NULL;
2925         }
2926 }
2927
2928 void
2929 WriteHead(ArchiveHandle *AH)
2930 {
2931         struct tm       crtm;
2932
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);
2940
2941 #ifndef HAVE_LIBZ
2942         if (AH->compression != 0)
2943                 write_msg(modulename, "WARNING: requested compression not available in this "
2944                                   "installation -- archive will be uncompressed\n");
2945
2946         AH->compression = 0;
2947 #endif
2948
2949         WriteInt(AH, AH->compression);
2950
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);
2962 }
2963
2964 void
2965 ReadHead(ArchiveHandle *AH)
2966 {
2967         char            tmpMag[7];
2968         int                     fmt;
2969         struct tm       crtm;
2970
2971         /* If we haven't already read the header... */
2972         if (!AH->readHeader)
2973         {
2974                 if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
2975                         die_horribly(AH, modulename, "unexpected end of file\n");
2976
2977                 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2978                         die_horribly(AH, modulename, "did not find magic string in file header\n");
2979
2980                 AH->vmaj = (*AH->ReadBytePtr) (AH);
2981                 AH->vmin = (*AH->ReadBytePtr) (AH);
2982
2983                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
2984                         AH->vrev = (*AH->ReadBytePtr) (AH);
2985                 else
2986                         AH->vrev = 0;
2987
2988                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2989
2990
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);
2994
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);
2999
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");
3002
3003                 if (AH->version >= K_VERS_1_7)
3004                         AH->offSize = (*AH->ReadBytePtr) (AH);
3005                 else
3006                         AH->offSize = AH->intSize;
3007
3008                 fmt = (*AH->ReadBytePtr) (AH);
3009
3010                 if (AH->format != fmt)
3011                         die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
3012                                                  AH->format, fmt);
3013         }
3014
3015         if (AH->version >= K_VERS_1_2)
3016         {
3017                 if (AH->version < K_VERS_1_4)
3018                         AH->compression = (*AH->ReadBytePtr) (AH);
3019                 else
3020                         AH->compression = ReadInt(AH);
3021         }
3022         else
3023                 AH->compression = Z_DEFAULT_COMPRESSION;
3024
3025 #ifndef HAVE_LIBZ
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");
3028 #endif
3029
3030         if (AH->version >= K_VERS_1_4)
3031         {
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);
3039
3040                 AH->archdbname = ReadStr(AH);
3041
3042                 AH->createDate = mktime(&crtm);
3043
3044                 if (AH->createDate == (time_t) -1)
3045                         write_msg(modulename, "WARNING: invalid creation date in header\n");
3046         }
3047
3048         if (AH->version >= K_VERS_1_10)
3049         {
3050                 AH->archiveRemoteVersion = ReadStr(AH);
3051                 AH->archiveDumpVersion = ReadStr(AH);
3052         }
3053
3054 }
3055
3056
3057 /*
3058  * checkSeek
3059  *        check to see if fseek can be performed.
3060  */
3061 bool
3062 checkSeek(FILE *fp)
3063 {
3064         if (fseeko(fp, 0, SEEK_CUR) != 0)
3065                 return false;
3066         else if (sizeof(pgoff_t) > sizeof(long))
3067         {
3068                 /*
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.
3071                  */
3072 #ifdef HAVE_FSEEKO
3073                 return true;
3074 #else
3075                 return false;
3076 #endif
3077         }
3078         else
3079                 return true;
3080 }
3081
3082
3083 /*
3084  * dumpTimestamp
3085  */
3086 static void
3087 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
3088 {
3089         char            buf[256];
3090
3091         /*
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
3095          * dump script.
3096          */
3097         if (strftime(buf, sizeof(buf),
3098 #ifndef WIN32
3099                                  "%Y-%m-%d %H:%M:%S %Z",
3100 #else
3101                                  "%Y-%m-%d %H:%M:%S",
3102 #endif
3103                                  localtime(&tim)) != 0)
3104                 ahprintf(AH, "-- %s %s\n\n", msg, buf);
3105 }
3106
3107
3108 /*
3109  * Main engine for parallel restore.
3110  *
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).
3118  */
3119 static void
3120 restore_toc_entries_parallel(ArchiveHandle *AH)
3121 {
3122         RestoreOptions *ropt = AH->ropt;
3123         int                     n_slots = ropt->number_of_jobs;
3124         ParallelSlot *slots;
3125         int                     work_status;
3126         int                     next_slot;
3127         TocEntry        pending_list;
3128         TocEntry        ready_list;
3129         TocEntry   *next_work_item;
3130         thandle         ret_child;
3131         TocEntry   *te;
3132
3133         ahlog(AH, 2, "entering restore_toc_entries_parallel\n");
3134
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");
3138
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");
3142
3143         slots = (ParallelSlot *) calloc(sizeof(ParallelSlot), n_slots);
3144
3145         /* Adjust dependency information */
3146         fix_dependencies(AH);
3147
3148         /*
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
3152          * setup overhead.
3153          */
3154         for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3155         {
3156                 if (next_work_item->section == SECTION_DATA ||
3157                         next_work_item->section == SECTION_POST_DATA)
3158                         break;
3159
3160                 ahlog(AH, 1, "processing item %d %s %s\n",
3161                           next_work_item->dumpId,
3162                           next_work_item->desc, next_work_item->tag);
3163
3164                 (void) restore_toc_entry(AH, next_work_item, ropt, false);
3165
3166                 /* there should be no touch of ready_list here, so pass NULL */
3167                 reduce_dependencies(AH, next_work_item, NULL);
3168         }
3169
3170         /*
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
3173          * connections.
3174          */
3175         PQfinish(AH->connection);
3176         AH->connection = NULL;
3177
3178         /* blow away any transient state from the old connection */
3179         if (AH->currUser)
3180                 free(AH->currUser);
3181         AH->currUser = NULL;
3182         if (AH->currSchema)
3183                 free(AH->currSchema);
3184         AH->currSchema = NULL;
3185         if (AH->currTablespace)
3186                 free(AH->currTablespace);
3187         AH->currTablespace = NULL;
3188         AH->currWithOids = -1;
3189
3190         /*
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.
3198          */
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)
3202         {
3203                 if (next_work_item->depCount > 0)
3204                         par_list_append(&pending_list, next_work_item);
3205                 else
3206                         par_list_append(&ready_list, next_work_item);
3207         }
3208
3209         /*
3210          * main parent loop
3211          *
3212          * Keep going until there is no worker still running AND there is no work
3213          * left to be done.
3214          */
3215
3216         ahlog(AH, 1, "entering main parallel loop\n");
3217
3218         while ((next_work_item = get_next_work_item(AH, &ready_list,
3219                                                                                                 slots, n_slots)) != NULL ||
3220                    work_in_progress(slots, n_slots))
3221         {
3222                 if (next_work_item != NULL)
3223                 {
3224                         teReqs          reqs;
3225
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)
3229                         {
3230                                 ahlog(AH, 1, "skipping item %d %s %s\n",
3231                                           next_work_item->dumpId,
3232                                           next_work_item->desc, next_work_item->tag);
3233
3234                                 par_list_remove(next_work_item);
3235                                 reduce_dependencies(AH, next_work_item, &ready_list);
3236
3237                                 continue;
3238                         }
3239
3240                         if ((next_slot = get_next_slot(slots, n_slots)) != NO_SLOT)
3241                         {
3242                                 /* There is work still to do and a worker slot available */
3243                                 thandle         child;
3244                                 RestoreArgs *args;
3245
3246                                 ahlog(AH, 1, "launching item %d %s %s\n",
3247                                           next_work_item->dumpId,
3248                                           next_work_item->desc, next_work_item->tag);
3249
3250                                 par_list_remove(next_work_item);
3251
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;
3256
3257                                 /* run the step in a worker child */
3258                                 child = spawn_restore(args);
3259
3260                                 slots[next_slot].child_id = child;
3261                                 slots[next_slot].args = args;
3262
3263                                 continue;
3264                         }
3265                 }
3266
3267                 /*
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.
3272                  */
3273                 ret_child = reap_child(slots, n_slots, &work_status);
3274
3275                 if (WIFEXITED(work_status))
3276                 {
3277                         mark_work_done(AH, &ready_list,
3278                                                    ret_child, WEXITSTATUS(work_status),
3279                                                    slots, n_slots);
3280                 }
3281                 else
3282                 {
3283                         die_horribly(AH, modulename, "worker process crashed: status %d\n",
3284                                                  work_status);
3285                 }
3286         }
3287
3288         ahlog(AH, 1, "finished main parallel loop\n");
3289
3290         /*
3291          * Now reconnect the single parent connection.
3292          */
3293         ConnectDatabase((Archive *) AH, ropt->dbname,
3294                                         ropt->pghost, ropt->pgport, ropt->username,
3295                                         ropt->promptPassword);
3296
3297         _doSetFixedOutputState(AH);
3298
3299         /*
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.
3303          */
3304         for (te = pending_list.par_next; te != &pending_list; te = te->par_next)
3305         {
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);
3309         }
3310
3311         /* The ACLs will be handled back in RestoreArchive. */
3312 }
3313
3314 /*
3315  * create a worker child to perform a restore step in parallel
3316  */
3317 static thandle
3318 spawn_restore(RestoreArgs *args)
3319 {
3320         thandle         child;
3321
3322         /* Ensure stdio state is quiesced before forking */
3323         fflush(NULL);
3324
3325 #ifndef WIN32
3326         child = fork();
3327         if (child == 0)
3328         {
3329                 /* in child process */
3330                 parallel_restore(args);
3331                 die_horribly(args->AH, modulename,
3332                                          "parallel_restore should not return\n");
3333         }
3334         else if (child < 0)
3335         {
3336                 /* fork failed */
3337                 die_horribly(args->AH, modulename,
3338                                          "could not create worker process: %s\n",
3339                                          strerror(errno));
3340         }
3341 #else
3342         child = (HANDLE) _beginthreadex(NULL, 0, (void *) parallel_restore,
3343                                                                         args, 0, NULL);
3344         if (child == 0)
3345                 die_horribly(args->AH, modulename,
3346                                          "could not create worker thread: %s\n",
3347                                          strerror(errno));
3348 #endif
3349
3350         return child;
3351 }
3352
3353 /*
3354  *      collect status from a completed worker child
3355  */
3356 static thandle
3357 reap_child(ParallelSlot *slots, int n_slots, int *work_status)
3358 {
3359 #ifndef WIN32
3360         /* Unix is so much easier ... */
3361         return wait(work_status);
3362 #else
3363         static HANDLE *handles = NULL;
3364         int                     hindex,
3365                                 snum,
3366                                 tnum;
3367         thandle         ret_child;
3368         DWORD           res;
3369
3370         /* first time around only, make space for handles to listen on */
3371         if (handles == NULL)
3372                 handles = (HANDLE *) calloc(sizeof(HANDLE), n_slots);
3373
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;
3378
3379         /* wait for one to finish */
3380         hindex = WaitForMultipleObjects(tnum, handles, false, INFINITE);
3381
3382         /* get handle of finished thread */
3383         ret_child = handles[hindex - WAIT_OBJECT_0];
3384
3385         /* get the result */
3386         GetExitCodeThread(ret_child, &res);
3387         *work_status = res;
3388
3389         /* dispose of handle to stop leaks */
3390         CloseHandle(ret_child);
3391
3392         return ret_child;
3393 #endif
3394 }
3395
3396 /*
3397  * are we doing anything now?
3398  */
3399 static bool
3400 work_in_progress(ParallelSlot *slots, int n_slots)
3401 {
3402         int                     i;
3403
3404         for (i = 0; i < n_slots; i++)
3405         {
3406                 if (slots[i].child_id != 0)
3407                         return true;
3408         }
3409         return false;
3410 }
3411
3412 /*
3413  * find the first free parallel slot (if any).
3414  */
3415 static int
3416 get_next_slot(ParallelSlot *slots, int n_slots)
3417 {
3418         int                     i;
3419
3420         for (i = 0; i < n_slots; i++)
3421         {
3422                 if (slots[i].child_id == 0)
3423                         return i;
3424         }
3425         return NO_SLOT;
3426 }
3427
3428
3429 /*
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.
3432  */
3433 static bool
3434 has_lock_conflicts(TocEntry *te1, TocEntry *te2)
3435 {
3436         int                     j,
3437                                 k;
3438
3439         for (j = 0; j < te1->nLockDeps; j++)
3440         {
3441                 for (k = 0; k < te2->nDeps; k++)
3442                 {
3443                         if (te1->lockDeps[j] == te2->dependencies[k])
3444                                 return true;
3445                 }
3446         }
3447         return false;
3448 }
3449
3450
3451 /*
3452  * Initialize the header of a parallel-processing list.
3453  *
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.
3457  */
3458 static void
3459 par_list_header_init(TocEntry *l)
3460 {
3461         l->par_prev = l->par_next = l;
3462 }
3463
3464 /* Append te to the end of the parallel-processing list headed by l */
3465 static void
3466 par_list_append(TocEntry *l, TocEntry *te)
3467 {
3468         te->par_prev = l->par_prev;
3469         l->par_prev->par_next = te;
3470         l->par_prev = te;
3471         te->par_next = l;
3472 }
3473
3474 /* Remove te from whatever parallel-processing list it's in */
3475 static void
3476 par_list_remove(TocEntry *te)
3477 {
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;
3482 }
3483
3484
3485 /*
3486  * Find the next work item (if any) that is capable of being run now.
3487  *
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.
3492  *
3493  * Note that the returned item has *not* been removed from ready_list.
3494  * The caller must do that after successfully dispatching the item.
3495  *
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.
3499  */
3500 static TocEntry *
3501 get_next_work_item(ArchiveHandle *AH, TocEntry *ready_list,
3502                                    ParallelSlot *slots, int n_slots)
3503 {
3504         bool            pref_non_data = false;  /* or get from AH->ropt */
3505         TocEntry   *data_te = NULL;
3506         TocEntry   *te;
3507         int                     i,
3508                                 k;
3509
3510         /*
3511          * Bogus heuristics for pref_non_data
3512          */
3513         if (pref_non_data)
3514         {
3515                 int                     count = 0;
3516
3517                 for (k = 0; k < n_slots; k++)
3518                         if (slots[k].args->te != NULL &&
3519                                 slots[k].args->te->section == SECTION_DATA)
3520                                 count++;
3521                 if (n_slots == 0 || count * 4 < n_slots)
3522                         pref_non_data = false;
3523         }
3524
3525         /*
3526          * Search the ready_list until we find a suitable item.
3527          */
3528         for (te = ready_list->par_next; te != ready_list; te = te->par_next)
3529         {
3530                 bool            conflicts = false;
3531
3532                 /*
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.
3536                  */
3537                 for (i = 0; i < n_slots && !conflicts; i++)
3538                 {
3539                         TocEntry   *running_te;
3540
3541                         if (slots[i].args == NULL)
3542                                 continue;
3543                         running_te = slots[i].args->te;
3544
3545                         if (has_lock_conflicts(te, running_te) ||
3546                                 has_lock_conflicts(running_te, te))
3547                         {
3548                                 conflicts = true;
3549                                 break;
3550                         }
3551                 }
3552
3553                 if (conflicts)
3554                         continue;
3555
3556                 if (pref_non_data && te->section == SECTION_DATA)
3557                 {
3558                         if (data_te == NULL)
3559                                 data_te = te;
3560                         continue;
3561                 }
3562
3563                 /* passed all tests, so this item can run */
3564                 return te;
3565         }
3566
3567         if (data_te != NULL)
3568                 return data_te;
3569
3570         ahlog(AH, 2, "no item ready\n");
3571         return NULL;
3572 }
3573
3574
3575 /*
3576  * Restore a single TOC item in parallel with others
3577  *
3578  * this is the procedure run as a thread (Windows) or a
3579  * separate process (everything else).
3580  */
3581 static parallel_restore_result
3582 parallel_restore(RestoreArgs *args)
3583 {
3584         ArchiveHandle *AH = args->AH;
3585         TocEntry   *te = args->te;
3586         RestoreOptions *ropt = AH->ropt;
3587         int                     retval;
3588
3589         /*
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.
3594          *
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.
3597          */
3598         if (te->section == SECTION_DATA)
3599                 (AH->ReopenPtr) (AH);
3600 #ifndef WIN32
3601         else
3602                 (AH->ClosePtr) (AH);
3603 #endif
3604
3605         /*
3606          * We need our own database connection, too
3607          */
3608         ConnectDatabase((Archive *) AH, ropt->dbname,
3609                                         ropt->pghost, ropt->pgport, ropt->username,
3610                                         ropt->promptPassword);
3611
3612         _doSetFixedOutputState(AH);
3613
3614         /* Restore the TOC item */
3615         retval = restore_toc_entry(AH, te, ropt, true);
3616
3617         /* And clean up */
3618         PQfinish(AH->connection);
3619         AH->connection = NULL;
3620
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);
3624
3625         if (retval == 0 && AH->public.n_errors)
3626                 retval = WORKER_IGNORED_ERRORS;
3627
3628 #ifndef WIN32
3629         exit(retval);
3630 #else
3631         return retval;
3632 #endif
3633 }
3634
3635
3636 /*
3637  * Housekeeping to be done after a step has been parallel restored.
3638  *
3639  * Clear the appropriate slot, free all the extra memory we allocated,
3640  * update status, and reduce the dependency count of any dependent items.
3641  */
3642 static void
3643 mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
3644                            thandle worker, int status,
3645                            ParallelSlot *slots, int n_slots)
3646 {
3647         TocEntry   *te = NULL;
3648         int                     i;
3649
3650         for (i = 0; i < n_slots; i++)
3651         {
3652                 if (slots[i].child_id == worker)
3653                 {
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;
3659
3660                         break;
3661                 }
3662         }
3663
3664         if (te == NULL)
3665                 die_horribly(AH, modulename, "could not find slot of finished worker\n");
3666
3667         ahlog(AH, 1, "finished item %d %s %s\n",
3668                   te->dumpId, te->desc, te->tag);
3669
3670         if (status == WORKER_CREATE_DONE)
3671                 mark_create_done(AH, te);
3672         else if (status == WORKER_INHIBIT_DATA)
3673         {
3674                 inhibit_data_for_failed_table(AH, te);
3675                 AH->public.n_errors++;
3676         }
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",
3681                                          status);
3682
3683         reduce_dependencies(AH, te, ready_list);
3684 }
3685
3686
3687 /*
3688  * Process the dependency information into a form useful for parallel restore.
3689  *
3690  * We set up depCount fields that are the number of as-yet-unprocessed
3691  * dependencies for each TOC entry.
3692  *
3693  * We also identify locking dependencies so that we can avoid trying to
3694  * schedule conflicting items at the same time.
3695  */
3696 static void
3697 fix_dependencies(ArchiveHandle *AH)
3698 {
3699         TocEntry  **tocsByDumpId;
3700         TocEntry   *te;
3701         DumpId          maxDumpId;
3702         int                     i;
3703
3704         /*
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.
3708          *
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.
3712          *
3713          * Also, initialize the depCount fields, and make sure all the TOC items
3714          * are marked as not being in any parallel-processing list.
3715          */
3716         maxDumpId = AH->maxDumpId;
3717         tocsByDumpId = (TocEntry **) calloc(maxDumpId, sizeof(TocEntry *));
3718         for (te = AH->toc->next; te != AH->toc; te = te->next)
3719         {
3720                 tocsByDumpId[te->dumpId - 1] = te;
3721                 te->depCount = te->nDeps;
3722                 te->par_prev = NULL;
3723                 te->par_next = NULL;
3724         }
3725
3726         /*
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
3731          * dependencies.
3732          *
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.
3739          */
3740         for (te = AH->toc->next; te != AH->toc; te = te->next)
3741         {
3742                 if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
3743                 {
3744                         DumpId          tableId = te->dependencies[0];
3745
3746                         if (tableId > maxDumpId ||
3747                                 tocsByDumpId[tableId - 1] == NULL ||
3748                                 strcmp(tocsByDumpId[tableId - 1]->desc, "TABLE") == 0)
3749                         {
3750                                 repoint_table_dependencies(AH, tableId, te->dumpId);
3751                         }
3752                 }
3753         }
3754
3755         /*
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.)
3759          */
3760         if (AH->version < K_VERS_1_11)
3761         {
3762                 for (te = AH->toc->next; te != AH->toc; te = te->next)
3763                 {
3764                         if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
3765                         {
3766                                 TocEntry   *te2;
3767
3768                                 for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
3769                                 {
3770                                         if (strcmp(te2->desc, "BLOBS") == 0)
3771                                         {
3772                                                 te->dependencies = (DumpId *) malloc(sizeof(DumpId));
3773                                                 te->dependencies[0] = te2->dumpId;
3774                                                 te->nDeps++;
3775                                                 te->depCount++;
3776                                                 break;
3777                                         }
3778                                 }
3779                                 break;
3780                         }
3781                 }
3782         }
3783
3784         /*
3785          * It is possible that the dependencies list items that are not in the
3786          * archive at all.      Subtract such items from the depCounts.
3787          */
3788         for (te = AH->toc->next; te != AH->toc; te = te->next)
3789         {
3790                 for (i = 0; i < te->nDeps; i++)
3791                 {
3792                         DumpId          depid = te->dependencies[i];
3793
3794                         if (depid > maxDumpId || tocsByDumpId[depid - 1] == NULL)
3795                                 te->depCount--;
3796                 }
3797         }
3798
3799         /*
3800          * Lastly, work out the locking dependencies.
3801          */
3802         for (te = AH->toc->next; te != AH->toc; te = te->next)
3803         {
3804                 te->lockDeps = NULL;
3805                 te->nLockDeps = 0;
3806                 identify_locking_dependencies(te, tocsByDumpId, maxDumpId);
3807         }
3808
3809         free(tocsByDumpId);
3810 }
3811
3812 /*
3813  * Change dependencies on tableId to depend on tableDataId instead,
3814  * but only in POST_DATA items.
3815  */
3816 static void
3817 repoint_table_dependencies(ArchiveHandle *AH,
3818                                                    DumpId tableId, DumpId tableDataId)
3819 {
3820         TocEntry   *te;
3821         int                     i;
3822
3823         for (te = AH->toc->next; te != AH->toc; te = te->next)
3824         {
3825                 if (te->section != SECTION_POST_DATA)
3826                         continue;
3827                 for (i = 0; i < te->nDeps; i++)
3828                 {
3829                         if (te->dependencies[i] == tableId)
3830                         {
3831                                 te->dependencies[i] = tableDataId;
3832                                 ahlog(AH, 2, "transferring dependency %d -> %d to %d\n",
3833                                           te->dumpId, tableId, tableDataId);
3834                         }
3835                 }
3836         }
3837 }
3838
3839 /*
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.
3845  */
3846 static void
3847 identify_locking_dependencies(TocEntry *te,
3848                                                           TocEntry **tocsByDumpId,
3849                                                           DumpId maxDumpId)
3850 {
3851         DumpId     *lockids;
3852         int                     nlockids;
3853         int                     i;
3854
3855         /* Quick exit if no dependencies at all */
3856         if (te->nDeps == 0)
3857                 return;
3858
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))
3865                 return;
3866
3867         /*
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.)
3873          */
3874         lockids = (DumpId *) malloc(te->nDeps * sizeof(DumpId));
3875         nlockids = 0;
3876         for (i = 0; i < te->nDeps; i++)
3877         {
3878                 DumpId          depid = te->dependencies[i];
3879
3880                 if (depid <= maxDumpId && tocsByDumpId[depid - 1] &&
3881                         strcmp(tocsByDumpId[depid - 1]->desc, "TABLE DATA") == 0)
3882                         lockids[nlockids++] = depid;
3883         }
3884
3885         if (nlockids == 0)
3886         {
3887                 free(lockids);
3888                 return;
3889         }
3890
3891         te->lockDeps = realloc(lockids, nlockids * sizeof(DumpId));
3892         te->nLockDeps = nlockids;
3893 }
3894
3895 /*
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.
3899  */
3900 static void
3901 reduce_dependencies(ArchiveHandle *AH, TocEntry *te, TocEntry *ready_list)
3902 {
3903         DumpId          target = te->dumpId;
3904         int                     i;
3905
3906         ahlog(AH, 2, "reducing dependencies for %d\n", target);
3907
3908         /*
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.
3912          */
3913         for (te = AH->toc->next; te != AH->toc; te = te->next)
3914         {
3915                 for (i = 0; i < te->nDeps; i++)
3916                 {
3917                         if (te->dependencies[i] == target)
3918                         {
3919                                 te->depCount--;
3920                                 if (te->depCount == 0 && te->par_prev != NULL)
3921                                 {
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);
3926                                 }
3927                         }
3928                 }
3929         }
3930 }
3931
3932 /*
3933  * Set the created flag on the DATA member corresponding to the given
3934  * TABLE member
3935  */
3936 static void
3937 mark_create_done(ArchiveHandle *AH, TocEntry *te)
3938 {
3939         TocEntry   *tes;
3940
3941         for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
3942         {
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)
3947                 {
3948                         tes->created = true;
3949                         break;
3950                 }
3951         }
3952 }
3953
3954 /*
3955  * Mark the DATA member corresponding to the given TABLE member
3956  * as not wanted
3957  */
3958 static void
3959 inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
3960 {
3961         RestoreOptions *ropt = AH->ropt;
3962         TocEntry   *tes;
3963
3964         ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
3965                   te->tag);
3966
3967         for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
3968         {
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)
3973                 {
3974                         /* mark it unwanted; we assume idWanted array already exists */
3975                         ropt->idWanted[tes->dumpId - 1] = false;
3976                         break;
3977                 }
3978         }
3979 }
3980
3981
3982 /*
3983  * Clone and de-clone routines used in parallel restoration.
3984  *
3985  * Enough of the structure is cloned to ensure that there is no
3986  * conflict between different threads each with their own clone.
3987  *
3988  * These could be public, but no need at present.
3989  */
3990 static ArchiveHandle *
3991 CloneArchive(ArchiveHandle *AH)
3992 {
3993         ArchiveHandle *clone;
3994
3995         /* Make a "flat" copy */
3996         clone = (ArchiveHandle *) malloc(sizeof(ArchiveHandle));
3997         if (clone == NULL)
3998                 die_horribly(AH, modulename, "out of memory\n");
3999         memcpy(clone, AH, sizeof(ArchiveHandle));
4000
4001         /* Handle format-independent fields */
4002         clone->pgCopyBuf = createPQExpBuffer();
4003         clone->sqlBuf = createPQExpBuffer();
4004         clone->sqlparse.tagBuf = NULL;
4005
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;
4012
4013         /* savedPassword must be local in case we change it while connecting */
4014         if (clone->savedPassword)
4015                 clone->savedPassword = strdup(clone->savedPassword);
4016
4017         /* clone has its own error count, too */
4018         clone->public.n_errors = 0;
4019
4020         /* Let the format-specific code have a chance too */
4021         (clone->ClonePtr) (clone);
4022
4023         return clone;
4024 }
4025
4026 /*
4027  * Release clone-local storage.
4028  *
4029  * Note: we assume any clone-local connection was already closed.
4030  */
4031 static void
4032 DeCloneArchive(ArchiveHandle *AH)
4033 {
4034         /* Clear format-specific state */
4035         (AH->DeClonePtr) (AH);
4036
4037         /* Clear state allocated by CloneArchive */
4038         destroyPQExpBuffer(AH->pgCopyBuf);
4039         destroyPQExpBuffer(AH->sqlBuf);
4040         if (AH->sqlparse.tagBuf)
4041                 destroyPQExpBuffer(AH->sqlparse.tagBuf);
4042
4043         /* Clear any connection-local state */
4044         if (AH->currUser)
4045                 free(AH->currUser);
4046         if (AH->currSchema)
4047                 free(AH->currSchema);
4048         if (AH->currTablespace)
4049                 free(AH->currTablespace);
4050         if (AH->savedPassword)
4051                 free(AH->savedPassword);
4052
4053         free(AH);
4054 }