LCOV - differential code coverage report
Current view: top level - src/bin/pg_dump - pg_backup_archiver.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DUB DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 82.1 % 2049 1682 23 344 4 19 1659 23 18
Current Date: 2026-08-27 14:31:44 +0300 Functions: 94.8 % 96 91 1 4 16 75
Baseline: lcov-20260827-baseline Branches: 68.2 % 1525 1040 22 463 3 9 1028
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 4 4 4
(7,30] days: 100.0 % 3 3 3
(30,360] days: 70.2 % 124 87 23 14 15 72
(360..) days: 82.8 % 1918 1588 330 4 1584
Function coverage date bins:
(30,360] days: 80.0 % 5 4 1 3 1
(360..) days: 95.6 % 91 87 4 13 74
Branch coverage date bins:
(1,7] days: 50.0 % 2 1 1 1
(7,30] days: 83.3 % 6 5 1 5
(30,360] days: 71.3 % 115 82 21 12 8 74
(360..) days: 67.9 % 1402 952 450 3 949

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

Generated by: LCOV version 2.0-1