LCOV - differential code coverage report
Current view: top level - src/bin/pg_dump - pg_backup_archiver.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: 7a15cff1f11193467898da1c1fabf06fd2caee04 vs 84a3778c79c2d28b4dc281d03ef2ab019b16483b Lines: 81.2 % 2029 1648 2 4 375 10 8 1630 2 3
Current Date: 2025-12-15 18:36:29 -0500 Functions: 94.8 % 96 91 5 5 86 1
Baseline: lcov-20251216-010103-baseline Branches: 66.7 % 1497 999 1 5 492 16 9 974
Baseline Date: 2025-12-15 13:30:48 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 50.0 % 4 2 2 2
(30,360] days: 89.1 % 110 98 12 2 6 90
(360..) days: 80.8 % 1915 1548 4 363 8 1540
Function coverage date bins:
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 94.5 % 91 86 5 4 82
Branch coverage date bins:
(30,360] days: 83.6 % 110 92 1 17 4 9 79
(360..) days: 65.4 % 1387 907 5 475 12 895

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

Generated by: LCOV version 2.4-beta