LCOV - code coverage report
Current view: top level - src/bin/pg_dump - pg_backup_archiver.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1398 1894 73.8 %
Date: 2019-11-15 22:06:47 Functions: 91 98 92.9 %
Legend: Lines: hit not hit

          Line data    Source code
       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             :  *      src/bin/pg_dump/pg_backup_archiver.c
      19             :  *
      20             :  *-------------------------------------------------------------------------
      21             :  */
      22             : #include "postgres_fe.h"
      23             : 
      24             : #include <ctype.h>
      25             : #include <fcntl.h>
      26             : #include <unistd.h>
      27             : #include <sys/stat.h>
      28             : #include <sys/wait.h>
      29             : #ifdef WIN32
      30             : #include <io.h>
      31             : #endif
      32             : 
      33             : #include "dumputils.h"
      34             : #include "fe_utils/string_utils.h"
      35             : #include "libpq/libpq-fs.h"
      36             : #include "parallel.h"
      37             : #include "pg_backup_archiver.h"
      38             : #include "pg_backup_db.h"
      39             : #include "pg_backup_utils.h"
      40             : 
      41             : #define TEXT_DUMP_HEADER "--\n-- PostgreSQL database dump\n--\n\n"
      42             : #define TEXT_DUMPALL_HEADER "--\n-- PostgreSQL database cluster dump\n--\n\n"
      43             : 
      44             : /* state needed to save/restore an archive's output target */
      45             : typedef struct _outputContext
      46             : {
      47             :     void       *OF;
      48             :     int         gzOut;
      49             : } OutputContext;
      50             : 
      51             : /*
      52             :  * State for tracking TocEntrys that are ready to process during a parallel
      53             :  * restore.  (This used to be a list, and we still call it that, though now
      54             :  * it's really an array so that we can apply qsort to it.)
      55             :  *
      56             :  * tes[] is sized large enough that we can't overrun it.
      57             :  * The valid entries are indexed first_te .. last_te inclusive.
      58             :  * We periodically sort the array to bring larger-by-dataLength entries to
      59             :  * the front; "sorted" is true if the valid entries are known sorted.
      60             :  */
      61             : typedef struct _parallelReadyList
      62             : {
      63             :     TocEntry  **tes;            /* Ready-to-dump TocEntrys */
      64             :     int         first_te;       /* index of first valid entry in tes[] */
      65             :     int         last_te;        /* index of last valid entry in tes[] */
      66             :     bool        sorted;         /* are valid entries currently sorted? */
      67             : } ParallelReadyList;
      68             : 
      69             : 
      70             : static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
      71             :                                const int compression, bool dosync, ArchiveMode mode,
      72             :                                SetupWorkerPtrType setupWorkerPtr);
      73             : static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
      74             :                                   ArchiveHandle *AH);
      75             : static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData);
      76             : static char *sanitize_line(const char *str, bool want_hyphen);
      77             : static void _doSetFixedOutputState(ArchiveHandle *AH);
      78             : static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
      79             : static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
      80             : static void _becomeUser(ArchiveHandle *AH, const char *user);
      81             : static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
      82             : static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
      83             : static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
      84             : static void _selectTableAccessMethod(ArchiveHandle *AH, const char *tableam);
      85             : static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
      86             : static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
      87             : static void processSearchPathEntry(ArchiveHandle *AH, TocEntry *te);
      88             : static teReqs _tocEntryRequired(TocEntry *te, teSection curSection, ArchiveHandle *AH);
      89             : static RestorePass _tocEntryRestorePass(TocEntry *te);
      90             : static bool _tocEntryIsACL(TocEntry *te);
      91             : static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te);
      92             : static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te);
      93             : static void buildTocEntryArrays(ArchiveHandle *AH);
      94             : static void _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
      95             : static int  _discoverArchiveFormat(ArchiveHandle *AH);
      96             : 
      97             : static int  RestoringToDB(ArchiveHandle *AH);
      98             : static void dump_lo_buf(ArchiveHandle *AH);
      99             : static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
     100             : static void SetOutput(ArchiveHandle *AH, const char *filename, int compression);
     101             : static OutputContext SaveOutput(ArchiveHandle *AH);
     102             : static void RestoreOutput(ArchiveHandle *AH, OutputContext savedContext);
     103             : 
     104             : static int  restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel);
     105             : static void restore_toc_entries_prefork(ArchiveHandle *AH,
     106             :                                         TocEntry *pending_list);
     107             : static void restore_toc_entries_parallel(ArchiveHandle *AH,
     108             :                                          ParallelState *pstate,
     109             :                                          TocEntry *pending_list);
     110             : static void restore_toc_entries_postfork(ArchiveHandle *AH,
     111             :                                          TocEntry *pending_list);
     112             : static void pending_list_header_init(TocEntry *l);
     113             : static void pending_list_append(TocEntry *l, TocEntry *te);
     114             : static void pending_list_remove(TocEntry *te);
     115             : static void ready_list_init(ParallelReadyList *ready_list, int tocCount);
     116             : static void ready_list_free(ParallelReadyList *ready_list);
     117             : static void ready_list_insert(ParallelReadyList *ready_list, TocEntry *te);
     118             : static void ready_list_remove(ParallelReadyList *ready_list, int i);
     119             : static void ready_list_sort(ParallelReadyList *ready_list);
     120             : static int  TocEntrySizeCompare(const void *p1, const void *p2);
     121             : static void move_to_ready_list(TocEntry *pending_list,
     122             :                                ParallelReadyList *ready_list,
     123             :                                RestorePass pass);
     124             : static TocEntry *pop_next_work_item(ArchiveHandle *AH,
     125             :                                     ParallelReadyList *ready_list,
     126             :                                     ParallelState *pstate);
     127             : static void mark_dump_job_done(ArchiveHandle *AH,
     128             :                                TocEntry *te,
     129             :                                int status,
     130             :                                void *callback_data);
     131             : static void mark_restore_job_done(ArchiveHandle *AH,
     132             :                                   TocEntry *te,
     133             :                                   int status,
     134             :                                   void *callback_data);
     135             : static void fix_dependencies(ArchiveHandle *AH);
     136             : static bool has_lock_conflicts(TocEntry *te1, TocEntry *te2);
     137             : static void repoint_table_dependencies(ArchiveHandle *AH);
     138             : static void identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te);
     139             : static void reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
     140             :                                 ParallelReadyList *ready_list);
     141             : static void mark_create_done(ArchiveHandle *AH, TocEntry *te);
     142             : static void inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te);
     143             : 
     144             : static void StrictNamesCheck(RestoreOptions *ropt);
     145             : 
     146             : 
     147             : /*
     148             :  * Allocate a new DumpOptions block containing all default values.
     149             :  */
     150             : DumpOptions *
     151          40 : NewDumpOptions(void)
     152             : {
     153          40 :     DumpOptions *opts = (DumpOptions *) pg_malloc(sizeof(DumpOptions));
     154             : 
     155          40 :     InitDumpOptions(opts);
     156          40 :     return opts;
     157             : }
     158             : 
     159             : /*
     160             :  * Initialize a DumpOptions struct to all default values
     161             :  */
     162             : void
     163         228 : InitDumpOptions(DumpOptions *opts)
     164             : {
     165         228 :     memset(opts, 0, sizeof(DumpOptions));
     166             :     /* set any fields that shouldn't default to zeroes */
     167         228 :     opts->include_everything = true;
     168         228 :     opts->dumpSections = DUMP_UNSECTIONED;
     169         228 : }
     170             : 
     171             : /*
     172             :  * Create a freshly allocated DumpOptions with options equivalent to those
     173             :  * found in the given RestoreOptions.
     174             :  */
     175             : DumpOptions *
     176          40 : dumpOptionsFromRestoreOptions(RestoreOptions *ropt)
     177             : {
     178          40 :     DumpOptions *dopt = NewDumpOptions();
     179             : 
     180             :     /* this is the inverse of what's at the end of pg_dump.c's main() */
     181          40 :     dopt->outputClean = ropt->dropSchema;
     182          40 :     dopt->dataOnly = ropt->dataOnly;
     183          40 :     dopt->schemaOnly = ropt->schemaOnly;
     184          40 :     dopt->if_exists = ropt->if_exists;
     185          40 :     dopt->column_inserts = ropt->column_inserts;
     186          40 :     dopt->dumpSections = ropt->dumpSections;
     187          40 :     dopt->aclsSkip = ropt->aclsSkip;
     188          40 :     dopt->outputSuperuser = ropt->superuser;
     189          40 :     dopt->outputCreateDB = ropt->createDB;
     190          40 :     dopt->outputNoOwner = ropt->noOwner;
     191          40 :     dopt->outputNoTablespaces = ropt->noTablespace;
     192          40 :     dopt->disable_triggers = ropt->disable_triggers;
     193          40 :     dopt->use_setsessauth = ropt->use_setsessauth;
     194          40 :     dopt->disable_dollar_quoting = ropt->disable_dollar_quoting;
     195          40 :     dopt->dump_inserts = ropt->dump_inserts;
     196          40 :     dopt->no_comments = ropt->no_comments;
     197          40 :     dopt->no_publications = ropt->no_publications;
     198          40 :     dopt->no_security_labels = ropt->no_security_labels;
     199          40 :     dopt->no_subscriptions = ropt->no_subscriptions;
     200          40 :     dopt->lockWaitTimeout = ropt->lockWaitTimeout;
     201          40 :     dopt->include_everything = ropt->include_everything;
     202          40 :     dopt->enable_row_security = ropt->enable_row_security;
     203          40 :     dopt->sequence_data = ropt->sequence_data;
     204             : 
     205          40 :     return dopt;
     206             : }
     207             : 
     208             : 
     209             : /*
     210             :  *  Wrapper functions.
     211             :  *
     212             :  *  The objective it to make writing new formats and dumpers as simple
     213             :  *  as possible, if necessary at the expense of extra function calls etc.
     214             :  *
     215             :  */
     216             : 
     217             : /*
     218             :  * The dump worker setup needs lots of knowledge of the internals of pg_dump,
     219             :  * so It's defined in pg_dump.c and passed into OpenArchive. The restore worker
     220             :  * setup doesn't need to know anything much, so it's defined here.
     221             :  */
     222             : static void
     223           8 : setupRestoreWorker(Archive *AHX)
     224             : {
     225           8 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
     226             : 
     227           8 :     AH->ReopenPtr(AH);
     228           8 : }
     229             : 
     230             : 
     231             : /* Create a new archive */
     232             : /* Public */
     233             : Archive *
     234         168 : CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
     235             :               const int compression, bool dosync, ArchiveMode mode,
     236             :               SetupWorkerPtrType setupDumpWorker)
     237             : 
     238             : {
     239         168 :     ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, dosync,
     240             :                                  mode, setupDumpWorker);
     241             : 
     242         168 :     return (Archive *) AH;
     243             : }
     244             : 
     245             : /* Open an existing archive */
     246             : /* Public */
     247             : Archive *
     248          36 : OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
     249             : {
     250          36 :     ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, true, archModeRead, setupRestoreWorker);
     251             : 
     252          36 :     return (Archive *) AH;
     253             : }
     254             : 
     255             : /* Public */
     256             : void
     257         192 : CloseArchive(Archive *AHX)
     258             : {
     259         192 :     int         res = 0;
     260         192 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
     261             : 
     262         192 :     AH->ClosePtr(AH);
     263             : 
     264             :     /* Close the output */
     265         192 :     if (AH->gzOut)
     266           0 :         res = GZCLOSE(AH->OF);
     267         192 :     else if (AH->OF != stdout)
     268           0 :         res = fclose(AH->OF);
     269             : 
     270         192 :     if (res != 0)
     271           0 :         fatal("could not close output file: %m");
     272         192 : }
     273             : 
     274             : /* Public */
     275             : void
     276         368 : SetArchiveOptions(Archive *AH, DumpOptions *dopt, RestoreOptions *ropt)
     277             : {
     278             :     /* Caller can omit dump options, in which case we synthesize them */
     279         368 :     if (dopt == NULL && ropt != NULL)
     280          40 :         dopt = dumpOptionsFromRestoreOptions(ropt);
     281             : 
     282             :     /* Save options for later access */
     283         368 :     AH->dopt = dopt;
     284         368 :     AH->ropt = ropt;
     285         368 : }
     286             : 
     287             : /* Public */
     288             : void
     289         192 : ProcessArchiveRestoreOptions(Archive *AHX)
     290             : {
     291         192 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
     292         192 :     RestoreOptions *ropt = AH->public.ropt;
     293             :     TocEntry   *te;
     294             :     teSection   curSection;
     295             : 
     296             :     /* Decide which TOC entries will be dumped/restored, and mark them */
     297         192 :     curSection = SECTION_PRE_DATA;
     298       24932 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
     299             :     {
     300             :         /*
     301             :          * When writing an archive, we also take this opportunity to check
     302             :          * that we have generated the entries in a sane order that respects
     303             :          * the section divisions.  When reading, don't complain, since buggy
     304             :          * old versions of pg_dump might generate out-of-order archives.
     305             :          */
     306       24740 :         if (AH->mode != archModeRead)
     307             :         {
     308       19700 :             switch (te->section)
     309             :             {
     310             :                 case SECTION_NONE:
     311             :                     /* ok to be anywhere */
     312        2974 :                     break;
     313             :                 case SECTION_PRE_DATA:
     314        9852 :                     if (curSection != SECTION_PRE_DATA)
     315           0 :                         pg_log_warning("archive items not in correct section order");
     316        9852 :                     break;
     317             :                 case SECTION_DATA:
     318        2992 :                     if (curSection == SECTION_POST_DATA)
     319           0 :                         pg_log_warning("archive items not in correct section order");
     320        2992 :                     break;
     321             :                 case SECTION_POST_DATA:
     322             :                     /* ok no matter which section we were in */
     323        3882 :                     break;
     324             :                 default:
     325           0 :                     fatal("unexpected section code %d",
     326             :                           (int) te->section);
     327             :                     break;
     328             :             }
     329             :         }
     330             : 
     331       24740 :         if (te->section != SECTION_NONE)
     332       21012 :             curSection = te->section;
     333             : 
     334       24740 :         te->reqs = _tocEntryRequired(te, curSection, AH);
     335             :     }
     336             : 
     337             :     /* Enforce strict names checking */
     338         192 :     if (ropt->strict_names)
     339           0 :         StrictNamesCheck(ropt);
     340         192 : }
     341             : 
     342             : /* Public */
     343             : void
     344         162 : RestoreArchive(Archive *AHX)
     345             : {
     346         162 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
     347         162 :     RestoreOptions *ropt = AH->public.ropt;
     348             :     bool        parallel_mode;
     349             :     TocEntry   *te;
     350             :     OutputContext sav;
     351             : 
     352         162 :     AH->stage = STAGE_INITIALIZING;
     353             : 
     354             :     /*
     355             :      * If we're going to do parallel restore, there are some restrictions.
     356             :      */
     357         162 :     parallel_mode = (AH->public.numWorkers > 1 && ropt->useDB);
     358         162 :     if (parallel_mode)
     359             :     {
     360             :         /* We haven't got round to making this work for all archive formats */
     361           4 :         if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
     362           0 :             fatal("parallel restore is not supported with this archive file format");
     363             : 
     364             :         /* Doesn't work if the archive represents dependencies as OIDs */
     365           4 :         if (AH->version < K_VERS_1_8)
     366           0 :             fatal("parallel restore is not supported with archives made by pre-8.0 pg_dump");
     367             : 
     368             :         /*
     369             :          * It's also not gonna work if we can't reopen the input file, so
     370             :          * let's try that immediately.
     371             :          */
     372           4 :         AH->ReopenPtr(AH);
     373             :     }
     374             : 
     375             :     /*
     376             :      * Make sure we won't need (de)compression we haven't got
     377             :      */
     378             : #ifndef HAVE_LIBZ
     379             :     if (AH->compression != 0 && AH->PrintTocDataPtr != NULL)
     380             :     {
     381             :         for (te = AH->toc->next; te != AH->toc; te = te->next)
     382             :         {
     383             :             if (te->hadDumper && (te->reqs & REQ_DATA) != 0)
     384             :                 fatal("cannot restore from compressed archive (compression not supported in this installation)");
     385             :         }
     386             :     }
     387             : #endif
     388             : 
     389             :     /*
     390             :      * Prepare index arrays, so we can assume we have them throughout restore.
     391             :      * It's possible we already did this, though.
     392             :      */
     393         162 :     if (AH->tocsByDumpId == NULL)
     394         158 :         buildTocEntryArrays(AH);
     395             : 
     396             :     /*
     397             :      * If we're using a DB connection, then connect it.
     398             :      */
     399         162 :     if (ropt->useDB)
     400             :     {
     401          16 :         pg_log_info("connecting to database for restore");
     402          16 :         if (AH->version < K_VERS_1_3)
     403           0 :             fatal("direct database connections are not supported in pre-1.3 archives");
     404             : 
     405             :         /*
     406             :          * We don't want to guess at whether the dump will successfully
     407             :          * restore; allow the attempt regardless of the version of the restore
     408             :          * target.
     409             :          */
     410          16 :         AHX->minRemoteVersion = 0;
     411          16 :         AHX->maxRemoteVersion = 9999999;
     412             : 
     413          32 :         ConnectDatabase(AHX, ropt->dbname,
     414          16 :                         ropt->pghost, ropt->pgport, ropt->username,
     415             :                         ropt->promptPassword);
     416             : 
     417             :         /*
     418             :          * If we're talking to the DB directly, don't send comments since they
     419             :          * obscure SQL when displaying errors
     420             :          */
     421          16 :         AH->noTocComments = 1;
     422             :     }
     423             : 
     424             :     /*
     425             :      * Work out if we have an implied data-only restore. This can happen if
     426             :      * the dump was data only or if the user has used a toc list to exclude
     427             :      * all of the schema data. All we do is look for schema entries - if none
     428             :      * are found then we set the dataOnly flag.
     429             :      *
     430             :      * We could scan for wanted TABLE entries, but that is not the same as
     431             :      * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
     432             :      */
     433         162 :     if (!ropt->dataOnly)
     434             :     {
     435         154 :         int         impliedDataOnly = 1;
     436             : 
     437        1390 :         for (te = AH->toc->next; te != AH->toc; te = te->next)
     438             :         {
     439        1364 :             if ((te->reqs & REQ_SCHEMA) != 0)
     440             :             {                   /* It's schema, and it's wanted */
     441         128 :                 impliedDataOnly = 0;
     442         128 :                 break;
     443             :             }
     444             :         }
     445         154 :         if (impliedDataOnly)
     446             :         {
     447          26 :             ropt->dataOnly = impliedDataOnly;
     448          26 :             pg_log_info("implied data-only restore");
     449             :         }
     450             :     }
     451             : 
     452             :     /*
     453             :      * Setup the output file if necessary.
     454             :      */
     455         162 :     sav = SaveOutput(AH);
     456         162 :     if (ropt->filename || ropt->compression)
     457         142 :         SetOutput(AH, ropt->filename, ropt->compression);
     458             : 
     459         162 :     ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
     460             : 
     461         162 :     if (AH->archiveRemoteVersion)
     462         162 :         ahprintf(AH, "-- Dumped from database version %s\n",
     463             :                  AH->archiveRemoteVersion);
     464         162 :     if (AH->archiveDumpVersion)
     465         162 :         ahprintf(AH, "-- Dumped by pg_dump version %s\n",
     466             :                  AH->archiveDumpVersion);
     467             : 
     468         162 :     ahprintf(AH, "\n");
     469             : 
     470         162 :     if (AH->public.verbose)
     471          28 :         dumpTimestamp(AH, "Started on", AH->createDate);
     472             : 
     473         162 :     if (ropt->single_txn)
     474             :     {
     475           0 :         if (AH->connection)
     476           0 :             StartTransaction(AHX);
     477             :         else
     478           0 :             ahprintf(AH, "BEGIN;\n\n");
     479             :     }
     480             : 
     481             :     /*
     482             :      * Establish important parameter values right away.
     483             :      */
     484         162 :     _doSetFixedOutputState(AH);
     485             : 
     486         162 :     AH->stage = STAGE_PROCESSING;
     487             : 
     488             :     /*
     489             :      * Drop the items at the start, in reverse order
     490             :      */
     491         162 :     if (ropt->dropSchema)
     492             :     {
     493        1310 :         for (te = AH->toc->prev; te != AH->toc; te = te->prev)
     494             :         {
     495        1292 :             AH->currentTE = te;
     496             : 
     497             :             /*
     498             :              * In createDB mode, issue a DROP *only* for the database as a
     499             :              * whole.  Issuing drops against anything else would be wrong,
     500             :              * because at this point we're connected to the wrong database.
     501             :              * (The DATABASE PROPERTIES entry, if any, should be treated like
     502             :              * the DATABASE entry.)
     503             :              */
     504        1292 :             if (ropt->createDB)
     505             :             {
     506         900 :                 if (strcmp(te->desc, "DATABASE") != 0 &&
     507         446 :                     strcmp(te->desc, "DATABASE PROPERTIES") != 0)
     508         442 :                     continue;
     509             :             }
     510             : 
     511             :             /* Otherwise, drop anything that's selected and has a dropStmt */
     512         850 :             if (((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0) && te->dropStmt)
     513             :             {
     514         396 :                 pg_log_info("dropping %s %s", te->desc, te->tag);
     515             :                 /* Select owner and schema as necessary */
     516         396 :                 _becomeOwner(AH, te);
     517         396 :                 _selectOutputSchema(AH, te->namespace);
     518             : 
     519             :                 /*
     520             :                  * Now emit the DROP command, if the object has one.  Note we
     521             :                  * don't necessarily emit it verbatim; at this point we add an
     522             :                  * appropriate IF EXISTS clause, if the user requested it.
     523             :                  */
     524         396 :                 if (*te->dropStmt != '\0')
     525             :                 {
     526         390 :                     if (!ropt->if_exists)
     527             :                     {
     528             :                         /* No --if-exists?  Then just use the original */
     529         200 :                         ahprintf(AH, "%s", te->dropStmt);
     530             :                     }
     531             :                     else
     532             :                     {
     533             :                         /*
     534             :                          * Inject an appropriate spelling of "if exists".  For
     535             :                          * large objects, we have a separate routine that
     536             :                          * knows how to do it, without depending on
     537             :                          * te->dropStmt; use that.  For other objects we need
     538             :                          * to parse the command.
     539             :                          */
     540         190 :                         if (strncmp(te->desc, "BLOB", 4) == 0)
     541             :                         {
     542           2 :                             DropBlobIfExists(AH, te->catalogId.oid);
     543             :                         }
     544             :                         else
     545             :                         {
     546         188 :                             char       *dropStmt = pg_strdup(te->dropStmt);
     547         188 :                             char       *dropStmtOrig = dropStmt;
     548         188 :                             PQExpBuffer ftStmt = createPQExpBuffer();
     549             : 
     550             :                             /*
     551             :                              * Need to inject IF EXISTS clause after ALTER
     552             :                              * TABLE part in ALTER TABLE .. DROP statement
     553             :                              */
     554         188 :                             if (strncmp(dropStmt, "ALTER TABLE", 11) == 0)
     555             :                             {
     556          22 :                                 appendPQExpBufferStr(ftStmt,
     557             :                                                      "ALTER TABLE IF EXISTS");
     558          22 :                                 dropStmt = dropStmt + 11;
     559             :                             }
     560             : 
     561             :                             /*
     562             :                              * ALTER TABLE..ALTER COLUMN..DROP DEFAULT does
     563             :                              * not support the IF EXISTS clause, and therefore
     564             :                              * we simply emit the original command for DEFAULT
     565             :                              * objects (modulo the adjustment made above).
     566             :                              *
     567             :                              * Likewise, don't mess with DATABASE PROPERTIES.
     568             :                              *
     569             :                              * If we used CREATE OR REPLACE VIEW as a means of
     570             :                              * quasi-dropping an ON SELECT rule, that should
     571             :                              * be emitted unchanged as well.
     572             :                              *
     573             :                              * For other object types, we need to extract the
     574             :                              * first part of the DROP which includes the
     575             :                              * object type.  Most of the time this matches
     576             :                              * te->desc, so search for that; however for the
     577             :                              * different kinds of CONSTRAINTs, we know to
     578             :                              * search for hardcoded "DROP CONSTRAINT" instead.
     579             :                              */
     580         370 :                             if (strcmp(te->desc, "DEFAULT") == 0 ||
     581         364 :                                 strcmp(te->desc, "DATABASE PROPERTIES") == 0 ||
     582         182 :                                 strncmp(dropStmt, "CREATE OR REPLACE VIEW", 22) == 0)
     583           6 :                                 appendPQExpBufferStr(ftStmt, dropStmt);
     584             :                             else
     585             :                             {
     586             :                                 char        buffer[40];
     587             :                                 char       *mark;
     588             : 
     589         352 :                                 if (strcmp(te->desc, "CONSTRAINT") == 0 ||
     590         340 :                                     strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
     591         170 :                                     strcmp(te->desc, "FK CONSTRAINT") == 0)
     592          16 :                                     strcpy(buffer, "DROP CONSTRAINT");
     593             :                                 else
     594         166 :                                     snprintf(buffer, sizeof(buffer), "DROP %s",
     595             :                                              te->desc);
     596             : 
     597         182 :                                 mark = strstr(dropStmt, buffer);
     598             : 
     599         182 :                                 if (mark)
     600             :                                 {
     601         182 :                                     *mark = '\0';
     602         182 :                                     appendPQExpBuffer(ftStmt, "%s%s IF EXISTS%s",
     603             :                                                       dropStmt, buffer,
     604         182 :                                                       mark + strlen(buffer));
     605             :                                 }
     606             :                                 else
     607             :                                 {
     608             :                                     /* complain and emit unmodified command */
     609           0 :                                     pg_log_warning("could not find where to insert IF EXISTS in statement \"%s\"",
     610             :                                                    dropStmtOrig);
     611           0 :                                     appendPQExpBufferStr(ftStmt, dropStmt);
     612             :                                 }
     613             :                             }
     614             : 
     615         188 :                             ahprintf(AH, "%s", ftStmt->data);
     616             : 
     617         188 :                             destroyPQExpBuffer(ftStmt);
     618         188 :                             pg_free(dropStmtOrig);
     619             :                         }
     620             :                     }
     621             :                 }
     622             :             }
     623             :         }
     624             : 
     625             :         /*
     626             :          * _selectOutputSchema may have set currSchema to reflect the effect
     627             :          * of a "SET search_path" command it emitted.  However, by now we may
     628             :          * have dropped that schema; or it might not have existed in the first
     629             :          * place.  In either case the effective value of search_path will not
     630             :          * be what we think.  Forcibly reset currSchema so that we will
     631             :          * re-establish the search_path setting when needed (after creating
     632             :          * the schema).
     633             :          *
     634             :          * If we treated users as pg_dump'able objects then we'd need to reset
     635             :          * currUser here too.
     636             :          */
     637          18 :         if (AH->currSchema)
     638           0 :             free(AH->currSchema);
     639          18 :         AH->currSchema = NULL;
     640             :     }
     641             : 
     642         162 :     if (parallel_mode)
     643             :     {
     644             :         /*
     645             :          * In parallel mode, turn control over to the parallel-restore logic.
     646             :          */
     647             :         ParallelState *pstate;
     648             :         TocEntry    pending_list;
     649             : 
     650             :         /* The archive format module may need some setup for this */
     651           4 :         if (AH->PrepParallelRestorePtr)
     652           4 :             AH->PrepParallelRestorePtr(AH);
     653             : 
     654           4 :         pending_list_header_init(&pending_list);
     655             : 
     656             :         /* This runs PRE_DATA items and then disconnects from the database */
     657           4 :         restore_toc_entries_prefork(AH, &pending_list);
     658             :         Assert(AH->connection == NULL);
     659             : 
     660             :         /* ParallelBackupStart() will actually fork the processes */
     661           4 :         pstate = ParallelBackupStart(AH);
     662           4 :         restore_toc_entries_parallel(AH, pstate, &pending_list);
     663           4 :         ParallelBackupEnd(AH, pstate);
     664             : 
     665             :         /* reconnect the master and see if we missed something */
     666           4 :         restore_toc_entries_postfork(AH, &pending_list);
     667             :         Assert(AH->connection != NULL);
     668             :     }
     669             :     else
     670             :     {
     671             :         /*
     672             :          * In serial mode, process everything in three phases: normal items,
     673             :          * then ACLs, then matview refresh items.  We might be able to skip
     674             :          * one or both extra phases in some cases, eg data-only restores.
     675             :          */
     676         158 :         bool        haveACL = false;
     677         158 :         bool        haveRefresh = false;
     678             : 
     679       20266 :         for (te = AH->toc->next; te != AH->toc; te = te->next)
     680             :         {
     681       20108 :             if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) == 0)
     682        1366 :                 continue;       /* ignore if not to be dumped at all */
     683             : 
     684       18742 :             switch (_tocEntryRestorePass(te))
     685             :             {
     686             :                 case RESTORE_PASS_MAIN:
     687       16450 :                     (void) restore_toc_entry(AH, te, false);
     688       16450 :                     break;
     689             :                 case RESTORE_PASS_ACL:
     690        2074 :                     haveACL = true;
     691        2074 :                     break;
     692             :                 case RESTORE_PASS_REFRESH:
     693         218 :                     haveRefresh = true;
     694         218 :                     break;
     695             :             }
     696             :         }
     697             : 
     698         158 :         if (haveACL)
     699             :         {
     700       19206 :             for (te = AH->toc->next; te != AH->toc; te = te->next)
     701             :             {
     702       37450 :                 if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0 &&
     703       18334 :                     _tocEntryRestorePass(te) == RESTORE_PASS_ACL)
     704        2074 :                     (void) restore_toc_entry(AH, te, false);
     705             :             }
     706             :         }
     707             : 
     708         158 :         if (haveRefresh)
     709             :         {
     710       14712 :             for (te = AH->toc->next; te != AH->toc; te = te->next)
     711             :             {
     712       28890 :                 if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0 &&
     713       14220 :                     _tocEntryRestorePass(te) == RESTORE_PASS_REFRESH)
     714         218 :                     (void) restore_toc_entry(AH, te, false);
     715             :             }
     716             :         }
     717             :     }
     718             : 
     719         162 :     if (ropt->single_txn)
     720             :     {
     721           0 :         if (AH->connection)
     722           0 :             CommitTransaction(AHX);
     723             :         else
     724           0 :             ahprintf(AH, "COMMIT;\n\n");
     725             :     }
     726             : 
     727         162 :     if (AH->public.verbose)
     728          28 :         dumpTimestamp(AH, "Completed on", time(NULL));
     729             : 
     730         162 :     ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
     731             : 
     732             :     /*
     733             :      * Clean up & we're done.
     734             :      */
     735         162 :     AH->stage = STAGE_FINALIZING;
     736             : 
     737         162 :     if (ropt->filename || ropt->compression)
     738         142 :         RestoreOutput(AH, sav);
     739             : 
     740         162 :     if (ropt->useDB)
     741          16 :         DisconnectDatabase(&AH->public);
     742         162 : }
     743             : 
     744             : /*
     745             :  * Restore a single TOC item.  Used in both parallel and non-parallel restore;
     746             :  * is_parallel is true if we are in a worker child process.
     747             :  *
     748             :  * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
     749             :  * the parallel parent has to make the corresponding status update.
     750             :  */
     751             : static int
     752       18766 : restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
     753             : {
     754       18766 :     RestoreOptions *ropt = AH->public.ropt;
     755       18766 :     int         status = WORKER_OK;
     756             :     teReqs      reqs;
     757             :     bool        defnDumped;
     758             : 
     759       18766 :     AH->currentTE = te;
     760             : 
     761             :     /* Dump any relevant dump warnings to stderr */
     762       18766 :     if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
     763             :     {
     764           0 :         if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
     765           0 :             pg_log_warning("warning from original dump file: %s", te->defn);
     766           0 :         else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
     767           0 :             pg_log_warning("warning from original dump file: %s", te->copyStmt);
     768             :     }
     769             : 
     770             :     /* Work out what, if anything, we want from this entry */
     771       18766 :     reqs = te->reqs;
     772             : 
     773       18766 :     defnDumped = false;
     774             : 
     775             :     /*
     776             :      * If it has a schema component that we want, then process that
     777             :      */
     778       18766 :     if ((reqs & REQ_SCHEMA) != 0)
     779             :     {
     780             :         /* Show namespace in log message if available */
     781       15652 :         if (te->namespace)
     782       14454 :             pg_log_info("creating %s \"%s.%s\"",
     783             :                         te->desc, te->namespace, te->tag);
     784             :         else
     785        1198 :             pg_log_info("creating %s \"%s\"",
     786             :                         te->desc, te->tag);
     787             : 
     788       15652 :         _printTocEntry(AH, te, false);
     789       15652 :         defnDumped = true;
     790             : 
     791       15652 :         if (strcmp(te->desc, "TABLE") == 0)
     792             :         {
     793        3884 :             if (AH->lastErrorTE == te)
     794             :             {
     795             :                 /*
     796             :                  * We failed to create the table. If
     797             :                  * --no-data-for-failed-tables was given, mark the
     798             :                  * corresponding TABLE DATA to be ignored.
     799             :                  *
     800             :                  * In the parallel case this must be done in the parent, so we
     801             :                  * just set the return value.
     802             :                  */
     803           0 :                 if (ropt->noDataForFailedTables)
     804             :                 {
     805           0 :                     if (is_parallel)
     806           0 :                         status = WORKER_INHIBIT_DATA;
     807             :                     else
     808           0 :                         inhibit_data_for_failed_table(AH, te);
     809             :                 }
     810             :             }
     811             :             else
     812             :             {
     813             :                 /*
     814             :                  * We created the table successfully.  Mark the corresponding
     815             :                  * TABLE DATA for possible truncation.
     816             :                  *
     817             :                  * In the parallel case this must be done in the parent, so we
     818             :                  * just set the return value.
     819             :                  */
     820        3884 :                 if (is_parallel)
     821           0 :                     status = WORKER_CREATE_DONE;
     822             :                 else
     823        3884 :                     mark_create_done(AH, te);
     824             :             }
     825             :         }
     826             : 
     827             :         /*
     828             :          * If we created a DB, connect to it.  Also, if we changed DB
     829             :          * properties, reconnect to ensure that relevant GUC settings are
     830             :          * applied to our session.
     831             :          */
     832       31252 :         if (strcmp(te->desc, "DATABASE") == 0 ||
     833       15600 :             strcmp(te->desc, "DATABASE PROPERTIES") == 0)
     834             :         {
     835             :             PQExpBufferData connstr;
     836             : 
     837          68 :             initPQExpBuffer(&connstr);
     838          68 :             appendPQExpBufferStr(&connstr, "dbname=");
     839          68 :             appendConnStrVal(&connstr, te->tag);
     840             :             /* Abandon struct, but keep its buffer until process exit. */
     841             : 
     842          68 :             pg_log_info("connecting to new database \"%s\"", te->tag);
     843          68 :             _reconnectToDB(AH, te->tag);
     844          68 :             ropt->dbname = connstr.data;
     845             :         }
     846             :     }
     847             : 
     848             :     /*
     849             :      * If it has a data component that we want, then process that
     850             :      */
     851       18766 :     if ((reqs & REQ_DATA) != 0)
     852             :     {
     853             :         /*
     854             :          * hadDumper will be set if there is genuine data component for this
     855             :          * node. Otherwise, we need to check the defn field for statements
     856             :          * that need to be executed in data-only restores.
     857             :          */
     858        3100 :         if (te->hadDumper)
     859             :         {
     860             :             /*
     861             :              * If we can output the data, then restore it.
     862             :              */
     863        2548 :             if (AH->PrintTocDataPtr != NULL)
     864             :             {
     865        2548 :                 _printTocEntry(AH, te, true);
     866             : 
     867        5052 :                 if (strcmp(te->desc, "BLOBS") == 0 ||
     868        2504 :                     strcmp(te->desc, "BLOB COMMENTS") == 0)
     869             :                 {
     870          44 :                     pg_log_info("processing %s", te->desc);
     871             : 
     872          44 :                     _selectOutputSchema(AH, "pg_catalog");
     873             : 
     874             :                     /* Send BLOB COMMENTS data to ExecuteSimpleCommands() */
     875          44 :                     if (strcmp(te->desc, "BLOB COMMENTS") == 0)
     876           0 :                         AH->outputKind = OUTPUT_OTHERDATA;
     877             : 
     878          44 :                     AH->PrintTocDataPtr(AH, te);
     879             : 
     880          44 :                     AH->outputKind = OUTPUT_SQLCMDS;
     881             :                 }
     882             :                 else
     883             :                 {
     884        2504 :                     _disableTriggersIfNecessary(AH, te);
     885             : 
     886             :                     /* Select owner and schema as necessary */
     887        2504 :                     _becomeOwner(AH, te);
     888        2504 :                     _selectOutputSchema(AH, te->namespace);
     889             : 
     890        2504 :                     pg_log_info("processing data for table \"%s.%s\"",
     891             :                                 te->namespace, te->tag);
     892             : 
     893             :                     /*
     894             :                      * In parallel restore, if we created the table earlier in
     895             :                      * the run then we wrap the COPY in a transaction and
     896             :                      * precede it with a TRUNCATE.  If archiving is not on
     897             :                      * this prevents WAL-logging the COPY.  This obtains a
     898             :                      * speedup similar to that from using single_txn mode in
     899             :                      * non-parallel restores.
     900             :                      */
     901        2504 :                     if (is_parallel && te->created)
     902             :                     {
     903             :                         /*
     904             :                          * Parallel restore is always talking directly to a
     905             :                          * server, so no need to see if we should issue BEGIN.
     906             :                          */
     907           4 :                         StartTransaction(&AH->public);
     908             : 
     909             :                         /*
     910             :                          * If the server version is >= 8.4, make sure we issue
     911             :                          * TRUNCATE with ONLY so that child tables are not
     912             :                          * wiped.
     913             :                          */
     914           8 :                         ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
     915           4 :                                  (PQserverVersion(AH->connection) >= 80400 ?
     916             :                                   "ONLY " : ""),
     917           4 :                                  fmtQualifiedId(te->namespace, te->tag));
     918             :                     }
     919             : 
     920             :                     /*
     921             :                      * If we have a copy statement, use it.
     922             :                      */
     923        2504 :                     if (te->copyStmt && strlen(te->copyStmt) > 0)
     924             :                     {
     925        2470 :                         ahprintf(AH, "%s", te->copyStmt);
     926        2470 :                         AH->outputKind = OUTPUT_COPYDATA;
     927             :                     }
     928             :                     else
     929          34 :                         AH->outputKind = OUTPUT_OTHERDATA;
     930             : 
     931        2504 :                     AH->PrintTocDataPtr(AH, te);
     932             : 
     933             :                     /*
     934             :                      * Terminate COPY if needed.
     935             :                      */
     936        4974 :                     if (AH->outputKind == OUTPUT_COPYDATA &&
     937        2470 :                         RestoringToDB(AH))
     938           4 :                         EndDBCopyMode(&AH->public, te->tag);
     939        2504 :                     AH->outputKind = OUTPUT_SQLCMDS;
     940             : 
     941             :                     /* close out the transaction started above */
     942        2504 :                     if (is_parallel && te->created)
     943           4 :                         CommitTransaction(&AH->public);
     944             : 
     945        2504 :                     _enableTriggersIfNecessary(AH, te);
     946             :                 }
     947             :             }
     948             :         }
     949         552 :         else if (!defnDumped)
     950             :         {
     951             :             /* If we haven't already dumped the defn part, do so now */
     952         552 :             pg_log_info("executing %s %s", te->desc, te->tag);
     953         552 :             _printTocEntry(AH, te, false);
     954             :         }
     955             :     }
     956             : 
     957       18766 :     if (AH->public.n_errors > 0 && status == WORKER_OK)
     958           0 :         status = WORKER_IGNORED_ERRORS;
     959             : 
     960       18766 :     return status;
     961             : }
     962             : 
     963             : /*
     964             :  * Allocate a new RestoreOptions block.
     965             :  * This is mainly so we can initialize it, but also for future expansion,
     966             :  */
     967             : RestoreOptions *
     968         222 : NewRestoreOptions(void)
     969             : {
     970             :     RestoreOptions *opts;
     971             : 
     972         222 :     opts = (RestoreOptions *) pg_malloc0(sizeof(RestoreOptions));
     973             : 
     974             :     /* set any fields that shouldn't default to zeroes */
     975         222 :     opts->format = archUnknown;
     976         222 :     opts->promptPassword = TRI_DEFAULT;
     977         222 :     opts->dumpSections = DUMP_UNSECTIONED;
     978             : 
     979         222 :     return opts;
     980             : }
     981             : 
     982             : static void
     983        2504 : _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
     984             : {
     985        2504 :     RestoreOptions *ropt = AH->public.ropt;
     986             : 
     987             :     /* This hack is only needed in a data-only restore */
     988        2504 :     if (!ropt->dataOnly || !ropt->disable_triggers)
     989        2474 :         return;
     990             : 
     991          30 :     pg_log_info("disabling triggers for %s", te->tag);
     992             : 
     993             :     /*
     994             :      * Become superuser if possible, since they are the only ones who can
     995             :      * disable constraint triggers.  If -S was not given, assume the initial
     996             :      * user identity is a superuser.  (XXX would it be better to become the
     997             :      * table owner?)
     998             :      */
     999          30 :     _becomeUser(AH, ropt->superuser);
    1000             : 
    1001             :     /*
    1002             :      * Disable them.
    1003             :      */
    1004          30 :     ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
    1005          30 :              fmtQualifiedId(te->namespace, te->tag));
    1006             : }
    1007             : 
    1008             : static void
    1009        2504 : _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
    1010             : {
    1011        2504 :     RestoreOptions *ropt = AH->public.ropt;
    1012             : 
    1013             :     /* This hack is only needed in a data-only restore */
    1014        2504 :     if (!ropt->dataOnly || !ropt->disable_triggers)
    1015        2474 :         return;
    1016             : 
    1017          30 :     pg_log_info("enabling triggers for %s", te->tag);
    1018             : 
    1019             :     /*
    1020             :      * Become superuser if possible, since they are the only ones who can
    1021             :      * disable constraint triggers.  If -S was not given, assume the initial
    1022             :      * user identity is a superuser.  (XXX would it be better to become the
    1023             :      * table owner?)
    1024             :      */
    1025          30 :     _becomeUser(AH, ropt->superuser);
    1026             : 
    1027             :     /*
    1028             :      * Enable them.
    1029             :      */
    1030          30 :     ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
    1031          30 :              fmtQualifiedId(te->namespace, te->tag));
    1032             : }
    1033             : 
    1034             : /*
    1035             :  * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
    1036             :  */
    1037             : 
    1038             : /* Public */
    1039             : void
    1040     1456186 : WriteData(Archive *AHX, const void *data, size_t dLen)
    1041             : {
    1042     1456186 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1043             : 
    1044     1456186 :     if (!AH->currToc)
    1045           0 :         fatal("internal error -- WriteData cannot be called outside the context of a DataDumper routine");
    1046             : 
    1047     1456186 :     AH->WriteDataPtr(AH, data, dLen);
    1048             : 
    1049     1456186 :     return;
    1050             : }
    1051             : 
    1052             : /*
    1053             :  * Create a new TOC entry. The TOC was designed as a TOC, but is now the
    1054             :  * repository for all metadata. But the name has stuck.
    1055             :  *
    1056             :  * The new entry is added to the Archive's TOC list.  Most callers can ignore
    1057             :  * the result value because nothing else need be done, but a few want to
    1058             :  * manipulate the TOC entry further.
    1059             :  */
    1060             : 
    1061             : /* Public */
    1062             : TocEntry *
    1063       19700 : ArchiveEntry(Archive *AHX, CatalogId catalogId, DumpId dumpId,
    1064             :              ArchiveOpts *opts)
    1065             : {
    1066       19700 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1067             :     TocEntry   *newToc;
    1068             : 
    1069       19700 :     newToc = (TocEntry *) pg_malloc0(sizeof(TocEntry));
    1070             : 
    1071       19700 :     AH->tocCount++;
    1072       19700 :     if (dumpId > AH->maxDumpId)
    1073        4124 :         AH->maxDumpId = dumpId;
    1074             : 
    1075       19700 :     newToc->prev = AH->toc->prev;
    1076       19700 :     newToc->next = AH->toc;
    1077       19700 :     AH->toc->prev->next = newToc;
    1078       19700 :     AH->toc->prev = newToc;
    1079             : 
    1080       19700 :     newToc->catalogId = catalogId;
    1081       19700 :     newToc->dumpId = dumpId;
    1082       19700 :     newToc->section = opts->section;
    1083             : 
    1084       19700 :     newToc->tag = pg_strdup(opts->tag);
    1085       19700 :     newToc->namespace = opts->namespace ? pg_strdup(opts->namespace) : NULL;
    1086       19700 :     newToc->tablespace = opts->tablespace ? pg_strdup(opts->tablespace) : NULL;
    1087       19700 :     newToc->tableam = opts->tableam ? pg_strdup(opts->tableam) : NULL;
    1088       19700 :     newToc->owner = opts->owner ? pg_strdup(opts->owner) : NULL;
    1089       19700 :     newToc->desc = pg_strdup(opts->description);
    1090       19700 :     newToc->defn = opts->createStmt ? pg_strdup(opts->createStmt) : NULL;
    1091       19700 :     newToc->dropStmt = opts->dropStmt ? pg_strdup(opts->dropStmt) : NULL;
    1092       19700 :     newToc->copyStmt = opts->copyStmt ? pg_strdup(opts->copyStmt) : NULL;
    1093             : 
    1094       19700 :     if (opts->nDeps > 0)
    1095             :     {
    1096        6358 :         newToc->dependencies = (DumpId *) pg_malloc(opts->nDeps * sizeof(DumpId));
    1097        6358 :         memcpy(newToc->dependencies, opts->deps, opts->nDeps * sizeof(DumpId));
    1098        6358 :         newToc->nDeps = opts->nDeps;
    1099             :     }
    1100             :     else
    1101             :     {
    1102       13342 :         newToc->dependencies = NULL;
    1103       13342 :         newToc->nDeps = 0;
    1104             :     }
    1105             : 
    1106       19700 :     newToc->dataDumper = opts->dumpFn;
    1107       19700 :     newToc->dataDumperArg = opts->dumpArg;
    1108       19700 :     newToc->hadDumper = opts->dumpFn ? true : false;
    1109             : 
    1110       19700 :     newToc->formatData = NULL;
    1111       19700 :     newToc->dataLength = 0;
    1112             : 
    1113       19700 :     if (AH->ArchiveEntryPtr != NULL)
    1114        5032 :         AH->ArchiveEntryPtr(AH, newToc);
    1115             : 
    1116       19700 :     return newToc;
    1117             : }
    1118             : 
    1119             : /* Public */
    1120             : void
    1121           0 : PrintTOCSummary(Archive *AHX)
    1122             : {
    1123           0 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1124           0 :     RestoreOptions *ropt = AH->public.ropt;
    1125             :     TocEntry   *te;
    1126             :     teSection   curSection;
    1127             :     OutputContext sav;
    1128             :     const char *fmtName;
    1129             :     char        stamp_str[64];
    1130             : 
    1131           0 :     sav = SaveOutput(AH);
    1132           0 :     if (ropt->filename)
    1133           0 :         SetOutput(AH, ropt->filename, 0 /* no compression */ );
    1134             : 
    1135           0 :     if (strftime(stamp_str, sizeof(stamp_str), PGDUMP_STRFTIME_FMT,
    1136           0 :                  localtime(&AH->createDate)) == 0)
    1137           0 :         strcpy(stamp_str, "[unknown]");
    1138             : 
    1139           0 :     ahprintf(AH, ";\n; Archive created at %s\n", stamp_str);
    1140           0 :     ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
    1141           0 :              sanitize_line(AH->archdbname, false),
    1142             :              AH->tocCount, AH->compression);
    1143             : 
    1144           0 :     switch (AH->format)
    1145             :     {
    1146             :         case archCustom:
    1147           0 :             fmtName = "CUSTOM";
    1148           0 :             break;
    1149             :         case archDirectory:
    1150           0 :             fmtName = "DIRECTORY";
    1151           0 :             break;
    1152             :         case archTar:
    1153           0 :             fmtName = "TAR";
    1154           0 :             break;
    1155             :         default:
    1156           0 :             fmtName = "UNKNOWN";
    1157             :     }
    1158             : 
    1159           0 :     ahprintf(AH, ";     Dump Version: %d.%d-%d\n",
    1160           0 :              ARCHIVE_MAJOR(AH->version), ARCHIVE_MINOR(AH->version), ARCHIVE_REV(AH->version));
    1161           0 :     ahprintf(AH, ";     Format: %s\n", fmtName);
    1162           0 :     ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
    1163           0 :     ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
    1164           0 :     if (AH->archiveRemoteVersion)
    1165           0 :         ahprintf(AH, ";     Dumped from database version: %s\n",
    1166             :                  AH->archiveRemoteVersion);
    1167           0 :     if (AH->archiveDumpVersion)
    1168           0 :         ahprintf(AH, ";     Dumped by pg_dump version: %s\n",
    1169             :                  AH->archiveDumpVersion);
    1170             : 
    1171           0 :     ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
    1172             : 
    1173           0 :     curSection = SECTION_PRE_DATA;
    1174           0 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    1175             :     {
    1176           0 :         if (te->section != SECTION_NONE)
    1177           0 :             curSection = te->section;
    1178           0 :         if (ropt->verbose ||
    1179           0 :             (_tocEntryRequired(te, curSection, AH) & (REQ_SCHEMA | REQ_DATA)) != 0)
    1180             :         {
    1181             :             char       *sanitized_name;
    1182             :             char       *sanitized_schema;
    1183             :             char       *sanitized_owner;
    1184             : 
    1185             :             /*
    1186             :              */
    1187           0 :             sanitized_name = sanitize_line(te->tag, false);
    1188           0 :             sanitized_schema = sanitize_line(te->namespace, true);
    1189           0 :             sanitized_owner = sanitize_line(te->owner, false);
    1190             : 
    1191           0 :             ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
    1192             :                      te->catalogId.tableoid, te->catalogId.oid,
    1193             :                      te->desc, sanitized_schema, sanitized_name,
    1194             :                      sanitized_owner);
    1195             : 
    1196           0 :             free(sanitized_name);
    1197           0 :             free(sanitized_schema);
    1198           0 :             free(sanitized_owner);
    1199             :         }
    1200           0 :         if (ropt->verbose && te->nDeps > 0)
    1201             :         {
    1202             :             int         i;
    1203             : 
    1204           0 :             ahprintf(AH, ";\tdepends on:");
    1205           0 :             for (i = 0; i < te->nDeps; i++)
    1206           0 :                 ahprintf(AH, " %d", te->dependencies[i]);
    1207           0 :             ahprintf(AH, "\n");
    1208             :         }
    1209             :     }
    1210             : 
    1211             :     /* Enforce strict names checking */
    1212           0 :     if (ropt->strict_names)
    1213           0 :         StrictNamesCheck(ropt);
    1214             : 
    1215           0 :     if (ropt->filename)
    1216           0 :         RestoreOutput(AH, sav);
    1217           0 : }
    1218             : 
    1219             : /***********
    1220             :  * BLOB Archival
    1221             :  ***********/
    1222             : 
    1223             : /* Called by a dumper to signal start of a BLOB */
    1224             : int
    1225          50 : StartBlob(Archive *AHX, Oid oid)
    1226             : {
    1227          50 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1228             : 
    1229          50 :     if (!AH->StartBlobPtr)
    1230           0 :         fatal("large-object output not supported in chosen format");
    1231             : 
    1232          50 :     AH->StartBlobPtr(AH, AH->currToc, oid);
    1233             : 
    1234          50 :     return 1;
    1235             : }
    1236             : 
    1237             : /* Called by a dumper to signal end of a BLOB */
    1238             : int
    1239          50 : EndBlob(Archive *AHX, Oid oid)
    1240             : {
    1241          50 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1242             : 
    1243          50 :     if (AH->EndBlobPtr)
    1244          50 :         AH->EndBlobPtr(AH, AH->currToc, oid);
    1245             : 
    1246          50 :     return 1;
    1247             : }
    1248             : 
    1249             : /**********
    1250             :  * BLOB Restoration
    1251             :  **********/
    1252             : 
    1253             : /*
    1254             :  * Called by a format handler before any blobs are restored
    1255             :  */
    1256             : void
    1257           8 : StartRestoreBlobs(ArchiveHandle *AH)
    1258             : {
    1259           8 :     RestoreOptions *ropt = AH->public.ropt;
    1260             : 
    1261           8 :     if (!ropt->single_txn)
    1262             :     {
    1263           8 :         if (AH->connection)
    1264           0 :             StartTransaction(&AH->public);
    1265             :         else
    1266           8 :             ahprintf(AH, "BEGIN;\n\n");
    1267             :     }
    1268             : 
    1269           8 :     AH->blobCount = 0;
    1270           8 : }
    1271             : 
    1272             : /*
    1273             :  * Called by a format handler after all blobs are restored
    1274             :  */
    1275             : void
    1276           8 : EndRestoreBlobs(ArchiveHandle *AH)
    1277             : {
    1278           8 :     RestoreOptions *ropt = AH->public.ropt;
    1279             : 
    1280           8 :     if (!ropt->single_txn)
    1281             :     {
    1282           8 :         if (AH->connection)
    1283           0 :             CommitTransaction(&AH->public);
    1284             :         else
    1285           8 :             ahprintf(AH, "COMMIT;\n\n");
    1286             :     }
    1287             : 
    1288           8 :     pg_log_info(ngettext("restored %d large object",
    1289             :                          "restored %d large objects",
    1290             :                          AH->blobCount),
    1291             :                 AH->blobCount);
    1292           8 : }
    1293             : 
    1294             : 
    1295             : /*
    1296             :  * Called by a format handler to initiate restoration of a blob
    1297             :  */
    1298             : void
    1299           8 : StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
    1300             : {
    1301           8 :     bool        old_blob_style = (AH->version < K_VERS_1_12);
    1302             :     Oid         loOid;
    1303             : 
    1304           8 :     AH->blobCount++;
    1305             : 
    1306             :     /* Initialize the LO Buffer */
    1307           8 :     AH->lo_buf_used = 0;
    1308             : 
    1309           8 :     pg_log_info("restoring large object with OID %u", oid);
    1310             : 
    1311             :     /* With an old archive we must do drop and create logic here */
    1312           8 :     if (old_blob_style && drop)
    1313           0 :         DropBlobIfExists(AH, oid);
    1314             : 
    1315           8 :     if (AH->connection)
    1316             :     {
    1317           0 :         if (old_blob_style)
    1318             :         {
    1319           0 :             loOid = lo_create(AH->connection, oid);
    1320           0 :             if (loOid == 0 || loOid != oid)
    1321           0 :                 fatal("could not create large object %u: %s",
    1322             :                       oid, PQerrorMessage(AH->connection));
    1323             :         }
    1324           0 :         AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
    1325           0 :         if (AH->loFd == -1)
    1326           0 :             fatal("could not open large object %u: %s",
    1327             :                   oid, PQerrorMessage(AH->connection));
    1328             :     }
    1329             :     else
    1330             :     {
    1331           8 :         if (old_blob_style)
    1332           0 :             ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
    1333             :                      oid, INV_WRITE);
    1334             :         else
    1335           8 :             ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
    1336             :                      oid, INV_WRITE);
    1337             :     }
    1338             : 
    1339           8 :     AH->writingBlob = 1;
    1340           8 : }
    1341             : 
    1342             : void
    1343           8 : EndRestoreBlob(ArchiveHandle *AH, Oid oid)
    1344             : {
    1345           8 :     if (AH->lo_buf_used > 0)
    1346             :     {
    1347             :         /* Write remaining bytes from the LO buffer */
    1348           8 :         dump_lo_buf(AH);
    1349             :     }
    1350             : 
    1351           8 :     AH->writingBlob = 0;
    1352             : 
    1353           8 :     if (AH->connection)
    1354             :     {
    1355           0 :         lo_close(AH->connection, AH->loFd);
    1356           0 :         AH->loFd = -1;
    1357             :     }
    1358             :     else
    1359             :     {
    1360           8 :         ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
    1361             :     }
    1362           8 : }
    1363             : 
    1364             : /***********
    1365             :  * Sorting and Reordering
    1366             :  ***********/
    1367             : 
    1368             : void
    1369           0 : SortTocFromFile(Archive *AHX)
    1370             : {
    1371           0 :     ArchiveHandle *AH = (ArchiveHandle *) AHX;
    1372           0 :     RestoreOptions *ropt = AH->public.ropt;
    1373             :     FILE       *fh;
    1374             :     char        buf[100];
    1375             :     bool        incomplete_line;
    1376             : 
    1377             :     /* Allocate space for the 'wanted' array, and init it */
    1378           0 :     ropt->idWanted = (bool *) pg_malloc0(sizeof(bool) * AH->maxDumpId);
    1379             : 
    1380             :     /* Setup the file */
    1381           0 :     fh = fopen(ropt->tocFile, PG_BINARY_R);
    1382           0 :     if (!fh)
    1383           0 :         fatal("could not open TOC file \"%s\": %m", ropt->tocFile);
    1384             : 
    1385           0 :     incomplete_line = false;
    1386           0 :     while (fgets(buf, sizeof(buf), fh) != NULL)
    1387             :     {
    1388           0 :         bool        prev_incomplete_line = incomplete_line;
    1389             :         int         buflen;
    1390             :         char       *cmnt;
    1391             :         char       *endptr;
    1392             :         DumpId      id;
    1393             :         TocEntry   *te;
    1394             : 
    1395             :         /*
    1396             :          * Some lines in the file might be longer than sizeof(buf).  This is
    1397             :          * no problem, since we only care about the leading numeric ID which
    1398             :          * can be at most a few characters; but we have to skip continuation
    1399             :          * bufferloads when processing a long line.
    1400             :          */
    1401           0 :         buflen = strlen(buf);
    1402           0 :         if (buflen > 0 && buf[buflen - 1] == '\n')
    1403           0 :             incomplete_line = false;
    1404             :         else
    1405           0 :             incomplete_line = true;
    1406           0 :         if (prev_incomplete_line)
    1407           0 :             continue;
    1408             : 
    1409             :         /* Truncate line at comment, if any */
    1410           0 :         cmnt = strchr(buf, ';');
    1411           0 :         if (cmnt != NULL)
    1412           0 :             cmnt[0] = '\0';
    1413             : 
    1414             :         /* Ignore if all blank */
    1415           0 :         if (strspn(buf, " \t\r\n") == strlen(buf))
    1416           0 :             continue;
    1417             : 
    1418             :         /* Get an ID, check it's valid and not already seen */
    1419           0 :         id = strtol(buf, &endptr, 10);
    1420           0 :         if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
    1421           0 :             ropt->idWanted[id - 1])
    1422             :         {
    1423           0 :             pg_log_warning("line ignored: %s", buf);
    1424           0 :             continue;
    1425             :         }
    1426             : 
    1427             :         /* Find TOC entry */
    1428           0 :         te = getTocEntryByDumpId(AH, id);
    1429           0 :         if (!te)
    1430           0 :             fatal("could not find entry for ID %d",
    1431             :                   id);
    1432             : 
    1433             :         /* Mark it wanted */
    1434           0 :         ropt->idWanted[id - 1] = true;
    1435             : 
    1436             :         /*
    1437             :          * Move each item to the end of the list as it is selected, so that
    1438             :          * they are placed in the desired order.  Any unwanted items will end
    1439             :          * up at the front of the list, which may seem unintuitive but it's
    1440             :          * what we need.  In an ordinary serial restore that makes no
    1441             :          * difference, but in a parallel restore we need to mark unrestored
    1442             :          * items' dependencies as satisfied before we start examining
    1443             :          * restorable items.  Otherwise they could have surprising
    1444             :          * side-effects on the order in which restorable items actually get
    1445             :          * restored.
    1446             :          */
    1447           0 :         _moveBefore(AH, AH->toc, te);
    1448             :     }
    1449             : 
    1450           0 :     if (fclose(fh) != 0)
    1451           0 :         fatal("could not close TOC file: %m");
    1452           0 : }
    1453             : 
    1454             : /**********************
    1455             :  * 'Convenience functions that look like standard IO functions
    1456             :  * for writing data when in dump mode.
    1457             :  **********************/
    1458             : 
    1459             : /* Public */
    1460             : void
    1461         626 : archputs(const char *s, Archive *AH)
    1462             : {
    1463         626 :     WriteData(AH, s, strlen(s));
    1464         626 :     return;
    1465             : }
    1466             : 
    1467             : /* Public */
    1468             : int
    1469        2440 : archprintf(Archive *AH, const char *fmt,...)
    1470             : {
    1471        2440 :     int         save_errno = errno;
    1472             :     char       *p;
    1473        2440 :     size_t      len = 128;      /* initial assumption about buffer size */
    1474             :     size_t      cnt;
    1475             : 
    1476             :     for (;;)
    1477           0 :     {
    1478             :         va_list     args;
    1479             : 
    1480             :         /* Allocate work buffer. */
    1481        2440 :         p = (char *) pg_malloc(len);
    1482             : 
    1483             :         /* Try to format the data. */
    1484        2440 :         errno = save_errno;
    1485        2440 :         va_start(args, fmt);
    1486        2440 :         cnt = pvsnprintf(p, len, fmt, args);
    1487        2440 :         va_end(args);
    1488             : 
    1489        2440 :         if (cnt < len)
    1490        2440 :             break;              /* success */
    1491             : 
    1492             :         /* Release buffer and loop around to try again with larger len. */
    1493           0 :         free(p);
    1494           0 :         len = cnt;
    1495             :     }
    1496             : 
    1497        2440 :     WriteData(AH, p, cnt);
    1498        2440 :     free(p);
    1499        4880 :     return (int) cnt;
    1500             : }
    1501             : 
    1502             : 
    1503             : /*******************************
    1504             :  * Stuff below here should be 'private' to the archiver routines
    1505             :  *******************************/
    1506             : 
    1507             : static void
    1508         142 : SetOutput(ArchiveHandle *AH, const char *filename, int compression)
    1509             : {
    1510             :     int         fn;
    1511             : 
    1512         142 :     if (filename)
    1513             :     {
    1514         142 :         if (strcmp(filename, "-") == 0)
    1515           0 :             fn = fileno(stdout);
    1516             :         else
    1517         142 :             fn = -1;
    1518             :     }
    1519           0 :     else if (AH->FH)
    1520           0 :         fn = fileno(AH->FH);
    1521           0 :     else if (AH->fSpec)
    1522             :     {
    1523           0 :         fn = -1;
    1524           0 :         filename = AH->fSpec;
    1525             :     }
    1526             :     else
    1527           0 :         fn = fileno(stdout);
    1528             : 
    1529             :     /* If compression explicitly requested, use gzopen */
    1530             : #ifdef HAVE_LIBZ
    1531         142 :     if (compression != 0)
    1532             :     {
    1533             :         char        fmode[14];
    1534             : 
    1535             :         /* Don't use PG_BINARY_x since this is zlib */
    1536           0 :         sprintf(fmode, "wb%d", compression);
    1537           0 :         if (fn >= 0)
    1538           0 :             AH->OF = gzdopen(dup(fn), fmode);
    1539             :         else
    1540           0 :             AH->OF = gzopen(filename, fmode);
    1541           0 :         AH->gzOut = 1;
    1542             :     }
    1543             :     else
    1544             : #endif
    1545             :     {                           /* Use fopen */
    1546         142 :         if (AH->mode == archModeAppend)
    1547             :         {
    1548          52 :             if (fn >= 0)
    1549           0 :                 AH->OF = fdopen(dup(fn), PG_BINARY_A);
    1550             :             else
    1551          52 :                 AH->OF = fopen(filename, PG_BINARY_A);
    1552             :         }
    1553             :         else
    1554             :         {
    1555          90 :             if (fn >= 0)
    1556           0 :                 AH->OF = fdopen(dup(fn), PG_BINARY_W);
    1557             :             else
    1558          90 :                 AH->OF = fopen(filename, PG_BINARY_W);
    1559             :         }
    1560         142 :         AH->gzOut = 0;
    1561             :     }
    1562             : 
    1563         142 :     if (!AH->OF)
    1564             :     {
    1565           0 :         if (filename)
    1566           0 :             fatal("could not open output file \"%s\": %m", filename);
    1567             :         else
    1568           0 :             fatal("could not open output file: %m");
    1569             :     }
    1570         142 : }
    1571             : 
    1572             : static OutputContext
    1573         162 : SaveOutput(ArchiveHandle *AH)
    1574             : {
    1575             :     OutputContext sav;
    1576             : 
    1577         162 :     sav.OF = AH->OF;
    1578         162 :     sav.gzOut = AH->gzOut;
    1579             : 
    1580         162 :     return sav;
    1581             : }
    1582             : 
    1583             : static void
    1584         142 : RestoreOutput(ArchiveHandle *AH, OutputContext savedContext)
    1585             : {
    1586             :     int         res;
    1587             : 
    1588         142 :     if (AH->gzOut)
    1589           0 :         res = GZCLOSE(AH->OF);
    1590             :     else
    1591         142 :         res = fclose(AH->OF);
    1592             : 
    1593         142 :     if (res != 0)
    1594           0 :         fatal("could not close output file: %m");
    1595             : 
    1596         142 :     AH->gzOut = savedContext.gzOut;
    1597         142 :     AH->OF = savedContext.OF;
    1598         142 : }
    1599             : 
    1600             : 
    1601             : 
    1602             : /*
    1603             :  *  Print formatted text to the output file (usually stdout).
    1604             :  */
    1605             : int
    1606       99008 : ahprintf(ArchiveHandle *AH, const char *fmt,...)
    1607             : {
    1608       99008 :     int         save_errno = errno;
    1609             :     char       *p;
    1610       99008 :     size_t      len = 128;      /* initial assumption about buffer size */
    1611             :     size_t      cnt;
    1612             : 
    1613             :     for (;;)
    1614        6920 :     {
    1615             :         va_list     args;
    1616             : 
    1617             :         /* Allocate work buffer. */
    1618      105928 :         p = (char *) pg_malloc(len);
    1619             : 
    1620             :         /* Try to format the data. */
    1621      105928 :         errno = save_errno;
    1622      105928 :         va_start(args, fmt);
    1623      105928 :         cnt = pvsnprintf(p, len, fmt, args);
    1624      105928 :         va_end(args);
    1625             : 
    1626      105928 :         if (cnt < len)
    1627       99008 :             break;              /* success */
    1628             : 
    1629             :         /* Release buffer and loop around to try again with larger len. */
    1630        6920 :         free(p);
    1631        6920 :         len = cnt;
    1632             :     }
    1633             : 
    1634       99008 :     ahwrite(p, 1, cnt, AH);
    1635       99008 :     free(p);
    1636      198016 :     return (int) cnt;
    1637             : }
    1638             : 
    1639             : /*
    1640             :  * Single place for logic which says 'We are restoring to a direct DB connection'.
    1641             :  */
    1642             : static int
    1643     1555410 : RestoringToDB(ArchiveHandle *AH)
    1644             : {
    1645     1555410 :     RestoreOptions *ropt = AH->public.ropt;
    1646             : 
    1647     1555410 :     return (ropt && ropt->useDB && AH->connection);
    1648             : }
    1649             : 
    1650             : /*
    1651             :  * Dump the current contents of the LO data buffer while writing a BLOB
    1652             :  */
    1653             : static void
    1654           8 : dump_lo_buf(ArchiveHandle *AH)
    1655             : {
    1656           8 :     if (AH->connection)
    1657             :     {
    1658             :         size_t      res;
    1659             : 
    1660           0 :         res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
    1661           0 :         pg_log_debug(ngettext("wrote %lu byte of large object data (result = %lu)",
    1662             :                               "wrote %lu bytes of large object data (result = %lu)",
    1663             :                               AH->lo_buf_used),
    1664             :                      (unsigned long) AH->lo_buf_used, (unsigned long) res);
    1665           0 :         if (res != AH->lo_buf_used)
    1666           0 :             fatal("could not write to large object (result: %lu, expected: %lu)",
    1667             :                   (unsigned long) res, (unsigned long) AH->lo_buf_used);
    1668             :     }
    1669             :     else
    1670             :     {
    1671           8 :         PQExpBuffer buf = createPQExpBuffer();
    1672             : 
    1673           8 :         appendByteaLiteralAHX(buf,
    1674             :                               (const unsigned char *) AH->lo_buf,
    1675             :                               AH->lo_buf_used,
    1676             :                               AH);
    1677             : 
    1678             :         /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
    1679           8 :         AH->writingBlob = 0;
    1680           8 :         ahprintf(AH, "SELECT pg_catalog.lowrite(0, %s);\n", buf->data);
    1681           8 :         AH->writingBlob = 1;
    1682             : 
    1683           8 :         destroyPQExpBuffer(buf);
    1684             :     }
    1685           8 :     AH->lo_buf_used = 0;
    1686           8 : }
    1687             : 
    1688             : 
    1689             : /*
    1690             :  *  Write buffer to the output file (usually stdout). This is used for
    1691             :  *  outputting 'restore' scripts etc. It is even possible for an archive
    1692             :  *  format to create a custom output routine to 'fake' a restore if it
    1693             :  *  wants to generate a script (see TAR output).
    1694             :  */
    1695             : void
    1696     1554924 : ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
    1697             : {
    1698     1554924 :     int         bytes_written = 0;
    1699             : 
    1700     1554924 :     if (AH->writingBlob)
    1701             :     {
    1702           8 :         size_t      remaining = size * nmemb;
    1703             : 
    1704          16 :         while (AH->lo_buf_used + remaining > AH->lo_buf_size)
    1705             :         {
    1706           0 :             size_t      avail = AH->lo_buf_size - AH->lo_buf_used;
    1707             : 
    1708           0 :             memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
    1709           0 :             ptr = (const void *) ((const char *) ptr + avail);
    1710           0 :             remaining -= avail;
    1711           0 :             AH->lo_buf_used += avail;
    1712           0 :             dump_lo_buf(AH);
    1713             :         }
    1714             : 
    1715           8 :         memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
    1716           8 :         AH->lo_buf_used += remaining;
    1717             : 
    1718           8 :         bytes_written = size * nmemb;
    1719             :     }
    1720     1554916 :     else if (AH->gzOut)
    1721           0 :         bytes_written = GZWRITE(ptr, size, nmemb, AH->OF);
    1722     1554916 :     else if (AH->CustomOutPtr)
    1723        2424 :         bytes_written = AH->CustomOutPtr(AH, ptr, size * nmemb);
    1724             : 
    1725             :     else
    1726             :     {
    1727             :         /*
    1728             :          * If we're doing a restore, and it's direct to DB, and we're
    1729             :          * connected then send it to the DB.
    1730             :          */
    1731     1552492 :         if (RestoringToDB(AH))
    1732        5562 :             bytes_written = ExecuteSqlCommandBuf(&AH->public, (const char *) ptr, size * nmemb);
    1733             :         else
    1734     1546930 :             bytes_written = fwrite(ptr, size, nmemb, AH->OF) * size;
    1735             :     }
    1736             : 
    1737     1554924 :     if (bytes_written != size * nmemb)
    1738           0 :         WRITE_ERROR_EXIT;
    1739             : 
    1740     1554924 :     return;
    1741             : }
    1742             : 
    1743             : /* on some error, we may decide to go on... */
    1744             : void
    1745           0 : warn_or_exit_horribly(ArchiveHandle *AH, const char *fmt,...)
    1746             : {
    1747             :     va_list     ap;
    1748             : 
    1749           0 :     switch (AH->stage)
    1750             :     {
    1751             : 
    1752             :         case STAGE_NONE:
    1753             :             /* Do nothing special */
    1754           0 :             break;
    1755             : 
    1756             :         case STAGE_INITIALIZING:
    1757           0 :             if (AH->stage != AH->lastErrorStage)
    1758           0 :                 pg_log_generic(PG_LOG_INFO, "while INITIALIZING:");
    1759           0 :             break;
    1760             : 
    1761             :         case STAGE_PROCESSING:
    1762           0 :             if (AH->stage != AH->lastErrorStage)
    1763           0 :                 pg_log_generic(PG_LOG_INFO, "while PROCESSING TOC:");
    1764           0 :             break;
    1765             : 
    1766             :         case STAGE_FINALIZING:
    1767           0 :             if (AH->stage != AH->lastErrorStage)
    1768           0 :                 pg_log_generic(PG_LOG_INFO, "while FINALIZING:");
    1769           0 :             break;
    1770             :     }
    1771           0 :     if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
    1772             :     {
    1773           0 :         pg_log_generic(PG_LOG_INFO, "from TOC entry %d; %u %u %s %s %s",
    1774           0 :                        AH->currentTE->dumpId,
    1775           0 :                        AH->currentTE->catalogId.tableoid,
    1776           0 :                        AH->currentTE->catalogId.oid,
    1777           0 :                        AH->currentTE->desc ? AH->currentTE->desc : "(no desc)",
    1778           0 :                        AH->currentTE->tag ? AH->currentTE->tag : "(no tag)",
    1779           0 :                        AH->currentTE->owner ? AH->currentTE->owner : "(no owner)");
    1780             :     }
    1781           0 :     AH->lastErrorStage = AH->stage;
    1782           0 :     AH->lastErrorTE = AH->currentTE;
    1783             : 
    1784           0 :     va_start(ap, fmt);
    1785           0 :     pg_log_generic_v(PG_LOG_ERROR, fmt, ap);
    1786           0 :     va_end(ap);
    1787             : 
    1788           0 :     if (AH->public.exit_on_error)
    1789           0 :         exit_nicely(1);
    1790             :     else
    1791           0 :         AH->public.n_errors++;
    1792           0 : }
    1793             : 
    1794             : #ifdef NOT_USED
    1795             : 
    1796             : static void
    1797             : _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
    1798             : {
    1799             :     /* Unlink te from list */
    1800             :     te->prev->next = te->next;
    1801             :     te->next->prev = te->prev;
    1802             : 
    1803             :     /* and insert it after "pos" */
    1804             :     te->prev = pos;
    1805             :     te->next = pos->next;
    1806             :     pos->next->prev = te;
    1807             :     pos->next = te;
    1808             : }
    1809             : #endif
    1810             : 
    1811             : static void
    1812           0 : _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
    1813             : {
    1814             :     /* Unlink te from list */
    1815           0 :     te->prev->next = te->next;
    1816           0 :     te->next->prev = te->prev;
    1817             : 
    1818             :     /* and insert it before "pos" */
    1819           0 :     te->prev = pos->prev;
    1820           0 :     te->next = pos;
    1821           0 :     pos->prev->next = te;
    1822           0 :     pos->prev = te;
    1823           0 : }
    1824             : 
    1825             : /*
    1826             :  * Build index arrays for the TOC list
    1827             :  *
    1828             :  * This should be invoked only after we have created or read in all the TOC
    1829             :  * items.
    1830             :  *
    1831             :  * The arrays are indexed by dump ID (so entry zero is unused).  Note that the
    1832             :  * array entries run only up to maxDumpId.  We might see dependency dump IDs
    1833             :  * beyond that (if the dump was partial); so always check the array bound
    1834             :  * before trying to touch an array entry.
    1835             :  */
    1836             : static void
    1837         182 : buildTocEntryArrays(ArchiveHandle *AH)
    1838             : {
    1839         182 :     DumpId      maxDumpId = AH->maxDumpId;
    1840             :     TocEntry   *te;
    1841             : 
    1842         182 :     AH->tocsByDumpId = (TocEntry **) pg_malloc0((maxDumpId + 1) * sizeof(TocEntry *));
    1843         182 :     AH->tableDataId = (DumpId *) pg_malloc0((maxDumpId + 1) * sizeof(DumpId));
    1844             : 
    1845       24856 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    1846             :     {
    1847             :         /* this check is purely paranoia, maxDumpId should be correct */
    1848       24674 :         if (te->dumpId <= 0 || te->dumpId > maxDumpId)
    1849           0 :             fatal("bad dumpId");
    1850             : 
    1851             :         /* tocsByDumpId indexes all TOCs by their dump ID */
    1852       24674 :         AH->tocsByDumpId[te->dumpId] = te;
    1853             : 
    1854             :         /*
    1855             :          * tableDataId provides the TABLE DATA item's dump ID for each TABLE
    1856             :          * TOC entry that has a DATA item.  We compute this by reversing the
    1857             :          * TABLE DATA item's dependency, knowing that a TABLE DATA item has
    1858             :          * just one dependency and it is the TABLE item.
    1859             :          */
    1860       24674 :         if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
    1861             :         {
    1862        2668 :             DumpId      tableId = te->dependencies[0];
    1863             : 
    1864             :             /*
    1865             :              * The TABLE item might not have been in the archive, if this was
    1866             :              * a data-only dump; but its dump ID should be less than its data
    1867             :              * item's dump ID, so there should be a place for it in the array.
    1868             :              */
    1869        2668 :             if (tableId <= 0 || tableId > maxDumpId)
    1870           0 :                 fatal("bad table dumpId for TABLE DATA item");
    1871             : 
    1872        2668 :             AH->tableDataId[tableId] = te->dumpId;
    1873             :         }
    1874             :     }
    1875         182 : }
    1876             : 
    1877             : TocEntry *
    1878       11116 : getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
    1879             : {
    1880             :     /* build index arrays if we didn't already */
    1881       11116 :     if (AH->tocsByDumpId == NULL)
    1882          24 :         buildTocEntryArrays(AH);
    1883             : 
    1884       11116 :     if (id > 0 && id <= AH->maxDumpId)
    1885       11116 :         return AH->tocsByDumpId[id];
    1886             : 
    1887           0 :     return NULL;
    1888             : }
    1889             : 
    1890             : teReqs
    1891       11074 : TocIDRequired(ArchiveHandle *AH, DumpId id)
    1892             : {
    1893       11074 :     TocEntry   *te = getTocEntryByDumpId(AH, id);
    1894             : 
    1895       11074 :     if (!te)
    1896        6098 :         return 0;
    1897             : 
    1898        4976 :     return te->reqs;
    1899             : }
    1900             : 
    1901             : size_t
    1902        7428 : WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
    1903             : {
    1904             :     int         off;
    1905             : 
    1906             :     /* Save the flag */
    1907        7428 :     AH->WriteBytePtr(AH, wasSet);
    1908             : 
    1909             :     /* Write out pgoff_t smallest byte first, prevents endian mismatch */
    1910       66852 :     for (off = 0; off < sizeof(pgoff_t); off++)
    1911             :     {
    1912       59424 :         AH->WriteBytePtr(AH, o & 0xFF);
    1913       59424 :         o >>= 8;
    1914             :     }
    1915        7428 :     return sizeof(pgoff_t) + 1;
    1916             : }
    1917             : 
    1918             : int
    1919        3714 : ReadOffset(ArchiveHandle *AH, pgoff_t * o)
    1920             : {
    1921             :     int         i;
    1922             :     int         off;
    1923             :     int         offsetFlg;
    1924             : 
    1925             :     /* Initialize to zero */
    1926        3714 :     *o = 0;
    1927             : 
    1928             :     /* Check for old version */
    1929        3714 :     if (AH->version < K_VERS_1_7)
    1930             :     {
    1931             :         /* Prior versions wrote offsets using WriteInt */
    1932           0 :         i = ReadInt(AH);
    1933             :         /* -1 means not set */
    1934           0 :         if (i < 0)
    1935           0 :             return K_OFFSET_POS_NOT_SET;
    1936           0 :         else if (i == 0)
    1937           0 :             return K_OFFSET_NO_DATA;
    1938             : 
    1939             :         /* Cast to pgoff_t because it was written as an int. */
    1940           0 :         *o = (pgoff_t) i;
    1941           0 :         return K_OFFSET_POS_SET;
    1942             :     }
    1943             : 
    1944             :     /*
    1945             :      * Read the flag indicating the state of the data pointer. Check if valid
    1946             :      * and die if not.
    1947             :      *
    1948             :      * This used to be handled by a negative or zero pointer, now we use an
    1949             :      * extra byte specifically for the state.
    1950             :      */
    1951        3714 :     offsetFlg = AH->ReadBytePtr(AH) & 0xFF;
    1952             : 
    1953        3714 :     switch (offsetFlg)
    1954             :     {
    1955             :         case K_OFFSET_POS_NOT_SET:
    1956             :         case K_OFFSET_NO_DATA:
    1957             :         case K_OFFSET_POS_SET:
    1958             : 
    1959        3714 :             break;
    1960             : 
    1961             :         default:
    1962           0 :             fatal("unexpected data offset flag %d", offsetFlg);
    1963             :     }
    1964             : 
    1965             :     /*
    1966             :      * Read the bytes
    1967             :      */
    1968       33426 :     for (off = 0; off < AH->offSize; off++)
    1969             :     {
    1970       29712 :         if (off < sizeof(pgoff_t))
    1971       29712 :             *o |= ((pgoff_t) (AH->ReadBytePtr(AH))) << (off * 8);
    1972             :         else
    1973             :         {
    1974           0 :             if (AH->ReadBytePtr(AH) != 0)
    1975           0 :                 fatal("file offset in dump file is too large");
    1976             :         }
    1977             :     }
    1978             : 
    1979        3714 :     return offsetFlg;
    1980             : }
    1981             : 
    1982             : size_t
    1983      152386 : WriteInt(ArchiveHandle *AH, int i)
    1984             : {
    1985             :     int         b;
    1986             : 
    1987             :     /*
    1988             :      * This is a bit yucky, but I don't want to make the binary format very
    1989             :      * dependent on representation, and not knowing much about it, I write out
    1990             :      * a sign byte. If you change this, don't forget to change the file
    1991             :      * version #, and modify ReadInt to read the new format AS WELL AS the old
    1992             :      * formats.
    1993             :      */
    1994             : 
    1995             :     /* SIGN byte */
    1996      152386 :     if (i < 0)
    1997             :     {
    1998       32790 :         AH->WriteBytePtr(AH, 1);
    1999       32790 :         i = -i;
    2000             :     }
    2001             :     else
    2002      119596 :         AH->WriteBytePtr(AH, 0);
    2003             : 
    2004      761930 :     for (b = 0; b < AH->intSize; b++)
    2005             :     {
    2006      609544 :         AH->WriteBytePtr(AH, i & 0xFF);
    2007      609544 :         i >>= 8;
    2008             :     }
    2009             : 
    2010      152386 :     return AH->intSize + 1;
    2011             : }
    2012             : 
    2013             : int
    2014       88620 : ReadInt(ArchiveHandle *AH)
    2015             : {
    2016       88620 :     int         res = 0;
    2017             :     int         bv,
    2018             :                 b;
    2019       88620 :     int         sign = 0;       /* Default positive */
    2020       88620 :     int         bitShift = 0;
    2021             : 
    2022       88620 :     if (AH->version > K_VERS_1_0)
    2023             :         /* Read a sign byte */
    2024       88620 :         sign = AH->ReadBytePtr(AH);
    2025             : 
    2026      443100 :     for (b = 0; b < AH->intSize; b++)
    2027             :     {
    2028      354480 :         bv = AH->ReadBytePtr(AH) & 0xFF;
    2029      354480 :         if (bv != 0)
    2030       86790 :             res = res + (bv << bitShift);
    2031      354480 :         bitShift += 8;
    2032             :     }
    2033             : 
    2034       88620 :     if (sign)
    2035       19474 :         res = -res;
    2036             : 
    2037       88620 :     return res;
    2038             : }
    2039             : 
    2040             : size_t
    2041      125730 : WriteStr(ArchiveHandle *AH, const char *c)
    2042             : {
    2043             :     size_t      res;
    2044             : 
    2045      125730 :     if (c)
    2046             :     {
    2047       92966 :         int         len = strlen(c);
    2048             : 
    2049       92966 :         res = WriteInt(AH, len);
    2050       92966 :         AH->WriteBufPtr(AH, c, len);
    2051       92966 :         res += len;
    2052             :     }
    2053             :     else
    2054       32764 :         res = WriteInt(AH, -1);
    2055             : 
    2056      125730 :     return res;
    2057             : }
    2058             : 
    2059             : char *
    2060       73070 : ReadStr(ArchiveHandle *AH)
    2061             : {
    2062             :     char       *buf;
    2063             :     int         l;
    2064             : 
    2065       73070 :     l = ReadInt(AH);
    2066       73070 :     if (l < 0)
    2067       19446 :         buf = NULL;
    2068             :     else
    2069             :     {
    2070       53624 :         buf = (char *) pg_malloc(l + 1);
    2071       53624 :         AH->ReadBufPtr(AH, (void *) buf, l);
    2072             : 
    2073       53624 :         buf[l] = '\0';
    2074             :     }
    2075             : 
    2076       73070 :     return buf;
    2077             : }
    2078             : 
    2079             : static int
    2080          28 : _discoverArchiveFormat(ArchiveHandle *AH)
    2081             : {
    2082             :     FILE       *fh;
    2083             :     char        sig[6];         /* More than enough */
    2084             :     size_t      cnt;
    2085          28 :     int         wantClose = 0;
    2086             : 
    2087          28 :     pg_log_debug("attempting to ascertain archive format");
    2088             : 
    2089          28 :     if (AH->lookahead)
    2090           0 :         free(AH->lookahead);
    2091             : 
    2092          28 :     AH->lookaheadSize = 512;
    2093          28 :     AH->lookahead = pg_malloc0(512);
    2094          28 :     AH->lookaheadLen = 0;
    2095          28 :     AH->lookaheadPos = 0;
    2096             : 
    2097          28 :     if (AH->fSpec)
    2098             :     {
    2099             :         struct stat st;
    2100             : 
    2101          28 :         wantClose = 1;
    2102             : 
    2103             :         /*
    2104             :          * Check if the specified archive is a directory. If so, check if
    2105             :          * there's a "toc.dat" (or "toc.dat.gz") file in it.
    2106             :          */
    2107          28 :         if (stat(AH->fSpec, &st) == 0 && S_ISDIR(st.st_mode))
    2108             :         {
    2109             :             char        buf[MAXPGPATH];
    2110             : 
    2111          12 :             if (snprintf(buf, MAXPGPATH, "%s/toc.dat", AH->fSpec) >= MAXPGPATH)
    2112           0 :                 fatal("directory name too long: \"%s\"",
    2113             :                       AH->fSpec);
    2114          12 :             if (stat(buf, &st) == 0 && S_ISREG(st.st_mode))
    2115             :             {
    2116          12 :                 AH->format = archDirectory;
    2117          24 :                 return AH->format;
    2118             :             }
    2119             : 
    2120             : #ifdef HAVE_LIBZ
    2121           0 :             if (snprintf(buf, MAXPGPATH, "%s/toc.dat.gz", AH->fSpec) >= MAXPGPATH)
    2122           0 :                 fatal("directory name too long: \"%s\"",
    2123             :                       AH->fSpec);
    2124           0 :             if (stat(buf, &st) == 0 && S_ISREG(st.st_mode))
    2125             :             {
    2126           0 :                 AH->format = archDirectory;
    2127           0 :                 return AH->format;
    2128             :             }
    2129             : #endif
    2130           0 :             fatal("directory \"%s\" does not appear to be a valid archive (\"toc.dat\" does not exist)",
    2131             :                   AH->fSpec);
    2132             :             fh = NULL;          /* keep compiler quiet */
    2133             :         }
    2134             :         else
    2135             :         {
    2136          16 :             fh = fopen(AH->fSpec, PG_BINARY_R);
    2137          16 :             if (!fh)
    2138           0 :                 fatal("could not open input file \"%s\": %m", AH->fSpec);
    2139             :         }
    2140             :     }
    2141             :     else
    2142             :     {
    2143           0 :         fh = stdin;
    2144           0 :         if (!fh)
    2145           0 :             fatal("could not open input file: %m");
    2146             :     }
    2147             : 
    2148          16 :     if ((cnt = fread(sig, 1, 5, fh)) != 5)
    2149             :     {
    2150           0 :         if (ferror(fh))
    2151           0 :             fatal("could not read input file: %m");
    2152             :         else
    2153           0 :             fatal("input file is too short (read %lu, expected 5)",
    2154             :                   (unsigned long) cnt);
    2155             :     }
    2156             : 
    2157             :     /* Save it, just in case we need it later */
    2158          16 :     memcpy(&AH->lookahead[0], sig, 5);
    2159          16 :     AH->lookaheadLen = 5;
    2160             : 
    2161          16 :     if (strncmp(sig, "PGDMP", 5) == 0)
    2162             :     {
    2163             :         int         byteread;
    2164             :         char        vmaj,
    2165             :                     vmin,
    2166             :                     vrev;
    2167             : 
    2168             :         /*
    2169             :          * Finish reading (most of) a custom-format header.
    2170             :          *
    2171             :          * NB: this code must agree with ReadHead().
    2172             :          */
    2173          14 :         if ((byteread = fgetc(fh)) == EOF)
    2174           0 :             READ_ERROR_EXIT(fh);
    2175             : 
    2176          14 :         vmaj = byteread;
    2177             : 
    2178          14 :         if ((byteread = fgetc(fh)) == EOF)
    2179           0 :             READ_ERROR_EXIT(fh);
    2180             : 
    2181          14 :         vmin = byteread;
    2182             : 
    2183             :         /* Save these too... */
    2184          14 :         AH->lookahead[AH->lookaheadLen++] = vmaj;
    2185          14 :         AH->lookahead[AH->lookaheadLen++] = vmin;
    2186             : 
    2187             :         /* Check header version; varies from V1.0 */
    2188          14 :         if (vmaj > 1 || (vmaj == 1 && vmin > 0))  /* Version > 1.0 */
    2189             :         {
    2190          14 :             if ((byteread = fgetc(fh)) == EOF)
    2191           0 :                 READ_ERROR_EXIT(fh);
    2192             : 
    2193          14 :             vrev = byteread;
    2194          14 :             AH->lookahead[AH->lookaheadLen++] = vrev;
    2195             :         }
    2196             :         else
    2197           0 :             vrev = 0;
    2198             : 
    2199          14 :         AH->version = MAKE_ARCHIVE_VERSION(vmaj, vmin, vrev);
    2200             : 
    2201          14 :         if ((AH->intSize = fgetc(fh)) == EOF)
    2202           0 :             READ_ERROR_EXIT(fh);
    2203          14 :         AH->lookahead[AH->lookaheadLen++] = AH->intSize;
    2204             : 
    2205          14 :         if (AH->version >= K_VERS_1_7)
    2206             :         {
    2207          14 :             if ((AH->offSize = fgetc(fh)) == EOF)
    2208           0 :                 READ_ERROR_EXIT(fh);
    2209          14 :             AH->lookahead[AH->lookaheadLen++] = AH->offSize;
    2210             :         }
    2211             :         else
    2212           0 :             AH->offSize = AH->intSize;
    2213             : 
    2214          14 :         if ((byteread = fgetc(fh)) == EOF)
    2215           0 :             READ_ERROR_EXIT(fh);
    2216             : 
    2217          14 :         AH->format = byteread;
    2218          14 :         AH->lookahead[AH->lookaheadLen++] = AH->format;
    2219             :     }
    2220             :     else
    2221             :     {
    2222             :         /*
    2223             :          * *Maybe* we have a tar archive format file or a text dump ... So,
    2224             :          * read first 512 byte header...
    2225             :          */
    2226           2 :         cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
    2227             :         /* read failure is checked below */
    2228           2 :         AH->lookaheadLen += cnt;
    2229             : 
    2230           4 :         if (AH->lookaheadLen >= strlen(TEXT_DUMPALL_HEADER) &&
    2231           4 :             (strncmp(AH->lookahead, TEXT_DUMP_HEADER, strlen(TEXT_DUMP_HEADER)) == 0 ||
    2232           2 :              strncmp(AH->lookahead, TEXT_DUMPALL_HEADER, strlen(TEXT_DUMPALL_HEADER)) == 0))
    2233             :         {
    2234             :             /*
    2235             :              * looks like it's probably a text format dump. so suggest they
    2236             :              * try psql
    2237             :              */
    2238           0 :             fatal("input file appears to be a text format dump. Please use psql.");
    2239             :         }
    2240             : 
    2241           2 :         if (AH->lookaheadLen != 512)
    2242             :         {
    2243           0 :             if (feof(fh))
    2244           0 :                 fatal("input file does not appear to be a valid archive (too short?)");
    2245             :             else
    2246           0 :                 READ_ERROR_EXIT(fh);
    2247             :         }
    2248             : 
    2249           2 :         if (!isValidTarHeader(AH->lookahead))
    2250           0 :             fatal("input file does not appear to be a valid archive");
    2251             : 
    2252           2 :         AH->format = archTar;
    2253             :     }
    2254             : 
    2255             :     /* If we can't seek, then mark the header as read */
    2256          16 :     if (fseeko(fh, 0, SEEK_SET) != 0)
    2257             :     {
    2258             :         /*
    2259             :          * NOTE: Formats that use the lookahead buffer can unset this in their
    2260             :          * Init routine.
    2261             :          */
    2262           0 :         AH->readHeader = 1;
    2263             :     }
    2264             :     else
    2265          16 :         AH->lookaheadLen = 0;    /* Don't bother since we've reset the file */
    2266             : 
    2267             :     /* Close the file */
    2268          16 :     if (wantClose)
    2269          16 :         if (fclose(fh) != 0)
    2270           0 :             fatal("could not close input file: %m");
    2271             : 
    2272          16 :     return AH->format;
    2273             : }
    2274             : 
    2275             : 
    2276             : /*
    2277             :  * Allocate an archive handle
    2278             :  */
    2279             : static ArchiveHandle *
    2280         204 : _allocAH(const char *FileSpec, const ArchiveFormat fmt,
    2281             :          const int compression, bool dosync, ArchiveMode mode,
    2282             :          SetupWorkerPtrType setupWorkerPtr)
    2283             : {
    2284             :     ArchiveHandle *AH;
    2285             : 
    2286         204 :     pg_log_debug("allocating AH for %s, format %d", FileSpec, fmt);
    2287             : 
    2288         204 :     AH = (ArchiveHandle *) pg_malloc0(sizeof(ArchiveHandle));
    2289             : 
    2290         204 :     AH->version = K_VERS_SELF;
    2291             : 
    2292             :     /* initialize for backwards compatible string processing */
    2293         204 :     AH->public.encoding = 0; /* PG_SQL_ASCII */
    2294         204 :     AH->public.std_strings = false;
    2295             : 
    2296             :     /* sql error handling */
    2297         204 :     AH->public.exit_on_error = true;
    2298         204 :     AH->public.n_errors = 0;
    2299             : 
    2300         204 :     AH->archiveDumpVersion = PG_VERSION;
    2301             : 
    2302         204 :     AH->createDate = time(NULL);
    2303             : 
    2304         204 :     AH->intSize = sizeof(int);
    2305         204 :     AH->offSize = sizeof(pgoff_t);
    2306         204 :     if (FileSpec)
    2307             :     {
    2308         192 :         AH->fSpec = pg_strdup(FileSpec);
    2309             : 
    2310             :         /*
    2311             :          * Not used; maybe later....
    2312             :          *
    2313             :          * AH->workDir = pg_strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
    2314             :          * i--) if (AH->workDir[i-1] == '/')
    2315             :          */
    2316             :     }
    2317             :     else
    2318          12 :         AH->fSpec = NULL;
    2319             : 
    2320         204 :     AH->currUser = NULL;     /* unknown */
    2321         204 :     AH->currSchema = NULL;       /* ditto */
    2322         204 :     AH->currTablespace = NULL;   /* ditto */
    2323         204 :     AH->currTableAm = NULL;      /* ditto */
    2324             : 
    2325         204 :     AH->toc = (TocEntry *) pg_malloc0(sizeof(TocEntry));
    2326             : 
    2327         204 :     AH->toc->next = AH->toc;
    2328         204 :     AH->toc->prev = AH->toc;
    2329             : 
    2330         204 :     AH->mode = mode;
    2331         204 :     AH->compression = compression;
    2332         204 :     AH->dosync = dosync;
    2333             : 
    2334         204 :     memset(&(AH->sqlparse), 0, sizeof(AH->sqlparse));
    2335             : 
    2336             :     /* Open stdout with no compression for AH output handle */
    2337         204 :     AH->gzOut = 0;
    2338         204 :     AH->OF = stdout;
    2339             : 
    2340             :     /*
    2341             :      * On Windows, we need to use binary mode to read/write non-text files,
    2342             :      * which include all archive formats as well as compressed plain text.
    2343             :      * Force stdin/stdout into binary mode if that is what we are using.
    2344             :      */
    2345             : #ifdef WIN32
    2346             :     if ((fmt != archNull || compression != 0) &&
    2347             :         (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
    2348             :     {
    2349             :         if (mode == archModeWrite)
    2350             :             _setmode(fileno(stdout), O_BINARY);
    2351             :         else
    2352             :             _setmode(fileno(stdin), O_BINARY);
    2353             :     }
    2354             : #endif
    2355             : 
    2356         204 :     AH->SetupWorkerPtr = setupWorkerPtr;
    2357             : 
    2358         204 :     if (fmt == archUnknown)
    2359          28 :         AH->format = _discoverArchiveFormat(AH);
    2360             :     else
    2361         176 :         AH->format = fmt;
    2362             : 
    2363         204 :     AH->promptPassword = TRI_DEFAULT;
    2364             : 
    2365         204 :     switch (AH->format)
    2366             :     {
    2367             :         case archCustom:
    2368          36 :             InitArchiveFmt_Custom(AH);
    2369          36 :             break;
    2370             : 
    2371             :         case archNull:
    2372         134 :             InitArchiveFmt_Null(AH);
    2373         134 :             break;
    2374             : 
    2375             :         case archDirectory:
    2376          26 :             InitArchiveFmt_Directory(AH);
    2377          26 :             break;
    2378             : 
    2379             :         case archTar:
    2380           8 :             InitArchiveFmt_Tar(AH);
    2381           8 :             break;
    2382             : 
    2383             :         default:
    2384           0 :             fatal("unrecognized file format \"%d\"", fmt);
    2385             :     }
    2386             : 
    2387         204 :     return AH;
    2388             : }
    2389             : 
    2390             : /*
    2391             :  * Write out all data (tables & blobs)
    2392             :  */
    2393             : void
    2394          34 : WriteDataChunks(ArchiveHandle *AH, ParallelState *pstate)
    2395             : {
    2396             :     TocEntry   *te;
    2397             : 
    2398          34 :     if (pstate && pstate->numWorkers > 1)
    2399           8 :     {
    2400             :         /*
    2401             :          * In parallel mode, this code runs in the master process.  We
    2402             :          * construct an array of candidate TEs, then sort it into decreasing
    2403             :          * size order, then dispatch each TE to a data-transfer worker.  By
    2404             :          * dumping larger tables first, we avoid getting into a situation
    2405             :          * where we're down to one job and it's big, losing parallelism.
    2406             :          */
    2407             :         TocEntry  **tes;
    2408             :         int         ntes;
    2409             : 
    2410           8 :         tes = (TocEntry **) pg_malloc(AH->tocCount * sizeof(TocEntry *));
    2411           8 :         ntes = 0;
    2412         474 :         for (te = AH->toc->next; te != AH->toc; te = te->next)
    2413             :         {
    2414             :             /* Consider only TEs with dataDumper functions ... */
    2415         466 :             if (!te->dataDumper)
    2416         428 :                 continue;
    2417             :             /* ... and ignore ones not enabled for dump */
    2418          38 :             if ((te->reqs & REQ_DATA) == 0)
    2419           0 :                 continue;
    2420             : 
    2421          38 :             tes[ntes++] = te;
    2422             :         }
    2423             : 
    2424           8 :         if (ntes > 1)
    2425           2 :             qsort((void *) tes, ntes, sizeof(TocEntry *),
    2426             :                   TocEntrySizeCompare);
    2427             : 
    2428          46 :         for (int i = 0; i < ntes; i++)
    2429          38 :             DispatchJobForTocEntry(AH, pstate, tes[i], ACT_DUMP,
    2430             :                                    mark_dump_job_done, NULL);
    2431             : 
    2432           8 :         pg_free(tes);
    2433             : 
    2434             :         /* Now wait for workers to finish. */
    2435           8 :         WaitForWorkers(AH, pstate, WFW_ALL_IDLE);
    2436             :     }
    2437             :     else
    2438             :     {
    2439             :         /* Non-parallel mode: just dump all candidate TEs sequentially. */
    2440        4592 :         for (te = AH->toc->next; te != AH->toc; te = te->next)
    2441             :         {
    2442             :             /* Must have same filter conditions as above */
    2443        4566 :             if (!te->dataDumper)
    2444        4460 :                 continue;
    2445         106 :             if ((te->reqs & REQ_DATA) == 0)
    2446           4 :                 continue;
    2447             : 
    2448         102 :             WriteDataChunksForTocEntry(AH, te);
    2449             :         }
    2450             :     }
    2451          34 : }
    2452             : 
    2453             : 
    2454             : /*
    2455             :  * Callback function that's invoked in the master process after a step has
    2456             :  * been parallel dumped.
    2457             :  *
    2458             :  * We don't need to do anything except check for worker failure.
    2459             :  */
    2460             : static void
    2461          38 : mark_dump_job_done(ArchiveHandle *AH,
    2462             :                    TocEntry *te,
    2463             :                    int status,
    2464             :                    void *callback_data)
    2465             : {
    2466          38 :     pg_log_info("finished item %d %s %s",
    2467             :                 te->dumpId, te->desc, te->tag);
    2468             : 
    2469          38 :     if (status != 0)
    2470           0 :         fatal("worker process failed: exit code %d",
    2471             :               status);
    2472          38 : }
    2473             : 
    2474             : 
    2475             : void
    2476         140 : WriteDataChunksForTocEntry(ArchiveHandle *AH, TocEntry *te)
    2477             : {
    2478             :     StartDataPtrType startPtr;
    2479             :     EndDataPtrType endPtr;
    2480             : 
    2481         140 :     AH->currToc = te;
    2482             : 
    2483         140 :     if (strcmp(te->desc, "BLOBS") == 0)
    2484             :     {
    2485           8 :         startPtr = AH->StartBlobsPtr;
    2486           8 :         endPtr = AH->EndBlobsPtr;
    2487             :     }
    2488             :     else
    2489             :     {
    2490         132 :         startPtr = AH->StartDataPtr;
    2491         132 :         endPtr = AH->EndDataPtr;
    2492             :     }
    2493             : 
    2494         140 :     if (startPtr != NULL)
    2495         140 :         (*startPtr) (AH, te);
    2496             : 
    2497             :     /*
    2498             :      * The user-provided DataDumper routine needs to call AH->WriteData
    2499             :      */
    2500         140 :     te->dataDumper((Archive *) AH, te->dataDumperArg);
    2501             : 
    2502         140 :     if (endPtr != NULL)
    2503         140 :         (*endPtr) (AH, te);
    2504             : 
    2505         140 :     AH->currToc = NULL;
    2506         140 : }
    2507             : 
    2508             : void
    2509          52 : WriteToc(ArchiveHandle *AH)
    2510             : {
    2511             :     TocEntry   *te;
    2512             :     char        workbuf[32];
    2513             :     int         tocCount;
    2514             :     int         i;
    2515             : 
    2516             :     /* count entries that will actually be dumped */
    2517          52 :     tocCount = 0;
    2518        8802 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    2519             :     {
    2520        8750 :         if ((te->reqs & (REQ_SCHEMA | REQ_DATA | REQ_SPECIAL)) != 0)
    2521        8742 :             tocCount++;
    2522             :     }
    2523             : 
    2524             :     /* printf("%d TOC Entries to save\n", tocCount); */
    2525             : 
    2526          52 :     WriteInt(AH, tocCount);
    2527             : 
    2528        8802 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    2529             :     {
    2530        8750 :         if ((te->reqs & (REQ_SCHEMA | REQ_DATA | REQ_SPECIAL)) == 0)
    2531           8 :             continue;
    2532             : 
    2533        8742 :         WriteInt(AH, te->dumpId);
    2534        8742 :         WriteInt(AH, te->dataDumper ? 1 : 0);
    2535             : 
    2536             :         /* OID is recorded as a string for historical reasons */
    2537        8742 :         sprintf(workbuf, "%u", te->catalogId.tableoid);
    2538        8742 :         WriteStr(AH, workbuf);
    2539        8742 :         sprintf(workbuf, "%u", te->catalogId.oid);
    2540        8742 :         WriteStr(AH, workbuf);
    2541             : 
    2542        8742 :         WriteStr(AH, te->tag);
    2543        8742 :         WriteStr(AH, te->desc);
    2544        8742 :         WriteInt(AH, te->section);
    2545        8742 :         WriteStr(AH, te->defn);
    2546        8742 :         WriteStr(AH, te->dropStmt);
    2547        8742 :         WriteStr(AH, te->copyStmt);
    2548        8742 :         WriteStr(AH, te->namespace);
    2549        8742 :         WriteStr(AH, te->tablespace);
    2550        8742 :         WriteStr(AH, te->tableam);
    2551        8742 :         WriteStr(AH, te->owner);
    2552        8742 :         WriteStr(AH, "false");
    2553             : 
    2554             :         /* Dump list of dependencies */
    2555       19410 :         for (i = 0; i < te->nDeps; i++)
    2556             :         {
    2557       10668 :             sprintf(workbuf, "%d", te->dependencies[i]);
    2558       10668 :             WriteStr(AH, workbuf);
    2559             :         }
    2560        8742 :         WriteStr(AH, NULL);     /* Terminate List */
    2561             : 
    2562        8742 :         if (AH->WriteExtraTocPtr)
    2563        8742 :             AH->WriteExtraTocPtr(AH, te);
    2564             :     }
    2565          52 : }
    2566             : 
    2567             : void
    2568          36 : ReadToc(ArchiveHandle *AH)
    2569             : {
    2570             :     int         i;
    2571             :     char       *tmp;
    2572             :     DumpId     *deps;
    2573             :     int         depIdx;
    2574             :     int         depSize;
    2575             :     TocEntry   *te;
    2576             : 
    2577          36 :     AH->tocCount = ReadInt(AH);
    2578          36 :     AH->maxDumpId = 0;
    2579             : 
    2580        5076 :     for (i = 0; i < AH->tocCount; i++)
    2581             :     {
    2582        5040 :         te = (TocEntry *) pg_malloc0(sizeof(TocEntry));
    2583        5040 :         te->dumpId = ReadInt(AH);
    2584             : 
    2585        5040 :         if (te->dumpId > AH->maxDumpId)
    2586        1084 :             AH->maxDumpId = te->dumpId;
    2587             : 
    2588             :         /* Sanity check */
    2589        5040 :         if (te->dumpId <= 0)
    2590           0 :             fatal("entry ID %d out of range -- perhaps a corrupt TOC",
    2591             :                   te->dumpId);
    2592             : 
    2593        5040 :         te->hadDumper = ReadInt(AH);
    2594             : 
    2595        5040 :         if (AH->version >= K_VERS_1_8)
    2596             :         {
    2597        5040 :             tmp = ReadStr(AH);
    2598        5040 :             sscanf(tmp, "%u", &te->catalogId.tableoid);
    2599        5040 :             free(tmp);
    2600             :         }
    2601             :         else
    2602           0 :             te->catalogId.tableoid = InvalidOid;
    2603        5040 :         tmp = ReadStr(AH);
    2604        5040 :         sscanf(tmp, "%u", &te->catalogId.oid);
    2605        5040 :         free(tmp);
    2606             : 
    2607        5040 :         te->tag = ReadStr(AH);
    2608        5040 :         te->desc = ReadStr(AH);
    2609             : 
    2610        5040 :         if (AH->version >= K_VERS_1_11)
    2611             :         {
    2612        5040 :             te->section = ReadInt(AH);
    2613             :         }
    2614             :         else
    2615             :         {
    2616             :             /*
    2617             :              * Rules for pre-8.4 archives wherein pg_dump hasn't classified
    2618             :              * the entries into sections.  This list need not cover entry
    2619             :              * types added later than 8.4.
    2620             :              */
    2621           0 :             if (strcmp(te->desc, "COMMENT") == 0 ||
    2622           0 :                 strcmp(te->desc, "ACL") == 0 ||
    2623           0 :                 strcmp(te->desc, "ACL LANGUAGE") == 0)
    2624           0 :                 te->section = SECTION_NONE;
    2625           0 :             else if (strcmp(te->desc, "TABLE DATA") == 0 ||
    2626           0 :                      strcmp(te->desc, "BLOBS") == 0 ||
    2627           0 :                      strcmp(te->desc, "BLOB COMMENTS") == 0)
    2628           0 :                 te->section = SECTION_DATA;
    2629           0 :             else if (strcmp(te->desc, "CONSTRAINT") == 0 ||
    2630           0 :                      strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
    2631           0 :                      strcmp(te->desc, "FK CONSTRAINT") == 0 ||
    2632           0 :                      strcmp(te->desc, "INDEX") == 0 ||
    2633           0 :                      strcmp(te->desc, "RULE") == 0 ||
    2634           0 :                      strcmp(te->desc, "TRIGGER") == 0)
    2635           0 :                 te->section = SECTION_POST_DATA;
    2636             :             else
    2637           0 :                 te->section = SECTION_PRE_DATA;
    2638             :         }
    2639             : 
    2640        5040 :         te->defn = ReadStr(AH);
    2641        5040 :         te->dropStmt = ReadStr(AH);
    2642             : 
    2643        5040 :         if (AH->version >= K_VERS_1_3)
    2644        5040 :             te->copyStmt = ReadStr(AH);
    2645             : 
    2646        5040 :         if (AH->version >= K_VERS_1_6)
    2647        5040 :             te->namespace = ReadStr(AH);
    2648             : 
    2649        5040 :         if (AH->version >= K_VERS_1_10)
    2650        5040 :             te->tablespace = ReadStr(AH);
    2651             : 
    2652        5040 :         if (AH->version >= K_VERS_1_14)
    2653        5040 :             te->tableam = ReadStr(AH);
    2654             : 
    2655        5040 :         te->owner = ReadStr(AH);
    2656        5040 :         if (AH->version < K_VERS_1_9 || strcmp(ReadStr(AH), "true") == 0)
    2657           0 :             pg_log_warning("restoring tables WITH OIDS is not supported anymore");
    2658             : 
    2659             :         /* Read TOC entry dependencies */
    2660        5040 :         if (AH->version >= K_VERS_1_5)
    2661             :         {
    2662        5040 :             depSize = 100;
    2663        5040 :             deps = (DumpId *) pg_malloc(sizeof(DumpId) * depSize);
    2664        5040 :             depIdx = 0;
    2665             :             for (;;)
    2666             :             {
    2667       17272 :                 tmp = ReadStr(AH);
    2668       11156 :                 if (!tmp)
    2669        5040 :                     break;      /* end of list */
    2670        6116 :                 if (depIdx >= depSize)
    2671             :                 {
    2672           0 :                     depSize *= 2;
    2673           0 :                     deps = (DumpId *) pg_realloc(deps, sizeof(DumpId) * depSize);
    2674             :                 }
    2675        6116 :                 sscanf(tmp, "%d", &deps[depIdx]);
    2676        6116 :                 free(tmp);
    2677        6116 :                 depIdx++;
    2678             :             }
    2679             : 
    2680        5040 :             if (depIdx > 0)      /* We have a non-null entry */
    2681             :             {
    2682        3542 :                 deps = (DumpId *) pg_realloc(deps, sizeof(DumpId) * depIdx);
    2683        3542 :                 te->dependencies = deps;
    2684        3542 :                 te->nDeps = depIdx;
    2685             :             }
    2686             :             else
    2687             :             {
    2688        1498 :                 free(deps);
    2689        1498 :                 te->dependencies = NULL;
    2690        1498 :                 te->nDeps = 0;
    2691             :             }
    2692             :         }
    2693             :         else
    2694             :         {
    2695           0 :             te->dependencies = NULL;
    2696           0 :             te->nDeps = 0;
    2697             :         }
    2698        5040 :         te->dataLength = 0;
    2699             : 
    2700        5040 :         if (AH->ReadExtraTocPtr)
    2701        5040 :             AH->ReadExtraTocPtr(AH, te);
    2702             : 
    2703        5040 :         pg_log_debug("read TOC entry %d (ID %d) for %s %s",
    2704             :                      i, te->dumpId, te->desc, te->tag);
    2705             : 
    2706             :         /* link completed entry into TOC circular list */
    2707        5040 :         te->prev = AH->toc->prev;
    2708        5040 :         AH->toc->prev->next = te;
    2709        5040 :         AH->toc->prev = te;
    2710        5040 :         te->next = AH->toc;
    2711             : 
    2712             :         /* special processing immediately upon read for some items */
    2713        5040 :         if (strcmp(te->desc, "ENCODING") == 0)
    2714          36 :             processEncodingEntry(AH, te);
    2715        5004 :         else if (strcmp(te->desc, "STDSTRINGS") == 0)
    2716          36 :             processStdStringsEntry(AH, te);
    2717        4968 :         else if (strcmp(te->desc, "SEARCHPATH") == 0)
    2718          36 :             processSearchPathEntry(AH, te);
    2719             :     }
    2720          36 : }
    2721             : 
    2722             : static void
    2723          36 : processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
    2724             : {
    2725             :     /* te->defn should have the form SET client_encoding = 'foo'; */
    2726          36 :     char       *defn = pg_strdup(te->defn);
    2727             :     char       *ptr1;
    2728          36 :     char       *ptr2 = NULL;
    2729             :     int         encoding;
    2730             : 
    2731          36 :     ptr1 = strchr(defn, '\'');
    2732          36 :     if (ptr1)
    2733          36 :         ptr2 = strchr(++ptr1, '\'');
    2734          36 :     if (ptr2)
    2735             :     {
    2736          36 :         *ptr2 = '\0';
    2737          36 :         encoding = pg_char_to_encoding(ptr1);
    2738          36 :         if (encoding < 0)
    2739           0 :             fatal("unrecognized encoding \"%s\"",
    2740             :                   ptr1);
    2741          36 :         AH->public.encoding = encoding;
    2742             :     }
    2743             :     else
    2744           0 :         fatal("invalid ENCODING item: %s",
    2745             :               te->defn);
    2746             : 
    2747          36 :     free(defn);
    2748          36 : }
    2749             : 
    2750             : static void
    2751          36 : processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
    2752             : {
    2753             :     /* te->defn should have the form SET standard_conforming_strings = 'x'; */
    2754             :     char       *ptr1;
    2755             : 
    2756          36 :     ptr1 = strchr(te->defn, '\'');
    2757          36 :     if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
    2758          36 :         AH->public.std_strings = true;
    2759           0 :     else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
    2760           0 :         AH->public.std_strings = false;
    2761             :     else
    2762           0 :         fatal("invalid STDSTRINGS item: %s",
    2763             :               te->defn);
    2764          36 : }
    2765             : 
    2766             : static void
    2767          36 : processSearchPathEntry(ArchiveHandle *AH, TocEntry *te)
    2768             : {
    2769             :     /*
    2770             :      * te->defn should contain a command to set search_path.  We just copy it
    2771             :      * verbatim for use later.
    2772             :      */
    2773          36 :     AH->public.searchpath = pg_strdup(te->defn);
    2774          36 : }
    2775             : 
    2776             : static void
    2777           0 : StrictNamesCheck(RestoreOptions *ropt)
    2778             : {
    2779             :     const char *missing_name;
    2780             : 
    2781             :     Assert(ropt->strict_names);
    2782             : 
    2783           0 :     if (ropt->schemaNames.head != NULL)
    2784             :     {
    2785           0 :         missing_name = simple_string_list_not_touched(&ropt->schemaNames);
    2786           0 :         if (missing_name != NULL)
    2787           0 :             fatal("schema \"%s\" not found", missing_name);
    2788             :     }
    2789             : 
    2790           0 :     if (ropt->tableNames.head != NULL)
    2791             :     {
    2792           0 :         missing_name = simple_string_list_not_touched(&ropt->tableNames);
    2793           0 :         if (missing_name != NULL)
    2794           0 :             fatal("table \"%s\" not found", missing_name);
    2795             :     }
    2796             : 
    2797           0 :     if (ropt->indexNames.head != NULL)
    2798             :     {
    2799           0 :         missing_name = simple_string_list_not_touched(&ropt->indexNames);
    2800           0 :         if (missing_name != NULL)
    2801           0 :             fatal("index \"%s\" not found", missing_name);
    2802             :     }
    2803             : 
    2804           0 :     if (ropt->functionNames.head != NULL)
    2805             :     {
    2806           0 :         missing_name = simple_string_list_not_touched(&ropt->functionNames);
    2807           0 :         if (missing_name != NULL)
    2808           0 :             fatal("function \"%s\" not found", missing_name);
    2809             :     }
    2810             : 
    2811           0 :     if (ropt->triggerNames.head != NULL)
    2812             :     {
    2813           0 :         missing_name = simple_string_list_not_touched(&ropt->triggerNames);
    2814           0 :         if (missing_name != NULL)
    2815           0 :             fatal("trigger \"%s\" not found", missing_name);
    2816             :     }
    2817           0 : }
    2818             : 
    2819             : /*
    2820             :  * Determine whether we want to restore this TOC entry.
    2821             :  *
    2822             :  * Returns 0 if entry should be skipped, or some combination of the
    2823             :  * REQ_SCHEMA and REQ_DATA bits if we want to restore schema and/or data
    2824             :  * portions of this TOC entry, or REQ_SPECIAL if it's a special entry.
    2825             :  */
    2826             : static teReqs
    2827       24740 : _tocEntryRequired(TocEntry *te, teSection curSection, ArchiveHandle *AH)
    2828             : {
    2829       24740 :     teReqs      res = REQ_SCHEMA | REQ_DATA;
    2830       24740 :     RestoreOptions *ropt = AH->public.ropt;
    2831             : 
    2832             :     /* These items are treated specially */
    2833       49288 :     if (strcmp(te->desc, "ENCODING") == 0 ||
    2834       48904 :         strcmp(te->desc, "STDSTRINGS") == 0 ||
    2835       24356 :         strcmp(te->desc, "SEARCHPATH") == 0)
    2836         576 :         return REQ_SPECIAL;
    2837             : 
    2838             :     /*
    2839             :      * DATABASE and DATABASE PROPERTIES also have a special rule: they are
    2840             :      * restored in createDB mode, and not restored otherwise, independently of
    2841             :      * all else.
    2842             :      */
    2843       48224 :     if (strcmp(te->desc, "DATABASE") == 0 ||
    2844       24060 :         strcmp(te->desc, "DATABASE PROPERTIES") == 0)
    2845             :     {
    2846         136 :         if (ropt->createDB)
    2847         112 :             return REQ_SCHEMA;
    2848             :         else
    2849          24 :             return 0;
    2850             :     }
    2851             : 
    2852             :     /*
    2853             :      * Process exclusions that affect certain classes of TOC entries.
    2854             :      */
    2855             : 
    2856             :     /* If it's an ACL, maybe ignore it */
    2857       24028 :     if (ropt->aclsSkip && _tocEntryIsACL(te))
    2858           0 :         return 0;
    2859             : 
    2860             :     /* If it's a comment, maybe ignore it */
    2861       24028 :     if (ropt->no_comments && strcmp(te->desc, "COMMENT") == 0)
    2862           0 :         return 0;
    2863             : 
    2864             :     /*
    2865             :      * If it's a publication or a table part of a publication, maybe ignore
    2866             :      * it.
    2867             :      */
    2868       24028 :     if (ropt->no_publications &&
    2869           0 :         (strcmp(te->desc, "PUBLICATION") == 0 ||
    2870           0 :          strcmp(te->desc, "PUBLICATION TABLE") == 0))
    2871           0 :         return 0;
    2872             : 
    2873             :     /* If it's a security label, maybe ignore it */
    2874       24028 :     if (ropt->no_security_labels && strcmp(te->desc, "SECURITY LABEL") == 0)
    2875           0 :         return 0;
    2876             : 
    2877             :     /* If it's a subscription, maybe ignore it */
    2878       24028 :     if (ropt->no_subscriptions && strcmp(te->desc, "SUBSCRIPTION") == 0)
    2879           0 :         return 0;
    2880             : 
    2881             :     /* Ignore it if section is not to be dumped/restored */
    2882       24028 :     switch (curSection)
    2883             :     {
    2884             :         case SECTION_PRE_DATA:
    2885       15644 :             if (!(ropt->dumpSections & DUMP_PRE_DATA))
    2886         568 :                 return 0;
    2887       15076 :             break;
    2888             :         case SECTION_DATA:
    2889        3248 :             if (!(ropt->dumpSections & DUMP_DATA))
    2890          84 :                 return 0;
    2891        3164 :             break;
    2892             :         case SECTION_POST_DATA:
    2893        5136 :             if (!(ropt->dumpSections & DUMP_POST_DATA))
    2894         156 :                 return 0;
    2895        4980 :             break;
    2896             :         default:
    2897             :             /* shouldn't get here, really, but ignore it */
    2898           0 :             return 0;
    2899             :     }
    2900             : 
    2901             :     /* Ignore it if rejected by idWanted[] (cf. SortTocFromFile) */
    2902       23220 :     if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
    2903           0 :         return 0;
    2904             : 
    2905             :     /*
    2906             :      * Check options for selective dump/restore.
    2907             :      */
    2908       44064 :     if (strcmp(te->desc, "ACL") == 0 ||
    2909       40612 :         strcmp(te->desc, "COMMENT") == 0 ||
    2910       19768 :         strcmp(te->desc, "SECURITY LABEL") == 0)
    2911             :     {
    2912             :         /* Database properties react to createDB, not selectivity options. */
    2913        6884 :         if (strncmp(te->tag, "DATABASE ", 9) == 0)
    2914             :         {
    2915          58 :             if (!ropt->createDB)
    2916          20 :                 return 0;
    2917             :         }
    2918        6788 :         else if (ropt->schemaNames.head != NULL ||
    2919        6788 :                  ropt->schemaExcludeNames.head != NULL ||
    2920        3394 :                  ropt->selTypes)
    2921             :         {
    2922             :             /*
    2923             :              * In a selective dump/restore, we want to restore these dependent
    2924             :              * TOC entry types only if their parent object is being restored.
    2925             :              * Without selectivity options, we let through everything in the
    2926             :              * archive.  Note there may be such entries with no parent, eg
    2927             :              * non-default ACLs for built-in objects.
    2928             :              *
    2929             :              * This code depends on the parent having been marked already,
    2930             :              * which should be the case; if it isn't, perhaps due to
    2931             :              * SortTocFromFile rearrangement, skipping the dependent entry
    2932             :              * seems prudent anyway.
    2933             :              *
    2934             :              * Ideally we'd handle, eg, table CHECK constraints this way too.
    2935             :              * But it's hard to tell which of their dependencies is the one to
    2936             :              * consult.
    2937             :              */
    2938           0 :             if (te->nDeps != 1 ||
    2939           0 :                 TocIDRequired(AH, te->dependencies[0]) == 0)
    2940           0 :                 return 0;
    2941             :         }
    2942             :     }
    2943             :     else
    2944             :     {
    2945             :         /* Apply selective-restore rules for standalone TOC entries. */
    2946       19768 :         if (ropt->schemaNames.head != NULL)
    2947             :         {
    2948             :             /* If no namespace is specified, it means all. */
    2949           0 :             if (!te->namespace)
    2950           0 :                 return 0;
    2951           0 :             if (!simple_string_list_member(&ropt->schemaNames, te->namespace))
    2952           0 :                 return 0;
    2953             :         }
    2954             : 
    2955       19768 :         if (ropt->schemaExcludeNames.head != NULL &&
    2956           0 :             te->namespace &&
    2957           0 :             simple_string_list_member(&ropt->schemaExcludeNames, te->namespace))
    2958           0 :             return 0;
    2959             : 
    2960       19768 :         if (ropt->selTypes)
    2961             :         {
    2962           0 :             if (strcmp(te->desc, "TABLE") == 0 ||
    2963           0 :                 strcmp(te->desc, "TABLE DATA") == 0 ||
    2964           0 :                 strcmp(te->desc, "VIEW") == 0 ||
    2965           0 :                 strcmp(te->desc, "FOREIGN TABLE") == 0 ||
    2966           0 :                 strcmp(te->desc, "MATERIALIZED VIEW") == 0 ||
    2967           0 :                 strcmp(te->desc, "MATERIALIZED VIEW DATA") == 0 ||
    2968           0 :                 strcmp(te->desc, "SEQUENCE") == 0 ||
    2969           0 :                 strcmp(te->desc, "SEQUENCE SET") == 0)
    2970             :             {
    2971           0 :                 if (!ropt->selTable)
    2972           0 :                     return 0;
    2973           0 :                 if (ropt->tableNames.head != NULL &&
    2974           0 :                     !simple_string_list_member(&ropt->tableNames, te->tag))
    2975           0 :                     return 0;
    2976             :             }
    2977           0 :             else if (strcmp(te->desc, "INDEX") == 0)
    2978             :             {
    2979           0 :                 if (!ropt->selIndex)
    2980           0 :                     return 0;
    2981           0 :                 if (ropt->indexNames.head != NULL &&
    2982           0 :                     !simple_string_list_member(&ropt->indexNames, te->tag))
    2983           0 :                     return 0;
    2984             :             }
    2985           0 :             else if (strcmp(te->desc, "FUNCTION") == 0 ||
    2986           0 :                      strcmp(te->desc, "AGGREGATE") == 0 ||
    2987           0 :                      strcmp(te->desc, "PROCEDURE") == 0)
    2988             :             {
    2989           0 :                 if (!ropt->selFunction)
    2990           0 :                     return 0;
    2991           0 :                 if (ropt->functionNames.head != NULL &&
    2992           0 :                     !simple_string_list_member(&ropt->functionNames, te->tag))
    2993           0 :                     return 0;
    2994             :             }
    2995           0 :             else if (strcmp(te->desc, "TRIGGER") == 0)
    2996             :             {
    2997           0 :                 if (!ropt->selTrigger)
    2998           0 :                     return 0;
    2999           0 :                 if (ropt->triggerNames.head != NULL &&
    3000           0 :                     !simple_string_list_member(&ropt->triggerNames, te->tag))
    3001           0 :                     return 0;
    3002             :             }
    3003             :             else
    3004           0 :                 return 0;
    3005             :         }
    3006             :     }
    3007             : 
    3008             :     /*
    3009             :      * Determine whether the TOC entry contains schema and/or data components,
    3010             :      * and mask off inapplicable REQ bits.  If it had a dataDumper, assume
    3011             :      * it's both schema and data.  Otherwise it's probably schema-only, but
    3012             :      * there are exceptions.
    3013             :      */
    3014       23200 :     if (!te->hadDumper)
    3015             :     {
    3016             :         /*
    3017             :          * Special Case: If 'SEQUENCE SET' or anything to do with BLOBs, then
    3018             :          * it is considered a data entry.  We don't need to check for the
    3019             :          * BLOBS entry or old-style BLOB COMMENTS, because they will have
    3020             :          * hadDumper = true ... but we do need to check new-style BLOB ACLs,
    3021             :          * comments, etc.
    3022             :          */
    3023       40578 :         if (strcmp(te->desc, "SEQUENCE SET") == 0 ||
    3024       39998 :             strcmp(te->desc, "BLOB") == 0 ||
    3025       22338 :             (strcmp(te->desc, "ACL") == 0 &&
    3026       22290 :              strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
    3027       20970 :             (strcmp(te->desc, "COMMENT") == 0 &&
    3028       20904 :              strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
    3029       19848 :             (strcmp(te->desc, "SECURITY LABEL") == 0 &&
    3030           0 :              strncmp(te->tag, "LARGE OBJECT ", 13) == 0))
    3031         694 :             res = res & REQ_DATA;
    3032             :         else
    3033       19848 :             res = res & ~REQ_DATA;
    3034             :     }
    3035             : 
    3036             :     /* If there's no definition command, there's no schema component */
    3037       23200 :     if (!te->defn || !te->defn[0])
    3038        2658 :         res = res & ~REQ_SCHEMA;
    3039             : 
    3040             :     /*
    3041             :      * Special case: <Init> type with <Max OID> tag; this is obsolete and we
    3042             :      * always ignore it.
    3043             :      */
    3044       23200 :     if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
    3045           0 :         return 0;
    3046             : 
    3047             :     /* Mask it if we only want schema */
    3048       23200 :     if (ropt->schemaOnly)
    3049             :     {
    3050             :         /*
    3051             :          * The sequence_data option overrides schemaOnly for SEQUENCE SET.
    3052             :          *
    3053             :          * In binary-upgrade mode, even with schemaOnly set, we do not mask
    3054             :          * out large objects.  (Only large object definitions, comments and
    3055             :          * other metadata should be generated in binary-upgrade mode, not the
    3056             :          * actual data, but that need not concern us here.)
    3057             :          */
    3058        7182 :         if (!(ropt->sequence_data && strcmp(te->desc, "SEQUENCE SET") == 0) &&
    3059        6744 :             !(ropt->binary_upgrade &&
    3060        6388 :               (strcmp(te->desc, "BLOB") == 0 ||
    3061        3324 :                (strcmp(te->desc, "ACL") == 0 &&
    3062        3322 :                 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
    3063        3256 :                (strcmp(te->desc, "COMMENT") == 0 &&
    3064        3250 :                 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
    3065        3182 :                (strcmp(te->desc, "SECURITY LABEL") == 0 &&
    3066           0 :                 strncmp(te->tag, "LARGE OBJECT ", 13) == 0))))
    3067        3530 :             res = res & REQ_SCHEMA;
    3068             :     }
    3069             : 
    3070             :     /* Mask it if we only want data */
    3071       23200 :     if (ropt->dataOnly)
    3072         138 :         res = res & REQ_DATA;
    3073             : 
    3074       23200 :     return res;
    3075             : }
    3076             : 
    3077             : /*
    3078             :  * Identify which pass we should restore this TOC entry in.
    3079             :  *
    3080             :  * See notes with the RestorePass typedef in pg_backup_archiver.h.
    3081             :  */
    3082             : static RestorePass
    3083       51328 : _tocEntryRestorePass(TocEntry *te)
    3084             : {
    3085             :     /* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
    3086       97294 :     if (strcmp(te->desc, "ACL") == 0 ||
    3087       91932 :         strcmp(te->desc, "ACL LANGUAGE") == 0 ||
    3088       45966 :         strcmp(te->desc, "DEFAULT ACL") == 0)
    3089        5694 :         return RESTORE_PASS_ACL;
    3090       45634 :     if (strcmp(te->desc, "MATERIALIZED VIEW DATA") == 0)
    3091         644 :         return RESTORE_PASS_REFRESH;
    3092       44990 :     return RESTORE_PASS_MAIN;
    3093             : }
    3094             : 
    3095             : /*
    3096             :  * Identify TOC entries that are ACLs.
    3097             :  *
    3098             :  * Note: it seems worth duplicating some code here to avoid a hard-wired
    3099             :  * assumption that these are exactly the same entries that we restore during
    3100             :  * the RESTORE_PASS_ACL phase.
    3101             :  */
    3102             : static bool
    3103       19050 : _tocEntryIsACL(TocEntry *te)
    3104             : {
    3105             :     /* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
    3106       36142 :     if (strcmp(te->desc, "ACL") == 0 ||
    3107       34184 :         strcmp(te->desc, "ACL LANGUAGE") == 0 ||
    3108       17092 :         strcmp(te->desc, "DEFAULT ACL") == 0)
    3109        2074 :         return true;
    3110       16976 :     return false;
    3111             : }
    3112             : 
    3113             : /*
    3114             :  * Issue SET commands for parameters that we want to have set the same way
    3115             :  * at all times during execution of a restore script.
    3116             :  */
    3117             : static void
    3118         242 : _doSetFixedOutputState(ArchiveHandle *AH)
    3119             : {
    3120         242 :     RestoreOptions *ropt = AH->public.ropt;
    3121             : 
    3122             :     /*
    3123             :      * Disable timeouts to allow for slow commands, idle parallel workers, etc
    3124             :      */
    3125         242 :     ahprintf(AH, "SET statement_timeout = 0;\n");
    3126         242 :     ahprintf(AH, "SET lock_timeout = 0;\n");
    3127         242 :     ahprintf(AH, "SET idle_in_transaction_session_timeout = 0;\n");
    3128             : 
    3129             :     /* Select the correct character set encoding */
    3130         242 :     ahprintf(AH, "SET client_encoding = '%s';\n",
    3131             :              pg_encoding_to_char(AH->public.encoding));
    3132             : 
    3133             :     /* Select the correct string literal syntax */
    3134         242 :     ahprintf(AH, "SET standard_conforming_strings = %s;\n",
    3135         242 :              AH->public.std_strings ? "on" : "off");
    3136             : 
    3137             :     /* Select the role to be used during restore */
    3138         242 :     if (ropt && ropt->use_role)
    3139           0 :         ahprintf(AH, "SET ROLE %s;\n", fmtId(ropt->use_role));
    3140             : 
    3141             :     /* Select the dump-time search_path */
    3142         242 :     if (AH->public.searchpath)
    3143         242 :         ahprintf(AH, "%s", AH->public.searchpath);
    3144             : 
    3145             :     /* Make sure function checking is disabled */
    3146         242 :     ahprintf(AH, "SET check_function_bodies = false;\n");
    3147             : 
    3148             :     /* Ensure that all valid XML data will be accepted */
    3149         242 :     ahprintf(AH, "SET xmloption = content;\n");
    3150             : 
    3151             :     /* Avoid annoying notices etc */
    3152         242 :     ahprintf(AH, "SET client_min_messages = warning;\n");
    3153         242 :     if (!AH->public.std_strings)
    3154           0 :         ahprintf(AH, "SET escape_string_warning = off;\n");
    3155             : 
    3156             :     /* Adjust row-security state */
    3157         242 :     if (ropt && ropt->enable_row_security)
    3158           0 :         ahprintf(AH, "SET row_security = on;\n");
    3159             :     else
    3160         242 :         ahprintf(AH, "SET row_security = off;\n");
    3161             : 
    3162         242 :     ahprintf(AH, "\n");
    3163         242 : }
    3164             : 
    3165             : /*
    3166             :  * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
    3167             :  * for updating state if appropriate.  If user is NULL or an empty string,
    3168             :  * the specification DEFAULT will be used.
    3169             :  */
    3170             : static void
    3171           2 : _doSetSessionAuth(ArchiveHandle *AH, const char *user)
    3172             : {
    3173           2 :     PQExpBuffer cmd = createPQExpBuffer();
    3174             : 
    3175           2 :     appendPQExpBufferStr(cmd, "SET SESSION AUTHORIZATION ");
    3176             : 
    3177             :     /*
    3178             :      * SQL requires a string literal here.  Might as well be correct.
    3179             :      */
    3180           2 :     if (user && *user)
    3181           2 :         appendStringLiteralAHX(cmd, user, AH);
    3182             :     else
    3183           0 :         appendPQExpBufferStr(cmd, "DEFAULT");
    3184           2 :     appendPQExpBufferChar(cmd, ';');
    3185             : 
    3186           2 :     if (RestoringToDB(AH))
    3187             :     {
    3188             :         PGresult   *res;
    3189             : 
    3190           0 :         res = PQexec(AH->connection, cmd->data);
    3191             : 
    3192           0 :         if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    3193             :             /* NOT warn_or_exit_horribly... use -O instead to skip this. */
    3194           0 :             fatal("could not set session user to \"%s\": %s",
    3195             :                   user, PQerrorMessage(AH->connection));
    3196             : 
    3197           0 :         PQclear(res);
    3198             :     }
    3199             :     else
    3200           2 :         ahprintf(AH, "%s\n\n", cmd->data);
    3201             : 
    3202           2 :     destroyPQExpBuffer(cmd);
    3203           2 : }
    3204             : 
    3205             : 
    3206             : /*
    3207             :  * Issue the commands to connect to the specified database.
    3208             :  *
    3209             :  * If we're currently restoring right into a database, this will
    3210             :  * actually establish a connection. Otherwise it puts a \connect into
    3211             :  * the script output.
    3212             :  *
    3213             :  * NULL dbname implies reconnecting to the current DB (pretty useless).
    3214             :  */
    3215             : static void
    3216          68 : _reconnectToDB(ArchiveHandle *AH, const char *dbname)
    3217             : {
    3218          68 :     if (RestoringToDB(AH))
    3219          26 :         ReconnectToServer(AH, dbname, NULL);
    3220             :     else
    3221             :     {
    3222          42 :         if (dbname)
    3223             :         {
    3224             :             PQExpBufferData connectbuf;
    3225             : 
    3226          42 :             initPQExpBuffer(&connectbuf);
    3227          42 :             appendPsqlMetaConnect(&connectbuf, dbname);
    3228          42 :             ahprintf(AH, "%s\n", connectbuf.data);
    3229          42 :             termPQExpBuffer(&connectbuf);
    3230             :         }
    3231             :         else
    3232           0 :             ahprintf(AH, "%s\n", "\\connect -\n");
    3233             :     }
    3234             : 
    3235             :     /*
    3236             :      * NOTE: currUser keeps track of what the imaginary session user in our
    3237             :      * script is.  It's now effectively reset to the original userID.
    3238             :      */
    3239          68 :     if (AH->currUser)
    3240           0 :         free(AH->currUser);
    3241          68 :     AH->currUser = NULL;
    3242             : 
    3243             :     /* don't assume we still know the output schema, tablespace, etc either */
    3244          68 :     if (AH->currSchema)
    3245           0 :         free(AH->currSchema);
    3246          68 :     AH->currSchema = NULL;
    3247          68 :     if (AH->currTablespace)
    3248           0 :         free(AH->currTablespace);
    3249          68 :     AH->currTablespace = NULL;
    3250             : 
    3251             :     /* re-establish fixed state */
    3252          68 :     _doSetFixedOutputState(AH);
    3253          68 : }
    3254             : 
    3255             : /*
    3256             :  * Become the specified user, and update state to avoid redundant commands
    3257             :  *
    3258             :  * NULL or empty argument is taken to mean restoring the session default
    3259             :  */
    3260             : static void
    3261          60 : _becomeUser(ArchiveHandle *AH, const char *user)
    3262             : {
    3263          60 :     if (!user)
    3264           0 :         user = "";                /* avoid null pointers */
    3265             : 
    3266          60 :     if (AH->currUser && strcmp(AH->currUser, user) == 0)
    3267          58 :         return;                 /* no need to do anything */
    3268             : 
    3269           2 :     _doSetSessionAuth(AH, user);
    3270             : 
    3271             :     /*
    3272             :      * NOTE: currUser keeps track of what the imaginary session user in our
    3273             :      * script is
    3274             :      */
    3275           2 :     if (AH->currUser)
    3276           0 :         free(AH->currUser);
    3277           2 :     AH->currUser = pg_strdup(user);
    3278             : }
    3279             : 
    3280             : /*
    3281             :  * Become the owner of the given TOC entry object.  If
    3282             :  * changes in ownership are not allowed, this doesn't do anything.
    3283             :  */
    3284             : static void
    3285       21652 : _becomeOwner(ArchiveHandle *AH, TocEntry *te)
    3286             : {
    3287       21652 :     RestoreOptions *ropt = AH->public.ropt;
    3288             : 
    3289       21652 :     if (ropt && (ropt->noOwner || !ropt->use_setsessauth))
    3290       21652 :         return;
    3291             : 
    3292           0 :     _becomeUser(AH, te->owner);
    3293             : }
    3294             : 
    3295             : 
    3296             : /*
    3297             :  * Issue the commands to select the specified schema as the current schema
    3298             :  * in the target database.
    3299             :  */
    3300             : static void
    3301       21696 : _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
    3302             : {
    3303             :     PQExpBuffer qry;
    3304             : 
    3305             :     /*
    3306             :      * If there was a SEARCHPATH TOC entry, we're supposed to just stay with
    3307             :      * that search_path rather than switching to entry-specific paths.
    3308             :      * Otherwise, it's an old archive that will not restore correctly unless
    3309             :      * we set the search_path as it's expecting.
    3310             :      */
    3311       21696 :     if (AH->public.searchpath)
    3312       21696 :         return;
    3313             : 
    3314           0 :     if (!schemaName || *schemaName == '\0' ||
    3315           0 :         (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
    3316           0 :         return;                 /* no need to do anything */
    3317             : 
    3318           0 :     qry = createPQExpBuffer();
    3319             : 
    3320           0 :     appendPQExpBuffer(qry, "SET search_path = %s",
    3321             :                       fmtId(schemaName));
    3322           0 :     if (strcmp(schemaName, "pg_catalog") != 0)
    3323           0 :         appendPQExpBufferStr(qry, ", pg_catalog");
    3324             : 
    3325           0 :     if (RestoringToDB(AH))
    3326             :     {
    3327             :         PGresult   *res;
    3328             : 
    3329           0 :         res = PQexec(AH->connection, qry->data);
    3330             : 
    3331           0 :         if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    3332           0 :             warn_or_exit_horribly(AH,
    3333             :                                   "could not set search_path to \"%s\": %s",
    3334           0 :                                   schemaName, PQerrorMessage(AH->connection));
    3335             : 
    3336           0 :         PQclear(res);
    3337             :     }
    3338             :     else
    3339           0 :         ahprintf(AH, "%s;\n\n", qry->data);
    3340             : 
    3341           0 :     if (AH->currSchema)
    3342           0 :         free(AH->currSchema);
    3343           0 :     AH->currSchema = pg_strdup(schemaName);
    3344             : 
    3345           0 :     destroyPQExpBuffer(qry);
    3346             : }
    3347             : 
    3348             : /*
    3349             :  * Issue the commands to select the specified tablespace as the current one
    3350             :  * in the target database.
    3351             :  */
    3352             : static void
    3353       18752 : _selectTablespace(ArchiveHandle *AH, const char *tablespace)
    3354             : {
    3355       18752 :     RestoreOptions *ropt = AH->public.ropt;
    3356             :     PQExpBuffer qry;
    3357             :     const char *want,
    3358             :                *have;
    3359             : 
    3360             :     /* do nothing in --no-tablespaces mode */
    3361       18752 :     if (ropt->noTablespace)
    3362           0 :         return;
    3363             : 
    3364       18752 :     have = AH->currTablespace;
    3365       18752 :     want = tablespace;
    3366             : 
    3367             :     /* no need to do anything for non-tablespace object */
    3368       18752 :     if (!want)
    3369       12884 :         return;
    3370             : 
    3371        5868 :     if (have && strcmp(want, have) == 0)
    3372        5774 :         return;                 /* no need to do anything */
    3373             : 
    3374          94 :     qry = createPQExpBuffer();
    3375             : 
    3376          94 :     if (strcmp(want, "") == 0)
    3377             :     {
    3378             :         /* We want the tablespace to be the database's default */
    3379          94 :         appendPQExpBufferStr(qry, "SET default_tablespace = ''");
    3380             :     }
    3381             :     else
    3382             :     {
    3383             :         /* We want an explicit tablespace */
    3384           0 :         appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
    3385             :     }
    3386             : 
    3387          94 :     if (RestoringToDB(AH))
    3388             :     {
    3389             :         PGresult   *res;
    3390             : 
    3391           6 :         res = PQexec(AH->connection, qry->data);
    3392             : 
    3393           6 :         if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    3394           0 :             warn_or_exit_horribly(AH,
    3395             :                                   "could not set default_tablespace to %s: %s",
    3396           0 :                                   fmtId(want), PQerrorMessage(AH->connection));
    3397             : 
    3398           6 :         PQclear(res);
    3399             :     }
    3400             :     else
    3401          88 :         ahprintf(AH, "%s;\n\n", qry->data);
    3402             : 
    3403          94 :     if (AH->currTablespace)
    3404           0 :         free(AH->currTablespace);
    3405          94 :     AH->currTablespace = pg_strdup(want);
    3406             : 
    3407          94 :     destroyPQExpBuffer(qry);
    3408             : }
    3409             : 
    3410             : /*
    3411             :  * Set the proper default_table_access_method value for the table.
    3412             :  */
    3413             : static void
    3414       18752 : _selectTableAccessMethod(ArchiveHandle *AH, const char *tableam)
    3415             : {
    3416             :     PQExpBuffer cmd;
    3417             :     const char *want,
    3418             :                *have;
    3419             : 
    3420       18752 :     have = AH->currTableAm;
    3421       18752 :     want = tableam;
    3422             : 
    3423       18752 :     if (!want)
    3424       14988 :         return;
    3425             : 
    3426        3764 :     if (have && strcmp(want, have) == 0)
    3427        3480 :         return;
    3428             : 
    3429         284 :     cmd = createPQExpBuffer();
    3430         284 :     appendPQExpBuffer(cmd, "SET default_table_access_method = %s;", fmtId(want));
    3431             : 
    3432         284 :     if (RestoringToDB(AH))
    3433             :     {
    3434             :         PGresult   *res;
    3435             : 
    3436          14 :         res = PQexec(AH->connection, cmd->data);
    3437             : 
    3438          14 :         if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    3439           0 :             warn_or_exit_horribly(AH,
    3440             :                                   "could not set default_table_access_method: %s",
    3441           0 :                                   PQerrorMessage(AH->connection));
    3442             : 
    3443          14 :         PQclear(res);
    3444             :     }
    3445             :     else
    3446         270 :         ahprintf(AH, "%s\n\n", cmd->data);
    3447             : 
    3448         284 :     destroyPQExpBuffer(cmd);
    3449             : 
    3450         284 :     AH->currTableAm = pg_strdup(want);
    3451             : }
    3452             : 
    3453             : /*
    3454             :  * Extract an object description for a TOC entry, and append it to buf.
    3455             :  *
    3456             :  * This is used for ALTER ... OWNER TO.
    3457             :  */
    3458             : static void
    3459        8452 : _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
    3460             : {
    3461        8452 :     const char *type = te->desc;
    3462             : 
    3463             :     /* Use ALTER TABLE for views and sequences */
    3464       16372 :     if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0 ||
    3465        7920 :         strcmp(type, "MATERIALIZED VIEW") == 0)
    3466         854 :         type = "TABLE";
    3467             : 
    3468             :     /* objects that don't require special decoration */
    3469       16866 :     if (strcmp(type, "COLLATION") == 0 ||
    3470       16788 :         strcmp(type, "CONVERSION") == 0 ||
    3471       16612 :         strcmp(type, "DOMAIN") == 0 ||
    3472       11774 :         strcmp(type, "TABLE") == 0 ||
    3473        6650 :         strcmp(type, "TYPE") == 0 ||
    3474        6188 :         strcmp(type, "FOREIGN TABLE") == 0 ||
    3475        6054 :         strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
    3476        5896 :         strcmp(type, "TEXT SEARCH CONFIGURATION") == 0 ||
    3477        5728 :         strcmp(type, "STATISTICS") == 0 ||
    3478             :     /* non-schema-specified objects */
    3479        5572 :         strcmp(type, "DATABASE") == 0 ||
    3480        5482 :         strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
    3481        5306 :         strcmp(type, "SCHEMA") == 0 ||
    3482        5130 :         strcmp(type, "EVENT TRIGGER") == 0 ||
    3483        5048 :         strcmp(type, "FOREIGN DATA WRAPPER") == 0 ||
    3484        4960 :         strcmp(type, "SERVER") == 0 ||
    3485        4840 :         strcmp(type, "PUBLICATION") == 0 ||
    3486        4726 :         strcmp(type, "SUBSCRIPTION") == 0 ||
    3487        2344 :         strcmp(type, "USER MAPPING") == 0)
    3488             :     {
    3489        6108 :         appendPQExpBuffer(buf, "%s ", type);
    3490        6108 :         if (te->namespace && *te->namespace)
    3491        5640 :             appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
    3492        6108 :         appendPQExpBufferStr(buf, fmtId(te->tag));
    3493        6108 :         return;
    3494             :     }
    3495             : 
    3496             :     /* BLOBs just have a name, but it's numeric so must not use fmtId */
    3497        2344 :     if (strcmp(type, "BLOB") == 0)
    3498             :     {
    3499          58 :         appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
    3500          58 :         return;
    3501             :     }
    3502             : 
    3503             :     /*
    3504             :      * These object types require additional decoration.  Fortunately, the
    3505             :      * information needed is exactly what's in the DROP command.
    3506             :      */
    3507        4254 :     if (strcmp(type, "AGGREGATE") == 0 ||
    3508        2392 :         strcmp(type, "FUNCTION") == 0 ||
    3509         730 :         strcmp(type, "OPERATOR") == 0 ||
    3510         480 :         strcmp(type, "OPERATOR CLASS") == 0 ||
    3511         238 :         strcmp(type, "OPERATOR FAMILY") == 0 ||
    3512          64 :         strcmp(type, "PROCEDURE") == 0)
    3513             :     {
    3514             :         /* Chop "DROP " off the front and make a modifiable copy */
    3515        2286 :         char       *first = pg_strdup(te->dropStmt + 5);
    3516             :         char       *last;
    3517             : 
    3518             :         /* point to last character in string */
    3519        2286 :         last = first + strlen(first) - 1;
    3520             : 
    3521             :         /* Strip off any ';' or '\n' at the end */
    3522        9144 :         while (last >= first && (*last == '\n' || *last == ';'))
    3523        4572 :             last--;
    3524        2286 :         *(last + 1) = '\0';
    3525             : 
    3526        2286 :         appendPQExpBufferStr(buf, first);
    3527             : 
    3528        2286 :         free(first);
    3529        2286 :         return;
    3530             :     }
    3531             : 
    3532           0 :     pg_log_warning("don't know how to set owner for object type \"%s\"",
    3533             :                    type);
    3534             : }
    3535             : 
    3536             : /*
    3537             :  * Emit the SQL commands to create the object represented by a TOC entry
    3538             :  *
    3539             :  * This now also includes issuing an ALTER OWNER command to restore the
    3540             :  * object's ownership, if wanted.  But note that the object's permissions
    3541             :  * will remain at default, until the matching ACL TOC entry is restored.
    3542             :  */
    3543             : static void
    3544       18752 : _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData)
    3545             : {
    3546       18752 :     RestoreOptions *ropt = AH->public.ropt;
    3547             : 
    3548             :     /* Select owner, schema, tablespace and default AM as necessary */
    3549       18752 :     _becomeOwner(AH, te);
    3550       18752 :     _selectOutputSchema(AH, te->namespace);
    3551       18752 :     _selectTablespace(AH, te->tablespace);
    3552       18752 :     _selectTableAccessMethod(AH, te->tableam);
    3553             : 
    3554             :     /* Emit header comment for item */
    3555       18752 :     if (!AH->noTocComments)
    3556             :     {
    3557             :         const char *pfx;
    3558             :         char       *sanitized_name;
    3559             :         char       *sanitized_schema;
    3560             :         char       *sanitized_owner;
    3561             : 
    3562       15846 :         if (isData)
    3563        2544 :             pfx = "Data for ";
    3564             :         else
    3565       13302 :             pfx = "";
    3566             : 
    3567       15846 :         ahprintf(AH, "--\n");
    3568       15846 :         if (AH->public.verbose)
    3569             :         {
    3570        1170 :             ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
    3571             :                      te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
    3572        1170 :             if (te->nDeps > 0)
    3573             :             {
    3574             :                 int         i;
    3575             : 
    3576         718 :                 ahprintf(AH, "-- Dependencies:");
    3577        1584 :                 for (i = 0; i < te->nDeps; i++)
    3578         866 :                     ahprintf(AH, " %d", te->dependencies[i]);
    3579         718 :                 ahprintf(AH, "\n");
    3580             :             }
    3581             :         }
    3582             : 
    3583       15846 :         sanitized_name = sanitize_line(te->tag, false);
    3584       15846 :         sanitized_schema = sanitize_line(te->namespace, true);
    3585       15846 :         sanitized_owner = sanitize_line(ropt->noOwner ? NULL : te->owner, true);
    3586             : 
    3587       15846 :         ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
    3588             :                  pfx, sanitized_name, te->desc, sanitized_schema,
    3589             :                  sanitized_owner);
    3590             : 
    3591       15846 :         free(sanitized_name);
    3592       15846 :         free(sanitized_schema);
    3593       15846 :         free(sanitized_owner);
    3594             : 
    3595       15846 :         if (te->tablespace && strlen(te->tablespace) > 0 && !ropt->noTablespace)
    3596             :         {
    3597             :             char       *sanitized_tablespace;
    3598             : 
    3599           0 :             sanitized_tablespace = sanitize_line(te->tablespace, false);
    3600           0 :             ahprintf(AH, "; Tablespace: %s", sanitized_tablespace);
    3601           0 :             free(sanitized_tablespace);
    3602             :         }
    3603       15846 :         ahprintf(AH, "\n");
    3604             : 
    3605       15846 :         if (AH->PrintExtraTocPtr != NULL)
    3606        2394 :             AH->PrintExtraTocPtr(AH, te);
    3607       15846 :         ahprintf(AH, "--\n\n");
    3608             :     }
    3609             : 
    3610             :     /*
    3611             :      * Actually print the definition.
    3612             :      *
    3613             :      * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
    3614             :      * versions put into CREATE SCHEMA.  We have to do this when --no-owner
    3615             :      * mode is selected.  This is ugly, but I see no other good way ...
    3616             :      */
    3617       18752 :     if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
    3618             :     {
    3619           4 :         ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
    3620             :     }
    3621             :     else
    3622             :     {
    3623       18748 :         if (te->defn && strlen(te->defn) > 0)
    3624       16200 :             ahprintf(AH, "%s\n\n", te->defn);
    3625             :     }
    3626             : 
    3627             :     /*
    3628             :      * If we aren't using SET SESSION AUTH to determine ownership, we must
    3629             :      * instead issue an ALTER OWNER command.  We assume that anything without
    3630             :      * a DROP command is not a separately ownable object.  All the categories
    3631             :      * with DROP commands must appear in one list or the other.
    3632             :      */
    3633       37100 :     if (!ropt->noOwner && !ropt->use_setsessauth &&
    3634       53446 :         te->owner && strlen(te->owner) > 0 &&
    3635       28972 :         te->dropStmt && strlen(te->dropStmt) > 0)
    3636             :     {
    3637       22358 :         if (strcmp(te->desc, "AGGREGATE") == 0 ||
    3638       21982 :             strcmp(te->desc, "BLOB") == 0 ||
    3639       21886 :             strcmp(te->desc, "COLLATION") == 0 ||
    3640       21808 :             strcmp(te->desc, "CONVERSION") == 0 ||
    3641       21716 :             strcmp(te->desc, "DATABASE") == 0 ||
    3642       21528 :             strcmp(te->desc, "DOMAIN") == 0 ||
    3643       19848 :             strcmp(te->desc, "FUNCTION") == 0 ||
    3644       18186 :             strcmp(te->desc, "OPERATOR") == 0 ||
    3645       17936 :             strcmp(te->desc, "OPERATOR CLASS") == 0 ||
    3646       17694 :             strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
    3647       17520 :             strcmp(te->desc, "PROCEDURE") == 0 ||
    3648       17418 :             strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
    3649       17242 :             strcmp(te->desc, "SCHEMA") == 0 ||
    3650       17066 :             strcmp(te->desc, "EVENT TRIGGER") == 0 ||
    3651       13180 :             strcmp(te->desc, "TABLE") == 0 ||
    3652        8910 :             strcmp(te->desc, "TYPE") == 0 ||
    3653        8190 :             strcmp(te->desc, "VIEW") == 0 ||
    3654        7570 :             strcmp(te->desc, "MATERIALIZED VIEW") == 0 ||
    3655        7014 :             strcmp(te->desc, "SEQUENCE") == 0 ||
    3656        6740 :             strcmp(te->desc, "FOREIGN TABLE") == 0 ||
    3657        6606 :             strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
    3658        6448 :             strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0 ||
    3659        6340 :             strcmp(te->desc, "FOREIGN DATA WRAPPER") == 0 ||
    3660        6252 :             strcmp(te->desc, "SERVER") == 0 ||
    3661        6104 :             strcmp(te->desc, "STATISTICS") == 0 ||
    3662        5924 :             strcmp(te->desc, "PUBLICATION") == 0 ||
    3663        2924 :             strcmp(te->desc, "SUBSCRIPTION") == 0)
    3664        8452 :         {
    3665        8452 :             PQExpBuffer temp = createPQExpBuffer();
    3666             : 
    3667        8452 :             appendPQExpBufferStr(temp, "ALTER ");
    3668        8452 :             _getObjectDescription(temp, te, AH);
    3669        8452 :             appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
    3670        8452 :             ahprintf(AH, "%s\n\n", temp->data);
    3671        8452 :             destroyPQExpBuffer(temp);
    3672             :         }
    3673        5772 :         else if (strcmp(te->desc, "CAST") == 0 ||
    3674        5742 :                  strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
    3675        4972 :                  strcmp(te->desc, "CONSTRAINT") == 0 ||
    3676        4230 :                  strcmp(te->desc, "DATABASE PROPERTIES") == 0 ||
    3677        4062 :                  strcmp(te->desc, "DEFAULT") == 0 ||
    3678        3726 :                  strcmp(te->desc, "FK CONSTRAINT") == 0 ||
    3679        2708 :                  strcmp(te->desc, "INDEX") == 0 ||
    3680        1644 :                  strcmp(te->desc, "RULE") == 0 ||
    3681        1046 :                  strcmp(te->desc, "TRIGGER") == 0 ||
    3682         664 :                  strcmp(te->desc, "ROW SECURITY") == 0 ||
    3683         370 :                  strcmp(te->desc, "POLICY") == 0 ||
    3684          38 :                  strcmp(te->desc, "USER MAPPING") == 0)
    3685             :         {
    3686             :             /* these object types don't have separate owners */
    3687             :         }
    3688             :         else
    3689             :         {
    3690           0 :             pg_log_warning("don't know how to set owner for object type \"%s\"",
    3691             :                            te->desc);
    3692             :         }
    3693             :     }
    3694             : 
    3695             :     /*
    3696             :      * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
    3697             :      * commands, so we can no longer assume we know the current auth setting.
    3698             :      */
    3699       18752 :     if (_tocEntryIsACL(te))
    3700             :     {
    3701        2074 :         if (AH->currUser)
    3702           2 :             free(AH->currUser);
    3703        2074 :         AH->currUser = NULL;
    3704             :     }
    3705       18752 : }
    3706             : 
    3707             : /*
    3708             :  * Sanitize a string to be included in an SQL comment or TOC listing, by
    3709             :  * replacing any newlines with spaces.  This ensures each logical output line
    3710             :  * is in fact one physical output line, to prevent corruption of the dump
    3711             :  * (which could, in the worst case, present an SQL injection vulnerability
    3712             :  * if someone were to incautiously load a dump containing objects with
    3713             :  * maliciously crafted names).
    3714             :  *
    3715             :  * The result is a freshly malloc'd string.  If the input string is NULL,
    3716             :  * return a malloc'ed empty string, unless want_hyphen, in which case return a
    3717             :  * malloc'ed hyphen.
    3718             :  *
    3719             :  * Note that we currently don't bother to quote names, meaning that the name
    3720             :  * fields aren't automatically parseable.  "pg_restore -L" doesn't care because
    3721             :  * it only examines the dumpId field, but someday we might want to try harder.
    3722             :  */
    3723             : static char *
    3724       47538 : sanitize_line(const char *str, bool want_hyphen)
    3725             : {
    3726             :     char       *result;
    3727             :     char       *s;
    3728             : 
    3729       47538 :     if (!str)
    3730        2350 :         return pg_strdup(want_hyphen ? "-" : "");
    3731             : 
    3732       45188 :     result = pg_strdup(str);
    3733             : 
    3734      558580 :     for (s = result; *s != '\0'; s++)
    3735             :     {
    3736      513392 :         if (*s == '\n' || *s == '\r')
    3737           0 :             *s = ' ';
    3738             :     }
    3739             : 
    3740       45188 :     return result;
    3741             : }
    3742             : 
    3743             : /*
    3744             :  * Write the file header for a custom-format archive
    3745             :  */
    3746             : void
    3747          34 : WriteHead(ArchiveHandle *AH)
    3748             : {
    3749             :     struct tm   crtm;
    3750             : 
    3751          34 :     AH->WriteBufPtr(AH, "PGDMP", 5);   /* Magic code */
    3752          34 :     AH->WriteBytePtr(AH, ARCHIVE_MAJOR(AH->version));
    3753          34 :     AH->WriteBytePtr(AH, ARCHIVE_MINOR(AH->version));
    3754          34 :     AH->WriteBytePtr(AH, ARCHIVE_REV(AH->version));
    3755          34 :     AH->WriteBytePtr(AH, AH->intSize);
    3756          34 :     AH->WriteBytePtr(AH, AH->offSize);
    3757          34 :     AH->WriteBytePtr(AH, AH->format);
    3758          34 :     WriteInt(AH, AH->compression);
    3759          34 :     crtm = *localtime(&AH->createDate);
    3760          34 :     WriteInt(AH, crtm.tm_sec);
    3761          34 :     WriteInt(AH, crtm.tm_min);
    3762          34 :     WriteInt(AH, crtm.tm_hour);
    3763          34 :     WriteInt(AH, crtm.tm_mday);
    3764          34 :     WriteInt(AH, crtm.tm_mon);
    3765          34 :     WriteInt(AH, crtm.tm_year);
    3766          34 :     WriteInt(AH, crtm.tm_isdst);
    3767          34 :     WriteStr(AH, PQdb(AH->connection));
    3768          34 :     WriteStr(AH, AH->public.remoteVersionStr);
    3769          34 :     WriteStr(AH, PG_VERSION);
    3770          34 : }
    3771             : 
    3772             : void
    3773          36 : ReadHead(ArchiveHandle *AH)
    3774             : {
    3775             :     char        tmpMag[7];
    3776             :     int         fmt;
    3777             :     struct tm   crtm;
    3778             : 
    3779             :     /*
    3780             :      * If we haven't already read the header, do so.
    3781             :      *
    3782             :      * NB: this code must agree with _discoverArchiveFormat().  Maybe find a
    3783             :      * way to unify the cases?
    3784             :      */
    3785          36 :     if (!AH->readHeader)
    3786             :     {
    3787             :         char        vmaj,
    3788             :                     vmin,
    3789             :                     vrev;
    3790             : 
    3791          36 :         AH->ReadBufPtr(AH, tmpMag, 5);
    3792             : 
    3793          36 :         if (strncmp(tmpMag, "PGDMP", 5) != 0)
    3794           0 :             fatal("did not find magic string in file header");
    3795             : 
    3796          36 :         vmaj = AH->ReadBytePtr(AH);
    3797          36 :         vmin = AH->ReadBytePtr(AH);
    3798             : 
    3799          36 :         if (vmaj > 1 || (vmaj == 1 && vmin > 0))  /* Version > 1.0 */
    3800          36 :             vrev = AH->ReadBytePtr(AH);
    3801             :         else
    3802           0 :             vrev = 0;
    3803             : 
    3804          36 :         AH->version = MAKE_ARCHIVE_VERSION(vmaj, vmin, vrev);
    3805             : 
    3806          36 :         if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
    3807           0 :             fatal("unsupported version (%d.%d) in file header",
    3808             :                   vmaj, vmin);
    3809             : 
    3810          36 :         AH->intSize = AH->ReadBytePtr(AH);
    3811          36 :         if (AH->intSize > 32)
    3812           0 :             fatal("sanity check on integer size (%lu) failed",
    3813             :                   (unsigned long) AH->intSize);
    3814             : 
    3815          36 :         if (AH->intSize > sizeof(int))
    3816           0 :             pg_log_warning("archive was made on a machine with larger integers, some operations might fail");
    3817             : 
    3818          36 :         if (AH->version >= K_VERS_1_7)
    3819          36 :             AH->offSize = AH->ReadBytePtr(AH);
    3820             :         else
    3821           0 :             AH->offSize = AH->intSize;
    3822             : 
    3823          36 :         fmt = AH->ReadBytePtr(AH);
    3824             : 
    3825          36 :         if (AH->format != fmt)
    3826           0 :             fatal("expected format (%d) differs from format found in file (%d)",
    3827             :                   AH->format, fmt);
    3828             :     }
    3829             : 
    3830          36 :     if (AH->version >= K_VERS_1_2)
    3831             :     {
    3832          36 :         if (AH->version < K_VERS_1_4)
    3833           0 :             AH->compression = AH->ReadBytePtr(AH);
    3834             :         else
    3835          36 :             AH->compression = ReadInt(AH);
    3836             :     }
    3837             :     else
    3838           0 :         AH->compression = Z_DEFAULT_COMPRESSION;
    3839             : 
    3840             : #ifndef HAVE_LIBZ
    3841             :     if (AH->compression != 0)
    3842             :         pg_log_warning("archive is compressed, but this installation does not support compression -- no data will be available");
    3843             : #endif
    3844             : 
    3845          36 :     if (AH->version >= K_VERS_1_4)
    3846             :     {
    3847          36 :         crtm.tm_sec = ReadInt(AH);
    3848          36 :         crtm.tm_min = ReadInt(AH);
    3849          36 :         crtm.tm_hour = ReadInt(AH);
    3850          36 :         crtm.tm_mday = ReadInt(AH);
    3851          36 :         crtm.tm_mon = ReadInt(AH);
    3852          36 :         crtm.tm_year = ReadInt(AH);
    3853          36 :         crtm.tm_isdst = ReadInt(AH);
    3854             : 
    3855          36 :         AH->archdbname = ReadStr(AH);
    3856             : 
    3857          36 :         AH->createDate = mktime(&crtm);
    3858             : 
    3859          36 :         if (AH->createDate == (time_t) -1)
    3860           0 :             pg_log_warning("invalid creation date in header");
    3861             :     }
    3862             : 
    3863          36 :     if (AH->version >= K_VERS_1_10)
    3864             :     {
    3865          36 :         AH->archiveRemoteVersion = ReadStr(AH);
    3866          36 :         AH->archiveDumpVersion = ReadStr(AH);
    3867             :     }
    3868          36 : }
    3869             : 
    3870             : 
    3871             : /*
    3872             :  * checkSeek
    3873             :  *    check to see if ftell/fseek can be performed.
    3874             :  */
    3875             : bool
    3876          44 : checkSeek(FILE *fp)
    3877             : {
    3878             :     pgoff_t     tpos;
    3879             : 
    3880             :     /*
    3881             :      * If pgoff_t is wider than long, we must have "real" fseeko and not an
    3882             :      * emulation using fseek.  Otherwise report no seek capability.
    3883             :      */
    3884             : #ifndef HAVE_FSEEKO
    3885             :     if (sizeof(pgoff_t) > sizeof(long))
    3886             :         return false;
    3887             : #endif
    3888             : 
    3889             :     /* Check that ftello works on this file */
    3890          44 :     tpos = ftello(fp);
    3891          44 :     if (tpos < 0)
    3892           0 :         return false;
    3893             : 
    3894             :     /*
    3895             :      * Check that fseeko(SEEK_SET) works, too.  NB: we used to try to test
    3896             :      * this with fseeko(fp, 0, SEEK_CUR).  But some platforms treat that as a
    3897             :      * successful no-op even on files that are otherwise unseekable.
    3898             :      */
    3899          44 :     if (fseeko(fp, tpos, SEEK_SET) != 0)
    3900           0 :         return false;
    3901             : 
    3902          44 :     return true;
    3903             : }
    3904             : 
    3905             : 
    3906             : /*
    3907             :  * dumpTimestamp
    3908             :  */
    3909             : static void
    3910          56 : dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
    3911             : {
    3912             :     char        buf[64];
    3913             : 
    3914          56 :     if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&tim)) != 0)
    3915          56 :         ahprintf(AH, "-- %s %s\n\n", msg, buf);
    3916          56 : }
    3917             : 
    3918             : /*
    3919             :  * Main engine for parallel restore.
    3920             :  *
    3921             :  * Parallel restore is done in three phases.  In this first phase,
    3922             :  * we'll process all SECTION_PRE_DATA TOC entries that are allowed to be
    3923             :  * processed in the RESTORE_PASS_MAIN pass.  (In practice, that's all
    3924             :  * PRE_DATA items other than ACLs.)  Entries we can't process now are
    3925             :  * added to the pending_list for later phases to deal with.
    3926             :  */
    3927             : static void
    3928           4 : restore_toc_entries_prefork(ArchiveHandle *AH, TocEntry *pending_list)
    3929             : {
    3930             :     bool        skipped_some;
    3931             :     TocEntry   *next_work_item;
    3932             : 
    3933           4 :     pg_log_debug("entering restore_toc_entries_prefork");
    3934             : 
    3935             :     /* Adjust dependency information */
    3936           4 :     fix_dependencies(AH);
    3937             : 
    3938             :     /*
    3939             :      * Do all the early stuff in a single connection in the parent. There's no
    3940             :      * great point in running it in parallel, in fact it will actually run
    3941             :      * faster in a single connection because we avoid all the connection and
    3942             :      * setup overhead.  Also, pre-9.2 pg_dump versions were not very good
    3943             :      * about showing all the dependencies of SECTION_PRE_DATA items, so we do
    3944             :      * not risk trying to process them out-of-order.
    3945             :      *
    3946             :      * Stuff that we can't do immediately gets added to the pending_list.
    3947             :      * Note: we don't yet filter out entries that aren't going to be restored.
    3948             :      * They might participate in dependency chains connecting entries that
    3949             :      * should be restored, so we treat them as live until we actually process
    3950             :      * them.
    3951             :      *
    3952             :      * Note: as of 9.2, it should be guaranteed that all PRE_DATA items appear
    3953             :      * before DATA items, and all DATA items before POST_DATA items.  That is
    3954             :      * not certain to be true in older archives, though, and in any case use
    3955             :      * of a list file would destroy that ordering (cf. SortTocFromFile).  So
    3956             :      * this loop cannot assume that it holds.
    3957             :      */
    3958           4 :     AH->restorePass = RESTORE_PASS_MAIN;
    3959           4 :     skipped_some = false;
    3960          28 :     for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
    3961             :     {
    3962          24 :         bool        do_now = true;
    3963             : 
    3964          24 :         if (next_work_item->section != SECTION_PRE_DATA)
    3965             :         {
    3966             :             /* DATA and POST_DATA items are just ignored for now */
    3967           4 :             if (next_work_item->section == SECTION_DATA ||
    3968           0 :                 next_work_item->section == SECTION_POST_DATA)
    3969             :             {
    3970           4 :                 do_now = false;
    3971           4 :                 skipped_some = true;
    3972             :             }
    3973             :             else
    3974             :             {
    3975             :                 /*
    3976             :                  * SECTION_NONE items, such as comments, can be processed now
    3977             :                  * if we are still in the PRE_DATA part of the archive.  Once
    3978             :                  * we've skipped any items, we have to consider whether the
    3979             :                  * comment's dependencies are satisfied, so skip it for now.
    3980             :                  */
    3981           0 :                 if (skipped_some)
    3982           0 :                     do_now = false;
    3983             :             }
    3984             :         }
    3985             : 
    3986             :         /*
    3987             :          * Also skip items that need to be forced into later passes.  We need
    3988             :          * not set skipped_some in this case, since by assumption no main-pass
    3989             :          * items could depend on these.
    3990             :          */
    3991          24 :         if (_tocEntryRestorePass(next_work_item) != RESTORE_PASS_MAIN)
    3992           0 :             do_now = false;
    3993             : 
    3994          24 :         if (do_now)
    3995             :         {
    3996             :             /* OK, restore the item and update its dependencies */
    3997          20 :             pg_log_info("processing item %d %s %s",
    3998             :                         next_work_item->dumpId,
    3999             :                         next_work_item->desc, next_work_item->tag);
    4000             : 
    4001          20 :             (void) restore_toc_entry(AH, next_work_item, false);
    4002             : 
    4003             :             /* Reduce dependencies, but don't move anything to ready_list */
    4004          20 :             reduce_dependencies(AH, next_work_item, NULL);
    4005             :         }
    4006             :         else
    4007             :         {
    4008             :             /* Nope, so add it to pending_list */
    4009           4 :             pending_list_append(pending_list, next_work_item);
    4010             :         }
    4011             :     }
    4012             : 
    4013             :     /*
    4014             :      * Now close parent connection in prep for parallel steps.  We do this
    4015             :      * mainly to ensure that we don't exceed the specified number of parallel
    4016             :      * connections.
    4017             :      */
    4018           4 :     DisconnectDatabase(&AH->public);
    4019             : 
    4020             :     /* blow away any transient state from the old connection */
    4021           4 :     if (AH->currUser)
    4022           0 :         free(AH->currUser);
    4023           4 :     AH->currUser = NULL;
    4024           4 :     if (AH->currSchema)
    4025           0 :         free(AH->currSchema);
    4026           4 :     AH->currSchema = NULL;
    4027           4 :     if (AH->currTablespace)
    4028           4 :         free(AH->currTablespace);
    4029           4 :     AH->currTablespace = NULL;
    4030           4 :     if (AH->currTableAm)
    4031           4 :         free(AH->currTableAm);
    4032           4 :     AH->currTableAm = NULL;
    4033           4 : }
    4034             : 
    4035             : /*
    4036             :  * Main engine for parallel restore.
    4037             :  *
    4038             :  * Parallel restore is done in three phases.  In this second phase,
    4039             :  * we process entries by dispatching them to parallel worker children
    4040             :  * (processes on Unix, threads on Windows), each of which connects
    4041             :  * separately to the database.  Inter-entry dependencies are respected,
    4042             :  * and so is the RestorePass multi-pass structure.  When we can no longer
    4043             :  * make any entries ready to process, we exit.  Normally, there will be
    4044             :  * nothing left to do; but if there is, the third phase will mop up.
    4045             :  */
    4046             : static void
    4047           4 : restore_toc_entries_parallel(ArchiveHandle *AH, ParallelState *pstate,
    4048             :                              TocEntry *pending_list)
    4049             : {
    4050             :     ParallelReadyList ready_list;
    4051             :     TocEntry   *next_work_item;
    4052             : 
    4053           4 :     pg_log_debug("entering restore_toc_entries_parallel");
    4054             : 
    4055             :     /* Set up ready_list with enough room for all known TocEntrys */
    4056           4 :     ready_list_init(&ready_list, AH->tocCount);
    4057             : 
    4058             :     /*
    4059             :      * The pending_list contains all items that we need to restore.  Move all
    4060             :      * items that are available to process immediately into the ready_list.
    4061             :      * After this setup, the pending list is everything that needs to be done
    4062             :      * but is blocked by one or more dependencies, while the ready list
    4063             :      * contains items that have no remaining dependencies and are OK to
    4064             :      * process in the current restore pass.
    4065             :      */
    4066           4 :     AH->restorePass = RESTORE_PASS_MAIN;
    4067           4 :     move_to_ready_list(pending_list, &ready_list, AH->restorePass);
    4068             : 
    4069             :     /*
    4070             :      * main parent loop
    4071             :      *
    4072             :      * Keep going until there is no worker still running AND there is no work
    4073             :      * left to be done.  Note invariant: at top of loop, there should always
    4074             :      * be at least one worker available to dispatch a job to.
    4075             :      */
    4076           4 :     pg_log_info("entering main parallel loop");
    4077             : 
    4078             :     for (;;)
    4079             :     {
    4080             :         /* Look for an item ready to be dispatched to a worker */
    4081          36 :         next_work_item = pop_next_work_item(AH, &ready_list, pstate);
    4082          20 :         if (next_work_item != NULL)
    4083             :         {
    4084             :             /* If not to be restored, don't waste time launching a worker */
    4085           4 :             if ((next_work_item->reqs & (REQ_SCHEMA | REQ_DATA)) == 0)
    4086             :             {
    4087           0 :                 pg_log_info("skipping item %d %s %s",
    4088             :                             next_work_item->dumpId,
    4089             :                             next_work_item->desc, next_work_item->tag);
    4090             :                 /* Update its dependencies as though we'd completed it */
    4091           0 :                 reduce_dependencies(AH, next_work_item, &ready_list);
    4092             :                 /* Loop around to see if anything else can be dispatched */
    4093           0 :                 continue;
    4094             :             }
    4095             : 
    4096           4 :             pg_log_info("launching item %d %s %s",
    4097             :                         next_work_item->dumpId,
    4098             :                         next_work_item->desc, next_work_item->tag);
    4099             : 
    4100             :             /* Dispatch to some worker */
    4101           4 :             DispatchJobForTocEntry(AH, pstate, next_work_item, ACT_RESTORE,
    4102             :                                    mark_restore_job_done, &ready_list);
    4103             :         }
    4104          16 :         else if (IsEveryWorkerIdle(pstate))
    4105             :         {
    4106             :             /*
    4107             :              * Nothing is ready and no worker is running, so we're done with
    4108             :              * the current pass or maybe with the whole process.
    4109             :              */
    4110          12 :             if (AH->restorePass == RESTORE_PASS_LAST)
    4111           4 :                 break;          /* No more parallel processing is possible */
    4112             : 
    4113             :             /* Advance to next restore pass */
    4114           8 :             AH->restorePass++;
    4115             :             /* That probably allows some stuff to be made ready */
    4116           8 :             move_to_ready_list(pending_list, &ready_list, AH->restorePass);
    4117             :             /* Loop around to see if anything's now ready */
    4118           8 :             continue;
    4119             :         }
    4120             :         else
    4121             :         {
    4122             :             /*
    4123             :              * We have nothing ready, but at least one child is working, so
    4124             :              * wait for some subjob to finish.
    4125             :              */
    4126             :         }
    4127             : 
    4128             :         /*
    4129             :          * Before dispatching another job, check to see if anything has
    4130             :          * finished.  We should check every time through the loop so as to
    4131             :          * reduce dependencies as soon as possible.  If we were unable to
    4132             :          * dispatch any job this time through, wait until some worker finishes
    4133             :          * (and, hopefully, unblocks some pending item).  If we did dispatch
    4134             :          * something, continue as soon as there's at least one idle worker.
    4135             :          * Note that in either case, there's guaranteed to be at least one
    4136             :          * idle worker when we return to the top of the loop.  This ensures we
    4137             :          * won't block inside DispatchJobForTocEntry, which would be
    4138             :          * undesirable: we'd rather postpone dispatching until we see what's
    4139             :          * been unblocked by finished jobs.
    4140             :          */
    4141           8 :         WaitForWorkers(AH, pstate,
    4142             :                        next_work_item ? WFW_ONE_IDLE : WFW_GOT_STATUS);
    4143             :     }
    4144             : 
    4145             :     /* There should now be nothing in ready_list. */
    4146             :     Assert(ready_list.first_te > ready_list.last_te);
    4147             : 
    4148           4 :     ready_list_free(&ready_list);
    4149             : 
    4150           4 :     pg_log_info("finished main parallel loop");
    4151           4 : }
    4152             : 
    4153             : /*
    4154             :  * Main engine for parallel restore.
    4155             :  *
    4156             :  * Parallel restore is done in three phases.  In this third phase,
    4157             :  * we mop up any remaining TOC entries by processing them serially.
    4158             :  * This phase normally should have nothing to do, but if we've somehow
    4159             :  * gotten stuck due to circular dependencies or some such, this provides
    4160             :  * at least some chance of completing the restore successfully.
    4161             :  */
    4162             : static void
    4163           4 : restore_toc_entries_postfork(ArchiveHandle *AH, TocEntry *pending_list)
    4164             : {
    4165           4 :     RestoreOptions *ropt = AH->public.ropt;
    4166             :     TocEntry   *te;
    4167             : 
    4168           4 :     pg_log_debug("entering restore_toc_entries_postfork");
    4169             : 
    4170             :     /*
    4171             :      * Now reconnect the single parent connection.
    4172             :      */
    4173           8 :     ConnectDatabase((Archive *) AH, ropt->dbname,
    4174           4 :                     ropt->pghost, ropt->pgport, ropt->username,
    4175             :                     ropt->promptPassword);
    4176             : 
    4177             :     /* re-establish fixed state */
    4178           4 :     _doSetFixedOutputState(AH);
    4179             : 
    4180             :     /*
    4181             :      * Make sure there is no work left due to, say, circular dependencies, or
    4182             :      * some other pathological condition.  If so, do it in the single parent
    4183             :      * connection.  We don't sweat about RestorePass ordering; it's likely we
    4184             :      * already violated that.
    4185             :      */
    4186           4 :     for (te = pending_list->pending_next; te != pending_list; te = te->pending_next)
    4187             :     {
    4188           0 :         pg_log_info("processing missed item %d %s %s",
    4189             :                     te->dumpId, te->desc, te->tag);
    4190           0 :         (void) restore_toc_entry(AH, te, false);
    4191             :     }
    4192           4 : }
    4193             : 
    4194             : /*
    4195             :  * Check if te1 has an exclusive lock requirement for an item that te2 also
    4196             :  * requires, whether or not te2's requirement is for an exclusive lock.
    4197             :  */
    4198             : static bool
    4199           0 : has_lock_conflicts(TocEntry *te1, TocEntry *te2)
    4200             : {
    4201             :     int         j,
    4202             :                 k;
    4203             : 
    4204           0 :     for (j = 0; j < te1->nLockDeps; j++)
    4205             :     {
    4206           0 :         for (k = 0; k < te2->nDeps; k++)
    4207             :         {
    4208           0 :             if (te1->lockDeps[j] == te2->dependencies[k])
    4209           0 :                 return true;
    4210             :         }
    4211             :     }
    4212           0 :     return false;
    4213             : }
    4214             : 
    4215             : 
    4216             : /*
    4217             :  * Initialize the header of the pending-items list.
    4218             :  *
    4219             :  * This is a circular list with a dummy TocEntry as header, just like the
    4220             :  * main TOC list; but we use separate list links so that an entry can be in
    4221             :  * the main TOC list as well as in the pending list.
    4222             :  */
    4223             : static void
    4224           4 : pending_list_header_init(TocEntry *l)
    4225             : {
    4226           4 :     l->pending_prev = l->pending_next = l;
    4227           4 : }
    4228             : 
    4229             : /* Append te to the end of the pending-list headed by l */
    4230             : static void
    4231           4 : pending_list_append(TocEntry *l, TocEntry *te)
    4232             : {
    4233           4 :     te->pending_prev = l->pending_prev;
    4234           4 :     l->pending_prev->pending_next = te;
    4235           4 :     l->pending_prev = te;
    4236           4 :     te->pending_next = l;
    4237           4 : }
    4238             : 
    4239             : /* Remove te from the pending-list */
    4240             : static void
    4241           4 : pending_list_remove(TocEntry *te)
    4242             : {
    4243           4 :     te->pending_prev->pending_next = te->pending_next;
    4244           4 :     te->pending_next->pending_prev = te->pending_prev;
    4245           4 :     te->pending_prev = NULL;
    4246           4 :     te->pending_next = NULL;
    4247           4 : }
    4248             : 
    4249             : 
    4250             : /*
    4251             :  * Initialize the ready_list with enough room for up to tocCount entries.
    4252             :  */
    4253             : static void
    4254           4 : ready_list_init(ParallelReadyList *ready_list, int tocCount)
    4255             : {
    4256           4 :     ready_list->tes = (TocEntry **)
    4257           4 :         pg_malloc(tocCount * sizeof(TocEntry *));
    4258           4 :     ready_list->first_te = 0;
    4259           4 :     ready_list->last_te = -1;
    4260           4 :     ready_list->sorted = false;
    4261           4 : }
    4262             : 
    4263             : /*
    4264             :  * Free storage for a ready_list.
    4265             :  */
    4266             : static void
    4267           4 : ready_list_free(ParallelReadyList *ready_list)
    4268             : {
    4269           4 :     pg_free(ready_list->tes);
    4270           4 : }
    4271             : 
    4272             : /* Add te to the ready_list */
    4273             : static void
    4274           4 : ready_list_insert(ParallelReadyList *ready_list, TocEntry *te)
    4275             : {
    4276           4 :     ready_list->tes[++ready_list->last_te] = te;
    4277             :     /* List is (probably) not sorted anymore. */
    4278           4 :     ready_list->sorted = false;
    4279           4 : }
    4280             : 
    4281             : /* Remove the i'th entry in the ready_list */
    4282             : static void
    4283           4 : ready_list_remove(ParallelReadyList *ready_list, int i)
    4284             : {
    4285           4 :     int         f = ready_list->first_te;
    4286             : 
    4287             :     Assert(i >= f && i <= ready_list->last_te);
    4288             : 
    4289             :     /*
    4290             :      * In the typical case where the item to be removed is the first ready
    4291             :      * entry, we need only increment first_te to remove it.  Otherwise, move
    4292             :      * the entries before it to compact the list.  (This preserves sortedness,
    4293             :      * if any.)  We could alternatively move the entries after i, but there
    4294             :      * are typically many more of those.
    4295             :      */
    4296           4 :     if (i > f)
    4297             :     {
    4298           0 :         TocEntry  **first_te_ptr = &ready_list->tes[f];
    4299             : 
    4300           0 :         memmove(first_te_ptr + 1, first_te_ptr, (i - f) * sizeof(TocEntry *));
    4301             :     }
    4302           4 :     ready_list->first_te++;
    4303           4 : }
    4304             : 
    4305             : /* Sort the ready_list into the desired order */
    4306             : static void
    4307          20 : ready_list_sort(ParallelReadyList *ready_list)
    4308             : {
    4309          20 :     if (!ready_list->sorted)
    4310             :     {
    4311           4 :         int         n = ready_list->last_te - ready_list->first_te + 1;
    4312             : 
    4313           4 :         if (n > 1)
    4314           0 :             qsort(ready_list->tes + ready_list->first_te, n,
    4315             :                   sizeof(TocEntry *),
    4316             :                   TocEntrySizeCompare);
    4317           4 :         ready_list->sorted = true;
    4318             :     }
    4319          20 : }
    4320             : 
    4321             : /* qsort comparator for sorting TocEntries by dataLength */
    4322             : static int
    4323         116 : TocEntrySizeCompare(const void *p1, const void *p2)
    4324             : {
    4325         116 :     const TocEntry *te1 = *(const TocEntry *const *) p1;
    4326         116 :     const TocEntry *te2 = *(const TocEntry *const *) p2;
    4327             : 
    4328             :     /* Sort by decreasing dataLength */
    4329         116 :     if (te1->dataLength > te2->dataLength)
    4330           8 :         return -1;
    4331         108 :     if (te1->dataLength < te2->dataLength)
    4332           6 :         return 1;
    4333             : 
    4334             :     /* For equal dataLengths, sort by dumpId, just to be stable */
    4335         102 :     if (te1->dumpId < te2->dumpId)
    4336          44 :         return -1;
    4337          58 :     if (te1->dumpId > te2->dumpId)
    4338          58 :         return 1;
    4339             : 
    4340           0 :     return 0;
    4341             : }
    4342             : 
    4343             : 
    4344             : /*
    4345             :  * Move all immediately-ready items from pending_list to ready_list.
    4346             :  *
    4347             :  * Items are considered ready if they have no remaining dependencies and
    4348             :  * they belong in the current restore pass.  (See also reduce_dependencies,
    4349             :  * which applies the same logic one-at-a-time.)
    4350             :  */
    4351             : static void
    4352          12 : move_to_ready_list(TocEntry *pending_list,
    4353             :                    ParallelReadyList *ready_list,
    4354             :                    RestorePass pass)
    4355             : {
    4356             :     TocEntry   *te;
    4357             :     TocEntry   *next_te;
    4358             : 
    4359          16 :     for (te = pending_list->pending_next; te != pending_list; te = next_te)
    4360             :     {
    4361             :         /* must save list link before possibly removing te from list */
    4362           4 :         next_te = te->pending_next;
    4363             : 
    4364           8 :         if (te->depCount == 0 &&
    4365           4 :             _tocEntryRestorePass(te) == pass)
    4366             :         {
    4367             :             /* Remove it from pending_list ... */
    4368           4 :             pending_list_remove(te);
    4369             :             /* ... and add to ready_list */
    4370           4 :             ready_list_insert(ready_list, te);
    4371             :         }
    4372             :     }
    4373          12 : }
    4374             : 
    4375             : /*
    4376             :  * Find the next work item (if any) that is capable of being run now,
    4377             :  * and remove it from the ready_list.
    4378             :  *
    4379             :  * Returns the item, or NULL if nothing is runnable.
    4380             :  *
    4381             :  * To qualify, the item must have no remaining dependencies
    4382             :  * and no requirements for locks that are incompatible with
    4383             :  * items currently running.  Items in the ready_list are known to have
    4384             :  * no remaining dependencies, but we have to check for lock conflicts.
    4385             :  */
    4386             : static TocEntry *
    4387          20 : pop_next_work_item(ArchiveHandle *AH, ParallelReadyList *ready_list,
    4388             :                    ParallelState *pstate)
    4389             : {
    4390             :     /*
    4391             :      * Sort the ready_list so that we'll tackle larger jobs first.
    4392             :      */
    4393          20 :     ready_list_sort(ready_list);
    4394             : 
    4395             :     /*
    4396             :      * Search the ready_list until we find a suitable item.
    4397             :      */
    4398          40 :     for (int i = ready_list->first_te; i <= ready_list->last_te; i++)
    4399             :     {
    4400           4 :         TocEntry   *te = ready_list->tes[i];
    4401           4 :         bool        conflicts = false;
    4402             : 
    4403             :         /*
    4404             :          * Check to see if the item would need exclusive lock on something
    4405             :          * that a currently running item also needs lock on, or vice versa. If
    4406             :          * so, we don't want to schedule them together.
    4407             :          */
    4408          12 :         for (int k = 0; k < pstate->numWorkers; k++)
    4409             :         {
    4410           8 :             TocEntry   *running_te = pstate->te[k];
    4411             : 
    4412           8 :             if (running_te == NULL)
    4413           8 :                 continue;
    4414           0 :             if (has_lock_conflicts(te, running_te) ||
    4415           0 :                 has_lock_conflicts(running_te, te))
    4416             :             {
    4417           0 :                 conflicts = true;
    4418           0 :                 break;
    4419             :             }
    4420             :         }
    4421             : 
    4422           4 :         if (conflicts)
    4423           0 :             continue;
    4424             : 
    4425             :         /* passed all tests, so this item can run */
    4426           4 :         ready_list_remove(ready_list, i);
    4427           4 :         return te;
    4428             :     }
    4429             : 
    4430          16 :     pg_log_debug("no item ready");
    4431          16 :     return NULL;
    4432             : }
    4433             : 
    4434             : 
    4435             : /*
    4436             :  * Restore a single TOC item in parallel with others
    4437             :  *
    4438             :  * this is run in the worker, i.e. in a thread (Windows) or a separate process
    4439             :  * (everything else). A worker process executes several such work items during
    4440             :  * a parallel backup or restore. Once we terminate here and report back that
    4441             :  * our work is finished, the master process will assign us a new work item.
    4442             :  */
    4443             : int
    4444           4 : parallel_restore(ArchiveHandle *AH, TocEntry *te)
    4445             : {
    4446             :     int         status;
    4447             : 
    4448             :     Assert(AH->connection != NULL);
    4449             : 
    4450             :     /* Count only errors associated with this TOC entry */
    4451           4 :     AH->public.n_errors = 0;
    4452             : 
    4453             :     /* Restore the TOC item */
    4454           4 :     status = restore_toc_entry(AH, te, true);
    4455             : 
    4456           4 :     return status;
    4457             : }
    4458             : 
    4459             : 
    4460             : /*
    4461             :  * Callback function that's invoked in the master process after a step has
    4462             :  * been parallel restored.
    4463             :  *
    4464             :  * Update status and reduce the dependency count of any dependent items.
    4465             :  */
    4466             : static void
    4467           4 : mark_restore_job_done(ArchiveHandle *AH,
    4468             :                       TocEntry *te,
    4469             :                       int status,
    4470             :                       void *callback_data)
    4471             : {
    4472           4 :     ParallelReadyList *ready_list = (ParallelReadyList *) callback_data;
    4473             : 
    4474           4 :     pg_log_info("finished item %d %s %s",
    4475             :                 te->dumpId, te->desc, te->tag);
    4476             : 
    4477           4 :     if (status == WORKER_CREATE_DONE)
    4478           0 :         mark_create_done(AH, te);
    4479           4 :     else if (status == WORKER_INHIBIT_DATA)
    4480             :     {
    4481           0 :         inhibit_data_for_failed_table(AH, te);
    4482           0 :         AH->public.n_errors++;
    4483             :     }
    4484           4 :     else if (status == WORKER_IGNORED_ERRORS)
    4485           0 :         AH->public.n_errors++;
    4486           4 :     else if (status != 0)
    4487           0 :         fatal("worker process failed: exit code %d",
    4488             :               status);
    4489             : 
    4490           4 :     reduce_dependencies(AH, te, ready_list);
    4491           4 : }
    4492             : 
    4493             : 
    4494             : /*
    4495             :  * Process the dependency information into a form useful for parallel restore.
    4496             :  *
    4497             :  * This function takes care of fixing up some missing or badly designed
    4498             :  * dependencies, and then prepares subsidiary data structures that will be
    4499             :  * used in the main parallel-restore logic, including:
    4500             :  * 1. We build the revDeps[] arrays of incoming dependency dumpIds.
    4501             :  * 2. We set up depCount fields that are the number of as-yet-unprocessed
    4502             :  * dependencies for each TOC entry.
    4503             :  *
    4504             :  * We also identify locking dependencies so that we can avoid trying to
    4505             :  * schedule conflicting items at the same time.
    4506             :  */
    4507             : static void
    4508           4 : fix_dependencies(ArchiveHandle *AH)
    4509             : {
    4510             :     TocEntry   *te;
    4511             :     int         i;
    4512             : 
    4513             :     /*
    4514             :      * Initialize the depCount/revDeps/nRevDeps fields, and make sure the TOC
    4515             :      * items are marked as not being in any parallel-processing list.
    4516             :      */
    4517          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4518             :     {
    4519          24 :         te->depCount = te->nDeps;
    4520          24 :         te->revDeps = NULL;
    4521          24 :         te->nRevDeps = 0;
    4522          24 :         te->pending_prev = NULL;
    4523          24 :         te->pending_next = NULL;
    4524             :     }
    4525             : 
    4526             :     /*
    4527             :      * POST_DATA items that are shown as depending on a table need to be
    4528             :      * re-pointed to depend on that table's data, instead.  This ensures they
    4529             :      * won't get scheduled until the data has been loaded.
    4530             :      */
    4531           4 :     repoint_table_dependencies(AH);
    4532             : 
    4533             :     /*
    4534             :      * Pre-8.4 versions of pg_dump neglected to set up a dependency from BLOB
    4535             :      * COMMENTS to BLOBS.  Cope.  (We assume there's only one BLOBS and only
    4536             :      * one BLOB COMMENTS in such files.)
    4537             :      */
    4538           4 :     if (AH->version < K_VERS_1_11)
    4539             :     {
    4540           0 :         for (te = AH->toc->next; te != AH->toc; te = te->next)
    4541             :         {
    4542           0 :             if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
    4543             :             {
    4544             :                 TocEntry   *te2;
    4545             : 
    4546           0 :                 for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
    4547             :                 {
    4548           0 :                     if (strcmp(te2->desc, "BLOBS") == 0)
    4549             :                     {
    4550           0 :                         te->dependencies = (DumpId *) pg_malloc(sizeof(DumpId));
    4551           0 :                         te->dependencies[0] = te2->dumpId;
    4552           0 :                         te->nDeps++;
    4553           0 :                         te->depCount++;
    4554           0 :                         break;
    4555             :                     }
    4556             :                 }
    4557           0 :                 break;
    4558             :             }
    4559             :         }
    4560             :     }
    4561             : 
    4562             :     /*
    4563             :      * At this point we start to build the revDeps reverse-dependency arrays,
    4564             :      * so all changes of dependencies must be complete.
    4565             :      */
    4566             : 
    4567             :     /*
    4568             :      * Count the incoming dependencies for each item.  Also, it is possible
    4569             :      * that the dependencies list items that are not in the archive at all
    4570             :      * (that should not happen in 9.2 and later, but is highly likely in older
    4571             :      * archives).  Subtract such items from the depCounts.
    4572             :      */
    4573          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4574             :     {
    4575          28 :         for (i = 0; i < te->nDeps; i++)
    4576             :         {
    4577           4 :             DumpId      depid = te->dependencies[i];
    4578             : 
    4579           4 :             if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL)
    4580           4 :                 AH->tocsByDumpId[depid]->nRevDeps++;
    4581             :             else
    4582           0 :                 te->depCount--;
    4583             :         }
    4584             :     }
    4585             : 
    4586             :     /*
    4587             :      * Allocate space for revDeps[] arrays, and reset nRevDeps so we can use
    4588             :      * it as a counter below.
    4589             :      */
    4590          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4591             :     {
    4592          24 :         if (te->nRevDeps > 0)
    4593           4 :             te->revDeps = (DumpId *) pg_malloc(te->nRevDeps * sizeof(DumpId));
    4594          24 :         te->nRevDeps = 0;
    4595             :     }
    4596             : 
    4597             :     /*
    4598             :      * Build the revDeps[] arrays of incoming-dependency dumpIds.  This had
    4599             :      * better agree with the loops above.
    4600             :      */
    4601          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4602             :     {
    4603          28 :         for (i = 0; i < te->nDeps; i++)
    4604             :         {
    4605           4 :             DumpId      depid = te->dependencies[i];
    4606             : 
    4607           4 :             if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL)
    4608             :             {
    4609           4 :                 TocEntry   *otherte = AH->tocsByDumpId[depid];
    4610             : 
    4611           4 :                 otherte->revDeps[otherte->nRevDeps++] = te->dumpId;
    4612             :             }
    4613             :         }
    4614             :     }
    4615             : 
    4616             :     /*
    4617             :      * Lastly, work out the locking dependencies.
    4618             :      */
    4619          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4620             :     {
    4621          24 :         te->lockDeps = NULL;
    4622          24 :         te->nLockDeps = 0;
    4623          24 :         identify_locking_dependencies(AH, te);
    4624             :     }
    4625           4 : }
    4626             : 
    4627             : /*
    4628             :  * Change dependencies on table items to depend on table data items instead,
    4629             :  * but only in POST_DATA items.
    4630             :  *
    4631             :  * Also, for any item having such dependency(s), set its dataLength to the
    4632             :  * largest dataLength of the table data items it depends on.  This ensures
    4633             :  * that parallel restore will prioritize larger jobs (index builds, FK
    4634             :  * constraint checks, etc) over smaller ones, avoiding situations where we
    4635             :  * end a restore with only one active job working on a large table.
    4636             :  */
    4637             : static void
    4638           4 : repoint_table_dependencies(ArchiveHandle *AH)
    4639             : {
    4640             :     TocEntry   *te;
    4641             :     int         i;
    4642             :     DumpId      olddep;
    4643             : 
    4644          28 :     for (te = AH->toc->next; te != AH->toc; te = te->next)
    4645             :     {
    4646          24 :         if (te->section != SECTION_POST_DATA)
    4647          24 :             continue;
    4648           0 :         for (i = 0; i < te->nDeps; i++)
    4649             :         {
    4650           0 :             olddep = te->dependencies[i];
    4651           0 :             if (olddep <= AH->maxDumpId &&
    4652           0 :                 AH->tableDataId[olddep] != 0)
    4653             :             {
    4654           0 :                 DumpId      tabledataid = AH->tableDataId[olddep];
    4655           0 :                 TocEntry   *tabledatate = AH->tocsByDumpId[tabledataid];
    4656             : 
    4657           0 :                 te->dependencies[i] = tabledataid;
    4658           0 :                 te->dataLength = Max(te->dataLength, tabledatate->dataLength);
    4659           0 :                 pg_log_debug("transferring dependency %d -> %d to %d",
    4660             :                              te->dumpId, olddep, tabledataid);
    4661             :             }
    4662             :         }
    4663             :     }
    4664           4 : }
    4665             : 
    4666             : /*
    4667             :  * Identify which objects we'll need exclusive lock on in order to restore
    4668             :  * the given TOC entry (*other* than the one identified by the TOC entry
    4669             :  * itself).  Record their dump IDs in the entry's lockDeps[] array.
    4670             :  */
    4671             : static void
    4672          24 : identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te)
    4673             : {
    4674             :     DumpId     *lockids;
    4675             :     int         nlockids;
    4676             :     int         i;
    4677             : 
    4678             :     /*
    4679             :      * We only care about this for POST_DATA items.  PRE_DATA items are not
    4680             :      * run in parallel, and DATA items are all independent by assumption.
    4681             :      */
    4682          24 :     if (te->section != SECTION_POST_DATA)
    4683          24 :         return;
    4684             : 
    4685             :     /* Quick exit if no dependencies at all */
    4686           0 :     if (te->nDeps == 0)
    4687           0 :         return;
    4688             : 
    4689             :     /*
    4690             :      * Most POST_DATA items are ALTER TABLEs or some moral equivalent of that,
    4691             :      * and hence require exclusive lock.  However, we know that CREATE INDEX
    4692             :      * does not.  (Maybe someday index-creating CONSTRAINTs will fall in that
    4693             :      * category too ... but today is not that day.)
    4694             :      */
    4695           0 :     if (strcmp(te->desc, "INDEX") == 0)
    4696           0 :         return;
    4697             : 
    4698             :     /*
    4699             :      * We assume the entry requires exclusive lock on each TABLE or TABLE DATA
    4700             :      * item listed among its dependencies.  Originally all of these would have
    4701             :      * been TABLE items, but repoint_table_dependencies would have repointed
    4702             :      * them to the TABLE DATA items if those are present (which they might not
    4703             :      * be, eg in a schema-only dump).  Note that all of the entries we are
    4704             :      * processing here are POST_DATA; otherwise there might be a significant
    4705             :      * difference between a dependency on a table and a dependency on its
    4706             :      * data, so that closer analysis would be needed here.
    4707             :      */
    4708           0 :     lockids = (DumpId *) pg_malloc(te->nDeps * sizeof(DumpId));
    4709           0 :     nlockids = 0;
    4710           0 :     for (i = 0; i < te->nDeps; i++)
    4711             :     {
    4712           0 :         DumpId      depid = te->dependencies[i];
    4713             : 
    4714           0 :         if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL &&
    4715           0 :             ((strcmp(AH->tocsByDumpId[depid]->desc, "TABLE DATA") == 0) ||
    4716           0 :              strcmp(AH->tocsByDumpId[depid]->desc, "TABLE") == 0))
    4717           0 :             lockids[nlockids++] = depid;
    4718             :     }
    4719             : 
    4720           0 :     if (nlockids == 0)
    4721             :     {
    4722           0 :         free(lockids);
    4723           0 :         return;
    4724             :     }
    4725             : 
    4726           0 :     te->lockDeps = pg_realloc(lockids, nlockids * sizeof(DumpId));
    4727           0 :     te->nLockDeps = nlockids;
    4728             : }
    4729             : 
    4730             : /*
    4731             :  * Remove the specified TOC entry from the depCounts of items that depend on
    4732             :  * it, thereby possibly making them ready-to-run.  Any pending item that
    4733             :  * becomes ready should be moved to the ready_list, if that's provided.
    4734             :  */
    4735             : static void
    4736          24 : reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
    4737             :                     ParallelReadyList *ready_list)
    4738             : {
    4739             :     int         i;
    4740             : 
    4741          24 :     pg_log_debug("reducing dependencies for %d", te->dumpId);
    4742             : 
    4743          28 :     for (i = 0; i < te->nRevDeps; i++)
    4744             :     {
    4745           4 :         TocEntry   *otherte = AH->tocsByDumpId[te->revDeps[i]];
    4746             : 
    4747             :         Assert(otherte->depCount > 0);
    4748           4 :         otherte->depCount--;
    4749             : 
    4750             :         /*
    4751             :          * It's ready if it has no remaining dependencies, and it belongs in
    4752             :          * the current restore pass, and it is currently a member of the
    4753             :          * pending list (that check is needed to prevent double restore in
    4754             :          * some cases where a list-file forces out-of-order restoring).
    4755             :          * However, if ready_list == NULL then caller doesn't want any list
    4756             :          * memberships changed.
    4757             :          */
    4758           8 :         if (otherte->depCount == 0 &&
    4759           8 :             _tocEntryRestorePass(otherte) == AH->restorePass &&
    4760           4 :             otherte->pending_prev != NULL &&
    4761             :             ready_list != NULL)
    4762             :         {
    4763             :             /* Remove it from pending list ... */
    4764           0 :             pending_list_remove(otherte);
    4765             :             /* ... and add to ready_list */
    4766           0 :             ready_list_insert(ready_list, otherte);
    4767             :         }
    4768             :     }
    4769          24 : }
    4770             : 
    4771             : /*
    4772             :  * Set the created flag on the DATA member corresponding to the given
    4773             :  * TABLE member
    4774             :  */
    4775             : static void
    4776        3884 : mark_create_done(ArchiveHandle *AH, TocEntry *te)
    4777             : {
    4778        3884 :     if (AH->tableDataId[te->dumpId] != 0)
    4779             :     {
    4780        2438 :         TocEntry   *ted = AH->tocsByDumpId[AH->tableDataId[te->dumpId]];
    4781             : 
    4782        2438 :         ted->created = true;
    4783             :     }
    4784        3884 : }
    4785             : 
    4786             : /*
    4787             :  * Mark the DATA member corresponding to the given TABLE member
    4788             :  * as not wanted
    4789             :  */
    4790             : static void
    4791           0 : inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
    4792             : {
    4793           0 :     pg_log_info("table \"%s\" could not be created, will not restore its data",
    4794             :                 te->tag);
    4795             : 
    4796           0 :     if (AH->tableDataId[te->dumpId] != 0)
    4797             :     {
    4798           0 :         TocEntry   *ted = AH->tocsByDumpId[AH->tableDataId[te->dumpId]];
    4799             : 
    4800           0 :         ted->reqs = 0;
    4801             :     }
    4802           0 : }
    4803             : 
    4804             : /*
    4805             :  * Clone and de-clone routines used in parallel restoration.
    4806             :  *
    4807             :  * Enough of the structure is cloned to ensure that there is no
    4808             :  * conflict between different threads each with their own clone.
    4809             :  */
    4810             : ArchiveHandle *
    4811          24 : CloneArchive(ArchiveHandle *AH)
    4812             : {
    4813             :     ArchiveHandle *clone;
    4814             : 
    4815             :     /* Make a "flat" copy */
    4816          24 :     clone = (ArchiveHandle *) pg_malloc(sizeof(ArchiveHandle));
    4817          24 :     memcpy(clone, AH, sizeof(ArchiveHandle));
    4818             : 
    4819             :     /* Handle format-independent fields */
    4820          24 :     memset(&(clone->sqlparse), 0, sizeof(clone->sqlparse));
    4821             : 
    4822             :     /* The clone will have its own connection, so disregard connection state */
    4823          24 :     clone->connection = NULL;
    4824          24 :     clone->connCancel = NULL;
    4825          24 :     clone->currUser = NULL;
    4826          24 :     clone->currSchema = NULL;
    4827          24 :     clone->currTablespace = NULL;
    4828             : 
    4829             :     /* savedPassword must be local in case we change it while connecting */
    4830          24 :     if (clone->savedPassword)
    4831           0 :         clone->savedPassword = pg_strdup(clone->savedPassword);
    4832             : 
    4833             :     /* clone has its own error count, too */
    4834          24 :     clone->public.n_errors = 0;
    4835             : 
    4836             :     /*
    4837             :      * Connect our new clone object to the database: In parallel restore the
    4838             :      * parent is already disconnected, because we can connect the worker
    4839             :      * processes independently to the database (no snapshot sync required). In
    4840             :      * parallel backup we clone the parent's existing connection.
    4841             :      */
    4842          24 :     if (AH->mode == archModeRead)
    4843             :     {
    4844           8 :         RestoreOptions *ropt = AH->public.ropt;
    4845             : 
    4846             :         Assert(AH->connection == NULL);
    4847             : 
    4848             :         /* this also sets clone->connection */
    4849          16 :         ConnectDatabase((Archive *) clone, ropt->dbname,
    4850           8 :                         ropt->pghost, ropt->pgport, ropt->username,
    4851             :                         ropt->promptPassword);
    4852             : 
    4853             :         /* re-establish fixed state */
    4854           8 :         _doSetFixedOutputState(clone);
    4855             :     }
    4856             :     else
    4857             :     {
    4858             :         PQExpBufferData connstr;
    4859             :         char       *pghost;
    4860             :         char       *pgport;
    4861             :         char       *username;
    4862             : 
    4863             :         Assert(AH->connection != NULL);
    4864             : 
    4865             :         /*
    4866             :          * Even though we are technically accessing the parent's database
    4867             :          * object here, these functions are fine to be called like that
    4868             :          * because all just return a pointer and do not actually send/receive
    4869             :          * any data to/from the database.
    4870             :          */
    4871          16 :         initPQExpBuffer(&connstr);
    4872          16 :         appendPQExpBufferStr(&connstr, "dbname=");
    4873          16 :         appendConnStrVal(&connstr, PQdb(AH->connection));
    4874          16 :         pghost = PQhost(AH->connection);
    4875          16 :         pgport = PQport(AH->connection);
    4876          16 :         username = PQuser(AH->connection);
    4877             : 
    4878             :         /* this also sets clone->connection */
    4879          16 :         ConnectDatabase((Archive *) clone, connstr.data,
    4880             :                         pghost, pgport, username, TRI_NO);
    4881             : 
    4882          16 :         termPQExpBuffer(&connstr);
    4883             :         /* setupDumpWorker will fix up connection state */
    4884             :     }
    4885             : 
    4886             :     /* Let the format-specific code have a chance too */
    4887          24 :     clone->ClonePtr(clone);
    4888             : 
    4889             :     Assert(clone->connection != NULL);
    4890          24 :     return clone;
    4891             : }
    4892             : 
    4893             : /*
    4894             :  * Release clone-local storage.
    4895             :  *
    4896             :  * Note: we assume any clone-local connection was already closed.
    4897             :  */
    4898             : void
    4899          24 : DeCloneArchive(ArchiveHandle *AH)
    4900             : {
    4901             :     /* Should not have an open database connection */
    4902             :     Assert(AH->connection == NULL);
    4903             : 
    4904             :     /* Clear format-specific state */
    4905          24 :     AH->DeClonePtr(AH);
    4906             : 
    4907             :     /* Clear state allocated by CloneArchive */
    4908          24 :     if (AH->sqlparse.curCmd)
    4909           0 :         destroyPQExpBuffer(AH->sqlparse.curCmd);
    4910             : 
    4911             :     /* Clear any connection-local state */
    4912          24 :     if (AH->currUser)
    4913           0 :         free(AH->currUser);
    4914          24 :     if (AH->currSchema)
    4915           0 :         free(AH->currSchema);
    4916          24 :     if (AH->currTablespace)
    4917           0 :         free(AH->currTablespace);
    4918          24 :     if (AH->currTableAm)
    4919           0 :         free(AH->currTableAm);
    4920          24 :     if (AH->savedPassword)
    4921           0 :         free(AH->savedPassword);
    4922             : 
    4923          24 :     free(AH);
    4924          24 : }

Generated by: LCOV version 1.13